clang 22.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/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.AnonymousTagLocations = false;
497 }
498
499 Expr *makeOpaqueValueExpr(Expr *Inner) {
500 auto *OVE = new (S.Context)
501 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
502 Inner->getObjectKind(), Inner);
503 Actions.push_back(OVE);
504 return OVE;
505 }
506
507 Expr *getStringLiteral(llvm::StringRef Str) {
509 // Wrap the literal in parentheses to attach a source location.
510 return new (S.Context) ParenExpr(Loc, Loc, Lit);
511 }
512
513 bool callPrintFunction(llvm::StringRef Format,
514 llvm::ArrayRef<Expr *> Exprs = {}) {
515 SmallVector<Expr *, 8> Args;
516 assert(TheCall->getNumArgs() >= 2);
517 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
518 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
519 Args.push_back(getStringLiteral(Format));
520 llvm::append_range(Args, Exprs);
521
522 // Register a note to explain why we're performing the call.
523 Sema::CodeSynthesisContext Ctx;
525 Ctx.PointOfInstantiation = Loc;
526 Ctx.CallArgs = Args.data();
527 Ctx.NumCallArgs = Args.size();
529
530 ExprResult RealCall =
531 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
532 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
533
535 if (!RealCall.isInvalid())
536 Actions.push_back(RealCall.get());
537 // Bail out if we've hit any errors, even if we managed to build the
538 // call. We don't want to produce more than one error.
539 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
540 }
541
542 Expr *getIndentString(unsigned Depth) {
543 if (!Depth)
544 return nullptr;
545
546 llvm::SmallString<32> Indent;
547 Indent.resize(Depth * Policy.Indentation, ' ');
548 return getStringLiteral(Indent);
549 }
550
551 Expr *getTypeString(QualType T) {
552 return getStringLiteral(T.getAsString(Policy));
553 }
554
555 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
556 llvm::raw_svector_ostream OS(Str);
557
558 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
559 // than trying to print a single character.
560 if (auto *BT = T->getAs<BuiltinType>()) {
561 switch (BT->getKind()) {
562 case BuiltinType::Bool:
563 OS << "%d";
564 return true;
565 case BuiltinType::Char_U:
566 case BuiltinType::UChar:
567 OS << "%hhu";
568 return true;
569 case BuiltinType::Char_S:
570 case BuiltinType::SChar:
571 OS << "%hhd";
572 return true;
573 default:
574 break;
575 }
576 }
577
578 analyze_printf::PrintfSpecifier Specifier;
579 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
580 // We were able to guess how to format this.
581 if (Specifier.getConversionSpecifier().getKind() ==
582 analyze_printf::PrintfConversionSpecifier::sArg) {
583 // Wrap double-quotes around a '%s' specifier and limit its maximum
584 // length. Ideally we'd also somehow escape special characters in the
585 // contents but printf doesn't support that.
586 // FIXME: '%s' formatting is not safe in general.
587 OS << '"';
588 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
589 Specifier.toString(OS);
590 OS << '"';
591 // FIXME: It would be nice to include a '...' if the string doesn't fit
592 // in the length limit.
593 } else {
594 Specifier.toString(OS);
595 }
596 return true;
597 }
598
599 if (T->isPointerType()) {
600 // Format all pointers with '%p'.
601 OS << "%p";
602 return true;
603 }
604
605 return false;
606 }
607
608 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
609 Expr *IndentLit = getIndentString(Depth);
610 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
611 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
612 : callPrintFunction("%s", {TypeLit}))
613 return true;
614
615 return dumpRecordValue(RD, E, IndentLit, Depth);
616 }
617
618 // Dump a record value. E should be a pointer or lvalue referring to an RD.
619 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
620 unsigned Depth) {
621 // FIXME: Decide what to do if RD is a union. At least we should probably
622 // turn off printing `const char*` members with `%s`, because that is very
623 // likely to crash if that's not the active member. Whatever we decide, we
624 // should document it.
625
626 // Build an OpaqueValueExpr so we can refer to E more than once without
627 // triggering re-evaluation.
628 Expr *RecordArg = makeOpaqueValueExpr(E);
629 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
630
631 if (callPrintFunction(" {\n"))
632 return true;
633
634 // Dump each base class, regardless of whether they're aggregates.
635 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
636 for (const auto &Base : CXXRD->bases()) {
637 QualType BaseType =
638 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
639 : S.Context.getLValueReferenceType(Base.getType());
641 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
642 RecordArg);
643 if (BasePtr.isInvalid() ||
644 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
645 Depth + 1))
646 return true;
647 }
648 }
649
650 Expr *FieldIndentArg = getIndentString(Depth + 1);
651
652 // Dump each field.
653 for (auto *D : RD->decls()) {
654 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
655 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
656 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
657 continue;
658
659 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
660 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
661 getTypeString(FD->getType()),
662 getStringLiteral(FD->getName())};
663
664 if (FD->isBitField()) {
665 Format += ": %zu ";
666 QualType SizeT = S.Context.getSizeType();
667 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
668 FD->getBitWidthValue());
669 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
670 }
671
672 Format += "=";
673
676 CXXScopeSpec(), Loc, IFD,
677 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
679 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
681 DeclarationNameInfo(FD->getDeclName(), Loc));
682 if (Field.isInvalid())
683 return true;
684
685 auto *InnerRD = FD->getType()->getAsRecordDecl();
686 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
687 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
688 // Recursively print the values of members of aggregate record type.
689 if (callPrintFunction(Format, Args) ||
690 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
691 return true;
692 } else {
693 Format += " ";
694 if (appendFormatSpecifier(FD->getType(), Format)) {
695 // We know how to print this field.
696 Args.push_back(Field.get());
697 } else {
698 // We don't know how to print this field. Print out its address
699 // with a format specifier that a smart tool will be able to
700 // recognize and treat specially.
701 Format += "*%p";
702 ExprResult FieldAddr =
703 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
704 if (FieldAddr.isInvalid())
705 return true;
706 Args.push_back(FieldAddr.get());
707 }
708 Format += "\n";
709 if (callPrintFunction(Format, Args))
710 return true;
711 }
712 }
713
714 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
715 : callPrintFunction("}\n");
716 }
717
718 Expr *buildWrapper() {
719 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
721 TheCall->setType(Wrapper->getType());
722 TheCall->setValueKind(Wrapper->getValueKind());
723 return Wrapper;
724 }
725};
726} // namespace
727
729 if (S.checkArgCountAtLeast(TheCall, 2))
730 return ExprError();
731
732 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
733 if (PtrArgResult.isInvalid())
734 return ExprError();
735 TheCall->setArg(0, PtrArgResult.get());
736
737 // First argument should be a pointer to a struct.
738 QualType PtrArgType = PtrArgResult.get()->getType();
739 if (!PtrArgType->isPointerType() ||
740 !PtrArgType->getPointeeType()->isRecordType()) {
741 S.Diag(PtrArgResult.get()->getBeginLoc(),
742 diag::err_expected_struct_pointer_argument)
743 << 1 << TheCall->getDirectCallee() << PtrArgType;
744 return ExprError();
745 }
746 QualType Pointee = PtrArgType->getPointeeType();
747 const RecordDecl *RD = Pointee->getAsRecordDecl();
748 // Try to instantiate the class template as appropriate; otherwise, access to
749 // its data() may lead to a crash.
750 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
751 diag::err_incomplete_type))
752 return ExprError();
753 // Second argument is a callable, but we can't fully validate it until we try
754 // calling it.
755 QualType FnArgType = TheCall->getArg(1)->getType();
756 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
757 !FnArgType->isBlockPointerType() &&
758 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
759 auto *BT = FnArgType->getAs<BuiltinType>();
760 switch (BT ? BT->getKind() : BuiltinType::Void) {
761 case BuiltinType::Dependent:
762 case BuiltinType::Overload:
763 case BuiltinType::BoundMember:
764 case BuiltinType::PseudoObject:
765 case BuiltinType::UnknownAny:
766 case BuiltinType::BuiltinFn:
767 // This might be a callable.
768 break;
769
770 default:
771 S.Diag(TheCall->getArg(1)->getBeginLoc(),
772 diag::err_expected_callable_argument)
773 << 2 << TheCall->getDirectCallee() << FnArgType;
774 return ExprError();
775 }
776 }
777
778 BuiltinDumpStructGenerator Generator(S, TheCall);
779
780 // Wrap parentheses around the given pointer. This is not necessary for
781 // correct code generation, but it means that when we pretty-print the call
782 // arguments in our diagnostics we will produce '(&s)->n' instead of the
783 // incorrect '&s->n'.
784 Expr *PtrArg = PtrArgResult.get();
785 PtrArg = new (S.Context)
786 ParenExpr(PtrArg->getBeginLoc(),
787 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
788 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
789 return ExprError();
790
791 return Generator.buildWrapper();
792}
793
794static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
795 if (S.checkArgCount(BuiltinCall, 2))
796 return true;
797
798 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
799 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
800 Expr *Call = BuiltinCall->getArg(0);
801 Expr *Chain = BuiltinCall->getArg(1);
802
803 if (Call->getStmtClass() != Stmt::CallExprClass) {
804 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
805 << Call->getSourceRange();
806 return true;
807 }
808
809 auto CE = cast<CallExpr>(Call);
810 if (CE->getCallee()->getType()->isBlockPointerType()) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 const Decl *TargetDecl = CE->getCalleeDecl();
817 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
818 if (FD->getBuiltinID()) {
819 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
820 << Call->getSourceRange();
821 return true;
822 }
823
824 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
825 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
826 << Call->getSourceRange();
827 return true;
828 }
829
830 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
831 if (ChainResult.isInvalid())
832 return true;
833 if (!ChainResult.get()->getType()->isPointerType()) {
834 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
835 << Chain->getSourceRange();
836 return true;
837 }
838
839 QualType ReturnTy = CE->getCallReturnType(S.Context);
840 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
841 QualType BuiltinTy = S.Context.getFunctionType(
842 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
843 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
844
845 Builtin =
846 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
847
848 BuiltinCall->setType(CE->getType());
849 BuiltinCall->setValueKind(CE->getValueKind());
850 BuiltinCall->setObjectKind(CE->getObjectKind());
851 BuiltinCall->setCallee(Builtin);
852 BuiltinCall->setArg(1, ChainResult.get());
853
854 return false;
855}
856
857namespace {
858
859class ScanfDiagnosticFormatHandler
861 // Accepts the argument index (relative to the first destination index) of the
862 // argument whose size we want.
863 using ComputeSizeFunction =
864 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
865
866 // Accepts the argument index (relative to the first destination index), the
867 // destination size, and the source size).
868 using DiagnoseFunction =
869 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
870
871 ComputeSizeFunction ComputeSizeArgument;
872 DiagnoseFunction Diagnose;
873
874public:
875 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
876 DiagnoseFunction Diagnose)
877 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
878
879 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
880 const char *StartSpecifier,
881 unsigned specifierLen) override {
882 if (!FS.consumesDataArgument())
883 return true;
884
885 unsigned NulByte = 0;
886 switch ((FS.getConversionSpecifier().getKind())) {
887 default:
888 return true;
891 NulByte = 1;
892 break;
894 break;
895 }
896
897 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
898 if (FW.getHowSpecified() !=
899 analyze_format_string::OptionalAmount::HowSpecified::Constant)
900 return true;
901
902 unsigned SourceSize = FW.getConstantAmount() + NulByte;
903
904 std::optional<llvm::APSInt> DestSizeAPS =
905 ComputeSizeArgument(FS.getArgIndex());
906 if (!DestSizeAPS)
907 return true;
908
909 unsigned DestSize = DestSizeAPS->getZExtValue();
910
911 if (DestSize < SourceSize)
912 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
913
914 return true;
915 }
916};
917
918class EstimateSizeFormatHandler
920 size_t Size;
921 /// Whether the format string contains Linux kernel's format specifier
922 /// extension.
923 bool IsKernelCompatible = true;
924
925public:
926 EstimateSizeFormatHandler(StringRef Format)
927 : Size(std::min(Format.find(0), Format.size()) +
928 1 /* null byte always written by sprintf */) {}
929
930 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
931 const char *, unsigned SpecifierLen,
932 const TargetInfo &) override {
933
934 const size_t FieldWidth = computeFieldWidth(FS);
935 const size_t Precision = computePrecision(FS);
936
937 // The actual format.
938 switch (FS.getConversionSpecifier().getKind()) {
939 // Just a char.
942 Size += std::max(FieldWidth, (size_t)1);
943 break;
944 // Just an integer.
954 Size += std::max(FieldWidth, Precision);
955 break;
956
957 // %g style conversion switches between %f or %e style dynamically.
958 // %g removes trailing zeros, and does not print decimal point if there are
959 // no digits that follow it. Thus %g can print a single digit.
960 // FIXME: If it is alternative form:
961 // For g and G conversions, trailing zeros are not removed from the result.
964 Size += 1;
965 break;
966
967 // Floating point number in the form '[+]ddd.ddd'.
970 Size += std::max(FieldWidth, 1 /* integer part */ +
971 (Precision ? 1 + Precision
972 : 0) /* period + decimal */);
973 break;
974
975 // Floating point number in the form '[-]d.ddde[+-]dd'.
978 Size +=
979 std::max(FieldWidth,
980 1 /* integer part */ +
981 (Precision ? 1 + Precision : 0) /* period + decimal */ +
982 1 /* e or E letter */ + 2 /* exponent */);
983 break;
984
985 // Floating point number in the form '[-]0xh.hhhhp±dd'.
988 Size +=
989 std::max(FieldWidth,
990 2 /* 0x */ + 1 /* integer part */ +
991 (Precision ? 1 + Precision : 0) /* period + decimal */ +
992 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
993 break;
994
995 // Just a string.
998 Size += FieldWidth;
999 break;
1000
1001 // Just a pointer in the form '0xddd'.
1003 // Linux kernel has its own extesion for `%p` specifier.
1004 // Kernel Document:
1005 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1006 IsKernelCompatible = false;
1007 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1008 break;
1009
1010 // A plain percent.
1012 Size += 1;
1013 break;
1014
1015 default:
1016 break;
1017 }
1018
1019 // If field width is specified, the sign/space is already accounted for
1020 // within the field width, so no additional size is needed.
1021 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1022 Size += 1;
1023
1024 if (FS.hasAlternativeForm()) {
1025 switch (FS.getConversionSpecifier().getKind()) {
1026 // For o conversion, it increases the precision, if and only if necessary,
1027 // to force the first digit of the result to be a zero
1028 // (if the value and precision are both 0, a single 0 is printed)
1030 // For b conversion, a nonzero result has 0b prefixed to it.
1032 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1033 // it.
1036 // Note: even when the prefix is added, if
1037 // (prefix_width <= FieldWidth - formatted_length) holds,
1038 // the prefix does not increase the format
1039 // size. e.g.(("%#3x", 0xf) is "0xf")
1040
1041 // If the result is zero, o, b, x, X adds nothing.
1042 break;
1043 // For a, A, e, E, f, F, g, and G conversions,
1044 // the result of converting a floating-point number always contains a
1045 // decimal-point
1054 Size += (Precision ? 0 : 1);
1055 break;
1056 // For other conversions, the behavior is undefined.
1057 default:
1058 break;
1059 }
1060 }
1061 assert(SpecifierLen <= Size && "no underflow");
1062 Size -= SpecifierLen;
1063 return true;
1064 }
1065
1066 size_t getSizeLowerBound() const { return Size; }
1067 bool isKernelCompatible() const { return IsKernelCompatible; }
1068
1069private:
1070 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1071 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1072 size_t FieldWidth = 0;
1074 FieldWidth = FW.getConstantAmount();
1075 return FieldWidth;
1076 }
1077
1078 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1079 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1080 size_t Precision = 0;
1081
1082 // See man 3 printf for default precision value based on the specifier.
1083 switch (FW.getHowSpecified()) {
1085 switch (FS.getConversionSpecifier().getKind()) {
1086 default:
1087 break;
1091 Precision = 1;
1092 break;
1099 Precision = 1;
1100 break;
1107 Precision = 6;
1108 break;
1110 Precision = 1;
1111 break;
1112 }
1113 break;
1115 Precision = FW.getConstantAmount();
1116 break;
1117 default:
1118 break;
1119 }
1120 return Precision;
1121 }
1122};
1123
1124} // namespace
1125
1126static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1127 StringRef &FormatStrRef, size_t &StrLen,
1128 ASTContext &Context) {
1129 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1130 Format && (Format->isOrdinary() || Format->isUTF8())) {
1131 FormatStrRef = Format->getString();
1132 const ConstantArrayType *T =
1133 Context.getAsConstantArrayType(Format->getType());
1134 assert(T && "String literal not of constant array type!");
1135 size_t TypeSize = T->getZExtSize();
1136 // In case there's a null byte somewhere.
1137 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1138 return true;
1139 }
1140 return false;
1141}
1142
1143void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1144 CallExpr *TheCall) {
1145 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1147 return;
1148
1149 bool UseDABAttr = false;
1150 const FunctionDecl *UseDecl = FD;
1151
1152 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1153 if (DABAttr) {
1154 UseDecl = DABAttr->getFunction();
1155 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1156 UseDABAttr = true;
1157 }
1158
1159 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1160
1161 if (!BuiltinID)
1162 return;
1163
1164 const TargetInfo &TI = getASTContext().getTargetInfo();
1165 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1166
1167 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1168 // If we refer to a diagnose_as_builtin attribute, we need to change the
1169 // argument index to refer to the arguments of the called function. Unless
1170 // the index is out of bounds, which presumably means it's a variadic
1171 // function.
1172 if (!UseDABAttr)
1173 return Index;
1174 unsigned DABIndices = DABAttr->argIndices_size();
1175 unsigned NewIndex = Index < DABIndices
1176 ? DABAttr->argIndices_begin()[Index]
1177 : Index - DABIndices + FD->getNumParams();
1178 if (NewIndex >= TheCall->getNumArgs())
1179 return std::nullopt;
1180 return NewIndex;
1181 };
1182
1183 auto ComputeExplicitObjectSizeArgument =
1184 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1185 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1186 if (!IndexOptional)
1187 return std::nullopt;
1188 unsigned NewIndex = *IndexOptional;
1189 Expr::EvalResult Result;
1190 Expr *SizeArg = TheCall->getArg(NewIndex);
1191 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1192 return std::nullopt;
1193 llvm::APSInt Integer = Result.Val.getInt();
1194 Integer.setIsUnsigned(true);
1195 return Integer;
1196 };
1197
1198 auto ComputeSizeArgument =
1199 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1200 // If the parameter has a pass_object_size attribute, then we should use its
1201 // (potentially) more strict checking mode. Otherwise, conservatively assume
1202 // type 0.
1203 int BOSType = 0;
1204 // This check can fail for variadic functions.
1205 if (Index < FD->getNumParams()) {
1206 if (const auto *POS =
1207 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1208 BOSType = POS->getType();
1209 }
1210
1211 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1212 if (!IndexOptional)
1213 return std::nullopt;
1214 unsigned NewIndex = *IndexOptional;
1215
1216 if (NewIndex >= TheCall->getNumArgs())
1217 return std::nullopt;
1218
1219 const Expr *ObjArg = TheCall->getArg(NewIndex);
1221 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1222 return std::nullopt;
1223
1224 // Get the object size in the target's size_t width.
1225 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1226 };
1227
1228 auto ComputeStrLenArgument =
1229 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1230 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1231 if (!IndexOptional)
1232 return std::nullopt;
1233 unsigned NewIndex = *IndexOptional;
1234
1235 const Expr *ObjArg = TheCall->getArg(NewIndex);
1237 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1238 return std::nullopt;
1239 // Add 1 for null byte.
1240 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1241 };
1242
1243 std::optional<llvm::APSInt> SourceSize;
1244 std::optional<llvm::APSInt> DestinationSize;
1245 unsigned DiagID = 0;
1246 bool IsChkVariant = false;
1247
1248 auto GetFunctionName = [&]() {
1249 std::string FunctionNameStr =
1250 getASTContext().BuiltinInfo.getName(BuiltinID);
1251 llvm::StringRef FunctionName = FunctionNameStr;
1252 // Skim off the details of whichever builtin was called to produce a better
1253 // diagnostic, as it's unlikely that the user wrote the __builtin
1254 // explicitly.
1255 if (IsChkVariant) {
1256 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1257 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1258 } else {
1259 FunctionName.consume_front("__builtin_");
1260 }
1261 return FunctionName.str();
1262 };
1263
1264 switch (BuiltinID) {
1265 default:
1266 return;
1267 case Builtin::BI__builtin_strcat:
1268 case Builtin::BIstrcat:
1269 case Builtin::BI__builtin_stpcpy:
1270 case Builtin::BIstpcpy:
1271 case Builtin::BI__builtin_strcpy:
1272 case Builtin::BIstrcpy: {
1273 DiagID = diag::warn_fortify_strlen_overflow;
1274 SourceSize = ComputeStrLenArgument(1);
1275 DestinationSize = ComputeSizeArgument(0);
1276 break;
1277 }
1278
1279 case Builtin::BI__builtin___strcat_chk:
1280 case Builtin::BI__builtin___stpcpy_chk:
1281 case Builtin::BI__builtin___strcpy_chk: {
1282 DiagID = diag::warn_fortify_strlen_overflow;
1283 SourceSize = ComputeStrLenArgument(1);
1284 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1285 IsChkVariant = true;
1286 break;
1287 }
1288
1289 case Builtin::BIscanf:
1290 case Builtin::BIfscanf:
1291 case Builtin::BIsscanf: {
1292 unsigned FormatIndex = 1;
1293 unsigned DataIndex = 2;
1294 if (BuiltinID == Builtin::BIscanf) {
1295 FormatIndex = 0;
1296 DataIndex = 1;
1297 }
1298
1299 const auto *FormatExpr =
1300 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1301
1302 StringRef FormatStrRef;
1303 size_t StrLen;
1304 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1305 return;
1306
1307 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1308 unsigned SourceSize) {
1309 DiagID = diag::warn_fortify_scanf_overflow;
1310 unsigned Index = ArgIndex + DataIndex;
1311 std::string FunctionName = GetFunctionName();
1312 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1313 PDiag(DiagID) << FunctionName << (Index + 1)
1314 << DestSize << SourceSize);
1315 };
1316
1317 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1318 return ComputeSizeArgument(Index + DataIndex);
1319 };
1320 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1321 const char *FormatBytes = FormatStrRef.data();
1323 FormatBytes + StrLen, getLangOpts(),
1324 Context.getTargetInfo());
1325
1326 // Unlike the other cases, in this one we have already issued the diagnostic
1327 // here, so no need to continue (because unlike the other cases, here the
1328 // diagnostic refers to the argument number).
1329 return;
1330 }
1331
1332 case Builtin::BIsprintf:
1333 case Builtin::BI__builtin___sprintf_chk: {
1334 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1335 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1336
1337 StringRef FormatStrRef;
1338 size_t StrLen;
1339 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1340 EstimateSizeFormatHandler H(FormatStrRef);
1341 const char *FormatBytes = FormatStrRef.data();
1343 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1344 Context.getTargetInfo(), false)) {
1345 DiagID = H.isKernelCompatible()
1346 ? diag::warn_format_overflow
1347 : diag::warn_format_overflow_non_kprintf;
1348 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1349 .extOrTrunc(SizeTypeWidth);
1350 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1351 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1352 IsChkVariant = true;
1353 } else {
1354 DestinationSize = ComputeSizeArgument(0);
1355 }
1356 break;
1357 }
1358 }
1359 return;
1360 }
1361 case Builtin::BI__builtin___memcpy_chk:
1362 case Builtin::BI__builtin___memmove_chk:
1363 case Builtin::BI__builtin___memset_chk:
1364 case Builtin::BI__builtin___strlcat_chk:
1365 case Builtin::BI__builtin___strlcpy_chk:
1366 case Builtin::BI__builtin___strncat_chk:
1367 case Builtin::BI__builtin___strncpy_chk:
1368 case Builtin::BI__builtin___stpncpy_chk:
1369 case Builtin::BI__builtin___memccpy_chk:
1370 case Builtin::BI__builtin___mempcpy_chk: {
1371 DiagID = diag::warn_builtin_chk_overflow;
1372 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1373 DestinationSize =
1374 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1375 IsChkVariant = true;
1376 break;
1377 }
1378
1379 case Builtin::BI__builtin___snprintf_chk:
1380 case Builtin::BI__builtin___vsnprintf_chk: {
1381 DiagID = diag::warn_builtin_chk_overflow;
1382 SourceSize = ComputeExplicitObjectSizeArgument(1);
1383 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1384 IsChkVariant = true;
1385 break;
1386 }
1387
1388 case Builtin::BIstrncat:
1389 case Builtin::BI__builtin_strncat:
1390 case Builtin::BIstrncpy:
1391 case Builtin::BI__builtin_strncpy:
1392 case Builtin::BIstpncpy:
1393 case Builtin::BI__builtin_stpncpy: {
1394 // Whether these functions overflow depends on the runtime strlen of the
1395 // string, not just the buffer size, so emitting the "always overflow"
1396 // diagnostic isn't quite right. We should still diagnose passing a buffer
1397 // size larger than the destination buffer though; this is a runtime abort
1398 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1399 DiagID = diag::warn_fortify_source_size_mismatch;
1400 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1401 DestinationSize = ComputeSizeArgument(0);
1402 break;
1403 }
1404
1405 case Builtin::BImemcpy:
1406 case Builtin::BI__builtin_memcpy:
1407 case Builtin::BImemmove:
1408 case Builtin::BI__builtin_memmove:
1409 case Builtin::BImemset:
1410 case Builtin::BI__builtin_memset:
1411 case Builtin::BImempcpy:
1412 case Builtin::BI__builtin_mempcpy: {
1413 DiagID = diag::warn_fortify_source_overflow;
1414 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1415 DestinationSize = ComputeSizeArgument(0);
1416 break;
1417 }
1418 case Builtin::BIsnprintf:
1419 case Builtin::BI__builtin_snprintf:
1420 case Builtin::BIvsnprintf:
1421 case Builtin::BI__builtin_vsnprintf: {
1422 DiagID = diag::warn_fortify_source_size_mismatch;
1423 SourceSize = ComputeExplicitObjectSizeArgument(1);
1424 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1425 StringRef FormatStrRef;
1426 size_t StrLen;
1427 if (SourceSize &&
1428 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1429 EstimateSizeFormatHandler H(FormatStrRef);
1430 const char *FormatBytes = FormatStrRef.data();
1432 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1433 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1434 llvm::APSInt FormatSize =
1435 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1436 .extOrTrunc(SizeTypeWidth);
1437 if (FormatSize > *SourceSize && *SourceSize != 0) {
1438 unsigned TruncationDiagID =
1439 H.isKernelCompatible() ? diag::warn_format_truncation
1440 : diag::warn_format_truncation_non_kprintf;
1441 SmallString<16> SpecifiedSizeStr;
1442 SmallString<16> FormatSizeStr;
1443 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1444 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1445 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1446 PDiag(TruncationDiagID)
1447 << GetFunctionName() << SpecifiedSizeStr
1448 << FormatSizeStr);
1449 }
1450 }
1451 }
1452 DestinationSize = ComputeSizeArgument(0);
1453 }
1454 }
1455
1456 if (!SourceSize || !DestinationSize ||
1457 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1458 return;
1459
1460 std::string FunctionName = GetFunctionName();
1461
1462 SmallString<16> DestinationStr;
1463 SmallString<16> SourceStr;
1464 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1465 SourceSize->toString(SourceStr, /*Radix=*/10);
1466 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1467 PDiag(DiagID)
1468 << FunctionName << DestinationStr << SourceStr);
1469}
1470
1471static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1472 Scope::ScopeFlags NeededScopeFlags,
1473 unsigned DiagID) {
1474 // Scopes aren't available during instantiation. Fortunately, builtin
1475 // functions cannot be template args so they cannot be formed through template
1476 // instantiation. Therefore checking once during the parse is sufficient.
1477 if (SemaRef.inTemplateInstantiation())
1478 return false;
1479
1480 Scope *S = SemaRef.getCurScope();
1481 while (S && !S->isSEHExceptScope())
1482 S = S->getParent();
1483 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1484 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1485 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1486 << DRE->getDecl()->getIdentifier();
1487 return true;
1488 }
1489
1490 return false;
1491}
1492
1493// In OpenCL, __builtin_alloca_* should return a pointer to address space
1494// that corresponds to the stack address space i.e private address space.
1495static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1496 QualType RT = TheCall->getType();
1497 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1498 "__builtin_alloca has invalid address space");
1499
1500 RT = RT->getPointeeType();
1502 TheCall->setType(S.Context.getPointerType(RT));
1503}
1504
1505static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1506 if (S.checkArgCountAtLeast(TheCall, 1))
1507 return true;
1508
1509 for (Expr *Arg : TheCall->arguments()) {
1510 // If argument is dependent on a template parameter, we can't resolve now.
1511 if (Arg->isTypeDependent() || Arg->isValueDependent())
1512 continue;
1513 // Reject void types.
1514 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1515 if (ArgTy->isVoidType())
1516 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1517 }
1518
1519 TheCall->setType(S.Context.getSizeType());
1520 return false;
1521}
1522
1523namespace {
1524enum PointerAuthOpKind {
1525 PAO_Strip,
1526 PAO_Sign,
1527 PAO_Auth,
1528 PAO_SignGeneric,
1529 PAO_Discriminator,
1530 PAO_BlendPointer,
1531 PAO_BlendInteger
1532};
1533}
1534
1536 if (getLangOpts().PointerAuthIntrinsics)
1537 return false;
1538
1539 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1540 return true;
1541}
1542
1543static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1545}
1546
1547static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1548 // Convert it to type 'int'.
1549 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1550 return true;
1551
1552 // Value-dependent expressions are okay; wait for template instantiation.
1553 if (Arg->isValueDependent())
1554 return false;
1555
1556 unsigned KeyValue;
1557 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1558}
1559
1561 // Attempt to constant-evaluate the expression.
1562 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1563 if (!KeyValue) {
1564 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1565 << 0 << Arg->getSourceRange();
1566 return true;
1567 }
1568
1569 // Ask the target to validate the key parameter.
1570 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1572 {
1573 llvm::raw_svector_ostream Str(Value);
1574 Str << *KeyValue;
1575 }
1576
1577 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1578 << Value << Arg->getSourceRange();
1579 return true;
1580 }
1581
1582 Result = KeyValue->getZExtValue();
1583 return false;
1584}
1585
1588 unsigned &IntVal) {
1589 if (!Arg) {
1590 IntVal = 0;
1591 return true;
1592 }
1593
1594 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1595 if (!Result) {
1596 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1597 return false;
1598 }
1599
1600 unsigned Max;
1601 bool IsAddrDiscArg = false;
1602
1603 switch (Kind) {
1605 Max = 1;
1606 IsAddrDiscArg = true;
1607 break;
1610 break;
1611 };
1612
1614 if (IsAddrDiscArg)
1615 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1616 << Result->getExtValue();
1617 else
1618 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1619 << Result->getExtValue() << Max;
1620
1621 return false;
1622 };
1623
1624 IntVal = Result->getZExtValue();
1625 return true;
1626}
1627
1628static std::pair<const ValueDecl *, CharUnits>
1630 // Must evaluate as a pointer.
1631 Expr::EvalResult Result;
1632 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1633 return {nullptr, CharUnits()};
1634
1635 const auto *BaseDecl =
1636 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1637 if (!BaseDecl)
1638 return {nullptr, CharUnits()};
1639
1640 return {BaseDecl, Result.Val.getLValueOffset()};
1641}
1642
1643static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1644 bool RequireConstant = false) {
1645 if (Arg->hasPlaceholderType()) {
1647 if (R.isInvalid())
1648 return true;
1649 Arg = R.get();
1650 }
1651
1652 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1653 return OpKind != PAO_BlendInteger;
1654 };
1655 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1656 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1657 OpKind == PAO_SignGeneric;
1658 };
1659
1660 // Require the value to have the right range of type.
1661 QualType ExpectedTy;
1662 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1663 ExpectedTy = Arg->getType().getUnqualifiedType();
1664 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1665 ExpectedTy = S.Context.VoidPtrTy;
1666 } else if (AllowsInteger(OpKind) &&
1668 ExpectedTy = S.Context.getUIntPtrType();
1669
1670 } else {
1671 // Diagnose the failures.
1672 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1673 << unsigned(OpKind == PAO_Discriminator ? 1
1674 : OpKind == PAO_BlendPointer ? 2
1675 : OpKind == PAO_BlendInteger ? 3
1676 : 0)
1677 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1678 << Arg->getType() << Arg->getSourceRange();
1679 return true;
1680 }
1681
1682 // Convert to that type. This should just be an lvalue-to-rvalue
1683 // conversion.
1684 if (convertArgumentToType(S, Arg, ExpectedTy))
1685 return true;
1686
1687 if (!RequireConstant) {
1688 // Warn about null pointers for non-generic sign and auth operations.
1689 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1691 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1692 ? diag::warn_ptrauth_sign_null_pointer
1693 : diag::warn_ptrauth_auth_null_pointer)
1694 << Arg->getSourceRange();
1695 }
1696
1697 return false;
1698 }
1699
1700 // Perform special checking on the arguments to ptrauth_sign_constant.
1701
1702 // The main argument.
1703 if (OpKind == PAO_Sign) {
1704 // Require the value we're signing to have a special form.
1705 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1706 bool Invalid;
1707
1708 // Must be rooted in a declaration reference.
1709 if (!BaseDecl)
1710 Invalid = true;
1711
1712 // If it's a function declaration, we can't have an offset.
1713 else if (isa<FunctionDecl>(BaseDecl))
1714 Invalid = !Offset.isZero();
1715
1716 // Otherwise we're fine.
1717 else
1718 Invalid = false;
1719
1720 if (Invalid)
1721 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1722 return Invalid;
1723 }
1724
1725 // The discriminator argument.
1726 assert(OpKind == PAO_Discriminator);
1727
1728 // Must be a pointer or integer or blend thereof.
1729 Expr *Pointer = nullptr;
1730 Expr *Integer = nullptr;
1731 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1732 if (Call->getBuiltinCallee() ==
1733 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1734 Pointer = Call->getArg(0);
1735 Integer = Call->getArg(1);
1736 }
1737 }
1738 if (!Pointer && !Integer) {
1739 if (Arg->getType()->isPointerType())
1740 Pointer = Arg;
1741 else
1742 Integer = Arg;
1743 }
1744
1745 // Check the pointer.
1746 bool Invalid = false;
1747 if (Pointer) {
1748 assert(Pointer->getType()->isPointerType());
1749
1750 // TODO: if we're initializing a global, check that the address is
1751 // somehow related to what we're initializing. This probably will
1752 // never really be feasible and we'll have to catch it at link-time.
1753 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1754 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1755 Invalid = true;
1756 }
1757
1758 // Check the integer.
1759 if (Integer) {
1760 assert(Integer->getType()->isIntegerType());
1761 if (!Integer->isEvaluatable(S.Context))
1762 Invalid = true;
1763 }
1764
1765 if (Invalid)
1766 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1767 return Invalid;
1768}
1769
1771 if (S.checkArgCount(Call, 2))
1772 return ExprError();
1774 return ExprError();
1775 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1776 checkPointerAuthKey(S, Call->getArgs()[1]))
1777 return ExprError();
1778
1779 Call->setType(Call->getArgs()[0]->getType());
1780 return Call;
1781}
1782
1784 if (S.checkArgCount(Call, 2))
1785 return ExprError();
1787 return ExprError();
1788 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1789 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1790 return ExprError();
1791
1792 Call->setType(S.Context.getUIntPtrType());
1793 return Call;
1794}
1795
1797 if (S.checkArgCount(Call, 2))
1798 return ExprError();
1800 return ExprError();
1801 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1802 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1803 return ExprError();
1804
1805 Call->setType(S.Context.getUIntPtrType());
1806 return Call;
1807}
1808
1810 PointerAuthOpKind OpKind,
1811 bool RequireConstant) {
1812 if (S.checkArgCount(Call, 3))
1813 return ExprError();
1815 return ExprError();
1816 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1817 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1818 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1819 RequireConstant))
1820 return ExprError();
1821
1822 Call->setType(Call->getArgs()[0]->getType());
1823 return Call;
1824}
1825
1827 if (S.checkArgCount(Call, 5))
1828 return ExprError();
1830 return ExprError();
1831 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1832 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1833 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1834 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1835 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1836 return ExprError();
1837
1838 Call->setType(Call->getArgs()[0]->getType());
1839 return Call;
1840}
1841
1844 return ExprError();
1845
1846 // We've already performed normal call type-checking.
1847 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1848
1849 // Operand must be an ordinary or UTF-8 string literal.
1850 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1851 if (!Literal || Literal->getCharByteWidth() != 1) {
1852 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1853 << (Literal ? 1 : 0) << Arg->getSourceRange();
1854 return ExprError();
1855 }
1856
1857 return Call;
1858}
1859
1861 if (S.checkArgCount(Call, 1))
1862 return ExprError();
1863 Expr *FirstArg = Call->getArg(0);
1864 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1865 if (FirstValue.isInvalid())
1866 return ExprError();
1867 Call->setArg(0, FirstValue.get());
1868 QualType FirstArgType = FirstArg->getType();
1869 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1870 FirstArgType = S.Context.getDecayedType(FirstArgType);
1871
1872 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1873 if (!FirstArgRecord) {
1874 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1875 << /*isPolymorphic=*/0 << FirstArgType;
1876 return ExprError();
1877 }
1878 if (S.RequireCompleteType(
1879 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1880 diag::err_get_vtable_pointer_requires_complete_type)) {
1881 return ExprError();
1882 }
1883
1884 if (!FirstArgRecord->isPolymorphic()) {
1885 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1886 << /*isPolymorphic=*/1 << FirstArgRecord;
1887 return ExprError();
1888 }
1890 Call->setType(ReturnType);
1891 return Call;
1892}
1893
1895 if (S.checkArgCount(TheCall, 1))
1896 return ExprError();
1897
1898 // Compute __builtin_launder's parameter type from the argument.
1899 // The parameter type is:
1900 // * The type of the argument if it's not an array or function type,
1901 // Otherwise,
1902 // * The decayed argument type.
1903 QualType ParamTy = [&]() {
1904 QualType ArgTy = TheCall->getArg(0)->getType();
1905 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1906 return S.Context.getPointerType(Ty->getElementType());
1907 if (ArgTy->isFunctionType()) {
1908 return S.Context.getPointerType(ArgTy);
1909 }
1910 return ArgTy;
1911 }();
1912
1913 TheCall->setType(ParamTy);
1914
1915 auto DiagSelect = [&]() -> std::optional<unsigned> {
1916 if (!ParamTy->isPointerType())
1917 return 0;
1918 if (ParamTy->isFunctionPointerType())
1919 return 1;
1920 if (ParamTy->isVoidPointerType())
1921 return 2;
1922 return std::optional<unsigned>{};
1923 }();
1924 if (DiagSelect) {
1925 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1926 << *DiagSelect << TheCall->getSourceRange();
1927 return ExprError();
1928 }
1929
1930 // We either have an incomplete class type, or we have a class template
1931 // whose instantiation has not been forced. Example:
1932 //
1933 // template <class T> struct Foo { T value; };
1934 // Foo<int> *p = nullptr;
1935 // auto *d = __builtin_launder(p);
1936 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1937 diag::err_incomplete_type))
1938 return ExprError();
1939
1940 assert(ParamTy->getPointeeType()->isObjectType() &&
1941 "Unhandled non-object pointer case");
1942
1943 InitializedEntity Entity =
1945 ExprResult Arg =
1946 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1947 if (Arg.isInvalid())
1948 return ExprError();
1949 TheCall->setArg(0, Arg.get());
1950
1951 return TheCall;
1952}
1953
1955 if (S.checkArgCount(TheCall, 1))
1956 return ExprError();
1957
1959 if (Arg.isInvalid())
1960 return ExprError();
1961 QualType ParamTy = Arg.get()->getType();
1962 TheCall->setArg(0, Arg.get());
1963 TheCall->setType(S.Context.BoolTy);
1964
1965 // Only accept pointers to objects as arguments, which should have object
1966 // pointer or void pointer types.
1967 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1968 // LWG4138: Function pointer types not allowed
1969 if (PT->getPointeeType()->isFunctionType()) {
1970 S.Diag(TheCall->getArg(0)->getExprLoc(),
1971 diag::err_builtin_is_within_lifetime_invalid_arg)
1972 << 1;
1973 return ExprError();
1974 }
1975 // Disallow VLAs too since those shouldn't be able to
1976 // be a template parameter for `std::is_within_lifetime`
1977 if (PT->getPointeeType()->isVariableArrayType()) {
1978 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1979 << 1 << "__builtin_is_within_lifetime";
1980 return ExprError();
1981 }
1982 } else {
1983 S.Diag(TheCall->getArg(0)->getExprLoc(),
1984 diag::err_builtin_is_within_lifetime_invalid_arg)
1985 << 0;
1986 return ExprError();
1987 }
1988 return TheCall;
1989}
1990
1992 if (S.checkArgCount(TheCall, 3))
1993 return ExprError();
1994
1995 QualType Dest = TheCall->getArg(0)->getType();
1996 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
1997 S.Diag(TheCall->getArg(0)->getExprLoc(),
1998 diag::err_builtin_trivially_relocate_invalid_arg_type)
1999 << /*a pointer*/ 0;
2000 return ExprError();
2001 }
2002
2003 QualType T = Dest->getPointeeType();
2004 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2005 diag::err_incomplete_type))
2006 return ExprError();
2007
2008 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2009 T->isIncompleteArrayType()) {
2010 S.Diag(TheCall->getArg(0)->getExprLoc(),
2011 diag::err_builtin_trivially_relocate_invalid_arg_type)
2012 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2013 return ExprError();
2014 }
2015
2016 TheCall->setType(Dest);
2017
2018 QualType Src = TheCall->getArg(1)->getType();
2019 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2020 S.Diag(TheCall->getArg(1)->getExprLoc(),
2021 diag::err_builtin_trivially_relocate_invalid_arg_type)
2022 << /*the same*/ 3;
2023 return ExprError();
2024 }
2025
2026 Expr *SizeExpr = TheCall->getArg(2);
2027 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2028 if (Size.isInvalid())
2029 return ExprError();
2030
2031 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2032 if (Size.isInvalid())
2033 return ExprError();
2034 SizeExpr = Size.get();
2035 TheCall->setArg(2, SizeExpr);
2036
2037 return TheCall;
2038}
2039
2040// Emit an error and return true if the current object format type is in the
2041// list of unsupported types.
2043 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2044 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2045 llvm::Triple::ObjectFormatType CurObjFormat =
2046 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2047 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2048 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2049 << TheCall->getSourceRange();
2050 return true;
2051 }
2052 return false;
2053}
2054
2055// Emit an error and return true if the current architecture is not in the list
2056// of supported architectures.
2057static bool
2059 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2060 llvm::Triple::ArchType CurArch =
2061 S.getASTContext().getTargetInfo().getTriple().getArch();
2062 if (llvm::is_contained(SupportedArchs, CurArch))
2063 return false;
2064 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2065 << TheCall->getSourceRange();
2066 return true;
2067}
2068
2069static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2070 SourceLocation CallSiteLoc);
2071
2072bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2073 CallExpr *TheCall) {
2074 switch (TI.getTriple().getArch()) {
2075 default:
2076 // Some builtins don't require additional checking, so just consider these
2077 // acceptable.
2078 return false;
2079 case llvm::Triple::arm:
2080 case llvm::Triple::armeb:
2081 case llvm::Triple::thumb:
2082 case llvm::Triple::thumbeb:
2083 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2084 case llvm::Triple::aarch64:
2085 case llvm::Triple::aarch64_32:
2086 case llvm::Triple::aarch64_be:
2087 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2088 case llvm::Triple::bpfeb:
2089 case llvm::Triple::bpfel:
2090 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2091 case llvm::Triple::dxil:
2092 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2093 case llvm::Triple::hexagon:
2094 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2095 case llvm::Triple::mips:
2096 case llvm::Triple::mipsel:
2097 case llvm::Triple::mips64:
2098 case llvm::Triple::mips64el:
2099 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2100 case llvm::Triple::spirv:
2101 case llvm::Triple::spirv32:
2102 case llvm::Triple::spirv64:
2103 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2104 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2105 return false;
2106 case llvm::Triple::systemz:
2107 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2108 case llvm::Triple::x86:
2109 case llvm::Triple::x86_64:
2110 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2111 case llvm::Triple::ppc:
2112 case llvm::Triple::ppcle:
2113 case llvm::Triple::ppc64:
2114 case llvm::Triple::ppc64le:
2115 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2116 case llvm::Triple::amdgcn:
2117 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2118 case llvm::Triple::riscv32:
2119 case llvm::Triple::riscv64:
2120 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2121 case llvm::Triple::loongarch32:
2122 case llvm::Triple::loongarch64:
2123 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2124 TheCall);
2125 case llvm::Triple::wasm32:
2126 case llvm::Triple::wasm64:
2127 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2128 case llvm::Triple::nvptx:
2129 case llvm::Triple::nvptx64:
2130 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2131 }
2132}
2133
2134// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2135// not a valid type, emit an error message and return true. Otherwise return
2136// false.
2137static bool
2140 int ArgOrdinal) {
2141 QualType EltTy = ArgTy;
2142 if (auto *VecTy = EltTy->getAs<VectorType>())
2143 EltTy = VecTy->getElementType();
2144
2145 switch (ArgTyRestr) {
2147 if (!ArgTy->getAs<VectorType>() &&
2149 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2150 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2151 << ArgTy;
2152 }
2153 break;
2155 if (!EltTy->isRealFloatingType()) {
2156 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2157 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2158 << /* floating-point */ 1 << ArgTy;
2159 }
2160 break;
2162 if (!EltTy->isIntegerType()) {
2163 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2164 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2165 << /* no fp */ 0 << ArgTy;
2166 }
2167 break;
2169 if (EltTy->isUnsignedIntegerType()) {
2170 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2171 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2172 << /* or fp */ 1 << ArgTy;
2173 }
2174 break;
2175 }
2176
2177 return false;
2178}
2179
2180/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2181/// This checks that the target supports the builtin and that the string
2182/// argument is constant and valid.
2183static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2184 const TargetInfo *AuxTI, unsigned BuiltinID) {
2185 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2186 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2187 "Expecting __builtin_cpu_...");
2188
2189 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2190 const TargetInfo *TheTI = &TI;
2191 auto SupportsBI = [=](const TargetInfo *TInfo) {
2192 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2193 (!IsCPUSupports && TInfo->supportsCpuIs()));
2194 };
2195 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2196 TheTI = AuxTI;
2197
2198 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2199 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2200 return S.Diag(TheCall->getBeginLoc(),
2201 TI.getTriple().isOSAIX()
2202 ? diag::err_builtin_aix_os_unsupported
2203 : diag::err_builtin_target_unsupported)
2204 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2205
2206 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2207 // Check if the argument is a string literal.
2208 if (!isa<StringLiteral>(Arg))
2209 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2210 << Arg->getSourceRange();
2211
2212 // Check the contents of the string.
2213 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2214 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2215 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2216 << Arg->getSourceRange();
2217 return false;
2218 }
2219 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2220 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2221 << Arg->getSourceRange();
2222 return false;
2223}
2224
2225/// Checks that __builtin_bswapg was called with a single argument, which is an
2226/// unsigned integer, and overrides the return value type to the integer type.
2227static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2228 if (S.checkArgCount(TheCall, 1))
2229 return true;
2230 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2231 if (ArgRes.isInvalid())
2232 return true;
2233
2234 Expr *Arg = ArgRes.get();
2235 TheCall->setArg(0, Arg);
2236 if (Arg->isTypeDependent())
2237 return false;
2238
2239 QualType ArgTy = Arg->getType();
2240
2241 if (!ArgTy->isIntegerType()) {
2242 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2243 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2244 << ArgTy;
2245 return true;
2246 }
2247 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2248 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8) {
2249 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2250 << ArgTy << BT->getNumBits();
2251 return true;
2252 }
2253 }
2254 TheCall->setType(ArgTy);
2255 return false;
2256}
2257
2258/// Checks that __builtin_popcountg was called with a single argument, which is
2259/// an unsigned integer.
2260static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2261 if (S.checkArgCount(TheCall, 1))
2262 return true;
2263
2264 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2265 if (ArgRes.isInvalid())
2266 return true;
2267
2268 Expr *Arg = ArgRes.get();
2269 TheCall->setArg(0, Arg);
2270
2271 QualType ArgTy = Arg->getType();
2272
2273 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2274 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2275 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2276 << ArgTy;
2277 return true;
2278 }
2279 return false;
2280}
2281
2282/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2283/// an unsigned integer, and an optional second argument, which is promoted to
2284/// an 'int'.
2285static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2286 if (S.checkArgCountRange(TheCall, 1, 2))
2287 return true;
2288
2289 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2290 if (Arg0Res.isInvalid())
2291 return true;
2292
2293 Expr *Arg0 = Arg0Res.get();
2294 TheCall->setArg(0, Arg0);
2295
2296 QualType Arg0Ty = Arg0->getType();
2297
2298 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2299 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2300 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2301 << Arg0Ty;
2302 return true;
2303 }
2304
2305 if (TheCall->getNumArgs() > 1) {
2306 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2307 if (Arg1Res.isInvalid())
2308 return true;
2309
2310 Expr *Arg1 = Arg1Res.get();
2311 TheCall->setArg(1, Arg1);
2312
2313 QualType Arg1Ty = Arg1->getType();
2314
2315 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2316 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2317 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2318 return true;
2319 }
2320 }
2321
2322 return false;
2323}
2324
2325static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2326 unsigned Pos, bool AllowConst,
2327 bool AllowAS) {
2328 QualType MaskTy = MaskArg->getType();
2329 if (!MaskTy->isExtVectorBoolType())
2330 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2331 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2332 << MaskTy;
2333
2334 QualType PtrTy = PtrArg->getType();
2335 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2336 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2337 << Pos << "scalar pointer";
2338
2339 QualType PointeeTy = PtrTy->getPointeeType();
2340 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2341 (!AllowConst && PointeeTy.isConstQualified()) ||
2342 (!AllowAS && PointeeTy.hasAddressSpace())) {
2345 return S.Diag(PtrArg->getExprLoc(),
2346 diag::err_typecheck_convert_incompatible)
2347 << PtrTy << Target << /*different qualifiers=*/5
2348 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2349 << PtrTy << Target;
2350 }
2351 return false;
2352}
2353
2354static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2355 bool TypeDependent = false;
2356 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2357 ExprResult Converted =
2359 if (Converted.isInvalid())
2360 return true;
2361 TheCall->setArg(Arg, Converted.get());
2362 TypeDependent |= Converted.get()->isTypeDependent();
2363 }
2364
2365 if (TypeDependent)
2366 TheCall->setType(S.Context.DependentTy);
2367 return false;
2368}
2369
2371 if (S.checkArgCountRange(TheCall, 2, 3))
2372 return ExprError();
2373
2374 if (ConvertMaskedBuiltinArgs(S, TheCall))
2375 return ExprError();
2376
2377 Expr *MaskArg = TheCall->getArg(0);
2378 Expr *PtrArg = TheCall->getArg(1);
2379 if (TheCall->isTypeDependent())
2380 return TheCall;
2381
2382 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2383 TheCall->getBuiltinCallee() ==
2384 Builtin::BI__builtin_masked_load))
2385 return ExprError();
2386
2387 QualType MaskTy = MaskArg->getType();
2388 QualType PtrTy = PtrArg->getType();
2389 QualType PointeeTy = PtrTy->getPointeeType();
2390 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2391
2393 MaskVecTy->getNumElements());
2394 if (TheCall->getNumArgs() == 3) {
2395 Expr *PassThruArg = TheCall->getArg(2);
2396 QualType PassThruTy = PassThruArg->getType();
2397 if (!S.Context.hasSameType(PassThruTy, RetTy))
2398 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2399 << /* third argument */ 3 << RetTy;
2400 }
2401
2402 TheCall->setType(RetTy);
2403 return TheCall;
2404}
2405
2407 if (S.checkArgCount(TheCall, 3))
2408 return ExprError();
2409
2410 if (ConvertMaskedBuiltinArgs(S, TheCall))
2411 return ExprError();
2412
2413 Expr *MaskArg = TheCall->getArg(0);
2414 Expr *ValArg = TheCall->getArg(1);
2415 Expr *PtrArg = TheCall->getArg(2);
2416 if (TheCall->isTypeDependent())
2417 return TheCall;
2418
2419 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2420 TheCall->getBuiltinCallee() ==
2421 Builtin::BI__builtin_masked_store))
2422 return ExprError();
2423
2424 QualType MaskTy = MaskArg->getType();
2425 QualType PtrTy = PtrArg->getType();
2426 QualType ValTy = ValArg->getType();
2427 if (!ValTy->isVectorType())
2428 return ExprError(
2429 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2430 << 2 << "vector");
2431
2432 QualType PointeeTy = PtrTy->getPointeeType();
2433 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2434 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2435 MaskVecTy->getNumElements());
2436 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2437 MemoryTy.getUnqualifiedType()))
2438 return ExprError(S.Diag(TheCall->getBeginLoc(),
2439 diag::err_vec_builtin_incompatible_vector)
2440 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2441 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2442 TheCall->getArg(1)->getEndLoc()));
2443
2444 TheCall->setType(S.Context.VoidTy);
2445 return TheCall;
2446}
2447
2449 if (S.checkArgCountRange(TheCall, 3, 4))
2450 return ExprError();
2451
2452 if (ConvertMaskedBuiltinArgs(S, TheCall))
2453 return ExprError();
2454
2455 Expr *MaskArg = TheCall->getArg(0);
2456 Expr *IdxArg = TheCall->getArg(1);
2457 Expr *PtrArg = TheCall->getArg(2);
2458 if (TheCall->isTypeDependent())
2459 return TheCall;
2460
2461 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2462 /*AllowAS=*/true))
2463 return ExprError();
2464
2465 QualType IdxTy = IdxArg->getType();
2466 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2467 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2468 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2469 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2470 << IdxTy;
2471
2472 QualType MaskTy = MaskArg->getType();
2473 QualType PtrTy = PtrArg->getType();
2474 QualType PointeeTy = PtrTy->getPointeeType();
2475 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2476 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2477 return ExprError(
2478 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2480 TheCall->getBuiltinCallee())
2481 << MaskTy << IdxTy);
2482
2484 MaskVecTy->getNumElements());
2485 if (TheCall->getNumArgs() == 4) {
2486 Expr *PassThruArg = TheCall->getArg(3);
2487 QualType PassThruTy = PassThruArg->getType();
2488 if (!S.Context.hasSameType(PassThruTy, RetTy))
2489 return S.Diag(PassThruArg->getExprLoc(),
2490 diag::err_vec_masked_load_store_ptr)
2491 << /* fourth argument */ 4 << RetTy;
2492 }
2493
2494 TheCall->setType(RetTy);
2495 return TheCall;
2496}
2497
2499 if (S.checkArgCount(TheCall, 4))
2500 return ExprError();
2501
2502 if (ConvertMaskedBuiltinArgs(S, TheCall))
2503 return ExprError();
2504
2505 Expr *MaskArg = TheCall->getArg(0);
2506 Expr *IdxArg = TheCall->getArg(1);
2507 Expr *ValArg = TheCall->getArg(2);
2508 Expr *PtrArg = TheCall->getArg(3);
2509 if (TheCall->isTypeDependent())
2510 return TheCall;
2511
2512 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2513 /*AllowAS=*/true))
2514 return ExprError();
2515
2516 QualType IdxTy = IdxArg->getType();
2517 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2518 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2519 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2520 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2521 << IdxTy;
2522
2523 QualType ValTy = ValArg->getType();
2524 QualType MaskTy = MaskArg->getType();
2525 QualType PtrTy = PtrArg->getType();
2526 QualType PointeeTy = PtrTy->getPointeeType();
2527
2528 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2529 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2530 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2531 return ExprError(
2532 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2534 TheCall->getBuiltinCallee())
2535 << MaskTy << IdxTy);
2536 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2537 return ExprError(
2538 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2540 TheCall->getBuiltinCallee())
2541 << MaskTy << ValTy);
2542
2544 MaskVecTy->getNumElements());
2545 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2546 return ExprError(S.Diag(TheCall->getBeginLoc(),
2547 diag::err_vec_builtin_incompatible_vector)
2548 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2549 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2550 TheCall->getArg(1)->getEndLoc()));
2551
2552 TheCall->setType(S.Context.VoidTy);
2553 return TheCall;
2554}
2555
2557 SourceLocation Loc = TheCall->getBeginLoc();
2558 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2559 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2560
2561 if (Args.size() == 0) {
2562 S.Diag(TheCall->getBeginLoc(),
2563 diag::err_typecheck_call_too_few_args_at_least)
2564 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2565 << /*is_non_object=*/0 << TheCall->getSourceRange();
2566 return ExprError();
2567 }
2568
2569 QualType FuncT = Args[0]->getType();
2570
2571 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2572 if (Args.size() < 2) {
2573 S.Diag(TheCall->getBeginLoc(),
2574 diag::err_typecheck_call_too_few_args_at_least)
2575 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2576 << /*is_non_object=*/0 << TheCall->getSourceRange();
2577 return ExprError();
2578 }
2579
2580 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2581 QualType ObjectT = Args[1]->getType();
2582
2583 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2584 return ExprError();
2585
2586 ExprResult ObjectArg = [&]() -> ExprResult {
2587 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2588 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2589 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2590 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2591 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2592 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2593 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2594 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2595 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2596 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2597 return Args[1];
2598 }
2599
2600 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2601 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2602 // reference_wrapper;
2603 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2604 if (RD->isInStdNamespace() &&
2605 RD->getDeclName().getAsString() == "reference_wrapper") {
2606 CXXScopeSpec SS;
2607 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2608 UnqualifiedId GetID;
2609 GetID.setIdentifier(GetName, Loc);
2610
2612 S.getCurScope(), Args[1], Loc, tok::period, SS,
2613 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2614
2615 if (MemExpr.isInvalid())
2616 return ExprError();
2617
2618 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2619 }
2620 }
2621
2622 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2623 // class T and t1 does not satisfy the previous two items;
2624
2625 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2626 }();
2627
2628 if (ObjectArg.isInvalid())
2629 return ExprError();
2630
2631 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2632 tok::periodstar, ObjectArg.get(), Args[0]);
2633 if (BinOp.isInvalid())
2634 return ExprError();
2635
2636 if (MPT->isMemberDataPointer())
2637 return BinOp;
2638
2639 auto *MemCall = new (S.Context)
2641
2642 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2643 Args.drop_front(2), TheCall->getRParenLoc());
2644 }
2645 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2646 Args.drop_front(), TheCall->getRParenLoc());
2647}
2648
2649// Performs a similar job to Sema::UsualUnaryConversions, but without any
2650// implicit promotion of integral/enumeration types.
2652 // First, convert to an r-value.
2654 if (Res.isInvalid())
2655 return ExprError();
2656
2657 // Promote floating-point types.
2658 return S.UsualUnaryFPConversions(Res.get());
2659}
2660
2662Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2663 CallExpr *TheCall) {
2664 ExprResult TheCallResult(TheCall);
2665
2666 // Find out if any arguments are required to be integer constant expressions.
2667 unsigned ICEArguments = 0;
2669 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2671 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2672
2673 // If any arguments are required to be ICE's, check and diagnose.
2674 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2675 // Skip arguments not required to be ICE's.
2676 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2677
2678 llvm::APSInt Result;
2679 // If we don't have enough arguments, continue so we can issue better
2680 // diagnostic in checkArgCount(...)
2681 if (ArgNo < TheCall->getNumArgs() &&
2682 BuiltinConstantArg(TheCall, ArgNo, Result))
2683 return true;
2684 ICEArguments &= ~(1 << ArgNo);
2685 }
2686
2687 FPOptions FPO;
2688 switch (BuiltinID) {
2689 case Builtin::BI__builtin_cpu_supports:
2690 case Builtin::BI__builtin_cpu_is:
2691 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2692 Context.getAuxTargetInfo(), BuiltinID))
2693 return ExprError();
2694 break;
2695 case Builtin::BI__builtin_cpu_init:
2696 if (!Context.getTargetInfo().supportsCpuInit()) {
2697 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2698 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2699 return ExprError();
2700 }
2701 break;
2702 case Builtin::BI__builtin___CFStringMakeConstantString:
2703 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2704 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2706 *this, BuiltinID, TheCall,
2707 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2708 return ExprError();
2709 assert(TheCall->getNumArgs() == 1 &&
2710 "Wrong # arguments to builtin CFStringMakeConstantString");
2711 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2712 return ExprError();
2713 break;
2714 case Builtin::BI__builtin_ms_va_start:
2715 case Builtin::BI__builtin_stdarg_start:
2716 case Builtin::BI__builtin_va_start:
2717 case Builtin::BI__builtin_c23_va_start:
2718 if (BuiltinVAStart(BuiltinID, TheCall))
2719 return ExprError();
2720 break;
2721 case Builtin::BI__va_start: {
2722 switch (Context.getTargetInfo().getTriple().getArch()) {
2723 case llvm::Triple::aarch64:
2724 case llvm::Triple::arm:
2725 case llvm::Triple::thumb:
2726 if (BuiltinVAStartARMMicrosoft(TheCall))
2727 return ExprError();
2728 break;
2729 default:
2730 if (BuiltinVAStart(BuiltinID, TheCall))
2731 return ExprError();
2732 break;
2733 }
2734 break;
2735 }
2736
2737 // The acquire, release, and no fence variants are ARM and AArch64 only.
2738 case Builtin::BI_interlockedbittestandset_acq:
2739 case Builtin::BI_interlockedbittestandset_rel:
2740 case Builtin::BI_interlockedbittestandset_nf:
2741 case Builtin::BI_interlockedbittestandreset_acq:
2742 case Builtin::BI_interlockedbittestandreset_rel:
2743 case Builtin::BI_interlockedbittestandreset_nf:
2745 *this, TheCall,
2746 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2747 return ExprError();
2748 break;
2749
2750 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2751 case Builtin::BI_bittest64:
2752 case Builtin::BI_bittestandcomplement64:
2753 case Builtin::BI_bittestandreset64:
2754 case Builtin::BI_bittestandset64:
2755 case Builtin::BI_interlockedbittestandreset64:
2756 case Builtin::BI_interlockedbittestandset64:
2758 *this, TheCall,
2759 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2760 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2761 return ExprError();
2762 break;
2763
2764 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2765 case Builtin::BI_interlockedbittestandreset64_acq:
2766 case Builtin::BI_interlockedbittestandreset64_rel:
2767 case Builtin::BI_interlockedbittestandreset64_nf:
2768 case Builtin::BI_interlockedbittestandset64_acq:
2769 case Builtin::BI_interlockedbittestandset64_rel:
2770 case Builtin::BI_interlockedbittestandset64_nf:
2771 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2772 return ExprError();
2773 break;
2774
2775 case Builtin::BI__builtin_set_flt_rounds:
2777 *this, TheCall,
2778 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2779 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2780 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2781 llvm::Triple::ppc64le}))
2782 return ExprError();
2783 break;
2784
2785 case Builtin::BI__builtin_isgreater:
2786 case Builtin::BI__builtin_isgreaterequal:
2787 case Builtin::BI__builtin_isless:
2788 case Builtin::BI__builtin_islessequal:
2789 case Builtin::BI__builtin_islessgreater:
2790 case Builtin::BI__builtin_isunordered:
2791 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2792 return ExprError();
2793 break;
2794 case Builtin::BI__builtin_fpclassify:
2795 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2796 return ExprError();
2797 break;
2798 case Builtin::BI__builtin_isfpclass:
2799 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2800 return ExprError();
2801 break;
2802 case Builtin::BI__builtin_isfinite:
2803 case Builtin::BI__builtin_isinf:
2804 case Builtin::BI__builtin_isinf_sign:
2805 case Builtin::BI__builtin_isnan:
2806 case Builtin::BI__builtin_issignaling:
2807 case Builtin::BI__builtin_isnormal:
2808 case Builtin::BI__builtin_issubnormal:
2809 case Builtin::BI__builtin_iszero:
2810 case Builtin::BI__builtin_signbit:
2811 case Builtin::BI__builtin_signbitf:
2812 case Builtin::BI__builtin_signbitl:
2813 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2814 return ExprError();
2815 break;
2816 case Builtin::BI__builtin_shufflevector:
2817 return BuiltinShuffleVector(TheCall);
2818 // TheCall will be freed by the smart pointer here, but that's fine, since
2819 // BuiltinShuffleVector guts it, but then doesn't release it.
2820 case Builtin::BI__builtin_masked_load:
2821 case Builtin::BI__builtin_masked_expand_load:
2822 return BuiltinMaskedLoad(*this, TheCall);
2823 case Builtin::BI__builtin_masked_store:
2824 case Builtin::BI__builtin_masked_compress_store:
2825 return BuiltinMaskedStore(*this, TheCall);
2826 case Builtin::BI__builtin_masked_gather:
2827 return BuiltinMaskedGather(*this, TheCall);
2828 case Builtin::BI__builtin_masked_scatter:
2829 return BuiltinMaskedScatter(*this, TheCall);
2830 case Builtin::BI__builtin_invoke:
2831 return BuiltinInvoke(*this, TheCall);
2832 case Builtin::BI__builtin_prefetch:
2833 if (BuiltinPrefetch(TheCall))
2834 return ExprError();
2835 break;
2836 case Builtin::BI__builtin_alloca_with_align:
2837 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2838 if (BuiltinAllocaWithAlign(TheCall))
2839 return ExprError();
2840 [[fallthrough]];
2841 case Builtin::BI__builtin_alloca:
2842 case Builtin::BI__builtin_alloca_uninitialized:
2843 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2844 << TheCall->getDirectCallee();
2845 if (getLangOpts().OpenCL) {
2846 builtinAllocaAddrSpace(*this, TheCall);
2847 }
2848 break;
2849 case Builtin::BI__builtin_infer_alloc_token:
2850 if (checkBuiltinInferAllocToken(*this, TheCall))
2851 return ExprError();
2852 break;
2853 case Builtin::BI__arithmetic_fence:
2854 if (BuiltinArithmeticFence(TheCall))
2855 return ExprError();
2856 break;
2857 case Builtin::BI__assume:
2858 case Builtin::BI__builtin_assume:
2859 if (BuiltinAssume(TheCall))
2860 return ExprError();
2861 break;
2862 case Builtin::BI__builtin_assume_aligned:
2863 if (BuiltinAssumeAligned(TheCall))
2864 return ExprError();
2865 break;
2866 case Builtin::BI__builtin_dynamic_object_size:
2867 case Builtin::BI__builtin_object_size:
2868 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2869 return ExprError();
2870 break;
2871 case Builtin::BI__builtin_longjmp:
2872 if (BuiltinLongjmp(TheCall))
2873 return ExprError();
2874 break;
2875 case Builtin::BI__builtin_setjmp:
2876 if (BuiltinSetjmp(TheCall))
2877 return ExprError();
2878 break;
2879 case Builtin::BI__builtin_classify_type:
2880 if (checkArgCount(TheCall, 1))
2881 return true;
2882 TheCall->setType(Context.IntTy);
2883 break;
2884 case Builtin::BI__builtin_complex:
2885 if (BuiltinComplex(TheCall))
2886 return ExprError();
2887 break;
2888 case Builtin::BI__builtin_constant_p: {
2889 if (checkArgCount(TheCall, 1))
2890 return true;
2892 if (Arg.isInvalid()) return true;
2893 TheCall->setArg(0, Arg.get());
2894 TheCall->setType(Context.IntTy);
2895 break;
2896 }
2897 case Builtin::BI__builtin_launder:
2898 return BuiltinLaunder(*this, TheCall);
2899 case Builtin::BI__builtin_is_within_lifetime:
2900 return BuiltinIsWithinLifetime(*this, TheCall);
2901 case Builtin::BI__builtin_trivially_relocate:
2902 return BuiltinTriviallyRelocate(*this, TheCall);
2903
2904 case Builtin::BI__sync_fetch_and_add:
2905 case Builtin::BI__sync_fetch_and_add_1:
2906 case Builtin::BI__sync_fetch_and_add_2:
2907 case Builtin::BI__sync_fetch_and_add_4:
2908 case Builtin::BI__sync_fetch_and_add_8:
2909 case Builtin::BI__sync_fetch_and_add_16:
2910 case Builtin::BI__sync_fetch_and_sub:
2911 case Builtin::BI__sync_fetch_and_sub_1:
2912 case Builtin::BI__sync_fetch_and_sub_2:
2913 case Builtin::BI__sync_fetch_and_sub_4:
2914 case Builtin::BI__sync_fetch_and_sub_8:
2915 case Builtin::BI__sync_fetch_and_sub_16:
2916 case Builtin::BI__sync_fetch_and_or:
2917 case Builtin::BI__sync_fetch_and_or_1:
2918 case Builtin::BI__sync_fetch_and_or_2:
2919 case Builtin::BI__sync_fetch_and_or_4:
2920 case Builtin::BI__sync_fetch_and_or_8:
2921 case Builtin::BI__sync_fetch_and_or_16:
2922 case Builtin::BI__sync_fetch_and_and:
2923 case Builtin::BI__sync_fetch_and_and_1:
2924 case Builtin::BI__sync_fetch_and_and_2:
2925 case Builtin::BI__sync_fetch_and_and_4:
2926 case Builtin::BI__sync_fetch_and_and_8:
2927 case Builtin::BI__sync_fetch_and_and_16:
2928 case Builtin::BI__sync_fetch_and_xor:
2929 case Builtin::BI__sync_fetch_and_xor_1:
2930 case Builtin::BI__sync_fetch_and_xor_2:
2931 case Builtin::BI__sync_fetch_and_xor_4:
2932 case Builtin::BI__sync_fetch_and_xor_8:
2933 case Builtin::BI__sync_fetch_and_xor_16:
2934 case Builtin::BI__sync_fetch_and_nand:
2935 case Builtin::BI__sync_fetch_and_nand_1:
2936 case Builtin::BI__sync_fetch_and_nand_2:
2937 case Builtin::BI__sync_fetch_and_nand_4:
2938 case Builtin::BI__sync_fetch_and_nand_8:
2939 case Builtin::BI__sync_fetch_and_nand_16:
2940 case Builtin::BI__sync_add_and_fetch:
2941 case Builtin::BI__sync_add_and_fetch_1:
2942 case Builtin::BI__sync_add_and_fetch_2:
2943 case Builtin::BI__sync_add_and_fetch_4:
2944 case Builtin::BI__sync_add_and_fetch_8:
2945 case Builtin::BI__sync_add_and_fetch_16:
2946 case Builtin::BI__sync_sub_and_fetch:
2947 case Builtin::BI__sync_sub_and_fetch_1:
2948 case Builtin::BI__sync_sub_and_fetch_2:
2949 case Builtin::BI__sync_sub_and_fetch_4:
2950 case Builtin::BI__sync_sub_and_fetch_8:
2951 case Builtin::BI__sync_sub_and_fetch_16:
2952 case Builtin::BI__sync_and_and_fetch:
2953 case Builtin::BI__sync_and_and_fetch_1:
2954 case Builtin::BI__sync_and_and_fetch_2:
2955 case Builtin::BI__sync_and_and_fetch_4:
2956 case Builtin::BI__sync_and_and_fetch_8:
2957 case Builtin::BI__sync_and_and_fetch_16:
2958 case Builtin::BI__sync_or_and_fetch:
2959 case Builtin::BI__sync_or_and_fetch_1:
2960 case Builtin::BI__sync_or_and_fetch_2:
2961 case Builtin::BI__sync_or_and_fetch_4:
2962 case Builtin::BI__sync_or_and_fetch_8:
2963 case Builtin::BI__sync_or_and_fetch_16:
2964 case Builtin::BI__sync_xor_and_fetch:
2965 case Builtin::BI__sync_xor_and_fetch_1:
2966 case Builtin::BI__sync_xor_and_fetch_2:
2967 case Builtin::BI__sync_xor_and_fetch_4:
2968 case Builtin::BI__sync_xor_and_fetch_8:
2969 case Builtin::BI__sync_xor_and_fetch_16:
2970 case Builtin::BI__sync_nand_and_fetch:
2971 case Builtin::BI__sync_nand_and_fetch_1:
2972 case Builtin::BI__sync_nand_and_fetch_2:
2973 case Builtin::BI__sync_nand_and_fetch_4:
2974 case Builtin::BI__sync_nand_and_fetch_8:
2975 case Builtin::BI__sync_nand_and_fetch_16:
2976 case Builtin::BI__sync_val_compare_and_swap:
2977 case Builtin::BI__sync_val_compare_and_swap_1:
2978 case Builtin::BI__sync_val_compare_and_swap_2:
2979 case Builtin::BI__sync_val_compare_and_swap_4:
2980 case Builtin::BI__sync_val_compare_and_swap_8:
2981 case Builtin::BI__sync_val_compare_and_swap_16:
2982 case Builtin::BI__sync_bool_compare_and_swap:
2983 case Builtin::BI__sync_bool_compare_and_swap_1:
2984 case Builtin::BI__sync_bool_compare_and_swap_2:
2985 case Builtin::BI__sync_bool_compare_and_swap_4:
2986 case Builtin::BI__sync_bool_compare_and_swap_8:
2987 case Builtin::BI__sync_bool_compare_and_swap_16:
2988 case Builtin::BI__sync_lock_test_and_set:
2989 case Builtin::BI__sync_lock_test_and_set_1:
2990 case Builtin::BI__sync_lock_test_and_set_2:
2991 case Builtin::BI__sync_lock_test_and_set_4:
2992 case Builtin::BI__sync_lock_test_and_set_8:
2993 case Builtin::BI__sync_lock_test_and_set_16:
2994 case Builtin::BI__sync_lock_release:
2995 case Builtin::BI__sync_lock_release_1:
2996 case Builtin::BI__sync_lock_release_2:
2997 case Builtin::BI__sync_lock_release_4:
2998 case Builtin::BI__sync_lock_release_8:
2999 case Builtin::BI__sync_lock_release_16:
3000 case Builtin::BI__sync_swap:
3001 case Builtin::BI__sync_swap_1:
3002 case Builtin::BI__sync_swap_2:
3003 case Builtin::BI__sync_swap_4:
3004 case Builtin::BI__sync_swap_8:
3005 case Builtin::BI__sync_swap_16:
3006 return BuiltinAtomicOverloaded(TheCallResult);
3007 case Builtin::BI__sync_synchronize:
3008 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3009 << TheCall->getCallee()->getSourceRange();
3010 break;
3011 case Builtin::BI__builtin_nontemporal_load:
3012 case Builtin::BI__builtin_nontemporal_store:
3013 return BuiltinNontemporalOverloaded(TheCallResult);
3014 case Builtin::BI__builtin_memcpy_inline: {
3015 clang::Expr *SizeOp = TheCall->getArg(2);
3016 // We warn about copying to or from `nullptr` pointers when `size` is
3017 // greater than 0. When `size` is value dependent we cannot evaluate its
3018 // value so we bail out.
3019 if (SizeOp->isValueDependent())
3020 break;
3021 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3022 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3023 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3024 }
3025 break;
3026 }
3027 case Builtin::BI__builtin_memset_inline: {
3028 clang::Expr *SizeOp = TheCall->getArg(2);
3029 // We warn about filling to `nullptr` pointers when `size` is greater than
3030 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3031 // out.
3032 if (SizeOp->isValueDependent())
3033 break;
3034 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3035 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3036 break;
3037 }
3038#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3039 case Builtin::BI##ID: \
3040 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3041#include "clang/Basic/Builtins.inc"
3042 case Builtin::BI__annotation:
3043 if (BuiltinMSVCAnnotation(*this, TheCall))
3044 return ExprError();
3045 break;
3046 case Builtin::BI__builtin_annotation:
3047 if (BuiltinAnnotation(*this, TheCall))
3048 return ExprError();
3049 break;
3050 case Builtin::BI__builtin_addressof:
3051 if (BuiltinAddressof(*this, TheCall))
3052 return ExprError();
3053 break;
3054 case Builtin::BI__builtin_function_start:
3055 if (BuiltinFunctionStart(*this, TheCall))
3056 return ExprError();
3057 break;
3058 case Builtin::BI__builtin_is_aligned:
3059 case Builtin::BI__builtin_align_up:
3060 case Builtin::BI__builtin_align_down:
3061 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3062 return ExprError();
3063 break;
3064 case Builtin::BI__builtin_add_overflow:
3065 case Builtin::BI__builtin_sub_overflow:
3066 case Builtin::BI__builtin_mul_overflow:
3067 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3068 return ExprError();
3069 break;
3070 case Builtin::BI__builtin_operator_new:
3071 case Builtin::BI__builtin_operator_delete: {
3072 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3073 ExprResult Res =
3074 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3075 return Res;
3076 }
3077 case Builtin::BI__builtin_dump_struct:
3078 return BuiltinDumpStruct(*this, TheCall);
3079 case Builtin::BI__builtin_expect_with_probability: {
3080 // We first want to ensure we are called with 3 arguments
3081 if (checkArgCount(TheCall, 3))
3082 return ExprError();
3083 // then check probability is constant float in range [0.0, 1.0]
3084 const Expr *ProbArg = TheCall->getArg(2);
3085 SmallVector<PartialDiagnosticAt, 8> Notes;
3086 Expr::EvalResult Eval;
3087 Eval.Diag = &Notes;
3088 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3089 !Eval.Val.isFloat()) {
3090 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3091 << ProbArg->getSourceRange();
3092 for (const PartialDiagnosticAt &PDiag : Notes)
3093 Diag(PDiag.first, PDiag.second);
3094 return ExprError();
3095 }
3096 llvm::APFloat Probability = Eval.Val.getFloat();
3097 bool LoseInfo = false;
3098 Probability.convert(llvm::APFloat::IEEEdouble(),
3099 llvm::RoundingMode::Dynamic, &LoseInfo);
3100 if (!(Probability >= llvm::APFloat(0.0) &&
3101 Probability <= llvm::APFloat(1.0))) {
3102 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3103 << ProbArg->getSourceRange();
3104 return ExprError();
3105 }
3106 break;
3107 }
3108 case Builtin::BI__builtin_preserve_access_index:
3109 if (BuiltinPreserveAI(*this, TheCall))
3110 return ExprError();
3111 break;
3112 case Builtin::BI__builtin_call_with_static_chain:
3113 if (BuiltinCallWithStaticChain(*this, TheCall))
3114 return ExprError();
3115 break;
3116 case Builtin::BI__exception_code:
3117 case Builtin::BI_exception_code:
3118 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3119 diag::err_seh___except_block))
3120 return ExprError();
3121 break;
3122 case Builtin::BI__exception_info:
3123 case Builtin::BI_exception_info:
3124 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3125 diag::err_seh___except_filter))
3126 return ExprError();
3127 break;
3128 case Builtin::BI__GetExceptionInfo:
3129 if (checkArgCount(TheCall, 1))
3130 return ExprError();
3131
3133 TheCall->getBeginLoc(),
3134 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3135 TheCall))
3136 return ExprError();
3137
3138 TheCall->setType(Context.VoidPtrTy);
3139 break;
3140 case Builtin::BIaddressof:
3141 case Builtin::BI__addressof:
3142 case Builtin::BIforward:
3143 case Builtin::BIforward_like:
3144 case Builtin::BImove:
3145 case Builtin::BImove_if_noexcept:
3146 case Builtin::BIas_const: {
3147 // These are all expected to be of the form
3148 // T &/&&/* f(U &/&&)
3149 // where T and U only differ in qualification.
3150 if (checkArgCount(TheCall, 1))
3151 return ExprError();
3152 QualType Param = FDecl->getParamDecl(0)->getType();
3153 QualType Result = FDecl->getReturnType();
3154 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3155 BuiltinID == Builtin::BI__addressof;
3156 if (!(Param->isReferenceType() &&
3157 (ReturnsPointer ? Result->isAnyPointerType()
3158 : Result->isReferenceType()) &&
3159 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3160 Result->getPointeeType()))) {
3161 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3162 << FDecl;
3163 return ExprError();
3164 }
3165 break;
3166 }
3167 case Builtin::BI__builtin_ptrauth_strip:
3168 return PointerAuthStrip(*this, TheCall);
3169 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3170 return PointerAuthBlendDiscriminator(*this, TheCall);
3171 case Builtin::BI__builtin_ptrauth_sign_constant:
3172 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3173 /*RequireConstant=*/true);
3174 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3175 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3176 /*RequireConstant=*/false);
3177 case Builtin::BI__builtin_ptrauth_auth:
3178 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3179 /*RequireConstant=*/false);
3180 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3181 return PointerAuthSignGenericData(*this, TheCall);
3182 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3183 return PointerAuthAuthAndResign(*this, TheCall);
3184 case Builtin::BI__builtin_ptrauth_string_discriminator:
3185 return PointerAuthStringDiscriminator(*this, TheCall);
3186
3187 case Builtin::BI__builtin_get_vtable_pointer:
3188 return GetVTablePointer(*this, TheCall);
3189
3190 // OpenCL v2.0, s6.13.16 - Pipe functions
3191 case Builtin::BIread_pipe:
3192 case Builtin::BIwrite_pipe:
3193 // Since those two functions are declared with var args, we need a semantic
3194 // check for the argument.
3195 if (OpenCL().checkBuiltinRWPipe(TheCall))
3196 return ExprError();
3197 break;
3198 case Builtin::BIreserve_read_pipe:
3199 case Builtin::BIreserve_write_pipe:
3200 case Builtin::BIwork_group_reserve_read_pipe:
3201 case Builtin::BIwork_group_reserve_write_pipe:
3202 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3203 return ExprError();
3204 break;
3205 case Builtin::BIsub_group_reserve_read_pipe:
3206 case Builtin::BIsub_group_reserve_write_pipe:
3207 if (OpenCL().checkSubgroupExt(TheCall) ||
3208 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3209 return ExprError();
3210 break;
3211 case Builtin::BIcommit_read_pipe:
3212 case Builtin::BIcommit_write_pipe:
3213 case Builtin::BIwork_group_commit_read_pipe:
3214 case Builtin::BIwork_group_commit_write_pipe:
3215 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3216 return ExprError();
3217 break;
3218 case Builtin::BIsub_group_commit_read_pipe:
3219 case Builtin::BIsub_group_commit_write_pipe:
3220 if (OpenCL().checkSubgroupExt(TheCall) ||
3221 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3222 return ExprError();
3223 break;
3224 case Builtin::BIget_pipe_num_packets:
3225 case Builtin::BIget_pipe_max_packets:
3226 if (OpenCL().checkBuiltinPipePackets(TheCall))
3227 return ExprError();
3228 break;
3229 case Builtin::BIto_global:
3230 case Builtin::BIto_local:
3231 case Builtin::BIto_private:
3232 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3233 return ExprError();
3234 break;
3235 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3236 case Builtin::BIenqueue_kernel:
3237 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3238 return ExprError();
3239 break;
3240 case Builtin::BIget_kernel_work_group_size:
3241 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3242 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3243 return ExprError();
3244 break;
3245 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3246 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3247 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3248 return ExprError();
3249 break;
3250 case Builtin::BI__builtin_os_log_format:
3251 Cleanup.setExprNeedsCleanups(true);
3252 [[fallthrough]];
3253 case Builtin::BI__builtin_os_log_format_buffer_size:
3254 if (BuiltinOSLogFormat(TheCall))
3255 return ExprError();
3256 break;
3257 case Builtin::BI__builtin_frame_address:
3258 case Builtin::BI__builtin_return_address: {
3259 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3260 return ExprError();
3261
3262 // -Wframe-address warning if non-zero passed to builtin
3263 // return/frame address.
3264 Expr::EvalResult Result;
3265 if (!TheCall->getArg(0)->isValueDependent() &&
3266 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3267 Result.Val.getInt() != 0)
3268 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3269 << ((BuiltinID == Builtin::BI__builtin_return_address)
3270 ? "__builtin_return_address"
3271 : "__builtin_frame_address")
3272 << TheCall->getSourceRange();
3273 break;
3274 }
3275
3276 case Builtin::BI__builtin_nondeterministic_value: {
3277 if (BuiltinNonDeterministicValue(TheCall))
3278 return ExprError();
3279 break;
3280 }
3281
3282 // __builtin_elementwise_abs restricts the element type to signed integers or
3283 // floating point types only.
3284 case Builtin::BI__builtin_elementwise_abs:
3287 return ExprError();
3288 break;
3289
3290 // These builtins restrict the element type to floating point
3291 // types only.
3292 case Builtin::BI__builtin_elementwise_acos:
3293 case Builtin::BI__builtin_elementwise_asin:
3294 case Builtin::BI__builtin_elementwise_atan:
3295 case Builtin::BI__builtin_elementwise_ceil:
3296 case Builtin::BI__builtin_elementwise_cos:
3297 case Builtin::BI__builtin_elementwise_cosh:
3298 case Builtin::BI__builtin_elementwise_exp:
3299 case Builtin::BI__builtin_elementwise_exp2:
3300 case Builtin::BI__builtin_elementwise_exp10:
3301 case Builtin::BI__builtin_elementwise_floor:
3302 case Builtin::BI__builtin_elementwise_log:
3303 case Builtin::BI__builtin_elementwise_log2:
3304 case Builtin::BI__builtin_elementwise_log10:
3305 case Builtin::BI__builtin_elementwise_roundeven:
3306 case Builtin::BI__builtin_elementwise_round:
3307 case Builtin::BI__builtin_elementwise_rint:
3308 case Builtin::BI__builtin_elementwise_nearbyint:
3309 case Builtin::BI__builtin_elementwise_sin:
3310 case Builtin::BI__builtin_elementwise_sinh:
3311 case Builtin::BI__builtin_elementwise_sqrt:
3312 case Builtin::BI__builtin_elementwise_tan:
3313 case Builtin::BI__builtin_elementwise_tanh:
3314 case Builtin::BI__builtin_elementwise_trunc:
3315 case Builtin::BI__builtin_elementwise_canonicalize:
3318 return ExprError();
3319 break;
3320 case Builtin::BI__builtin_elementwise_fma:
3321 if (BuiltinElementwiseTernaryMath(TheCall))
3322 return ExprError();
3323 break;
3324
3325 case Builtin::BI__builtin_elementwise_ldexp: {
3326 if (checkArgCount(TheCall, 2))
3327 return ExprError();
3328
3329 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3330 if (A.isInvalid())
3331 return ExprError();
3332 QualType TyA = A.get()->getType();
3333 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3335 return ExprError();
3336
3337 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3338 if (Exp.isInvalid())
3339 return ExprError();
3340 QualType TyExp = Exp.get()->getType();
3341 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3343 2))
3344 return ExprError();
3345
3346 // Check the two arguments are either scalars or vectors of equal length.
3347 const auto *Vec0 = TyA->getAs<VectorType>();
3348 const auto *Vec1 = TyExp->getAs<VectorType>();
3349 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3350 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3351 if (Arg0Length != Arg1Length) {
3352 Diag(Exp.get()->getBeginLoc(),
3353 diag::err_typecheck_vector_lengths_not_equal)
3354 << TyA << TyExp << A.get()->getSourceRange()
3355 << Exp.get()->getSourceRange();
3356 return ExprError();
3357 }
3358
3359 TheCall->setArg(0, A.get());
3360 TheCall->setArg(1, Exp.get());
3361 TheCall->setType(TyA);
3362 break;
3363 }
3364
3365 // These builtins restrict the element type to floating point
3366 // types only, and take in two arguments.
3367 case Builtin::BI__builtin_elementwise_minnum:
3368 case Builtin::BI__builtin_elementwise_maxnum:
3369 case Builtin::BI__builtin_elementwise_minimum:
3370 case Builtin::BI__builtin_elementwise_maximum:
3371 case Builtin::BI__builtin_elementwise_minimumnum:
3372 case Builtin::BI__builtin_elementwise_maximumnum:
3373 case Builtin::BI__builtin_elementwise_atan2:
3374 case Builtin::BI__builtin_elementwise_fmod:
3375 case Builtin::BI__builtin_elementwise_pow:
3376 if (BuiltinElementwiseMath(TheCall,
3378 return ExprError();
3379 break;
3380 // These builtins restrict the element type to integer
3381 // types only.
3382 case Builtin::BI__builtin_elementwise_add_sat:
3383 case Builtin::BI__builtin_elementwise_sub_sat:
3384 if (BuiltinElementwiseMath(TheCall,
3386 return ExprError();
3387 break;
3388 case Builtin::BI__builtin_elementwise_fshl:
3389 case Builtin::BI__builtin_elementwise_fshr:
3392 return ExprError();
3393 break;
3394 case Builtin::BI__builtin_elementwise_min:
3395 case Builtin::BI__builtin_elementwise_max:
3396 if (BuiltinElementwiseMath(TheCall))
3397 return ExprError();
3398 break;
3399 case Builtin::BI__builtin_elementwise_popcount:
3400 case Builtin::BI__builtin_elementwise_bitreverse:
3403 return ExprError();
3404 break;
3405 case Builtin::BI__builtin_elementwise_copysign: {
3406 if (checkArgCount(TheCall, 2))
3407 return ExprError();
3408
3409 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3410 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3411 if (Magnitude.isInvalid() || Sign.isInvalid())
3412 return ExprError();
3413
3414 QualType MagnitudeTy = Magnitude.get()->getType();
3415 QualType SignTy = Sign.get()->getType();
3417 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3420 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3422 return ExprError();
3423 }
3424
3425 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3426 return Diag(Sign.get()->getBeginLoc(),
3427 diag::err_typecheck_call_different_arg_types)
3428 << MagnitudeTy << SignTy;
3429 }
3430
3431 TheCall->setArg(0, Magnitude.get());
3432 TheCall->setArg(1, Sign.get());
3433 TheCall->setType(Magnitude.get()->getType());
3434 break;
3435 }
3436 case Builtin::BI__builtin_elementwise_clzg:
3437 case Builtin::BI__builtin_elementwise_ctzg:
3438 // These builtins can be unary or binary. Note for empty calls we call the
3439 // unary checker in order to not emit an error that says the function
3440 // expects 2 arguments, which would be misleading.
3441 if (TheCall->getNumArgs() <= 1) {
3444 return ExprError();
3445 } else if (BuiltinElementwiseMath(
3447 return ExprError();
3448 break;
3449 case Builtin::BI__builtin_reduce_max:
3450 case Builtin::BI__builtin_reduce_min: {
3451 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3452 return ExprError();
3453
3454 const Expr *Arg = TheCall->getArg(0);
3455 const auto *TyA = Arg->getType()->getAs<VectorType>();
3456
3457 QualType ElTy;
3458 if (TyA)
3459 ElTy = TyA->getElementType();
3460 else if (Arg->getType()->isSizelessVectorType())
3462
3463 if (ElTy.isNull()) {
3464 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3465 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3466 << Arg->getType();
3467 return ExprError();
3468 }
3469
3470 TheCall->setType(ElTy);
3471 break;
3472 }
3473 case Builtin::BI__builtin_reduce_maximum:
3474 case Builtin::BI__builtin_reduce_minimum: {
3475 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3476 return ExprError();
3477
3478 const Expr *Arg = TheCall->getArg(0);
3479 const auto *TyA = Arg->getType()->getAs<VectorType>();
3480
3481 QualType ElTy;
3482 if (TyA)
3483 ElTy = TyA->getElementType();
3484 else if (Arg->getType()->isSizelessVectorType())
3486
3487 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3488 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3489 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3490 << Arg->getType();
3491 return ExprError();
3492 }
3493
3494 TheCall->setType(ElTy);
3495 break;
3496 }
3497
3498 // These builtins support vectors of integers only.
3499 // TODO: ADD/MUL should support floating-point types.
3500 case Builtin::BI__builtin_reduce_add:
3501 case Builtin::BI__builtin_reduce_mul:
3502 case Builtin::BI__builtin_reduce_xor:
3503 case Builtin::BI__builtin_reduce_or:
3504 case Builtin::BI__builtin_reduce_and: {
3505 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3506 return ExprError();
3507
3508 const Expr *Arg = TheCall->getArg(0);
3509 const auto *TyA = Arg->getType()->getAs<VectorType>();
3510
3511 QualType ElTy;
3512 if (TyA)
3513 ElTy = TyA->getElementType();
3514 else if (Arg->getType()->isSizelessVectorType())
3516
3517 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3518 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3519 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3520 << Arg->getType();
3521 return ExprError();
3522 }
3523
3524 TheCall->setType(ElTy);
3525 break;
3526 }
3527
3528 case Builtin::BI__builtin_matrix_transpose:
3529 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3530
3531 case Builtin::BI__builtin_matrix_column_major_load:
3532 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3533
3534 case Builtin::BI__builtin_matrix_column_major_store:
3535 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3536
3537 case Builtin::BI__builtin_verbose_trap:
3538 if (!checkBuiltinVerboseTrap(TheCall, *this))
3539 return ExprError();
3540 break;
3541
3542 case Builtin::BI__builtin_get_device_side_mangled_name: {
3543 auto Check = [](CallExpr *TheCall) {
3544 if (TheCall->getNumArgs() != 1)
3545 return false;
3546 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3547 if (!DRE)
3548 return false;
3549 auto *D = DRE->getDecl();
3550 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3551 return false;
3552 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3553 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3554 };
3555 if (!Check(TheCall)) {
3556 Diag(TheCall->getBeginLoc(),
3557 diag::err_hip_invalid_args_builtin_mangled_name);
3558 return ExprError();
3559 }
3560 break;
3561 }
3562 case Builtin::BI__builtin_bswapg:
3563 if (BuiltinBswapg(*this, TheCall))
3564 return ExprError();
3565 break;
3566 case Builtin::BI__builtin_popcountg:
3567 if (BuiltinPopcountg(*this, TheCall))
3568 return ExprError();
3569 break;
3570 case Builtin::BI__builtin_clzg:
3571 case Builtin::BI__builtin_ctzg:
3572 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3573 return ExprError();
3574 break;
3575
3576 case Builtin::BI__builtin_allow_runtime_check: {
3577 Expr *Arg = TheCall->getArg(0);
3578 // Check if the argument is a string literal.
3580 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3581 << Arg->getSourceRange();
3582 return ExprError();
3583 }
3584 break;
3585 }
3586 case Builtin::BI__builtin_counted_by_ref:
3587 if (BuiltinCountedByRef(TheCall))
3588 return ExprError();
3589 break;
3590 }
3591
3592 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3593 return ExprError();
3594
3595 // Since the target specific builtins for each arch overlap, only check those
3596 // of the arch we are compiling for.
3597 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3598 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3599 assert(Context.getAuxTargetInfo() &&
3600 "Aux Target Builtin, but not an aux target?");
3601
3602 if (CheckTSBuiltinFunctionCall(
3603 *Context.getAuxTargetInfo(),
3604 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3605 return ExprError();
3606 } else {
3607 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3608 TheCall))
3609 return ExprError();
3610 }
3611 }
3612
3613 return TheCallResult;
3614}
3615
3616bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3617 llvm::APSInt Result;
3618 // We can't check the value of a dependent argument.
3619 Expr *Arg = TheCall->getArg(ArgNum);
3620 if (Arg->isTypeDependent() || Arg->isValueDependent())
3621 return false;
3622
3623 // Check constant-ness first.
3624 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3625 return true;
3626
3627 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3628 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3629 return false;
3630
3631 return Diag(TheCall->getBeginLoc(),
3632 diag::err_argument_not_contiguous_bit_field)
3633 << ArgNum << Arg->getSourceRange();
3634}
3635
3636bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3637 unsigned FirstArg, FormatStringInfo *FSI) {
3638 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3639 bool IsVariadic = false;
3640 if (const FunctionType *FnTy = D->getFunctionType())
3641 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3642 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3643 IsVariadic = BD->isVariadic();
3644 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3645 IsVariadic = OMD->isVariadic();
3646
3647 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3648 IsVariadic, FSI);
3649}
3650
3651bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3652 bool HasImplicitThisParam, bool IsVariadic,
3653 FormatStringInfo *FSI) {
3654 if (FirstArg == 0)
3656 else if (IsVariadic)
3658 else
3660 FSI->FormatIdx = FormatIdx - 1;
3661 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3662
3663 // The way the format attribute works in GCC, the implicit this argument
3664 // of member functions is counted. However, it doesn't appear in our own
3665 // lists, so decrement format_idx in that case.
3666 if (HasImplicitThisParam) {
3667 if(FSI->FormatIdx == 0)
3668 return false;
3669 --FSI->FormatIdx;
3670 if (FSI->FirstDataArg != 0)
3671 --FSI->FirstDataArg;
3672 }
3673 return true;
3674}
3675
3676/// Checks if a the given expression evaluates to null.
3677///
3678/// Returns true if the value evaluates to null.
3679static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3680 // Treat (smart) pointers constructed from nullptr as null, whether we can
3681 // const-evaluate them or not.
3682 // This must happen first: the smart pointer expr might have _Nonnull type!
3686 return true;
3687
3688 // If the expression has non-null type, it doesn't evaluate to null.
3689 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3690 if (*nullability == NullabilityKind::NonNull)
3691 return false;
3692 }
3693
3694 // As a special case, transparent unions initialized with zero are
3695 // considered null for the purposes of the nonnull attribute.
3696 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3697 UT &&
3698 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3699 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3700 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3701 Expr = ILE->getInit(0);
3702 }
3703
3704 bool Result;
3705 return (!Expr->isValueDependent() &&
3707 !Result);
3708}
3709
3711 const Expr *ArgExpr,
3712 SourceLocation CallSiteLoc) {
3713 if (CheckNonNullExpr(S, ArgExpr))
3714 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3715 S.PDiag(diag::warn_null_arg)
3716 << ArgExpr->getSourceRange());
3717}
3718
3719/// Determine whether the given type has a non-null nullability annotation.
3721 if (auto nullability = type->getNullability())
3722 return *nullability == NullabilityKind::NonNull;
3723
3724 return false;
3725}
3726
3728 const NamedDecl *FDecl,
3729 const FunctionProtoType *Proto,
3731 SourceLocation CallSiteLoc) {
3732 assert((FDecl || Proto) && "Need a function declaration or prototype");
3733
3734 // Already checked by constant evaluator.
3736 return;
3737 // Check the attributes attached to the method/function itself.
3738 llvm::SmallBitVector NonNullArgs;
3739 if (FDecl) {
3740 // Handle the nonnull attribute on the function/method declaration itself.
3741 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3742 if (!NonNull->args_size()) {
3743 // Easy case: all pointer arguments are nonnull.
3744 for (const auto *Arg : Args)
3745 if (S.isValidPointerAttrType(Arg->getType()))
3746 CheckNonNullArgument(S, Arg, CallSiteLoc);
3747 return;
3748 }
3749
3750 for (const ParamIdx &Idx : NonNull->args()) {
3751 unsigned IdxAST = Idx.getASTIndex();
3752 if (IdxAST >= Args.size())
3753 continue;
3754 if (NonNullArgs.empty())
3755 NonNullArgs.resize(Args.size());
3756 NonNullArgs.set(IdxAST);
3757 }
3758 }
3759 }
3760
3761 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3762 // Handle the nonnull attribute on the parameters of the
3763 // function/method.
3765 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3766 parms = FD->parameters();
3767 else
3768 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3769
3770 unsigned ParamIndex = 0;
3771 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3772 I != E; ++I, ++ParamIndex) {
3773 const ParmVarDecl *PVD = *I;
3774 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3775 if (NonNullArgs.empty())
3776 NonNullArgs.resize(Args.size());
3777
3778 NonNullArgs.set(ParamIndex);
3779 }
3780 }
3781 } else {
3782 // If we have a non-function, non-method declaration but no
3783 // function prototype, try to dig out the function prototype.
3784 if (!Proto) {
3785 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3786 QualType type = VD->getType().getNonReferenceType();
3787 if (auto pointerType = type->getAs<PointerType>())
3788 type = pointerType->getPointeeType();
3789 else if (auto blockType = type->getAs<BlockPointerType>())
3790 type = blockType->getPointeeType();
3791 // FIXME: data member pointers?
3792
3793 // Dig out the function prototype, if there is one.
3794 Proto = type->getAs<FunctionProtoType>();
3795 }
3796 }
3797
3798 // Fill in non-null argument information from the nullability
3799 // information on the parameter types (if we have them).
3800 if (Proto) {
3801 unsigned Index = 0;
3802 for (auto paramType : Proto->getParamTypes()) {
3803 if (isNonNullType(paramType)) {
3804 if (NonNullArgs.empty())
3805 NonNullArgs.resize(Args.size());
3806
3807 NonNullArgs.set(Index);
3808 }
3809
3810 ++Index;
3811 }
3812 }
3813 }
3814
3815 // Check for non-null arguments.
3816 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3817 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3818 if (NonNullArgs[ArgIndex])
3819 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3820 }
3821}
3822
3823void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3824 StringRef ParamName, QualType ArgTy,
3825 QualType ParamTy) {
3826
3827 // If a function accepts a pointer or reference type
3828 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3829 return;
3830
3831 // If the parameter is a pointer type, get the pointee type for the
3832 // argument too. If the parameter is a reference type, don't try to get
3833 // the pointee type for the argument.
3834 if (ParamTy->isPointerType())
3835 ArgTy = ArgTy->getPointeeType();
3836
3837 // Remove reference or pointer
3838 ParamTy = ParamTy->getPointeeType();
3839
3840 // Find expected alignment, and the actual alignment of the passed object.
3841 // getTypeAlignInChars requires complete types
3842 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3843 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3844 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3845 return;
3846
3847 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3848 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3849
3850 // If the argument is less aligned than the parameter, there is a
3851 // potential alignment issue.
3852 if (ArgAlign < ParamAlign)
3853 Diag(Loc, diag::warn_param_mismatched_alignment)
3854 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3855 << ParamName << (FDecl != nullptr) << FDecl;
3856}
3857
3858void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3859 const Expr *ThisArg,
3861 if (!FD || Args.empty())
3862 return;
3863 auto GetArgAt = [&](int Idx) -> const Expr * {
3864 if (Idx == LifetimeCaptureByAttr::Global ||
3865 Idx == LifetimeCaptureByAttr::Unknown)
3866 return nullptr;
3867 if (IsMemberFunction && Idx == 0)
3868 return ThisArg;
3869 return Args[Idx - IsMemberFunction];
3870 };
3871 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3872 unsigned ArgIdx) {
3873 if (!Attr)
3874 return;
3875
3876 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3877 for (int CapturingParamIdx : Attr->params()) {
3878 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3879 // initialization codepath.
3880 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3882 continue;
3883 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3884 CapturingEntity CE{Capturing};
3885 // Ensure that 'Captured' outlives the 'Capturing' entity.
3886 checkCaptureByLifetime(*this, CE, Captured);
3887 }
3888 };
3889 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3890 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3891 I + IsMemberFunction);
3892 // Check when the implicit object param is captured.
3893 if (IsMemberFunction) {
3894 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3895 if (!TSI)
3896 return;
3898 for (TypeLoc TL = TSI->getTypeLoc();
3899 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3900 TL = ATL.getModifiedLoc())
3901 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3902 }
3903}
3904
3906 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3907 bool IsMemberFunction, SourceLocation Loc,
3908 SourceRange Range, VariadicCallType CallType) {
3909 // FIXME: We should check as much as we can in the template definition.
3910 if (CurContext->isDependentContext())
3911 return;
3912
3913 // Printf and scanf checking.
3914 llvm::SmallBitVector CheckedVarArgs;
3915 if (FDecl) {
3916 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3917 // Only create vector if there are format attributes.
3918 CheckedVarArgs.resize(Args.size());
3919 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3920 CheckedVarArgs);
3921 }
3922
3923 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3924 CheckedVarArgs.resize(Args.size());
3925 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3926 CheckedVarArgs);
3927 }
3928 }
3929
3930 // Refuse POD arguments that weren't caught by the format string
3931 // checks above.
3932 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3933 if (CallType != VariadicCallType::DoesNotApply &&
3934 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3935 unsigned NumParams = Proto ? Proto->getNumParams()
3936 : isa_and_nonnull<FunctionDecl>(FDecl)
3937 ? cast<FunctionDecl>(FDecl)->getNumParams()
3938 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3939 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3940 : 0;
3941
3942 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3943 // Args[ArgIdx] can be null in malformed code.
3944 if (const Expr *Arg = Args[ArgIdx]) {
3945 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3946 checkVariadicArgument(Arg, CallType);
3947 }
3948 }
3949 }
3950 if (FD)
3951 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3952 if (FDecl || Proto) {
3953 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3954
3955 // Type safety checking.
3956 if (FDecl) {
3957 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3958 CheckArgumentWithTypeTag(I, Args, Loc);
3959 }
3960 }
3961
3962 // Check that passed arguments match the alignment of original arguments.
3963 // Try to get the missing prototype from the declaration.
3964 if (!Proto && FDecl) {
3965 const auto *FT = FDecl->getFunctionType();
3966 if (isa_and_nonnull<FunctionProtoType>(FT))
3967 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3968 }
3969 if (Proto) {
3970 // For variadic functions, we may have more args than parameters.
3971 // For some K&R functions, we may have less args than parameters.
3972 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3973 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3974 bool IsScalableArg = false;
3975 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3976 // Args[ArgIdx] can be null in malformed code.
3977 if (const Expr *Arg = Args[ArgIdx]) {
3978 if (Arg->containsErrors())
3979 continue;
3980
3981 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3982 FDecl->hasLinkage() &&
3983 FDecl->getFormalLinkage() != Linkage::Internal &&
3985 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3986
3987 QualType ParamTy = Proto->getParamType(ArgIdx);
3988 if (ParamTy->isSizelessVectorType())
3989 IsScalableArg = true;
3990 QualType ArgTy = Arg->getType();
3991 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3992 ArgTy, ParamTy);
3993 }
3994 }
3995
3996 // If the callee has an AArch64 SME attribute to indicate that it is an
3997 // __arm_streaming function, then the caller requires SME to be available.
4000 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4001 llvm::StringMap<bool> CallerFeatureMap;
4002 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4003 if (!CallerFeatureMap.contains("sme"))
4004 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4005 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4006 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4007 }
4008 }
4009
4010 // If the call requires a streaming-mode change and has scalable vector
4011 // arguments or return values, then warn the user that the streaming and
4012 // non-streaming vector lengths may be different.
4013 // When both streaming and non-streaming vector lengths are defined and
4014 // mismatched, produce an error.
4015 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4016 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4017 (IsScalableArg || IsScalableRet)) {
4018 bool IsCalleeStreaming =
4020 bool IsCalleeStreamingCompatible =
4021 ExtInfo.AArch64SMEAttributes &
4023 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4024 if (!IsCalleeStreamingCompatible &&
4025 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4026 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4027 const LangOptions &LO = getLangOpts();
4028 unsigned VL = LO.VScaleMin * 128;
4029 unsigned SVL = LO.VScaleStreamingMin * 128;
4030 bool IsVLMismatch = VL && SVL && VL != SVL;
4031
4032 auto EmitDiag = [&](bool IsArg) {
4033 if (IsVLMismatch) {
4034 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4035 // Emit warning for streaming-compatible callers
4036 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4037 << IsArg << IsCalleeStreaming << SVL << VL;
4038 else
4039 // Emit error otherwise
4040 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4041 << IsArg << SVL << VL;
4042 } else
4043 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4044 << IsArg;
4045 };
4046
4047 if (IsScalableArg)
4048 EmitDiag(true);
4049 if (IsScalableRet)
4050 EmitDiag(false);
4051 }
4052 }
4053
4054 FunctionType::ArmStateValue CalleeArmZAState =
4056 FunctionType::ArmStateValue CalleeArmZT0State =
4058 if (CalleeArmZAState != FunctionType::ARM_None ||
4059 CalleeArmZT0State != FunctionType::ARM_None) {
4060 bool CallerHasZAState = false;
4061 bool CallerHasZT0State = false;
4062 if (CallerFD) {
4063 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4064 if (Attr && Attr->isNewZA())
4065 CallerHasZAState = true;
4066 if (Attr && Attr->isNewZT0())
4067 CallerHasZT0State = true;
4068 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4069 CallerHasZAState |=
4071 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4073 CallerHasZT0State |=
4075 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4077 }
4078 }
4079
4080 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4081 Diag(Loc, diag::err_sme_za_call_no_za_state);
4082
4083 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4084 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4085
4086 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4087 CalleeArmZT0State != FunctionType::ARM_None) {
4088 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4089 Diag(Loc, diag::note_sme_use_preserves_za);
4090 }
4091 }
4092 }
4093
4094 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4095 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4096 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4097 if (!Arg->isValueDependent()) {
4098 Expr::EvalResult Align;
4099 if (Arg->EvaluateAsInt(Align, Context)) {
4100 const llvm::APSInt &I = Align.Val.getInt();
4101 if (!I.isPowerOf2())
4102 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4103 << Arg->getSourceRange();
4104
4105 if (I > Sema::MaximumAlignment)
4106 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4107 << Arg->getSourceRange() << Sema::MaximumAlignment;
4108 }
4109 }
4110 }
4111
4112 if (FD)
4113 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4114}
4115
4116void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4117 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4118 DiagnoseUseOfDecl(Decl, Loc);
4119 }
4120}
4121
4122void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4124 const FunctionProtoType *Proto,
4125 SourceLocation Loc) {
4126 VariadicCallType CallType = Proto->isVariadic()
4129
4130 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4131 CheckArgAlignment(
4132 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4133 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4134
4135 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4136 Loc, SourceRange(), CallType);
4137}
4138
4140 const FunctionProtoType *Proto) {
4141 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4142 isa<CXXMethodDecl>(FDecl);
4143 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4144 IsMemberOperatorCall;
4145 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4146 TheCall->getCallee());
4147 Expr** Args = TheCall->getArgs();
4148 unsigned NumArgs = TheCall->getNumArgs();
4149
4150 Expr *ImplicitThis = nullptr;
4151 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4152 // If this is a call to a member operator, hide the first
4153 // argument from checkCall.
4154 // FIXME: Our choice of AST representation here is less than ideal.
4155 ImplicitThis = Args[0];
4156 ++Args;
4157 --NumArgs;
4158 } else if (IsMemberFunction && !FDecl->isStatic() &&
4160 ImplicitThis =
4161 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4162
4163 if (ImplicitThis) {
4164 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4165 // used.
4166 QualType ThisType = ImplicitThis->getType();
4167 if (!ThisType->isPointerType()) {
4168 assert(!ThisType->isReferenceType());
4169 ThisType = Context.getPointerType(ThisType);
4170 }
4171
4172 QualType ThisTypeFromDecl = Context.getPointerType(
4173 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4174
4175 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4176 ThisTypeFromDecl);
4177 }
4178
4179 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4180 IsMemberFunction, TheCall->getRParenLoc(),
4181 TheCall->getCallee()->getSourceRange(), CallType);
4182
4183 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4184 // None of the checks below are needed for functions that don't have
4185 // simple names (e.g., C++ conversion functions).
4186 if (!FnInfo)
4187 return false;
4188
4189 // Enforce TCB except for builtin calls, which are always allowed.
4190 if (FDecl->getBuiltinID() == 0)
4191 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4192
4193 CheckAbsoluteValueFunction(TheCall, FDecl);
4194 CheckMaxUnsignedZero(TheCall, FDecl);
4195 CheckInfNaNFunction(TheCall, FDecl);
4196
4197 if (getLangOpts().ObjC)
4198 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4199
4200 unsigned CMId = FDecl->getMemoryFunctionKind();
4201
4202 // Handle memory setting and copying functions.
4203 switch (CMId) {
4204 case 0:
4205 return false;
4206 case Builtin::BIstrlcpy: // fallthrough
4207 case Builtin::BIstrlcat:
4208 CheckStrlcpycatArguments(TheCall, FnInfo);
4209 break;
4210 case Builtin::BIstrncat:
4211 CheckStrncatArguments(TheCall, FnInfo);
4212 break;
4213 case Builtin::BIfree:
4214 CheckFreeArguments(TheCall);
4215 break;
4216 default:
4217 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4218 }
4219
4220 return false;
4221}
4222
4223bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4224 const FunctionProtoType *Proto) {
4225 QualType Ty;
4226 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4227 Ty = V->getType().getNonReferenceType();
4228 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4229 Ty = F->getType().getNonReferenceType();
4230 else
4231 return false;
4232
4233 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4234 !Ty->isFunctionProtoType())
4235 return false;
4236
4237 VariadicCallType CallType;
4238 if (!Proto || !Proto->isVariadic()) {
4240 } else if (Ty->isBlockPointerType()) {
4241 CallType = VariadicCallType::Block;
4242 } else { // Ty->isFunctionPointerType()
4243 CallType = VariadicCallType::Function;
4244 }
4245
4246 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4247 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4248 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4249 TheCall->getCallee()->getSourceRange(), CallType);
4250
4251 return false;
4252}
4253
4254bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4255 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4256 TheCall->getCallee());
4257 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4258 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4259 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4260 TheCall->getCallee()->getSourceRange(), CallType);
4261
4262 return false;
4263}
4264
4265static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4266 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4267 return false;
4268
4269 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4270 switch (Op) {
4271 case AtomicExpr::AO__c11_atomic_init:
4272 case AtomicExpr::AO__opencl_atomic_init:
4273 llvm_unreachable("There is no ordering argument for an init");
4274
4275 case AtomicExpr::AO__c11_atomic_load:
4276 case AtomicExpr::AO__opencl_atomic_load:
4277 case AtomicExpr::AO__hip_atomic_load:
4278 case AtomicExpr::AO__atomic_load_n:
4279 case AtomicExpr::AO__atomic_load:
4280 case AtomicExpr::AO__scoped_atomic_load_n:
4281 case AtomicExpr::AO__scoped_atomic_load:
4282 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4283 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4284
4285 case AtomicExpr::AO__c11_atomic_store:
4286 case AtomicExpr::AO__opencl_atomic_store:
4287 case AtomicExpr::AO__hip_atomic_store:
4288 case AtomicExpr::AO__atomic_store:
4289 case AtomicExpr::AO__atomic_store_n:
4290 case AtomicExpr::AO__scoped_atomic_store:
4291 case AtomicExpr::AO__scoped_atomic_store_n:
4292 case AtomicExpr::AO__atomic_clear:
4293 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4294 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4295 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4296
4297 default:
4298 return true;
4299 }
4300}
4301
4302ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4304 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4305 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4306 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4307 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4308 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4309 Op);
4310}
4311
4313 SourceLocation RParenLoc, MultiExprArg Args,
4315 AtomicArgumentOrder ArgOrder) {
4316 // All the non-OpenCL operations take one of the following forms.
4317 // The OpenCL operations take the __c11 forms with one extra argument for
4318 // synchronization scope.
4319 enum {
4320 // C __c11_atomic_init(A *, C)
4321 Init,
4322
4323 // C __c11_atomic_load(A *, int)
4324 Load,
4325
4326 // void __atomic_load(A *, CP, int)
4327 LoadCopy,
4328
4329 // void __atomic_store(A *, CP, int)
4330 Copy,
4331
4332 // C __c11_atomic_add(A *, M, int)
4333 Arithmetic,
4334
4335 // C __atomic_exchange_n(A *, CP, int)
4336 Xchg,
4337
4338 // void __atomic_exchange(A *, C *, CP, int)
4339 GNUXchg,
4340
4341 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4342 C11CmpXchg,
4343
4344 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4345 GNUCmpXchg,
4346
4347 // bool __atomic_test_and_set(A *, int)
4348 TestAndSetByte,
4349
4350 // void __atomic_clear(A *, int)
4351 ClearByte,
4352 } Form = Init;
4353
4354 const unsigned NumForm = ClearByte + 1;
4355 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4356 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4357 // where:
4358 // C is an appropriate type,
4359 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4360 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4361 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4362 // the int parameters are for orderings.
4363
4364 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4365 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4366 "need to update code for modified forms");
4367 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4368 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4369 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4370 "need to update code for modified C11 atomics");
4371 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4372 Op <= AtomicExpr::AO__opencl_atomic_store;
4373 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4374 Op <= AtomicExpr::AO__hip_atomic_store;
4375 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4376 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4377 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4378 Op <= AtomicExpr::AO__c11_atomic_store) ||
4379 IsOpenCL;
4380 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4381 Op == AtomicExpr::AO__atomic_store_n ||
4382 Op == AtomicExpr::AO__atomic_exchange_n ||
4383 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4384 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4385 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4386 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4387 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4388 // Bit mask for extra allowed value types other than integers for atomic
4389 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4390 // allow floating point.
4391 enum ArithOpExtraValueType {
4392 AOEVT_None = 0,
4393 AOEVT_Pointer = 1,
4394 AOEVT_FP = 2,
4395 };
4396 unsigned ArithAllows = AOEVT_None;
4397
4398 switch (Op) {
4399 case AtomicExpr::AO__c11_atomic_init:
4400 case AtomicExpr::AO__opencl_atomic_init:
4401 Form = Init;
4402 break;
4403
4404 case AtomicExpr::AO__c11_atomic_load:
4405 case AtomicExpr::AO__opencl_atomic_load:
4406 case AtomicExpr::AO__hip_atomic_load:
4407 case AtomicExpr::AO__atomic_load_n:
4408 case AtomicExpr::AO__scoped_atomic_load_n:
4409 Form = Load;
4410 break;
4411
4412 case AtomicExpr::AO__atomic_load:
4413 case AtomicExpr::AO__scoped_atomic_load:
4414 Form = LoadCopy;
4415 break;
4416
4417 case AtomicExpr::AO__c11_atomic_store:
4418 case AtomicExpr::AO__opencl_atomic_store:
4419 case AtomicExpr::AO__hip_atomic_store:
4420 case AtomicExpr::AO__atomic_store:
4421 case AtomicExpr::AO__atomic_store_n:
4422 case AtomicExpr::AO__scoped_atomic_store:
4423 case AtomicExpr::AO__scoped_atomic_store_n:
4424 Form = Copy;
4425 break;
4426 case AtomicExpr::AO__atomic_fetch_add:
4427 case AtomicExpr::AO__atomic_fetch_sub:
4428 case AtomicExpr::AO__atomic_add_fetch:
4429 case AtomicExpr::AO__atomic_sub_fetch:
4430 case AtomicExpr::AO__scoped_atomic_fetch_add:
4431 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4432 case AtomicExpr::AO__scoped_atomic_add_fetch:
4433 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4434 case AtomicExpr::AO__c11_atomic_fetch_add:
4435 case AtomicExpr::AO__c11_atomic_fetch_sub:
4436 case AtomicExpr::AO__opencl_atomic_fetch_add:
4437 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4438 case AtomicExpr::AO__hip_atomic_fetch_add:
4439 case AtomicExpr::AO__hip_atomic_fetch_sub:
4440 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4441 Form = Arithmetic;
4442 break;
4443 case AtomicExpr::AO__atomic_fetch_max:
4444 case AtomicExpr::AO__atomic_fetch_min:
4445 case AtomicExpr::AO__atomic_max_fetch:
4446 case AtomicExpr::AO__atomic_min_fetch:
4447 case AtomicExpr::AO__scoped_atomic_fetch_max:
4448 case AtomicExpr::AO__scoped_atomic_fetch_min:
4449 case AtomicExpr::AO__scoped_atomic_max_fetch:
4450 case AtomicExpr::AO__scoped_atomic_min_fetch:
4451 case AtomicExpr::AO__c11_atomic_fetch_max:
4452 case AtomicExpr::AO__c11_atomic_fetch_min:
4453 case AtomicExpr::AO__opencl_atomic_fetch_max:
4454 case AtomicExpr::AO__opencl_atomic_fetch_min:
4455 case AtomicExpr::AO__hip_atomic_fetch_max:
4456 case AtomicExpr::AO__hip_atomic_fetch_min:
4457 ArithAllows = AOEVT_FP;
4458 Form = Arithmetic;
4459 break;
4460 case AtomicExpr::AO__c11_atomic_fetch_and:
4461 case AtomicExpr::AO__c11_atomic_fetch_or:
4462 case AtomicExpr::AO__c11_atomic_fetch_xor:
4463 case AtomicExpr::AO__hip_atomic_fetch_and:
4464 case AtomicExpr::AO__hip_atomic_fetch_or:
4465 case AtomicExpr::AO__hip_atomic_fetch_xor:
4466 case AtomicExpr::AO__c11_atomic_fetch_nand:
4467 case AtomicExpr::AO__opencl_atomic_fetch_and:
4468 case AtomicExpr::AO__opencl_atomic_fetch_or:
4469 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4470 case AtomicExpr::AO__atomic_fetch_and:
4471 case AtomicExpr::AO__atomic_fetch_or:
4472 case AtomicExpr::AO__atomic_fetch_xor:
4473 case AtomicExpr::AO__atomic_fetch_nand:
4474 case AtomicExpr::AO__atomic_and_fetch:
4475 case AtomicExpr::AO__atomic_or_fetch:
4476 case AtomicExpr::AO__atomic_xor_fetch:
4477 case AtomicExpr::AO__atomic_nand_fetch:
4478 case AtomicExpr::AO__scoped_atomic_fetch_and:
4479 case AtomicExpr::AO__scoped_atomic_fetch_or:
4480 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4481 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4482 case AtomicExpr::AO__scoped_atomic_and_fetch:
4483 case AtomicExpr::AO__scoped_atomic_or_fetch:
4484 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4485 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4486 case AtomicExpr::AO__scoped_atomic_uinc_wrap:
4487 case AtomicExpr::AO__scoped_atomic_udec_wrap:
4488 Form = Arithmetic;
4489 break;
4490
4491 case AtomicExpr::AO__c11_atomic_exchange:
4492 case AtomicExpr::AO__hip_atomic_exchange:
4493 case AtomicExpr::AO__opencl_atomic_exchange:
4494 case AtomicExpr::AO__atomic_exchange_n:
4495 case AtomicExpr::AO__scoped_atomic_exchange_n:
4496 Form = Xchg;
4497 break;
4498
4499 case AtomicExpr::AO__atomic_exchange:
4500 case AtomicExpr::AO__scoped_atomic_exchange:
4501 Form = GNUXchg;
4502 break;
4503
4504 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4505 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4506 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4507 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4508 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4509 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4510 Form = C11CmpXchg;
4511 break;
4512
4513 case AtomicExpr::AO__atomic_compare_exchange:
4514 case AtomicExpr::AO__atomic_compare_exchange_n:
4515 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4516 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4517 Form = GNUCmpXchg;
4518 break;
4519
4520 case AtomicExpr::AO__atomic_test_and_set:
4521 Form = TestAndSetByte;
4522 break;
4523
4524 case AtomicExpr::AO__atomic_clear:
4525 Form = ClearByte;
4526 break;
4527 }
4528
4529 unsigned AdjustedNumArgs = NumArgs[Form];
4530 if ((IsOpenCL || IsHIP || IsScoped) &&
4531 Op != AtomicExpr::AO__opencl_atomic_init)
4532 ++AdjustedNumArgs;
4533 // Check we have the right number of arguments.
4534 if (Args.size() < AdjustedNumArgs) {
4535 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4536 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4537 << /*is non object*/ 0 << ExprRange;
4538 return ExprError();
4539 } else if (Args.size() > AdjustedNumArgs) {
4540 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4541 diag::err_typecheck_call_too_many_args)
4542 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4543 << /*is non object*/ 0 << ExprRange;
4544 return ExprError();
4545 }
4546
4547 // Inspect the first argument of the atomic operation.
4548 Expr *Ptr = Args[0];
4550 if (ConvertedPtr.isInvalid())
4551 return ExprError();
4552
4553 Ptr = ConvertedPtr.get();
4554 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4555 if (!pointerType) {
4556 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4557 << Ptr->getType() << 0 << Ptr->getSourceRange();
4558 return ExprError();
4559 }
4560
4561 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4562 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4563 QualType ValType = AtomTy; // 'C'
4564 if (IsC11) {
4565 if (!AtomTy->isAtomicType()) {
4566 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4567 << Ptr->getType() << Ptr->getSourceRange();
4568 return ExprError();
4569 }
4570 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4572 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4573 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4574 << Ptr->getSourceRange();
4575 return ExprError();
4576 }
4577 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4578 } else if (Form != Load && Form != LoadCopy) {
4579 if (ValType.isConstQualified()) {
4580 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4581 << Ptr->getType() << Ptr->getSourceRange();
4582 return ExprError();
4583 }
4584 }
4585
4586 if (Form != TestAndSetByte && Form != ClearByte) {
4587 // Pointer to object of size zero is not allowed.
4588 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4589 diag::err_incomplete_type))
4590 return ExprError();
4591
4592 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4593 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4594 << Ptr->getType() << 1 << Ptr->getSourceRange();
4595 return ExprError();
4596 }
4597 } else {
4598 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4599 // non-const pointer type, including void* and pointers to incomplete
4600 // structs, but only access the first byte.
4601 AtomTy = Context.CharTy;
4602 AtomTy = AtomTy.withCVRQualifiers(
4603 pointerType->getPointeeType().getCVRQualifiers());
4604 QualType PointerQT = Context.getPointerType(AtomTy);
4605 pointerType = PointerQT->getAs<PointerType>();
4606 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4607 ValType = AtomTy;
4608 }
4609
4610 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4611 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4612 Diag(ExprRange.getBegin(),
4613 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4614 << 0 << Ptr->getType() << Ptr->getSourceRange();
4615 return ExprError();
4616 }
4617
4618 // For an arithmetic operation, the implied arithmetic must be well-formed.
4619 if (Form == Arithmetic) {
4620 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4621 // trivial type errors.
4622 auto IsAllowedValueType = [&](QualType ValType,
4623 unsigned AllowedType) -> bool {
4624 if (ValType->isIntegerType())
4625 return true;
4626 if (ValType->isPointerType())
4627 return AllowedType & AOEVT_Pointer;
4628 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4629 return false;
4630 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4631 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4632 &Context.getTargetInfo().getLongDoubleFormat() ==
4633 &llvm::APFloat::x87DoubleExtended())
4634 return false;
4635 return true;
4636 };
4637 if (!IsAllowedValueType(ValType, ArithAllows)) {
4638 auto DID = ArithAllows & AOEVT_FP
4639 ? (ArithAllows & AOEVT_Pointer
4640 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4641 : diag::err_atomic_op_needs_atomic_int_or_fp)
4642 : diag::err_atomic_op_needs_atomic_int;
4643 Diag(ExprRange.getBegin(), DID)
4644 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4645 return ExprError();
4646 }
4647 if (IsC11 && ValType->isPointerType() &&
4649 diag::err_incomplete_type)) {
4650 return ExprError();
4651 }
4652 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4653 // For __atomic_*_n operations, the value type must be a scalar integral or
4654 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4655 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4656 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4657 return ExprError();
4658 }
4659
4660 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4661 !AtomTy->isScalarType()) {
4662 // For GNU atomics, require a trivially-copyable type. This is not part of
4663 // the GNU atomics specification but we enforce it for consistency with
4664 // other atomics which generally all require a trivially-copyable type. This
4665 // is because atomics just copy bits.
4666 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4667 << Ptr->getType() << Ptr->getSourceRange();
4668 return ExprError();
4669 }
4670
4671 switch (ValType.getObjCLifetime()) {
4674 // okay
4675 break;
4676
4680 // FIXME: Can this happen? By this point, ValType should be known
4681 // to be trivially copyable.
4682 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4683 << ValType << Ptr->getSourceRange();
4684 return ExprError();
4685 }
4686
4687 // All atomic operations have an overload which takes a pointer to a volatile
4688 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4689 // into the result or the other operands. Similarly atomic_load takes a
4690 // pointer to a const 'A'.
4691 ValType.removeLocalVolatile();
4692 ValType.removeLocalConst();
4693 QualType ResultType = ValType;
4694 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4695 Form == ClearByte)
4696 ResultType = Context.VoidTy;
4697 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4698 ResultType = Context.BoolTy;
4699
4700 // The type of a parameter passed 'by value'. In the GNU atomics, such
4701 // arguments are actually passed as pointers.
4702 QualType ByValType = ValType; // 'CP'
4703 bool IsPassedByAddress = false;
4704 if (!IsC11 && !IsHIP && !IsN) {
4705 ByValType = Ptr->getType();
4706 IsPassedByAddress = true;
4707 }
4708
4709 SmallVector<Expr *, 5> APIOrderedArgs;
4710 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4711 APIOrderedArgs.push_back(Args[0]);
4712 switch (Form) {
4713 case Init:
4714 case Load:
4715 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4716 break;
4717 case LoadCopy:
4718 case Copy:
4719 case Arithmetic:
4720 case Xchg:
4721 APIOrderedArgs.push_back(Args[2]); // Val1
4722 APIOrderedArgs.push_back(Args[1]); // Order
4723 break;
4724 case GNUXchg:
4725 APIOrderedArgs.push_back(Args[2]); // Val1
4726 APIOrderedArgs.push_back(Args[3]); // Val2
4727 APIOrderedArgs.push_back(Args[1]); // Order
4728 break;
4729 case C11CmpXchg:
4730 APIOrderedArgs.push_back(Args[2]); // Val1
4731 APIOrderedArgs.push_back(Args[4]); // Val2
4732 APIOrderedArgs.push_back(Args[1]); // Order
4733 APIOrderedArgs.push_back(Args[3]); // OrderFail
4734 break;
4735 case GNUCmpXchg:
4736 APIOrderedArgs.push_back(Args[2]); // Val1
4737 APIOrderedArgs.push_back(Args[4]); // Val2
4738 APIOrderedArgs.push_back(Args[5]); // Weak
4739 APIOrderedArgs.push_back(Args[1]); // Order
4740 APIOrderedArgs.push_back(Args[3]); // OrderFail
4741 break;
4742 case TestAndSetByte:
4743 case ClearByte:
4744 APIOrderedArgs.push_back(Args[1]); // Order
4745 break;
4746 }
4747 } else
4748 APIOrderedArgs.append(Args.begin(), Args.end());
4749
4750 // The first argument's non-CV pointer type is used to deduce the type of
4751 // subsequent arguments, except for:
4752 // - weak flag (always converted to bool)
4753 // - memory order (always converted to int)
4754 // - scope (always converted to int)
4755 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4756 QualType Ty;
4757 if (i < NumVals[Form] + 1) {
4758 switch (i) {
4759 case 0:
4760 // The first argument is always a pointer. It has a fixed type.
4761 // It is always dereferenced, a nullptr is undefined.
4762 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4763 // Nothing else to do: we already know all we want about this pointer.
4764 continue;
4765 case 1:
4766 // The second argument is the non-atomic operand. For arithmetic, this
4767 // is always passed by value, and for a compare_exchange it is always
4768 // passed by address. For the rest, GNU uses by-address and C11 uses
4769 // by-value.
4770 assert(Form != Load);
4771 if (Form == Arithmetic && ValType->isPointerType())
4772 Ty = Context.getPointerDiffType();
4773 else if (Form == Init || Form == Arithmetic)
4774 Ty = ValType;
4775 else if (Form == Copy || Form == Xchg) {
4776 if (IsPassedByAddress) {
4777 // The value pointer is always dereferenced, a nullptr is undefined.
4778 CheckNonNullArgument(*this, APIOrderedArgs[i],
4779 ExprRange.getBegin());
4780 }
4781 Ty = ByValType;
4782 } else {
4783 Expr *ValArg = APIOrderedArgs[i];
4784 // The value pointer is always dereferenced, a nullptr is undefined.
4785 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4787 // Keep address space of non-atomic pointer type.
4788 if (const PointerType *PtrTy =
4789 ValArg->getType()->getAs<PointerType>()) {
4790 AS = PtrTy->getPointeeType().getAddressSpace();
4791 }
4792 Ty = Context.getPointerType(
4793 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4794 }
4795 break;
4796 case 2:
4797 // The third argument to compare_exchange / GNU exchange is the desired
4798 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4799 if (IsPassedByAddress)
4800 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4801 Ty = ByValType;
4802 break;
4803 case 3:
4804 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4805 Ty = Context.BoolTy;
4806 break;
4807 }
4808 } else {
4809 // The order(s) and scope are always converted to int.
4810 Ty = Context.IntTy;
4811 }
4812
4813 InitializedEntity Entity =
4815 ExprResult Arg = APIOrderedArgs[i];
4816 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4817 if (Arg.isInvalid())
4818 return true;
4819 APIOrderedArgs[i] = Arg.get();
4820 }
4821
4822 // Permute the arguments into a 'consistent' order.
4823 SmallVector<Expr*, 5> SubExprs;
4824 SubExprs.push_back(Ptr);
4825 switch (Form) {
4826 case Init:
4827 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4828 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4829 break;
4830 case Load:
4831 case TestAndSetByte:
4832 case ClearByte:
4833 SubExprs.push_back(APIOrderedArgs[1]); // Order
4834 break;
4835 case LoadCopy:
4836 case Copy:
4837 case Arithmetic:
4838 case Xchg:
4839 SubExprs.push_back(APIOrderedArgs[2]); // Order
4840 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4841 break;
4842 case GNUXchg:
4843 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4844 SubExprs.push_back(APIOrderedArgs[3]); // Order
4845 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4846 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4847 break;
4848 case C11CmpXchg:
4849 SubExprs.push_back(APIOrderedArgs[3]); // Order
4850 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4851 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4852 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4853 break;
4854 case GNUCmpXchg:
4855 SubExprs.push_back(APIOrderedArgs[4]); // Order
4856 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4857 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4858 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4859 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4860 break;
4861 }
4862
4863 // If the memory orders are constants, check they are valid.
4864 if (SubExprs.size() >= 2 && Form != Init) {
4865 std::optional<llvm::APSInt> Success =
4866 SubExprs[1]->getIntegerConstantExpr(Context);
4867 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4868 Diag(SubExprs[1]->getBeginLoc(),
4869 diag::warn_atomic_op_has_invalid_memory_order)
4870 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4871 << SubExprs[1]->getSourceRange();
4872 }
4873 if (SubExprs.size() >= 5) {
4874 if (std::optional<llvm::APSInt> Failure =
4875 SubExprs[3]->getIntegerConstantExpr(Context)) {
4876 if (!llvm::is_contained(
4877 {llvm::AtomicOrderingCABI::relaxed,
4878 llvm::AtomicOrderingCABI::consume,
4879 llvm::AtomicOrderingCABI::acquire,
4880 llvm::AtomicOrderingCABI::seq_cst},
4881 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4882 Diag(SubExprs[3]->getBeginLoc(),
4883 diag::warn_atomic_op_has_invalid_memory_order)
4884 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4885 }
4886 }
4887 }
4888 }
4889
4890 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4891 auto *Scope = Args[Args.size() - 1];
4892 if (std::optional<llvm::APSInt> Result =
4893 Scope->getIntegerConstantExpr(Context)) {
4894 if (!ScopeModel->isValid(Result->getZExtValue()))
4895 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4896 << Scope->getSourceRange();
4897 }
4898 SubExprs.push_back(Scope);
4899 }
4900
4901 AtomicExpr *AE = new (Context)
4902 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4903
4904 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4905 Op == AtomicExpr::AO__c11_atomic_store ||
4906 Op == AtomicExpr::AO__opencl_atomic_load ||
4907 Op == AtomicExpr::AO__hip_atomic_load ||
4908 Op == AtomicExpr::AO__opencl_atomic_store ||
4909 Op == AtomicExpr::AO__hip_atomic_store) &&
4910 Context.AtomicUsesUnsupportedLibcall(AE))
4911 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4912 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4913 Op == AtomicExpr::AO__opencl_atomic_load ||
4914 Op == AtomicExpr::AO__hip_atomic_load)
4915 ? 0
4916 : 1);
4917
4918 if (ValType->isBitIntType()) {
4919 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4920 return ExprError();
4921 }
4922
4923 return AE;
4924}
4925
4926/// checkBuiltinArgument - Given a call to a builtin function, perform
4927/// normal type-checking on the given argument, updating the call in
4928/// place. This is useful when a builtin function requires custom
4929/// type-checking for some of its arguments but not necessarily all of
4930/// them.
4931///
4932/// Returns true on error.
4933static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4934 FunctionDecl *Fn = E->getDirectCallee();
4935 assert(Fn && "builtin call without direct callee!");
4936
4937 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4938 InitializedEntity Entity =
4940
4941 ExprResult Arg = E->getArg(ArgIndex);
4942 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4943 if (Arg.isInvalid())
4944 return true;
4945
4946 E->setArg(ArgIndex, Arg.get());
4947 return false;
4948}
4949
4950ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4951 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4952 Expr *Callee = TheCall->getCallee();
4953 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4954 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4955
4956 // Ensure that we have at least one argument to do type inference from.
4957 if (TheCall->getNumArgs() < 1) {
4958 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4959 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4960 << Callee->getSourceRange();
4961 return ExprError();
4962 }
4963
4964 // Inspect the first argument of the atomic builtin. This should always be
4965 // a pointer type, whose element is an integral scalar or pointer type.
4966 // Because it is a pointer type, we don't have to worry about any implicit
4967 // casts here.
4968 // FIXME: We don't allow floating point scalars as input.
4969 Expr *FirstArg = TheCall->getArg(0);
4970 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4971 if (FirstArgResult.isInvalid())
4972 return ExprError();
4973 FirstArg = FirstArgResult.get();
4974 TheCall->setArg(0, FirstArg);
4975
4976 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4977 if (!pointerType) {
4978 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4979 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4980 return ExprError();
4981 }
4982
4983 QualType ValType = pointerType->getPointeeType();
4984 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4985 !ValType->isBlockPointerType()) {
4986 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4987 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4988 return ExprError();
4989 }
4990 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4991 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4992 Diag(FirstArg->getBeginLoc(),
4993 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4994 << 1 << ValType << FirstArg->getSourceRange();
4995 return ExprError();
4996 }
4997
4998 if (ValType.isConstQualified()) {
4999 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5000 << FirstArg->getType() << FirstArg->getSourceRange();
5001 return ExprError();
5002 }
5003
5004 switch (ValType.getObjCLifetime()) {
5007 // okay
5008 break;
5009
5013 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5014 << ValType << FirstArg->getSourceRange();
5015 return ExprError();
5016 }
5017
5018 // Strip any qualifiers off ValType.
5019 ValType = ValType.getUnqualifiedType();
5020
5021 // The majority of builtins return a value, but a few have special return
5022 // types, so allow them to override appropriately below.
5023 QualType ResultType = ValType;
5024
5025 // We need to figure out which concrete builtin this maps onto. For example,
5026 // __sync_fetch_and_add with a 2 byte object turns into
5027 // __sync_fetch_and_add_2.
5028#define BUILTIN_ROW(x) \
5029 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5030 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5031
5032 static const unsigned BuiltinIndices[][5] = {
5033 BUILTIN_ROW(__sync_fetch_and_add),
5034 BUILTIN_ROW(__sync_fetch_and_sub),
5035 BUILTIN_ROW(__sync_fetch_and_or),
5036 BUILTIN_ROW(__sync_fetch_and_and),
5037 BUILTIN_ROW(__sync_fetch_and_xor),
5038 BUILTIN_ROW(__sync_fetch_and_nand),
5039
5040 BUILTIN_ROW(__sync_add_and_fetch),
5041 BUILTIN_ROW(__sync_sub_and_fetch),
5042 BUILTIN_ROW(__sync_and_and_fetch),
5043 BUILTIN_ROW(__sync_or_and_fetch),
5044 BUILTIN_ROW(__sync_xor_and_fetch),
5045 BUILTIN_ROW(__sync_nand_and_fetch),
5046
5047 BUILTIN_ROW(__sync_val_compare_and_swap),
5048 BUILTIN_ROW(__sync_bool_compare_and_swap),
5049 BUILTIN_ROW(__sync_lock_test_and_set),
5050 BUILTIN_ROW(__sync_lock_release),
5051 BUILTIN_ROW(__sync_swap)
5052 };
5053#undef BUILTIN_ROW
5054
5055 // Determine the index of the size.
5056 unsigned SizeIndex;
5057 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5058 case 1: SizeIndex = 0; break;
5059 case 2: SizeIndex = 1; break;
5060 case 4: SizeIndex = 2; break;
5061 case 8: SizeIndex = 3; break;
5062 case 16: SizeIndex = 4; break;
5063 default:
5064 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5065 << FirstArg->getType() << FirstArg->getSourceRange();
5066 return ExprError();
5067 }
5068
5069 // Each of these builtins has one pointer argument, followed by some number of
5070 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5071 // that we ignore. Find out which row of BuiltinIndices to read from as well
5072 // as the number of fixed args.
5073 unsigned BuiltinID = FDecl->getBuiltinID();
5074 unsigned BuiltinIndex, NumFixed = 1;
5075 bool WarnAboutSemanticsChange = false;
5076 switch (BuiltinID) {
5077 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5078 case Builtin::BI__sync_fetch_and_add:
5079 case Builtin::BI__sync_fetch_and_add_1:
5080 case Builtin::BI__sync_fetch_and_add_2:
5081 case Builtin::BI__sync_fetch_and_add_4:
5082 case Builtin::BI__sync_fetch_and_add_8:
5083 case Builtin::BI__sync_fetch_and_add_16:
5084 BuiltinIndex = 0;
5085 break;
5086
5087 case Builtin::BI__sync_fetch_and_sub:
5088 case Builtin::BI__sync_fetch_and_sub_1:
5089 case Builtin::BI__sync_fetch_and_sub_2:
5090 case Builtin::BI__sync_fetch_and_sub_4:
5091 case Builtin::BI__sync_fetch_and_sub_8:
5092 case Builtin::BI__sync_fetch_and_sub_16:
5093 BuiltinIndex = 1;
5094 break;
5095
5096 case Builtin::BI__sync_fetch_and_or:
5097 case Builtin::BI__sync_fetch_and_or_1:
5098 case Builtin::BI__sync_fetch_and_or_2:
5099 case Builtin::BI__sync_fetch_and_or_4:
5100 case Builtin::BI__sync_fetch_and_or_8:
5101 case Builtin::BI__sync_fetch_and_or_16:
5102 BuiltinIndex = 2;
5103 break;
5104
5105 case Builtin::BI__sync_fetch_and_and:
5106 case Builtin::BI__sync_fetch_and_and_1:
5107 case Builtin::BI__sync_fetch_and_and_2:
5108 case Builtin::BI__sync_fetch_and_and_4:
5109 case Builtin::BI__sync_fetch_and_and_8:
5110 case Builtin::BI__sync_fetch_and_and_16:
5111 BuiltinIndex = 3;
5112 break;
5113
5114 case Builtin::BI__sync_fetch_and_xor:
5115 case Builtin::BI__sync_fetch_and_xor_1:
5116 case Builtin::BI__sync_fetch_and_xor_2:
5117 case Builtin::BI__sync_fetch_and_xor_4:
5118 case Builtin::BI__sync_fetch_and_xor_8:
5119 case Builtin::BI__sync_fetch_and_xor_16:
5120 BuiltinIndex = 4;
5121 break;
5122
5123 case Builtin::BI__sync_fetch_and_nand:
5124 case Builtin::BI__sync_fetch_and_nand_1:
5125 case Builtin::BI__sync_fetch_and_nand_2:
5126 case Builtin::BI__sync_fetch_and_nand_4:
5127 case Builtin::BI__sync_fetch_and_nand_8:
5128 case Builtin::BI__sync_fetch_and_nand_16:
5129 BuiltinIndex = 5;
5130 WarnAboutSemanticsChange = true;
5131 break;
5132
5133 case Builtin::BI__sync_add_and_fetch:
5134 case Builtin::BI__sync_add_and_fetch_1:
5135 case Builtin::BI__sync_add_and_fetch_2:
5136 case Builtin::BI__sync_add_and_fetch_4:
5137 case Builtin::BI__sync_add_and_fetch_8:
5138 case Builtin::BI__sync_add_and_fetch_16:
5139 BuiltinIndex = 6;
5140 break;
5141
5142 case Builtin::BI__sync_sub_and_fetch:
5143 case Builtin::BI__sync_sub_and_fetch_1:
5144 case Builtin::BI__sync_sub_and_fetch_2:
5145 case Builtin::BI__sync_sub_and_fetch_4:
5146 case Builtin::BI__sync_sub_and_fetch_8:
5147 case Builtin::BI__sync_sub_and_fetch_16:
5148 BuiltinIndex = 7;
5149 break;
5150
5151 case Builtin::BI__sync_and_and_fetch:
5152 case Builtin::BI__sync_and_and_fetch_1:
5153 case Builtin::BI__sync_and_and_fetch_2:
5154 case Builtin::BI__sync_and_and_fetch_4:
5155 case Builtin::BI__sync_and_and_fetch_8:
5156 case Builtin::BI__sync_and_and_fetch_16:
5157 BuiltinIndex = 8;
5158 break;
5159
5160 case Builtin::BI__sync_or_and_fetch:
5161 case Builtin::BI__sync_or_and_fetch_1:
5162 case Builtin::BI__sync_or_and_fetch_2:
5163 case Builtin::BI__sync_or_and_fetch_4:
5164 case Builtin::BI__sync_or_and_fetch_8:
5165 case Builtin::BI__sync_or_and_fetch_16:
5166 BuiltinIndex = 9;
5167 break;
5168
5169 case Builtin::BI__sync_xor_and_fetch:
5170 case Builtin::BI__sync_xor_and_fetch_1:
5171 case Builtin::BI__sync_xor_and_fetch_2:
5172 case Builtin::BI__sync_xor_and_fetch_4:
5173 case Builtin::BI__sync_xor_and_fetch_8:
5174 case Builtin::BI__sync_xor_and_fetch_16:
5175 BuiltinIndex = 10;
5176 break;
5177
5178 case Builtin::BI__sync_nand_and_fetch:
5179 case Builtin::BI__sync_nand_and_fetch_1:
5180 case Builtin::BI__sync_nand_and_fetch_2:
5181 case Builtin::BI__sync_nand_and_fetch_4:
5182 case Builtin::BI__sync_nand_and_fetch_8:
5183 case Builtin::BI__sync_nand_and_fetch_16:
5184 BuiltinIndex = 11;
5185 WarnAboutSemanticsChange = true;
5186 break;
5187
5188 case Builtin::BI__sync_val_compare_and_swap:
5189 case Builtin::BI__sync_val_compare_and_swap_1:
5190 case Builtin::BI__sync_val_compare_and_swap_2:
5191 case Builtin::BI__sync_val_compare_and_swap_4:
5192 case Builtin::BI__sync_val_compare_and_swap_8:
5193 case Builtin::BI__sync_val_compare_and_swap_16:
5194 BuiltinIndex = 12;
5195 NumFixed = 2;
5196 break;
5197
5198 case Builtin::BI__sync_bool_compare_and_swap:
5199 case Builtin::BI__sync_bool_compare_and_swap_1:
5200 case Builtin::BI__sync_bool_compare_and_swap_2:
5201 case Builtin::BI__sync_bool_compare_and_swap_4:
5202 case Builtin::BI__sync_bool_compare_and_swap_8:
5203 case Builtin::BI__sync_bool_compare_and_swap_16:
5204 BuiltinIndex = 13;
5205 NumFixed = 2;
5206 ResultType = Context.BoolTy;
5207 break;
5208
5209 case Builtin::BI__sync_lock_test_and_set:
5210 case Builtin::BI__sync_lock_test_and_set_1:
5211 case Builtin::BI__sync_lock_test_and_set_2:
5212 case Builtin::BI__sync_lock_test_and_set_4:
5213 case Builtin::BI__sync_lock_test_and_set_8:
5214 case Builtin::BI__sync_lock_test_and_set_16:
5215 BuiltinIndex = 14;
5216 break;
5217
5218 case Builtin::BI__sync_lock_release:
5219 case Builtin::BI__sync_lock_release_1:
5220 case Builtin::BI__sync_lock_release_2:
5221 case Builtin::BI__sync_lock_release_4:
5222 case Builtin::BI__sync_lock_release_8:
5223 case Builtin::BI__sync_lock_release_16:
5224 BuiltinIndex = 15;
5225 NumFixed = 0;
5226 ResultType = Context.VoidTy;
5227 break;
5228
5229 case Builtin::BI__sync_swap:
5230 case Builtin::BI__sync_swap_1:
5231 case Builtin::BI__sync_swap_2:
5232 case Builtin::BI__sync_swap_4:
5233 case Builtin::BI__sync_swap_8:
5234 case Builtin::BI__sync_swap_16:
5235 BuiltinIndex = 16;
5236 break;
5237 }
5238
5239 // Now that we know how many fixed arguments we expect, first check that we
5240 // have at least that many.
5241 if (TheCall->getNumArgs() < 1+NumFixed) {
5242 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5243 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5244 << Callee->getSourceRange();
5245 return ExprError();
5246 }
5247
5248 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5249 << Callee->getSourceRange();
5250
5251 if (WarnAboutSemanticsChange) {
5252 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5253 << Callee->getSourceRange();
5254 }
5255
5256 // Get the decl for the concrete builtin from this, we can tell what the
5257 // concrete integer type we should convert to is.
5258 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5259 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5260 FunctionDecl *NewBuiltinDecl;
5261 if (NewBuiltinID == BuiltinID)
5262 NewBuiltinDecl = FDecl;
5263 else {
5264 // Perform builtin lookup to avoid redeclaring it.
5265 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5266 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5267 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5268 assert(Res.getFoundDecl());
5269 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5270 if (!NewBuiltinDecl)
5271 return ExprError();
5272 }
5273
5274 // The first argument --- the pointer --- has a fixed type; we
5275 // deduce the types of the rest of the arguments accordingly. Walk
5276 // the remaining arguments, converting them to the deduced value type.
5277 for (unsigned i = 0; i != NumFixed; ++i) {
5278 ExprResult Arg = TheCall->getArg(i+1);
5279
5280 // GCC does an implicit conversion to the pointer or integer ValType. This
5281 // can fail in some cases (1i -> int**), check for this error case now.
5282 // Initialize the argument.
5283 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5284 ValType, /*consume*/ false);
5285 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5286 if (Arg.isInvalid())
5287 return ExprError();
5288
5289 // Okay, we have something that *can* be converted to the right type. Check
5290 // to see if there is a potentially weird extension going on here. This can
5291 // happen when you do an atomic operation on something like an char* and
5292 // pass in 42. The 42 gets converted to char. This is even more strange
5293 // for things like 45.123 -> char, etc.
5294 // FIXME: Do this check.
5295 TheCall->setArg(i+1, Arg.get());
5296 }
5297
5298 // Create a new DeclRefExpr to refer to the new decl.
5299 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5300 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5301 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5302 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5303
5304 // Set the callee in the CallExpr.
5305 // FIXME: This loses syntactic information.
5306 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5307 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5308 CK_BuiltinFnToFnPtr);
5309 TheCall->setCallee(PromotedCall.get());
5310
5311 // Change the result type of the call to match the original value type. This
5312 // is arbitrary, but the codegen for these builtins ins design to handle it
5313 // gracefully.
5314 TheCall->setType(ResultType);
5315
5316 // Prohibit problematic uses of bit-precise integer types with atomic
5317 // builtins. The arguments would have already been converted to the first
5318 // argument's type, so only need to check the first argument.
5319 const auto *BitIntValType = ValType->getAs<BitIntType>();
5320 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5321 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5322 return ExprError();
5323 }
5324
5325 return TheCallResult;
5326}
5327
5328ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5329 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5330 DeclRefExpr *DRE =
5332 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5333 unsigned BuiltinID = FDecl->getBuiltinID();
5334 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5335 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5336 "Unexpected nontemporal load/store builtin!");
5337 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5338 unsigned numArgs = isStore ? 2 : 1;
5339
5340 // Ensure that we have the proper number of arguments.
5341 if (checkArgCount(TheCall, numArgs))
5342 return ExprError();
5343
5344 // Inspect the last argument of the nontemporal builtin. This should always
5345 // be a pointer type, from which we imply the type of the memory access.
5346 // Because it is a pointer type, we don't have to worry about any implicit
5347 // casts here.
5348 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5349 ExprResult PointerArgResult =
5351
5352 if (PointerArgResult.isInvalid())
5353 return ExprError();
5354 PointerArg = PointerArgResult.get();
5355 TheCall->setArg(numArgs - 1, PointerArg);
5356
5357 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5358 if (!pointerType) {
5359 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5360 << PointerArg->getType() << PointerArg->getSourceRange();
5361 return ExprError();
5362 }
5363
5364 QualType ValType = pointerType->getPointeeType();
5365
5366 // Strip any qualifiers off ValType.
5367 ValType = ValType.getUnqualifiedType();
5368 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5369 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5370 !ValType->isVectorType()) {
5371 Diag(DRE->getBeginLoc(),
5372 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5373 << PointerArg->getType() << PointerArg->getSourceRange();
5374 return ExprError();
5375 }
5376
5377 if (!isStore) {
5378 TheCall->setType(ValType);
5379 return TheCallResult;
5380 }
5381
5382 ExprResult ValArg = TheCall->getArg(0);
5383 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5384 Context, ValType, /*consume*/ false);
5385 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5386 if (ValArg.isInvalid())
5387 return ExprError();
5388
5389 TheCall->setArg(0, ValArg.get());
5390 TheCall->setType(Context.VoidTy);
5391 return TheCallResult;
5392}
5393
5394/// CheckObjCString - Checks that the format string argument to the os_log()
5395/// and os_trace() functions is correct, and converts it to const char *.
5396ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5397 Arg = Arg->IgnoreParenCasts();
5398 auto *Literal = dyn_cast<StringLiteral>(Arg);
5399 if (!Literal) {
5400 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5401 Literal = ObjcLiteral->getString();
5402 }
5403 }
5404
5405 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5406 return ExprError(
5407 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5408 << Arg->getSourceRange());
5409 }
5410
5411 ExprResult Result(Literal);
5412 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5413 InitializedEntity Entity =
5415 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5416 return Result;
5417}
5418
5419/// Check that the user is calling the appropriate va_start builtin for the
5420/// target and calling convention.
5421static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5422 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5423 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5424 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5425 TT.getArch() == llvm::Triple::aarch64_32);
5426 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5427 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5428 if (IsX64 || IsAArch64) {
5429 CallingConv CC = CC_C;
5430 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5431 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5432 if (IsMSVAStart) {
5433 // Don't allow this in System V ABI functions.
5434 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5435 return S.Diag(Fn->getBeginLoc(),
5436 diag::err_ms_va_start_used_in_sysv_function);
5437 } else {
5438 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5439 // On x64 Windows, don't allow this in System V ABI functions.
5440 // (Yes, that means there's no corresponding way to support variadic
5441 // System V ABI functions on Windows.)
5442 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5443 (!IsWindowsOrUEFI && CC == CC_Win64))
5444 return S.Diag(Fn->getBeginLoc(),
5445 diag::err_va_start_used_in_wrong_abi_function)
5446 << !IsWindowsOrUEFI;
5447 }
5448 return false;
5449 }
5450
5451 if (IsMSVAStart)
5452 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5453 return false;
5454}
5455
5457 ParmVarDecl **LastParam = nullptr) {
5458 // Determine whether the current function, block, or obj-c method is variadic
5459 // and get its parameter list.
5460 bool IsVariadic = false;
5462 DeclContext *Caller = S.CurContext;
5463 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5464 IsVariadic = Block->isVariadic();
5465 Params = Block->parameters();
5466 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5467 IsVariadic = FD->isVariadic();
5468 Params = FD->parameters();
5469 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5470 IsVariadic = MD->isVariadic();
5471 // FIXME: This isn't correct for methods (results in bogus warning).
5472 Params = MD->parameters();
5473 } else if (isa<CapturedDecl>(Caller)) {
5474 // We don't support va_start in a CapturedDecl.
5475 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5476 return true;
5477 } else {
5478 // This must be some other declcontext that parses exprs.
5479 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5480 return true;
5481 }
5482
5483 if (!IsVariadic) {
5484 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5485 return true;
5486 }
5487
5488 if (LastParam)
5489 *LastParam = Params.empty() ? nullptr : Params.back();
5490
5491 return false;
5492}
5493
5494bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5495 Expr *Fn = TheCall->getCallee();
5496 if (checkVAStartABI(*this, BuiltinID, Fn))
5497 return true;
5498
5499 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5500 // This builtin requires one argument (the va_list), allows two arguments,
5501 // but diagnoses more than two arguments. e.g.,
5502 // __builtin_c23_va_start(); // error
5503 // __builtin_c23_va_start(list); // ok
5504 // __builtin_c23_va_start(list, param); // ok
5505 // __builtin_c23_va_start(list, anything, anything); // error
5506 // This differs from the GCC behavior in that they accept the last case
5507 // with a warning, but it doesn't seem like a useful behavior to allow.
5508 if (checkArgCountRange(TheCall, 1, 2))
5509 return true;
5510 } else {
5511 // In C23 mode, va_start only needs one argument. However, the builtin still
5512 // requires two arguments (which matches the behavior of the GCC builtin),
5513 // <stdarg.h> passes `0` as the second argument in C23 mode.
5514 if (checkArgCount(TheCall, 2))
5515 return true;
5516 }
5517
5518 // Type-check the first argument normally.
5519 if (checkBuiltinArgument(*this, TheCall, 0))
5520 return true;
5521
5522 // Check that the current function is variadic, and get its last parameter.
5523 ParmVarDecl *LastParam;
5524 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5525 return true;
5526
5527 // Verify that the second argument to the builtin is the last non-variadic
5528 // argument of the current function or method. In C23 mode, if the call is
5529 // not to __builtin_c23_va_start, and the second argument is an integer
5530 // constant expression with value 0, then we don't bother with this check.
5531 // For __builtin_c23_va_start, we only perform the check for the second
5532 // argument being the last argument to the current function if there is a
5533 // second argument present.
5534 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5535 TheCall->getNumArgs() < 2) {
5536 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5537 return false;
5538 }
5539
5540 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5541 if (std::optional<llvm::APSInt> Val =
5543 Val && LangOpts.C23 && *Val == 0 &&
5544 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5545 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5546 return false;
5547 }
5548
5549 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5550 // next block.
5551 QualType Type;
5552 SourceLocation ParamLoc;
5553 bool IsCRegister = false;
5554 bool SecondArgIsLastNonVariadicArgument = false;
5555 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5556 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5557 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5558
5559 Type = PV->getType();
5560 ParamLoc = PV->getLocation();
5561 IsCRegister =
5562 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5563 }
5564 }
5565
5566 if (!SecondArgIsLastNonVariadicArgument)
5567 Diag(TheCall->getArg(1)->getBeginLoc(),
5568 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5569 else if (IsCRegister || Type->isReferenceType() ||
5570 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5571 // Promotable integers are UB, but enumerations need a bit of
5572 // extra checking to see what their promotable type actually is.
5573 if (!Context.isPromotableIntegerType(Type))
5574 return false;
5575 const auto *ED = Type->getAsEnumDecl();
5576 if (!ED)
5577 return true;
5578 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5579 }()) {
5580 unsigned Reason = 0;
5581 if (Type->isReferenceType()) Reason = 1;
5582 else if (IsCRegister) Reason = 2;
5583 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5584 Diag(ParamLoc, diag::note_parameter_type) << Type;
5585 }
5586
5587 return false;
5588}
5589
5590bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5591 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5592 const LangOptions &LO = getLangOpts();
5593
5594 if (LO.CPlusPlus)
5595 return Arg->getType()
5597 .getTypePtr()
5598 ->getPointeeType()
5600
5601 // In C, allow aliasing through `char *`, this is required for AArch64 at
5602 // least.
5603 return true;
5604 };
5605
5606 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5607 // const char *named_addr);
5608
5609 Expr *Func = Call->getCallee();
5610
5611 if (Call->getNumArgs() < 3)
5612 return Diag(Call->getEndLoc(),
5613 diag::err_typecheck_call_too_few_args_at_least)
5614 << 0 /*function call*/ << 3 << Call->getNumArgs()
5615 << /*is non object*/ 0;
5616
5617 // Type-check the first argument normally.
5618 if (checkBuiltinArgument(*this, Call, 0))
5619 return true;
5620
5621 // Check that the current function is variadic.
5623 return true;
5624
5625 // __va_start on Windows does not validate the parameter qualifiers
5626
5627 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5628 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5629
5630 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5631 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5632
5633 const QualType &ConstCharPtrTy =
5634 Context.getPointerType(Context.CharTy.withConst());
5635 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5636 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5637 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5638 << 0 /* qualifier difference */
5639 << 3 /* parameter mismatch */
5640 << 2 << Arg1->getType() << ConstCharPtrTy;
5641
5642 const QualType SizeTy = Context.getSizeType();
5643 if (!Context.hasSameType(
5645 SizeTy))
5646 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5647 << Arg2->getType() << SizeTy << 1 /* different class */
5648 << 0 /* qualifier difference */
5649 << 3 /* parameter mismatch */
5650 << 3 << Arg2->getType() << SizeTy;
5651
5652 return false;
5653}
5654
5655bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5656 if (checkArgCount(TheCall, 2))
5657 return true;
5658
5659 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5660 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5661 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5662 << 1 << 0 << TheCall->getSourceRange();
5663
5664 ExprResult OrigArg0 = TheCall->getArg(0);
5665 ExprResult OrigArg1 = TheCall->getArg(1);
5666
5667 // Do standard promotions between the two arguments, returning their common
5668 // type.
5669 QualType Res = UsualArithmeticConversions(
5670 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5671 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5672 return true;
5673
5674 // Make sure any conversions are pushed back into the call; this is
5675 // type safe since unordered compare builtins are declared as "_Bool
5676 // foo(...)".
5677 TheCall->setArg(0, OrigArg0.get());
5678 TheCall->setArg(1, OrigArg1.get());
5679
5680 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5681 return false;
5682
5683 // If the common type isn't a real floating type, then the arguments were
5684 // invalid for this operation.
5685 if (Res.isNull() || !Res->isRealFloatingType())
5686 return Diag(OrigArg0.get()->getBeginLoc(),
5687 diag::err_typecheck_call_invalid_ordered_compare)
5688 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5689 << SourceRange(OrigArg0.get()->getBeginLoc(),
5690 OrigArg1.get()->getEndLoc());
5691
5692 return false;
5693}
5694
5695bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5696 unsigned BuiltinID) {
5697 if (checkArgCount(TheCall, NumArgs))
5698 return true;
5699
5700 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5701 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5702 BuiltinID == Builtin::BI__builtin_isinf ||
5703 BuiltinID == Builtin::BI__builtin_isinf_sign))
5704 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5705 << 0 << 0 << TheCall->getSourceRange();
5706
5707 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5708 BuiltinID == Builtin::BI__builtin_isunordered))
5709 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5710 << 1 << 0 << TheCall->getSourceRange();
5711
5712 bool IsFPClass = NumArgs == 2;
5713
5714 // Find out position of floating-point argument.
5715 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5716
5717 // We can count on all parameters preceding the floating-point just being int.
5718 // Try all of those.
5719 for (unsigned i = 0; i < FPArgNo; ++i) {
5720 Expr *Arg = TheCall->getArg(i);
5721
5722 if (Arg->isTypeDependent())
5723 return false;
5724
5727
5728 if (Res.isInvalid())
5729 return true;
5730 TheCall->setArg(i, Res.get());
5731 }
5732
5733 Expr *OrigArg = TheCall->getArg(FPArgNo);
5734
5735 if (OrigArg->isTypeDependent())
5736 return false;
5737
5738 // Usual Unary Conversions will convert half to float, which we want for
5739 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5740 // type how it is, but do normal L->Rvalue conversions.
5741 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5742 ExprResult Res = UsualUnaryConversions(OrigArg);
5743
5744 if (!Res.isUsable())
5745 return true;
5746 OrigArg = Res.get();
5747 } else {
5749
5750 if (!Res.isUsable())
5751 return true;
5752 OrigArg = Res.get();
5753 }
5754 TheCall->setArg(FPArgNo, OrigArg);
5755
5756 QualType VectorResultTy;
5757 QualType ElementTy = OrigArg->getType();
5758 // TODO: When all classification function are implemented with is_fpclass,
5759 // vector argument can be supported in all of them.
5760 if (ElementTy->isVectorType() && IsFPClass) {
5761 VectorResultTy = GetSignedVectorType(ElementTy);
5762 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5763 }
5764
5765 // This operation requires a non-_Complex floating-point number.
5766 if (!ElementTy->isRealFloatingType())
5767 return Diag(OrigArg->getBeginLoc(),
5768 diag::err_typecheck_call_invalid_unary_fp)
5769 << OrigArg->getType() << OrigArg->getSourceRange();
5770
5771 // __builtin_isfpclass has integer parameter that specify test mask. It is
5772 // passed in (...), so it should be analyzed completely here.
5773 if (IsFPClass)
5774 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5775 return true;
5776
5777 // TODO: enable this code to all classification functions.
5778 if (IsFPClass) {
5779 QualType ResultTy;
5780 if (!VectorResultTy.isNull())
5781 ResultTy = VectorResultTy;
5782 else
5783 ResultTy = Context.IntTy;
5784 TheCall->setType(ResultTy);
5785 }
5786
5787 return false;
5788}
5789
5790bool Sema::BuiltinComplex(CallExpr *TheCall) {
5791 if (checkArgCount(TheCall, 2))
5792 return true;
5793
5794 bool Dependent = false;
5795 for (unsigned I = 0; I != 2; ++I) {
5796 Expr *Arg = TheCall->getArg(I);
5797 QualType T = Arg->getType();
5798 if (T->isDependentType()) {
5799 Dependent = true;
5800 continue;
5801 }
5802
5803 // Despite supporting _Complex int, GCC requires a real floating point type
5804 // for the operands of __builtin_complex.
5805 if (!T->isRealFloatingType()) {
5806 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5807 << Arg->getType() << Arg->getSourceRange();
5808 }
5809
5810 ExprResult Converted = DefaultLvalueConversion(Arg);
5811 if (Converted.isInvalid())
5812 return true;
5813 TheCall->setArg(I, Converted.get());
5814 }
5815
5816 if (Dependent) {
5817 TheCall->setType(Context.DependentTy);
5818 return false;
5819 }
5820
5821 Expr *Real = TheCall->getArg(0);
5822 Expr *Imag = TheCall->getArg(1);
5823 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5824 return Diag(Real->getBeginLoc(),
5825 diag::err_typecheck_call_different_arg_types)
5826 << Real->getType() << Imag->getType()
5827 << Real->getSourceRange() << Imag->getSourceRange();
5828 }
5829
5830 TheCall->setType(Context.getComplexType(Real->getType()));
5831 return false;
5832}
5833
5834/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5835// This is declared to take (...), so we have to check everything.
5837 unsigned NumArgs = TheCall->getNumArgs();
5838 if (NumArgs < 2)
5839 return ExprError(Diag(TheCall->getEndLoc(),
5840 diag::err_typecheck_call_too_few_args_at_least)
5841 << 0 /*function call*/ << 2 << NumArgs
5842 << /*is non object*/ 0 << TheCall->getSourceRange());
5843
5844 // Determine which of the following types of shufflevector we're checking:
5845 // 1) unary, vector mask: (lhs, mask)
5846 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5847 QualType ResType = TheCall->getArg(0)->getType();
5848 unsigned NumElements = 0;
5849
5850 if (!TheCall->getArg(0)->isTypeDependent() &&
5851 !TheCall->getArg(1)->isTypeDependent()) {
5852 QualType LHSType = TheCall->getArg(0)->getType();
5853 QualType RHSType = TheCall->getArg(1)->getType();
5854
5855 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5856 return ExprError(
5857 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5858 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5859 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5860 TheCall->getArg(1)->getEndLoc()));
5861
5862 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5863 unsigned NumResElements = NumArgs - 2;
5864
5865 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5866 // with mask. If so, verify that RHS is an integer vector type with the
5867 // same number of elts as lhs.
5868 if (NumArgs == 2) {
5869 if (!RHSType->hasIntegerRepresentation() ||
5870 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5871 return ExprError(Diag(TheCall->getBeginLoc(),
5872 diag::err_vec_builtin_incompatible_vector)
5873 << TheCall->getDirectCallee()
5874 << /*isMoreThanTwoArgs*/ false
5875 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5876 TheCall->getArg(1)->getEndLoc()));
5877 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5878 return ExprError(Diag(TheCall->getBeginLoc(),
5879 diag::err_vec_builtin_incompatible_vector)
5880 << TheCall->getDirectCallee()
5881 << /*isMoreThanTwoArgs*/ false
5882 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5883 TheCall->getArg(1)->getEndLoc()));
5884 } else if (NumElements != NumResElements) {
5885 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5886 ResType = ResType->isExtVectorType()
5887 ? Context.getExtVectorType(EltType, NumResElements)
5888 : Context.getVectorType(EltType, NumResElements,
5890 }
5891 }
5892
5893 for (unsigned I = 2; I != NumArgs; ++I) {
5894 Expr *Arg = TheCall->getArg(I);
5895 if (Arg->isTypeDependent() || Arg->isValueDependent())
5896 continue;
5897
5898 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5899 if (!Result)
5900 return ExprError(Diag(TheCall->getBeginLoc(),
5901 diag::err_shufflevector_nonconstant_argument)
5902 << Arg->getSourceRange());
5903
5904 // Allow -1 which will be translated to undef in the IR.
5905 if (Result->isSigned() && Result->isAllOnes())
5906 ;
5907 else if (Result->getActiveBits() > 64 ||
5908 Result->getZExtValue() >= NumElements * 2)
5909 return ExprError(Diag(TheCall->getBeginLoc(),
5910 diag::err_shufflevector_argument_too_large)
5911 << Arg->getSourceRange());
5912
5913 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5914 }
5915
5916 auto *Result = new (Context) ShuffleVectorExpr(
5917 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5918 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5919
5920 // All moved to Result.
5921 TheCall->shrinkNumArgs(0);
5922 return Result;
5923}
5924
5926 SourceLocation BuiltinLoc,
5927 SourceLocation RParenLoc) {
5930 QualType DstTy = TInfo->getType();
5931 QualType SrcTy = E->getType();
5932
5933 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5934 return ExprError(Diag(BuiltinLoc,
5935 diag::err_convertvector_non_vector)
5936 << E->getSourceRange());
5937 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5938 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5939 << "second"
5940 << "__builtin_convertvector");
5941
5942 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5943 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5944 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5945 if (SrcElts != DstElts)
5946 return ExprError(Diag(BuiltinLoc,
5947 diag::err_convertvector_incompatible_vector)
5948 << E->getSourceRange());
5949 }
5950
5951 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5952 RParenLoc, CurFPFeatureOverrides());
5953}
5954
5955bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5956 unsigned NumArgs = TheCall->getNumArgs();
5957
5958 if (NumArgs > 3)
5959 return Diag(TheCall->getEndLoc(),
5960 diag::err_typecheck_call_too_many_args_at_most)
5961 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5962 << TheCall->getSourceRange();
5963
5964 // Argument 0 is checked for us and the remaining arguments must be
5965 // constant integers.
5966 for (unsigned i = 1; i != NumArgs; ++i)
5967 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5968 return true;
5969
5970 return false;
5971}
5972
5973bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5974 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
5975 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5976 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5977 if (checkArgCount(TheCall, 1))
5978 return true;
5979 Expr *Arg = TheCall->getArg(0);
5980 if (Arg->isInstantiationDependent())
5981 return false;
5982
5983 QualType ArgTy = Arg->getType();
5984 if (!ArgTy->hasFloatingRepresentation())
5985 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5986 << ArgTy;
5987 if (Arg->isLValue()) {
5988 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5989 TheCall->setArg(0, FirstArg.get());
5990 }
5991 TheCall->setType(TheCall->getArg(0)->getType());
5992 return false;
5993}
5994
5995bool Sema::BuiltinAssume(CallExpr *TheCall) {
5996 Expr *Arg = TheCall->getArg(0);
5997 if (Arg->isInstantiationDependent()) return false;
5998
5999 if (Arg->HasSideEffects(Context))
6000 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6001 << Arg->getSourceRange()
6002 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6003
6004 return false;
6005}
6006
6007bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6008 // The alignment must be a constant integer.
6009 Expr *Arg = TheCall->getArg(1);
6010
6011 // We can't check the value of a dependent argument.
6012 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6013 if (const auto *UE =
6014 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6015 if (UE->getKind() == UETT_AlignOf ||
6016 UE->getKind() == UETT_PreferredAlignOf)
6017 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6018 << Arg->getSourceRange();
6019
6020 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6021
6022 if (!Result.isPowerOf2())
6023 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6024 << Arg->getSourceRange();
6025
6026 if (Result < Context.getCharWidth())
6027 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6028 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6029
6030 if (Result > std::numeric_limits<int32_t>::max())
6031 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6032 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6033 }
6034
6035 return false;
6036}
6037
6038bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6039 if (checkArgCountRange(TheCall, 2, 3))
6040 return true;
6041
6042 unsigned NumArgs = TheCall->getNumArgs();
6043 Expr *FirstArg = TheCall->getArg(0);
6044
6045 {
6046 ExprResult FirstArgResult =
6048 if (!FirstArgResult.get()->getType()->isPointerType()) {
6049 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6050 << TheCall->getSourceRange();
6051 return true;
6052 }
6053 TheCall->setArg(0, FirstArgResult.get());
6054 }
6055
6056 // The alignment must be a constant integer.
6057 Expr *SecondArg = TheCall->getArg(1);
6058
6059 // We can't check the value of a dependent argument.
6060 if (!SecondArg->isValueDependent()) {
6061 llvm::APSInt Result;
6062 if (BuiltinConstantArg(TheCall, 1, Result))
6063 return true;
6064
6065 if (!Result.isPowerOf2())
6066 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6067 << SecondArg->getSourceRange();
6068
6070 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6071 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6072
6073 TheCall->setArg(1,
6075 }
6076
6077 if (NumArgs > 2) {
6078 Expr *ThirdArg = TheCall->getArg(2);
6079 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6080 return true;
6081 TheCall->setArg(2, ThirdArg);
6082 }
6083
6084 return false;
6085}
6086
6087bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6088 unsigned BuiltinID =
6089 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6090 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6091
6092 unsigned NumArgs = TheCall->getNumArgs();
6093 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6094 if (NumArgs < NumRequiredArgs) {
6095 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6096 << 0 /* function call */ << NumRequiredArgs << NumArgs
6097 << /*is non object*/ 0 << TheCall->getSourceRange();
6098 }
6099 if (NumArgs >= NumRequiredArgs + 0x100) {
6100 return Diag(TheCall->getEndLoc(),
6101 diag::err_typecheck_call_too_many_args_at_most)
6102 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6103 << /*is non object*/ 0 << TheCall->getSourceRange();
6104 }
6105 unsigned i = 0;
6106
6107 // For formatting call, check buffer arg.
6108 if (!IsSizeCall) {
6109 ExprResult Arg(TheCall->getArg(i));
6110 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6111 Context, Context.VoidPtrTy, false);
6112 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6113 if (Arg.isInvalid())
6114 return true;
6115 TheCall->setArg(i, Arg.get());
6116 i++;
6117 }
6118
6119 // Check string literal arg.
6120 unsigned FormatIdx = i;
6121 {
6122 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6123 if (Arg.isInvalid())
6124 return true;
6125 TheCall->setArg(i, Arg.get());
6126 i++;
6127 }
6128
6129 // Make sure variadic args are scalar.
6130 unsigned FirstDataArg = i;
6131 while (i < NumArgs) {
6133 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6134 if (Arg.isInvalid())
6135 return true;
6136 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6137 if (ArgSize.getQuantity() >= 0x100) {
6138 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6139 << i << (int)ArgSize.getQuantity() << 0xff
6140 << TheCall->getSourceRange();
6141 }
6142 TheCall->setArg(i, Arg.get());
6143 i++;
6144 }
6145
6146 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6147 // call to avoid duplicate diagnostics.
6148 if (!IsSizeCall) {
6149 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6150 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6151 bool Success = CheckFormatArguments(
6152 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6154 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6155 if (!Success)
6156 return true;
6157 }
6158
6159 if (IsSizeCall) {
6160 TheCall->setType(Context.getSizeType());
6161 } else {
6162 TheCall->setType(Context.VoidPtrTy);
6163 }
6164 return false;
6165}
6166
6167bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6168 llvm::APSInt &Result) {
6169 Expr *Arg = TheCall->getArg(ArgNum);
6170
6171 if (Arg->isTypeDependent() || Arg->isValueDependent())
6172 return false;
6173
6174 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6175 if (!R) {
6176 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6177 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6178 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6179 << FDecl->getDeclName() << Arg->getSourceRange();
6180 }
6181 Result = *R;
6182
6183 return false;
6184}
6185
6186bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6187 int High, bool RangeIsError) {
6189 return false;
6190 llvm::APSInt Result;
6191
6192 // We can't check the value of a dependent argument.
6193 Expr *Arg = TheCall->getArg(ArgNum);
6194 if (Arg->isTypeDependent() || Arg->isValueDependent())
6195 return false;
6196
6197 // Check constant-ness first.
6198 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6199 return true;
6200
6201 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6202 if (RangeIsError)
6203 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6204 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6205 else
6206 // Defer the warning until we know if the code will be emitted so that
6207 // dead code can ignore this.
6208 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6209 PDiag(diag::warn_argument_invalid_range)
6210 << toString(Result, 10) << Low << High
6211 << Arg->getSourceRange());
6212 }
6213
6214 return false;
6215}
6216
6217bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6218 unsigned Num) {
6219 llvm::APSInt Result;
6220
6221 // We can't check the value of a dependent argument.
6222 Expr *Arg = TheCall->getArg(ArgNum);
6223 if (Arg->isTypeDependent() || Arg->isValueDependent())
6224 return false;
6225
6226 // Check constant-ness first.
6227 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6228 return true;
6229
6230 if (Result.getSExtValue() % Num != 0)
6231 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6232 << Num << Arg->getSourceRange();
6233
6234 return false;
6235}
6236
6237bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6238 llvm::APSInt Result;
6239
6240 // We can't check the value of a dependent argument.
6241 Expr *Arg = TheCall->getArg(ArgNum);
6242 if (Arg->isTypeDependent() || Arg->isValueDependent())
6243 return false;
6244
6245 // Check constant-ness first.
6246 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6247 return true;
6248
6249 if (Result.isPowerOf2())
6250 return false;
6251
6252 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6253 << Arg->getSourceRange();
6254}
6255
6256static bool IsShiftedByte(llvm::APSInt Value) {
6257 if (Value.isNegative())
6258 return false;
6259
6260 // Check if it's a shifted byte, by shifting it down
6261 while (true) {
6262 // If the value fits in the bottom byte, the check passes.
6263 if (Value < 0x100)
6264 return true;
6265
6266 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6267 // fails.
6268 if ((Value & 0xFF) != 0)
6269 return false;
6270
6271 // If the bottom 8 bits are all 0, but something above that is nonzero,
6272 // then shifting the value right by 8 bits won't affect whether it's a
6273 // shifted byte or not. So do that, and go round again.
6274 Value >>= 8;
6275 }
6276}
6277
6278bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6279 unsigned ArgBits) {
6280 llvm::APSInt Result;
6281
6282 // We can't check the value of a dependent argument.
6283 Expr *Arg = TheCall->getArg(ArgNum);
6284 if (Arg->isTypeDependent() || Arg->isValueDependent())
6285 return false;
6286
6287 // Check constant-ness first.
6288 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6289 return true;
6290
6291 // Truncate to the given size.
6292 Result = Result.getLoBits(ArgBits);
6293 Result.setIsUnsigned(true);
6294
6295 if (IsShiftedByte(Result))
6296 return false;
6297
6298 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6299 << Arg->getSourceRange();
6300}
6301
6303 unsigned ArgNum,
6304 unsigned ArgBits) {
6305 llvm::APSInt Result;
6306
6307 // We can't check the value of a dependent argument.
6308 Expr *Arg = TheCall->getArg(ArgNum);
6309 if (Arg->isTypeDependent() || Arg->isValueDependent())
6310 return false;
6311
6312 // Check constant-ness first.
6313 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6314 return true;
6315
6316 // Truncate to the given size.
6317 Result = Result.getLoBits(ArgBits);
6318 Result.setIsUnsigned(true);
6319
6320 // Check to see if it's in either of the required forms.
6321 if (IsShiftedByte(Result) ||
6322 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6323 return false;
6324
6325 return Diag(TheCall->getBeginLoc(),
6326 diag::err_argument_not_shifted_byte_or_xxff)
6327 << Arg->getSourceRange();
6328}
6329
6330bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6331 if (!Context.getTargetInfo().hasSjLjLowering())
6332 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6333 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6334
6335 Expr *Arg = TheCall->getArg(1);
6336 llvm::APSInt Result;
6337
6338 // TODO: This is less than ideal. Overload this to take a value.
6339 if (BuiltinConstantArg(TheCall, 1, Result))
6340 return true;
6341
6342 if (Result != 1)
6343 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6344 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6345
6346 return false;
6347}
6348
6349bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6350 if (!Context.getTargetInfo().hasSjLjLowering())
6351 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6352 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6353 return false;
6354}
6355
6356bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6357 if (checkArgCount(TheCall, 1))
6358 return true;
6359
6360 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6361 if (ArgRes.isInvalid())
6362 return true;
6363
6364 // For simplicity, we support only limited expressions for the argument.
6365 // Specifically a flexible array member or a pointer with counted_by:
6366 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6367 // complex casting, which really shouldn't be a huge problem.
6368 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6369 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6370 return Diag(Arg->getBeginLoc(),
6371 diag::err_builtin_counted_by_ref_invalid_arg)
6372 << Arg->getSourceRange();
6373
6374 if (Arg->HasSideEffects(Context))
6375 return Diag(Arg->getBeginLoc(),
6376 diag::err_builtin_counted_by_ref_has_side_effects)
6377 << Arg->getSourceRange();
6378
6379 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6380 const auto *CATy =
6381 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6382
6383 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6384 // Member has counted_by attribute - return pointer to count field
6385 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6386 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6387 TheCall->setType(Context.getPointerType(CountFD->getType()));
6388 return false;
6389 }
6390 }
6391
6392 // FAMs and pointers without counted_by return void*
6393 QualType MemberTy = ME->getMemberDecl()->getType();
6394 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6395 return Diag(Arg->getBeginLoc(),
6396 diag::err_builtin_counted_by_ref_invalid_arg)
6397 << Arg->getSourceRange();
6398 } else {
6399 return Diag(Arg->getBeginLoc(),
6400 diag::err_builtin_counted_by_ref_invalid_arg)
6401 << Arg->getSourceRange();
6402 }
6403
6404 TheCall->setType(Context.getPointerType(Context.VoidTy));
6405 return false;
6406}
6407
6408/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6409/// It allows leaking and modification of bounds safety information.
6410bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6412 const CallExpr *CE =
6413 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6414 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6415 return false;
6416
6417 switch (K) {
6420 Diag(E->getExprLoc(),
6421 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6422 << 0 << E->getSourceRange();
6423 break;
6425 Diag(E->getExprLoc(),
6426 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6427 << 1 << E->getSourceRange();
6428 break;
6430 Diag(E->getExprLoc(),
6431 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6432 << 2 << E->getSourceRange();
6433 break;
6435 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6436 << 0 << E->getSourceRange();
6437 break;
6439 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6440 << 1 << E->getSourceRange();
6441 break;
6442 }
6443
6444 return true;
6445}
6446
6447namespace {
6448
6449class UncoveredArgHandler {
6450 enum { Unknown = -1, AllCovered = -2 };
6451
6452 signed FirstUncoveredArg = Unknown;
6453 SmallVector<const Expr *, 4> DiagnosticExprs;
6454
6455public:
6456 UncoveredArgHandler() = default;
6457
6458 bool hasUncoveredArg() const {
6459 return (FirstUncoveredArg >= 0);
6460 }
6461
6462 unsigned getUncoveredArg() const {
6463 assert(hasUncoveredArg() && "no uncovered argument");
6464 return FirstUncoveredArg;
6465 }
6466
6467 void setAllCovered() {
6468 // A string has been found with all arguments covered, so clear out
6469 // the diagnostics.
6470 DiagnosticExprs.clear();
6471 FirstUncoveredArg = AllCovered;
6472 }
6473
6474 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6475 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6476
6477 // Don't update if a previous string covers all arguments.
6478 if (FirstUncoveredArg == AllCovered)
6479 return;
6480
6481 // UncoveredArgHandler tracks the highest uncovered argument index
6482 // and with it all the strings that match this index.
6483 if (NewFirstUncoveredArg == FirstUncoveredArg)
6484 DiagnosticExprs.push_back(StrExpr);
6485 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6486 DiagnosticExprs.clear();
6487 DiagnosticExprs.push_back(StrExpr);
6488 FirstUncoveredArg = NewFirstUncoveredArg;
6489 }
6490 }
6491
6492 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6493};
6494
6495enum StringLiteralCheckType {
6496 SLCT_NotALiteral,
6497 SLCT_UncheckedLiteral,
6498 SLCT_CheckedLiteral
6499};
6500
6501} // namespace
6502
6503static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6504 BinaryOperatorKind BinOpKind,
6505 bool AddendIsRight) {
6506 unsigned BitWidth = Offset.getBitWidth();
6507 unsigned AddendBitWidth = Addend.getBitWidth();
6508 // There might be negative interim results.
6509 if (Addend.isUnsigned()) {
6510 Addend = Addend.zext(++AddendBitWidth);
6511 Addend.setIsSigned(true);
6512 }
6513 // Adjust the bit width of the APSInts.
6514 if (AddendBitWidth > BitWidth) {
6515 Offset = Offset.sext(AddendBitWidth);
6516 BitWidth = AddendBitWidth;
6517 } else if (BitWidth > AddendBitWidth) {
6518 Addend = Addend.sext(BitWidth);
6519 }
6520
6521 bool Ov = false;
6522 llvm::APSInt ResOffset = Offset;
6523 if (BinOpKind == BO_Add)
6524 ResOffset = Offset.sadd_ov(Addend, Ov);
6525 else {
6526 assert(AddendIsRight && BinOpKind == BO_Sub &&
6527 "operator must be add or sub with addend on the right");
6528 ResOffset = Offset.ssub_ov(Addend, Ov);
6529 }
6530
6531 // We add an offset to a pointer here so we should support an offset as big as
6532 // possible.
6533 if (Ov) {
6534 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6535 "index (intermediate) result too big");
6536 Offset = Offset.sext(2 * BitWidth);
6537 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6538 return;
6539 }
6540
6541 Offset = ResOffset;
6542}
6543
6544namespace {
6545
6546// This is a wrapper class around StringLiteral to support offsetted string
6547// literals as format strings. It takes the offset into account when returning
6548// the string and its length or the source locations to display notes correctly.
6549class FormatStringLiteral {
6550 const StringLiteral *FExpr;
6551 int64_t Offset;
6552
6553public:
6554 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6555 : FExpr(fexpr), Offset(Offset) {}
6556
6557 const StringLiteral *getFormatString() const { return FExpr; }
6558
6559 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6560
6561 unsigned getByteLength() const {
6562 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6563 }
6564
6565 unsigned getLength() const { return FExpr->getLength() - Offset; }
6566 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6567
6568 StringLiteralKind getKind() const { return FExpr->getKind(); }
6569
6570 QualType getType() const { return FExpr->getType(); }
6571
6572 bool isAscii() const { return FExpr->isOrdinary(); }
6573 bool isWide() const { return FExpr->isWide(); }
6574 bool isUTF8() const { return FExpr->isUTF8(); }
6575 bool isUTF16() const { return FExpr->isUTF16(); }
6576 bool isUTF32() const { return FExpr->isUTF32(); }
6577 bool isPascal() const { return FExpr->isPascal(); }
6578
6579 SourceLocation getLocationOfByte(
6580 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6581 const TargetInfo &Target, unsigned *StartToken = nullptr,
6582 unsigned *StartTokenByteOffset = nullptr) const {
6583 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6584 StartToken, StartTokenByteOffset);
6585 }
6586
6587 SourceLocation getBeginLoc() const LLVM_READONLY {
6588 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6589 }
6590
6591 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6592};
6593
6594} // namespace
6595
6596static void CheckFormatString(
6597 Sema &S, const FormatStringLiteral *FExpr,
6598 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6600 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6601 bool inFunctionCall, VariadicCallType CallType,
6602 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6603 bool IgnoreStringsWithoutSpecifiers);
6604
6605static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6606 const Expr *E);
6607
6608// Determine if an expression is a string literal or constant string.
6609// If this function returns false on the arguments to a function expecting a
6610// format string, we will usually need to emit a warning.
6611// True string literals are then checked by CheckFormatString.
6612static StringLiteralCheckType
6613checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6614 const Expr *E, ArrayRef<const Expr *> Args,
6615 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6616 unsigned firstDataArg, FormatStringType Type,
6617 VariadicCallType CallType, bool InFunctionCall,
6618 llvm::SmallBitVector &CheckedVarArgs,
6619 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6620 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6621 bool IgnoreStringsWithoutSpecifiers = false) {
6623 return SLCT_NotALiteral;
6624tryAgain:
6625 assert(Offset.isSigned() && "invalid offset");
6626
6627 if (E->isTypeDependent() || E->isValueDependent())
6628 return SLCT_NotALiteral;
6629
6630 E = E->IgnoreParenCasts();
6631
6633 // Technically -Wformat-nonliteral does not warn about this case.
6634 // The behavior of printf and friends in this case is implementation
6635 // dependent. Ideally if the format string cannot be null then
6636 // it should have a 'nonnull' attribute in the function prototype.
6637 return SLCT_UncheckedLiteral;
6638
6639 switch (E->getStmtClass()) {
6640 case Stmt::InitListExprClass:
6641 // Handle expressions like {"foobar"}.
6642 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6643 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6644 format_idx, firstDataArg, Type, CallType,
6645 /*InFunctionCall*/ false, CheckedVarArgs,
6646 UncoveredArg, Offset, CallerFormatParamIdx,
6647 IgnoreStringsWithoutSpecifiers);
6648 }
6649 return SLCT_NotALiteral;
6650 case Stmt::BinaryConditionalOperatorClass:
6651 case Stmt::ConditionalOperatorClass: {
6652 // The expression is a literal if both sub-expressions were, and it was
6653 // completely checked only if both sub-expressions were checked.
6656
6657 // Determine whether it is necessary to check both sub-expressions, for
6658 // example, because the condition expression is a constant that can be
6659 // evaluated at compile time.
6660 bool CheckLeft = true, CheckRight = true;
6661
6662 bool Cond;
6663 if (C->getCond()->EvaluateAsBooleanCondition(
6665 if (Cond)
6666 CheckRight = false;
6667 else
6668 CheckLeft = false;
6669 }
6670
6671 // We need to maintain the offsets for the right and the left hand side
6672 // separately to check if every possible indexed expression is a valid
6673 // string literal. They might have different offsets for different string
6674 // literals in the end.
6675 StringLiteralCheckType Left;
6676 if (!CheckLeft)
6677 Left = SLCT_UncheckedLiteral;
6678 else {
6679 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
6680 Args, APK, format_idx, firstDataArg, Type,
6681 CallType, InFunctionCall, CheckedVarArgs,
6682 UncoveredArg, Offset, CallerFormatParamIdx,
6683 IgnoreStringsWithoutSpecifiers);
6684 if (Left == SLCT_NotALiteral || !CheckRight) {
6685 return Left;
6686 }
6687 }
6688
6689 StringLiteralCheckType Right = checkFormatStringExpr(
6690 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6691 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6692 UncoveredArg, Offset, CallerFormatParamIdx,
6693 IgnoreStringsWithoutSpecifiers);
6694
6695 return (CheckLeft && Left < Right) ? Left : Right;
6696 }
6697
6698 case Stmt::ImplicitCastExprClass:
6699 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6700 goto tryAgain;
6701
6702 case Stmt::OpaqueValueExprClass:
6703 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6704 E = src;
6705 goto tryAgain;
6706 }
6707 return SLCT_NotALiteral;
6708
6709 case Stmt::PredefinedExprClass:
6710 // While __func__, etc., are technically not string literals, they
6711 // cannot contain format specifiers and thus are not a security
6712 // liability.
6713 return SLCT_UncheckedLiteral;
6714
6715 case Stmt::DeclRefExprClass: {
6716 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6717
6718 // As an exception, do not flag errors for variables binding to
6719 // const string literals.
6720 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6721 bool isConstant = false;
6722 QualType T = DR->getType();
6723
6724 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6725 isConstant = AT->getElementType().isConstant(S.Context);
6726 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6727 isConstant = T.isConstant(S.Context) &&
6728 PT->getPointeeType().isConstant(S.Context);
6729 } else if (T->isObjCObjectPointerType()) {
6730 // In ObjC, there is usually no "const ObjectPointer" type,
6731 // so don't check if the pointee type is constant.
6732 isConstant = T.isConstant(S.Context);
6733 }
6734
6735 if (isConstant) {
6736 if (const Expr *Init = VD->getAnyInitializer()) {
6737 // Look through initializers like const char c[] = { "foo" }
6738 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6739 if (InitList->isStringLiteralInit())
6740 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6741 }
6742 return checkFormatStringExpr(
6743 S, ReferenceFormatString, Init, Args, APK, format_idx,
6744 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
6745 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
6746 }
6747 }
6748
6749 // When the format argument is an argument of this function, and this
6750 // function also has the format attribute, there are several interactions
6751 // for which there shouldn't be a warning. For instance, when calling
6752 // v*printf from a function that has the printf format attribute, we
6753 // should not emit a warning about using `fmt`, even though it's not
6754 // constant, because the arguments have already been checked for the
6755 // caller of `logmessage`:
6756 //
6757 // __attribute__((format(printf, 1, 2)))
6758 // void logmessage(char const *fmt, ...) {
6759 // va_list ap;
6760 // va_start(ap, fmt);
6761 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6762 // ...
6763 // }
6764 //
6765 // Another interaction that we need to support is using a format string
6766 // specified by the format_matches attribute:
6767 //
6768 // __attribute__((format_matches(printf, 1, "%s %d")))
6769 // void logmessage(char const *fmt, const char *a, int b) {
6770 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6771 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6772 // ...
6773 // }
6774 //
6775 // Yet another interaction that we need to support is calling a variadic
6776 // format function from a format function that has fixed arguments. For
6777 // instance:
6778 //
6779 // __attribute__((format(printf, 1, 2)))
6780 // void logstring(char const *fmt, char const *str) {
6781 // printf(fmt, str); /* do not emit a warning about "fmt" */
6782 // }
6783 //
6784 // Same (and perhaps more relatably) for the variadic template case:
6785 //
6786 // template<typename... Args>
6787 // __attribute__((format(printf, 1, 2)))
6788 // void log(const char *fmt, Args&&... args) {
6789 // printf(fmt, forward<Args>(args)...);
6790 // /* do not emit a warning about "fmt" */
6791 // }
6792 //
6793 // Due to implementation difficulty, we only check the format, not the
6794 // format arguments, in all cases.
6795 //
6796 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6797 if (CallerFormatParamIdx)
6798 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
6799 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6800 for (const auto *PVFormatMatches :
6801 D->specific_attrs<FormatMatchesAttr>()) {
6802 Sema::FormatStringInfo CalleeFSI;
6803 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6804 0, &CalleeFSI))
6805 continue;
6806 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6807 // If using the wrong type of format string, emit a diagnostic
6808 // here and stop checking to avoid irrelevant diagnostics.
6809 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6810 S.Diag(Args[format_idx]->getBeginLoc(),
6811 diag::warn_format_string_type_incompatible)
6812 << PVFormatMatches->getType()->getName()
6814 if (!InFunctionCall) {
6815 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6816 diag::note_format_string_defined);
6817 }
6818 return SLCT_UncheckedLiteral;
6819 }
6820 return checkFormatStringExpr(
6821 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6822 Args, APK, format_idx, firstDataArg, Type, CallType,
6823 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6824 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6825 }
6826 }
6827
6828 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6829 Sema::FormatStringInfo CallerFSI;
6830 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6831 PVFormat->getFirstArg(), &CallerFSI))
6832 continue;
6833 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6834 // We also check if the formats are compatible.
6835 // We can't pass a 'scanf' string to a 'printf' function.
6836 if (Type != S.GetFormatStringType(PVFormat)) {
6837 S.Diag(Args[format_idx]->getBeginLoc(),
6838 diag::warn_format_string_type_incompatible)
6839 << PVFormat->getType()->getName()
6841 if (!InFunctionCall) {
6842 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6843 }
6844 return SLCT_UncheckedLiteral;
6845 }
6846 // Lastly, check that argument passing kinds transition in a
6847 // way that makes sense:
6848 // from a caller with FAPK_VAList, allow FAPK_VAList
6849 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6850 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6851 // from a caller with FAPK_Variadic, allow FAPK_VAList
6852 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6857 return SLCT_UncheckedLiteral;
6858 }
6859 }
6860 }
6861 }
6862 }
6863 }
6864
6865 return SLCT_NotALiteral;
6866 }
6867
6868 case Stmt::CallExprClass:
6869 case Stmt::CXXMemberCallExprClass: {
6870 const CallExpr *CE = cast<CallExpr>(E);
6871 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6872 bool IsFirst = true;
6873 StringLiteralCheckType CommonResult;
6874 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6875 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6876 StringLiteralCheckType Result = checkFormatStringExpr(
6877 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6878 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6879 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6880 if (IsFirst) {
6881 CommonResult = Result;
6882 IsFirst = false;
6883 }
6884 }
6885 if (!IsFirst)
6886 return CommonResult;
6887
6888 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6889 unsigned BuiltinID = FD->getBuiltinID();
6890 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6891 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6892 const Expr *Arg = CE->getArg(0);
6893 return checkFormatStringExpr(
6894 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6895 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6896 UncoveredArg, Offset, CallerFormatParamIdx,
6897 IgnoreStringsWithoutSpecifiers);
6898 }
6899 }
6900 }
6901 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6902 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6903 format_idx, firstDataArg, Type, CallType,
6904 /*InFunctionCall*/ false, CheckedVarArgs,
6905 UncoveredArg, Offset, CallerFormatParamIdx,
6906 IgnoreStringsWithoutSpecifiers);
6907 return SLCT_NotALiteral;
6908 }
6909 case Stmt::ObjCMessageExprClass: {
6910 const auto *ME = cast<ObjCMessageExpr>(E);
6911 if (const auto *MD = ME->getMethodDecl()) {
6912 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6913 // As a special case heuristic, if we're using the method -[NSBundle
6914 // localizedStringForKey:value:table:], ignore any key strings that lack
6915 // format specifiers. The idea is that if the key doesn't have any
6916 // format specifiers then its probably just a key to map to the
6917 // localized strings. If it does have format specifiers though, then its
6918 // likely that the text of the key is the format string in the
6919 // programmer's language, and should be checked.
6920 const ObjCInterfaceDecl *IFace;
6921 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6922 IFace->getIdentifier()->isStr("NSBundle") &&
6923 MD->getSelector().isKeywordSelector(
6924 {"localizedStringForKey", "value", "table"})) {
6925 IgnoreStringsWithoutSpecifiers = true;
6926 }
6927
6928 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6929 return checkFormatStringExpr(
6930 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6931 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6932 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6933 }
6934 }
6935
6936 return SLCT_NotALiteral;
6937 }
6938 case Stmt::ObjCStringLiteralClass:
6939 case Stmt::StringLiteralClass: {
6940 const StringLiteral *StrE = nullptr;
6941
6942 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6943 StrE = ObjCFExpr->getString();
6944 else
6945 StrE = cast<StringLiteral>(E);
6946
6947 if (StrE) {
6948 if (Offset.isNegative() || Offset > StrE->getLength()) {
6949 // TODO: It would be better to have an explicit warning for out of
6950 // bounds literals.
6951 return SLCT_NotALiteral;
6952 }
6953 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6954 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6955 format_idx, firstDataArg, Type, InFunctionCall,
6956 CallType, CheckedVarArgs, UncoveredArg,
6957 IgnoreStringsWithoutSpecifiers);
6958 return SLCT_CheckedLiteral;
6959 }
6960
6961 return SLCT_NotALiteral;
6962 }
6963 case Stmt::BinaryOperatorClass: {
6964 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6965
6966 // A string literal + an int offset is still a string literal.
6967 if (BinOp->isAdditiveOp()) {
6968 Expr::EvalResult LResult, RResult;
6969
6970 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6971 LResult, S.Context, Expr::SE_NoSideEffects,
6973 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6974 RResult, S.Context, Expr::SE_NoSideEffects,
6976
6977 if (LIsInt != RIsInt) {
6978 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6979
6980 if (LIsInt) {
6981 if (BinOpKind == BO_Add) {
6982 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6983 E = BinOp->getRHS();
6984 goto tryAgain;
6985 }
6986 } else {
6987 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6988 E = BinOp->getLHS();
6989 goto tryAgain;
6990 }
6991 }
6992 }
6993
6994 return SLCT_NotALiteral;
6995 }
6996 case Stmt::UnaryOperatorClass: {
6997 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6998 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6999 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7000 Expr::EvalResult IndexResult;
7001 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7004 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7005 /*RHS is int*/ true);
7006 E = ASE->getBase();
7007 goto tryAgain;
7008 }
7009 }
7010
7011 return SLCT_NotALiteral;
7012 }
7013
7014 default:
7015 return SLCT_NotALiteral;
7016 }
7017}
7018
7019// If this expression can be evaluated at compile-time,
7020// check if the result is a StringLiteral and return it
7021// otherwise return nullptr
7023 const Expr *E) {
7024 Expr::EvalResult Result;
7025 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7026 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7027 if (isa_and_nonnull<StringLiteral>(LVE))
7028 return LVE;
7029 }
7030 return nullptr;
7031}
7032
7034 switch (FST) {
7036 return "scanf";
7038 return "printf";
7040 return "NSString";
7042 return "strftime";
7044 return "strfmon";
7046 return "kprintf";
7048 return "freebsd_kprintf";
7050 return "os_log";
7051 default:
7052 return "<unknown>";
7053 }
7054}
7055
7057 return llvm::StringSwitch<FormatStringType>(Flavor)
7058 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7059 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7061 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7062 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7063 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7064 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7066 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7067 .Case("os_trace", FormatStringType::OSLog)
7068 .Case("os_log", FormatStringType::OSLog)
7069 .Default(FormatStringType::Unknown);
7070}
7071
7073 return GetFormatStringType(Format->getType()->getName());
7074}
7075
7076FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7077 return GetFormatStringType(Format->getType()->getName());
7078}
7079
7080bool Sema::CheckFormatArguments(const FormatAttr *Format,
7081 ArrayRef<const Expr *> Args, bool IsCXXMember,
7082 VariadicCallType CallType, SourceLocation Loc,
7083 SourceRange Range,
7084 llvm::SmallBitVector &CheckedVarArgs) {
7085 FormatStringInfo FSI;
7086 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7087 IsCXXMember,
7088 CallType != VariadicCallType::DoesNotApply, &FSI))
7089 return CheckFormatArguments(
7090 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7091 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7092 return false;
7093}
7094
7095bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7096 ArrayRef<const Expr *> Args, bool IsCXXMember,
7097 VariadicCallType CallType, SourceLocation Loc,
7098 SourceRange Range,
7099 llvm::SmallBitVector &CheckedVarArgs) {
7100 FormatStringInfo FSI;
7101 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7102 &FSI)) {
7103 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7104 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7105 Format->getFormatString(), FSI.FormatIdx,
7106 FSI.FirstDataArg, GetFormatStringType(Format),
7107 CallType, Loc, Range, CheckedVarArgs);
7108 }
7109 return false;
7110}
7111
7114 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7115 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7116 SourceLocation Loc) {
7117 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7118 return false;
7119
7120 DeclContext *DC = S->CurContext;
7121 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7122 return false;
7123 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7124
7125 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7126
7127 // Find the offset to convert between attribute and parameter indexes.
7128 unsigned CallerArgumentIndexOffset =
7129 hasImplicitObjectParameter(Caller) ? 2 : 1;
7130
7131 unsigned FirstArgumentIndex = -1;
7132 switch (APK) {
7135 // As an extension, clang allows the format attribute on non-variadic
7136 // functions.
7137 // Caller must have fixed arguments to pass them to a fixed or variadic
7138 // function. Try to match caller and callee arguments. If successful, then
7139 // emit a diag with the caller idx, otherwise we can't determine the callee
7140 // arguments.
7141 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7142 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7143 // There aren't enough arguments in the caller to pass to callee.
7144 return false;
7145 }
7146 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7147 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7148 const auto *Arg =
7149 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7150 if (!Arg)
7151 return false;
7152 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7153 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7154 return false;
7155 }
7156 FirstArgumentIndex =
7157 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7158 break;
7159 }
7161 // Caller arguments are either variadic or a va_list.
7162 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7163 ? (NumCallerParams + CallerArgumentIndexOffset)
7164 : 0;
7165 break;
7167 // The callee has a format_matches attribute. We will emit that instead.
7168 if (!ReferenceFormatString)
7169 return false;
7170 break;
7171 }
7172
7173 // Emit the diagnostic and fixit.
7174 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7175 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7176 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7177 do {
7178 std::string Attr, Fixit;
7179 llvm::raw_string_ostream AttrOS(Attr);
7181 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7182 << FirstArgumentIndex << ")";
7183 } else {
7184 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7185 << ", \"";
7186 AttrOS.write_escaped(ReferenceFormatString->getString());
7187 AttrOS << "\")";
7188 }
7189 AttrOS.flush();
7190 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7191 if (ND)
7192 DB << ND;
7193 else
7194 DB << "block";
7195
7196 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7197 if (isa<BlockDecl>(Caller))
7198 break;
7199
7200 SourceLocation SL;
7201 llvm::raw_string_ostream IS(Fixit);
7202 // The attribute goes at the start of the declaration in C/C++ functions
7203 // and methods, but after the declaration for Objective-C methods.
7204 if (isa<ObjCMethodDecl>(Caller)) {
7205 IS << ' ';
7206 SL = Caller->getEndLoc();
7207 }
7208 const LangOptions &LO = S->getLangOpts();
7209 if (LO.C23 || LO.CPlusPlus11)
7210 IS << "[[gnu::" << Attr << "]]";
7211 else if (LO.ObjC || LO.GNUMode)
7212 IS << "__attribute__((" << Attr << "))";
7213 else
7214 break;
7215 if (!isa<ObjCMethodDecl>(Caller)) {
7216 IS << ' ';
7217 SL = Caller->getBeginLoc();
7218 }
7219 IS.flush();
7220
7221 DB << FixItHint::CreateInsertion(SL, Fixit);
7222 } while (false);
7223
7224 // Add implicit format or format_matches attribute.
7226 Caller->addAttr(FormatAttr::CreateImplicit(
7227 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7228 FormatStringIndex, FirstArgumentIndex));
7229 } else {
7230 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7231 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7232 FormatStringIndex, ReferenceFormatString));
7233 }
7234
7235 {
7236 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7237 if (ND)
7238 DB << ND;
7239 else
7240 DB << "block";
7241 }
7242 return true;
7243}
7244
7245bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7247 StringLiteral *ReferenceFormatString,
7248 unsigned format_idx, unsigned firstDataArg,
7250 VariadicCallType CallType, SourceLocation Loc,
7251 SourceRange Range,
7252 llvm::SmallBitVector &CheckedVarArgs) {
7253 // CHECK: printf/scanf-like function is called with no format string.
7254 if (format_idx >= Args.size()) {
7255 Diag(Loc, diag::warn_missing_format_string) << Range;
7256 return false;
7257 }
7258
7259 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7260
7261 // CHECK: format string is not a string literal.
7262 //
7263 // Dynamically generated format strings are difficult to
7264 // automatically vet at compile time. Requiring that format strings
7265 // are string literals: (1) permits the checking of format strings by
7266 // the compiler and thereby (2) can practically remove the source of
7267 // many format string exploits.
7268
7269 // Format string can be either ObjC string (e.g. @"%d") or
7270 // C string (e.g. "%d")
7271 // ObjC string uses the same format specifiers as C string, so we can use
7272 // the same format string checking logic for both ObjC and C strings.
7273 UncoveredArgHandler UncoveredArg;
7274 std::optional<unsigned> CallerParamIdx;
7275 StringLiteralCheckType CT = checkFormatStringExpr(
7276 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7277 firstDataArg, Type, CallType,
7278 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7279 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7280
7281 // Generate a diagnostic where an uncovered argument is detected.
7282 if (UncoveredArg.hasUncoveredArg()) {
7283 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7284 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7285 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7286 }
7287
7288 if (CT != SLCT_NotALiteral)
7289 // Literal format string found, check done!
7290 return CT == SLCT_CheckedLiteral;
7291
7292 // Do not emit diag when the string param is a macro expansion and the
7293 // format is either NSString or CFString. This is a hack to prevent
7294 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7295 // which are usually used in place of NS and CF string literals.
7296 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7298 SourceMgr.isInSystemMacro(FormatLoc))
7299 return false;
7300
7301 if (CallerParamIdx && CheckMissingFormatAttribute(
7302 this, Args, APK, ReferenceFormatString, format_idx,
7303 firstDataArg, Type, *CallerParamIdx, Loc))
7304 return false;
7305
7306 // Strftime is particular as it always uses a single 'time' argument,
7307 // so it is safe to pass a non-literal string.
7309 return false;
7310
7311 // If there are no arguments specified, warn with -Wformat-security, otherwise
7312 // warn only with -Wformat-nonliteral.
7313 if (Args.size() == firstDataArg) {
7314 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7315 << OrigFormatExpr->getSourceRange();
7316 switch (Type) {
7317 default:
7318 break;
7322 Diag(FormatLoc, diag::note_format_security_fixit)
7323 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7324 break;
7326 Diag(FormatLoc, diag::note_format_security_fixit)
7327 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7328 break;
7329 }
7330 } else {
7331 Diag(FormatLoc, diag::warn_format_nonliteral)
7332 << OrigFormatExpr->getSourceRange();
7333 }
7334 return false;
7335}
7336
7337namespace {
7338
7339class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7340protected:
7341 Sema &S;
7342 const FormatStringLiteral *FExpr;
7343 const Expr *OrigFormatExpr;
7344 const FormatStringType FSType;
7345 const unsigned FirstDataArg;
7346 const unsigned NumDataArgs;
7347 const char *Beg; // Start of format string.
7348 const Sema::FormatArgumentPassingKind ArgPassingKind;
7349 ArrayRef<const Expr *> Args;
7350 unsigned FormatIdx;
7351 llvm::SmallBitVector CoveredArgs;
7352 bool usesPositionalArgs = false;
7353 bool atFirstArg = true;
7354 bool inFunctionCall;
7355 VariadicCallType CallType;
7356 llvm::SmallBitVector &CheckedVarArgs;
7357 UncoveredArgHandler &UncoveredArg;
7358
7359public:
7360 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7361 const Expr *origFormatExpr, const FormatStringType type,
7362 unsigned firstDataArg, unsigned numDataArgs,
7363 const char *beg, Sema::FormatArgumentPassingKind APK,
7364 ArrayRef<const Expr *> Args, unsigned formatIdx,
7365 bool inFunctionCall, VariadicCallType callType,
7366 llvm::SmallBitVector &CheckedVarArgs,
7367 UncoveredArgHandler &UncoveredArg)
7368 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7369 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7370 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7371 inFunctionCall(inFunctionCall), CallType(callType),
7372 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7373 CoveredArgs.resize(numDataArgs);
7374 CoveredArgs.reset();
7375 }
7376
7377 bool HasFormatArguments() const {
7378 return ArgPassingKind == Sema::FAPK_Fixed ||
7379 ArgPassingKind == Sema::FAPK_Variadic;
7380 }
7381
7382 void DoneProcessing();
7383
7384 void HandleIncompleteSpecifier(const char *startSpecifier,
7385 unsigned specifierLen) override;
7386
7387 void HandleInvalidLengthModifier(
7388 const analyze_format_string::FormatSpecifier &FS,
7389 const analyze_format_string::ConversionSpecifier &CS,
7390 const char *startSpecifier, unsigned specifierLen,
7391 unsigned DiagID);
7392
7393 void HandleNonStandardLengthModifier(
7394 const analyze_format_string::FormatSpecifier &FS,
7395 const char *startSpecifier, unsigned specifierLen);
7396
7397 void HandleNonStandardConversionSpecifier(
7398 const analyze_format_string::ConversionSpecifier &CS,
7399 const char *startSpecifier, unsigned specifierLen);
7400
7401 void HandlePosition(const char *startPos, unsigned posLen) override;
7402
7403 void HandleInvalidPosition(const char *startSpecifier,
7404 unsigned specifierLen,
7406
7407 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7408
7409 void HandleNullChar(const char *nullCharacter) override;
7410
7411 template <typename Range>
7412 static void
7413 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7414 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7415 bool IsStringLocation, Range StringRange,
7416 ArrayRef<FixItHint> Fixit = {});
7417
7418protected:
7419 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7420 const char *startSpec,
7421 unsigned specifierLen,
7422 const char *csStart, unsigned csLen);
7423
7424 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7425 const char *startSpec,
7426 unsigned specifierLen);
7427
7428 SourceRange getFormatStringRange();
7429 CharSourceRange getSpecifierRange(const char *startSpecifier,
7430 unsigned specifierLen);
7431 SourceLocation getLocationOfByte(const char *x);
7432
7433 const Expr *getDataArg(unsigned i) const;
7434
7435 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7436 const analyze_format_string::ConversionSpecifier &CS,
7437 const char *startSpecifier, unsigned specifierLen,
7438 unsigned argIndex);
7439
7440 template <typename Range>
7441 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7442 bool IsStringLocation, Range StringRange,
7443 ArrayRef<FixItHint> Fixit = {});
7444};
7445
7446} // namespace
7447
7448SourceRange CheckFormatHandler::getFormatStringRange() {
7449 return OrigFormatExpr->getSourceRange();
7450}
7451
7452CharSourceRange CheckFormatHandler::
7453getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7454 SourceLocation Start = getLocationOfByte(startSpecifier);
7455 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7456
7457 // Advance the end SourceLocation by one due to half-open ranges.
7458 End = End.getLocWithOffset(1);
7459
7460 return CharSourceRange::getCharRange(Start, End);
7461}
7462
7463SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7464 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7466}
7467
7468void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7469 unsigned specifierLen){
7470 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7471 getLocationOfByte(startSpecifier),
7472 /*IsStringLocation*/true,
7473 getSpecifierRange(startSpecifier, specifierLen));
7474}
7475
7476void CheckFormatHandler::HandleInvalidLengthModifier(
7479 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7480 using namespace analyze_format_string;
7481
7482 const LengthModifier &LM = FS.getLengthModifier();
7483 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7484
7485 // See if we know how to fix this length modifier.
7486 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7487 if (FixedLM) {
7488 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7489 getLocationOfByte(LM.getStart()),
7490 /*IsStringLocation*/true,
7491 getSpecifierRange(startSpecifier, specifierLen));
7492
7493 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7494 << FixedLM->toString()
7495 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7496
7497 } else {
7498 FixItHint Hint;
7499 if (DiagID == diag::warn_format_nonsensical_length)
7500 Hint = FixItHint::CreateRemoval(LMRange);
7501
7502 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7503 getLocationOfByte(LM.getStart()),
7504 /*IsStringLocation*/true,
7505 getSpecifierRange(startSpecifier, specifierLen),
7506 Hint);
7507 }
7508}
7509
7510void CheckFormatHandler::HandleNonStandardLengthModifier(
7512 const char *startSpecifier, unsigned specifierLen) {
7513 using namespace analyze_format_string;
7514
7515 const LengthModifier &LM = FS.getLengthModifier();
7516 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7517
7518 // See if we know how to fix this length modifier.
7519 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7520 if (FixedLM) {
7521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7522 << LM.toString() << 0,
7523 getLocationOfByte(LM.getStart()),
7524 /*IsStringLocation*/true,
7525 getSpecifierRange(startSpecifier, specifierLen));
7526
7527 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7528 << FixedLM->toString()
7529 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7530
7531 } else {
7532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7533 << LM.toString() << 0,
7534 getLocationOfByte(LM.getStart()),
7535 /*IsStringLocation*/true,
7536 getSpecifierRange(startSpecifier, specifierLen));
7537 }
7538}
7539
7540void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7542 const char *startSpecifier, unsigned specifierLen) {
7543 using namespace analyze_format_string;
7544
7545 // See if we know how to fix this conversion specifier.
7546 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7547 if (FixedCS) {
7548 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7549 << CS.toString() << /*conversion specifier*/1,
7550 getLocationOfByte(CS.getStart()),
7551 /*IsStringLocation*/true,
7552 getSpecifierRange(startSpecifier, specifierLen));
7553
7554 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7555 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7556 << FixedCS->toString()
7557 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7558 } else {
7559 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7560 << CS.toString() << /*conversion specifier*/1,
7561 getLocationOfByte(CS.getStart()),
7562 /*IsStringLocation*/true,
7563 getSpecifierRange(startSpecifier, specifierLen));
7564 }
7565}
7566
7567void CheckFormatHandler::HandlePosition(const char *startPos,
7568 unsigned posLen) {
7569 if (!S.getDiagnostics().isIgnored(
7570 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7571 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7572 getLocationOfByte(startPos),
7573 /*IsStringLocation*/ true,
7574 getSpecifierRange(startPos, posLen));
7575}
7576
7577void CheckFormatHandler::HandleInvalidPosition(
7578 const char *startSpecifier, unsigned specifierLen,
7580 if (!S.getDiagnostics().isIgnored(
7581 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7582 EmitFormatDiagnostic(
7583 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7584 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7585 getSpecifierRange(startSpecifier, specifierLen));
7586}
7587
7588void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7589 unsigned posLen) {
7590 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7591 SourceLocation()))
7592 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7593 getLocationOfByte(startPos),
7594 /*IsStringLocation*/ true,
7595 getSpecifierRange(startPos, posLen));
7596}
7597
7598void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7599 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7600 // The presence of a null character is likely an error.
7601 EmitFormatDiagnostic(
7602 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7603 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7604 getFormatStringRange());
7605 }
7606}
7607
7608// Note that this may return NULL if there was an error parsing or building
7609// one of the argument expressions.
7610const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7611 return Args[FirstDataArg + i];
7612}
7613
7614void CheckFormatHandler::DoneProcessing() {
7615 // Does the number of data arguments exceed the number of
7616 // format conversions in the format string?
7617 if (HasFormatArguments()) {
7618 // Find any arguments that weren't covered.
7619 CoveredArgs.flip();
7620 signed notCoveredArg = CoveredArgs.find_first();
7621 if (notCoveredArg >= 0) {
7622 assert((unsigned)notCoveredArg < NumDataArgs);
7623 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7624 } else {
7625 UncoveredArg.setAllCovered();
7626 }
7627 }
7628}
7629
7630void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7631 const Expr *ArgExpr) {
7632 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7633 "Invalid state");
7634
7635 if (!ArgExpr)
7636 return;
7637
7638 SourceLocation Loc = ArgExpr->getBeginLoc();
7639
7640 if (S.getSourceManager().isInSystemMacro(Loc))
7641 return;
7642
7643 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7644 for (auto E : DiagnosticExprs)
7645 PDiag << E->getSourceRange();
7646
7647 CheckFormatHandler::EmitFormatDiagnostic(
7648 S, IsFunctionCall, DiagnosticExprs[0],
7649 PDiag, Loc, /*IsStringLocation*/false,
7650 DiagnosticExprs[0]->getSourceRange());
7651}
7652
7653bool
7654CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7655 SourceLocation Loc,
7656 const char *startSpec,
7657 unsigned specifierLen,
7658 const char *csStart,
7659 unsigned csLen) {
7660 bool keepGoing = true;
7661 if (argIndex < NumDataArgs) {
7662 // Consider the argument coverered, even though the specifier doesn't
7663 // make sense.
7664 CoveredArgs.set(argIndex);
7665 }
7666 else {
7667 // If argIndex exceeds the number of data arguments we
7668 // don't issue a warning because that is just a cascade of warnings (and
7669 // they may have intended '%%' anyway). We don't want to continue processing
7670 // the format string after this point, however, as we will like just get
7671 // gibberish when trying to match arguments.
7672 keepGoing = false;
7673 }
7674
7675 StringRef Specifier(csStart, csLen);
7676
7677 // If the specifier in non-printable, it could be the first byte of a UTF-8
7678 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7679 // hex value.
7680 std::string CodePointStr;
7681 if (!llvm::sys::locale::isPrint(*csStart)) {
7682 llvm::UTF32 CodePoint;
7683 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7684 const llvm::UTF8 *E =
7685 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7686 llvm::ConversionResult Result =
7687 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7688
7689 if (Result != llvm::conversionOK) {
7690 unsigned char FirstChar = *csStart;
7691 CodePoint = (llvm::UTF32)FirstChar;
7692 }
7693
7694 llvm::raw_string_ostream OS(CodePointStr);
7695 if (CodePoint < 256)
7696 OS << "\\x" << llvm::format("%02x", CodePoint);
7697 else if (CodePoint <= 0xFFFF)
7698 OS << "\\u" << llvm::format("%04x", CodePoint);
7699 else
7700 OS << "\\U" << llvm::format("%08x", CodePoint);
7701 Specifier = CodePointStr;
7702 }
7703
7704 EmitFormatDiagnostic(
7705 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7706 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7707
7708 return keepGoing;
7709}
7710
7711void
7712CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7713 const char *startSpec,
7714 unsigned specifierLen) {
7715 EmitFormatDiagnostic(
7716 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7717 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7718}
7719
7720bool
7721CheckFormatHandler::CheckNumArgs(
7724 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7725
7726 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7728 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7729 << (argIndex+1) << NumDataArgs)
7730 : S.PDiag(diag::warn_printf_insufficient_data_args);
7731 EmitFormatDiagnostic(
7732 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7733 getSpecifierRange(startSpecifier, specifierLen));
7734
7735 // Since more arguments than conversion tokens are given, by extension
7736 // all arguments are covered, so mark this as so.
7737 UncoveredArg.setAllCovered();
7738 return false;
7739 }
7740 return true;
7741}
7742
7743template<typename Range>
7744void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7745 SourceLocation Loc,
7746 bool IsStringLocation,
7747 Range StringRange,
7748 ArrayRef<FixItHint> FixIt) {
7749 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7750 Loc, IsStringLocation, StringRange, FixIt);
7751}
7752
7753/// If the format string is not within the function call, emit a note
7754/// so that the function call and string are in diagnostic messages.
7755///
7756/// \param InFunctionCall if true, the format string is within the function
7757/// call and only one diagnostic message will be produced. Otherwise, an
7758/// extra note will be emitted pointing to location of the format string.
7759///
7760/// \param ArgumentExpr the expression that is passed as the format string
7761/// argument in the function call. Used for getting locations when two
7762/// diagnostics are emitted.
7763///
7764/// \param PDiag the callee should already have provided any strings for the
7765/// diagnostic message. This function only adds locations and fixits
7766/// to diagnostics.
7767///
7768/// \param Loc primary location for diagnostic. If two diagnostics are
7769/// required, one will be at Loc and a new SourceLocation will be created for
7770/// the other one.
7771///
7772/// \param IsStringLocation if true, Loc points to the format string should be
7773/// used for the note. Otherwise, Loc points to the argument list and will
7774/// be used with PDiag.
7775///
7776/// \param StringRange some or all of the string to highlight. This is
7777/// templated so it can accept either a CharSourceRange or a SourceRange.
7778///
7779/// \param FixIt optional fix it hint for the format string.
7780template <typename Range>
7781void CheckFormatHandler::EmitFormatDiagnostic(
7782 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7783 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7784 Range StringRange, ArrayRef<FixItHint> FixIt) {
7785 if (InFunctionCall) {
7786 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7787 D << StringRange;
7788 D << FixIt;
7789 } else {
7790 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7791 << ArgumentExpr->getSourceRange();
7792
7794 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7795 diag::note_format_string_defined);
7796
7797 Note << StringRange;
7798 Note << FixIt;
7799 }
7800}
7801
7802//===--- CHECK: Printf format string checking -----------------------------===//
7803
7804namespace {
7805
7806class CheckPrintfHandler : public CheckFormatHandler {
7807public:
7808 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7809 const Expr *origFormatExpr, const FormatStringType type,
7810 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7811 const char *beg, Sema::FormatArgumentPassingKind APK,
7812 ArrayRef<const Expr *> Args, unsigned formatIdx,
7813 bool inFunctionCall, VariadicCallType CallType,
7814 llvm::SmallBitVector &CheckedVarArgs,
7815 UncoveredArgHandler &UncoveredArg)
7816 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7817 numDataArgs, beg, APK, Args, formatIdx,
7818 inFunctionCall, CallType, CheckedVarArgs,
7819 UncoveredArg) {}
7820
7821 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7822
7823 /// Returns true if '%@' specifiers are allowed in the format string.
7824 bool allowsObjCArg() const {
7825 return FSType == FormatStringType::NSString ||
7826 FSType == FormatStringType::OSLog ||
7827 FSType == FormatStringType::OSTrace;
7828 }
7829
7830 bool HandleInvalidPrintfConversionSpecifier(
7831 const analyze_printf::PrintfSpecifier &FS,
7832 const char *startSpecifier,
7833 unsigned specifierLen) override;
7834
7835 void handleInvalidMaskType(StringRef MaskType) override;
7836
7837 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7838 const char *startSpecifier, unsigned specifierLen,
7839 const TargetInfo &Target) override;
7840 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7841 const char *StartSpecifier,
7842 unsigned SpecifierLen,
7843 const Expr *E);
7844
7845 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7846 const char *startSpecifier, unsigned specifierLen);
7847 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7848 const analyze_printf::OptionalAmount &Amt,
7849 unsigned type,
7850 const char *startSpecifier, unsigned specifierLen);
7851 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7852 const analyze_printf::OptionalFlag &flag,
7853 const char *startSpecifier, unsigned specifierLen);
7854 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7855 const analyze_printf::OptionalFlag &ignoredFlag,
7856 const analyze_printf::OptionalFlag &flag,
7857 const char *startSpecifier, unsigned specifierLen);
7858 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7859 const Expr *E);
7860
7861 void HandleEmptyObjCModifierFlag(const char *startFlag,
7862 unsigned flagLen) override;
7863
7864 void HandleInvalidObjCModifierFlag(const char *startFlag,
7865 unsigned flagLen) override;
7866
7867 void
7868 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7869 const char *flagsEnd,
7870 const char *conversionPosition) override;
7871};
7872
7873/// Keeps around the information needed to verify that two specifiers are
7874/// compatible.
7875class EquatableFormatArgument {
7876public:
7877 enum SpecifierSensitivity : unsigned {
7878 SS_None,
7879 SS_Private,
7880 SS_Public,
7881 SS_Sensitive
7882 };
7883
7884 enum FormatArgumentRole : unsigned {
7885 FAR_Data,
7886 FAR_FieldWidth,
7887 FAR_Precision,
7888 FAR_Auxiliary, // FreeBSD kernel %b and %D
7889 };
7890
7891private:
7892 analyze_format_string::ArgType ArgType;
7894 StringRef SpecifierLetter;
7895 CharSourceRange Range;
7896 SourceLocation ElementLoc;
7897 FormatArgumentRole Role : 2;
7898 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7899 unsigned Position : 14;
7900 unsigned ModifierFor : 14; // not set for FAR_Data
7901
7902 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7903 bool InFunctionCall) const;
7904
7905public:
7906 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7908 StringRef SpecifierLetter,
7909 analyze_format_string::ArgType ArgType,
7910 FormatArgumentRole Role,
7911 SpecifierSensitivity Sensitivity, unsigned Position,
7912 unsigned ModifierFor)
7913 : ArgType(ArgType), LengthMod(LengthMod),
7914 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7915 Role(Role), Sensitivity(Sensitivity), Position(Position),
7916 ModifierFor(ModifierFor) {}
7917
7918 unsigned getPosition() const { return Position; }
7919 SourceLocation getSourceLocation() const { return ElementLoc; }
7920 CharSourceRange getSourceRange() const { return Range; }
7921 analyze_format_string::LengthModifier getLengthModifier() const {
7922 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7923 }
7924 void setModifierFor(unsigned V) { ModifierFor = V; }
7925
7926 std::string buildFormatSpecifier() const {
7927 std::string result;
7928 llvm::raw_string_ostream(result)
7929 << getLengthModifier().toString() << SpecifierLetter;
7930 return result;
7931 }
7932
7933 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7934 const Expr *FmtExpr, bool InFunctionCall) const;
7935};
7936
7937/// Turns format strings into lists of EquatableSpecifier objects.
7938class DecomposePrintfHandler : public CheckPrintfHandler {
7939 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7940 bool HadError;
7941
7942 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7943 const Expr *origFormatExpr,
7944 const FormatStringType type, unsigned firstDataArg,
7945 unsigned numDataArgs, bool isObjC, const char *beg,
7947 ArrayRef<const Expr *> Args, unsigned formatIdx,
7948 bool inFunctionCall, VariadicCallType CallType,
7949 llvm::SmallBitVector &CheckedVarArgs,
7950 UncoveredArgHandler &UncoveredArg,
7951 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7952 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7953 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7954 inFunctionCall, CallType, CheckedVarArgs,
7955 UncoveredArg),
7956 Specs(Specs), HadError(false) {}
7957
7958public:
7959 static bool
7960 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7961 FormatStringType type, bool IsObjC, bool InFunctionCall,
7962 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7963
7964 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7965 const char *startSpecifier,
7966 unsigned specifierLen,
7967 const TargetInfo &Target) override;
7968};
7969
7970} // namespace
7971
7972bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7973 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7974 unsigned specifierLen) {
7977
7978 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7979 getLocationOfByte(CS.getStart()),
7980 startSpecifier, specifierLen,
7981 CS.getStart(), CS.getLength());
7982}
7983
7984void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7985 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7986}
7987
7988// Error out if struct or complex type argments are passed to os_log.
7990 QualType T) {
7991 if (FSType != FormatStringType::OSLog)
7992 return false;
7993 return T->isRecordType() || T->isComplexType();
7994}
7995
7996bool CheckPrintfHandler::HandleAmount(
7997 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7998 const char *startSpecifier, unsigned specifierLen) {
7999 if (Amt.hasDataArgument()) {
8000 if (HasFormatArguments()) {
8001 unsigned argIndex = Amt.getArgIndex();
8002 if (argIndex >= NumDataArgs) {
8003 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8004 << k,
8005 getLocationOfByte(Amt.getStart()),
8006 /*IsStringLocation*/ true,
8007 getSpecifierRange(startSpecifier, specifierLen));
8008 // Don't do any more checking. We will just emit
8009 // spurious errors.
8010 return false;
8011 }
8012
8013 // Type check the data argument. It should be an 'int'.
8014 // Although not in conformance with C99, we also allow the argument to be
8015 // an 'unsigned int' as that is a reasonably safe case. GCC also
8016 // doesn't emit a warning for that case.
8017 CoveredArgs.set(argIndex);
8018 const Expr *Arg = getDataArg(argIndex);
8019 if (!Arg)
8020 return false;
8021
8022 QualType T = Arg->getType();
8023
8024 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8025 assert(AT.isValid());
8026
8027 if (!AT.matchesType(S.Context, T)) {
8028 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8029 ? diag::err_printf_asterisk_wrong_type
8030 : diag::warn_printf_asterisk_wrong_type;
8031 EmitFormatDiagnostic(S.PDiag(DiagID)
8033 << T << Arg->getSourceRange(),
8034 getLocationOfByte(Amt.getStart()),
8035 /*IsStringLocation*/ true,
8036 getSpecifierRange(startSpecifier, specifierLen));
8037 // Don't do any more checking. We will just emit
8038 // spurious errors.
8039 return false;
8040 }
8041 }
8042 }
8043 return true;
8044}
8045
8046void CheckPrintfHandler::HandleInvalidAmount(
8049 unsigned type,
8050 const char *startSpecifier,
8051 unsigned specifierLen) {
8054
8055 FixItHint fixit =
8057 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8058 Amt.getConstantLength()))
8059 : FixItHint();
8060
8061 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8062 << type << CS.toString(),
8063 getLocationOfByte(Amt.getStart()),
8064 /*IsStringLocation*/true,
8065 getSpecifierRange(startSpecifier, specifierLen),
8066 fixit);
8067}
8068
8069void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8070 const analyze_printf::OptionalFlag &flag,
8071 const char *startSpecifier,
8072 unsigned specifierLen) {
8073 // Warn about pointless flag with a fixit removal.
8076 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8077 << flag.toString() << CS.toString(),
8078 getLocationOfByte(flag.getPosition()),
8079 /*IsStringLocation*/true,
8080 getSpecifierRange(startSpecifier, specifierLen),
8082 getSpecifierRange(flag.getPosition(), 1)));
8083}
8084
8085void CheckPrintfHandler::HandleIgnoredFlag(
8087 const analyze_printf::OptionalFlag &ignoredFlag,
8088 const analyze_printf::OptionalFlag &flag,
8089 const char *startSpecifier,
8090 unsigned specifierLen) {
8091 // Warn about ignored flag with a fixit removal.
8092 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8093 << ignoredFlag.toString() << flag.toString(),
8094 getLocationOfByte(ignoredFlag.getPosition()),
8095 /*IsStringLocation*/true,
8096 getSpecifierRange(startSpecifier, specifierLen),
8098 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8099}
8100
8101void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8102 unsigned flagLen) {
8103 // Warn about an empty flag.
8104 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8105 getLocationOfByte(startFlag),
8106 /*IsStringLocation*/true,
8107 getSpecifierRange(startFlag, flagLen));
8108}
8109
8110void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8111 unsigned flagLen) {
8112 // Warn about an invalid flag.
8113 auto Range = getSpecifierRange(startFlag, flagLen);
8114 StringRef flag(startFlag, flagLen);
8115 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8116 getLocationOfByte(startFlag),
8117 /*IsStringLocation*/true,
8118 Range, FixItHint::CreateRemoval(Range));
8119}
8120
8121void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8122 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8123 // Warn about using '[...]' without a '@' conversion.
8124 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8125 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8126 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8127 getLocationOfByte(conversionPosition),
8128 /*IsStringLocation*/ true, Range,
8130}
8131
8132void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8133 const Expr *FmtExpr,
8134 bool InFunctionCall) const {
8135 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8136 ElementLoc, true, Range);
8137}
8138
8139bool EquatableFormatArgument::VerifyCompatible(
8140 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8141 bool InFunctionCall) const {
8143 if (Role != Other.Role) {
8144 // diagnose and stop
8145 EmitDiagnostic(
8146 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8147 FmtExpr, InFunctionCall);
8148 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8149 return false;
8150 }
8151
8152 if (Role != FAR_Data) {
8153 if (ModifierFor != Other.ModifierFor) {
8154 // diagnose and stop
8155 EmitDiagnostic(S,
8156 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8157 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8158 FmtExpr, InFunctionCall);
8159 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8160 return false;
8161 }
8162 return true;
8163 }
8164
8165 bool HadError = false;
8166 if (Sensitivity != Other.Sensitivity) {
8167 // diagnose and continue
8168 EmitDiagnostic(S,
8169 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8170 << Sensitivity << Other.Sensitivity,
8171 FmtExpr, InFunctionCall);
8172 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8173 << 0 << Other.Range;
8174 }
8175
8176 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8177 case MK::Match:
8178 break;
8179
8180 case MK::MatchPromotion:
8181 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8182 // MatchPromotion is treated as a failure by format_matches.
8183 case MK::NoMatch:
8184 case MK::NoMatchTypeConfusion:
8185 case MK::NoMatchPromotionTypeConfusion:
8186 EmitDiagnostic(S,
8187 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8188 << buildFormatSpecifier()
8189 << Other.buildFormatSpecifier(),
8190 FmtExpr, InFunctionCall);
8191 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8192 << 0 << Other.Range;
8193 break;
8194
8195 case MK::NoMatchPedantic:
8196 EmitDiagnostic(S,
8197 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8198 << buildFormatSpecifier()
8199 << Other.buildFormatSpecifier(),
8200 FmtExpr, InFunctionCall);
8201 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8202 << 0 << Other.Range;
8203 break;
8204
8205 case MK::NoMatchSignedness:
8206 EmitDiagnostic(S,
8207 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8208 << buildFormatSpecifier()
8209 << Other.buildFormatSpecifier(),
8210 FmtExpr, InFunctionCall);
8211 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8212 << 0 << Other.Range;
8213 break;
8214 }
8215 return !HadError;
8216}
8217
8218bool DecomposePrintfHandler::GetSpecifiers(
8219 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8220 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8222 StringRef Data = FSL->getString();
8223 const char *Str = Data.data();
8224 llvm::SmallBitVector BV;
8225 UncoveredArgHandler UA;
8226 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8227 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8228 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8229 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8230 UA, Args);
8231
8233 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8235 H.DoneProcessing();
8236 if (H.HadError)
8237 return false;
8238
8239 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8240 const EquatableFormatArgument &B) {
8241 return A.getPosition() < B.getPosition();
8242 });
8243 return true;
8244}
8245
8246bool DecomposePrintfHandler::HandlePrintfSpecifier(
8247 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8248 unsigned specifierLen, const TargetInfo &Target) {
8249 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8250 specifierLen, Target)) {
8251 HadError = true;
8252 return false;
8253 }
8254
8255 // Do not add any specifiers to the list for %%. This is possibly incorrect
8256 // if using a precision/width with a data argument, but that combination is
8257 // meaningless and we wouldn't know which format to attach the
8258 // precision/width to.
8259 const auto &CS = FS.getConversionSpecifier();
8261 return true;
8262
8263 // have to patch these to have the right ModifierFor if they are used
8264 const unsigned Unset = ~0;
8265 unsigned FieldWidthIndex = Unset;
8266 unsigned PrecisionIndex = Unset;
8267
8268 // field width?
8269 const auto &FieldWidth = FS.getFieldWidth();
8270 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8271 FieldWidthIndex = Specs.size();
8272 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8273 getLocationOfByte(FieldWidth.getStart()),
8275 FieldWidth.getArgType(S.Context),
8276 EquatableFormatArgument::FAR_FieldWidth,
8277 EquatableFormatArgument::SS_None,
8278 FieldWidth.usesPositionalArg()
8279 ? FieldWidth.getPositionalArgIndex() - 1
8280 : FieldWidthIndex,
8281 0);
8282 }
8283 // precision?
8284 const auto &Precision = FS.getPrecision();
8285 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8286 PrecisionIndex = Specs.size();
8287 Specs.emplace_back(
8288 getSpecifierRange(startSpecifier, specifierLen),
8289 getLocationOfByte(Precision.getStart()),
8291 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8292 EquatableFormatArgument::SS_None,
8293 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8294 : PrecisionIndex,
8295 0);
8296 }
8297
8298 // this specifier
8299 unsigned SpecIndex =
8300 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8301 if (FieldWidthIndex != Unset)
8302 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8303 if (PrecisionIndex != Unset)
8304 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8305
8306 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8307 if (FS.isPrivate())
8308 Sensitivity = EquatableFormatArgument::SS_Private;
8309 else if (FS.isPublic())
8310 Sensitivity = EquatableFormatArgument::SS_Public;
8311 else if (FS.isSensitive())
8312 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8313 else
8314 Sensitivity = EquatableFormatArgument::SS_None;
8315
8316 Specs.emplace_back(
8317 getSpecifierRange(startSpecifier, specifierLen),
8318 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8319 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8320 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8321
8322 // auxiliary argument?
8325 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8326 getLocationOfByte(CS.getStart()),
8328 CS.getCharacters(),
8330 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8331 SpecIndex + 1, SpecIndex);
8332 }
8333 return true;
8334}
8335
8336// Determines if the specified is a C++ class or struct containing
8337// a member with the specified name and kind (e.g. a CXXMethodDecl named
8338// "c_str()").
8339template<typename MemberKind>
8341CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8342 auto *RD = Ty->getAsCXXRecordDecl();
8344
8345 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8346 return Results;
8347
8348 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8351
8352 // We just need to include all members of the right kind turned up by the
8353 // filter, at this point.
8354 if (S.LookupQualifiedName(R, RD))
8355 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8356 NamedDecl *decl = (*I)->getUnderlyingDecl();
8357 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8358 Results.insert(FK);
8359 }
8360 return Results;
8361}
8362
8363/// Check if we could call '.c_str()' on an object.
8364///
8365/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8366/// allow the call, or if it would be ambiguous).
8368 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8369
8370 MethodSet Results =
8371 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8372 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8373 MI != ME; ++MI)
8374 if ((*MI)->getMinRequiredArguments() == 0)
8375 return true;
8376 return false;
8377}
8378
8379// Check if a (w)string was passed when a (w)char* was needed, and offer a
8380// better diagnostic if so. AT is assumed to be valid.
8381// Returns true when a c_str() conversion method is found.
8382bool CheckPrintfHandler::checkForCStrMembers(
8383 const analyze_printf::ArgType &AT, const Expr *E) {
8384 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8385
8386 MethodSet Results =
8388
8389 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8390 MI != ME; ++MI) {
8391 const CXXMethodDecl *Method = *MI;
8392 if (Method->getMinRequiredArguments() == 0 &&
8393 AT.matchesType(S.Context, Method->getReturnType())) {
8394 // FIXME: Suggest parens if the expression needs them.
8396 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8397 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8398 return true;
8399 }
8400 }
8401
8402 return false;
8403}
8404
8405bool CheckPrintfHandler::HandlePrintfSpecifier(
8406 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8407 unsigned specifierLen, const TargetInfo &Target) {
8408 using namespace analyze_format_string;
8409 using namespace analyze_printf;
8410
8411 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8412
8413 if (FS.consumesDataArgument()) {
8414 if (atFirstArg) {
8415 atFirstArg = false;
8416 usesPositionalArgs = FS.usesPositionalArg();
8417 }
8418 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8419 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8420 startSpecifier, specifierLen);
8421 return false;
8422 }
8423 }
8424
8425 // First check if the field width, precision, and conversion specifier
8426 // have matching data arguments.
8427 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8428 startSpecifier, specifierLen)) {
8429 return false;
8430 }
8431
8432 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8433 startSpecifier, specifierLen)) {
8434 return false;
8435 }
8436
8437 if (!CS.consumesDataArgument()) {
8438 // FIXME: Technically specifying a precision or field width here
8439 // makes no sense. Worth issuing a warning at some point.
8440 return true;
8441 }
8442
8443 // Consume the argument.
8444 unsigned argIndex = FS.getArgIndex();
8445 if (argIndex < NumDataArgs) {
8446 // The check to see if the argIndex is valid will come later.
8447 // We set the bit here because we may exit early from this
8448 // function if we encounter some other error.
8449 CoveredArgs.set(argIndex);
8450 }
8451
8452 // FreeBSD kernel extensions.
8453 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8454 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8455 // We need at least two arguments.
8456 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8457 return false;
8458
8459 if (HasFormatArguments()) {
8460 // Claim the second argument.
8461 CoveredArgs.set(argIndex + 1);
8462
8463 // Type check the first argument (int for %b, pointer for %D)
8464 const Expr *Ex = getDataArg(argIndex);
8465 const analyze_printf::ArgType &AT =
8466 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8467 ? ArgType(S.Context.IntTy)
8468 : ArgType::CPointerTy;
8469 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8470 EmitFormatDiagnostic(
8471 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8472 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8473 << false << Ex->getSourceRange(),
8474 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8475 getSpecifierRange(startSpecifier, specifierLen));
8476
8477 // Type check the second argument (char * for both %b and %D)
8478 Ex = getDataArg(argIndex + 1);
8480 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8481 EmitFormatDiagnostic(
8482 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8483 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8484 << false << Ex->getSourceRange(),
8485 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8486 getSpecifierRange(startSpecifier, specifierLen));
8487 }
8488 return true;
8489 }
8490
8491 // Check for using an Objective-C specific conversion specifier
8492 // in a non-ObjC literal.
8493 if (!allowsObjCArg() && CS.isObjCArg()) {
8494 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8495 specifierLen);
8496 }
8497
8498 // %P can only be used with os_log.
8499 if (FSType != FormatStringType::OSLog &&
8500 CS.getKind() == ConversionSpecifier::PArg) {
8501 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8502 specifierLen);
8503 }
8504
8505 // %n is not allowed with os_log.
8506 if (FSType == FormatStringType::OSLog &&
8507 CS.getKind() == ConversionSpecifier::nArg) {
8508 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8509 getLocationOfByte(CS.getStart()),
8510 /*IsStringLocation*/ false,
8511 getSpecifierRange(startSpecifier, specifierLen));
8512
8513 return true;
8514 }
8515
8516 // Only scalars are allowed for os_trace.
8517 if (FSType == FormatStringType::OSTrace &&
8518 (CS.getKind() == ConversionSpecifier::PArg ||
8519 CS.getKind() == ConversionSpecifier::sArg ||
8520 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8521 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8522 specifierLen);
8523 }
8524
8525 // Check for use of public/private annotation outside of os_log().
8526 if (FSType != FormatStringType::OSLog) {
8527 if (FS.isPublic().isSet()) {
8528 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8529 << "public",
8530 getLocationOfByte(FS.isPublic().getPosition()),
8531 /*IsStringLocation*/ false,
8532 getSpecifierRange(startSpecifier, specifierLen));
8533 }
8534 if (FS.isPrivate().isSet()) {
8535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8536 << "private",
8537 getLocationOfByte(FS.isPrivate().getPosition()),
8538 /*IsStringLocation*/ false,
8539 getSpecifierRange(startSpecifier, specifierLen));
8540 }
8541 }
8542
8543 const llvm::Triple &Triple = Target.getTriple();
8544 if (CS.getKind() == ConversionSpecifier::nArg &&
8545 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8546 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8547 getLocationOfByte(CS.getStart()),
8548 /*IsStringLocation*/ false,
8549 getSpecifierRange(startSpecifier, specifierLen));
8550 }
8551
8552 // Check for invalid use of field width
8553 if (!FS.hasValidFieldWidth()) {
8554 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8555 startSpecifier, specifierLen);
8556 }
8557
8558 // Check for invalid use of precision
8559 if (!FS.hasValidPrecision()) {
8560 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8561 startSpecifier, specifierLen);
8562 }
8563
8564 // Precision is mandatory for %P specifier.
8565 if (CS.getKind() == ConversionSpecifier::PArg &&
8567 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8568 getLocationOfByte(startSpecifier),
8569 /*IsStringLocation*/ false,
8570 getSpecifierRange(startSpecifier, specifierLen));
8571 }
8572
8573 // Check each flag does not conflict with any other component.
8575 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8576 if (!FS.hasValidLeadingZeros())
8577 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8578 if (!FS.hasValidPlusPrefix())
8579 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8580 if (!FS.hasValidSpacePrefix())
8581 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8582 if (!FS.hasValidAlternativeForm())
8583 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8584 if (!FS.hasValidLeftJustified())
8585 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8586
8587 // Check that flags are not ignored by another flag
8588 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8589 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8590 startSpecifier, specifierLen);
8591 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8592 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8593 startSpecifier, specifierLen);
8594
8595 // Check the length modifier is valid with the given conversion specifier.
8597 S.getLangOpts()))
8598 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8599 diag::warn_format_nonsensical_length);
8600 else if (!FS.hasStandardLengthModifier())
8601 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8603 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8604 diag::warn_format_non_standard_conversion_spec);
8605
8607 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8608
8609 // The remaining checks depend on the data arguments.
8610 if (!HasFormatArguments())
8611 return true;
8612
8613 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8614 return false;
8615
8616 const Expr *Arg = getDataArg(argIndex);
8617 if (!Arg)
8618 return true;
8619
8620 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8621}
8622
8623static bool requiresParensToAddCast(const Expr *E) {
8624 // FIXME: We should have a general way to reason about operator
8625 // precedence and whether parens are actually needed here.
8626 // Take care of a few common cases where they aren't.
8627 const Expr *Inside = E->IgnoreImpCasts();
8628 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8629 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8630
8631 switch (Inside->getStmtClass()) {
8632 case Stmt::ArraySubscriptExprClass:
8633 case Stmt::CallExprClass:
8634 case Stmt::CharacterLiteralClass:
8635 case Stmt::CXXBoolLiteralExprClass:
8636 case Stmt::DeclRefExprClass:
8637 case Stmt::FloatingLiteralClass:
8638 case Stmt::IntegerLiteralClass:
8639 case Stmt::MemberExprClass:
8640 case Stmt::ObjCArrayLiteralClass:
8641 case Stmt::ObjCBoolLiteralExprClass:
8642 case Stmt::ObjCBoxedExprClass:
8643 case Stmt::ObjCDictionaryLiteralClass:
8644 case Stmt::ObjCEncodeExprClass:
8645 case Stmt::ObjCIvarRefExprClass:
8646 case Stmt::ObjCMessageExprClass:
8647 case Stmt::ObjCPropertyRefExprClass:
8648 case Stmt::ObjCStringLiteralClass:
8649 case Stmt::ObjCSubscriptRefExprClass:
8650 case Stmt::ParenExprClass:
8651 case Stmt::StringLiteralClass:
8652 case Stmt::UnaryOperatorClass:
8653 return false;
8654 default:
8655 return true;
8656 }
8657}
8658
8659static std::pair<QualType, StringRef>
8661 QualType IntendedTy,
8662 const Expr *E) {
8663 // Use a 'while' to peel off layers of typedefs.
8664 QualType TyTy = IntendedTy;
8665 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8666 StringRef Name = UserTy->getDecl()->getName();
8667 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8668 .Case("CFIndex", Context.getNSIntegerType())
8669 .Case("NSInteger", Context.getNSIntegerType())
8670 .Case("NSUInteger", Context.getNSUIntegerType())
8671 .Case("SInt32", Context.IntTy)
8672 .Case("UInt32", Context.UnsignedIntTy)
8673 .Default(QualType());
8674
8675 if (!CastTy.isNull())
8676 return std::make_pair(CastTy, Name);
8677
8678 TyTy = UserTy->desugar();
8679 }
8680
8681 // Strip parens if necessary.
8682 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8683 return shouldNotPrintDirectly(Context,
8684 PE->getSubExpr()->getType(),
8685 PE->getSubExpr());
8686
8687 // If this is a conditional expression, then its result type is constructed
8688 // via usual arithmetic conversions and thus there might be no necessary
8689 // typedef sugar there. Recurse to operands to check for NSInteger &
8690 // Co. usage condition.
8691 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8692 QualType TrueTy, FalseTy;
8693 StringRef TrueName, FalseName;
8694
8695 std::tie(TrueTy, TrueName) =
8696 shouldNotPrintDirectly(Context,
8697 CO->getTrueExpr()->getType(),
8698 CO->getTrueExpr());
8699 std::tie(FalseTy, FalseName) =
8700 shouldNotPrintDirectly(Context,
8701 CO->getFalseExpr()->getType(),
8702 CO->getFalseExpr());
8703
8704 if (TrueTy == FalseTy)
8705 return std::make_pair(TrueTy, TrueName);
8706 else if (TrueTy.isNull())
8707 return std::make_pair(FalseTy, FalseName);
8708 else if (FalseTy.isNull())
8709 return std::make_pair(TrueTy, TrueName);
8710 }
8711
8712 return std::make_pair(QualType(), StringRef());
8713}
8714
8715/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8716/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8717/// type do not count.
8718static bool
8720 QualType From = ICE->getSubExpr()->getType();
8721 QualType To = ICE->getType();
8722 // It's an integer promotion if the destination type is the promoted
8723 // source type.
8724 if (ICE->getCastKind() == CK_IntegralCast &&
8726 S.Context.getPromotedIntegerType(From) == To)
8727 return true;
8728 // Look through vector types, since we do default argument promotion for
8729 // those in OpenCL.
8730 if (const auto *VecTy = From->getAs<ExtVectorType>())
8731 From = VecTy->getElementType();
8732 if (const auto *VecTy = To->getAs<ExtVectorType>())
8733 To = VecTy->getElementType();
8734 // It's a floating promotion if the source type is a lower rank.
8735 return ICE->getCastKind() == CK_FloatingCast &&
8736 S.Context.getFloatingTypeOrder(From, To) < 0;
8737}
8738
8741 DiagnosticsEngine &Diags, SourceLocation Loc) {
8743 if (Diags.isIgnored(
8744 diag::warn_format_conversion_argument_type_mismatch_signedness,
8745 Loc) ||
8746 Diags.isIgnored(
8747 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8748 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8750 }
8751 }
8752 return Match;
8753}
8754
8755bool
8756CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8757 const char *StartSpecifier,
8758 unsigned SpecifierLen,
8759 const Expr *E) {
8760 using namespace analyze_format_string;
8761 using namespace analyze_printf;
8762
8763 // Now type check the data expression that matches the
8764 // format specifier.
8765 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8766 if (!AT.isValid())
8767 return true;
8768
8769 QualType ExprTy = E->getType();
8770 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8771 ExprTy = TET->getUnderlyingExpr()->getType();
8772 }
8773
8774 // When using the format attribute in C++, you can receive a function or an
8775 // array that will necessarily decay to a pointer when passed to the final
8776 // format consumer. Apply decay before type comparison.
8777 if (ExprTy->canDecayToPointerType())
8778 ExprTy = S.Context.getDecayedType(ExprTy);
8779
8780 // Diagnose attempts to print a boolean value as a character. Unlike other
8781 // -Wformat diagnostics, this is fine from a type perspective, but it still
8782 // doesn't make sense.
8785 const CharSourceRange &CSR =
8786 getSpecifierRange(StartSpecifier, SpecifierLen);
8787 SmallString<4> FSString;
8788 llvm::raw_svector_ostream os(FSString);
8789 FS.toString(os);
8790 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8791 << FSString,
8792 E->getExprLoc(), false, CSR);
8793 return true;
8794 }
8795
8796 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8797 // dumping raw class data (like is-a pointer), not actual data.
8799 ExprTy->isObjCObjectPointerType()) {
8800 const CharSourceRange &CSR =
8801 getSpecifierRange(StartSpecifier, SpecifierLen);
8802 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8803 E->getExprLoc(), false, CSR);
8804 return true;
8805 }
8806
8807 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8809 ArgType::MatchKind OrigMatch = Match;
8810
8812 if (Match == ArgType::Match)
8813 return true;
8814
8815 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8816 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8817
8818 // Look through argument promotions for our error message's reported type.
8819 // This includes the integral and floating promotions, but excludes array
8820 // and function pointer decay (seeing that an argument intended to be a
8821 // string has type 'char [6]' is probably more confusing than 'char *') and
8822 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8823 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8824 if (isArithmeticArgumentPromotion(S, ICE)) {
8825 E = ICE->getSubExpr();
8826 ExprTy = E->getType();
8827
8828 // Check if we didn't match because of an implicit cast from a 'char'
8829 // or 'short' to an 'int'. This is done because printf is a varargs
8830 // function.
8831 if (ICE->getType() == S.Context.IntTy ||
8832 ICE->getType() == S.Context.UnsignedIntTy) {
8833 // All further checking is done on the subexpression
8834 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8835 if (OrigMatch == ArgType::NoMatchSignedness &&
8836 ImplicitMatch != ArgType::NoMatchSignedness)
8837 // If the original match was a signedness match this match on the
8838 // implicit cast type also need to be signedness match otherwise we
8839 // might introduce new unexpected warnings from -Wformat-signedness.
8840 return true;
8841 ImplicitMatch = handleFormatSignedness(
8842 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8843 if (ImplicitMatch == ArgType::Match)
8844 return true;
8845 }
8846 }
8847 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8848 // Special case for 'a', which has type 'int' in C.
8849 // Note, however, that we do /not/ want to treat multibyte constants like
8850 // 'MooV' as characters! This form is deprecated but still exists. In
8851 // addition, don't treat expressions as of type 'char' if one byte length
8852 // modifier is provided.
8853 if (ExprTy == S.Context.IntTy &&
8855 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8856 ExprTy = S.Context.CharTy;
8857 // To improve check results, we consider a character literal in C
8858 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8859 // more likely a type confusion situation, so we will suggest to
8860 // use '%hhd' instead by discarding the MatchPromotion.
8861 if (Match == ArgType::MatchPromotion)
8863 }
8864 }
8865 if (Match == ArgType::MatchPromotion) {
8866 // WG14 N2562 only clarified promotions in *printf
8867 // For NSLog in ObjC, just preserve -Wformat behavior
8868 if (!S.getLangOpts().ObjC &&
8869 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8870 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8871 return true;
8873 }
8874 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8875 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8876 Match = ImplicitMatch;
8877 assert(Match != ArgType::MatchPromotion);
8878
8879 // Look through unscoped enums to their underlying type.
8880 bool IsEnum = false;
8881 bool IsScopedEnum = false;
8882 QualType IntendedTy = ExprTy;
8883 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8884 IntendedTy = ED->getIntegerType();
8885 if (!ED->isScoped()) {
8886 ExprTy = IntendedTy;
8887 // This controls whether we're talking about the underlying type or not,
8888 // which we only want to do when it's an unscoped enum.
8889 IsEnum = true;
8890 } else {
8891 IsScopedEnum = true;
8892 }
8893 }
8894
8895 // %C in an Objective-C context prints a unichar, not a wchar_t.
8896 // If the argument is an integer of some kind, believe the %C and suggest
8897 // a cast instead of changing the conversion specifier.
8898 if (isObjCContext() &&
8901 !ExprTy->isCharType()) {
8902 // 'unichar' is defined as a typedef of unsigned short, but we should
8903 // prefer using the typedef if it is visible.
8904 IntendedTy = S.Context.UnsignedShortTy;
8905
8906 // While we are here, check if the value is an IntegerLiteral that happens
8907 // to be within the valid range.
8908 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8909 const llvm::APInt &V = IL->getValue();
8910 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8911 return true;
8912 }
8913
8914 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8916 if (S.LookupName(Result, S.getCurScope())) {
8917 NamedDecl *ND = Result.getFoundDecl();
8918 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8919 if (TD->getUnderlyingType() == IntendedTy)
8920 IntendedTy =
8922 /*Qualifier=*/std::nullopt, TD);
8923 }
8924 }
8925 }
8926
8927 // Special-case some of Darwin's platform-independence types by suggesting
8928 // casts to primitive types that are known to be large enough.
8929 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8930 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8931 QualType CastTy;
8932 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8933 if (!CastTy.isNull()) {
8934 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8935 // (long in ASTContext). Only complain to pedants or when they're the
8936 // underlying type of a scoped enum (which always needs a cast).
8937 if (!IsScopedEnum &&
8938 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8939 (AT.isSizeT() || AT.isPtrdiffT()) &&
8940 AT.matchesType(S.Context, CastTy))
8942 IntendedTy = CastTy;
8943 ShouldNotPrintDirectly = true;
8944 }
8945 }
8946
8947 // We may be able to offer a FixItHint if it is a supported type.
8948 PrintfSpecifier fixedFS = FS;
8949 bool Success =
8950 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8951
8952 if (Success) {
8953 // Get the fix string from the fixed format specifier
8954 SmallString<16> buf;
8955 llvm::raw_svector_ostream os(buf);
8956 fixedFS.toString(os);
8957
8958 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8959
8960 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8961 unsigned Diag;
8962 switch (Match) {
8963 case ArgType::Match:
8966 llvm_unreachable("expected non-matching");
8968 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8969 break;
8971 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8972 break;
8974 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8975 break;
8976 case ArgType::NoMatch:
8977 Diag = diag::warn_format_conversion_argument_type_mismatch;
8978 break;
8979 }
8980
8981 // In this case, the specifier is wrong and should be changed to match
8982 // the argument.
8983 EmitFormatDiagnostic(S.PDiag(Diag)
8985 << IntendedTy << IsEnum << E->getSourceRange(),
8986 E->getBeginLoc(),
8987 /*IsStringLocation*/ false, SpecRange,
8988 FixItHint::CreateReplacement(SpecRange, os.str()));
8989 } else {
8990 // The canonical type for formatting this value is different from the
8991 // actual type of the expression. (This occurs, for example, with Darwin's
8992 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8993 // should be printed as 'long' for 64-bit compatibility.)
8994 // Rather than emitting a normal format/argument mismatch, we want to
8995 // add a cast to the recommended type (and correct the format string
8996 // if necessary). We should also do so for scoped enumerations.
8997 SmallString<16> CastBuf;
8998 llvm::raw_svector_ostream CastFix(CastBuf);
8999 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9000 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9001 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9002
9004 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9005 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9006 E->getExprLoc());
9007 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9008 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9009
9010 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9011 // If there's already a cast present, just replace it.
9012 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9013 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9014
9015 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9016 // If the expression has high enough precedence,
9017 // just write the C-style cast.
9018 Hints.push_back(
9019 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9020 } else {
9021 // Otherwise, add parens around the expression as well as the cast.
9022 CastFix << "(";
9023 Hints.push_back(
9024 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9025
9026 // We don't use getLocForEndOfToken because it returns invalid source
9027 // locations for macro expansions (by design).
9031 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9032 }
9033
9034 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9035 // The expression has a type that should not be printed directly.
9036 // We extract the name from the typedef because we don't want to show
9037 // the underlying type in the diagnostic.
9038 StringRef Name;
9039 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9040 Name = TypedefTy->getDecl()->getName();
9041 else
9042 Name = CastTyName;
9043 unsigned Diag = Match == ArgType::NoMatchPedantic
9044 ? diag::warn_format_argument_needs_cast_pedantic
9045 : diag::warn_format_argument_needs_cast;
9046 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9047 << E->getSourceRange(),
9048 E->getBeginLoc(), /*IsStringLocation=*/false,
9049 SpecRange, Hints);
9050 } else {
9051 // In this case, the expression could be printed using a different
9052 // specifier, but we've decided that the specifier is probably correct
9053 // and we should cast instead. Just use the normal warning message.
9054
9055 unsigned Diag =
9056 IsScopedEnum
9057 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9058 : diag::warn_format_conversion_argument_type_mismatch;
9059
9060 EmitFormatDiagnostic(
9061 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9062 << IsEnum << E->getSourceRange(),
9063 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9064 }
9065 }
9066 } else {
9067 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9068 SpecifierLen);
9069 // Since the warning for passing non-POD types to variadic functions
9070 // was deferred until now, we emit a warning for non-POD
9071 // arguments here.
9072 bool EmitTypeMismatch = false;
9073 switch (S.isValidVarArgType(ExprTy)) {
9074 case VarArgKind::Valid:
9076 unsigned Diag;
9077 switch (Match) {
9078 case ArgType::Match:
9081 llvm_unreachable("expected non-matching");
9083 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9084 break;
9086 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9087 break;
9089 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9090 break;
9091 case ArgType::NoMatch:
9092 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9093 ? diag::err_format_conversion_argument_type_mismatch
9094 : diag::warn_format_conversion_argument_type_mismatch;
9095 break;
9096 }
9097
9098 EmitFormatDiagnostic(
9099 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9100 << IsEnum << CSR << E->getSourceRange(),
9101 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9102 break;
9103 }
9106 if (CallType == VariadicCallType::DoesNotApply) {
9107 EmitTypeMismatch = true;
9108 } else {
9109 EmitFormatDiagnostic(
9110 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9111 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9112 << AT.getRepresentativeTypeName(S.Context) << CSR
9113 << E->getSourceRange(),
9114 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9115 checkForCStrMembers(AT, E);
9116 }
9117 break;
9118
9120 if (CallType == VariadicCallType::DoesNotApply)
9121 EmitTypeMismatch = true;
9122 else if (ExprTy->isObjCObjectType())
9123 EmitFormatDiagnostic(
9124 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9125 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9126 << AT.getRepresentativeTypeName(S.Context) << CSR
9127 << E->getSourceRange(),
9128 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9129 else
9130 // FIXME: If this is an initializer list, suggest removing the braces
9131 // or inserting a cast to the target type.
9132 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9133 << isa<InitListExpr>(E) << ExprTy << CallType
9135 break;
9136 }
9137
9138 if (EmitTypeMismatch) {
9139 // The function is not variadic, so we do not generate warnings about
9140 // being allowed to pass that object as a variadic argument. Instead,
9141 // since there are inherently no printf specifiers for types which cannot
9142 // be passed as variadic arguments, emit a plain old specifier mismatch
9143 // argument.
9144 EmitFormatDiagnostic(
9145 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9146 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9147 << E->getSourceRange(),
9148 E->getBeginLoc(), false, CSR);
9149 }
9150
9151 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9152 "format string specifier index out of range");
9153 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9154 }
9155
9156 return true;
9157}
9158
9159//===--- CHECK: Scanf format string checking ------------------------------===//
9160
9161namespace {
9162
9163class CheckScanfHandler : public CheckFormatHandler {
9164public:
9165 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9166 const Expr *origFormatExpr, FormatStringType type,
9167 unsigned firstDataArg, unsigned numDataArgs,
9168 const char *beg, Sema::FormatArgumentPassingKind APK,
9169 ArrayRef<const Expr *> Args, unsigned formatIdx,
9170 bool inFunctionCall, VariadicCallType CallType,
9171 llvm::SmallBitVector &CheckedVarArgs,
9172 UncoveredArgHandler &UncoveredArg)
9173 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9174 numDataArgs, beg, APK, Args, formatIdx,
9175 inFunctionCall, CallType, CheckedVarArgs,
9176 UncoveredArg) {}
9177
9178 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9179 const char *startSpecifier,
9180 unsigned specifierLen) override;
9181
9182 bool HandleInvalidScanfConversionSpecifier(
9183 const analyze_scanf::ScanfSpecifier &FS,
9184 const char *startSpecifier,
9185 unsigned specifierLen) override;
9186
9187 void HandleIncompleteScanList(const char *start, const char *end) override;
9188};
9189
9190} // namespace
9191
9192void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9193 const char *end) {
9194 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9195 getLocationOfByte(end), /*IsStringLocation*/true,
9196 getSpecifierRange(start, end - start));
9197}
9198
9199bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9201 const char *startSpecifier,
9202 unsigned specifierLen) {
9205
9206 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9207 getLocationOfByte(CS.getStart()),
9208 startSpecifier, specifierLen,
9209 CS.getStart(), CS.getLength());
9210}
9211
9212bool CheckScanfHandler::HandleScanfSpecifier(
9214 const char *startSpecifier,
9215 unsigned specifierLen) {
9216 using namespace analyze_scanf;
9217 using namespace analyze_format_string;
9218
9219 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9220
9221 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9222 // be used to decide if we are using positional arguments consistently.
9223 if (FS.consumesDataArgument()) {
9224 if (atFirstArg) {
9225 atFirstArg = false;
9226 usesPositionalArgs = FS.usesPositionalArg();
9227 }
9228 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9229 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9230 startSpecifier, specifierLen);
9231 return false;
9232 }
9233 }
9234
9235 // Check if the field with is non-zero.
9236 const OptionalAmount &Amt = FS.getFieldWidth();
9238 if (Amt.getConstantAmount() == 0) {
9239 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9240 Amt.getConstantLength());
9241 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9242 getLocationOfByte(Amt.getStart()),
9243 /*IsStringLocation*/true, R,
9245 }
9246 }
9247
9248 if (!FS.consumesDataArgument()) {
9249 // FIXME: Technically specifying a precision or field width here
9250 // makes no sense. Worth issuing a warning at some point.
9251 return true;
9252 }
9253
9254 // Consume the argument.
9255 unsigned argIndex = FS.getArgIndex();
9256 if (argIndex < NumDataArgs) {
9257 // The check to see if the argIndex is valid will come later.
9258 // We set the bit here because we may exit early from this
9259 // function if we encounter some other error.
9260 CoveredArgs.set(argIndex);
9261 }
9262
9263 // Check the length modifier is valid with the given conversion specifier.
9265 S.getLangOpts()))
9266 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9267 diag::warn_format_nonsensical_length);
9268 else if (!FS.hasStandardLengthModifier())
9269 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9271 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9272 diag::warn_format_non_standard_conversion_spec);
9273
9275 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9276
9277 // The remaining checks depend on the data arguments.
9278 if (!HasFormatArguments())
9279 return true;
9280
9281 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9282 return false;
9283
9284 // Check that the argument type matches the format specifier.
9285 const Expr *Ex = getDataArg(argIndex);
9286 if (!Ex)
9287 return true;
9288
9290
9291 if (!AT.isValid()) {
9292 return true;
9293 }
9294
9296 AT.matchesType(S.Context, Ex->getType());
9299 return true;
9302
9303 ScanfSpecifier fixedFS = FS;
9304 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9305 S.getLangOpts(), S.Context);
9306
9307 unsigned Diag =
9308 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9309 : Signedness
9310 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9311 : diag::warn_format_conversion_argument_type_mismatch;
9312
9313 if (Success) {
9314 // Get the fix string from the fixed format specifier.
9315 SmallString<128> buf;
9316 llvm::raw_svector_ostream os(buf);
9317 fixedFS.toString(os);
9318
9319 EmitFormatDiagnostic(
9321 << Ex->getType() << false << Ex->getSourceRange(),
9322 Ex->getBeginLoc(),
9323 /*IsStringLocation*/ false,
9324 getSpecifierRange(startSpecifier, specifierLen),
9326 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9327 } else {
9328 EmitFormatDiagnostic(S.PDiag(Diag)
9330 << Ex->getType() << false << Ex->getSourceRange(),
9331 Ex->getBeginLoc(),
9332 /*IsStringLocation*/ false,
9333 getSpecifierRange(startSpecifier, specifierLen));
9334 }
9335
9336 return true;
9337}
9338
9339static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9341 const StringLiteral *Fmt,
9343 const Expr *FmtExpr, bool InFunctionCall) {
9344 bool HadError = false;
9345 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9346 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9347 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9348 // In positional-style format strings, the same specifier can appear
9349 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9350 // are sorted by getPosition(), and we process each range of equal
9351 // getPosition() values as one group.
9352 // RefArgs are taken from a string literal that was given to
9353 // attribute(format_matches), and if we got this far, we have already
9354 // verified that if it has positional specifiers that appear in multiple
9355 // locations, then they are all mutually compatible. What's left for us to
9356 // do is verify that all specifiers with the same position in FmtArgs are
9357 // compatible with the RefArgs specifiers. We check each specifier from
9358 // FmtArgs against the first member of the RefArgs group.
9359 for (; FmtIter < FmtEnd; ++FmtIter) {
9360 // Clang does not diagnose missing format specifiers in positional-style
9361 // strings (TODO: which it probably should do, as it is UB to skip over a
9362 // format argument). Skip specifiers if needed.
9363 if (FmtIter->getPosition() < RefIter->getPosition())
9364 continue;
9365
9366 // Delimits a new getPosition() value.
9367 if (FmtIter->getPosition() > RefIter->getPosition())
9368 break;
9369
9370 HadError |=
9371 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9372 }
9373
9374 // Jump RefIter to the start of the next group.
9375 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9376 return Arg.getPosition() != RefIter->getPosition();
9377 });
9378 }
9379
9380 if (FmtIter < FmtEnd) {
9381 CheckFormatHandler::EmitFormatDiagnostic(
9382 S, InFunctionCall, FmtExpr,
9383 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9384 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9385 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9386 } else if (RefIter < RefEnd) {
9387 CheckFormatHandler::EmitFormatDiagnostic(
9388 S, InFunctionCall, FmtExpr,
9389 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9390 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9391 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9392 << 1 << RefIter->getSourceRange();
9393 }
9394 return !HadError;
9395}
9396
9398 Sema &S, const FormatStringLiteral *FExpr,
9399 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9401 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9402 bool inFunctionCall, VariadicCallType CallType,
9403 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9404 bool IgnoreStringsWithoutSpecifiers) {
9405 // CHECK: is the format string a wide literal?
9406 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9407 CheckFormatHandler::EmitFormatDiagnostic(
9408 S, inFunctionCall, Args[format_idx],
9409 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9410 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9411 return;
9412 }
9413
9414 // Str - The format string. NOTE: this is NOT null-terminated!
9415 StringRef StrRef = FExpr->getString();
9416 const char *Str = StrRef.data();
9417 // Account for cases where the string literal is truncated in a declaration.
9418 const ConstantArrayType *T =
9419 S.Context.getAsConstantArrayType(FExpr->getType());
9420 assert(T && "String literal not of constant array type!");
9421 size_t TypeSize = T->getZExtSize();
9422 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9423 const unsigned numDataArgs = Args.size() - firstDataArg;
9424
9425 if (IgnoreStringsWithoutSpecifiers &&
9427 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9428 return;
9429
9430 // Emit a warning if the string literal is truncated and does not contain an
9431 // embedded null character.
9432 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9433 CheckFormatHandler::EmitFormatDiagnostic(
9434 S, inFunctionCall, Args[format_idx],
9435 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9436 FExpr->getBeginLoc(),
9437 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9438 return;
9439 }
9440
9441 // CHECK: empty format string?
9442 if (StrLen == 0 && numDataArgs > 0) {
9443 CheckFormatHandler::EmitFormatDiagnostic(
9444 S, inFunctionCall, Args[format_idx],
9445 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9446 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9447 return;
9448 }
9449
9454 bool IsObjC =
9456 if (ReferenceFormatString == nullptr) {
9457 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9458 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9459 inFunctionCall, CallType, CheckedVarArgs,
9460 UncoveredArg);
9461
9463 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9466 H.DoneProcessing();
9467 } else {
9469 Type, ReferenceFormatString, FExpr->getFormatString(),
9470 inFunctionCall ? nullptr : Args[format_idx]);
9471 }
9472 } else if (Type == FormatStringType::Scanf) {
9473 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9474 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9475 CallType, CheckedVarArgs, UncoveredArg);
9476
9478 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9479 H.DoneProcessing();
9480 } // TODO: handle other formats
9481}
9482
9484 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9485 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9490 return true;
9491
9492 bool IsObjC =
9495 FormatStringLiteral RefLit = AuthoritativeFormatString;
9496 FormatStringLiteral TestLit = TestedFormatString;
9497 const Expr *Arg;
9498 bool DiagAtStringLiteral;
9499 if (FunctionCallArg) {
9500 Arg = FunctionCallArg;
9501 DiagAtStringLiteral = false;
9502 } else {
9503 Arg = TestedFormatString;
9504 DiagAtStringLiteral = true;
9505 }
9506 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9507 AuthoritativeFormatString, Type,
9508 IsObjC, true, RefArgs) &&
9509 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9510 DiagAtStringLiteral, FmtArgs)) {
9511 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9512 TestedFormatString, FmtArgs, Arg,
9513 DiagAtStringLiteral);
9514 }
9515 return false;
9516}
9517
9519 const StringLiteral *Str) {
9524 return true;
9525
9526 FormatStringLiteral RefLit = Str;
9528 bool IsObjC =
9530 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9531 true, Args))
9532 return false;
9533
9534 // Group arguments by getPosition() value, and check that each member of the
9535 // group is compatible with the first member. This verifies that when
9536 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9537 // are mutually compatible. As an optimization, don't test the first member
9538 // against itself.
9539 bool HadError = false;
9540 auto Iter = Args.begin();
9541 auto End = Args.end();
9542 while (Iter != End) {
9543 const auto &FirstInGroup = *Iter;
9544 for (++Iter;
9545 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9546 ++Iter) {
9547 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9548 }
9549 }
9550 return !HadError;
9551}
9552
9554 // Str - The format string. NOTE: this is NOT null-terminated!
9555 StringRef StrRef = FExpr->getString();
9556 const char *Str = StrRef.data();
9557 // Account for cases where the string literal is truncated in a declaration.
9558 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9559 assert(T && "String literal not of constant array type!");
9560 size_t TypeSize = T->getZExtSize();
9561 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9562 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9563 getLangOpts(),
9564 Context.getTargetInfo());
9565}
9566
9567//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9568
9569// Returns the related absolute value function that is larger, of 0 if one
9570// does not exist.
9571static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9572 switch (AbsFunction) {
9573 default:
9574 return 0;
9575
9576 case Builtin::BI__builtin_abs:
9577 return Builtin::BI__builtin_labs;
9578 case Builtin::BI__builtin_labs:
9579 return Builtin::BI__builtin_llabs;
9580 case Builtin::BI__builtin_llabs:
9581 return 0;
9582
9583 case Builtin::BI__builtin_fabsf:
9584 return Builtin::BI__builtin_fabs;
9585 case Builtin::BI__builtin_fabs:
9586 return Builtin::BI__builtin_fabsl;
9587 case Builtin::BI__builtin_fabsl:
9588 return 0;
9589
9590 case Builtin::BI__builtin_cabsf:
9591 return Builtin::BI__builtin_cabs;
9592 case Builtin::BI__builtin_cabs:
9593 return Builtin::BI__builtin_cabsl;
9594 case Builtin::BI__builtin_cabsl:
9595 return 0;
9596
9597 case Builtin::BIabs:
9598 return Builtin::BIlabs;
9599 case Builtin::BIlabs:
9600 return Builtin::BIllabs;
9601 case Builtin::BIllabs:
9602 return 0;
9603
9604 case Builtin::BIfabsf:
9605 return Builtin::BIfabs;
9606 case Builtin::BIfabs:
9607 return Builtin::BIfabsl;
9608 case Builtin::BIfabsl:
9609 return 0;
9610
9611 case Builtin::BIcabsf:
9612 return Builtin::BIcabs;
9613 case Builtin::BIcabs:
9614 return Builtin::BIcabsl;
9615 case Builtin::BIcabsl:
9616 return 0;
9617 }
9618}
9619
9620// Returns the argument type of the absolute value function.
9622 unsigned AbsType) {
9623 if (AbsType == 0)
9624 return QualType();
9625
9627 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9629 return QualType();
9630
9632 if (!FT)
9633 return QualType();
9634
9635 if (FT->getNumParams() != 1)
9636 return QualType();
9637
9638 return FT->getParamType(0);
9639}
9640
9641// Returns the best absolute value function, or zero, based on type and
9642// current absolute value function.
9643static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9644 unsigned AbsFunctionKind) {
9645 unsigned BestKind = 0;
9646 uint64_t ArgSize = Context.getTypeSize(ArgType);
9647 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9648 Kind = getLargerAbsoluteValueFunction(Kind)) {
9649 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9650 if (Context.getTypeSize(ParamType) >= ArgSize) {
9651 if (BestKind == 0)
9652 BestKind = Kind;
9653 else if (Context.hasSameType(ParamType, ArgType)) {
9654 BestKind = Kind;
9655 break;
9656 }
9657 }
9658 }
9659 return BestKind;
9660}
9661
9667
9669 if (T->isIntegralOrEnumerationType())
9670 return AVK_Integer;
9671 if (T->isRealFloatingType())
9672 return AVK_Floating;
9673 if (T->isAnyComplexType())
9674 return AVK_Complex;
9675
9676 llvm_unreachable("Type not integer, floating, or complex");
9677}
9678
9679// Changes the absolute value function to a different type. Preserves whether
9680// the function is a builtin.
9681static unsigned changeAbsFunction(unsigned AbsKind,
9682 AbsoluteValueKind ValueKind) {
9683 switch (ValueKind) {
9684 case AVK_Integer:
9685 switch (AbsKind) {
9686 default:
9687 return 0;
9688 case Builtin::BI__builtin_fabsf:
9689 case Builtin::BI__builtin_fabs:
9690 case Builtin::BI__builtin_fabsl:
9691 case Builtin::BI__builtin_cabsf:
9692 case Builtin::BI__builtin_cabs:
9693 case Builtin::BI__builtin_cabsl:
9694 return Builtin::BI__builtin_abs;
9695 case Builtin::BIfabsf:
9696 case Builtin::BIfabs:
9697 case Builtin::BIfabsl:
9698 case Builtin::BIcabsf:
9699 case Builtin::BIcabs:
9700 case Builtin::BIcabsl:
9701 return Builtin::BIabs;
9702 }
9703 case AVK_Floating:
9704 switch (AbsKind) {
9705 default:
9706 return 0;
9707 case Builtin::BI__builtin_abs:
9708 case Builtin::BI__builtin_labs:
9709 case Builtin::BI__builtin_llabs:
9710 case Builtin::BI__builtin_cabsf:
9711 case Builtin::BI__builtin_cabs:
9712 case Builtin::BI__builtin_cabsl:
9713 return Builtin::BI__builtin_fabsf;
9714 case Builtin::BIabs:
9715 case Builtin::BIlabs:
9716 case Builtin::BIllabs:
9717 case Builtin::BIcabsf:
9718 case Builtin::BIcabs:
9719 case Builtin::BIcabsl:
9720 return Builtin::BIfabsf;
9721 }
9722 case AVK_Complex:
9723 switch (AbsKind) {
9724 default:
9725 return 0;
9726 case Builtin::BI__builtin_abs:
9727 case Builtin::BI__builtin_labs:
9728 case Builtin::BI__builtin_llabs:
9729 case Builtin::BI__builtin_fabsf:
9730 case Builtin::BI__builtin_fabs:
9731 case Builtin::BI__builtin_fabsl:
9732 return Builtin::BI__builtin_cabsf;
9733 case Builtin::BIabs:
9734 case Builtin::BIlabs:
9735 case Builtin::BIllabs:
9736 case Builtin::BIfabsf:
9737 case Builtin::BIfabs:
9738 case Builtin::BIfabsl:
9739 return Builtin::BIcabsf;
9740 }
9741 }
9742 llvm_unreachable("Unable to convert function");
9743}
9744
9745static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9746 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9747 if (!FnInfo)
9748 return 0;
9749
9750 switch (FDecl->getBuiltinID()) {
9751 default:
9752 return 0;
9753 case Builtin::BI__builtin_abs:
9754 case Builtin::BI__builtin_fabs:
9755 case Builtin::BI__builtin_fabsf:
9756 case Builtin::BI__builtin_fabsl:
9757 case Builtin::BI__builtin_labs:
9758 case Builtin::BI__builtin_llabs:
9759 case Builtin::BI__builtin_cabs:
9760 case Builtin::BI__builtin_cabsf:
9761 case Builtin::BI__builtin_cabsl:
9762 case Builtin::BIabs:
9763 case Builtin::BIlabs:
9764 case Builtin::BIllabs:
9765 case Builtin::BIfabs:
9766 case Builtin::BIfabsf:
9767 case Builtin::BIfabsl:
9768 case Builtin::BIcabs:
9769 case Builtin::BIcabsf:
9770 case Builtin::BIcabsl:
9771 return FDecl->getBuiltinID();
9772 }
9773 llvm_unreachable("Unknown Builtin type");
9774}
9775
9776// If the replacement is valid, emit a note with replacement function.
9777// Additionally, suggest including the proper header if not already included.
9779 unsigned AbsKind, QualType ArgType) {
9780 bool EmitHeaderHint = true;
9781 const char *HeaderName = nullptr;
9782 std::string FunctionName;
9783 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9784 FunctionName = "std::abs";
9785 if (ArgType->isIntegralOrEnumerationType()) {
9786 HeaderName = "cstdlib";
9787 } else if (ArgType->isRealFloatingType()) {
9788 HeaderName = "cmath";
9789 } else {
9790 llvm_unreachable("Invalid Type");
9791 }
9792
9793 // Lookup all std::abs
9794 if (NamespaceDecl *Std = S.getStdNamespace()) {
9795 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9797 S.LookupQualifiedName(R, Std);
9798
9799 for (const auto *I : R) {
9800 const FunctionDecl *FDecl = nullptr;
9801 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9802 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9803 } else {
9804 FDecl = dyn_cast<FunctionDecl>(I);
9805 }
9806 if (!FDecl)
9807 continue;
9808
9809 // Found std::abs(), check that they are the right ones.
9810 if (FDecl->getNumParams() != 1)
9811 continue;
9812
9813 // Check that the parameter type can handle the argument.
9814 QualType ParamType = FDecl->getParamDecl(0)->getType();
9815 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9816 S.Context.getTypeSize(ArgType) <=
9817 S.Context.getTypeSize(ParamType)) {
9818 // Found a function, don't need the header hint.
9819 EmitHeaderHint = false;
9820 break;
9821 }
9822 }
9823 }
9824 } else {
9825 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9826 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9827
9828 if (HeaderName) {
9829 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9830 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9832 S.LookupName(R, S.getCurScope());
9833
9834 if (R.isSingleResult()) {
9835 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9836 if (FD && FD->getBuiltinID() == AbsKind) {
9837 EmitHeaderHint = false;
9838 } else {
9839 return;
9840 }
9841 } else if (!R.empty()) {
9842 return;
9843 }
9844 }
9845 }
9846
9847 S.Diag(Loc, diag::note_replace_abs_function)
9848 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9849
9850 if (!HeaderName)
9851 return;
9852
9853 if (!EmitHeaderHint)
9854 return;
9855
9856 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9857 << FunctionName;
9858}
9859
9860template <std::size_t StrLen>
9861static bool IsStdFunction(const FunctionDecl *FDecl,
9862 const char (&Str)[StrLen]) {
9863 if (!FDecl)
9864 return false;
9865 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9866 return false;
9867 if (!FDecl->isInStdNamespace())
9868 return false;
9869
9870 return true;
9871}
9872
9873enum class MathCheck { NaN, Inf };
9874static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9875 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9876 return llvm::is_contained(names, calleeName);
9877 };
9878
9879 switch (Check) {
9880 case MathCheck::NaN:
9881 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9882 "__builtin_nanf16", "__builtin_nanf128"});
9883 case MathCheck::Inf:
9884 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9885 "__builtin_inff16", "__builtin_inff128"});
9886 }
9887 llvm_unreachable("unknown MathCheck");
9888}
9889
9890static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9891 if (FDecl->getName() != "infinity")
9892 return false;
9893
9894 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9895 const CXXRecordDecl *RDecl = MDecl->getParent();
9896 if (RDecl->getName() != "numeric_limits")
9897 return false;
9898
9899 if (const NamespaceDecl *NSDecl =
9900 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9901 return NSDecl->isStdNamespace();
9902 }
9903
9904 return false;
9905}
9906
9907void Sema::CheckInfNaNFunction(const CallExpr *Call,
9908 const FunctionDecl *FDecl) {
9909 if (!FDecl->getIdentifier())
9910 return;
9911
9912 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9913 if (FPO.getNoHonorNaNs() &&
9914 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9916 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9917 << 1 << 0 << Call->getSourceRange();
9918 return;
9919 }
9920
9921 if (FPO.getNoHonorInfs() &&
9922 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9923 IsInfinityFunction(FDecl) ||
9925 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9926 << 0 << 0 << Call->getSourceRange();
9927 }
9928}
9929
9930void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9931 const FunctionDecl *FDecl) {
9932 if (Call->getNumArgs() != 1)
9933 return;
9934
9935 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9936 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9937 if (AbsKind == 0 && !IsStdAbs)
9938 return;
9939
9940 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9941 QualType ParamType = Call->getArg(0)->getType();
9942
9943 // Unsigned types cannot be negative. Suggest removing the absolute value
9944 // function call.
9945 if (ArgType->isUnsignedIntegerType()) {
9946 std::string FunctionName =
9947 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9948 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9949 Diag(Call->getExprLoc(), diag::note_remove_abs)
9950 << FunctionName
9951 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9952 return;
9953 }
9954
9955 // Taking the absolute value of a pointer is very suspicious, they probably
9956 // wanted to index into an array, dereference a pointer, call a function, etc.
9957 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9958 unsigned DiagType = 0;
9959 if (ArgType->isFunctionType())
9960 DiagType = 1;
9961 else if (ArgType->isArrayType())
9962 DiagType = 2;
9963
9964 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9965 return;
9966 }
9967
9968 // std::abs has overloads which prevent most of the absolute value problems
9969 // from occurring.
9970 if (IsStdAbs)
9971 return;
9972
9973 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9974 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9975
9976 // The argument and parameter are the same kind. Check if they are the right
9977 // size.
9978 if (ArgValueKind == ParamValueKind) {
9979 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9980 return;
9981
9982 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9983 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9984 << FDecl << ArgType << ParamType;
9985
9986 if (NewAbsKind == 0)
9987 return;
9988
9989 emitReplacement(*this, Call->getExprLoc(),
9990 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9991 return;
9992 }
9993
9994 // ArgValueKind != ParamValueKind
9995 // The wrong type of absolute value function was used. Attempt to find the
9996 // proper one.
9997 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9998 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9999 if (NewAbsKind == 0)
10000 return;
10001
10002 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10003 << FDecl << ParamValueKind << ArgValueKind;
10004
10005 emitReplacement(*this, Call->getExprLoc(),
10006 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10007}
10008
10009//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10010void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10011 const FunctionDecl *FDecl) {
10012 if (!Call || !FDecl) return;
10013
10014 // Ignore template specializations and macros.
10015 if (inTemplateInstantiation()) return;
10016 if (Call->getExprLoc().isMacroID()) return;
10017
10018 // Only care about the one template argument, two function parameter std::max
10019 if (Call->getNumArgs() != 2) return;
10020 if (!IsStdFunction(FDecl, "max")) return;
10021 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10022 if (!ArgList) return;
10023 if (ArgList->size() != 1) return;
10024
10025 // Check that template type argument is unsigned integer.
10026 const auto& TA = ArgList->get(0);
10027 if (TA.getKind() != TemplateArgument::Type) return;
10028 QualType ArgType = TA.getAsType();
10029 if (!ArgType->isUnsignedIntegerType()) return;
10030
10031 // See if either argument is a literal zero.
10032 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10033 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10034 if (!MTE) return false;
10035 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10036 if (!Num) return false;
10037 if (Num->getValue() != 0) return false;
10038 return true;
10039 };
10040
10041 const Expr *FirstArg = Call->getArg(0);
10042 const Expr *SecondArg = Call->getArg(1);
10043 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10044 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10045
10046 // Only warn when exactly one argument is zero.
10047 if (IsFirstArgZero == IsSecondArgZero) return;
10048
10049 SourceRange FirstRange = FirstArg->getSourceRange();
10050 SourceRange SecondRange = SecondArg->getSourceRange();
10051
10052 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10053
10054 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10055 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10056
10057 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10058 SourceRange RemovalRange;
10059 if (IsFirstArgZero) {
10060 RemovalRange = SourceRange(FirstRange.getBegin(),
10061 SecondRange.getBegin().getLocWithOffset(-1));
10062 } else {
10063 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10064 SecondRange.getEnd());
10065 }
10066
10067 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10068 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10069 << FixItHint::CreateRemoval(RemovalRange);
10070}
10071
10072//===--- CHECK: Standard memory functions ---------------------------------===//
10073
10074/// Takes the expression passed to the size_t parameter of functions
10075/// such as memcmp, strncat, etc and warns if it's a comparison.
10076///
10077/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10079 const IdentifierInfo *FnName,
10080 SourceLocation FnLoc,
10081 SourceLocation RParenLoc) {
10082 const auto *Size = dyn_cast<BinaryOperator>(E);
10083 if (!Size)
10084 return false;
10085
10086 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10087 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10088 return false;
10089
10090 SourceRange SizeRange = Size->getSourceRange();
10091 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10092 << SizeRange << FnName;
10093 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10094 << FnName
10096 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10097 << FixItHint::CreateRemoval(RParenLoc);
10098 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10099 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10101 ")");
10102
10103 return true;
10104}
10105
10106/// Determine whether the given type is or contains a dynamic class type
10107/// (e.g., whether it has a vtable).
10109 bool &IsContained) {
10110 // Look through array types while ignoring qualifiers.
10111 const Type *Ty = T->getBaseElementTypeUnsafe();
10112 IsContained = false;
10113
10114 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10115 RD = RD ? RD->getDefinition() : nullptr;
10116 if (!RD || RD->isInvalidDecl())
10117 return nullptr;
10118
10119 if (RD->isDynamicClass())
10120 return RD;
10121
10122 // Check all the fields. If any bases were dynamic, the class is dynamic.
10123 // It's impossible for a class to transitively contain itself by value, so
10124 // infinite recursion is impossible.
10125 for (auto *FD : RD->fields()) {
10126 bool SubContained;
10127 if (const CXXRecordDecl *ContainedRD =
10128 getContainedDynamicClass(FD->getType(), SubContained)) {
10129 IsContained = true;
10130 return ContainedRD;
10131 }
10132 }
10133
10134 return nullptr;
10135}
10136
10138 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10139 if (Unary->getKind() == UETT_SizeOf)
10140 return Unary;
10141 return nullptr;
10142}
10143
10144/// If E is a sizeof expression, returns its argument expression,
10145/// otherwise returns NULL.
10146static const Expr *getSizeOfExprArg(const Expr *E) {
10148 if (!SizeOf->isArgumentType())
10149 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10150 return nullptr;
10151}
10152
10153/// If E is a sizeof expression, returns its argument type.
10156 return SizeOf->getTypeOfArgument();
10157 return QualType();
10158}
10159
10160namespace {
10161
10162struct SearchNonTrivialToInitializeField
10163 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10164 using Super =
10165 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10166
10167 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10168
10169 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10170 SourceLocation SL) {
10171 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10172 asDerived().visitArray(PDIK, AT, SL);
10173 return;
10174 }
10175
10176 Super::visitWithKind(PDIK, FT, SL);
10177 }
10178
10179 void visitARCStrong(QualType FT, SourceLocation SL) {
10180 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10181 }
10182 void visitARCWeak(QualType FT, SourceLocation SL) {
10183 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10184 }
10185 void visitStruct(QualType FT, SourceLocation SL) {
10186 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10187 visit(FD->getType(), FD->getLocation());
10188 }
10189 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10190 const ArrayType *AT, SourceLocation SL) {
10191 visit(getContext().getBaseElementType(AT), SL);
10192 }
10193 void visitTrivial(QualType FT, SourceLocation SL) {}
10194
10195 static void diag(QualType RT, const Expr *E, Sema &S) {
10196 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10197 }
10198
10199 ASTContext &getContext() { return S.getASTContext(); }
10200
10201 const Expr *E;
10202 Sema &S;
10203};
10204
10205struct SearchNonTrivialToCopyField
10206 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10207 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10208
10209 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10210
10211 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10212 SourceLocation SL) {
10213 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10214 asDerived().visitArray(PCK, AT, SL);
10215 return;
10216 }
10217
10218 Super::visitWithKind(PCK, FT, SL);
10219 }
10220
10221 void visitARCStrong(QualType FT, SourceLocation SL) {
10222 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10223 }
10224 void visitARCWeak(QualType FT, SourceLocation SL) {
10225 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10226 }
10227 void visitPtrAuth(QualType FT, SourceLocation SL) {
10228 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10229 }
10230 void visitStruct(QualType FT, SourceLocation SL) {
10231 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10232 visit(FD->getType(), FD->getLocation());
10233 }
10234 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10235 SourceLocation SL) {
10236 visit(getContext().getBaseElementType(AT), SL);
10237 }
10238 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10239 SourceLocation SL) {}
10240 void visitTrivial(QualType FT, SourceLocation SL) {}
10241 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10242
10243 static void diag(QualType RT, const Expr *E, Sema &S) {
10244 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10245 }
10246
10247 ASTContext &getContext() { return S.getASTContext(); }
10248
10249 const Expr *E;
10250 Sema &S;
10251};
10252
10253}
10254
10255/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10256static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10257 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10258
10259 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10260 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10261 return false;
10262
10263 return doesExprLikelyComputeSize(BO->getLHS()) ||
10264 doesExprLikelyComputeSize(BO->getRHS());
10265 }
10266
10267 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10268}
10269
10270/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10271///
10272/// \code
10273/// #define MACRO 0
10274/// foo(MACRO);
10275/// foo(0);
10276/// \endcode
10277///
10278/// This should return true for the first call to foo, but not for the second
10279/// (regardless of whether foo is a macro or function).
10281 SourceLocation CallLoc,
10282 SourceLocation ArgLoc) {
10283 if (!CallLoc.isMacroID())
10284 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10285
10286 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10287 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10288}
10289
10290/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10291/// last two arguments transposed.
10292static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10293 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10294 return;
10295
10296 const Expr *SizeArg =
10297 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10298
10299 auto isLiteralZero = [](const Expr *E) {
10300 return (isa<IntegerLiteral>(E) &&
10301 cast<IntegerLiteral>(E)->getValue() == 0) ||
10303 cast<CharacterLiteral>(E)->getValue() == 0);
10304 };
10305
10306 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10307 SourceLocation CallLoc = Call->getRParenLoc();
10309 if (isLiteralZero(SizeArg) &&
10310 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10311
10312 SourceLocation DiagLoc = SizeArg->getExprLoc();
10313
10314 // Some platforms #define bzero to __builtin_memset. See if this is the
10315 // case, and if so, emit a better diagnostic.
10316 if (BId == Builtin::BIbzero ||
10318 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10319 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10320 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10321 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10322 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10323 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10324 }
10325 return;
10326 }
10327
10328 // If the second argument to a memset is a sizeof expression and the third
10329 // isn't, this is also likely an error. This should catch
10330 // 'memset(buf, sizeof(buf), 0xff)'.
10331 if (BId == Builtin::BImemset &&
10332 doesExprLikelyComputeSize(Call->getArg(1)) &&
10333 !doesExprLikelyComputeSize(Call->getArg(2))) {
10334 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10335 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10336 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10337 return;
10338 }
10339}
10340
10341void Sema::CheckMemaccessArguments(const CallExpr *Call,
10342 unsigned BId,
10343 IdentifierInfo *FnName) {
10344 assert(BId != 0);
10345
10346 // It is possible to have a non-standard definition of memset. Validate
10347 // we have enough arguments, and if not, abort further checking.
10348 unsigned ExpectedNumArgs =
10349 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10350 if (Call->getNumArgs() < ExpectedNumArgs)
10351 return;
10352
10353 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10354 BId == Builtin::BIstrndup ? 1 : 2);
10355 unsigned LenArg =
10356 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10357 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10358
10359 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10360 Call->getBeginLoc(), Call->getRParenLoc()))
10361 return;
10362
10363 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10364 CheckMemaccessSize(*this, BId, Call);
10365
10366 // We have special checking when the length is a sizeof expression.
10367 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10368 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10369 llvm::FoldingSetNodeID SizeOfArgID;
10370
10371 // Although widely used, 'bzero' is not a standard function. Be more strict
10372 // with the argument types before allowing diagnostics and only allow the
10373 // form bzero(ptr, sizeof(...)).
10374 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10375 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10376 return;
10377
10378 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10379 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10380 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10381
10382 QualType DestTy = Dest->getType();
10383 QualType PointeeTy;
10384 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10385 PointeeTy = DestPtrTy->getPointeeType();
10386
10387 // Never warn about void type pointers. This can be used to suppress
10388 // false positives.
10389 if (PointeeTy->isVoidType())
10390 continue;
10391
10392 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10393 // actually comparing the expressions for equality. Because computing the
10394 // expression IDs can be expensive, we only do this if the diagnostic is
10395 // enabled.
10396 if (SizeOfArg &&
10397 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10398 SizeOfArg->getExprLoc())) {
10399 // We only compute IDs for expressions if the warning is enabled, and
10400 // cache the sizeof arg's ID.
10401 if (SizeOfArgID == llvm::FoldingSetNodeID())
10402 SizeOfArg->Profile(SizeOfArgID, Context, true);
10403 llvm::FoldingSetNodeID DestID;
10404 Dest->Profile(DestID, Context, true);
10405 if (DestID == SizeOfArgID) {
10406 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10407 // over sizeof(src) as well.
10408 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10409 StringRef ReadableName = FnName->getName();
10410
10411 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10412 if (UnaryOp->getOpcode() == UO_AddrOf)
10413 ActionIdx = 1; // If its an address-of operator, just remove it.
10414 if (!PointeeTy->isIncompleteType() &&
10415 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10416 ActionIdx = 2; // If the pointee's size is sizeof(char),
10417 // suggest an explicit length.
10418
10419 // If the function is defined as a builtin macro, do not show macro
10420 // expansion.
10421 SourceLocation SL = SizeOfArg->getExprLoc();
10422 SourceRange DSR = Dest->getSourceRange();
10423 SourceRange SSR = SizeOfArg->getSourceRange();
10424 SourceManager &SM = getSourceManager();
10425
10426 if (SM.isMacroArgExpansion(SL)) {
10427 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10428 SL = SM.getSpellingLoc(SL);
10429 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10430 SM.getSpellingLoc(DSR.getEnd()));
10431 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10432 SM.getSpellingLoc(SSR.getEnd()));
10433 }
10434
10435 DiagRuntimeBehavior(SL, SizeOfArg,
10436 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10437 << ReadableName
10438 << PointeeTy
10439 << DestTy
10440 << DSR
10441 << SSR);
10442 DiagRuntimeBehavior(SL, SizeOfArg,
10443 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10444 << ActionIdx
10445 << SSR);
10446
10447 break;
10448 }
10449 }
10450
10451 // Also check for cases where the sizeof argument is the exact same
10452 // type as the memory argument, and where it points to a user-defined
10453 // record type.
10454 if (SizeOfArgTy != QualType()) {
10455 if (PointeeTy->isRecordType() &&
10456 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10457 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10458 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10459 << FnName << SizeOfArgTy << ArgIdx
10460 << PointeeTy << Dest->getSourceRange()
10461 << LenExpr->getSourceRange());
10462 break;
10463 }
10464 }
10465 } else if (DestTy->isArrayType()) {
10466 PointeeTy = DestTy;
10467 }
10468
10469 if (PointeeTy == QualType())
10470 continue;
10471
10472 // Always complain about dynamic classes.
10473 bool IsContained;
10474 if (const CXXRecordDecl *ContainedRD =
10475 getContainedDynamicClass(PointeeTy, IsContained)) {
10476
10477 unsigned OperationType = 0;
10478 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10479 // "overwritten" if we're warning about the destination for any call
10480 // but memcmp; otherwise a verb appropriate to the call.
10481 if (ArgIdx != 0 || IsCmp) {
10482 if (BId == Builtin::BImemcpy)
10483 OperationType = 1;
10484 else if(BId == Builtin::BImemmove)
10485 OperationType = 2;
10486 else if (IsCmp)
10487 OperationType = 3;
10488 }
10489
10490 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10491 PDiag(diag::warn_dyn_class_memaccess)
10492 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10493 << IsContained << ContainedRD << OperationType
10494 << Call->getCallee()->getSourceRange());
10495 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10496 BId != Builtin::BImemset)
10498 Dest->getExprLoc(), Dest,
10499 PDiag(diag::warn_arc_object_memaccess)
10500 << ArgIdx << FnName << PointeeTy
10501 << Call->getCallee()->getSourceRange());
10502 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10503
10504 // FIXME: Do not consider incomplete types even though they may be
10505 // completed later. GCC does not diagnose such code, but we may want to
10506 // consider diagnosing it in the future, perhaps under a different, but
10507 // related, diagnostic group.
10508 bool NonTriviallyCopyableCXXRecord =
10509 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10510 !PointeeTy.isTriviallyCopyableType(Context);
10511
10512 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10514 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10515 PDiag(diag::warn_cstruct_memaccess)
10516 << ArgIdx << FnName << PointeeTy << 0);
10517 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10518 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10519 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10520 // FIXME: Limiting this warning to dest argument until we decide
10521 // whether it's valid for source argument too.
10522 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10523 PDiag(diag::warn_cxxstruct_memaccess)
10524 << FnName << PointeeTy);
10525 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10527 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10528 PDiag(diag::warn_cstruct_memaccess)
10529 << ArgIdx << FnName << PointeeTy << 1);
10530 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10531 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10532 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10533 // FIXME: Limiting this warning to dest argument until we decide
10534 // whether it's valid for source argument too.
10535 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10536 PDiag(diag::warn_cxxstruct_memaccess)
10537 << FnName << PointeeTy);
10538 } else {
10539 continue;
10540 }
10541 } else
10542 continue;
10543
10545 Dest->getExprLoc(), Dest,
10546 PDiag(diag::note_bad_memaccess_silence)
10547 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10548 break;
10549 }
10550}
10551
10552// A little helper routine: ignore addition and subtraction of integer literals.
10553// This intentionally does not ignore all integer constant expressions because
10554// we don't want to remove sizeof().
10555static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10556 Ex = Ex->IgnoreParenCasts();
10557
10558 while (true) {
10559 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10560 if (!BO || !BO->isAdditiveOp())
10561 break;
10562
10563 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10564 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10565
10566 if (isa<IntegerLiteral>(RHS))
10567 Ex = LHS;
10568 else if (isa<IntegerLiteral>(LHS))
10569 Ex = RHS;
10570 else
10571 break;
10572 }
10573
10574 return Ex;
10575}
10576
10578 ASTContext &Context) {
10579 // Only handle constant-sized or VLAs, but not flexible members.
10580 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10581 // Only issue the FIXIT for arrays of size > 1.
10582 if (CAT->getZExtSize() <= 1)
10583 return false;
10584 } else if (!Ty->isVariableArrayType()) {
10585 return false;
10586 }
10587 return true;
10588}
10589
10590void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10591 IdentifierInfo *FnName) {
10592
10593 // Don't crash if the user has the wrong number of arguments
10594 unsigned NumArgs = Call->getNumArgs();
10595 if ((NumArgs != 3) && (NumArgs != 4))
10596 return;
10597
10598 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10599 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10600 const Expr *CompareWithSrc = nullptr;
10601
10602 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10603 Call->getBeginLoc(), Call->getRParenLoc()))
10604 return;
10605
10606 // Look for 'strlcpy(dst, x, sizeof(x))'
10607 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10608 CompareWithSrc = Ex;
10609 else {
10610 // Look for 'strlcpy(dst, x, strlen(x))'
10611 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10612 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10613 SizeCall->getNumArgs() == 1)
10614 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10615 }
10616 }
10617
10618 if (!CompareWithSrc)
10619 return;
10620
10621 // Determine if the argument to sizeof/strlen is equal to the source
10622 // argument. In principle there's all kinds of things you could do
10623 // here, for instance creating an == expression and evaluating it with
10624 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10625 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10626 if (!SrcArgDRE)
10627 return;
10628
10629 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10630 if (!CompareWithSrcDRE ||
10631 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10632 return;
10633
10634 const Expr *OriginalSizeArg = Call->getArg(2);
10635 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10636 << OriginalSizeArg->getSourceRange() << FnName;
10637
10638 // Output a FIXIT hint if the destination is an array (rather than a
10639 // pointer to an array). This could be enhanced to handle some
10640 // pointers if we know the actual size, like if DstArg is 'array+2'
10641 // we could say 'sizeof(array)-2'.
10642 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10644 return;
10645
10646 SmallString<128> sizeString;
10647 llvm::raw_svector_ostream OS(sizeString);
10648 OS << "sizeof(";
10649 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10650 OS << ")";
10651
10652 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10653 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10654 OS.str());
10655}
10656
10657/// Check if two expressions refer to the same declaration.
10658static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10659 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10660 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10661 return D1->getDecl() == D2->getDecl();
10662 return false;
10663}
10664
10665static const Expr *getStrlenExprArg(const Expr *E) {
10666 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10667 const FunctionDecl *FD = CE->getDirectCallee();
10668 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10669 return nullptr;
10670 return CE->getArg(0)->IgnoreParenCasts();
10671 }
10672 return nullptr;
10673}
10674
10675void Sema::CheckStrncatArguments(const CallExpr *CE,
10676 const IdentifierInfo *FnName) {
10677 // Don't crash if the user has the wrong number of arguments.
10678 if (CE->getNumArgs() < 3)
10679 return;
10680 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10681 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10682 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10683
10684 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10685 CE->getRParenLoc()))
10686 return;
10687
10688 // Identify common expressions, which are wrongly used as the size argument
10689 // to strncat and may lead to buffer overflows.
10690 unsigned PatternType = 0;
10691 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10692 // - sizeof(dst)
10693 if (referToTheSameDecl(SizeOfArg, DstArg))
10694 PatternType = 1;
10695 // - sizeof(src)
10696 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10697 PatternType = 2;
10698 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10699 if (BE->getOpcode() == BO_Sub) {
10700 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10701 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10702 // - sizeof(dst) - strlen(dst)
10703 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10705 PatternType = 1;
10706 // - sizeof(src) - (anything)
10707 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10708 PatternType = 2;
10709 }
10710 }
10711
10712 if (PatternType == 0)
10713 return;
10714
10715 // Generate the diagnostic.
10716 SourceLocation SL = LenArg->getBeginLoc();
10717 SourceRange SR = LenArg->getSourceRange();
10718 SourceManager &SM = getSourceManager();
10719
10720 // If the function is defined as a builtin macro, do not show macro expansion.
10721 if (SM.isMacroArgExpansion(SL)) {
10722 SL = SM.getSpellingLoc(SL);
10723 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10724 SM.getSpellingLoc(SR.getEnd()));
10725 }
10726
10727 // Check if the destination is an array (rather than a pointer to an array).
10728 QualType DstTy = DstArg->getType();
10729 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10730 Context);
10731 if (!isKnownSizeArray) {
10732 if (PatternType == 1)
10733 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10734 else
10735 Diag(SL, diag::warn_strncat_src_size) << SR;
10736 return;
10737 }
10738
10739 if (PatternType == 1)
10740 Diag(SL, diag::warn_strncat_large_size) << SR;
10741 else
10742 Diag(SL, diag::warn_strncat_src_size) << SR;
10743
10744 SmallString<128> sizeString;
10745 llvm::raw_svector_ostream OS(sizeString);
10746 OS << "sizeof(";
10747 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10748 OS << ") - ";
10749 OS << "strlen(";
10750 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10751 OS << ") - 1";
10752
10753 Diag(SL, diag::note_strncat_wrong_size)
10754 << FixItHint::CreateReplacement(SR, OS.str());
10755}
10756
10757namespace {
10758void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10759 const UnaryOperator *UnaryExpr, const Decl *D) {
10761 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10762 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10763 return;
10764 }
10765}
10766
10767void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10768 const UnaryOperator *UnaryExpr) {
10769 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10770 const Decl *D = Lvalue->getDecl();
10771 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10772 if (!DD->getType()->isReferenceType())
10773 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10774 }
10775 }
10776
10777 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10778 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10779 Lvalue->getMemberDecl());
10780}
10781
10782void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10783 const UnaryOperator *UnaryExpr) {
10784 const auto *Lambda = dyn_cast<LambdaExpr>(
10786 if (!Lambda)
10787 return;
10788
10789 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10790 << CalleeName << 2 /*object: lambda expression*/;
10791}
10792
10793void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10794 const DeclRefExpr *Lvalue) {
10795 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10796 if (Var == nullptr)
10797 return;
10798
10799 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10800 << CalleeName << 0 /*object: */ << Var;
10801}
10802
10803void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10804 const CastExpr *Cast) {
10805 SmallString<128> SizeString;
10806 llvm::raw_svector_ostream OS(SizeString);
10807
10808 clang::CastKind Kind = Cast->getCastKind();
10809 if (Kind == clang::CK_BitCast &&
10810 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10811 return;
10812 if (Kind == clang::CK_IntegralToPointer &&
10814 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10815 return;
10816
10817 switch (Cast->getCastKind()) {
10818 case clang::CK_BitCast:
10819 case clang::CK_IntegralToPointer:
10820 case clang::CK_FunctionToPointerDecay:
10821 OS << '\'';
10822 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10823 OS << '\'';
10824 break;
10825 default:
10826 return;
10827 }
10828
10829 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10830 << CalleeName << 0 /*object: */ << OS.str();
10831}
10832} // namespace
10833
10834void Sema::CheckFreeArguments(const CallExpr *E) {
10835 const std::string CalleeName =
10836 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10837
10838 { // Prefer something that doesn't involve a cast to make things simpler.
10839 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10840 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10841 switch (UnaryExpr->getOpcode()) {
10842 case UnaryOperator::Opcode::UO_AddrOf:
10843 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10844 case UnaryOperator::Opcode::UO_Plus:
10845 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10846 default:
10847 break;
10848 }
10849
10850 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10851 if (Lvalue->getType()->isArrayType())
10852 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10853
10854 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10855 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10856 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10857 return;
10858 }
10859
10860 if (isa<BlockExpr>(Arg)) {
10861 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10862 << CalleeName << 1 /*object: block*/;
10863 return;
10864 }
10865 }
10866 // Maybe the cast was important, check after the other cases.
10867 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10868 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10869}
10870
10871void
10872Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10873 SourceLocation ReturnLoc,
10874 bool isObjCMethod,
10875 const AttrVec *Attrs,
10876 const FunctionDecl *FD) {
10877 // Check if the return value is null but should not be.
10878 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10879 (!isObjCMethod && isNonNullType(lhsType))) &&
10880 CheckNonNullExpr(*this, RetValExp))
10881 Diag(ReturnLoc, diag::warn_null_ret)
10882 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10883
10884 // C++11 [basic.stc.dynamic.allocation]p4:
10885 // If an allocation function declared with a non-throwing
10886 // exception-specification fails to allocate storage, it shall return
10887 // a null pointer. Any other allocation function that fails to allocate
10888 // storage shall indicate failure only by throwing an exception [...]
10889 if (FD) {
10891 if (Op == OO_New || Op == OO_Array_New) {
10892 const FunctionProtoType *Proto
10893 = FD->getType()->castAs<FunctionProtoType>();
10894 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10895 CheckNonNullExpr(*this, RetValExp))
10896 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10897 << FD << getLangOpts().CPlusPlus11;
10898 }
10899 }
10900
10901 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10902 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10903 }
10904
10905 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10906 // here prevent the user from using a PPC MMA type as trailing return type.
10907 if (Context.getTargetInfo().getTriple().isPPC64())
10908 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10909}
10910
10912 const Expr *RHS, BinaryOperatorKind Opcode) {
10913 if (!BinaryOperator::isEqualityOp(Opcode))
10914 return;
10915
10916 // Match and capture subexpressions such as "(float) X == 0.1".
10917 const FloatingLiteral *FPLiteral;
10918 const CastExpr *FPCast;
10919 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10920 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10921 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10922 return FPLiteral && FPCast;
10923 };
10924
10925 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10926 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10927 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10928 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10929 TargetTy->isFloatingPoint()) {
10930 bool Lossy;
10931 llvm::APFloat TargetC = FPLiteral->getValue();
10932 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10933 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10934 if (Lossy) {
10935 // If the literal cannot be represented in the source type, then a
10936 // check for == is always false and check for != is always true.
10937 Diag(Loc, diag::warn_float_compare_literal)
10938 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10939 << LHS->getSourceRange() << RHS->getSourceRange();
10940 return;
10941 }
10942 }
10943 }
10944
10945 // Match a more general floating-point equality comparison (-Wfloat-equal).
10946 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10947 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10948
10949 // Special case: check for x == x (which is OK).
10950 // Do not emit warnings for such cases.
10951 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10952 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10953 if (DRL->getDecl() == DRR->getDecl())
10954 return;
10955
10956 // Special case: check for comparisons against literals that can be exactly
10957 // represented by APFloat. In such cases, do not emit a warning. This
10958 // is a heuristic: often comparison against such literals are used to
10959 // detect if a value in a variable has not changed. This clearly can
10960 // lead to false negatives.
10961 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10962 if (FLL->isExact())
10963 return;
10964 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10965 if (FLR->isExact())
10966 return;
10967
10968 // Check for comparisons with builtin types.
10969 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10970 CL && CL->getBuiltinCallee())
10971 return;
10972
10973 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10974 CR && CR->getBuiltinCallee())
10975 return;
10976
10977 // Emit the diagnostic.
10978 Diag(Loc, diag::warn_floatingpoint_eq)
10979 << LHS->getSourceRange() << RHS->getSourceRange();
10980}
10981
10982//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10983//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10984
10985namespace {
10986
10987/// Structure recording the 'active' range of an integer-valued
10988/// expression.
10989struct IntRange {
10990 /// The number of bits active in the int. Note that this includes exactly one
10991 /// sign bit if !NonNegative.
10992 unsigned Width;
10993
10994 /// True if the int is known not to have negative values. If so, all leading
10995 /// bits before Width are known zero, otherwise they are known to be the
10996 /// same as the MSB within Width.
10997 bool NonNegative;
10998
10999 IntRange(unsigned Width, bool NonNegative)
11000 : Width(Width), NonNegative(NonNegative) {}
11001
11002 /// Number of bits excluding the sign bit.
11003 unsigned valueBits() const {
11004 return NonNegative ? Width : Width - 1;
11005 }
11006
11007 /// Returns the range of the bool type.
11008 static IntRange forBoolType() {
11009 return IntRange(1, true);
11010 }
11011
11012 /// Returns the range of an opaque value of the given integral type.
11013 static IntRange forValueOfType(ASTContext &C, QualType T) {
11014 return forValueOfCanonicalType(C,
11016 }
11017
11018 /// Returns the range of an opaque value of a canonical integral type.
11019 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11020 assert(T->isCanonicalUnqualified());
11021
11022 if (const auto *VT = dyn_cast<VectorType>(T))
11023 T = VT->getElementType().getTypePtr();
11024 if (const auto *CT = dyn_cast<ComplexType>(T))
11025 T = CT->getElementType().getTypePtr();
11026 if (const auto *AT = dyn_cast<AtomicType>(T))
11027 T = AT->getValueType().getTypePtr();
11028
11029 if (!C.getLangOpts().CPlusPlus) {
11030 // For enum types in C code, use the underlying datatype.
11031 if (const auto *ED = T->getAsEnumDecl())
11032 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11033 } else if (auto *Enum = T->getAsEnumDecl()) {
11034 // For enum types in C++, use the known bit width of the enumerators.
11035 // In C++11, enums can have a fixed underlying type. Use this type to
11036 // compute the range.
11037 if (Enum->isFixed()) {
11038 return IntRange(C.getIntWidth(QualType(T, 0)),
11039 !Enum->getIntegerType()->isSignedIntegerType());
11040 }
11041
11042 unsigned NumPositive = Enum->getNumPositiveBits();
11043 unsigned NumNegative = Enum->getNumNegativeBits();
11044
11045 if (NumNegative == 0)
11046 return IntRange(NumPositive, true/*NonNegative*/);
11047 else
11048 return IntRange(std::max(NumPositive + 1, NumNegative),
11049 false/*NonNegative*/);
11050 }
11051
11052 if (const auto *EIT = dyn_cast<BitIntType>(T))
11053 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11054
11055 const BuiltinType *BT = cast<BuiltinType>(T);
11056 assert(BT->isInteger());
11057
11058 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11059 }
11060
11061 /// Returns the "target" range of a canonical integral type, i.e.
11062 /// the range of values expressible in the type.
11063 ///
11064 /// This matches forValueOfCanonicalType except that enums have the
11065 /// full range of their type, not the range of their enumerators.
11066 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11067 assert(T->isCanonicalUnqualified());
11068
11069 if (const VectorType *VT = dyn_cast<VectorType>(T))
11070 T = VT->getElementType().getTypePtr();
11071 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11072 T = CT->getElementType().getTypePtr();
11073 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11074 T = AT->getValueType().getTypePtr();
11075 if (const auto *ED = T->getAsEnumDecl())
11076 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11077
11078 if (const auto *EIT = dyn_cast<BitIntType>(T))
11079 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11080
11081 const BuiltinType *BT = cast<BuiltinType>(T);
11082 assert(BT->isInteger());
11083
11084 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11085 }
11086
11087 /// Returns the supremum of two ranges: i.e. their conservative merge.
11088 static IntRange join(IntRange L, IntRange R) {
11089 bool Unsigned = L.NonNegative && R.NonNegative;
11090 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11091 L.NonNegative && R.NonNegative);
11092 }
11093
11094 /// Return the range of a bitwise-AND of the two ranges.
11095 static IntRange bit_and(IntRange L, IntRange R) {
11096 unsigned Bits = std::max(L.Width, R.Width);
11097 bool NonNegative = false;
11098 if (L.NonNegative) {
11099 Bits = std::min(Bits, L.Width);
11100 NonNegative = true;
11101 }
11102 if (R.NonNegative) {
11103 Bits = std::min(Bits, R.Width);
11104 NonNegative = true;
11105 }
11106 return IntRange(Bits, NonNegative);
11107 }
11108
11109 /// Return the range of a sum of the two ranges.
11110 static IntRange sum(IntRange L, IntRange R) {
11111 bool Unsigned = L.NonNegative && R.NonNegative;
11112 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11113 Unsigned);
11114 }
11115
11116 /// Return the range of a difference of the two ranges.
11117 static IntRange difference(IntRange L, IntRange R) {
11118 // We need a 1-bit-wider range if:
11119 // 1) LHS can be negative: least value can be reduced.
11120 // 2) RHS can be negative: greatest value can be increased.
11121 bool CanWiden = !L.NonNegative || !R.NonNegative;
11122 bool Unsigned = L.NonNegative && R.Width == 0;
11123 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11124 !Unsigned,
11125 Unsigned);
11126 }
11127
11128 /// Return the range of a product of the two ranges.
11129 static IntRange product(IntRange L, IntRange R) {
11130 // If both LHS and RHS can be negative, we can form
11131 // -2^L * -2^R = 2^(L + R)
11132 // which requires L + R + 1 value bits to represent.
11133 bool CanWiden = !L.NonNegative && !R.NonNegative;
11134 bool Unsigned = L.NonNegative && R.NonNegative;
11135 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11136 Unsigned);
11137 }
11138
11139 /// Return the range of a remainder operation between the two ranges.
11140 static IntRange rem(IntRange L, IntRange R) {
11141 // The result of a remainder can't be larger than the result of
11142 // either side. The sign of the result is the sign of the LHS.
11143 bool Unsigned = L.NonNegative;
11144 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11145 Unsigned);
11146 }
11147};
11148
11149} // namespace
11150
11151static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11152 if (value.isSigned() && value.isNegative())
11153 return IntRange(value.getSignificantBits(), false);
11154
11155 if (value.getBitWidth() > MaxWidth)
11156 value = value.trunc(MaxWidth);
11157
11158 // isNonNegative() just checks the sign bit without considering
11159 // signedness.
11160 return IntRange(value.getActiveBits(), true);
11161}
11162
11163static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11164 if (result.isInt())
11165 return GetValueRange(result.getInt(), MaxWidth);
11166
11167 if (result.isVector()) {
11168 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11169 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11170 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11171 R = IntRange::join(R, El);
11172 }
11173 return R;
11174 }
11175
11176 if (result.isComplexInt()) {
11177 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11178 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11179 return IntRange::join(R, I);
11180 }
11181
11182 // This can happen with lossless casts to intptr_t of "based" lvalues.
11183 // Assume it might use arbitrary bits.
11184 // FIXME: The only reason we need to pass the type in here is to get
11185 // the sign right on this one case. It would be nice if APValue
11186 // preserved this.
11187 assert(result.isLValue() || result.isAddrLabelDiff());
11188 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11189}
11190
11191static QualType GetExprType(const Expr *E) {
11192 QualType Ty = E->getType();
11193 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11194 Ty = AtomicRHS->getValueType();
11195 return Ty;
11196}
11197
11198/// Attempts to estimate an approximate range for the given integer expression.
11199/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11200/// reliable estimation cannot be determined.
11201///
11202/// \param MaxWidth The width to which the value will be truncated.
11203/// \param InConstantContext If \c true, interpret the expression within a
11204/// constant context.
11205/// \param Approximate If \c true, provide a likely range of values by assuming
11206/// that arithmetic on narrower types remains within those types.
11207/// If \c false, return a range that includes all possible values
11208/// resulting from the expression.
11209/// \returns A range of values that the expression might take, or
11210/// std::nullopt if a reliable estimation cannot be determined.
11211static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11212 unsigned MaxWidth,
11213 bool InConstantContext,
11214 bool Approximate) {
11215 E = E->IgnoreParens();
11216
11217 // Try a full evaluation first.
11218 Expr::EvalResult result;
11219 if (E->EvaluateAsRValue(result, C, InConstantContext))
11220 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11221
11222 // I think we only want to look through implicit casts here; if the
11223 // user has an explicit widening cast, we should treat the value as
11224 // being of the new, wider type.
11225 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11226 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11227 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11228 Approximate);
11229
11230 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11231
11232 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11233 CE->getCastKind() == CK_BooleanToSignedIntegral;
11234
11235 // Assume that non-integer casts can span the full range of the type.
11236 if (!isIntegerCast)
11237 return OutputTypeRange;
11238
11239 std::optional<IntRange> SubRange = TryGetExprRange(
11240 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11241 InConstantContext, Approximate);
11242 if (!SubRange)
11243 return std::nullopt;
11244
11245 // Bail out if the subexpr's range is as wide as the cast type.
11246 if (SubRange->Width >= OutputTypeRange.Width)
11247 return OutputTypeRange;
11248
11249 // Otherwise, we take the smaller width, and we're non-negative if
11250 // either the output type or the subexpr is.
11251 return IntRange(SubRange->Width,
11252 SubRange->NonNegative || OutputTypeRange.NonNegative);
11253 }
11254
11255 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11256 // If we can fold the condition, just take that operand.
11257 bool CondResult;
11258 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11259 return TryGetExprRange(
11260 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11261 InConstantContext, Approximate);
11262
11263 // Otherwise, conservatively merge.
11264 // TryGetExprRange requires an integer expression, but a throw expression
11265 // results in a void type.
11266 Expr *TrueExpr = CO->getTrueExpr();
11267 if (TrueExpr->getType()->isVoidType())
11268 return std::nullopt;
11269
11270 std::optional<IntRange> L =
11271 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11272 if (!L)
11273 return std::nullopt;
11274
11275 Expr *FalseExpr = CO->getFalseExpr();
11276 if (FalseExpr->getType()->isVoidType())
11277 return std::nullopt;
11278
11279 std::optional<IntRange> R =
11280 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11281 if (!R)
11282 return std::nullopt;
11283
11284 return IntRange::join(*L, *R);
11285 }
11286
11287 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11288 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11289
11290 switch (BO->getOpcode()) {
11291 case BO_Cmp:
11292 llvm_unreachable("builtin <=> should have class type");
11293
11294 // Boolean-valued operations are single-bit and positive.
11295 case BO_LAnd:
11296 case BO_LOr:
11297 case BO_LT:
11298 case BO_GT:
11299 case BO_LE:
11300 case BO_GE:
11301 case BO_EQ:
11302 case BO_NE:
11303 return IntRange::forBoolType();
11304
11305 // The type of the assignments is the type of the LHS, so the RHS
11306 // is not necessarily the same type.
11307 case BO_MulAssign:
11308 case BO_DivAssign:
11309 case BO_RemAssign:
11310 case BO_AddAssign:
11311 case BO_SubAssign:
11312 case BO_XorAssign:
11313 case BO_OrAssign:
11314 // TODO: bitfields?
11315 return IntRange::forValueOfType(C, GetExprType(E));
11316
11317 // Simple assignments just pass through the RHS, which will have
11318 // been coerced to the LHS type.
11319 case BO_Assign:
11320 // TODO: bitfields?
11321 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11322 Approximate);
11323
11324 // Operations with opaque sources are black-listed.
11325 case BO_PtrMemD:
11326 case BO_PtrMemI:
11327 return IntRange::forValueOfType(C, GetExprType(E));
11328
11329 // Bitwise-and uses the *infinum* of the two source ranges.
11330 case BO_And:
11331 case BO_AndAssign:
11332 Combine = IntRange::bit_and;
11333 break;
11334
11335 // Left shift gets black-listed based on a judgement call.
11336 case BO_Shl:
11337 // ...except that we want to treat '1 << (blah)' as logically
11338 // positive. It's an important idiom.
11339 if (IntegerLiteral *I
11340 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11341 if (I->getValue() == 1) {
11342 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11343 return IntRange(R.Width, /*NonNegative*/ true);
11344 }
11345 }
11346 [[fallthrough]];
11347
11348 case BO_ShlAssign:
11349 return IntRange::forValueOfType(C, GetExprType(E));
11350
11351 // Right shift by a constant can narrow its left argument.
11352 case BO_Shr:
11353 case BO_ShrAssign: {
11354 std::optional<IntRange> L = TryGetExprRange(
11355 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11356 if (!L)
11357 return std::nullopt;
11358
11359 // If the shift amount is a positive constant, drop the width by
11360 // that much.
11361 if (std::optional<llvm::APSInt> shift =
11362 BO->getRHS()->getIntegerConstantExpr(C)) {
11363 if (shift->isNonNegative()) {
11364 if (shift->uge(L->Width))
11365 L->Width = (L->NonNegative ? 0 : 1);
11366 else
11367 L->Width -= shift->getZExtValue();
11368 }
11369 }
11370
11371 return L;
11372 }
11373
11374 // Comma acts as its right operand.
11375 case BO_Comma:
11376 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11377 Approximate);
11378
11379 case BO_Add:
11380 if (!Approximate)
11381 Combine = IntRange::sum;
11382 break;
11383
11384 case BO_Sub:
11385 if (BO->getLHS()->getType()->isPointerType())
11386 return IntRange::forValueOfType(C, GetExprType(E));
11387 if (!Approximate)
11388 Combine = IntRange::difference;
11389 break;
11390
11391 case BO_Mul:
11392 if (!Approximate)
11393 Combine = IntRange::product;
11394 break;
11395
11396 // The width of a division result is mostly determined by the size
11397 // of the LHS.
11398 case BO_Div: {
11399 // Don't 'pre-truncate' the operands.
11400 unsigned opWidth = C.getIntWidth(GetExprType(E));
11401 std::optional<IntRange> L = TryGetExprRange(
11402 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11403 if (!L)
11404 return std::nullopt;
11405
11406 // If the divisor is constant, use that.
11407 if (std::optional<llvm::APSInt> divisor =
11408 BO->getRHS()->getIntegerConstantExpr(C)) {
11409 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11410 if (log2 >= L->Width)
11411 L->Width = (L->NonNegative ? 0 : 1);
11412 else
11413 L->Width = std::min(L->Width - log2, MaxWidth);
11414 return L;
11415 }
11416
11417 // Otherwise, just use the LHS's width.
11418 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11419 // could be -1.
11420 std::optional<IntRange> R = TryGetExprRange(
11421 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11422 if (!R)
11423 return std::nullopt;
11424
11425 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11426 }
11427
11428 case BO_Rem:
11429 Combine = IntRange::rem;
11430 break;
11431
11432 // The default behavior is okay for these.
11433 case BO_Xor:
11434 case BO_Or:
11435 break;
11436 }
11437
11438 // Combine the two ranges, but limit the result to the type in which we
11439 // performed the computation.
11440 QualType T = GetExprType(E);
11441 unsigned opWidth = C.getIntWidth(T);
11442 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11443 InConstantContext, Approximate);
11444 if (!L)
11445 return std::nullopt;
11446
11447 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11448 InConstantContext, Approximate);
11449 if (!R)
11450 return std::nullopt;
11451
11452 IntRange C = Combine(*L, *R);
11453 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11454 C.Width = std::min(C.Width, MaxWidth);
11455 return C;
11456 }
11457
11458 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11459 switch (UO->getOpcode()) {
11460 // Boolean-valued operations are white-listed.
11461 case UO_LNot:
11462 return IntRange::forBoolType();
11463
11464 // Operations with opaque sources are black-listed.
11465 case UO_Deref:
11466 case UO_AddrOf: // should be impossible
11467 return IntRange::forValueOfType(C, GetExprType(E));
11468
11469 case UO_Minus: {
11470 if (E->getType()->isUnsignedIntegerType()) {
11471 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11472 Approximate);
11473 }
11474
11475 std::optional<IntRange> SubRange = TryGetExprRange(
11476 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11477
11478 if (!SubRange)
11479 return std::nullopt;
11480
11481 // If the range was previously non-negative, we need an extra bit for the
11482 // sign bit. Otherwise, we need an extra bit because the negation of the
11483 // most-negative value is one bit wider than that value.
11484 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11485 }
11486
11487 case UO_Not: {
11488 if (E->getType()->isUnsignedIntegerType()) {
11489 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11490 Approximate);
11491 }
11492
11493 std::optional<IntRange> SubRange = TryGetExprRange(
11494 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11495
11496 if (!SubRange)
11497 return std::nullopt;
11498
11499 // The width increments by 1 if the sub-expression cannot be negative
11500 // since it now can be.
11501 return IntRange(
11502 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11503 false);
11504 }
11505
11506 default:
11507 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11508 Approximate);
11509 }
11510 }
11511
11512 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11513 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11514 Approximate);
11515
11516 if (const auto *BitField = E->getSourceBitField())
11517 return IntRange(BitField->getBitWidthValue(),
11518 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11519
11520 if (GetExprType(E)->isVoidType())
11521 return std::nullopt;
11522
11523 return IntRange::forValueOfType(C, GetExprType(E));
11524}
11525
11526static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11527 bool InConstantContext,
11528 bool Approximate) {
11529 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11530 Approximate);
11531}
11532
11533/// Checks whether the given value, which currently has the given
11534/// source semantics, has the same value when coerced through the
11535/// target semantics.
11536static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11537 const llvm::fltSemantics &Src,
11538 const llvm::fltSemantics &Tgt) {
11539 llvm::APFloat truncated = value;
11540
11541 bool ignored;
11542 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11543 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11544
11545 return truncated.bitwiseIsEqual(value);
11546}
11547
11548/// Checks whether the given value, which currently has the given
11549/// source semantics, has the same value when coerced through the
11550/// target semantics.
11551///
11552/// The value might be a vector of floats (or a complex number).
11553static bool IsSameFloatAfterCast(const APValue &value,
11554 const llvm::fltSemantics &Src,
11555 const llvm::fltSemantics &Tgt) {
11556 if (value.isFloat())
11557 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11558
11559 if (value.isVector()) {
11560 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11561 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11562 return false;
11563 return true;
11564 }
11565
11566 assert(value.isComplexFloat());
11567 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11568 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11569}
11570
11571static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11572 bool IsListInit = false);
11573
11574static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11575 // Suppress cases where we are comparing against an enum constant.
11576 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11577 if (isa<EnumConstantDecl>(DR->getDecl()))
11578 return true;
11579
11580 // Suppress cases where the value is expanded from a macro, unless that macro
11581 // is how a language represents a boolean literal. This is the case in both C
11582 // and Objective-C.
11583 SourceLocation BeginLoc = E->getBeginLoc();
11584 if (BeginLoc.isMacroID()) {
11585 StringRef MacroName = Lexer::getImmediateMacroName(
11586 BeginLoc, S.getSourceManager(), S.getLangOpts());
11587 return MacroName != "YES" && MacroName != "NO" &&
11588 MacroName != "true" && MacroName != "false";
11589 }
11590
11591 return false;
11592}
11593
11594static bool isKnownToHaveUnsignedValue(const Expr *E) {
11595 return E->getType()->isIntegerType() &&
11596 (!E->getType()->isSignedIntegerType() ||
11598}
11599
11600namespace {
11601/// The promoted range of values of a type. In general this has the
11602/// following structure:
11603///
11604/// |-----------| . . . |-----------|
11605/// ^ ^ ^ ^
11606/// Min HoleMin HoleMax Max
11607///
11608/// ... where there is only a hole if a signed type is promoted to unsigned
11609/// (in which case Min and Max are the smallest and largest representable
11610/// values).
11611struct PromotedRange {
11612 // Min, or HoleMax if there is a hole.
11613 llvm::APSInt PromotedMin;
11614 // Max, or HoleMin if there is a hole.
11615 llvm::APSInt PromotedMax;
11616
11617 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11618 if (R.Width == 0)
11619 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11620 else if (R.Width >= BitWidth && !Unsigned) {
11621 // Promotion made the type *narrower*. This happens when promoting
11622 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11623 // Treat all values of 'signed int' as being in range for now.
11624 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11625 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11626 } else {
11627 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11628 .extOrTrunc(BitWidth);
11629 PromotedMin.setIsUnsigned(Unsigned);
11630
11631 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11632 .extOrTrunc(BitWidth);
11633 PromotedMax.setIsUnsigned(Unsigned);
11634 }
11635 }
11636
11637 // Determine whether this range is contiguous (has no hole).
11638 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11639
11640 // Where a constant value is within the range.
11641 enum ComparisonResult {
11642 LT = 0x1,
11643 LE = 0x2,
11644 GT = 0x4,
11645 GE = 0x8,
11646 EQ = 0x10,
11647 NE = 0x20,
11648 InRangeFlag = 0x40,
11649
11650 Less = LE | LT | NE,
11651 Min = LE | InRangeFlag,
11652 InRange = InRangeFlag,
11653 Max = GE | InRangeFlag,
11654 Greater = GE | GT | NE,
11655
11656 OnlyValue = LE | GE | EQ | InRangeFlag,
11657 InHole = NE
11658 };
11659
11660 ComparisonResult compare(const llvm::APSInt &Value) const {
11661 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11662 Value.isUnsigned() == PromotedMin.isUnsigned());
11663 if (!isContiguous()) {
11664 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11665 if (Value.isMinValue()) return Min;
11666 if (Value.isMaxValue()) return Max;
11667 if (Value >= PromotedMin) return InRange;
11668 if (Value <= PromotedMax) return InRange;
11669 return InHole;
11670 }
11671
11672 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11673 case -1: return Less;
11674 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11675 case 1:
11676 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11677 case -1: return InRange;
11678 case 0: return Max;
11679 case 1: return Greater;
11680 }
11681 }
11682
11683 llvm_unreachable("impossible compare result");
11684 }
11685
11686 static std::optional<StringRef>
11687 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11688 if (Op == BO_Cmp) {
11689 ComparisonResult LTFlag = LT, GTFlag = GT;
11690 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11691
11692 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11693 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11694 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11695 return std::nullopt;
11696 }
11697
11698 ComparisonResult TrueFlag, FalseFlag;
11699 if (Op == BO_EQ) {
11700 TrueFlag = EQ;
11701 FalseFlag = NE;
11702 } else if (Op == BO_NE) {
11703 TrueFlag = NE;
11704 FalseFlag = EQ;
11705 } else {
11706 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11707 TrueFlag = LT;
11708 FalseFlag = GE;
11709 } else {
11710 TrueFlag = GT;
11711 FalseFlag = LE;
11712 }
11713 if (Op == BO_GE || Op == BO_LE)
11714 std::swap(TrueFlag, FalseFlag);
11715 }
11716 if (R & TrueFlag)
11717 return StringRef("true");
11718 if (R & FalseFlag)
11719 return StringRef("false");
11720 return std::nullopt;
11721 }
11722};
11723}
11724
11725static bool HasEnumType(const Expr *E) {
11726 // Strip off implicit integral promotions.
11727 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11728 if (ICE->getCastKind() != CK_IntegralCast &&
11729 ICE->getCastKind() != CK_NoOp)
11730 break;
11731 E = ICE->getSubExpr();
11732 }
11733
11734 return E->getType()->isEnumeralType();
11735}
11736
11737static int classifyConstantValue(Expr *Constant) {
11738 // The values of this enumeration are used in the diagnostics
11739 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11740 enum ConstantValueKind {
11741 Miscellaneous = 0,
11742 LiteralTrue,
11743 LiteralFalse
11744 };
11745 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11746 return BL->getValue() ? ConstantValueKind::LiteralTrue
11747 : ConstantValueKind::LiteralFalse;
11748 return ConstantValueKind::Miscellaneous;
11749}
11750
11752 Expr *Constant, Expr *Other,
11753 const llvm::APSInt &Value,
11754 bool RhsConstant) {
11756 return false;
11757
11758 Expr *OriginalOther = Other;
11759
11760 Constant = Constant->IgnoreParenImpCasts();
11761 Other = Other->IgnoreParenImpCasts();
11762
11763 // Suppress warnings on tautological comparisons between values of the same
11764 // enumeration type. There are only two ways we could warn on this:
11765 // - If the constant is outside the range of representable values of
11766 // the enumeration. In such a case, we should warn about the cast
11767 // to enumeration type, not about the comparison.
11768 // - If the constant is the maximum / minimum in-range value. For an
11769 // enumeratin type, such comparisons can be meaningful and useful.
11770 if (Constant->getType()->isEnumeralType() &&
11771 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11772 return false;
11773
11774 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11775 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11776 if (!OtherValueRange)
11777 return false;
11778
11779 QualType OtherT = Other->getType();
11780 if (const auto *AT = OtherT->getAs<AtomicType>())
11781 OtherT = AT->getValueType();
11782 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11783
11784 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11785 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11786 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11787 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11788 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11789
11790 // Whether we're treating Other as being a bool because of the form of
11791 // expression despite it having another type (typically 'int' in C).
11792 bool OtherIsBooleanDespiteType =
11793 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11794 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11795 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11796
11797 // Check if all values in the range of possible values of this expression
11798 // lead to the same comparison outcome.
11799 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11800 Value.isUnsigned());
11801 auto Cmp = OtherPromotedValueRange.compare(Value);
11802 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11803 if (!Result)
11804 return false;
11805
11806 // Also consider the range determined by the type alone. This allows us to
11807 // classify the warning under the proper diagnostic group.
11808 bool TautologicalTypeCompare = false;
11809 {
11810 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11811 Value.isUnsigned());
11812 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11813 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11814 RhsConstant)) {
11815 TautologicalTypeCompare = true;
11816 Cmp = TypeCmp;
11817 Result = TypeResult;
11818 }
11819 }
11820
11821 // Don't warn if the non-constant operand actually always evaluates to the
11822 // same value.
11823 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11824 return false;
11825
11826 // Suppress the diagnostic for an in-range comparison if the constant comes
11827 // from a macro or enumerator. We don't want to diagnose
11828 //
11829 // some_long_value <= INT_MAX
11830 //
11831 // when sizeof(int) == sizeof(long).
11832 bool InRange = Cmp & PromotedRange::InRangeFlag;
11833 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11834 return false;
11835
11836 // A comparison of an unsigned bit-field against 0 is really a type problem,
11837 // even though at the type level the bit-field might promote to 'signed int'.
11838 if (Other->refersToBitField() && InRange && Value == 0 &&
11839 Other->getType()->isUnsignedIntegerOrEnumerationType())
11840 TautologicalTypeCompare = true;
11841
11842 // If this is a comparison to an enum constant, include that
11843 // constant in the diagnostic.
11844 const EnumConstantDecl *ED = nullptr;
11845 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11846 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11847
11848 // Should be enough for uint128 (39 decimal digits)
11849 SmallString<64> PrettySourceValue;
11850 llvm::raw_svector_ostream OS(PrettySourceValue);
11851 if (ED) {
11852 OS << '\'' << *ED << "' (" << Value << ")";
11853 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11854 Constant->IgnoreParenImpCasts())) {
11855 OS << (BL->getValue() ? "YES" : "NO");
11856 } else {
11857 OS << Value;
11858 }
11859
11860 if (!TautologicalTypeCompare) {
11861 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11862 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11863 << E->getOpcodeStr() << OS.str() << *Result
11864 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11865 return true;
11866 }
11867
11868 if (IsObjCSignedCharBool) {
11870 S.PDiag(diag::warn_tautological_compare_objc_bool)
11871 << OS.str() << *Result);
11872 return true;
11873 }
11874
11875 // FIXME: We use a somewhat different formatting for the in-range cases and
11876 // cases involving boolean values for historical reasons. We should pick a
11877 // consistent way of presenting these diagnostics.
11878 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11879
11881 E->getOperatorLoc(), E,
11882 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11883 : diag::warn_tautological_bool_compare)
11884 << OS.str() << classifyConstantValue(Constant) << OtherT
11885 << OtherIsBooleanDespiteType << *Result
11886 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11887 } else {
11888 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11889 unsigned Diag =
11890 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11891 ? (HasEnumType(OriginalOther)
11892 ? diag::warn_unsigned_enum_always_true_comparison
11893 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11894 : diag::warn_unsigned_always_true_comparison)
11895 : diag::warn_tautological_constant_compare;
11896
11897 S.Diag(E->getOperatorLoc(), Diag)
11898 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11899 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11900 }
11901
11902 return true;
11903}
11904
11905/// Analyze the operands of the given comparison. Implements the
11906/// fallback case from AnalyzeComparison.
11911
11912/// Implements -Wsign-compare.
11913///
11914/// \param E the binary operator to check for warnings
11916 // The type the comparison is being performed in.
11917 QualType T = E->getLHS()->getType();
11918
11919 // Only analyze comparison operators where both sides have been converted to
11920 // the same type.
11922 return AnalyzeImpConvsInComparison(S, E);
11923
11924 // Don't analyze value-dependent comparisons directly.
11925 if (E->isValueDependent())
11926 return AnalyzeImpConvsInComparison(S, E);
11927
11928 Expr *LHS = E->getLHS();
11929 Expr *RHS = E->getRHS();
11930
11931 if (T->isIntegralType(S.Context)) {
11932 std::optional<llvm::APSInt> RHSValue =
11934 std::optional<llvm::APSInt> LHSValue =
11936
11937 // We don't care about expressions whose result is a constant.
11938 if (RHSValue && LHSValue)
11939 return AnalyzeImpConvsInComparison(S, E);
11940
11941 // We only care about expressions where just one side is literal
11942 if ((bool)RHSValue ^ (bool)LHSValue) {
11943 // Is the constant on the RHS or LHS?
11944 const bool RhsConstant = (bool)RHSValue;
11945 Expr *Const = RhsConstant ? RHS : LHS;
11946 Expr *Other = RhsConstant ? LHS : RHS;
11947 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11948
11949 // Check whether an integer constant comparison results in a value
11950 // of 'true' or 'false'.
11951 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11952 return AnalyzeImpConvsInComparison(S, E);
11953 }
11954 }
11955
11956 if (!T->hasUnsignedIntegerRepresentation()) {
11957 // We don't do anything special if this isn't an unsigned integral
11958 // comparison: we're only interested in integral comparisons, and
11959 // signed comparisons only happen in cases we don't care to warn about.
11960 return AnalyzeImpConvsInComparison(S, E);
11961 }
11962
11963 LHS = LHS->IgnoreParenImpCasts();
11964 RHS = RHS->IgnoreParenImpCasts();
11965
11966 if (!S.getLangOpts().CPlusPlus) {
11967 // Avoid warning about comparison of integers with different signs when
11968 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11969 // the type of `E`.
11970 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11971 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11972 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11973 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11974 }
11975
11976 // Check to see if one of the (unmodified) operands is of different
11977 // signedness.
11978 Expr *signedOperand, *unsignedOperand;
11980 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11981 "unsigned comparison between two signed integer expressions?");
11982 signedOperand = LHS;
11983 unsignedOperand = RHS;
11984 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11985 signedOperand = RHS;
11986 unsignedOperand = LHS;
11987 } else {
11988 return AnalyzeImpConvsInComparison(S, E);
11989 }
11990
11991 // Otherwise, calculate the effective range of the signed operand.
11992 std::optional<IntRange> signedRange =
11994 /*Approximate=*/true);
11995 if (!signedRange)
11996 return;
11997
11998 // Go ahead and analyze implicit conversions in the operands. Note
11999 // that we skip the implicit conversions on both sides.
12002
12003 // If the signed range is non-negative, -Wsign-compare won't fire.
12004 if (signedRange->NonNegative)
12005 return;
12006
12007 // For (in)equality comparisons, if the unsigned operand is a
12008 // constant which cannot collide with a overflowed signed operand,
12009 // then reinterpreting the signed operand as unsigned will not
12010 // change the result of the comparison.
12011 if (E->isEqualityOp()) {
12012 unsigned comparisonWidth = S.Context.getIntWidth(T);
12013 std::optional<IntRange> unsignedRange = TryGetExprRange(
12014 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12015 /*Approximate=*/true);
12016 if (!unsignedRange)
12017 return;
12018
12019 // We should never be unable to prove that the unsigned operand is
12020 // non-negative.
12021 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12022
12023 if (unsignedRange->Width < comparisonWidth)
12024 return;
12025 }
12026
12028 S.PDiag(diag::warn_mixed_sign_comparison)
12029 << LHS->getType() << RHS->getType()
12030 << LHS->getSourceRange() << RHS->getSourceRange());
12031}
12032
12033/// Analyzes an attempt to assign the given value to a bitfield.
12034///
12035/// Returns true if there was something fishy about the attempt.
12037 SourceLocation InitLoc) {
12038 assert(Bitfield->isBitField());
12039 if (Bitfield->isInvalidDecl())
12040 return false;
12041
12042 // White-list bool bitfields.
12043 QualType BitfieldType = Bitfield->getType();
12044 if (BitfieldType->isBooleanType())
12045 return false;
12046
12047 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12048 // If the underlying enum type was not explicitly specified as an unsigned
12049 // type and the enum contain only positive values, MSVC++ will cause an
12050 // inconsistency by storing this as a signed type.
12051 if (S.getLangOpts().CPlusPlus11 &&
12052 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12053 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12054 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12055 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12056 << BitfieldEnumDecl;
12057 }
12058 }
12059
12060 // Ignore value- or type-dependent expressions.
12061 if (Bitfield->getBitWidth()->isValueDependent() ||
12062 Bitfield->getBitWidth()->isTypeDependent() ||
12063 Init->isValueDependent() ||
12064 Init->isTypeDependent())
12065 return false;
12066
12067 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12068 unsigned FieldWidth = Bitfield->getBitWidthValue();
12069
12070 Expr::EvalResult Result;
12071 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12073 // The RHS is not constant. If the RHS has an enum type, make sure the
12074 // bitfield is wide enough to hold all the values of the enum without
12075 // truncation.
12076 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12077 const PreferredTypeAttr *PTAttr = nullptr;
12078 if (!ED) {
12079 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12080 if (PTAttr)
12081 ED = PTAttr->getType()->getAsEnumDecl();
12082 }
12083 if (ED) {
12084 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12085
12086 // Enum types are implicitly signed on Windows, so check if there are any
12087 // negative enumerators to see if the enum was intended to be signed or
12088 // not.
12089 bool SignedEnum = ED->getNumNegativeBits() > 0;
12090
12091 // Check for surprising sign changes when assigning enum values to a
12092 // bitfield of different signedness. If the bitfield is signed and we
12093 // have exactly the right number of bits to store this unsigned enum,
12094 // suggest changing the enum to an unsigned type. This typically happens
12095 // on Windows where unfixed enums always use an underlying type of 'int'.
12096 unsigned DiagID = 0;
12097 if (SignedEnum && !SignedBitfield) {
12098 DiagID =
12099 PTAttr == nullptr
12100 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12101 : diag::
12102 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12103 } else if (SignedBitfield && !SignedEnum &&
12104 ED->getNumPositiveBits() == FieldWidth) {
12105 DiagID =
12106 PTAttr == nullptr
12107 ? diag::warn_signed_bitfield_enum_conversion
12108 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12109 }
12110 if (DiagID) {
12111 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12112 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12113 SourceRange TypeRange =
12114 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12115 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12116 << SignedEnum << TypeRange;
12117 if (PTAttr)
12118 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12119 << ED;
12120 }
12121
12122 // Compute the required bitwidth. If the enum has negative values, we need
12123 // one more bit than the normal number of positive bits to represent the
12124 // sign bit.
12125 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12126 ED->getNumNegativeBits())
12127 : ED->getNumPositiveBits();
12128
12129 // Check the bitwidth.
12130 if (BitsNeeded > FieldWidth) {
12131 Expr *WidthExpr = Bitfield->getBitWidth();
12132 auto DiagID =
12133 PTAttr == nullptr
12134 ? diag::warn_bitfield_too_small_for_enum
12135 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12136 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12137 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12138 << BitsNeeded << ED << WidthExpr->getSourceRange();
12139 if (PTAttr)
12140 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12141 << ED;
12142 }
12143 }
12144
12145 return false;
12146 }
12147
12148 llvm::APSInt Value = Result.Val.getInt();
12149
12150 unsigned OriginalWidth = Value.getBitWidth();
12151
12152 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12153 // false positives where the user is demonstrating they intend to use the
12154 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12155 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12156 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12157 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12158 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12159 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12160 S.findMacroSpelling(MaybeMacroLoc, "true"))
12161 return false;
12162 }
12163
12164 if (!Value.isSigned() || Value.isNegative())
12165 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12166 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12167 OriginalWidth = Value.getSignificantBits();
12168
12169 if (OriginalWidth <= FieldWidth)
12170 return false;
12171
12172 // Compute the value which the bitfield will contain.
12173 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12174 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12175
12176 // Check whether the stored value is equal to the original value.
12177 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12178 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12179 return false;
12180
12181 std::string PrettyValue = toString(Value, 10);
12182 std::string PrettyTrunc = toString(TruncatedValue, 10);
12183
12184 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12185 ? diag::warn_impcast_single_bit_bitield_precision_constant
12186 : diag::warn_impcast_bitfield_precision_constant)
12187 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12188 << Init->getSourceRange();
12189
12190 return true;
12191}
12192
12193/// Analyze the given simple or compound assignment for warning-worthy
12194/// operations.
12196 // Just recurse on the LHS.
12198
12199 // We want to recurse on the RHS as normal unless we're assigning to
12200 // a bitfield.
12201 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12202 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12203 E->getOperatorLoc())) {
12204 // Recurse, ignoring any implicit conversions on the RHS.
12206 E->getOperatorLoc());
12207 }
12208 }
12209
12211
12212 // Diagnose implicitly sequentially-consistent atomic assignment.
12213 if (E->getLHS()->getType()->isAtomicType())
12214 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12215}
12216
12217/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12218static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12219 QualType T, SourceLocation CContext, unsigned diag,
12220 bool PruneControlFlow = false) {
12221 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12222 // address space annotations isn't really useful. The warnings aren't because
12223 // you're converting a `private int` to `unsigned int`, it is because you're
12224 // conerting `int` to `unsigned int`.
12225 if (SourceType.hasAddressSpace())
12226 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12227 if (T.hasAddressSpace())
12229 if (PruneControlFlow) {
12231 S.PDiag(diag)
12232 << SourceType << T << E->getSourceRange()
12233 << SourceRange(CContext));
12234 return;
12235 }
12236 S.Diag(E->getExprLoc(), diag)
12237 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12238}
12239
12240/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12241static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12242 SourceLocation CContext, unsigned diag,
12243 bool PruneControlFlow = false) {
12244 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12245}
12246
12247/// Diagnose an implicit cast from a floating point value to an integer value.
12248static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12249 SourceLocation CContext) {
12250 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12251 bool PruneWarnings = S.inTemplateInstantiation();
12252
12253 const Expr *InnerE = E->IgnoreParenImpCasts();
12254 // We also want to warn on, e.g., "int i = -1.234"
12255 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12256 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12257 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12258
12259 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12260
12261 llvm::APFloat Value(0.0);
12262 bool IsConstant =
12264 if (!IsConstant) {
12265 if (S.ObjC().isSignedCharBool(T)) {
12267 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12268 << E->getType());
12269 }
12270
12271 return DiagnoseImpCast(S, E, T, CContext,
12272 diag::warn_impcast_float_integer, PruneWarnings);
12273 }
12274
12275 bool isExact = false;
12276
12277 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12278 T->hasUnsignedIntegerRepresentation());
12279 llvm::APFloat::opStatus Result = Value.convertToInteger(
12280 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12281
12282 // FIXME: Force the precision of the source value down so we don't print
12283 // digits which are usually useless (we don't really care here if we
12284 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12285 // would automatically print the shortest representation, but it's a bit
12286 // tricky to implement.
12287 SmallString<16> PrettySourceValue;
12288 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12289 precision = (precision * 59 + 195) / 196;
12290 Value.toString(PrettySourceValue, precision);
12291
12292 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12294 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12295 << PrettySourceValue);
12296 }
12297
12298 if (Result == llvm::APFloat::opOK && isExact) {
12299 if (IsLiteral) return;
12300 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12301 PruneWarnings);
12302 }
12303
12304 // Conversion of a floating-point value to a non-bool integer where the
12305 // integral part cannot be represented by the integer type is undefined.
12306 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12307 return DiagnoseImpCast(
12308 S, E, T, CContext,
12309 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12310 : diag::warn_impcast_float_to_integer_out_of_range,
12311 PruneWarnings);
12312
12313 unsigned DiagID = 0;
12314 if (IsLiteral) {
12315 // Warn on floating point literal to integer.
12316 DiagID = diag::warn_impcast_literal_float_to_integer;
12317 } else if (IntegerValue == 0) {
12318 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12319 return DiagnoseImpCast(S, E, T, CContext,
12320 diag::warn_impcast_float_integer, PruneWarnings);
12321 }
12322 // Warn on non-zero to zero conversion.
12323 DiagID = diag::warn_impcast_float_to_integer_zero;
12324 } else {
12325 if (IntegerValue.isUnsigned()) {
12326 if (!IntegerValue.isMaxValue()) {
12327 return DiagnoseImpCast(S, E, T, CContext,
12328 diag::warn_impcast_float_integer, PruneWarnings);
12329 }
12330 } else { // IntegerValue.isSigned()
12331 if (!IntegerValue.isMaxSignedValue() &&
12332 !IntegerValue.isMinSignedValue()) {
12333 return DiagnoseImpCast(S, E, T, CContext,
12334 diag::warn_impcast_float_integer, PruneWarnings);
12335 }
12336 }
12337 // Warn on evaluatable floating point expression to integer conversion.
12338 DiagID = diag::warn_impcast_float_to_integer;
12339 }
12340
12341 SmallString<16> PrettyTargetValue;
12342 if (IsBool)
12343 PrettyTargetValue = Value.isZero() ? "false" : "true";
12344 else
12345 IntegerValue.toString(PrettyTargetValue);
12346
12347 if (PruneWarnings) {
12349 S.PDiag(DiagID)
12350 << E->getType() << T.getUnqualifiedType()
12351 << PrettySourceValue << PrettyTargetValue
12352 << E->getSourceRange() << SourceRange(CContext));
12353 } else {
12354 S.Diag(E->getExprLoc(), DiagID)
12355 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12356 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12357 }
12358}
12359
12360/// Analyze the given compound assignment for the possible losing of
12361/// floating-point precision.
12363 assert(isa<CompoundAssignOperator>(E) &&
12364 "Must be compound assignment operation");
12365 // Recurse on the LHS and RHS in here
12368
12369 if (E->getLHS()->getType()->isAtomicType())
12370 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12371
12372 // Now check the outermost expression
12373 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12374 const auto *RBT = cast<CompoundAssignOperator>(E)
12375 ->getComputationResultType()
12376 ->getAs<BuiltinType>();
12377
12378 // The below checks assume source is floating point.
12379 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12380
12381 // If source is floating point but target is an integer.
12382 if (ResultBT->isInteger())
12383 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12384 E->getExprLoc(), diag::warn_impcast_float_integer);
12385
12386 if (!ResultBT->isFloatingPoint())
12387 return;
12388
12389 // If both source and target are floating points, warn about losing precision.
12391 QualType(ResultBT, 0), QualType(RBT, 0));
12392 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12393 // warn about dropping FP rank.
12394 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12395 diag::warn_impcast_float_result_precision);
12396}
12397
12398static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12399 IntRange Range) {
12400 if (!Range.Width) return "0";
12401
12402 llvm::APSInt ValueInRange = Value;
12403 ValueInRange.setIsSigned(!Range.NonNegative);
12404 ValueInRange = ValueInRange.trunc(Range.Width);
12405 return toString(ValueInRange, 10);
12406}
12407
12408static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12409 bool ToBool) {
12410 if (!isa<ImplicitCastExpr>(Ex))
12411 return false;
12412
12413 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12415 const Type *Source =
12417 if (Target->isDependentType())
12418 return false;
12419
12420 const auto *FloatCandidateBT =
12421 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12422 const Type *BoolCandidateType = ToBool ? Target : Source;
12423
12424 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12425 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12426}
12427
12428static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12429 SourceLocation CC) {
12430 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12431 const Expr *CurrA = TheCall->getArg(I);
12432 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12433 continue;
12434
12435 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12436 S, TheCall->getArg(I - 1), false));
12437 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12438 S, TheCall->getArg(I + 1), false));
12439 if (IsSwapped) {
12440 // Warn on this floating-point to bool conversion.
12442 CurrA->getType(), CC,
12443 diag::warn_impcast_floating_point_to_bool);
12444 }
12445 }
12446}
12447
12449 SourceLocation CC) {
12450 // Don't warn on functions which have return type nullptr_t.
12451 if (isa<CallExpr>(E))
12452 return;
12453
12454 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12455 const Expr *NewE = E->IgnoreParenImpCasts();
12456 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12457 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12458 if (!IsGNUNullExpr && !HasNullPtrType)
12459 return;
12460
12461 // Return if target type is a safe conversion.
12462 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12463 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12464 return;
12465
12466 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12467 E->getExprLoc()))
12468 return;
12469
12471
12472 // Venture through the macro stacks to get to the source of macro arguments.
12473 // The new location is a better location than the complete location that was
12474 // passed in.
12475 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12477
12478 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12479 if (IsGNUNullExpr && Loc.isMacroID()) {
12480 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12481 Loc, S.SourceMgr, S.getLangOpts());
12482 if (MacroName == "NULL")
12484 }
12485
12486 // Only warn if the null and context location are in the same macro expansion.
12487 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12488 return;
12489
12490 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12491 << HasNullPtrType << T << SourceRange(CC)
12494}
12495
12496// Helper function to filter out cases for constant width constant conversion.
12497// Don't warn on char array initialization or for non-decimal values.
12499 SourceLocation CC) {
12500 // If initializing from a constant, and the constant starts with '0',
12501 // then it is a binary, octal, or hexadecimal. Allow these constants
12502 // to fill all the bits, even if there is a sign change.
12503 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12504 const char FirstLiteralCharacter =
12505 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12506 if (FirstLiteralCharacter == '0')
12507 return false;
12508 }
12509
12510 // If the CC location points to a '{', and the type is char, then assume
12511 // assume it is an array initialization.
12512 if (CC.isValid() && T->isCharType()) {
12513 const char FirstContextCharacter =
12515 if (FirstContextCharacter == '{')
12516 return false;
12517 }
12518
12519 return true;
12520}
12521
12523 const auto *IL = dyn_cast<IntegerLiteral>(E);
12524 if (!IL) {
12525 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12526 if (UO->getOpcode() == UO_Minus)
12527 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12528 }
12529 }
12530
12531 return IL;
12532}
12533
12535 E = E->IgnoreParenImpCasts();
12536 SourceLocation ExprLoc = E->getExprLoc();
12537
12538 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12539 BinaryOperator::Opcode Opc = BO->getOpcode();
12540 Expr::EvalResult Result;
12541 // Do not diagnose unsigned shifts.
12542 if (Opc == BO_Shl) {
12543 const auto *LHS = getIntegerLiteral(BO->getLHS());
12544 const auto *RHS = getIntegerLiteral(BO->getRHS());
12545 if (LHS && LHS->getValue() == 0)
12546 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12547 else if (!E->isValueDependent() && LHS && RHS &&
12548 RHS->getValue().isNonNegative() &&
12550 S.Diag(ExprLoc, diag::warn_left_shift_always)
12551 << (Result.Val.getInt() != 0);
12552 else if (E->getType()->isSignedIntegerType())
12553 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12556 ") != 0");
12557 }
12558 }
12559
12560 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12561 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12562 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12563 if (!LHS || !RHS)
12564 return;
12565 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12566 (RHS->getValue() == 0 || RHS->getValue() == 1))
12567 // Do not diagnose common idioms.
12568 return;
12569 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12570 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12571 }
12572}
12573
12575 const Type *Target, Expr *E,
12576 QualType T,
12577 SourceLocation CC) {
12578 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12579 Source != Target);
12580
12581 // Lone surrogates have a distinct representation in UTF-32.
12582 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12583 // so don't warn on such conversion.
12584 if (Source->isChar16Type() && Target->isChar32Type())
12585 return;
12586
12587 Expr::EvalResult Result;
12590 llvm::APSInt Value(32);
12591 Value = Result.Val.getInt();
12592 bool IsASCII = Value <= 0x7F;
12593 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12594 bool ConversionPreservesSemantics =
12595 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12596
12597 if (!ConversionPreservesSemantics) {
12598 auto IsSingleCodeUnitCP = [](const QualType &T,
12599 const llvm::APSInt &Value) {
12600 if (T->isChar8Type())
12601 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12602 if (T->isChar16Type())
12603 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12604 assert(T->isChar32Type());
12605 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12606 };
12607
12608 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12609 << E->getType() << T
12610 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12611 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12612 }
12613 } else {
12614 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12616 DiagnoseImpCast(S, E, T, CC,
12617 LosesPrecision ? diag::warn_impcast_unicode_precision
12618 : diag::warn_impcast_unicode_char_type);
12619 }
12620}
12621
12623 From = Context.getCanonicalType(From);
12624 To = Context.getCanonicalType(To);
12625 QualType MaybePointee = From->getPointeeType();
12626 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12627 From = MaybePointee;
12628 MaybePointee = To->getPointeeType();
12629 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12630 To = MaybePointee;
12631
12632 if (const auto *FromFn = From->getAs<FunctionType>()) {
12633 if (const auto *ToFn = To->getAs<FunctionType>()) {
12634 if (FromFn->getCFIUncheckedCalleeAttr() &&
12635 !ToFn->getCFIUncheckedCalleeAttr())
12636 return true;
12637 }
12638 }
12639 return false;
12640}
12641
12643 bool *ICContext, bool IsListInit) {
12644 if (E->isTypeDependent() || E->isValueDependent()) return;
12645
12646 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12647 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12648 if (Source == Target) return;
12649 if (Target->isDependentType()) return;
12650
12651 // If the conversion context location is invalid don't complain. We also
12652 // don't want to emit a warning if the issue occurs from the expansion of
12653 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12654 // delay this check as long as possible. Once we detect we are in that
12655 // scenario, we just return.
12656 if (CC.isInvalid())
12657 return;
12658
12659 if (Source->isAtomicType())
12660 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12661
12662 // Diagnose implicit casts to bool.
12663 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12664 if (isa<StringLiteral>(E))
12665 // Warn on string literal to bool. Checks for string literals in logical
12666 // and expressions, for instance, assert(0 && "error here"), are
12667 // prevented by a check in AnalyzeImplicitConversions().
12668 return DiagnoseImpCast(*this, E, T, CC,
12669 diag::warn_impcast_string_literal_to_bool);
12672 // This covers the literal expressions that evaluate to Objective-C
12673 // objects.
12674 return DiagnoseImpCast(*this, E, T, CC,
12675 diag::warn_impcast_objective_c_literal_to_bool);
12676 }
12677 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12678 // Warn on pointer to bool conversion that is always true.
12680 SourceRange(CC));
12681 }
12682 }
12683
12684 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12685 // is a typedef for signed char (macOS), then that constant value has to be 1
12686 // or 0.
12687 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12690 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12692 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12693 << toString(Result.Val.getInt(), 10));
12694 }
12695 return;
12696 }
12697 }
12698
12699 // Check implicit casts from Objective-C collection literals to specialized
12700 // collection types, e.g., NSArray<NSString *> *.
12701 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12702 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12703 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12704 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12705
12706 // Strip vector types.
12707 if (isa<VectorType>(Source)) {
12708 if (Target->isSveVLSBuiltinType() &&
12709 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12710 QualType(Source, 0)) ||
12711 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12712 QualType(Source, 0))))
12713 return;
12714
12715 if (Target->isRVVVLSBuiltinType() &&
12716 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12717 QualType(Source, 0)) ||
12718 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12719 QualType(Source, 0))))
12720 return;
12721
12722 if (!isa<VectorType>(Target)) {
12723 if (SourceMgr.isInSystemMacro(CC))
12724 return;
12725 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12726 }
12727 if (getLangOpts().HLSL &&
12728 Target->castAs<VectorType>()->getNumElements() <
12729 Source->castAs<VectorType>()->getNumElements()) {
12730 // Diagnose vector truncation but don't return. We may also want to
12731 // diagnose an element conversion.
12732 DiagnoseImpCast(*this, E, T, CC,
12733 diag::warn_hlsl_impcast_vector_truncation);
12734 }
12735
12736 // If the vector cast is cast between two vectors of the same size, it is
12737 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12738 if (!getLangOpts().HLSL &&
12739 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12740 return;
12741
12742 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12743 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12744 }
12745 if (const auto *VecTy = dyn_cast<VectorType>(Target))
12746 Target = VecTy->getElementType().getTypePtr();
12747
12748 if (isa<ConstantMatrixType>(Source)) {
12749 if (Target->isScalarType())
12750 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
12751
12752 if (getLangOpts().HLSL &&
12754 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
12755 // Diagnose Matrix truncation but don't return. We may also want to
12756 // diagnose an element conversion.
12757 DiagnoseImpCast(*this, E, T, CC,
12758 diag::warn_hlsl_impcast_matrix_truncation);
12759 }
12760 }
12761 // Strip complex types.
12762 if (isa<ComplexType>(Source)) {
12763 if (!isa<ComplexType>(Target)) {
12764 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12765 return;
12766
12767 return DiagnoseImpCast(*this, E, T, CC,
12769 ? diag::err_impcast_complex_scalar
12770 : diag::warn_impcast_complex_scalar);
12771 }
12772
12773 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12774 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12775 }
12776
12777 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12778 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12779
12780 // Strip SVE vector types
12781 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12782 // Need the original target type for vector type checks
12783 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12784 // Handle conversion from scalable to fixed when msve-vector-bits is
12785 // specified
12786 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12787 QualType(Source, 0)) ||
12788 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12789 QualType(Source, 0)))
12790 return;
12791
12792 // If the vector cast is cast between two vectors of the same size, it is
12793 // a bitcast, not a conversion.
12794 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12795 return;
12796
12797 Source = SourceBT->getSveEltType(Context).getTypePtr();
12798 }
12799
12800 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12801 Target = TargetBT->getSveEltType(Context).getTypePtr();
12802
12803 // If the source is floating point...
12804 if (SourceBT && SourceBT->isFloatingPoint()) {
12805 // ...and the target is floating point...
12806 if (TargetBT && TargetBT->isFloatingPoint()) {
12807 // ...then warn if we're dropping FP rank.
12808
12810 QualType(SourceBT, 0), QualType(TargetBT, 0));
12811 if (Order > 0) {
12812 // Don't warn about float constants that are precisely
12813 // representable in the target type.
12814 Expr::EvalResult result;
12815 if (E->EvaluateAsRValue(result, Context)) {
12816 // Value might be a float, a float vector, or a float complex.
12818 result.Val,
12819 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12820 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12821 return;
12822 }
12823
12824 if (SourceMgr.isInSystemMacro(CC))
12825 return;
12826
12827 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12828 }
12829 // ... or possibly if we're increasing rank, too
12830 else if (Order < 0) {
12831 if (SourceMgr.isInSystemMacro(CC))
12832 return;
12833
12834 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12835 }
12836 return;
12837 }
12838
12839 // If the target is integral, always warn.
12840 if (TargetBT && TargetBT->isInteger()) {
12841 if (SourceMgr.isInSystemMacro(CC))
12842 return;
12843
12844 DiagnoseFloatingImpCast(*this, E, T, CC);
12845 }
12846
12847 // Detect the case where a call result is converted from floating-point to
12848 // to bool, and the final argument to the call is converted from bool, to
12849 // discover this typo:
12850 //
12851 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12852 //
12853 // FIXME: This is an incredibly special case; is there some more general
12854 // way to detect this class of misplaced-parentheses bug?
12855 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12856 // Check last argument of function call to see if it is an
12857 // implicit cast from a type matching the type the result
12858 // is being cast to.
12859 CallExpr *CEx = cast<CallExpr>(E);
12860 if (unsigned NumArgs = CEx->getNumArgs()) {
12861 Expr *LastA = CEx->getArg(NumArgs - 1);
12862 Expr *InnerE = LastA->IgnoreParenImpCasts();
12863 if (isa<ImplicitCastExpr>(LastA) &&
12864 InnerE->getType()->isBooleanType()) {
12865 // Warn on this floating-point to bool conversion
12866 DiagnoseImpCast(*this, E, T, CC,
12867 diag::warn_impcast_floating_point_to_bool);
12868 }
12869 }
12870 }
12871 return;
12872 }
12873
12874 // Valid casts involving fixed point types should be accounted for here.
12875 if (Source->isFixedPointType()) {
12876 if (Target->isUnsaturatedFixedPointType()) {
12880 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12881 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12882 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12883 if (Value > MaxVal || Value < MinVal) {
12885 PDiag(diag::warn_impcast_fixed_point_range)
12886 << Value.toString() << T
12887 << E->getSourceRange()
12888 << clang::SourceRange(CC));
12889 return;
12890 }
12891 }
12892 } else if (Target->isIntegerType()) {
12896 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12897
12898 bool Overflowed;
12899 llvm::APSInt IntResult = FXResult.convertToInt(
12900 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12901 &Overflowed);
12902
12903 if (Overflowed) {
12905 PDiag(diag::warn_impcast_fixed_point_range)
12906 << FXResult.toString() << T
12907 << E->getSourceRange()
12908 << clang::SourceRange(CC));
12909 return;
12910 }
12911 }
12912 }
12913 } else if (Target->isUnsaturatedFixedPointType()) {
12914 if (Source->isIntegerType()) {
12918 llvm::APSInt Value = Result.Val.getInt();
12919
12920 bool Overflowed;
12921 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12922 Value, Context.getFixedPointSemantics(T), &Overflowed);
12923
12924 if (Overflowed) {
12926 PDiag(diag::warn_impcast_fixed_point_range)
12927 << toString(Value, /*Radix=*/10) << T
12928 << E->getSourceRange()
12929 << clang::SourceRange(CC));
12930 return;
12931 }
12932 }
12933 }
12934 }
12935
12936 // If we are casting an integer type to a floating point type without
12937 // initialization-list syntax, we might lose accuracy if the floating
12938 // point type has a narrower significand than the integer type.
12939 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12940 TargetBT->isFloatingType() && !IsListInit) {
12941 // Determine the number of precision bits in the source integer type.
12942 std::optional<IntRange> SourceRange =
12944 /*Approximate=*/true);
12945 if (!SourceRange)
12946 return;
12947 unsigned int SourcePrecision = SourceRange->Width;
12948
12949 // Determine the number of precision bits in the
12950 // target floating point type.
12951 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12952 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12953
12954 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12955 SourcePrecision > TargetPrecision) {
12956
12957 if (std::optional<llvm::APSInt> SourceInt =
12959 // If the source integer is a constant, convert it to the target
12960 // floating point type. Issue a warning if the value changes
12961 // during the whole conversion.
12962 llvm::APFloat TargetFloatValue(
12963 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12964 llvm::APFloat::opStatus ConversionStatus =
12965 TargetFloatValue.convertFromAPInt(
12966 *SourceInt, SourceBT->isSignedInteger(),
12967 llvm::APFloat::rmNearestTiesToEven);
12968
12969 if (ConversionStatus != llvm::APFloat::opOK) {
12970 SmallString<32> PrettySourceValue;
12971 SourceInt->toString(PrettySourceValue, 10);
12972 SmallString<32> PrettyTargetValue;
12973 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12974
12976 E->getExprLoc(), E,
12977 PDiag(diag::warn_impcast_integer_float_precision_constant)
12978 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12979 << E->getSourceRange() << clang::SourceRange(CC));
12980 }
12981 } else {
12982 // Otherwise, the implicit conversion may lose precision.
12983 DiagnoseImpCast(*this, E, T, CC,
12984 diag::warn_impcast_integer_float_precision);
12985 }
12986 }
12987 }
12988
12989 DiagnoseNullConversion(*this, E, T, CC);
12990
12992
12993 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12994 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12995 return;
12996 }
12997
12998 if (Target->isBooleanType())
12999 DiagnoseIntInBoolContext(*this, E);
13000
13002 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13003 << QualType(Source, 0) << QualType(Target, 0);
13004 }
13005
13006 if (!Source->isIntegerType() || !Target->isIntegerType())
13007 return;
13008
13009 // TODO: remove this early return once the false positives for constant->bool
13010 // in templates, macros, etc, are reduced or removed.
13011 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13012 return;
13013
13014 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13015 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13017 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13018 << E->getType());
13019 }
13020 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13021 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13022 if (!LikelySourceRange)
13023 return;
13024
13025 IntRange SourceTypeRange =
13026 IntRange::forTargetOfCanonicalType(Context, Source);
13027 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13028
13029 if (LikelySourceRange->Width > TargetRange.Width) {
13030 // If the source is a constant, use a default-on diagnostic.
13031 // TODO: this should happen for bitfield stores, too.
13035 llvm::APSInt Value(32);
13036 Value = Result.Val.getInt();
13037
13038 if (SourceMgr.isInSystemMacro(CC))
13039 return;
13040
13041 std::string PrettySourceValue = toString(Value, 10);
13042 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13043
13045 PDiag(diag::warn_impcast_integer_precision_constant)
13046 << PrettySourceValue << PrettyTargetValue
13047 << E->getType() << T << E->getSourceRange()
13048 << SourceRange(CC));
13049 return;
13050 }
13051
13052 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13053 if (SourceMgr.isInSystemMacro(CC))
13054 return;
13055
13056 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13057 if (UO->getOpcode() == UO_Minus)
13058 return DiagnoseImpCast(
13059 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13060 }
13061
13062 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13063 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13064 /* pruneControlFlow */ true);
13065 return DiagnoseImpCast(*this, E, T, CC,
13066 diag::warn_impcast_integer_precision);
13067 }
13068
13069 if (TargetRange.Width > SourceTypeRange.Width) {
13070 if (auto *UO = dyn_cast<UnaryOperator>(E))
13071 if (UO->getOpcode() == UO_Minus)
13072 if (Source->isUnsignedIntegerType()) {
13073 if (Target->isUnsignedIntegerType())
13074 return DiagnoseImpCast(*this, E, T, CC,
13075 diag::warn_impcast_high_order_zero_bits);
13076 if (Target->isSignedIntegerType())
13077 return DiagnoseImpCast(*this, E, T, CC,
13078 diag::warn_impcast_nonnegative_result);
13079 }
13080 }
13081
13082 if (TargetRange.Width == LikelySourceRange->Width &&
13083 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13084 Source->isSignedIntegerType()) {
13085 // Warn when doing a signed to signed conversion, warn if the positive
13086 // source value is exactly the width of the target type, which will
13087 // cause a negative value to be stored.
13088
13091 !SourceMgr.isInSystemMacro(CC)) {
13092 llvm::APSInt Value = Result.Val.getInt();
13093 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13094 std::string PrettySourceValue = toString(Value, 10);
13095 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13096
13097 Diag(E->getExprLoc(),
13098 PDiag(diag::warn_impcast_integer_precision_constant)
13099 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13100 << E->getSourceRange() << SourceRange(CC));
13101 return;
13102 }
13103 }
13104
13105 // Fall through for non-constants to give a sign conversion warning.
13106 }
13107
13108 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13109 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13110 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13111 LikelySourceRange->Width == TargetRange.Width))) {
13112 if (SourceMgr.isInSystemMacro(CC))
13113 return;
13114
13115 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13116 TargetBT->isInteger() &&
13117 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13118 return;
13119 }
13120
13121 unsigned DiagID = diag::warn_impcast_integer_sign;
13122
13123 // Traditionally, gcc has warned about this under -Wsign-compare.
13124 // We also want to warn about it in -Wconversion.
13125 // So if -Wconversion is off, use a completely identical diagnostic
13126 // in the sign-compare group.
13127 // The conditional-checking code will
13128 if (ICContext) {
13129 DiagID = diag::warn_impcast_integer_sign_conditional;
13130 *ICContext = true;
13131 }
13132
13133 DiagnoseImpCast(*this, E, T, CC, DiagID);
13134 }
13135
13136 // If we're implicitly converting from an integer into an enumeration, that
13137 // is valid in C but invalid in C++.
13138 QualType SourceType = E->getEnumCoercedType(Context);
13139 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13140 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13141 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13142
13143 // Diagnose conversions between different enumeration types.
13144 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13145 // type, to give us better diagnostics.
13146 Source = Context.getCanonicalType(SourceType).getTypePtr();
13147
13148 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13149 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13150 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13151 TargetEnum->getDecl()->hasNameForLinkage() &&
13152 SourceEnum != TargetEnum) {
13153 if (SourceMgr.isInSystemMacro(CC))
13154 return;
13155
13156 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13157 diag::warn_impcast_different_enum_types);
13158 }
13159}
13160
13163
13165 SourceLocation CC, bool &ICContext) {
13166 E = E->IgnoreParenImpCasts();
13167 // Diagnose incomplete type for second or third operand in C.
13168 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13169 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13170
13171 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13172 return CheckConditionalOperator(S, CO, CC, T);
13173
13175 if (E->getType() != T)
13176 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13177}
13178
13182
13183 Expr *TrueExpr = E->getTrueExpr();
13184 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13185 TrueExpr = BCO->getCommon();
13186
13187 bool Suspicious = false;
13188 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13189 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13190
13191 if (T->isBooleanType())
13193
13194 // If -Wconversion would have warned about either of the candidates
13195 // for a signedness conversion to the context type...
13196 if (!Suspicious) return;
13197
13198 // ...but it's currently ignored...
13199 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13200 return;
13201
13202 // ...then check whether it would have warned about either of the
13203 // candidates for a signedness conversion to the condition type.
13204 if (E->getType() == T) return;
13205
13206 Suspicious = false;
13207 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13208 &Suspicious);
13209 if (!Suspicious)
13211 E->getType(), CC, &Suspicious);
13212}
13213
13214/// Check conversion of given expression to boolean.
13215/// Input argument E is a logical expression.
13217 // Run the bool-like conversion checks only for C since there bools are
13218 // still not used as the return type from "boolean" operators or as the input
13219 // type for conditional operators.
13220 if (S.getLangOpts().CPlusPlus)
13221 return;
13223 return;
13225}
13226
13227namespace {
13228struct AnalyzeImplicitConversionsWorkItem {
13229 Expr *E;
13230 SourceLocation CC;
13231 bool IsListInit;
13232};
13233}
13234
13236 Sema &S, Expr *E, QualType T, SourceLocation CC,
13237 bool ExtraCheckForImplicitConversion,
13239 E = E->IgnoreParenImpCasts();
13240 WorkList.push_back({E, CC, false});
13241
13242 if (ExtraCheckForImplicitConversion && E->getType() != T)
13243 S.CheckImplicitConversion(E, T, CC);
13244}
13245
13246/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13247/// that should be visited are added to WorkList.
13249 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13251 Expr *OrigE = Item.E;
13252 SourceLocation CC = Item.CC;
13253
13254 QualType T = OrigE->getType();
13255 Expr *E = OrigE->IgnoreParenImpCasts();
13256
13257 // Propagate whether we are in a C++ list initialization expression.
13258 // If so, we do not issue warnings for implicit int-float conversion
13259 // precision loss, because C++11 narrowing already handles it.
13260 //
13261 // HLSL's initialization lists are special, so they shouldn't observe the C++
13262 // behavior here.
13263 bool IsListInit =
13264 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13265 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13266
13267 if (E->isTypeDependent() || E->isValueDependent())
13268 return;
13269
13270 Expr *SourceExpr = E;
13271 // Examine, but don't traverse into the source expression of an
13272 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13273 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13274 // evaluate it in the context of checking the specific conversion to T though.
13275 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13276 if (auto *Src = OVE->getSourceExpr())
13277 SourceExpr = Src;
13278
13279 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13280 if (UO->getOpcode() == UO_Not &&
13281 UO->getSubExpr()->isKnownToHaveBooleanValue())
13282 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13283 << OrigE->getSourceRange() << T->isBooleanType()
13284 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13285
13286 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13287 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13288 BO->getLHS()->isKnownToHaveBooleanValue() &&
13289 BO->getRHS()->isKnownToHaveBooleanValue() &&
13290 BO->getLHS()->HasSideEffects(S.Context) &&
13291 BO->getRHS()->HasSideEffects(S.Context)) {
13293 const LangOptions &LO = S.getLangOpts();
13294 SourceLocation BLoc = BO->getOperatorLoc();
13295 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13296 StringRef SR = clang::Lexer::getSourceText(
13297 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13298 // To reduce false positives, only issue the diagnostic if the operator
13299 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13300 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13301 // in C, along with other macro spellings the user might invent.
13302 if (SR.str() == "&" || SR.str() == "|") {
13303
13304 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13305 << (BO->getOpcode() == BO_And ? "&" : "|")
13306 << OrigE->getSourceRange()
13308 BO->getOperatorLoc(),
13309 (BO->getOpcode() == BO_And ? "&&" : "||"));
13310 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13311 }
13312 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13313 /// Analyze the given comma operator. The basic idea behind the analysis
13314 /// is to analyze the left and right operands slightly differently. The
13315 /// left operand needs to check whether the operand itself has an implicit
13316 /// conversion, but not whether the left operand induces an implicit
13317 /// conversion for the entire comma expression itself. This is similar to
13318 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13319 /// were directly used for the implicit conversion check.
13320 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13321 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13322 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13323 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13324 return;
13325 }
13326 }
13327
13328 // For conditional operators, we analyze the arguments as if they
13329 // were being fed directly into the output.
13330 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13331 CheckConditionalOperator(S, CO, CC, T);
13332 return;
13333 }
13334
13335 // Check implicit argument conversions for function calls.
13336 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13338
13339 // Go ahead and check any implicit conversions we might have skipped.
13340 // The non-canonical typecheck is just an optimization;
13341 // CheckImplicitConversion will filter out dead implicit conversions.
13342 if (SourceExpr->getType() != T)
13343 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13344
13345 // Now continue drilling into this expression.
13346
13347 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13348 // The bound subexpressions in a PseudoObjectExpr are not reachable
13349 // as transitive children.
13350 // FIXME: Use a more uniform representation for this.
13351 for (auto *SE : POE->semantics())
13352 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13353 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13354 }
13355
13356 // Skip past explicit casts.
13357 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13358 E = CE->getSubExpr();
13359 // In the special case of a C++ function-style cast with braces,
13360 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13361 // initializer. This InitListExpr basically belongs to the cast itself, so
13362 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13364 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13365 if (InitListE->getNumInits() == 1) {
13366 E = InitListE->getInit(0);
13367 }
13368 }
13369 }
13370 E = E->IgnoreParenImpCasts();
13371 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13372 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13373 WorkList.push_back({E, CC, IsListInit});
13374 return;
13375 }
13376
13377 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13378 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13379 // The base expression is only used to initialize the parameter for
13380 // arguments to `inout` parameters, so we only traverse down the base
13381 // expression for `inout` cases.
13382 if (OutArgE->isInOut())
13383 WorkList.push_back(
13384 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13385 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13386 return;
13387 }
13388
13389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13390 // Do a somewhat different check with comparison operators.
13391 if (BO->isComparisonOp())
13392 return AnalyzeComparison(S, BO);
13393
13394 // And with simple assignments.
13395 if (BO->getOpcode() == BO_Assign)
13396 return AnalyzeAssignment(S, BO);
13397 // And with compound assignments.
13398 if (BO->isAssignmentOp())
13399 return AnalyzeCompoundAssignment(S, BO);
13400 }
13401
13402 // These break the otherwise-useful invariant below. Fortunately,
13403 // we don't really need to recurse into them, because any internal
13404 // expressions should have been analyzed already when they were
13405 // built into statements.
13406 if (isa<StmtExpr>(E)) return;
13407
13408 // Don't descend into unevaluated contexts.
13409 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13410
13411 // Now just recurse over the expression's children.
13412 CC = E->getExprLoc();
13413 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13414 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13415 for (Stmt *SubStmt : E->children()) {
13416 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13417 if (!ChildExpr)
13418 continue;
13419
13420 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13421 if (ChildExpr == CSE->getOperand())
13422 // Do not recurse over a CoroutineSuspendExpr's operand.
13423 // The operand is also a subexpression of getCommonExpr(), and
13424 // recursing into it directly would produce duplicate diagnostics.
13425 continue;
13426
13427 if (IsLogicalAndOperator &&
13429 // Ignore checking string literals that are in logical and operators.
13430 // This is a common pattern for asserts.
13431 continue;
13432 WorkList.push_back({ChildExpr, CC, IsListInit});
13433 }
13434
13435 if (BO && BO->isLogicalOp()) {
13436 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13437 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13438 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13439
13440 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13441 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13442 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13443 }
13444
13445 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13446 if (U->getOpcode() == UO_LNot) {
13447 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13448 } else if (U->getOpcode() != UO_AddrOf) {
13449 if (U->getSubExpr()->getType()->isAtomicType())
13450 S.Diag(U->getSubExpr()->getBeginLoc(),
13451 diag::warn_atomic_implicit_seq_cst);
13452 }
13453 }
13454}
13455
13456/// AnalyzeImplicitConversions - Find and report any interesting
13457/// implicit conversions in the given expression. There are a couple
13458/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13460 bool IsListInit/*= false*/) {
13462 WorkList.push_back({OrigE, CC, IsListInit});
13463 while (!WorkList.empty())
13464 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13465}
13466
13467// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13468// Returns true when emitting a warning about taking the address of a reference.
13469static bool CheckForReference(Sema &SemaRef, const Expr *E,
13470 const PartialDiagnostic &PD) {
13471 E = E->IgnoreParenImpCasts();
13472
13473 const FunctionDecl *FD = nullptr;
13474
13475 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13476 if (!DRE->getDecl()->getType()->isReferenceType())
13477 return false;
13478 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13479 if (!M->getMemberDecl()->getType()->isReferenceType())
13480 return false;
13481 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13482 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13483 return false;
13484 FD = Call->getDirectCallee();
13485 } else {
13486 return false;
13487 }
13488
13489 SemaRef.Diag(E->getExprLoc(), PD);
13490
13491 // If possible, point to location of function.
13492 if (FD) {
13493 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13494 }
13495
13496 return true;
13497}
13498
13499// Returns true if the SourceLocation is expanded from any macro body.
13500// Returns false if the SourceLocation is invalid, is from not in a macro
13501// expansion, or is from expanded from a top-level macro argument.
13503 if (Loc.isInvalid())
13504 return false;
13505
13506 while (Loc.isMacroID()) {
13507 if (SM.isMacroBodyExpansion(Loc))
13508 return true;
13509 Loc = SM.getImmediateMacroCallerLoc(Loc);
13510 }
13511
13512 return false;
13513}
13514
13517 bool IsEqual, SourceRange Range) {
13518 if (!E)
13519 return;
13520
13521 // Don't warn inside macros.
13522 if (E->getExprLoc().isMacroID()) {
13524 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13525 IsInAnyMacroBody(SM, Range.getBegin()))
13526 return;
13527 }
13528 E = E->IgnoreImpCasts();
13529
13530 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13531
13532 if (isa<CXXThisExpr>(E)) {
13533 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13534 : diag::warn_this_bool_conversion;
13535 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13536 return;
13537 }
13538
13539 bool IsAddressOf = false;
13540
13541 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13542 if (UO->getOpcode() != UO_AddrOf)
13543 return;
13544 IsAddressOf = true;
13545 E = UO->getSubExpr();
13546 }
13547
13548 if (IsAddressOf) {
13549 unsigned DiagID = IsCompare
13550 ? diag::warn_address_of_reference_null_compare
13551 : diag::warn_address_of_reference_bool_conversion;
13552 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13553 << IsEqual;
13554 if (CheckForReference(*this, E, PD)) {
13555 return;
13556 }
13557 }
13558
13559 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13560 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13561 std::string Str;
13562 llvm::raw_string_ostream S(Str);
13563 E->printPretty(S, nullptr, getPrintingPolicy());
13564 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13565 : diag::warn_cast_nonnull_to_bool;
13566 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13567 << E->getSourceRange() << Range << IsEqual;
13568 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13569 };
13570
13571 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13572 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13573 if (auto *Callee = Call->getDirectCallee()) {
13574 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13575 ComplainAboutNonnullParamOrCall(A);
13576 return;
13577 }
13578 }
13579 }
13580
13581 // Complain if we are converting a lambda expression to a boolean value
13582 // outside of instantiation.
13583 if (!inTemplateInstantiation()) {
13584 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13585 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13586 MRecordDecl && MRecordDecl->isLambda()) {
13587 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13588 << /*LambdaPointerConversionOperatorType=*/3
13589 << MRecordDecl->getSourceRange() << Range << IsEqual;
13590 return;
13591 }
13592 }
13593 }
13594
13595 // Expect to find a single Decl. Skip anything more complicated.
13596 ValueDecl *D = nullptr;
13597 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13598 D = R->getDecl();
13599 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13600 D = M->getMemberDecl();
13601 }
13602
13603 // Weak Decls can be null.
13604 if (!D || D->isWeak())
13605 return;
13606
13607 // Check for parameter decl with nonnull attribute
13608 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13609 if (getCurFunction() &&
13610 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13611 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13612 ComplainAboutNonnullParamOrCall(A);
13613 return;
13614 }
13615
13616 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13617 // Skip function template not specialized yet.
13619 return;
13620 auto ParamIter = llvm::find(FD->parameters(), PV);
13621 assert(ParamIter != FD->param_end());
13622 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13623
13624 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13625 if (!NonNull->args_size()) {
13626 ComplainAboutNonnullParamOrCall(NonNull);
13627 return;
13628 }
13629
13630 for (const ParamIdx &ArgNo : NonNull->args()) {
13631 if (ArgNo.getASTIndex() == ParamNo) {
13632 ComplainAboutNonnullParamOrCall(NonNull);
13633 return;
13634 }
13635 }
13636 }
13637 }
13638 }
13639 }
13640
13641 QualType T = D->getType();
13642 const bool IsArray = T->isArrayType();
13643 const bool IsFunction = T->isFunctionType();
13644
13645 // Address of function is used to silence the function warning.
13646 if (IsAddressOf && IsFunction) {
13647 return;
13648 }
13649
13650 // Found nothing.
13651 if (!IsAddressOf && !IsFunction && !IsArray)
13652 return;
13653
13654 // Pretty print the expression for the diagnostic.
13655 std::string Str;
13656 llvm::raw_string_ostream S(Str);
13657 E->printPretty(S, nullptr, getPrintingPolicy());
13658
13659 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13660 : diag::warn_impcast_pointer_to_bool;
13661 enum {
13662 AddressOf,
13663 FunctionPointer,
13664 ArrayPointer
13665 } DiagType;
13666 if (IsAddressOf)
13667 DiagType = AddressOf;
13668 else if (IsFunction)
13669 DiagType = FunctionPointer;
13670 else if (IsArray)
13671 DiagType = ArrayPointer;
13672 else
13673 llvm_unreachable("Could not determine diagnostic.");
13674 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13675 << Range << IsEqual;
13676
13677 if (!IsFunction)
13678 return;
13679
13680 // Suggest '&' to silence the function warning.
13681 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13683
13684 // Check to see if '()' fixit should be emitted.
13685 QualType ReturnType;
13686 UnresolvedSet<4> NonTemplateOverloads;
13687 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13688 if (ReturnType.isNull())
13689 return;
13690
13691 if (IsCompare) {
13692 // There are two cases here. If there is null constant, the only suggest
13693 // for a pointer return type. If the null is 0, then suggest if the return
13694 // type is a pointer or an integer type.
13695 if (!ReturnType->isPointerType()) {
13696 if (NullKind == Expr::NPCK_ZeroExpression ||
13697 NullKind == Expr::NPCK_ZeroLiteral) {
13698 if (!ReturnType->isIntegerType())
13699 return;
13700 } else {
13701 return;
13702 }
13703 }
13704 } else { // !IsCompare
13705 // For function to bool, only suggest if the function pointer has bool
13706 // return type.
13707 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13708 return;
13709 }
13710 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13712}
13713
13714void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13715 // Don't diagnose in unevaluated contexts.
13717 return;
13718
13719 // Don't diagnose for value- or type-dependent expressions.
13720 if (E->isTypeDependent() || E->isValueDependent())
13721 return;
13722
13723 // Check for array bounds violations in cases where the check isn't triggered
13724 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13725 // ArraySubscriptExpr is on the RHS of a variable initialization.
13726 CheckArrayAccess(E);
13727
13728 // This is not the right CC for (e.g.) a variable initialization.
13729 AnalyzeImplicitConversions(*this, E, CC);
13730}
13731
13732void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13733 ::CheckBoolLikeConversion(*this, E, CC);
13734}
13735
13736void Sema::CheckForIntOverflow (const Expr *E) {
13737 // Use a work list to deal with nested struct initializers.
13738 SmallVector<const Expr *, 2> Exprs(1, E);
13739
13740 do {
13741 const Expr *OriginalE = Exprs.pop_back_val();
13742 const Expr *E = OriginalE->IgnoreParenCasts();
13743
13746 continue;
13747 }
13748
13749 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13750 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13751 else if (isa<ObjCBoxedExpr>(OriginalE))
13753 else if (const auto *Call = dyn_cast<CallExpr>(E))
13754 Exprs.append(Call->arg_begin(), Call->arg_end());
13755 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13756 Exprs.append(Message->arg_begin(), Message->arg_end());
13757 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13758 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13759 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13760 Exprs.push_back(Temporary->getSubExpr());
13761 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13762 Exprs.push_back(Array->getIdx());
13763 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13764 Exprs.push_back(Compound->getInitializer());
13765 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13766 New && New->isArray()) {
13767 if (auto ArraySize = New->getArraySize())
13768 Exprs.push_back(*ArraySize);
13769 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13770 Exprs.push_back(MTE->getSubExpr());
13771 } while (!Exprs.empty());
13772}
13773
13774namespace {
13775
13776/// Visitor for expressions which looks for unsequenced operations on the
13777/// same object.
13778class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13779 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13780
13781 /// A tree of sequenced regions within an expression. Two regions are
13782 /// unsequenced if one is an ancestor or a descendent of the other. When we
13783 /// finish processing an expression with sequencing, such as a comma
13784 /// expression, we fold its tree nodes into its parent, since they are
13785 /// unsequenced with respect to nodes we will visit later.
13786 class SequenceTree {
13787 struct Value {
13788 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13789 unsigned Parent : 31;
13790 LLVM_PREFERRED_TYPE(bool)
13791 unsigned Merged : 1;
13792 };
13793 SmallVector<Value, 8> Values;
13794
13795 public:
13796 /// A region within an expression which may be sequenced with respect
13797 /// to some other region.
13798 class Seq {
13799 friend class SequenceTree;
13800
13801 unsigned Index;
13802
13803 explicit Seq(unsigned N) : Index(N) {}
13804
13805 public:
13806 Seq() : Index(0) {}
13807 };
13808
13809 SequenceTree() { Values.push_back(Value(0)); }
13810 Seq root() const { return Seq(0); }
13811
13812 /// Create a new sequence of operations, which is an unsequenced
13813 /// subset of \p Parent. This sequence of operations is sequenced with
13814 /// respect to other children of \p Parent.
13815 Seq allocate(Seq Parent) {
13816 Values.push_back(Value(Parent.Index));
13817 return Seq(Values.size() - 1);
13818 }
13819
13820 /// Merge a sequence of operations into its parent.
13821 void merge(Seq S) {
13822 Values[S.Index].Merged = true;
13823 }
13824
13825 /// Determine whether two operations are unsequenced. This operation
13826 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13827 /// should have been merged into its parent as appropriate.
13828 bool isUnsequenced(Seq Cur, Seq Old) {
13829 unsigned C = representative(Cur.Index);
13830 unsigned Target = representative(Old.Index);
13831 while (C >= Target) {
13832 if (C == Target)
13833 return true;
13834 C = Values[C].Parent;
13835 }
13836 return false;
13837 }
13838
13839 private:
13840 /// Pick a representative for a sequence.
13841 unsigned representative(unsigned K) {
13842 if (Values[K].Merged)
13843 // Perform path compression as we go.
13844 return Values[K].Parent = representative(Values[K].Parent);
13845 return K;
13846 }
13847 };
13848
13849 /// An object for which we can track unsequenced uses.
13850 using Object = const NamedDecl *;
13851
13852 /// Different flavors of object usage which we track. We only track the
13853 /// least-sequenced usage of each kind.
13854 enum UsageKind {
13855 /// A read of an object. Multiple unsequenced reads are OK.
13856 UK_Use,
13857
13858 /// A modification of an object which is sequenced before the value
13859 /// computation of the expression, such as ++n in C++.
13860 UK_ModAsValue,
13861
13862 /// A modification of an object which is not sequenced before the value
13863 /// computation of the expression, such as n++.
13864 UK_ModAsSideEffect,
13865
13866 UK_Count = UK_ModAsSideEffect + 1
13867 };
13868
13869 /// Bundle together a sequencing region and the expression corresponding
13870 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13871 struct Usage {
13872 const Expr *UsageExpr = nullptr;
13873 SequenceTree::Seq Seq;
13874
13875 Usage() = default;
13876 };
13877
13878 struct UsageInfo {
13879 Usage Uses[UK_Count];
13880
13881 /// Have we issued a diagnostic for this object already?
13882 bool Diagnosed = false;
13883
13884 UsageInfo();
13885 };
13886 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13887
13888 Sema &SemaRef;
13889
13890 /// Sequenced regions within the expression.
13891 SequenceTree Tree;
13892
13893 /// Declaration modifications and references which we have seen.
13894 UsageInfoMap UsageMap;
13895
13896 /// The region we are currently within.
13897 SequenceTree::Seq Region;
13898
13899 /// Filled in with declarations which were modified as a side-effect
13900 /// (that is, post-increment operations).
13901 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13902
13903 /// Expressions to check later. We defer checking these to reduce
13904 /// stack usage.
13905 SmallVectorImpl<const Expr *> &WorkList;
13906
13907 /// RAII object wrapping the visitation of a sequenced subexpression of an
13908 /// expression. At the end of this process, the side-effects of the evaluation
13909 /// become sequenced with respect to the value computation of the result, so
13910 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13911 /// UK_ModAsValue.
13912 struct SequencedSubexpression {
13913 SequencedSubexpression(SequenceChecker &Self)
13914 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13915 Self.ModAsSideEffect = &ModAsSideEffect;
13916 }
13917
13918 ~SequencedSubexpression() {
13919 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13920 // Add a new usage with usage kind UK_ModAsValue, and then restore
13921 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13922 // the previous one was empty).
13923 UsageInfo &UI = Self.UsageMap[M.first];
13924 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13925 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13926 SideEffectUsage = M.second;
13927 }
13928 Self.ModAsSideEffect = OldModAsSideEffect;
13929 }
13930
13931 SequenceChecker &Self;
13932 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13933 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13934 };
13935
13936 /// RAII object wrapping the visitation of a subexpression which we might
13937 /// choose to evaluate as a constant. If any subexpression is evaluated and
13938 /// found to be non-constant, this allows us to suppress the evaluation of
13939 /// the outer expression.
13940 class EvaluationTracker {
13941 public:
13942 EvaluationTracker(SequenceChecker &Self)
13943 : Self(Self), Prev(Self.EvalTracker) {
13944 Self.EvalTracker = this;
13945 }
13946
13947 ~EvaluationTracker() {
13948 Self.EvalTracker = Prev;
13949 if (Prev)
13950 Prev->EvalOK &= EvalOK;
13951 }
13952
13953 bool evaluate(const Expr *E, bool &Result) {
13954 if (!EvalOK || E->isValueDependent())
13955 return false;
13956 EvalOK = E->EvaluateAsBooleanCondition(
13957 Result, Self.SemaRef.Context,
13958 Self.SemaRef.isConstantEvaluatedContext());
13959 return EvalOK;
13960 }
13961
13962 private:
13963 SequenceChecker &Self;
13964 EvaluationTracker *Prev;
13965 bool EvalOK = true;
13966 } *EvalTracker = nullptr;
13967
13968 /// Find the object which is produced by the specified expression,
13969 /// if any.
13970 Object getObject(const Expr *E, bool Mod) const {
13971 E = E->IgnoreParenCasts();
13972 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13973 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13974 return getObject(UO->getSubExpr(), Mod);
13975 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13976 if (BO->getOpcode() == BO_Comma)
13977 return getObject(BO->getRHS(), Mod);
13978 if (Mod && BO->isAssignmentOp())
13979 return getObject(BO->getLHS(), Mod);
13980 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13981 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13982 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13983 return ME->getMemberDecl();
13984 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13985 // FIXME: If this is a reference, map through to its value.
13986 return DRE->getDecl();
13987 return nullptr;
13988 }
13989
13990 /// Note that an object \p O was modified or used by an expression
13991 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13992 /// the object \p O as obtained via the \p UsageMap.
13993 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13994 // Get the old usage for the given object and usage kind.
13995 Usage &U = UI.Uses[UK];
13996 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13997 // If we have a modification as side effect and are in a sequenced
13998 // subexpression, save the old Usage so that we can restore it later
13999 // in SequencedSubexpression::~SequencedSubexpression.
14000 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14001 ModAsSideEffect->push_back(std::make_pair(O, U));
14002 // Then record the new usage with the current sequencing region.
14003 U.UsageExpr = UsageExpr;
14004 U.Seq = Region;
14005 }
14006 }
14007
14008 /// Check whether a modification or use of an object \p O in an expression
14009 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14010 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14011 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14012 /// usage and false we are checking for a mod-use unsequenced usage.
14013 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14014 UsageKind OtherKind, bool IsModMod) {
14015 if (UI.Diagnosed)
14016 return;
14017
14018 const Usage &U = UI.Uses[OtherKind];
14019 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14020 return;
14021
14022 const Expr *Mod = U.UsageExpr;
14023 const Expr *ModOrUse = UsageExpr;
14024 if (OtherKind == UK_Use)
14025 std::swap(Mod, ModOrUse);
14026
14027 SemaRef.DiagRuntimeBehavior(
14028 Mod->getExprLoc(), {Mod, ModOrUse},
14029 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14030 : diag::warn_unsequenced_mod_use)
14031 << O << SourceRange(ModOrUse->getExprLoc()));
14032 UI.Diagnosed = true;
14033 }
14034
14035 // A note on note{Pre, Post}{Use, Mod}:
14036 //
14037 // (It helps to follow the algorithm with an expression such as
14038 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14039 // operations before C++17 and both are well-defined in C++17).
14040 //
14041 // When visiting a node which uses/modify an object we first call notePreUse
14042 // or notePreMod before visiting its sub-expression(s). At this point the
14043 // children of the current node have not yet been visited and so the eventual
14044 // uses/modifications resulting from the children of the current node have not
14045 // been recorded yet.
14046 //
14047 // We then visit the children of the current node. After that notePostUse or
14048 // notePostMod is called. These will 1) detect an unsequenced modification
14049 // as side effect (as in "k++ + k") and 2) add a new usage with the
14050 // appropriate usage kind.
14051 //
14052 // We also have to be careful that some operation sequences modification as
14053 // side effect as well (for example: || or ,). To account for this we wrap
14054 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14055 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14056 // which record usages which are modifications as side effect, and then
14057 // downgrade them (or more accurately restore the previous usage which was a
14058 // modification as side effect) when exiting the scope of the sequenced
14059 // subexpression.
14060
14061 void notePreUse(Object O, const Expr *UseExpr) {
14062 UsageInfo &UI = UsageMap[O];
14063 // Uses conflict with other modifications.
14064 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14065 }
14066
14067 void notePostUse(Object O, const Expr *UseExpr) {
14068 UsageInfo &UI = UsageMap[O];
14069 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14070 /*IsModMod=*/false);
14071 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14072 }
14073
14074 void notePreMod(Object O, const Expr *ModExpr) {
14075 UsageInfo &UI = UsageMap[O];
14076 // Modifications conflict with other modifications and with uses.
14077 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14078 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14079 }
14080
14081 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14082 UsageInfo &UI = UsageMap[O];
14083 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14084 /*IsModMod=*/true);
14085 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14086 }
14087
14088public:
14089 SequenceChecker(Sema &S, const Expr *E,
14090 SmallVectorImpl<const Expr *> &WorkList)
14091 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14092 Visit(E);
14093 // Silence a -Wunused-private-field since WorkList is now unused.
14094 // TODO: Evaluate if it can be used, and if not remove it.
14095 (void)this->WorkList;
14096 }
14097
14098 void VisitStmt(const Stmt *S) {
14099 // Skip all statements which aren't expressions for now.
14100 }
14101
14102 void VisitExpr(const Expr *E) {
14103 // By default, just recurse to evaluated subexpressions.
14104 Base::VisitStmt(E);
14105 }
14106
14107 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14108 for (auto *Sub : CSE->children()) {
14109 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14110 if (!ChildExpr)
14111 continue;
14112
14113 if (ChildExpr == CSE->getOperand())
14114 // Do not recurse over a CoroutineSuspendExpr's operand.
14115 // The operand is also a subexpression of getCommonExpr(), and
14116 // recursing into it directly could confuse object management
14117 // for the sake of sequence tracking.
14118 continue;
14119
14120 Visit(Sub);
14121 }
14122 }
14123
14124 void VisitCastExpr(const CastExpr *E) {
14125 Object O = Object();
14126 if (E->getCastKind() == CK_LValueToRValue)
14127 O = getObject(E->getSubExpr(), false);
14128
14129 if (O)
14130 notePreUse(O, E);
14131 VisitExpr(E);
14132 if (O)
14133 notePostUse(O, E);
14134 }
14135
14136 void VisitSequencedExpressions(const Expr *SequencedBefore,
14137 const Expr *SequencedAfter) {
14138 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14139 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14140 SequenceTree::Seq OldRegion = Region;
14141
14142 {
14143 SequencedSubexpression SeqBefore(*this);
14144 Region = BeforeRegion;
14145 Visit(SequencedBefore);
14146 }
14147
14148 Region = AfterRegion;
14149 Visit(SequencedAfter);
14150
14151 Region = OldRegion;
14152
14153 Tree.merge(BeforeRegion);
14154 Tree.merge(AfterRegion);
14155 }
14156
14157 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14158 // C++17 [expr.sub]p1:
14159 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14160 // expression E1 is sequenced before the expression E2.
14161 if (SemaRef.getLangOpts().CPlusPlus17)
14162 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14163 else {
14164 Visit(ASE->getLHS());
14165 Visit(ASE->getRHS());
14166 }
14167 }
14168
14169 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14170 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14171 void VisitBinPtrMem(const BinaryOperator *BO) {
14172 // C++17 [expr.mptr.oper]p4:
14173 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14174 // the expression E1 is sequenced before the expression E2.
14175 if (SemaRef.getLangOpts().CPlusPlus17)
14176 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14177 else {
14178 Visit(BO->getLHS());
14179 Visit(BO->getRHS());
14180 }
14181 }
14182
14183 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14184 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14185 void VisitBinShlShr(const BinaryOperator *BO) {
14186 // C++17 [expr.shift]p4:
14187 // The expression E1 is sequenced before the expression E2.
14188 if (SemaRef.getLangOpts().CPlusPlus17)
14189 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14190 else {
14191 Visit(BO->getLHS());
14192 Visit(BO->getRHS());
14193 }
14194 }
14195
14196 void VisitBinComma(const BinaryOperator *BO) {
14197 // C++11 [expr.comma]p1:
14198 // Every value computation and side effect associated with the left
14199 // expression is sequenced before every value computation and side
14200 // effect associated with the right expression.
14201 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14202 }
14203
14204 void VisitBinAssign(const BinaryOperator *BO) {
14205 SequenceTree::Seq RHSRegion;
14206 SequenceTree::Seq LHSRegion;
14207 if (SemaRef.getLangOpts().CPlusPlus17) {
14208 RHSRegion = Tree.allocate(Region);
14209 LHSRegion = Tree.allocate(Region);
14210 } else {
14211 RHSRegion = Region;
14212 LHSRegion = Region;
14213 }
14214 SequenceTree::Seq OldRegion = Region;
14215
14216 // C++11 [expr.ass]p1:
14217 // [...] the assignment is sequenced after the value computation
14218 // of the right and left operands, [...]
14219 //
14220 // so check it before inspecting the operands and update the
14221 // map afterwards.
14222 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14223 if (O)
14224 notePreMod(O, BO);
14225
14226 if (SemaRef.getLangOpts().CPlusPlus17) {
14227 // C++17 [expr.ass]p1:
14228 // [...] The right operand is sequenced before the left operand. [...]
14229 {
14230 SequencedSubexpression SeqBefore(*this);
14231 Region = RHSRegion;
14232 Visit(BO->getRHS());
14233 }
14234
14235 Region = LHSRegion;
14236 Visit(BO->getLHS());
14237
14238 if (O && isa<CompoundAssignOperator>(BO))
14239 notePostUse(O, BO);
14240
14241 } else {
14242 // C++11 does not specify any sequencing between the LHS and RHS.
14243 Region = LHSRegion;
14244 Visit(BO->getLHS());
14245
14246 if (O && isa<CompoundAssignOperator>(BO))
14247 notePostUse(O, BO);
14248
14249 Region = RHSRegion;
14250 Visit(BO->getRHS());
14251 }
14252
14253 // C++11 [expr.ass]p1:
14254 // the assignment is sequenced [...] before the value computation of the
14255 // assignment expression.
14256 // C11 6.5.16/3 has no such rule.
14257 Region = OldRegion;
14258 if (O)
14259 notePostMod(O, BO,
14260 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14261 : UK_ModAsSideEffect);
14262 if (SemaRef.getLangOpts().CPlusPlus17) {
14263 Tree.merge(RHSRegion);
14264 Tree.merge(LHSRegion);
14265 }
14266 }
14267
14268 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14269 VisitBinAssign(CAO);
14270 }
14271
14272 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14273 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14274 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14275 Object O = getObject(UO->getSubExpr(), true);
14276 if (!O)
14277 return VisitExpr(UO);
14278
14279 notePreMod(O, UO);
14280 Visit(UO->getSubExpr());
14281 // C++11 [expr.pre.incr]p1:
14282 // the expression ++x is equivalent to x+=1
14283 notePostMod(O, UO,
14284 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14285 : UK_ModAsSideEffect);
14286 }
14287
14288 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14289 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14290 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14291 Object O = getObject(UO->getSubExpr(), true);
14292 if (!O)
14293 return VisitExpr(UO);
14294
14295 notePreMod(O, UO);
14296 Visit(UO->getSubExpr());
14297 notePostMod(O, UO, UK_ModAsSideEffect);
14298 }
14299
14300 void VisitBinLOr(const BinaryOperator *BO) {
14301 // C++11 [expr.log.or]p2:
14302 // If the second expression is evaluated, every value computation and
14303 // side effect associated with the first expression is sequenced before
14304 // every value computation and side effect associated with the
14305 // second expression.
14306 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14307 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14308 SequenceTree::Seq OldRegion = Region;
14309
14310 EvaluationTracker Eval(*this);
14311 {
14312 SequencedSubexpression Sequenced(*this);
14313 Region = LHSRegion;
14314 Visit(BO->getLHS());
14315 }
14316
14317 // C++11 [expr.log.or]p1:
14318 // [...] the second operand is not evaluated if the first operand
14319 // evaluates to true.
14320 bool EvalResult = false;
14321 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14322 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14323 if (ShouldVisitRHS) {
14324 Region = RHSRegion;
14325 Visit(BO->getRHS());
14326 }
14327
14328 Region = OldRegion;
14329 Tree.merge(LHSRegion);
14330 Tree.merge(RHSRegion);
14331 }
14332
14333 void VisitBinLAnd(const BinaryOperator *BO) {
14334 // C++11 [expr.log.and]p2:
14335 // If the second expression is evaluated, every value computation and
14336 // side effect associated with the first expression is sequenced before
14337 // every value computation and side effect associated with the
14338 // second expression.
14339 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14340 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14341 SequenceTree::Seq OldRegion = Region;
14342
14343 EvaluationTracker Eval(*this);
14344 {
14345 SequencedSubexpression Sequenced(*this);
14346 Region = LHSRegion;
14347 Visit(BO->getLHS());
14348 }
14349
14350 // C++11 [expr.log.and]p1:
14351 // [...] the second operand is not evaluated if the first operand is false.
14352 bool EvalResult = false;
14353 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14354 bool ShouldVisitRHS = !EvalOK || EvalResult;
14355 if (ShouldVisitRHS) {
14356 Region = RHSRegion;
14357 Visit(BO->getRHS());
14358 }
14359
14360 Region = OldRegion;
14361 Tree.merge(LHSRegion);
14362 Tree.merge(RHSRegion);
14363 }
14364
14365 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14366 // C++11 [expr.cond]p1:
14367 // [...] Every value computation and side effect associated with the first
14368 // expression is sequenced before every value computation and side effect
14369 // associated with the second or third expression.
14370 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14371
14372 // No sequencing is specified between the true and false expression.
14373 // However since exactly one of both is going to be evaluated we can
14374 // consider them to be sequenced. This is needed to avoid warning on
14375 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14376 // both the true and false expressions because we can't evaluate x.
14377 // This will still allow us to detect an expression like (pre C++17)
14378 // "(x ? y += 1 : y += 2) = y".
14379 //
14380 // We don't wrap the visitation of the true and false expression with
14381 // SequencedSubexpression because we don't want to downgrade modifications
14382 // as side effect in the true and false expressions after the visition
14383 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14384 // not warn between the two "y++", but we should warn between the "y++"
14385 // and the "y".
14386 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14387 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14388 SequenceTree::Seq OldRegion = Region;
14389
14390 EvaluationTracker Eval(*this);
14391 {
14392 SequencedSubexpression Sequenced(*this);
14393 Region = ConditionRegion;
14394 Visit(CO->getCond());
14395 }
14396
14397 // C++11 [expr.cond]p1:
14398 // [...] The first expression is contextually converted to bool (Clause 4).
14399 // It is evaluated and if it is true, the result of the conditional
14400 // expression is the value of the second expression, otherwise that of the
14401 // third expression. Only one of the second and third expressions is
14402 // evaluated. [...]
14403 bool EvalResult = false;
14404 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14405 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14406 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14407 if (ShouldVisitTrueExpr) {
14408 Region = TrueRegion;
14409 Visit(CO->getTrueExpr());
14410 }
14411 if (ShouldVisitFalseExpr) {
14412 Region = FalseRegion;
14413 Visit(CO->getFalseExpr());
14414 }
14415
14416 Region = OldRegion;
14417 Tree.merge(ConditionRegion);
14418 Tree.merge(TrueRegion);
14419 Tree.merge(FalseRegion);
14420 }
14421
14422 void VisitCallExpr(const CallExpr *CE) {
14423 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14424
14425 if (CE->isUnevaluatedBuiltinCall(Context))
14426 return;
14427
14428 // C++11 [intro.execution]p15:
14429 // When calling a function [...], every value computation and side effect
14430 // associated with any argument expression, or with the postfix expression
14431 // designating the called function, is sequenced before execution of every
14432 // expression or statement in the body of the function [and thus before
14433 // the value computation of its result].
14434 SequencedSubexpression Sequenced(*this);
14435 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14436 // C++17 [expr.call]p5
14437 // The postfix-expression is sequenced before each expression in the
14438 // expression-list and any default argument. [...]
14439 SequenceTree::Seq CalleeRegion;
14440 SequenceTree::Seq OtherRegion;
14441 if (SemaRef.getLangOpts().CPlusPlus17) {
14442 CalleeRegion = Tree.allocate(Region);
14443 OtherRegion = Tree.allocate(Region);
14444 } else {
14445 CalleeRegion = Region;
14446 OtherRegion = Region;
14447 }
14448 SequenceTree::Seq OldRegion = Region;
14449
14450 // Visit the callee expression first.
14451 Region = CalleeRegion;
14452 if (SemaRef.getLangOpts().CPlusPlus17) {
14453 SequencedSubexpression Sequenced(*this);
14454 Visit(CE->getCallee());
14455 } else {
14456 Visit(CE->getCallee());
14457 }
14458
14459 // Then visit the argument expressions.
14460 Region = OtherRegion;
14461 for (const Expr *Argument : CE->arguments())
14462 Visit(Argument);
14463
14464 Region = OldRegion;
14465 if (SemaRef.getLangOpts().CPlusPlus17) {
14466 Tree.merge(CalleeRegion);
14467 Tree.merge(OtherRegion);
14468 }
14469 });
14470 }
14471
14472 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14473 // C++17 [over.match.oper]p2:
14474 // [...] the operator notation is first transformed to the equivalent
14475 // function-call notation as summarized in Table 12 (where @ denotes one
14476 // of the operators covered in the specified subclause). However, the
14477 // operands are sequenced in the order prescribed for the built-in
14478 // operator (Clause 8).
14479 //
14480 // From the above only overloaded binary operators and overloaded call
14481 // operators have sequencing rules in C++17 that we need to handle
14482 // separately.
14483 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14484 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14485 return VisitCallExpr(CXXOCE);
14486
14487 enum {
14488 NoSequencing,
14489 LHSBeforeRHS,
14490 RHSBeforeLHS,
14491 LHSBeforeRest
14492 } SequencingKind;
14493 switch (CXXOCE->getOperator()) {
14494 case OO_Equal:
14495 case OO_PlusEqual:
14496 case OO_MinusEqual:
14497 case OO_StarEqual:
14498 case OO_SlashEqual:
14499 case OO_PercentEqual:
14500 case OO_CaretEqual:
14501 case OO_AmpEqual:
14502 case OO_PipeEqual:
14503 case OO_LessLessEqual:
14504 case OO_GreaterGreaterEqual:
14505 SequencingKind = RHSBeforeLHS;
14506 break;
14507
14508 case OO_LessLess:
14509 case OO_GreaterGreater:
14510 case OO_AmpAmp:
14511 case OO_PipePipe:
14512 case OO_Comma:
14513 case OO_ArrowStar:
14514 case OO_Subscript:
14515 SequencingKind = LHSBeforeRHS;
14516 break;
14517
14518 case OO_Call:
14519 SequencingKind = LHSBeforeRest;
14520 break;
14521
14522 default:
14523 SequencingKind = NoSequencing;
14524 break;
14525 }
14526
14527 if (SequencingKind == NoSequencing)
14528 return VisitCallExpr(CXXOCE);
14529
14530 // This is a call, so all subexpressions are sequenced before the result.
14531 SequencedSubexpression Sequenced(*this);
14532
14533 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14534 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14535 "Should only get there with C++17 and above!");
14536 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14537 "Should only get there with an overloaded binary operator"
14538 " or an overloaded call operator!");
14539
14540 if (SequencingKind == LHSBeforeRest) {
14541 assert(CXXOCE->getOperator() == OO_Call &&
14542 "We should only have an overloaded call operator here!");
14543
14544 // This is very similar to VisitCallExpr, except that we only have the
14545 // C++17 case. The postfix-expression is the first argument of the
14546 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14547 // are in the following arguments.
14548 //
14549 // Note that we intentionally do not visit the callee expression since
14550 // it is just a decayed reference to a function.
14551 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14552 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14553 SequenceTree::Seq OldRegion = Region;
14554
14555 assert(CXXOCE->getNumArgs() >= 1 &&
14556 "An overloaded call operator must have at least one argument"
14557 " for the postfix-expression!");
14558 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14559 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14560 CXXOCE->getNumArgs() - 1);
14561
14562 // Visit the postfix-expression first.
14563 {
14564 Region = PostfixExprRegion;
14565 SequencedSubexpression Sequenced(*this);
14566 Visit(PostfixExpr);
14567 }
14568
14569 // Then visit the argument expressions.
14570 Region = ArgsRegion;
14571 for (const Expr *Arg : Args)
14572 Visit(Arg);
14573
14574 Region = OldRegion;
14575 Tree.merge(PostfixExprRegion);
14576 Tree.merge(ArgsRegion);
14577 } else {
14578 assert(CXXOCE->getNumArgs() == 2 &&
14579 "Should only have two arguments here!");
14580 assert((SequencingKind == LHSBeforeRHS ||
14581 SequencingKind == RHSBeforeLHS) &&
14582 "Unexpected sequencing kind!");
14583
14584 // We do not visit the callee expression since it is just a decayed
14585 // reference to a function.
14586 const Expr *E1 = CXXOCE->getArg(0);
14587 const Expr *E2 = CXXOCE->getArg(1);
14588 if (SequencingKind == RHSBeforeLHS)
14589 std::swap(E1, E2);
14590
14591 return VisitSequencedExpressions(E1, E2);
14592 }
14593 });
14594 }
14595
14596 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14597 // This is a call, so all subexpressions are sequenced before the result.
14598 SequencedSubexpression Sequenced(*this);
14599
14600 if (!CCE->isListInitialization())
14601 return VisitExpr(CCE);
14602
14603 // In C++11, list initializations are sequenced.
14604 SequenceExpressionsInOrder(
14605 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14606 }
14607
14608 void VisitInitListExpr(const InitListExpr *ILE) {
14609 if (!SemaRef.getLangOpts().CPlusPlus11)
14610 return VisitExpr(ILE);
14611
14612 // In C++11, list initializations are sequenced.
14613 SequenceExpressionsInOrder(ILE->inits());
14614 }
14615
14616 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14617 // C++20 parenthesized list initializations are sequenced. See C++20
14618 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14619 SequenceExpressionsInOrder(PLIE->getInitExprs());
14620 }
14621
14622private:
14623 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14625 SequenceTree::Seq Parent = Region;
14626 for (const Expr *E : ExpressionList) {
14627 if (!E)
14628 continue;
14629 Region = Tree.allocate(Parent);
14630 Elts.push_back(Region);
14631 Visit(E);
14632 }
14633
14634 // Forget that the initializers are sequenced.
14635 Region = Parent;
14636 for (unsigned I = 0; I < Elts.size(); ++I)
14637 Tree.merge(Elts[I]);
14638 }
14639};
14640
14641SequenceChecker::UsageInfo::UsageInfo() = default;
14642
14643} // namespace
14644
14645void Sema::CheckUnsequencedOperations(const Expr *E) {
14646 SmallVector<const Expr *, 8> WorkList;
14647 WorkList.push_back(E);
14648 while (!WorkList.empty()) {
14649 const Expr *Item = WorkList.pop_back_val();
14650 SequenceChecker(*this, Item, WorkList);
14651 }
14652}
14653
14654void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14655 bool IsConstexpr) {
14656 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14657 IsConstexpr || isa<ConstantExpr>(E));
14658 CheckImplicitConversions(E, CheckLoc);
14659 if (!E->isInstantiationDependent())
14660 CheckUnsequencedOperations(E);
14661 if (!IsConstexpr && !E->isValueDependent())
14662 CheckForIntOverflow(E);
14663}
14664
14665void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14666 FieldDecl *BitField,
14667 Expr *Init) {
14668 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14669}
14670
14672 SourceLocation Loc) {
14673 if (!PType->isVariablyModifiedType())
14674 return;
14675 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14676 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14677 return;
14678 }
14679 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14680 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14681 return;
14682 }
14683 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14684 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14685 return;
14686 }
14687
14688 const ArrayType *AT = S.Context.getAsArrayType(PType);
14689 if (!AT)
14690 return;
14691
14694 return;
14695 }
14696
14697 S.Diag(Loc, diag::err_array_star_in_function_definition);
14698}
14699
14701 bool CheckParameterNames) {
14702 bool HasInvalidParm = false;
14703 for (ParmVarDecl *Param : Parameters) {
14704 assert(Param && "null in a parameter list");
14705 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14706 // function declarator that is part of a function definition of
14707 // that function shall not have incomplete type.
14708 //
14709 // C++23 [dcl.fct.def.general]/p2
14710 // The type of a parameter [...] for a function definition
14711 // shall not be a (possibly cv-qualified) class type that is incomplete
14712 // or abstract within the function body unless the function is deleted.
14713 if (!Param->isInvalidDecl() &&
14714 (RequireCompleteType(Param->getLocation(), Param->getType(),
14715 diag::err_typecheck_decl_incomplete_type) ||
14716 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14717 diag::err_abstract_type_in_decl,
14719 Param->setInvalidDecl();
14720 HasInvalidParm = true;
14721 }
14722
14723 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14724 // declaration of each parameter shall include an identifier.
14725 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14726 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14727 // Diagnose this as an extension in C17 and earlier.
14728 if (!getLangOpts().C23)
14729 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14730 }
14731
14732 // C99 6.7.5.3p12:
14733 // If the function declarator is not part of a definition of that
14734 // function, parameters may have incomplete type and may use the [*]
14735 // notation in their sequences of declarator specifiers to specify
14736 // variable length array types.
14737 QualType PType = Param->getOriginalType();
14738 // FIXME: This diagnostic should point the '[*]' if source-location
14739 // information is added for it.
14740 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14741
14742 // If the parameter is a c++ class type and it has to be destructed in the
14743 // callee function, declare the destructor so that it can be called by the
14744 // callee function. Do not perform any direct access check on the dtor here.
14745 if (!Param->isInvalidDecl()) {
14746 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14747 if (!ClassDecl->isInvalidDecl() &&
14748 !ClassDecl->hasIrrelevantDestructor() &&
14749 !ClassDecl->isDependentContext() &&
14750 ClassDecl->isParamDestroyedInCallee()) {
14752 MarkFunctionReferenced(Param->getLocation(), Destructor);
14753 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14754 }
14755 }
14756 }
14757
14758 // Parameters with the pass_object_size attribute only need to be marked
14759 // constant at function definitions. Because we lack information about
14760 // whether we're on a declaration or definition when we're instantiating the
14761 // attribute, we need to check for constness here.
14762 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14763 if (!Param->getType().isConstQualified())
14764 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14765 << Attr->getSpelling() << 1;
14766
14767 // Check for parameter names shadowing fields from the class.
14768 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14769 // The owning context for the parameter should be the function, but we
14770 // want to see if this function's declaration context is a record.
14771 DeclContext *DC = Param->getDeclContext();
14772 if (DC && DC->isFunctionOrMethod()) {
14773 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14774 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14775 RD, /*DeclIsField*/ false);
14776 }
14777 }
14778
14779 if (!Param->isInvalidDecl() &&
14780 Param->getOriginalType()->isWebAssemblyTableType()) {
14781 Param->setInvalidDecl();
14782 HasInvalidParm = true;
14783 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14784 }
14785 }
14786
14787 return HasInvalidParm;
14788}
14789
14790std::optional<std::pair<
14792 *E,
14794 &Ctx);
14795
14796/// Compute the alignment and offset of the base class object given the
14797/// derived-to-base cast expression and the alignment and offset of the derived
14798/// class object.
14799static std::pair<CharUnits, CharUnits>
14801 CharUnits BaseAlignment, CharUnits Offset,
14802 ASTContext &Ctx) {
14803 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14804 ++PathI) {
14805 const CXXBaseSpecifier *Base = *PathI;
14806 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14807 if (Base->isVirtual()) {
14808 // The complete object may have a lower alignment than the non-virtual
14809 // alignment of the base, in which case the base may be misaligned. Choose
14810 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14811 // conservative lower bound of the complete object alignment.
14812 CharUnits NonVirtualAlignment =
14814 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14815 Offset = CharUnits::Zero();
14816 } else {
14817 const ASTRecordLayout &RL =
14818 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14819 Offset += RL.getBaseClassOffset(BaseDecl);
14820 }
14821 DerivedType = Base->getType();
14822 }
14823
14824 return std::make_pair(BaseAlignment, Offset);
14825}
14826
14827/// Compute the alignment and offset of a binary additive operator.
14828static std::optional<std::pair<CharUnits, CharUnits>>
14830 bool IsSub, ASTContext &Ctx) {
14831 QualType PointeeType = PtrE->getType()->getPointeeType();
14832
14833 if (!PointeeType->isConstantSizeType())
14834 return std::nullopt;
14835
14836 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14837
14838 if (!P)
14839 return std::nullopt;
14840
14841 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14842 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14843 CharUnits Offset = EltSize * IdxRes->getExtValue();
14844 if (IsSub)
14845 Offset = -Offset;
14846 return std::make_pair(P->first, P->second + Offset);
14847 }
14848
14849 // If the integer expression isn't a constant expression, compute the lower
14850 // bound of the alignment using the alignment and offset of the pointer
14851 // expression and the element size.
14852 return std::make_pair(
14853 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14854 CharUnits::Zero());
14855}
14856
14857/// This helper function takes an lvalue expression and returns the alignment of
14858/// a VarDecl and a constant offset from the VarDecl.
14859std::optional<std::pair<
14860 CharUnits,
14862 ASTContext &Ctx) {
14863 E = E->IgnoreParens();
14864 switch (E->getStmtClass()) {
14865 default:
14866 break;
14867 case Stmt::CStyleCastExprClass:
14868 case Stmt::CXXStaticCastExprClass:
14869 case Stmt::ImplicitCastExprClass: {
14870 auto *CE = cast<CastExpr>(E);
14871 const Expr *From = CE->getSubExpr();
14872 switch (CE->getCastKind()) {
14873 default:
14874 break;
14875 case CK_NoOp:
14876 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14877 case CK_UncheckedDerivedToBase:
14878 case CK_DerivedToBase: {
14879 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14880 if (!P)
14881 break;
14882 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14883 P->second, Ctx);
14884 }
14885 }
14886 break;
14887 }
14888 case Stmt::ArraySubscriptExprClass: {
14889 auto *ASE = cast<ArraySubscriptExpr>(E);
14891 false, Ctx);
14892 }
14893 case Stmt::DeclRefExprClass: {
14894 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14895 // FIXME: If VD is captured by copy or is an escaping __block variable,
14896 // use the alignment of VD's type.
14897 if (!VD->getType()->isReferenceType()) {
14898 // Dependent alignment cannot be resolved -> bail out.
14899 if (VD->hasDependentAlignment())
14900 break;
14901 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14902 }
14903 if (VD->hasInit())
14904 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14905 }
14906 break;
14907 }
14908 case Stmt::MemberExprClass: {
14909 auto *ME = cast<MemberExpr>(E);
14910 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14911 if (!FD || FD->getType()->isReferenceType() ||
14912 FD->getParent()->isInvalidDecl())
14913 break;
14914 std::optional<std::pair<CharUnits, CharUnits>> P;
14915 if (ME->isArrow())
14916 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14917 else
14918 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14919 if (!P)
14920 break;
14921 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14922 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14923 return std::make_pair(P->first,
14924 P->second + CharUnits::fromQuantity(Offset));
14925 }
14926 case Stmt::UnaryOperatorClass: {
14927 auto *UO = cast<UnaryOperator>(E);
14928 switch (UO->getOpcode()) {
14929 default:
14930 break;
14931 case UO_Deref:
14933 }
14934 break;
14935 }
14936 case Stmt::BinaryOperatorClass: {
14937 auto *BO = cast<BinaryOperator>(E);
14938 auto Opcode = BO->getOpcode();
14939 switch (Opcode) {
14940 default:
14941 break;
14942 case BO_Comma:
14944 }
14945 break;
14946 }
14947 }
14948 return std::nullopt;
14949}
14950
14951/// This helper function takes a pointer expression and returns the alignment of
14952/// a VarDecl and a constant offset from the VarDecl.
14953std::optional<std::pair<
14955 *E,
14957 &Ctx) {
14958 E = E->IgnoreParens();
14959 switch (E->getStmtClass()) {
14960 default:
14961 break;
14962 case Stmt::CStyleCastExprClass:
14963 case Stmt::CXXStaticCastExprClass:
14964 case Stmt::ImplicitCastExprClass: {
14965 auto *CE = cast<CastExpr>(E);
14966 const Expr *From = CE->getSubExpr();
14967 switch (CE->getCastKind()) {
14968 default:
14969 break;
14970 case CK_NoOp:
14971 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14972 case CK_ArrayToPointerDecay:
14973 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14974 case CK_UncheckedDerivedToBase:
14975 case CK_DerivedToBase: {
14976 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14977 if (!P)
14978 break;
14980 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14981 }
14982 }
14983 break;
14984 }
14985 case Stmt::CXXThisExprClass: {
14986 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14988 return std::make_pair(Alignment, CharUnits::Zero());
14989 }
14990 case Stmt::UnaryOperatorClass: {
14991 auto *UO = cast<UnaryOperator>(E);
14992 if (UO->getOpcode() == UO_AddrOf)
14994 break;
14995 }
14996 case Stmt::BinaryOperatorClass: {
14997 auto *BO = cast<BinaryOperator>(E);
14998 auto Opcode = BO->getOpcode();
14999 switch (Opcode) {
15000 default:
15001 break;
15002 case BO_Add:
15003 case BO_Sub: {
15004 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15005 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15006 std::swap(LHS, RHS);
15007 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15008 Ctx);
15009 }
15010 case BO_Comma:
15011 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15012 }
15013 break;
15014 }
15015 }
15016 return std::nullopt;
15017}
15018
15020 // See if we can compute the alignment of a VarDecl and an offset from it.
15021 std::optional<std::pair<CharUnits, CharUnits>> P =
15023
15024 if (P)
15025 return P->first.alignmentAtOffset(P->second);
15026
15027 // If that failed, return the type's alignment.
15029}
15030
15032 // This is actually a lot of work to potentially be doing on every
15033 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15034 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15035 return;
15036
15037 // Ignore dependent types.
15038 if (T->isDependentType() || Op->getType()->isDependentType())
15039 return;
15040
15041 // Require that the destination be a pointer type.
15042 const PointerType *DestPtr = T->getAs<PointerType>();
15043 if (!DestPtr) return;
15044
15045 // If the destination has alignment 1, we're done.
15046 QualType DestPointee = DestPtr->getPointeeType();
15047 if (DestPointee->isIncompleteType()) return;
15048 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15049 if (DestAlign.isOne()) return;
15050
15051 // Require that the source be a pointer type.
15052 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15053 if (!SrcPtr) return;
15054 QualType SrcPointee = SrcPtr->getPointeeType();
15055
15056 // Explicitly allow casts from cv void*. We already implicitly
15057 // allowed casts to cv void*, since they have alignment 1.
15058 // Also allow casts involving incomplete types, which implicitly
15059 // includes 'void'.
15060 if (SrcPointee->isIncompleteType()) return;
15061
15062 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15063
15064 if (SrcAlign >= DestAlign) return;
15065
15066 Diag(TRange.getBegin(), diag::warn_cast_align)
15067 << Op->getType() << T
15068 << static_cast<unsigned>(SrcAlign.getQuantity())
15069 << static_cast<unsigned>(DestAlign.getQuantity())
15070 << TRange << Op->getSourceRange();
15071}
15072
15073void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15074 const ArraySubscriptExpr *ASE,
15075 bool AllowOnePastEnd, bool IndexNegated) {
15076 // Already diagnosed by the constant evaluator.
15078 return;
15079
15080 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15081 if (IndexExpr->isValueDependent())
15082 return;
15083
15084 const Type *EffectiveType =
15086 BaseExpr = BaseExpr->IgnoreParenCasts();
15087 const ConstantArrayType *ArrayTy =
15088 Context.getAsConstantArrayType(BaseExpr->getType());
15089
15091 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15092
15093 const Type *BaseType =
15094 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15095 bool IsUnboundedArray =
15096 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15097 Context, StrictFlexArraysLevel,
15098 /*IgnoreTemplateOrMacroSubstitution=*/true);
15099 if (EffectiveType->isDependentType() ||
15100 (!IsUnboundedArray && BaseType->isDependentType()))
15101 return;
15102
15104 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15105 return;
15106
15107 llvm::APSInt index = Result.Val.getInt();
15108 if (IndexNegated) {
15109 index.setIsUnsigned(false);
15110 index = -index;
15111 }
15112
15113 if (IsUnboundedArray) {
15114 if (EffectiveType->isFunctionType())
15115 return;
15116 if (index.isUnsigned() || !index.isNegative()) {
15117 const auto &ASTC = getASTContext();
15118 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15119 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15120 if (index.getBitWidth() < AddrBits)
15121 index = index.zext(AddrBits);
15122 std::optional<CharUnits> ElemCharUnits =
15123 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15124 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15125 // pointer) bounds-checking isn't meaningful.
15126 if (!ElemCharUnits || ElemCharUnits->isZero())
15127 return;
15128 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15129 // If index has more active bits than address space, we already know
15130 // we have a bounds violation to warn about. Otherwise, compute
15131 // address of (index + 1)th element, and warn about bounds violation
15132 // only if that address exceeds address space.
15133 if (index.getActiveBits() <= AddrBits) {
15134 bool Overflow;
15135 llvm::APInt Product(index);
15136 Product += 1;
15137 Product = Product.umul_ov(ElemBytes, Overflow);
15138 if (!Overflow && Product.getActiveBits() <= AddrBits)
15139 return;
15140 }
15141
15142 // Need to compute max possible elements in address space, since that
15143 // is included in diag message.
15144 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15145 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15146 MaxElems += 1;
15147 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15148 MaxElems = MaxElems.udiv(ElemBytes);
15149
15150 unsigned DiagID =
15151 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15152 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15153
15154 // Diag message shows element size in bits and in "bytes" (platform-
15155 // dependent CharUnits)
15156 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15157 PDiag(DiagID) << index << AddrBits
15158 << (unsigned)ASTC.toBits(*ElemCharUnits)
15159 << ElemBytes << MaxElems
15160 << MaxElems.getZExtValue()
15161 << IndexExpr->getSourceRange());
15162
15163 const NamedDecl *ND = nullptr;
15164 // Try harder to find a NamedDecl to point at in the note.
15165 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15166 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15167 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15168 ND = DRE->getDecl();
15169 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15170 ND = ME->getMemberDecl();
15171
15172 if (ND)
15173 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15174 PDiag(diag::note_array_declared_here) << ND);
15175 }
15176 return;
15177 }
15178
15179 if (index.isUnsigned() || !index.isNegative()) {
15180 // It is possible that the type of the base expression after
15181 // IgnoreParenCasts is incomplete, even though the type of the base
15182 // expression before IgnoreParenCasts is complete (see PR39746 for an
15183 // example). In this case we have no information about whether the array
15184 // access exceeds the array bounds. However we can still diagnose an array
15185 // access which precedes the array bounds.
15186 if (BaseType->isIncompleteType())
15187 return;
15188
15189 llvm::APInt size = ArrayTy->getSize();
15190
15191 if (BaseType != EffectiveType) {
15192 // Make sure we're comparing apples to apples when comparing index to
15193 // size.
15194 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15195 uint64_t array_typesize = Context.getTypeSize(BaseType);
15196
15197 // Handle ptrarith_typesize being zero, such as when casting to void*.
15198 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15199 if (!ptrarith_typesize)
15200 ptrarith_typesize = Context.getCharWidth();
15201
15202 if (ptrarith_typesize != array_typesize) {
15203 // There's a cast to a different size type involved.
15204 uint64_t ratio = array_typesize / ptrarith_typesize;
15205
15206 // TODO: Be smarter about handling cases where array_typesize is not a
15207 // multiple of ptrarith_typesize.
15208 if (ptrarith_typesize * ratio == array_typesize)
15209 size *= llvm::APInt(size.getBitWidth(), ratio);
15210 }
15211 }
15212
15213 if (size.getBitWidth() > index.getBitWidth())
15214 index = index.zext(size.getBitWidth());
15215 else if (size.getBitWidth() < index.getBitWidth())
15216 size = size.zext(index.getBitWidth());
15217
15218 // For array subscripting the index must be less than size, but for pointer
15219 // arithmetic also allow the index (offset) to be equal to size since
15220 // computing the next address after the end of the array is legal and
15221 // commonly done e.g. in C++ iterators and range-based for loops.
15222 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15223 return;
15224
15225 // Suppress the warning if the subscript expression (as identified by the
15226 // ']' location) and the index expression are both from macro expansions
15227 // within a system header.
15228 if (ASE) {
15229 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15230 ASE->getRBracketLoc());
15231 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15232 SourceLocation IndexLoc =
15233 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15234 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15235 return;
15236 }
15237 }
15238
15239 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15240 : diag::warn_ptr_arith_exceeds_bounds;
15241 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15242 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15243
15244 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15245 PDiag(DiagID)
15246 << index << ArrayTy->desugar() << CastMsg
15247 << CastMsgTy << IndexExpr->getSourceRange());
15248 } else {
15249 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15250 if (!ASE) {
15251 DiagID = diag::warn_ptr_arith_precedes_bounds;
15252 if (index.isNegative()) index = -index;
15253 }
15254
15255 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15256 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15257 }
15258
15259 const NamedDecl *ND = nullptr;
15260 // Try harder to find a NamedDecl to point at in the note.
15261 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15262 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15263 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15264 ND = DRE->getDecl();
15265 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15266 ND = ME->getMemberDecl();
15267
15268 if (ND)
15269 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15270 PDiag(diag::note_array_declared_here) << ND);
15271}
15272
15273void Sema::CheckArrayAccess(const Expr *expr) {
15274 int AllowOnePastEnd = 0;
15275 while (expr) {
15276 expr = expr->IgnoreParenImpCasts();
15277 switch (expr->getStmtClass()) {
15278 case Stmt::ArraySubscriptExprClass: {
15279 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15280 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15281 AllowOnePastEnd > 0);
15282 expr = ASE->getBase();
15283 break;
15284 }
15285 case Stmt::MemberExprClass: {
15286 expr = cast<MemberExpr>(expr)->getBase();
15287 break;
15288 }
15289 case Stmt::ArraySectionExprClass: {
15290 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15291 // FIXME: We should probably be checking all of the elements to the
15292 // 'length' here as well.
15293 if (ASE->getLowerBound())
15294 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15295 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15296 return;
15297 }
15298 case Stmt::UnaryOperatorClass: {
15299 // Only unwrap the * and & unary operators
15300 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15301 expr = UO->getSubExpr();
15302 switch (UO->getOpcode()) {
15303 case UO_AddrOf:
15304 AllowOnePastEnd++;
15305 break;
15306 case UO_Deref:
15307 AllowOnePastEnd--;
15308 break;
15309 default:
15310 return;
15311 }
15312 break;
15313 }
15314 case Stmt::ConditionalOperatorClass: {
15315 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15316 if (const Expr *lhs = cond->getLHS())
15317 CheckArrayAccess(lhs);
15318 if (const Expr *rhs = cond->getRHS())
15319 CheckArrayAccess(rhs);
15320 return;
15321 }
15322 case Stmt::CXXOperatorCallExprClass: {
15323 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15324 for (const auto *Arg : OCE->arguments())
15325 CheckArrayAccess(Arg);
15326 return;
15327 }
15328 default:
15329 return;
15330 }
15331 }
15332}
15333
15335 Expr *RHS, bool isProperty) {
15336 // Check if RHS is an Objective-C object literal, which also can get
15337 // immediately zapped in a weak reference. Note that we explicitly
15338 // allow ObjCStringLiterals, since those are designed to never really die.
15339 RHS = RHS->IgnoreParenImpCasts();
15340
15341 // This enum needs to match with the 'select' in
15342 // warn_objc_arc_literal_assign (off-by-1).
15344 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15345 return false;
15346
15347 S.Diag(Loc, diag::warn_arc_literal_assign)
15348 << (unsigned) Kind
15349 << (isProperty ? 0 : 1)
15350 << RHS->getSourceRange();
15351
15352 return true;
15353}
15354
15357 Expr *RHS, bool isProperty) {
15358 // Strip off any implicit cast added to get to the one ARC-specific.
15359 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15360 if (cast->getCastKind() == CK_ARCConsumeObject) {
15361 S.Diag(Loc, diag::warn_arc_retained_assign)
15363 << (isProperty ? 0 : 1)
15364 << RHS->getSourceRange();
15365 return true;
15366 }
15367 RHS = cast->getSubExpr();
15368 }
15369
15370 if (LT == Qualifiers::OCL_Weak &&
15371 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15372 return true;
15373
15374 return false;
15375}
15376
15378 QualType LHS, Expr *RHS) {
15380
15382 return false;
15383
15384 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15385 return true;
15386
15387 return false;
15388}
15389
15391 Expr *LHS, Expr *RHS) {
15392 QualType LHSType;
15393 // PropertyRef on LHS type need be directly obtained from
15394 // its declaration as it has a PseudoType.
15396 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15397 if (PRE && !PRE->isImplicitProperty()) {
15398 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15399 if (PD)
15400 LHSType = PD->getType();
15401 }
15402
15403 if (LHSType.isNull())
15404 LHSType = LHS->getType();
15405
15407
15408 if (LT == Qualifiers::OCL_Weak) {
15409 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15411 }
15412
15413 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15414 return;
15415
15416 // FIXME. Check for other life times.
15417 if (LT != Qualifiers::OCL_None)
15418 return;
15419
15420 if (PRE) {
15421 if (PRE->isImplicitProperty())
15422 return;
15423 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15424 if (!PD)
15425 return;
15426
15427 unsigned Attributes = PD->getPropertyAttributes();
15428 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15429 // when 'assign' attribute was not explicitly specified
15430 // by user, ignore it and rely on property type itself
15431 // for lifetime info.
15432 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15433 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15434 LHSType->isObjCRetainableType())
15435 return;
15436
15437 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15438 if (cast->getCastKind() == CK_ARCConsumeObject) {
15439 Diag(Loc, diag::warn_arc_retained_property_assign)
15440 << RHS->getSourceRange();
15441 return;
15442 }
15443 RHS = cast->getSubExpr();
15444 }
15445 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15446 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15447 return;
15448 }
15449 }
15450}
15451
15452//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15453
15454static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15455 SourceLocation StmtLoc,
15456 const NullStmt *Body) {
15457 // Do not warn if the body is a macro that expands to nothing, e.g:
15458 //
15459 // #define CALL(x)
15460 // if (condition)
15461 // CALL(0);
15462 if (Body->hasLeadingEmptyMacro())
15463 return false;
15464
15465 // Get line numbers of statement and body.
15466 bool StmtLineInvalid;
15467 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15468 &StmtLineInvalid);
15469 if (StmtLineInvalid)
15470 return false;
15471
15472 bool BodyLineInvalid;
15473 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15474 &BodyLineInvalid);
15475 if (BodyLineInvalid)
15476 return false;
15477
15478 // Warn if null statement and body are on the same line.
15479 if (StmtLine != BodyLine)
15480 return false;
15481
15482 return true;
15483}
15484
15486 const Stmt *Body,
15487 unsigned DiagID) {
15488 // Since this is a syntactic check, don't emit diagnostic for template
15489 // instantiations, this just adds noise.
15491 return;
15492
15493 // The body should be a null statement.
15494 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15495 if (!NBody)
15496 return;
15497
15498 // Do the usual checks.
15499 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15500 return;
15501
15502 Diag(NBody->getSemiLoc(), DiagID);
15503 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15504}
15505
15507 const Stmt *PossibleBody) {
15508 assert(!CurrentInstantiationScope); // Ensured by caller
15509
15510 SourceLocation StmtLoc;
15511 const Stmt *Body;
15512 unsigned DiagID;
15513 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15514 StmtLoc = FS->getRParenLoc();
15515 Body = FS->getBody();
15516 DiagID = diag::warn_empty_for_body;
15517 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15518 StmtLoc = WS->getRParenLoc();
15519 Body = WS->getBody();
15520 DiagID = diag::warn_empty_while_body;
15521 } else
15522 return; // Neither `for' nor `while'.
15523
15524 // The body should be a null statement.
15525 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15526 if (!NBody)
15527 return;
15528
15529 // Skip expensive checks if diagnostic is disabled.
15530 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15531 return;
15532
15533 // Do the usual checks.
15534 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15535 return;
15536
15537 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15538 // noise level low, emit diagnostics only if for/while is followed by a
15539 // CompoundStmt, e.g.:
15540 // for (int i = 0; i < n; i++);
15541 // {
15542 // a(i);
15543 // }
15544 // or if for/while is followed by a statement with more indentation
15545 // than for/while itself:
15546 // for (int i = 0; i < n; i++);
15547 // a(i);
15548 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15549 if (!ProbableTypo) {
15550 bool BodyColInvalid;
15551 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15552 PossibleBody->getBeginLoc(), &BodyColInvalid);
15553 if (BodyColInvalid)
15554 return;
15555
15556 bool StmtColInvalid;
15557 unsigned StmtCol =
15558 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15559 if (StmtColInvalid)
15560 return;
15561
15562 if (BodyCol > StmtCol)
15563 ProbableTypo = true;
15564 }
15565
15566 if (ProbableTypo) {
15567 Diag(NBody->getSemiLoc(), DiagID);
15568 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15569 }
15570}
15571
15572//===--- CHECK: Warn on self move with std::move. -------------------------===//
15573
15574void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15575 SourceLocation OpLoc) {
15576 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15577 return;
15578
15580 return;
15581
15582 // Strip parens and casts away.
15583 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15584 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15585
15586 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15587 // which we can treat as an inlined std::move
15588 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15589 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15590 RHSExpr = CE->getArg(0);
15591 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15592 CXXSCE && CXXSCE->isXValue())
15593 RHSExpr = CXXSCE->getSubExpr();
15594 else
15595 return;
15596
15597 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15598 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15599
15600 // Two DeclRefExpr's, check that the decls are the same.
15601 if (LHSDeclRef && RHSDeclRef) {
15602 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15603 return;
15604 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15605 RHSDeclRef->getDecl()->getCanonicalDecl())
15606 return;
15607
15608 auto D = Diag(OpLoc, diag::warn_self_move)
15609 << LHSExpr->getType() << LHSExpr->getSourceRange()
15610 << RHSExpr->getSourceRange();
15611 if (const FieldDecl *F =
15613 D << 1 << F
15614 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15615 else
15616 D << 0;
15617 return;
15618 }
15619
15620 // Member variables require a different approach to check for self moves.
15621 // MemberExpr's are the same if every nested MemberExpr refers to the same
15622 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15623 // the base Expr's are CXXThisExpr's.
15624 const Expr *LHSBase = LHSExpr;
15625 const Expr *RHSBase = RHSExpr;
15626 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15627 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15628 if (!LHSME || !RHSME)
15629 return;
15630
15631 while (LHSME && RHSME) {
15632 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15633 RHSME->getMemberDecl()->getCanonicalDecl())
15634 return;
15635
15636 LHSBase = LHSME->getBase();
15637 RHSBase = RHSME->getBase();
15638 LHSME = dyn_cast<MemberExpr>(LHSBase);
15639 RHSME = dyn_cast<MemberExpr>(RHSBase);
15640 }
15641
15642 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15643 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15644 if (LHSDeclRef && RHSDeclRef) {
15645 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15646 return;
15647 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15648 RHSDeclRef->getDecl()->getCanonicalDecl())
15649 return;
15650
15651 Diag(OpLoc, diag::warn_self_move)
15652 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15653 << RHSExpr->getSourceRange();
15654 return;
15655 }
15656
15657 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15658 Diag(OpLoc, diag::warn_self_move)
15659 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15660 << RHSExpr->getSourceRange();
15661}
15662
15663//===--- Layout compatibility ----------------------------------------------//
15664
15665static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15666
15667/// Check if two enumeration types are layout-compatible.
15668static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15669 const EnumDecl *ED2) {
15670 // C++11 [dcl.enum] p8:
15671 // Two enumeration types are layout-compatible if they have the same
15672 // underlying type.
15673 return ED1->isComplete() && ED2->isComplete() &&
15674 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15675}
15676
15677/// Check if two fields are layout-compatible.
15678/// Can be used on union members, which are exempt from alignment requirement
15679/// of common initial sequence.
15680static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15681 const FieldDecl *Field2,
15682 bool AreUnionMembers = false) {
15683#ifndef NDEBUG
15684 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15685 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15686 assert(((Field1Parent->isStructureOrClassType() &&
15687 Field2Parent->isStructureOrClassType()) ||
15688 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15689 "Can't evaluate layout compatibility between a struct field and a "
15690 "union field.");
15691 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15692 (AreUnionMembers && Field1Parent->isUnionType())) &&
15693 "AreUnionMembers should be 'true' for union fields (only).");
15694#endif
15695
15696 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15697 return false;
15698
15699 if (Field1->isBitField() != Field2->isBitField())
15700 return false;
15701
15702 if (Field1->isBitField()) {
15703 // Make sure that the bit-fields are the same length.
15704 unsigned Bits1 = Field1->getBitWidthValue();
15705 unsigned Bits2 = Field2->getBitWidthValue();
15706
15707 if (Bits1 != Bits2)
15708 return false;
15709 }
15710
15711 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15712 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15713 return false;
15714
15715 if (!AreUnionMembers &&
15716 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15717 return false;
15718
15719 return true;
15720}
15721
15722/// Check if two standard-layout structs are layout-compatible.
15723/// (C++11 [class.mem] p17)
15724static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15725 const RecordDecl *RD2) {
15726 // Get to the class where the fields are declared
15727 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15728 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15729
15730 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15731 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15732
15733 // Check the fields.
15734 return llvm::equal(RD1->fields(), RD2->fields(),
15735 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15736 return isLayoutCompatible(C, F1, F2);
15737 });
15738}
15739
15740/// Check if two standard-layout unions are layout-compatible.
15741/// (C++11 [class.mem] p18)
15742static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15743 const RecordDecl *RD2) {
15744 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15745 RD2->fields());
15746
15747 for (auto *Field1 : RD1->fields()) {
15748 auto I = UnmatchedFields.begin();
15749 auto E = UnmatchedFields.end();
15750
15751 for ( ; I != E; ++I) {
15752 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15753 bool Result = UnmatchedFields.erase(*I);
15754 (void) Result;
15755 assert(Result);
15756 break;
15757 }
15758 }
15759 if (I == E)
15760 return false;
15761 }
15762
15763 return UnmatchedFields.empty();
15764}
15765
15766static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15767 const RecordDecl *RD2) {
15768 if (RD1->isUnion() != RD2->isUnion())
15769 return false;
15770
15771 if (RD1->isUnion())
15772 return isLayoutCompatibleUnion(C, RD1, RD2);
15773 else
15774 return isLayoutCompatibleStruct(C, RD1, RD2);
15775}
15776
15777/// Check if two types are layout-compatible in C++11 sense.
15778static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15779 if (T1.isNull() || T2.isNull())
15780 return false;
15781
15782 // C++20 [basic.types] p11:
15783 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15784 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15785 // or layout-compatible standard-layout class types (11.4).
15788
15789 if (C.hasSameType(T1, T2))
15790 return true;
15791
15792 const Type::TypeClass TC1 = T1->getTypeClass();
15793 const Type::TypeClass TC2 = T2->getTypeClass();
15794
15795 if (TC1 != TC2)
15796 return false;
15797
15798 if (TC1 == Type::Enum)
15799 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15800 if (TC1 == Type::Record) {
15801 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15802 return false;
15803
15805 T2->castAsRecordDecl());
15806 }
15807
15808 return false;
15809}
15810
15812 return isLayoutCompatible(getASTContext(), T1, T2);
15813}
15814
15815//===-------------- Pointer interconvertibility ----------------------------//
15816
15818 const TypeSourceInfo *Derived) {
15819 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15820 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15821
15822 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15823 getASTContext().hasSameType(BaseT, DerivedT))
15824 return true;
15825
15826 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15827 return false;
15828
15829 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15830 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15831 return true;
15832
15833 return false;
15834}
15835
15836//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15837
15838/// Given a type tag expression find the type tag itself.
15839///
15840/// \param TypeExpr Type tag expression, as it appears in user's code.
15841///
15842/// \param VD Declaration of an identifier that appears in a type tag.
15843///
15844/// \param MagicValue Type tag magic value.
15845///
15846/// \param isConstantEvaluated whether the evalaution should be performed in
15847
15848/// constant context.
15849static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15850 const ValueDecl **VD, uint64_t *MagicValue,
15851 bool isConstantEvaluated) {
15852 while(true) {
15853 if (!TypeExpr)
15854 return false;
15855
15856 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15857
15858 switch (TypeExpr->getStmtClass()) {
15859 case Stmt::UnaryOperatorClass: {
15860 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15861 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15862 TypeExpr = UO->getSubExpr();
15863 continue;
15864 }
15865 return false;
15866 }
15867
15868 case Stmt::DeclRefExprClass: {
15869 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15870 *VD = DRE->getDecl();
15871 return true;
15872 }
15873
15874 case Stmt::IntegerLiteralClass: {
15875 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15876 llvm::APInt MagicValueAPInt = IL->getValue();
15877 if (MagicValueAPInt.getActiveBits() <= 64) {
15878 *MagicValue = MagicValueAPInt.getZExtValue();
15879 return true;
15880 } else
15881 return false;
15882 }
15883
15884 case Stmt::BinaryConditionalOperatorClass:
15885 case Stmt::ConditionalOperatorClass: {
15886 const AbstractConditionalOperator *ACO =
15888 bool Result;
15889 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15890 isConstantEvaluated)) {
15891 if (Result)
15892 TypeExpr = ACO->getTrueExpr();
15893 else
15894 TypeExpr = ACO->getFalseExpr();
15895 continue;
15896 }
15897 return false;
15898 }
15899
15900 case Stmt::BinaryOperatorClass: {
15901 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15902 if (BO->getOpcode() == BO_Comma) {
15903 TypeExpr = BO->getRHS();
15904 continue;
15905 }
15906 return false;
15907 }
15908
15909 default:
15910 return false;
15911 }
15912 }
15913}
15914
15915/// Retrieve the C type corresponding to type tag TypeExpr.
15916///
15917/// \param TypeExpr Expression that specifies a type tag.
15918///
15919/// \param MagicValues Registered magic values.
15920///
15921/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15922/// kind.
15923///
15924/// \param TypeInfo Information about the corresponding C type.
15925///
15926/// \param isConstantEvaluated whether the evalaution should be performed in
15927/// constant context.
15928///
15929/// \returns true if the corresponding C type was found.
15931 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15932 const ASTContext &Ctx,
15933 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15934 *MagicValues,
15935 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15936 bool isConstantEvaluated) {
15937 FoundWrongKind = false;
15938
15939 // Variable declaration that has type_tag_for_datatype attribute.
15940 const ValueDecl *VD = nullptr;
15941
15942 uint64_t MagicValue;
15943
15944 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15945 return false;
15946
15947 if (VD) {
15948 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15949 if (I->getArgumentKind() != ArgumentKind) {
15950 FoundWrongKind = true;
15951 return false;
15952 }
15953 TypeInfo.Type = I->getMatchingCType();
15954 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15955 TypeInfo.MustBeNull = I->getMustBeNull();
15956 return true;
15957 }
15958 return false;
15959 }
15960
15961 if (!MagicValues)
15962 return false;
15963
15964 llvm::DenseMap<Sema::TypeTagMagicValue,
15966 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15967 if (I == MagicValues->end())
15968 return false;
15969
15970 TypeInfo = I->second;
15971 return true;
15972}
15973
15975 uint64_t MagicValue, QualType Type,
15976 bool LayoutCompatible,
15977 bool MustBeNull) {
15978 if (!TypeTagForDatatypeMagicValues)
15979 TypeTagForDatatypeMagicValues.reset(
15980 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15981
15982 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15983 (*TypeTagForDatatypeMagicValues)[Magic] =
15984 TypeTagData(Type, LayoutCompatible, MustBeNull);
15985}
15986
15987static bool IsSameCharType(QualType T1, QualType T2) {
15988 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15989 if (!BT1)
15990 return false;
15991
15992 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15993 if (!BT2)
15994 return false;
15995
15996 BuiltinType::Kind T1Kind = BT1->getKind();
15997 BuiltinType::Kind T2Kind = BT2->getKind();
15998
15999 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16000 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16001 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16002 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16003}
16004
16005void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16006 const ArrayRef<const Expr *> ExprArgs,
16007 SourceLocation CallSiteLoc) {
16008 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16009 bool IsPointerAttr = Attr->getIsPointer();
16010
16011 // Retrieve the argument representing the 'type_tag'.
16012 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16013 if (TypeTagIdxAST >= ExprArgs.size()) {
16014 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16015 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16016 return;
16017 }
16018 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16019 bool FoundWrongKind;
16020 TypeTagData TypeInfo;
16021 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16022 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16023 TypeInfo, isConstantEvaluatedContext())) {
16024 if (FoundWrongKind)
16025 Diag(TypeTagExpr->getExprLoc(),
16026 diag::warn_type_tag_for_datatype_wrong_kind)
16027 << TypeTagExpr->getSourceRange();
16028 return;
16029 }
16030
16031 // Retrieve the argument representing the 'arg_idx'.
16032 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16033 if (ArgumentIdxAST >= ExprArgs.size()) {
16034 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16035 << 1 << Attr->getArgumentIdx().getSourceIndex();
16036 return;
16037 }
16038 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16039 if (IsPointerAttr) {
16040 // Skip implicit cast of pointer to `void *' (as a function argument).
16041 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16042 if (ICE->getType()->isVoidPointerType() &&
16043 ICE->getCastKind() == CK_BitCast)
16044 ArgumentExpr = ICE->getSubExpr();
16045 }
16046 QualType ArgumentType = ArgumentExpr->getType();
16047
16048 // Passing a `void*' pointer shouldn't trigger a warning.
16049 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16050 return;
16051
16052 if (TypeInfo.MustBeNull) {
16053 // Type tag with matching void type requires a null pointer.
16054 if (!ArgumentExpr->isNullPointerConstant(Context,
16056 Diag(ArgumentExpr->getExprLoc(),
16057 diag::warn_type_safety_null_pointer_required)
16058 << ArgumentKind->getName()
16059 << ArgumentExpr->getSourceRange()
16060 << TypeTagExpr->getSourceRange();
16061 }
16062 return;
16063 }
16064
16065 QualType RequiredType = TypeInfo.Type;
16066 if (IsPointerAttr)
16067 RequiredType = Context.getPointerType(RequiredType);
16068
16069 bool mismatch = false;
16070 if (!TypeInfo.LayoutCompatible) {
16071 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16072
16073 // C++11 [basic.fundamental] p1:
16074 // Plain char, signed char, and unsigned char are three distinct types.
16075 //
16076 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16077 // char' depending on the current char signedness mode.
16078 if (mismatch)
16079 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16080 RequiredType->getPointeeType())) ||
16081 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16082 mismatch = false;
16083 } else
16084 if (IsPointerAttr)
16085 mismatch = !isLayoutCompatible(Context,
16086 ArgumentType->getPointeeType(),
16087 RequiredType->getPointeeType());
16088 else
16089 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16090
16091 if (mismatch)
16092 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16093 << ArgumentType << ArgumentKind
16094 << TypeInfo.LayoutCompatible << RequiredType
16095 << ArgumentExpr->getSourceRange()
16096 << TypeTagExpr->getSourceRange();
16097}
16098
16099void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16100 CharUnits Alignment) {
16101 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16102 Alignment);
16103}
16104
16106 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16107 const NamedDecl *ND = m.RD;
16108 if (ND->getName().empty()) {
16109 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16110 ND = TD;
16111 }
16112 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16113 << m.MD << ND << m.E->getSourceRange();
16114 }
16116}
16117
16119 E = E->IgnoreParens();
16120 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16121 return;
16122 if (isa<UnaryOperator>(E) &&
16123 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16124 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16125 if (isa<MemberExpr>(Op)) {
16126 auto &MisalignedMembersForExpr =
16128 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16129 if (MA != MisalignedMembersForExpr.end() &&
16130 (T->isDependentType() || T->isIntegerType() ||
16131 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16132 Context.getTypeAlignInChars(
16133 T->getPointeeType()) <= MA->Alignment))))
16134 MisalignedMembersForExpr.erase(MA);
16135 }
16136 }
16137}
16138
16140 Expr *E,
16141 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16142 Action) {
16143 const auto *ME = dyn_cast<MemberExpr>(E);
16144 if (!ME)
16145 return;
16146
16147 // No need to check expressions with an __unaligned-qualified type.
16148 if (E->getType().getQualifiers().hasUnaligned())
16149 return;
16150
16151 // For a chain of MemberExpr like "a.b.c.d" this list
16152 // will keep FieldDecl's like [d, c, b].
16153 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16154 const MemberExpr *TopME = nullptr;
16155 bool AnyIsPacked = false;
16156 do {
16157 QualType BaseType = ME->getBase()->getType();
16158 if (BaseType->isDependentType())
16159 return;
16160 if (ME->isArrow())
16161 BaseType = BaseType->getPointeeType();
16162 auto *RD = BaseType->castAsRecordDecl();
16163 if (RD->isInvalidDecl())
16164 return;
16165
16166 ValueDecl *MD = ME->getMemberDecl();
16167 auto *FD = dyn_cast<FieldDecl>(MD);
16168 // We do not care about non-data members.
16169 if (!FD || FD->isInvalidDecl())
16170 return;
16171
16172 AnyIsPacked =
16173 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16174 ReverseMemberChain.push_back(FD);
16175
16176 TopME = ME;
16177 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16178 } while (ME);
16179 assert(TopME && "We did not compute a topmost MemberExpr!");
16180
16181 // Not the scope of this diagnostic.
16182 if (!AnyIsPacked)
16183 return;
16184
16185 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16186 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16187 // TODO: The innermost base of the member expression may be too complicated.
16188 // For now, just disregard these cases. This is left for future
16189 // improvement.
16190 if (!DRE && !isa<CXXThisExpr>(TopBase))
16191 return;
16192
16193 // Alignment expected by the whole expression.
16194 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16195
16196 // No need to do anything else with this case.
16197 if (ExpectedAlignment.isOne())
16198 return;
16199
16200 // Synthesize offset of the whole access.
16201 CharUnits Offset;
16202 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16203 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16204
16205 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16206 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16207 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16208
16209 // The base expression of the innermost MemberExpr may give
16210 // stronger guarantees than the class containing the member.
16211 if (DRE && !TopME->isArrow()) {
16212 const ValueDecl *VD = DRE->getDecl();
16213 if (!VD->getType()->isReferenceType())
16214 CompleteObjectAlignment =
16215 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16216 }
16217
16218 // Check if the synthesized offset fulfills the alignment.
16219 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16220 // It may fulfill the offset it but the effective alignment may still be
16221 // lower than the expected expression alignment.
16222 CompleteObjectAlignment < ExpectedAlignment) {
16223 // If this happens, we want to determine a sensible culprit of this.
16224 // Intuitively, watching the chain of member expressions from right to
16225 // left, we start with the required alignment (as required by the field
16226 // type) but some packed attribute in that chain has reduced the alignment.
16227 // It may happen that another packed structure increases it again. But if
16228 // we are here such increase has not been enough. So pointing the first
16229 // FieldDecl that either is packed or else its RecordDecl is,
16230 // seems reasonable.
16231 FieldDecl *FD = nullptr;
16232 CharUnits Alignment;
16233 for (FieldDecl *FDI : ReverseMemberChain) {
16234 if (FDI->hasAttr<PackedAttr>() ||
16235 FDI->getParent()->hasAttr<PackedAttr>()) {
16236 FD = FDI;
16237 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16238 Context.getTypeAlignInChars(
16239 Context.getCanonicalTagType(FD->getParent())));
16240 break;
16241 }
16242 }
16243 assert(FD && "We did not find a packed FieldDecl!");
16244 Action(E, FD->getParent(), FD, Alignment);
16245 }
16246}
16247
16248void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16249 using namespace std::placeholders;
16250
16252 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16253 _2, _3, _4));
16254}
16255
16257 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16258 if (checkArgCount(TheCall, 1))
16259 return true;
16260
16261 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16262 if (A.isInvalid())
16263 return true;
16264
16265 TheCall->setArg(0, A.get());
16266 QualType TyA = A.get()->getType();
16267
16268 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16269 ArgTyRestr, 1))
16270 return true;
16271
16272 TheCall->setType(TyA);
16273 return false;
16274}
16275
16276bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16277 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16278 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16279 TheCall->setType(*Res);
16280 return false;
16281 }
16282 return true;
16283}
16284
16286 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16287 if (!Res)
16288 return true;
16289
16290 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16291 TheCall->setType(VecTy0->getElementType());
16292 else
16293 TheCall->setType(*Res);
16294
16295 return false;
16296}
16297
16299 SourceLocation Loc) {
16301 R = RHS->getEnumCoercedType(S.Context);
16302 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16304 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16305 << LHS->getSourceRange() << RHS->getSourceRange()
16306 << /*Arithmetic Between*/ 0 << L << R;
16307 }
16308 return false;
16309}
16310
16311/// Check if all arguments have the same type. If the types don't match, emit an
16312/// error message and return true. Otherwise return false.
16313///
16314/// For scalars we directly compare their unqualified types. But even if we
16315/// compare unqualified vector types, a difference in qualifiers in the element
16316/// types can make the vector types be considered not equal. For example,
16317/// vector of 4 'const float' values vs vector of 4 'float' values.
16318/// So we compare unqualified types of their elements and number of elements.
16320 ArrayRef<Expr *> Args) {
16321 assert(!Args.empty() && "Should have at least one argument.");
16322
16323 Expr *Arg0 = Args.front();
16324 QualType Ty0 = Arg0->getType();
16325
16326 auto EmitError = [&](Expr *ArgI) {
16327 SemaRef.Diag(Arg0->getBeginLoc(),
16328 diag::err_typecheck_call_different_arg_types)
16329 << Arg0->getType() << ArgI->getType();
16330 };
16331
16332 // Compare scalar types.
16333 if (!Ty0->isVectorType()) {
16334 for (Expr *ArgI : Args.drop_front())
16335 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16336 EmitError(ArgI);
16337 return true;
16338 }
16339
16340 return false;
16341 }
16342
16343 // Compare vector types.
16344 const auto *Vec0 = Ty0->castAs<VectorType>();
16345 for (Expr *ArgI : Args.drop_front()) {
16346 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16347 if (!VecI ||
16348 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16349 VecI->getElementType()) ||
16350 Vec0->getNumElements() != VecI->getNumElements()) {
16351 EmitError(ArgI);
16352 return true;
16353 }
16354 }
16355
16356 return false;
16357}
16358
16359std::optional<QualType>
16361 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16362 if (checkArgCount(TheCall, 2))
16363 return std::nullopt;
16364
16366 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16367 return std::nullopt;
16368
16369 Expr *Args[2];
16370 for (int I = 0; I < 2; ++I) {
16371 ExprResult Converted =
16372 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16373 if (Converted.isInvalid())
16374 return std::nullopt;
16375 Args[I] = Converted.get();
16376 }
16377
16378 SourceLocation LocA = Args[0]->getBeginLoc();
16379 QualType TyA = Args[0]->getType();
16380
16381 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16382 return std::nullopt;
16383
16384 if (checkBuiltinVectorMathArgTypes(*this, Args))
16385 return std::nullopt;
16386
16387 TheCall->setArg(0, Args[0]);
16388 TheCall->setArg(1, Args[1]);
16389 return TyA;
16390}
16391
16393 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16394 if (checkArgCount(TheCall, 3))
16395 return true;
16396
16397 SourceLocation Loc = TheCall->getExprLoc();
16398 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16399 TheCall->getArg(1), Loc) ||
16400 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16401 TheCall->getArg(2), Loc))
16402 return true;
16403
16404 Expr *Args[3];
16405 for (int I = 0; I < 3; ++I) {
16406 ExprResult Converted =
16407 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16408 if (Converted.isInvalid())
16409 return true;
16410 Args[I] = Converted.get();
16411 }
16412
16413 int ArgOrdinal = 1;
16414 for (Expr *Arg : Args) {
16415 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16416 ArgTyRestr, ArgOrdinal++))
16417 return true;
16418 }
16419
16420 if (checkBuiltinVectorMathArgTypes(*this, Args))
16421 return true;
16422
16423 for (int I = 0; I < 3; ++I)
16424 TheCall->setArg(I, Args[I]);
16425
16426 TheCall->setType(Args[0]->getType());
16427 return false;
16428}
16429
16430bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16431 if (checkArgCount(TheCall, 1))
16432 return true;
16433
16434 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16435 if (A.isInvalid())
16436 return true;
16437
16438 TheCall->setArg(0, A.get());
16439 return false;
16440}
16441
16442bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16443 if (checkArgCount(TheCall, 1))
16444 return true;
16445
16446 ExprResult Arg = TheCall->getArg(0);
16447 QualType TyArg = Arg.get()->getType();
16448
16449 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16450 return Diag(TheCall->getArg(0)->getBeginLoc(),
16451 diag::err_builtin_invalid_arg_type)
16452 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16453
16454 TheCall->setType(TyArg);
16455 return false;
16456}
16457
16458ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16459 ExprResult CallResult) {
16460 if (checkArgCount(TheCall, 1))
16461 return ExprError();
16462
16463 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16464 if (MatrixArg.isInvalid())
16465 return MatrixArg;
16466 Expr *Matrix = MatrixArg.get();
16467
16468 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16469 if (!MType) {
16470 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16471 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16472 << Matrix->getType();
16473 return ExprError();
16474 }
16475
16476 // Create returned matrix type by swapping rows and columns of the argument
16477 // matrix type.
16478 QualType ResultType = Context.getConstantMatrixType(
16479 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16480
16481 // Change the return type to the type of the returned matrix.
16482 TheCall->setType(ResultType);
16483
16484 // Update call argument to use the possibly converted matrix argument.
16485 TheCall->setArg(0, Matrix);
16486 return CallResult;
16487}
16488
16489// Get and verify the matrix dimensions.
16490static std::optional<unsigned>
16492 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16493 if (!Value) {
16494 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16495 << Name;
16496 return {};
16497 }
16498 uint64_t Dim = Value->getZExtValue();
16499 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16500 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16501 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16502 return {};
16503 }
16504 return Dim;
16505}
16506
16507ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16508 ExprResult CallResult) {
16509 if (!getLangOpts().MatrixTypes) {
16510 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16511 return ExprError();
16512 }
16513
16514 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16516 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16517 << /*column*/ 1 << /*load*/ 0;
16518 return ExprError();
16519 }
16520
16521 if (checkArgCount(TheCall, 4))
16522 return ExprError();
16523
16524 unsigned PtrArgIdx = 0;
16525 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16526 Expr *RowsExpr = TheCall->getArg(1);
16527 Expr *ColumnsExpr = TheCall->getArg(2);
16528 Expr *StrideExpr = TheCall->getArg(3);
16529
16530 bool ArgError = false;
16531
16532 // Check pointer argument.
16533 {
16535 if (PtrConv.isInvalid())
16536 return PtrConv;
16537 PtrExpr = PtrConv.get();
16538 TheCall->setArg(0, PtrExpr);
16539 if (PtrExpr->isTypeDependent()) {
16540 TheCall->setType(Context.DependentTy);
16541 return TheCall;
16542 }
16543 }
16544
16545 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16546 QualType ElementTy;
16547 if (!PtrTy) {
16548 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16549 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16550 << PtrExpr->getType();
16551 ArgError = true;
16552 } else {
16553 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16554
16556 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16557 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16558 << /* no fp */ 0 << PtrExpr->getType();
16559 ArgError = true;
16560 }
16561 }
16562
16563 // Apply default Lvalue conversions and convert the expression to size_t.
16564 auto ApplyArgumentConversions = [this](Expr *E) {
16566 if (Conv.isInvalid())
16567 return Conv;
16568
16569 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16570 };
16571
16572 // Apply conversion to row and column expressions.
16573 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16574 if (!RowsConv.isInvalid()) {
16575 RowsExpr = RowsConv.get();
16576 TheCall->setArg(1, RowsExpr);
16577 } else
16578 RowsExpr = nullptr;
16579
16580 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16581 if (!ColumnsConv.isInvalid()) {
16582 ColumnsExpr = ColumnsConv.get();
16583 TheCall->setArg(2, ColumnsExpr);
16584 } else
16585 ColumnsExpr = nullptr;
16586
16587 // If any part of the result matrix type is still pending, just use
16588 // Context.DependentTy, until all parts are resolved.
16589 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16590 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16591 TheCall->setType(Context.DependentTy);
16592 return CallResult;
16593 }
16594
16595 // Check row and column dimensions.
16596 std::optional<unsigned> MaybeRows;
16597 if (RowsExpr)
16598 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16599
16600 std::optional<unsigned> MaybeColumns;
16601 if (ColumnsExpr)
16602 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16603
16604 // Check stride argument.
16605 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16606 if (StrideConv.isInvalid())
16607 return ExprError();
16608 StrideExpr = StrideConv.get();
16609 TheCall->setArg(3, StrideExpr);
16610
16611 if (MaybeRows) {
16612 if (std::optional<llvm::APSInt> Value =
16613 StrideExpr->getIntegerConstantExpr(Context)) {
16614 uint64_t Stride = Value->getZExtValue();
16615 if (Stride < *MaybeRows) {
16616 Diag(StrideExpr->getBeginLoc(),
16617 diag::err_builtin_matrix_stride_too_small);
16618 ArgError = true;
16619 }
16620 }
16621 }
16622
16623 if (ArgError || !MaybeRows || !MaybeColumns)
16624 return ExprError();
16625
16626 TheCall->setType(
16627 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16628 return CallResult;
16629}
16630
16631ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16632 ExprResult CallResult) {
16633 if (!getLangOpts().MatrixTypes) {
16634 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16635 return ExprError();
16636 }
16637
16638 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16640 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16641 << /*column*/ 1 << /*store*/ 1;
16642 return ExprError();
16643 }
16644
16645 if (checkArgCount(TheCall, 3))
16646 return ExprError();
16647
16648 unsigned PtrArgIdx = 1;
16649 Expr *MatrixExpr = TheCall->getArg(0);
16650 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16651 Expr *StrideExpr = TheCall->getArg(2);
16652
16653 bool ArgError = false;
16654
16655 {
16656 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16657 if (MatrixConv.isInvalid())
16658 return MatrixConv;
16659 MatrixExpr = MatrixConv.get();
16660 TheCall->setArg(0, MatrixExpr);
16661 }
16662 if (MatrixExpr->isTypeDependent()) {
16663 TheCall->setType(Context.DependentTy);
16664 return TheCall;
16665 }
16666
16667 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16668 if (!MatrixTy) {
16669 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16670 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16671 ArgError = true;
16672 }
16673
16674 {
16676 if (PtrConv.isInvalid())
16677 return PtrConv;
16678 PtrExpr = PtrConv.get();
16679 TheCall->setArg(1, PtrExpr);
16680 if (PtrExpr->isTypeDependent()) {
16681 TheCall->setType(Context.DependentTy);
16682 return TheCall;
16683 }
16684 }
16685
16686 // Check pointer argument.
16687 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16688 if (!PtrTy) {
16689 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16690 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16691 << PtrExpr->getType();
16692 ArgError = true;
16693 } else {
16694 QualType ElementTy = PtrTy->getPointeeType();
16695 if (ElementTy.isConstQualified()) {
16696 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16697 ArgError = true;
16698 }
16699 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16700 if (MatrixTy &&
16701 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16702 Diag(PtrExpr->getBeginLoc(),
16703 diag::err_builtin_matrix_pointer_arg_mismatch)
16704 << ElementTy << MatrixTy->getElementType();
16705 ArgError = true;
16706 }
16707 }
16708
16709 // Apply default Lvalue conversions and convert the stride expression to
16710 // size_t.
16711 {
16712 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16713 if (StrideConv.isInvalid())
16714 return StrideConv;
16715
16716 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16717 if (StrideConv.isInvalid())
16718 return StrideConv;
16719 StrideExpr = StrideConv.get();
16720 TheCall->setArg(2, StrideExpr);
16721 }
16722
16723 // Check stride argument.
16724 if (MatrixTy) {
16725 if (std::optional<llvm::APSInt> Value =
16726 StrideExpr->getIntegerConstantExpr(Context)) {
16727 uint64_t Stride = Value->getZExtValue();
16728 if (Stride < MatrixTy->getNumRows()) {
16729 Diag(StrideExpr->getBeginLoc(),
16730 diag::err_builtin_matrix_stride_too_small);
16731 ArgError = true;
16732 }
16733 }
16734 }
16735
16736 if (ArgError)
16737 return ExprError();
16738
16739 return CallResult;
16740}
16741
16743 const NamedDecl *Callee) {
16744 // This warning does not make sense in code that has no runtime behavior.
16746 return;
16747
16748 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16749
16750 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16751 return;
16752
16753 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16754 // all TCBs the callee is a part of.
16755 llvm::StringSet<> CalleeTCBs;
16756 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16757 CalleeTCBs.insert(A->getTCBName());
16758 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16759 CalleeTCBs.insert(A->getTCBName());
16760
16761 // Go through the TCBs the caller is a part of and emit warnings if Caller
16762 // is in a TCB that the Callee is not.
16763 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16764 StringRef CallerTCB = A->getTCBName();
16765 if (CalleeTCBs.count(CallerTCB) == 0) {
16766 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16767 << Callee << CallerTCB;
16768 }
16769 }
16770}
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 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 IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static 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)
MathCheck
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
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
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isComplexInt() const
Definition APValue.h:470
bool isFloat() const
Definition APValue.h:468
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isInt() const
Definition APValue.h:467
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
bool isAddrLabelDiff() const
Definition APValue.h:478
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
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:791
Builtin::Context & BuiltinInfo
Definition ASTContext.h:793
const LangOptions & getLangOpts() const
Definition ASTContext.h:945
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:844
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:910
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:4287
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4465
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4471
SourceLocation getQuestionLoc() const
Definition Expr.h:4314
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4477
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Expr * getBase()
Get base of the array section.
Definition Expr.h:7183
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7187
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getRBracketLoc() const
Definition Expr.h:2769
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
QualType getElementType() const
Definition TypeBase.h:3734
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:6963
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:6945
Attr - This represents one attribute.
Definition Attr.h:45
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:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
SourceLocation getExprLoc() const
Definition Expr.h:4013
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
BinaryOperatorKind Opcode
Definition Expr.h:3977
Pointer to a block type.
Definition TypeBase.h:3542
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
bool isInteger() const
Definition TypeBase.h:3225
bool isFloatingPoint() const
Definition TypeBase.h:3237
bool isSignedInteger() const
Definition TypeBase.h:3229
bool isUnsignedInteger() const
Definition TypeBase.h:3233
Kind getKind() const
Definition TypeBase.h:3212
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h: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:3903
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1630
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1688
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:154
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3094
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1591
arg_iterator arg_begin()
Definition Expr.h:3134
arg_iterator arg_end()
Definition Expr.h:3137
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
bool isCallToStdMove() const
Definition Expr.cpp:3623
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3170
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
arg_range arguments()
Definition Expr.h:3129
SourceLocation getEndLoc() const
Definition Expr.h:3230
SourceLocation getRParenLoc() const
Definition Expr.h:3208
Decl * getCalleeDecl()
Definition Expr.h:3054
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition Expr.cpp:1596
void setCallee(Expr *F)
Definition Expr.h:3026
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3113
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
Expr * getSubExpr()
Definition Expr.h:3660
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getLHS() const
Definition Expr.h:4359
Expr * getRHS() const
Definition Expr.h:4360
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
QualType desugar() const
Definition TypeBase.h:3861
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4395
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:5558
Expr * getOperand() const
Definition ExprCXX.h:5324
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:487
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp: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:1995
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4007
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4239
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4180
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:671
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
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:3085
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:205
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:4207
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
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:3669
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:3069
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4046
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:265
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:225
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:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4748
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2878
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4549
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:3758
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3861
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:3129
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4325
bool isStatic() const
Definition Decl.h:2929
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4140
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4126
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3822
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
unsigned getNumParams() const
Definition TypeBase.h:5532
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5653
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4759
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4755
QualType getReturnType() const
Definition TypeBase.h:4790
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
Describes an C or C++ initializer list.
Definition Expr.h:5233
ArrayRef< Expr * > inits()
Definition Expr.h:5283
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:974
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1020
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1056
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:498
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1103
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:848
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1937
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1693
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1707
SourceLocation getSemiLoc() const
Definition Stmt.h:1704
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:273
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6690
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5075
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2866
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8318
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
void removeLocalVolatile()
Definition TypeBase.h:8394
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8386
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8399
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8324
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4321
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4407
field_range fields() const
Definition Decl.h:4524
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4399
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:1025
@ 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:1108
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:97
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:277
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:283
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:526
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
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:1416
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:13030
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
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:2640
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9319
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9327
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9364
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:6917
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2045
SemaHexagon & Hexagon()
Definition Sema.h:1456
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:1654
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:833
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1546
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:1283
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
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:1486
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:754
ASTContext & getASTContext() const
Definition Sema.h:925
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:2585
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:1191
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:2692
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:918
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:1431
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:1446
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:1281
static const uint64_t MaximumAlignment
Definition Sema.h:1214
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:952
SemaHLSL & HLSL()
Definition Sema.h:1451
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1471
SemaRISCV & RISCV()
Definition Sema.h:1516
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:2758
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6950
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1666
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:1314
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:2665
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15348
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:2295
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:639
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:1414
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:1496
FormatArgumentPassingKind
Definition Sema.h:2595
@ FAPK_Elsewhere
Definition Sema.h:2599
@ FAPK_Fixed
Definition Sema.h:2596
@ FAPK_Variadic
Definition Sema.h:2597
@ FAPK_VAList
Definition Sema.h:2598
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:8161
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:13909
SourceManager & getSourceManager() const
Definition Sema.h:923
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
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:2587
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:1506
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:1246
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:1536
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:1286
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:783
DiagnosticsEngine & Diags
Definition Sema.h:1285
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:1481
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:6217
SemaSPIRV & SPIRV()
Definition Sema.h:1521
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:1461
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6405
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:1541
SemaARM & ARM()
Definition Sema.h:1421
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4577
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
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:299
StmtClass getStmtClass() const
Definition Stmt.h:1483
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
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:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
bool isUTF8() const
Definition Expr.h:1918
bool isWide() const
Definition Expr.h:1917
bool isPascal() const
Definition Expr.h:1922
unsigned getLength() const
Definition Expr.h:1909
StringLiteralKind getKind() const
Definition Expr.h:1912
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition Expr.cpp:1325
bool isUTF32() const
Definition Expr.h:1920
unsigned getByteLength() const
Definition Expr.h:1908
StringRef getString() const
Definition Expr.h:1867
bool isUTF16() const
Definition Expr.h:1919
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1974
bool isOrdinary() const
Definition Expr.h:1916
unsigned getCharByteWidth() const
Definition Expr.h:1910
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3832
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isUnion() const
Definition Decl.h:3922
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h: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:2706
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:6165
A container of type source information.
Definition TypeBase.h:8249
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:8260
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9051
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9031
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2066
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2425
bool isArrayType() const
Definition TypeBase.h:8614
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isPointerType() const
Definition TypeBase.h:8515
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isScalarType() const
Definition TypeBase.h:8973
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1909
bool isVariableArrayType() const
Definition TypeBase.h:8626
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isExtVectorType() const
Definition TypeBase.h:8658
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2646
bool isBitIntType() const
Definition TypeBase.h:8780
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8840
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8638
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2243
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2557
bool isAtomicType() const
Definition TypeBase.h:8697
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3074
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isUnscopedEnumerationType() const
Definition Type.cpp:2125
bool isObjCObjectType() const
Definition TypeBase.h:8688
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9144
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2312
bool isStructureOrClassType() const
Definition Type.cpp:706
bool isVectorType() const
Definition TypeBase.h:8654
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
bool isAnyPointerType() const
Definition TypeBase.h:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isObjCRetainableType() const
Definition Type.cpp:5283
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2569
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2634
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2362
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3395
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:5515
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2687
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:1257
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1242
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1235
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1249
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2492
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1203
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1264
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
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:511
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:661
@ Comparison
A comparison.
Definition Sema.h:665
@ 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:592
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:545
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
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:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:497
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:519
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:127
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
StringLiteralKind
Definition Expr.h:1763
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Win64
Definition Specifiers.h:285
@ CC_X86_64SysV
Definition Specifiers.h:286
@ Generic
not a target-specific vector type
Definition TypeBase.h:4136
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5874
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
Extra information about a function prototype.
Definition TypeBase.h:5339
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned Indentation
The number of spaces to use to indent each line.
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13201
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13227
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13217
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13176
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6811
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2607
#define log2(__x)
Definition tgmath.h:970