clang 20.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 "clang/AST/APValue.h"
16#include "clang/AST/Attr.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
31#include "clang/AST/NSAPI.h"
35#include "clang/AST/Stmt.h"
37#include "clang/AST/Type.h"
38#include "clang/AST/TypeLoc.h"
44#include "clang/Basic/LLVM.h"
57#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Scope.h"
63#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaARM.h"
66#include "clang/Sema/SemaBPF.h"
67#include "clang/Sema/SemaHLSL.h"
71#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaPPC.h"
78#include "clang/Sema/SemaWasm.h"
79#include "clang/Sema/SemaX86.h"
80#include "llvm/ADT/APFloat.h"
81#include "llvm/ADT/APInt.h"
82#include "llvm/ADT/APSInt.h"
83#include "llvm/ADT/ArrayRef.h"
84#include "llvm/ADT/DenseMap.h"
85#include "llvm/ADT/FoldingSet.h"
86#include "llvm/ADT/STLExtras.h"
87#include "llvm/ADT/SmallBitVector.h"
88#include "llvm/ADT/SmallPtrSet.h"
89#include "llvm/ADT/SmallString.h"
90#include "llvm/ADT/SmallVector.h"
91#include "llvm/ADT/StringExtras.h"
92#include "llvm/ADT/StringRef.h"
93#include "llvm/ADT/StringSet.h"
94#include "llvm/ADT/StringSwitch.h"
95#include "llvm/Support/AtomicOrdering.h"
96#include "llvm/Support/Casting.h"
97#include "llvm/Support/Compiler.h"
98#include "llvm/Support/ConvertUTF.h"
99#include "llvm/Support/ErrorHandling.h"
100#include "llvm/Support/Format.h"
101#include "llvm/Support/Locale.h"
102#include "llvm/Support/MathExtras.h"
103#include "llvm/Support/SaveAndRestore.h"
104#include "llvm/Support/raw_ostream.h"
105#include "llvm/TargetParser/RISCVTargetParser.h"
106#include "llvm/TargetParser/Triple.h"
107#include <algorithm>
108#include <bitset>
109#include <cassert>
110#include <cctype>
111#include <cstddef>
112#include <cstdint>
113#include <functional>
114#include <limits>
115#include <optional>
116#include <string>
117#include <tuple>
118#include <utility>
119
120using namespace clang;
121using namespace sema;
122
124 unsigned ByteNo) const {
125 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
127}
128
129static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
131 return (A << 8) | B;
132}
133
134bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
135 unsigned ArgCount = Call->getNumArgs();
136 if (ArgCount >= MinArgCount)
137 return false;
138
139 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
140 << 0 /*function call*/ << MinArgCount << ArgCount
141 << /*is non object*/ 0 << Call->getSourceRange();
142}
143
144bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
145 unsigned ArgCount = Call->getNumArgs();
146 if (ArgCount <= MaxArgCount)
147 return false;
148 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
149 << 0 /*function call*/ << MaxArgCount << ArgCount
150 << /*is non object*/ 0 << Call->getSourceRange();
151}
152
153bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
154 unsigned MaxArgCount) {
155 return checkArgCountAtLeast(Call, MinArgCount) ||
156 checkArgCountAtMost(Call, MaxArgCount);
157}
158
159bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
160 unsigned ArgCount = Call->getNumArgs();
161 if (ArgCount == DesiredArgCount)
162 return false;
163
164 if (checkArgCountAtLeast(Call, DesiredArgCount))
165 return true;
166 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
167
168 // Highlight all the excess arguments.
169 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
170 Call->getArg(ArgCount - 1)->getEndLoc());
171
172 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
173 << 0 /*function call*/ << DesiredArgCount << ArgCount
174 << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
175}
176
178 bool HasError = false;
179
180 for (unsigned I = 0; I < Call->getNumArgs(); ++I) {
181 Expr *Arg = Call->getArg(I);
182
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
290 if (Arg.isInvalid())
291 return true;
292
293 TheCall->setArg(0, Arg.get());
294 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
296
297 if (!FD) {
298 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
299 << TheCall->getSourceRange();
300 return true;
301 }
302
303 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
304 TheCall->getBeginLoc());
305}
306
307/// Check the number of arguments and set the result type to
308/// the argument type.
309static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
310 if (S.checkArgCount(TheCall, 1))
311 return true;
312
313 TheCall->setType(TheCall->getArg(0)->getType());
314 return false;
315}
316
317/// Check that the value argument for __builtin_is_aligned(value, alignment) and
318/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
319/// type (but not a function pointer) and that the alignment is a power-of-two.
320static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
321 if (S.checkArgCount(TheCall, 2))
322 return true;
323
324 clang::Expr *Source = TheCall->getArg(0);
325 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
326
327 auto IsValidIntegerType = [](QualType Ty) {
328 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
329 };
330 QualType SrcTy = Source->getType();
331 // We should also be able to use it with arrays (but not functions!).
332 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
333 SrcTy = S.Context.getDecayedType(SrcTy);
334 }
335 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
336 SrcTy->isFunctionPointerType()) {
337 // FIXME: this is not quite the right error message since we don't allow
338 // floating point types, or member pointers.
339 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
340 << SrcTy;
341 return true;
342 }
343
344 clang::Expr *AlignOp = TheCall->getArg(1);
345 if (!IsValidIntegerType(AlignOp->getType())) {
346 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
347 << AlignOp->getType();
348 return true;
349 }
350 Expr::EvalResult AlignResult;
351 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
352 // We can't check validity of alignment if it is value dependent.
353 if (!AlignOp->isValueDependent() &&
354 AlignOp->EvaluateAsInt(AlignResult, S.Context,
356 llvm::APSInt AlignValue = AlignResult.Val.getInt();
357 llvm::APSInt MaxValue(
358 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
359 if (AlignValue < 1) {
360 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
361 return true;
362 }
363 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
364 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
365 << toString(MaxValue, 10);
366 return true;
367 }
368 if (!AlignValue.isPowerOf2()) {
369 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
370 return true;
371 }
372 if (AlignValue == 1) {
373 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
374 << IsBooleanAlignBuiltin;
375 }
376 }
377
380 SourceLocation(), Source);
381 if (SrcArg.isInvalid())
382 return true;
383 TheCall->setArg(0, SrcArg.get());
384 ExprResult AlignArg =
386 S.Context, AlignOp->getType(), false),
387 SourceLocation(), AlignOp);
388 if (AlignArg.isInvalid())
389 return true;
390 TheCall->setArg(1, AlignArg.get());
391 // For align_up/align_down, the return type is the same as the (potentially
392 // decayed) argument type including qualifiers. For is_aligned(), the result
393 // is always bool.
394 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
395 return false;
396}
397
398static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
399 if (S.checkArgCount(TheCall, 3))
400 return true;
401
402 std::pair<unsigned, const char *> Builtins[] = {
403 { Builtin::BI__builtin_add_overflow, "ckd_add" },
404 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
405 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
406 };
407
408 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
409 const char *> &P) {
410 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
412 S.getSourceManager(), S.getLangOpts()) == P.second;
413 });
414
415 auto ValidCkdIntType = [](QualType QT) {
416 // A valid checked integer type is an integer type other than a plain char,
417 // bool, a bit-precise type, or an enumeration type.
418 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
419 return (BT->getKind() >= BuiltinType::Short &&
420 BT->getKind() <= BuiltinType::Int128) || (
421 BT->getKind() >= BuiltinType::UShort &&
422 BT->getKind() <= BuiltinType::UInt128) ||
423 BT->getKind() == BuiltinType::UChar ||
424 BT->getKind() == BuiltinType::SChar;
425 return false;
426 };
427
428 // First two arguments should be integers.
429 for (unsigned I = 0; I < 2; ++I) {
431 if (Arg.isInvalid()) return true;
432 TheCall->setArg(I, Arg.get());
433
434 QualType Ty = Arg.get()->getType();
435 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
436 if (!IsValid) {
437 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
438 << CkdOperation << Ty << Arg.get()->getSourceRange();
439 return true;
440 }
441 }
442
443 // Third argument should be a pointer to a non-const integer.
444 // IRGen correctly handles volatile, restrict, and address spaces, and
445 // the other qualifiers aren't possible.
446 {
448 if (Arg.isInvalid()) return true;
449 TheCall->setArg(2, Arg.get());
450
451 QualType Ty = Arg.get()->getType();
452 const auto *PtrTy = Ty->getAs<PointerType>();
453 if (!PtrTy ||
454 !PtrTy->getPointeeType()->isIntegerType() ||
455 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
456 PtrTy->getPointeeType().isConstQualified()) {
457 S.Diag(Arg.get()->getBeginLoc(),
458 diag::err_overflow_builtin_must_be_ptr_int)
459 << CkdOperation << Ty << Arg.get()->getSourceRange();
460 return true;
461 }
462 }
463
464 // Disallow signed bit-precise integer args larger than 128 bits to mul
465 // function until we improve backend support.
466 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
467 for (unsigned I = 0; I < 3; ++I) {
468 const auto Arg = TheCall->getArg(I);
469 // Third argument will be a pointer.
470 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
471 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
472 S.getASTContext().getIntWidth(Ty) > 128)
473 return S.Diag(Arg->getBeginLoc(),
474 diag::err_overflow_builtin_bit_int_max_size)
475 << 128;
476 }
477 }
478
479 return false;
480}
481
482namespace {
483struct BuiltinDumpStructGenerator {
484 Sema &S;
485 CallExpr *TheCall;
486 SourceLocation Loc = TheCall->getBeginLoc();
488 DiagnosticErrorTrap ErrorTracker;
489 PrintingPolicy Policy;
490
491 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
492 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
493 Policy(S.Context.getPrintingPolicy()) {
494 Policy.AnonymousTagLocations = false;
495 }
496
497 Expr *makeOpaqueValueExpr(Expr *Inner) {
498 auto *OVE = new (S.Context)
499 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
500 Inner->getObjectKind(), Inner);
501 Actions.push_back(OVE);
502 return OVE;
503 }
504
505 Expr *getStringLiteral(llvm::StringRef Str) {
507 // Wrap the literal in parentheses to attach a source location.
508 return new (S.Context) ParenExpr(Loc, Loc, Lit);
509 }
510
511 bool callPrintFunction(llvm::StringRef Format,
512 llvm::ArrayRef<Expr *> Exprs = {}) {
514 assert(TheCall->getNumArgs() >= 2);
515 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
516 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
517 Args.push_back(getStringLiteral(Format));
518 Args.insert(Args.end(), Exprs.begin(), Exprs.end());
519
520 // Register a note to explain why we're performing the call.
524 Ctx.CallArgs = Args.data();
525 Ctx.NumCallArgs = Args.size();
527
528 ExprResult RealCall =
529 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
530 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
531
533 if (!RealCall.isInvalid())
534 Actions.push_back(RealCall.get());
535 // Bail out if we've hit any errors, even if we managed to build the
536 // call. We don't want to produce more than one error.
537 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
538 }
539
540 Expr *getIndentString(unsigned Depth) {
541 if (!Depth)
542 return nullptr;
543
545 Indent.resize(Depth * Policy.Indentation, ' ');
546 return getStringLiteral(Indent);
547 }
548
550 return getStringLiteral(T.getAsString(Policy));
551 }
552
553 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
554 llvm::raw_svector_ostream OS(Str);
555
556 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
557 // than trying to print a single character.
558 if (auto *BT = T->getAs<BuiltinType>()) {
559 switch (BT->getKind()) {
560 case BuiltinType::Bool:
561 OS << "%d";
562 return true;
563 case BuiltinType::Char_U:
564 case BuiltinType::UChar:
565 OS << "%hhu";
566 return true;
567 case BuiltinType::Char_S:
568 case BuiltinType::SChar:
569 OS << "%hhd";
570 return true;
571 default:
572 break;
573 }
574 }
575
577 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
578 // We were able to guess how to format this.
579 if (Specifier.getConversionSpecifier().getKind() ==
580 analyze_printf::PrintfConversionSpecifier::sArg) {
581 // Wrap double-quotes around a '%s' specifier and limit its maximum
582 // length. Ideally we'd also somehow escape special characters in the
583 // contents but printf doesn't support that.
584 // FIXME: '%s' formatting is not safe in general.
585 OS << '"';
586 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
587 Specifier.toString(OS);
588 OS << '"';
589 // FIXME: It would be nice to include a '...' if the string doesn't fit
590 // in the length limit.
591 } else {
592 Specifier.toString(OS);
593 }
594 return true;
595 }
596
597 if (T->isPointerType()) {
598 // Format all pointers with '%p'.
599 OS << "%p";
600 return true;
601 }
602
603 return false;
604 }
605
606 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
607 Expr *IndentLit = getIndentString(Depth);
608 Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
609 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
610 : callPrintFunction("%s", {TypeLit}))
611 return true;
612
613 return dumpRecordValue(RD, E, IndentLit, Depth);
614 }
615
616 // Dump a record value. E should be a pointer or lvalue referring to an RD.
617 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
618 unsigned Depth) {
619 // FIXME: Decide what to do if RD is a union. At least we should probably
620 // turn off printing `const char*` members with `%s`, because that is very
621 // likely to crash if that's not the active member. Whatever we decide, we
622 // should document it.
623
624 // Build an OpaqueValueExpr so we can refer to E more than once without
625 // triggering re-evaluation.
626 Expr *RecordArg = makeOpaqueValueExpr(E);
627 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
628
629 if (callPrintFunction(" {\n"))
630 return true;
631
632 // Dump each base class, regardless of whether they're aggregates.
633 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
634 for (const auto &Base : CXXRD->bases()) {
635 QualType BaseType =
636 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
637 : S.Context.getLValueReferenceType(Base.getType());
640 RecordArg);
641 if (BasePtr.isInvalid() ||
642 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
643 Depth + 1))
644 return true;
645 }
646 }
647
648 Expr *FieldIndentArg = getIndentString(Depth + 1);
649
650 // Dump each field.
651 for (auto *D : RD->decls()) {
652 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
653 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
654 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
655 continue;
656
657 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
658 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
659 getTypeString(FD->getType()),
660 getStringLiteral(FD->getName())};
661
662 if (FD->isBitField()) {
663 Format += ": %zu ";
665 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
666 FD->getBitWidthValue(S.Context));
667 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
668 }
669
670 Format += "=";
671
674 CXXScopeSpec(), Loc, IFD,
675 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
677 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
679 DeclarationNameInfo(FD->getDeclName(), Loc));
680 if (Field.isInvalid())
681 return true;
682
683 auto *InnerRD = FD->getType()->getAsRecordDecl();
684 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
685 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
686 // Recursively print the values of members of aggregate record type.
687 if (callPrintFunction(Format, Args) ||
688 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
689 return true;
690 } else {
691 Format += " ";
692 if (appendFormatSpecifier(FD->getType(), Format)) {
693 // We know how to print this field.
694 Args.push_back(Field.get());
695 } else {
696 // We don't know how to print this field. Print out its address
697 // with a format specifier that a smart tool will be able to
698 // recognize and treat specially.
699 Format += "*%p";
700 ExprResult FieldAddr =
701 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
702 if (FieldAddr.isInvalid())
703 return true;
704 Args.push_back(FieldAddr.get());
705 }
706 Format += "\n";
707 if (callPrintFunction(Format, Args))
708 return true;
709 }
710 }
711
712 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
713 : callPrintFunction("}\n");
714 }
715
716 Expr *buildWrapper() {
717 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
719 TheCall->setType(Wrapper->getType());
720 TheCall->setValueKind(Wrapper->getValueKind());
721 return Wrapper;
722 }
723};
724} // namespace
725
727 if (S.checkArgCountAtLeast(TheCall, 2))
728 return ExprError();
729
730 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
731 if (PtrArgResult.isInvalid())
732 return ExprError();
733 TheCall->setArg(0, PtrArgResult.get());
734
735 // First argument should be a pointer to a struct.
736 QualType PtrArgType = PtrArgResult.get()->getType();
737 if (!PtrArgType->isPointerType() ||
738 !PtrArgType->getPointeeType()->isRecordType()) {
739 S.Diag(PtrArgResult.get()->getBeginLoc(),
740 diag::err_expected_struct_pointer_argument)
741 << 1 << TheCall->getDirectCallee() << PtrArgType;
742 return ExprError();
743 }
744 QualType Pointee = PtrArgType->getPointeeType();
745 const RecordDecl *RD = Pointee->getAsRecordDecl();
746 // Try to instantiate the class template as appropriate; otherwise, access to
747 // its data() may lead to a crash.
748 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
749 diag::err_incomplete_type))
750 return ExprError();
751 // Second argument is a callable, but we can't fully validate it until we try
752 // calling it.
753 QualType FnArgType = TheCall->getArg(1)->getType();
754 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
755 !FnArgType->isBlockPointerType() &&
756 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
757 auto *BT = FnArgType->getAs<BuiltinType>();
758 switch (BT ? BT->getKind() : BuiltinType::Void) {
759 case BuiltinType::Dependent:
760 case BuiltinType::Overload:
761 case BuiltinType::BoundMember:
762 case BuiltinType::PseudoObject:
763 case BuiltinType::UnknownAny:
764 case BuiltinType::BuiltinFn:
765 // This might be a callable.
766 break;
767
768 default:
769 S.Diag(TheCall->getArg(1)->getBeginLoc(),
770 diag::err_expected_callable_argument)
771 << 2 << TheCall->getDirectCallee() << FnArgType;
772 return ExprError();
773 }
774 }
775
776 BuiltinDumpStructGenerator Generator(S, TheCall);
777
778 // Wrap parentheses around the given pointer. This is not necessary for
779 // correct code generation, but it means that when we pretty-print the call
780 // arguments in our diagnostics we will produce '(&s)->n' instead of the
781 // incorrect '&s->n'.
782 Expr *PtrArg = PtrArgResult.get();
783 PtrArg = new (S.Context)
784 ParenExpr(PtrArg->getBeginLoc(),
785 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
786 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
787 return ExprError();
788
789 return Generator.buildWrapper();
790}
791
792static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
793 if (S.checkArgCount(BuiltinCall, 2))
794 return true;
795
796 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
797 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
798 Expr *Call = BuiltinCall->getArg(0);
799 Expr *Chain = BuiltinCall->getArg(1);
800
801 if (Call->getStmtClass() != Stmt::CallExprClass) {
802 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
803 << Call->getSourceRange();
804 return true;
805 }
806
807 auto CE = cast<CallExpr>(Call);
808 if (CE->getCallee()->getType()->isBlockPointerType()) {
809 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
810 << Call->getSourceRange();
811 return true;
812 }
813
814 const Decl *TargetDecl = CE->getCalleeDecl();
815 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
816 if (FD->getBuiltinID()) {
817 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
818 << Call->getSourceRange();
819 return true;
820 }
821
822 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
823 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
824 << Call->getSourceRange();
825 return true;
826 }
827
828 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
829 if (ChainResult.isInvalid())
830 return true;
831 if (!ChainResult.get()->getType()->isPointerType()) {
832 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
833 << Chain->getSourceRange();
834 return true;
835 }
836
837 QualType ReturnTy = CE->getCallReturnType(S.Context);
838 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
839 QualType BuiltinTy = S.Context.getFunctionType(
840 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
841 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
842
843 Builtin =
844 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
845
846 BuiltinCall->setType(CE->getType());
847 BuiltinCall->setValueKind(CE->getValueKind());
848 BuiltinCall->setObjectKind(CE->getObjectKind());
849 BuiltinCall->setCallee(Builtin);
850 BuiltinCall->setArg(1, ChainResult.get());
851
852 return false;
853}
854
855namespace {
856
857class ScanfDiagnosticFormatHandler
859 // Accepts the argument index (relative to the first destination index) of the
860 // argument whose size we want.
861 using ComputeSizeFunction =
862 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
863
864 // Accepts the argument index (relative to the first destination index), the
865 // destination size, and the source size).
866 using DiagnoseFunction =
867 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
868
869 ComputeSizeFunction ComputeSizeArgument;
870 DiagnoseFunction Diagnose;
871
872public:
873 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
874 DiagnoseFunction Diagnose)
875 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
876
877 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
878 const char *StartSpecifier,
879 unsigned specifierLen) override {
880 if (!FS.consumesDataArgument())
881 return true;
882
883 unsigned NulByte = 0;
884 switch ((FS.getConversionSpecifier().getKind())) {
885 default:
886 return true;
889 NulByte = 1;
890 break;
892 break;
893 }
894
895 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
896 if (FW.getHowSpecified() !=
897 analyze_format_string::OptionalAmount::HowSpecified::Constant)
898 return true;
899
900 unsigned SourceSize = FW.getConstantAmount() + NulByte;
901
902 std::optional<llvm::APSInt> DestSizeAPS =
903 ComputeSizeArgument(FS.getArgIndex());
904 if (!DestSizeAPS)
905 return true;
906
907 unsigned DestSize = DestSizeAPS->getZExtValue();
908
909 if (DestSize < SourceSize)
910 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
911
912 return true;
913 }
914};
915
916class EstimateSizeFormatHandler
918 size_t Size;
919 /// Whether the format string contains Linux kernel's format specifier
920 /// extension.
921 bool IsKernelCompatible = true;
922
923public:
924 EstimateSizeFormatHandler(StringRef Format)
925 : Size(std::min(Format.find(0), Format.size()) +
926 1 /* null byte always written by sprintf */) {}
927
928 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
929 const char *, unsigned SpecifierLen,
930 const TargetInfo &) override {
931
932 const size_t FieldWidth = computeFieldWidth(FS);
933 const size_t Precision = computePrecision(FS);
934
935 // The actual format.
936 switch (FS.getConversionSpecifier().getKind()) {
937 // Just a char.
940 Size += std::max(FieldWidth, (size_t)1);
941 break;
942 // Just an integer.
952 Size += std::max(FieldWidth, Precision);
953 break;
954
955 // %g style conversion switches between %f or %e style dynamically.
956 // %g removes trailing zeros, and does not print decimal point if there are
957 // no digits that follow it. Thus %g can print a single digit.
958 // FIXME: If it is alternative form:
959 // For g and G conversions, trailing zeros are not removed from the result.
962 Size += 1;
963 break;
964
965 // Floating point number in the form '[+]ddd.ddd'.
968 Size += std::max(FieldWidth, 1 /* integer part */ +
969 (Precision ? 1 + Precision
970 : 0) /* period + decimal */);
971 break;
972
973 // Floating point number in the form '[-]d.ddde[+-]dd'.
976 Size +=
977 std::max(FieldWidth,
978 1 /* integer part */ +
979 (Precision ? 1 + Precision : 0) /* period + decimal */ +
980 1 /* e or E letter */ + 2 /* exponent */);
981 break;
982
983 // Floating point number in the form '[-]0xh.hhhhp±dd'.
986 Size +=
987 std::max(FieldWidth,
988 2 /* 0x */ + 1 /* integer part */ +
989 (Precision ? 1 + Precision : 0) /* period + decimal */ +
990 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
991 break;
992
993 // Just a string.
996 Size += FieldWidth;
997 break;
998
999 // Just a pointer in the form '0xddd'.
1001 // Linux kernel has its own extesion for `%p` specifier.
1002 // Kernel Document:
1003 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1004 IsKernelCompatible = false;
1005 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1006 break;
1007
1008 // A plain percent.
1010 Size += 1;
1011 break;
1012
1013 default:
1014 break;
1015 }
1016
1017 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
1018
1019 if (FS.hasAlternativeForm()) {
1020 switch (FS.getConversionSpecifier().getKind()) {
1021 // For o conversion, it increases the precision, if and only if necessary,
1022 // to force the first digit of the result to be a zero
1023 // (if the value and precision are both 0, a single 0 is printed)
1025 // For b conversion, a nonzero result has 0b prefixed to it.
1027 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1028 // it.
1031 // Note: even when the prefix is added, if
1032 // (prefix_width <= FieldWidth - formatted_length) holds,
1033 // the prefix does not increase the format
1034 // size. e.g.(("%#3x", 0xf) is "0xf")
1035
1036 // If the result is zero, o, b, x, X adds nothing.
1037 break;
1038 // For a, A, e, E, f, F, g, and G conversions,
1039 // the result of converting a floating-point number always contains a
1040 // decimal-point
1049 Size += (Precision ? 0 : 1);
1050 break;
1051 // For other conversions, the behavior is undefined.
1052 default:
1053 break;
1054 }
1055 }
1056 assert(SpecifierLen <= Size && "no underflow");
1057 Size -= SpecifierLen;
1058 return true;
1059 }
1060
1061 size_t getSizeLowerBound() const { return Size; }
1062 bool isKernelCompatible() const { return IsKernelCompatible; }
1063
1064private:
1065 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1066 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1067 size_t FieldWidth = 0;
1069 FieldWidth = FW.getConstantAmount();
1070 return FieldWidth;
1071 }
1072
1073 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1074 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1075 size_t Precision = 0;
1076
1077 // See man 3 printf for default precision value based on the specifier.
1078 switch (FW.getHowSpecified()) {
1080 switch (FS.getConversionSpecifier().getKind()) {
1081 default:
1082 break;
1086 Precision = 1;
1087 break;
1094 Precision = 1;
1095 break;
1102 Precision = 6;
1103 break;
1105 Precision = 1;
1106 break;
1107 }
1108 break;
1110 Precision = FW.getConstantAmount();
1111 break;
1112 default:
1113 break;
1114 }
1115 return Precision;
1116 }
1117};
1118
1119} // namespace
1120
1121static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1122 StringRef &FormatStrRef, size_t &StrLen,
1123 ASTContext &Context) {
1124 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1125 Format && (Format->isOrdinary() || Format->isUTF8())) {
1126 FormatStrRef = Format->getString();
1127 const ConstantArrayType *T =
1128 Context.getAsConstantArrayType(Format->getType());
1129 assert(T && "String literal not of constant array type!");
1130 size_t TypeSize = T->getZExtSize();
1131 // In case there's a null byte somewhere.
1132 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1133 return true;
1134 }
1135 return false;
1136}
1137
1138void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1139 CallExpr *TheCall) {
1140 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1142 return;
1143
1144 bool UseDABAttr = false;
1145 const FunctionDecl *UseDecl = FD;
1146
1147 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1148 if (DABAttr) {
1149 UseDecl = DABAttr->getFunction();
1150 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1151 UseDABAttr = true;
1152 }
1153
1154 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1155
1156 if (!BuiltinID)
1157 return;
1158
1159 const TargetInfo &TI = getASTContext().getTargetInfo();
1160 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1161
1162 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1163 // If we refer to a diagnose_as_builtin attribute, we need to change the
1164 // argument index to refer to the arguments of the called function. Unless
1165 // the index is out of bounds, which presumably means it's a variadic
1166 // function.
1167 if (!UseDABAttr)
1168 return Index;
1169 unsigned DABIndices = DABAttr->argIndices_size();
1170 unsigned NewIndex = Index < DABIndices
1171 ? DABAttr->argIndices_begin()[Index]
1172 : Index - DABIndices + FD->getNumParams();
1173 if (NewIndex >= TheCall->getNumArgs())
1174 return std::nullopt;
1175 return NewIndex;
1176 };
1177
1178 auto ComputeExplicitObjectSizeArgument =
1179 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1180 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1181 if (!IndexOptional)
1182 return std::nullopt;
1183 unsigned NewIndex = *IndexOptional;
1185 Expr *SizeArg = TheCall->getArg(NewIndex);
1186 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1187 return std::nullopt;
1188 llvm::APSInt Integer = Result.Val.getInt();
1189 Integer.setIsUnsigned(true);
1190 return Integer;
1191 };
1192
1193 auto ComputeSizeArgument =
1194 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1195 // If the parameter has a pass_object_size attribute, then we should use its
1196 // (potentially) more strict checking mode. Otherwise, conservatively assume
1197 // type 0.
1198 int BOSType = 0;
1199 // This check can fail for variadic functions.
1200 if (Index < FD->getNumParams()) {
1201 if (const auto *POS =
1202 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1203 BOSType = POS->getType();
1204 }
1205
1206 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1207 if (!IndexOptional)
1208 return std::nullopt;
1209 unsigned NewIndex = *IndexOptional;
1210
1211 if (NewIndex >= TheCall->getNumArgs())
1212 return std::nullopt;
1213
1214 const Expr *ObjArg = TheCall->getArg(NewIndex);
1216 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1217 return std::nullopt;
1218
1219 // Get the object size in the target's size_t width.
1220 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1221 };
1222
1223 auto ComputeStrLenArgument =
1224 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1225 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1226 if (!IndexOptional)
1227 return std::nullopt;
1228 unsigned NewIndex = *IndexOptional;
1229
1230 const Expr *ObjArg = TheCall->getArg(NewIndex);
1232 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1233 return std::nullopt;
1234 // Add 1 for null byte.
1235 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1236 };
1237
1238 std::optional<llvm::APSInt> SourceSize;
1239 std::optional<llvm::APSInt> DestinationSize;
1240 unsigned DiagID = 0;
1241 bool IsChkVariant = false;
1242
1243 auto GetFunctionName = [&]() {
1244 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1245 // Skim off the details of whichever builtin was called to produce a better
1246 // diagnostic, as it's unlikely that the user wrote the __builtin
1247 // explicitly.
1248 if (IsChkVariant) {
1249 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1250 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1251 } else {
1252 FunctionName.consume_front("__builtin_");
1253 }
1254 return FunctionName;
1255 };
1256
1257 switch (BuiltinID) {
1258 default:
1259 return;
1260 case Builtin::BI__builtin_strcpy:
1261 case Builtin::BIstrcpy: {
1262 DiagID = diag::warn_fortify_strlen_overflow;
1263 SourceSize = ComputeStrLenArgument(1);
1264 DestinationSize = ComputeSizeArgument(0);
1265 break;
1266 }
1267
1268 case Builtin::BI__builtin___strcpy_chk: {
1269 DiagID = diag::warn_fortify_strlen_overflow;
1270 SourceSize = ComputeStrLenArgument(1);
1271 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1272 IsChkVariant = true;
1273 break;
1274 }
1275
1276 case Builtin::BIscanf:
1277 case Builtin::BIfscanf:
1278 case Builtin::BIsscanf: {
1279 unsigned FormatIndex = 1;
1280 unsigned DataIndex = 2;
1281 if (BuiltinID == Builtin::BIscanf) {
1282 FormatIndex = 0;
1283 DataIndex = 1;
1284 }
1285
1286 const auto *FormatExpr =
1287 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1288
1289 StringRef FormatStrRef;
1290 size_t StrLen;
1291 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1292 return;
1293
1294 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1295 unsigned SourceSize) {
1296 DiagID = diag::warn_fortify_scanf_overflow;
1297 unsigned Index = ArgIndex + DataIndex;
1298 StringRef FunctionName = GetFunctionName();
1299 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1300 PDiag(DiagID) << FunctionName << (Index + 1)
1301 << DestSize << SourceSize);
1302 };
1303
1304 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1305 return ComputeSizeArgument(Index + DataIndex);
1306 };
1307 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1308 const char *FormatBytes = FormatStrRef.data();
1310 FormatBytes + StrLen, getLangOpts(),
1312
1313 // Unlike the other cases, in this one we have already issued the diagnostic
1314 // here, so no need to continue (because unlike the other cases, here the
1315 // diagnostic refers to the argument number).
1316 return;
1317 }
1318
1319 case Builtin::BIsprintf:
1320 case Builtin::BI__builtin___sprintf_chk: {
1321 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1322 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1323
1324 StringRef FormatStrRef;
1325 size_t StrLen;
1326 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1327 EstimateSizeFormatHandler H(FormatStrRef);
1328 const char *FormatBytes = FormatStrRef.data();
1330 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1331 Context.getTargetInfo(), false)) {
1332 DiagID = H.isKernelCompatible()
1333 ? diag::warn_format_overflow
1334 : diag::warn_format_overflow_non_kprintf;
1335 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1336 .extOrTrunc(SizeTypeWidth);
1337 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1338 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1339 IsChkVariant = true;
1340 } else {
1341 DestinationSize = ComputeSizeArgument(0);
1342 }
1343 break;
1344 }
1345 }
1346 return;
1347 }
1348 case Builtin::BI__builtin___memcpy_chk:
1349 case Builtin::BI__builtin___memmove_chk:
1350 case Builtin::BI__builtin___memset_chk:
1351 case Builtin::BI__builtin___strlcat_chk:
1352 case Builtin::BI__builtin___strlcpy_chk:
1353 case Builtin::BI__builtin___strncat_chk:
1354 case Builtin::BI__builtin___strncpy_chk:
1355 case Builtin::BI__builtin___stpncpy_chk:
1356 case Builtin::BI__builtin___memccpy_chk:
1357 case Builtin::BI__builtin___mempcpy_chk: {
1358 DiagID = diag::warn_builtin_chk_overflow;
1359 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1360 DestinationSize =
1361 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1362 IsChkVariant = true;
1363 break;
1364 }
1365
1366 case Builtin::BI__builtin___snprintf_chk:
1367 case Builtin::BI__builtin___vsnprintf_chk: {
1368 DiagID = diag::warn_builtin_chk_overflow;
1369 SourceSize = ComputeExplicitObjectSizeArgument(1);
1370 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1371 IsChkVariant = true;
1372 break;
1373 }
1374
1375 case Builtin::BIstrncat:
1376 case Builtin::BI__builtin_strncat:
1377 case Builtin::BIstrncpy:
1378 case Builtin::BI__builtin_strncpy:
1379 case Builtin::BIstpncpy:
1380 case Builtin::BI__builtin_stpncpy: {
1381 // Whether these functions overflow depends on the runtime strlen of the
1382 // string, not just the buffer size, so emitting the "always overflow"
1383 // diagnostic isn't quite right. We should still diagnose passing a buffer
1384 // size larger than the destination buffer though; this is a runtime abort
1385 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1386 DiagID = diag::warn_fortify_source_size_mismatch;
1387 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1388 DestinationSize = ComputeSizeArgument(0);
1389 break;
1390 }
1391
1392 case Builtin::BImemcpy:
1393 case Builtin::BI__builtin_memcpy:
1394 case Builtin::BImemmove:
1395 case Builtin::BI__builtin_memmove:
1396 case Builtin::BImemset:
1397 case Builtin::BI__builtin_memset:
1398 case Builtin::BImempcpy:
1399 case Builtin::BI__builtin_mempcpy: {
1400 DiagID = diag::warn_fortify_source_overflow;
1401 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1402 DestinationSize = ComputeSizeArgument(0);
1403 break;
1404 }
1405 case Builtin::BIsnprintf:
1406 case Builtin::BI__builtin_snprintf:
1407 case Builtin::BIvsnprintf:
1408 case Builtin::BI__builtin_vsnprintf: {
1409 DiagID = diag::warn_fortify_source_size_mismatch;
1410 SourceSize = ComputeExplicitObjectSizeArgument(1);
1411 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1412 StringRef FormatStrRef;
1413 size_t StrLen;
1414 if (SourceSize &&
1415 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1416 EstimateSizeFormatHandler H(FormatStrRef);
1417 const char *FormatBytes = FormatStrRef.data();
1419 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1420 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1421 llvm::APSInt FormatSize =
1422 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1423 .extOrTrunc(SizeTypeWidth);
1424 if (FormatSize > *SourceSize && *SourceSize != 0) {
1425 unsigned TruncationDiagID =
1426 H.isKernelCompatible() ? diag::warn_format_truncation
1427 : diag::warn_format_truncation_non_kprintf;
1428 SmallString<16> SpecifiedSizeStr;
1429 SmallString<16> FormatSizeStr;
1430 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1431 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1432 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1433 PDiag(TruncationDiagID)
1434 << GetFunctionName() << SpecifiedSizeStr
1435 << FormatSizeStr);
1436 }
1437 }
1438 }
1439 DestinationSize = ComputeSizeArgument(0);
1440 }
1441 }
1442
1443 if (!SourceSize || !DestinationSize ||
1444 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1445 return;
1446
1447 StringRef FunctionName = GetFunctionName();
1448
1449 SmallString<16> DestinationStr;
1450 SmallString<16> SourceStr;
1451 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1452 SourceSize->toString(SourceStr, /*Radix=*/10);
1453 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1454 PDiag(DiagID)
1455 << FunctionName << DestinationStr << SourceStr);
1456}
1457
1458static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1459 Scope::ScopeFlags NeededScopeFlags,
1460 unsigned DiagID) {
1461 // Scopes aren't available during instantiation. Fortunately, builtin
1462 // functions cannot be template args so they cannot be formed through template
1463 // instantiation. Therefore checking once during the parse is sufficient.
1464 if (SemaRef.inTemplateInstantiation())
1465 return false;
1466
1467 Scope *S = SemaRef.getCurScope();
1468 while (S && !S->isSEHExceptScope())
1469 S = S->getParent();
1470 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1471 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1472 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1473 << DRE->getDecl()->getIdentifier();
1474 return true;
1475 }
1476
1477 return false;
1478}
1479
1480// In OpenCL, __builtin_alloca_* should return a pointer to address space
1481// that corresponds to the stack address space i.e private address space.
1482static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1483 QualType RT = TheCall->getType();
1484 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1485 "__builtin_alloca has invalid address space");
1486
1487 RT = RT->getPointeeType();
1489 TheCall->setType(S.Context.getPointerType(RT));
1490}
1491
1492namespace {
1493enum PointerAuthOpKind {
1494 PAO_Strip,
1495 PAO_Sign,
1496 PAO_Auth,
1497 PAO_SignGeneric,
1498 PAO_Discriminator,
1499 PAO_BlendPointer,
1500 PAO_BlendInteger
1501};
1502}
1503
1505 if (getLangOpts().PointerAuthIntrinsics)
1506 return false;
1507
1508 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1509 return true;
1510}
1511
1514}
1515
1516static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1517 // Convert it to type 'int'.
1518 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1519 return true;
1520
1521 // Value-dependent expressions are okay; wait for template instantiation.
1522 if (Arg->isValueDependent())
1523 return false;
1524
1525 unsigned KeyValue;
1526 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1527}
1528
1530 // Attempt to constant-evaluate the expression.
1531 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1532 if (!KeyValue) {
1533 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1534 << 0 << Arg->getSourceRange();
1535 return true;
1536 }
1537
1538 // Ask the target to validate the key parameter.
1539 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1541 {
1542 llvm::raw_svector_ostream Str(Value);
1543 Str << *KeyValue;
1544 }
1545
1546 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1547 << Value << Arg->getSourceRange();
1548 return true;
1549 }
1550
1551 Result = KeyValue->getZExtValue();
1552 return false;
1553}
1554
1555static std::pair<const ValueDecl *, CharUnits>
1557 // Must evaluate as a pointer.
1559 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1560 return {nullptr, CharUnits()};
1561
1562 const auto *BaseDecl =
1563 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1564 if (!BaseDecl)
1565 return {nullptr, CharUnits()};
1566
1567 return {BaseDecl, Result.Val.getLValueOffset()};
1568}
1569
1570static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1571 bool RequireConstant = false) {
1572 if (Arg->hasPlaceholderType()) {
1574 if (R.isInvalid())
1575 return true;
1576 Arg = R.get();
1577 }
1578
1579 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1580 return OpKind != PAO_BlendInteger;
1581 };
1582 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1583 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1584 OpKind == PAO_SignGeneric;
1585 };
1586
1587 // Require the value to have the right range of type.
1588 QualType ExpectedTy;
1589 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1590 ExpectedTy = Arg->getType().getUnqualifiedType();
1591 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1592 ExpectedTy = S.Context.VoidPtrTy;
1593 } else if (AllowsInteger(OpKind) &&
1595 ExpectedTy = S.Context.getUIntPtrType();
1596
1597 } else {
1598 // Diagnose the failures.
1599 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1600 << unsigned(OpKind == PAO_Discriminator ? 1
1601 : OpKind == PAO_BlendPointer ? 2
1602 : OpKind == PAO_BlendInteger ? 3
1603 : 0)
1604 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1605 << Arg->getType() << Arg->getSourceRange();
1606 return true;
1607 }
1608
1609 // Convert to that type. This should just be an lvalue-to-rvalue
1610 // conversion.
1611 if (convertArgumentToType(S, Arg, ExpectedTy))
1612 return true;
1613
1614 if (!RequireConstant) {
1615 // Warn about null pointers for non-generic sign and auth operations.
1616 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1618 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1619 ? diag::warn_ptrauth_sign_null_pointer
1620 : diag::warn_ptrauth_auth_null_pointer)
1621 << Arg->getSourceRange();
1622 }
1623
1624 return false;
1625 }
1626
1627 // Perform special checking on the arguments to ptrauth_sign_constant.
1628
1629 // The main argument.
1630 if (OpKind == PAO_Sign) {
1631 // Require the value we're signing to have a special form.
1632 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1633 bool Invalid;
1634
1635 // Must be rooted in a declaration reference.
1636 if (!BaseDecl)
1637 Invalid = true;
1638
1639 // If it's a function declaration, we can't have an offset.
1640 else if (isa<FunctionDecl>(BaseDecl))
1641 Invalid = !Offset.isZero();
1642
1643 // Otherwise we're fine.
1644 else
1645 Invalid = false;
1646
1647 if (Invalid)
1648 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1649 return Invalid;
1650 }
1651
1652 // The discriminator argument.
1653 assert(OpKind == PAO_Discriminator);
1654
1655 // Must be a pointer or integer or blend thereof.
1656 Expr *Pointer = nullptr;
1657 Expr *Integer = nullptr;
1658 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1659 if (Call->getBuiltinCallee() ==
1660 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1661 Pointer = Call->getArg(0);
1662 Integer = Call->getArg(1);
1663 }
1664 }
1665 if (!Pointer && !Integer) {
1666 if (Arg->getType()->isPointerType())
1667 Pointer = Arg;
1668 else
1669 Integer = Arg;
1670 }
1671
1672 // Check the pointer.
1673 bool Invalid = false;
1674 if (Pointer) {
1675 assert(Pointer->getType()->isPointerType());
1676
1677 // TODO: if we're initializing a global, check that the address is
1678 // somehow related to what we're initializing. This probably will
1679 // never really be feasible and we'll have to catch it at link-time.
1680 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1681 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1682 Invalid = true;
1683 }
1684
1685 // Check the integer.
1686 if (Integer) {
1687 assert(Integer->getType()->isIntegerType());
1688 if (!Integer->isEvaluatable(S.Context))
1689 Invalid = true;
1690 }
1691
1692 if (Invalid)
1693 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1694 return Invalid;
1695}
1696
1698 if (S.checkArgCount(Call, 2))
1699 return ExprError();
1701 return ExprError();
1702 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1703 checkPointerAuthKey(S, Call->getArgs()[1]))
1704 return ExprError();
1705
1706 Call->setType(Call->getArgs()[0]->getType());
1707 return Call;
1708}
1709
1711 if (S.checkArgCount(Call, 2))
1712 return ExprError();
1714 return ExprError();
1715 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1716 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1717 return ExprError();
1718
1719 Call->setType(S.Context.getUIntPtrType());
1720 return Call;
1721}
1722
1724 if (S.checkArgCount(Call, 2))
1725 return ExprError();
1727 return ExprError();
1728 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1729 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1730 return ExprError();
1731
1732 Call->setType(S.Context.getUIntPtrType());
1733 return Call;
1734}
1735
1737 PointerAuthOpKind OpKind,
1738 bool RequireConstant) {
1739 if (S.checkArgCount(Call, 3))
1740 return ExprError();
1742 return ExprError();
1743 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1744 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1745 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1746 RequireConstant))
1747 return ExprError();
1748
1749 Call->setType(Call->getArgs()[0]->getType());
1750 return Call;
1751}
1752
1754 if (S.checkArgCount(Call, 5))
1755 return ExprError();
1757 return ExprError();
1758 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1759 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1760 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1761 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1762 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1763 return ExprError();
1764
1765 Call->setType(Call->getArgs()[0]->getType());
1766 return Call;
1767}
1768
1771 return ExprError();
1772
1773 // We've already performed normal call type-checking.
1774 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1775
1776 // Operand must be an ordinary or UTF-8 string literal.
1777 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1778 if (!Literal || Literal->getCharByteWidth() != 1) {
1779 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1780 << (Literal ? 1 : 0) << Arg->getSourceRange();
1781 return ExprError();
1782 }
1783
1784 return Call;
1785}
1786
1788 if (S.checkArgCount(TheCall, 1))
1789 return ExprError();
1790
1791 // Compute __builtin_launder's parameter type from the argument.
1792 // The parameter type is:
1793 // * The type of the argument if it's not an array or function type,
1794 // Otherwise,
1795 // * The decayed argument type.
1796 QualType ParamTy = [&]() {
1797 QualType ArgTy = TheCall->getArg(0)->getType();
1798 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1799 return S.Context.getPointerType(Ty->getElementType());
1800 if (ArgTy->isFunctionType()) {
1801 return S.Context.getPointerType(ArgTy);
1802 }
1803 return ArgTy;
1804 }();
1805
1806 TheCall->setType(ParamTy);
1807
1808 auto DiagSelect = [&]() -> std::optional<unsigned> {
1809 if (!ParamTy->isPointerType())
1810 return 0;
1811 if (ParamTy->isFunctionPointerType())
1812 return 1;
1813 if (ParamTy->isVoidPointerType())
1814 return 2;
1815 return std::optional<unsigned>{};
1816 }();
1817 if (DiagSelect) {
1818 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1819 << *DiagSelect << TheCall->getSourceRange();
1820 return ExprError();
1821 }
1822
1823 // We either have an incomplete class type, or we have a class template
1824 // whose instantiation has not been forced. Example:
1825 //
1826 // template <class T> struct Foo { T value; };
1827 // Foo<int> *p = nullptr;
1828 // auto *d = __builtin_launder(p);
1829 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1830 diag::err_incomplete_type))
1831 return ExprError();
1832
1833 assert(ParamTy->getPointeeType()->isObjectType() &&
1834 "Unhandled non-object pointer case");
1835
1836 InitializedEntity Entity =
1838 ExprResult Arg =
1839 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1840 if (Arg.isInvalid())
1841 return ExprError();
1842 TheCall->setArg(0, Arg.get());
1843
1844 return TheCall;
1845}
1846
1847// Emit an error and return true if the current object format type is in the
1848// list of unsupported types.
1850 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1851 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
1852 llvm::Triple::ObjectFormatType CurObjFormat =
1853 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
1854 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
1855 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1856 << TheCall->getSourceRange();
1857 return true;
1858 }
1859 return false;
1860}
1861
1862// Emit an error and return true if the current architecture is not in the list
1863// of supported architectures.
1864static bool
1866 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1867 llvm::Triple::ArchType CurArch =
1868 S.getASTContext().getTargetInfo().getTriple().getArch();
1869 if (llvm::is_contained(SupportedArchs, CurArch))
1870 return false;
1871 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1872 << TheCall->getSourceRange();
1873 return true;
1874}
1875
1876static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1877 SourceLocation CallSiteLoc);
1878
1879bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1880 CallExpr *TheCall) {
1881 switch (TI.getTriple().getArch()) {
1882 default:
1883 // Some builtins don't require additional checking, so just consider these
1884 // acceptable.
1885 return false;
1886 case llvm::Triple::arm:
1887 case llvm::Triple::armeb:
1888 case llvm::Triple::thumb:
1889 case llvm::Triple::thumbeb:
1890 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1891 case llvm::Triple::aarch64:
1892 case llvm::Triple::aarch64_32:
1893 case llvm::Triple::aarch64_be:
1894 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1895 case llvm::Triple::bpfeb:
1896 case llvm::Triple::bpfel:
1897 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1898 case llvm::Triple::hexagon:
1899 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1900 case llvm::Triple::mips:
1901 case llvm::Triple::mipsel:
1902 case llvm::Triple::mips64:
1903 case llvm::Triple::mips64el:
1904 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1905 case llvm::Triple::systemz:
1906 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1907 case llvm::Triple::x86:
1908 case llvm::Triple::x86_64:
1909 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
1910 case llvm::Triple::ppc:
1911 case llvm::Triple::ppcle:
1912 case llvm::Triple::ppc64:
1913 case llvm::Triple::ppc64le:
1914 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1915 case llvm::Triple::amdgcn:
1916 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1917 case llvm::Triple::riscv32:
1918 case llvm::Triple::riscv64:
1919 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
1920 case llvm::Triple::loongarch32:
1921 case llvm::Triple::loongarch64:
1922 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
1923 TheCall);
1924 case llvm::Triple::wasm32:
1925 case llvm::Triple::wasm64:
1926 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
1927 case llvm::Triple::nvptx:
1928 case llvm::Triple::nvptx64:
1929 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
1930 }
1931}
1932
1933// Check if \p Ty is a valid type for the elementwise math builtins. If it is
1934// not a valid type, emit an error message and return true. Otherwise return
1935// false.
1937 QualType ArgTy, int ArgIndex) {
1938 if (!ArgTy->getAs<VectorType>() &&
1940 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
1941 << ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy;
1942 }
1943
1944 return false;
1945}
1946
1948 QualType ArgTy, int ArgIndex) {
1949 QualType EltTy = ArgTy;
1950 if (auto *VecTy = EltTy->getAs<VectorType>())
1951 EltTy = VecTy->getElementType();
1952
1953 if (!EltTy->isRealFloatingType()) {
1954 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
1955 << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
1956 }
1957
1958 return false;
1959}
1960
1961/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
1962/// This checks that the target supports the builtin and that the string
1963/// argument is constant and valid.
1964static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
1965 const TargetInfo *AuxTI, unsigned BuiltinID) {
1966 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
1967 BuiltinID == Builtin::BI__builtin_cpu_is) &&
1968 "Expecting __builtin_cpu_...");
1969
1970 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
1971 const TargetInfo *TheTI = &TI;
1972 auto SupportsBI = [=](const TargetInfo *TInfo) {
1973 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
1974 (!IsCPUSupports && TInfo->supportsCpuIs()));
1975 };
1976 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
1977 TheTI = AuxTI;
1978
1979 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
1980 (IsCPUSupports && !TheTI->supportsCpuSupports()))
1981 return S.Diag(TheCall->getBeginLoc(),
1982 TI.getTriple().isOSAIX()
1983 ? diag::err_builtin_aix_os_unsupported
1984 : diag::err_builtin_target_unsupported)
1985 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
1986
1987 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
1988 // Check if the argument is a string literal.
1989 if (!isa<StringLiteral>(Arg))
1990 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
1991 << Arg->getSourceRange();
1992
1993 // Check the contents of the string.
1994 StringRef Feature = cast<StringLiteral>(Arg)->getString();
1995 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
1996 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
1997 << Arg->getSourceRange();
1998 return false;
1999 }
2000 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2001 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2002 << Arg->getSourceRange();
2003 return false;
2004}
2005
2006/// Checks that __builtin_popcountg was called with a single argument, which is
2007/// an unsigned integer.
2008static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2009 if (S.checkArgCount(TheCall, 1))
2010 return true;
2011
2012 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2013 if (ArgRes.isInvalid())
2014 return true;
2015
2016 Expr *Arg = ArgRes.get();
2017 TheCall->setArg(0, Arg);
2018
2019 QualType ArgTy = Arg->getType();
2020
2021 if (!ArgTy->isUnsignedIntegerType()) {
2022 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2023 << 1 << /*unsigned integer ty*/ 7 << ArgTy;
2024 return true;
2025 }
2026 return false;
2027}
2028
2029/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2030/// an unsigned integer, and an optional second argument, which is promoted to
2031/// an 'int'.
2032static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2033 if (S.checkArgCountRange(TheCall, 1, 2))
2034 return true;
2035
2036 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2037 if (Arg0Res.isInvalid())
2038 return true;
2039
2040 Expr *Arg0 = Arg0Res.get();
2041 TheCall->setArg(0, Arg0);
2042
2043 QualType Arg0Ty = Arg0->getType();
2044
2045 if (!Arg0Ty->isUnsignedIntegerType()) {
2046 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2047 << 1 << /*unsigned integer ty*/ 7 << Arg0Ty;
2048 return true;
2049 }
2050
2051 if (TheCall->getNumArgs() > 1) {
2052 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2053 if (Arg1Res.isInvalid())
2054 return true;
2055
2056 Expr *Arg1 = Arg1Res.get();
2057 TheCall->setArg(1, Arg1);
2058
2059 QualType Arg1Ty = Arg1->getType();
2060
2061 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2062 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2063 << 2 << /*'int' ty*/ 8 << Arg1Ty;
2064 return true;
2065 }
2066 }
2067
2068 return false;
2069}
2070
2072Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2073 CallExpr *TheCall) {
2074 ExprResult TheCallResult(TheCall);
2075
2076 // Find out if any arguments are required to be integer constant expressions.
2077 unsigned ICEArguments = 0;
2079 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2080 if (Error != ASTContext::GE_None)
2081 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2082
2083 // If any arguments are required to be ICE's, check and diagnose.
2084 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2085 // Skip arguments not required to be ICE's.
2086 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2087
2088 llvm::APSInt Result;
2089 // If we don't have enough arguments, continue so we can issue better
2090 // diagnostic in checkArgCount(...)
2091 if (ArgNo < TheCall->getNumArgs() &&
2092 BuiltinConstantArg(TheCall, ArgNo, Result))
2093 return true;
2094 ICEArguments &= ~(1 << ArgNo);
2095 }
2096
2097 FPOptions FPO;
2098 switch (BuiltinID) {
2099 case Builtin::BI__builtin_cpu_supports:
2100 case Builtin::BI__builtin_cpu_is:
2101 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2102 Context.getAuxTargetInfo(), BuiltinID))
2103 return ExprError();
2104 break;
2105 case Builtin::BI__builtin_cpu_init:
2107 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2108 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2109 return ExprError();
2110 }
2111 break;
2112 case Builtin::BI__builtin___CFStringMakeConstantString:
2113 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2114 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2116 *this, BuiltinID, TheCall,
2117 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2118 return ExprError();
2119 assert(TheCall->getNumArgs() == 1 &&
2120 "Wrong # arguments to builtin CFStringMakeConstantString");
2121 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2122 return ExprError();
2123 break;
2124 case Builtin::BI__builtin_ms_va_start:
2125 case Builtin::BI__builtin_stdarg_start:
2126 case Builtin::BI__builtin_va_start:
2127 if (BuiltinVAStart(BuiltinID, TheCall))
2128 return ExprError();
2129 break;
2130 case Builtin::BI__va_start: {
2131 switch (Context.getTargetInfo().getTriple().getArch()) {
2132 case llvm::Triple::aarch64:
2133 case llvm::Triple::arm:
2134 case llvm::Triple::thumb:
2135 if (BuiltinVAStartARMMicrosoft(TheCall))
2136 return ExprError();
2137 break;
2138 default:
2139 if (BuiltinVAStart(BuiltinID, TheCall))
2140 return ExprError();
2141 break;
2142 }
2143 break;
2144 }
2145
2146 // The acquire, release, and no fence variants are ARM and AArch64 only.
2147 case Builtin::BI_interlockedbittestandset_acq:
2148 case Builtin::BI_interlockedbittestandset_rel:
2149 case Builtin::BI_interlockedbittestandset_nf:
2150 case Builtin::BI_interlockedbittestandreset_acq:
2151 case Builtin::BI_interlockedbittestandreset_rel:
2152 case Builtin::BI_interlockedbittestandreset_nf:
2154 *this, TheCall,
2155 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2156 return ExprError();
2157 break;
2158
2159 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2160 case Builtin::BI_bittest64:
2161 case Builtin::BI_bittestandcomplement64:
2162 case Builtin::BI_bittestandreset64:
2163 case Builtin::BI_bittestandset64:
2164 case Builtin::BI_interlockedbittestandreset64:
2165 case Builtin::BI_interlockedbittestandset64:
2167 *this, TheCall,
2168 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2169 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2170 return ExprError();
2171 break;
2172
2173 case Builtin::BI__builtin_set_flt_rounds:
2175 *this, TheCall,
2176 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2177 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2178 return ExprError();
2179 break;
2180
2181 case Builtin::BI__builtin_isgreater:
2182 case Builtin::BI__builtin_isgreaterequal:
2183 case Builtin::BI__builtin_isless:
2184 case Builtin::BI__builtin_islessequal:
2185 case Builtin::BI__builtin_islessgreater:
2186 case Builtin::BI__builtin_isunordered:
2187 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2188 return ExprError();
2189 break;
2190 case Builtin::BI__builtin_fpclassify:
2191 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2192 return ExprError();
2193 break;
2194 case Builtin::BI__builtin_isfpclass:
2195 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2196 return ExprError();
2197 break;
2198 case Builtin::BI__builtin_isfinite:
2199 case Builtin::BI__builtin_isinf:
2200 case Builtin::BI__builtin_isinf_sign:
2201 case Builtin::BI__builtin_isnan:
2202 case Builtin::BI__builtin_issignaling:
2203 case Builtin::BI__builtin_isnormal:
2204 case Builtin::BI__builtin_issubnormal:
2205 case Builtin::BI__builtin_iszero:
2206 case Builtin::BI__builtin_signbit:
2207 case Builtin::BI__builtin_signbitf:
2208 case Builtin::BI__builtin_signbitl:
2209 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2210 return ExprError();
2211 break;
2212 case Builtin::BI__builtin_shufflevector:
2213 return BuiltinShuffleVector(TheCall);
2214 // TheCall will be freed by the smart pointer here, but that's fine, since
2215 // BuiltinShuffleVector guts it, but then doesn't release it.
2216 case Builtin::BI__builtin_prefetch:
2217 if (BuiltinPrefetch(TheCall))
2218 return ExprError();
2219 break;
2220 case Builtin::BI__builtin_alloca_with_align:
2221 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2222 if (BuiltinAllocaWithAlign(TheCall))
2223 return ExprError();
2224 [[fallthrough]];
2225 case Builtin::BI__builtin_alloca:
2226 case Builtin::BI__builtin_alloca_uninitialized:
2227 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2228 << TheCall->getDirectCallee();
2229 if (getLangOpts().OpenCL) {
2230 builtinAllocaAddrSpace(*this, TheCall);
2231 }
2232 break;
2233 case Builtin::BI__arithmetic_fence:
2234 if (BuiltinArithmeticFence(TheCall))
2235 return ExprError();
2236 break;
2237 case Builtin::BI__assume:
2238 case Builtin::BI__builtin_assume:
2239 if (BuiltinAssume(TheCall))
2240 return ExprError();
2241 break;
2242 case Builtin::BI__builtin_assume_aligned:
2243 if (BuiltinAssumeAligned(TheCall))
2244 return ExprError();
2245 break;
2246 case Builtin::BI__builtin_dynamic_object_size:
2247 case Builtin::BI__builtin_object_size:
2248 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2249 return ExprError();
2250 break;
2251 case Builtin::BI__builtin_longjmp:
2252 if (BuiltinLongjmp(TheCall))
2253 return ExprError();
2254 break;
2255 case Builtin::BI__builtin_setjmp:
2256 if (BuiltinSetjmp(TheCall))
2257 return ExprError();
2258 break;
2259 case Builtin::BI__builtin_classify_type:
2260 if (checkArgCount(TheCall, 1))
2261 return true;
2262 TheCall->setType(Context.IntTy);
2263 break;
2264 case Builtin::BI__builtin_complex:
2265 if (BuiltinComplex(TheCall))
2266 return ExprError();
2267 break;
2268 case Builtin::BI__builtin_constant_p: {
2269 if (checkArgCount(TheCall, 1))
2270 return true;
2272 if (Arg.isInvalid()) return true;
2273 TheCall->setArg(0, Arg.get());
2274 TheCall->setType(Context.IntTy);
2275 break;
2276 }
2277 case Builtin::BI__builtin_launder:
2278 return BuiltinLaunder(*this, TheCall);
2279 case Builtin::BI__sync_fetch_and_add:
2280 case Builtin::BI__sync_fetch_and_add_1:
2281 case Builtin::BI__sync_fetch_and_add_2:
2282 case Builtin::BI__sync_fetch_and_add_4:
2283 case Builtin::BI__sync_fetch_and_add_8:
2284 case Builtin::BI__sync_fetch_and_add_16:
2285 case Builtin::BI__sync_fetch_and_sub:
2286 case Builtin::BI__sync_fetch_and_sub_1:
2287 case Builtin::BI__sync_fetch_and_sub_2:
2288 case Builtin::BI__sync_fetch_and_sub_4:
2289 case Builtin::BI__sync_fetch_and_sub_8:
2290 case Builtin::BI__sync_fetch_and_sub_16:
2291 case Builtin::BI__sync_fetch_and_or:
2292 case Builtin::BI__sync_fetch_and_or_1:
2293 case Builtin::BI__sync_fetch_and_or_2:
2294 case Builtin::BI__sync_fetch_and_or_4:
2295 case Builtin::BI__sync_fetch_and_or_8:
2296 case Builtin::BI__sync_fetch_and_or_16:
2297 case Builtin::BI__sync_fetch_and_and:
2298 case Builtin::BI__sync_fetch_and_and_1:
2299 case Builtin::BI__sync_fetch_and_and_2:
2300 case Builtin::BI__sync_fetch_and_and_4:
2301 case Builtin::BI__sync_fetch_and_and_8:
2302 case Builtin::BI__sync_fetch_and_and_16:
2303 case Builtin::BI__sync_fetch_and_xor:
2304 case Builtin::BI__sync_fetch_and_xor_1:
2305 case Builtin::BI__sync_fetch_and_xor_2:
2306 case Builtin::BI__sync_fetch_and_xor_4:
2307 case Builtin::BI__sync_fetch_and_xor_8:
2308 case Builtin::BI__sync_fetch_and_xor_16:
2309 case Builtin::BI__sync_fetch_and_nand:
2310 case Builtin::BI__sync_fetch_and_nand_1:
2311 case Builtin::BI__sync_fetch_and_nand_2:
2312 case Builtin::BI__sync_fetch_and_nand_4:
2313 case Builtin::BI__sync_fetch_and_nand_8:
2314 case Builtin::BI__sync_fetch_and_nand_16:
2315 case Builtin::BI__sync_add_and_fetch:
2316 case Builtin::BI__sync_add_and_fetch_1:
2317 case Builtin::BI__sync_add_and_fetch_2:
2318 case Builtin::BI__sync_add_and_fetch_4:
2319 case Builtin::BI__sync_add_and_fetch_8:
2320 case Builtin::BI__sync_add_and_fetch_16:
2321 case Builtin::BI__sync_sub_and_fetch:
2322 case Builtin::BI__sync_sub_and_fetch_1:
2323 case Builtin::BI__sync_sub_and_fetch_2:
2324 case Builtin::BI__sync_sub_and_fetch_4:
2325 case Builtin::BI__sync_sub_and_fetch_8:
2326 case Builtin::BI__sync_sub_and_fetch_16:
2327 case Builtin::BI__sync_and_and_fetch:
2328 case Builtin::BI__sync_and_and_fetch_1:
2329 case Builtin::BI__sync_and_and_fetch_2:
2330 case Builtin::BI__sync_and_and_fetch_4:
2331 case Builtin::BI__sync_and_and_fetch_8:
2332 case Builtin::BI__sync_and_and_fetch_16:
2333 case Builtin::BI__sync_or_and_fetch:
2334 case Builtin::BI__sync_or_and_fetch_1:
2335 case Builtin::BI__sync_or_and_fetch_2:
2336 case Builtin::BI__sync_or_and_fetch_4:
2337 case Builtin::BI__sync_or_and_fetch_8:
2338 case Builtin::BI__sync_or_and_fetch_16:
2339 case Builtin::BI__sync_xor_and_fetch:
2340 case Builtin::BI__sync_xor_and_fetch_1:
2341 case Builtin::BI__sync_xor_and_fetch_2:
2342 case Builtin::BI__sync_xor_and_fetch_4:
2343 case Builtin::BI__sync_xor_and_fetch_8:
2344 case Builtin::BI__sync_xor_and_fetch_16:
2345 case Builtin::BI__sync_nand_and_fetch:
2346 case Builtin::BI__sync_nand_and_fetch_1:
2347 case Builtin::BI__sync_nand_and_fetch_2:
2348 case Builtin::BI__sync_nand_and_fetch_4:
2349 case Builtin::BI__sync_nand_and_fetch_8:
2350 case Builtin::BI__sync_nand_and_fetch_16:
2351 case Builtin::BI__sync_val_compare_and_swap:
2352 case Builtin::BI__sync_val_compare_and_swap_1:
2353 case Builtin::BI__sync_val_compare_and_swap_2:
2354 case Builtin::BI__sync_val_compare_and_swap_4:
2355 case Builtin::BI__sync_val_compare_and_swap_8:
2356 case Builtin::BI__sync_val_compare_and_swap_16:
2357 case Builtin::BI__sync_bool_compare_and_swap:
2358 case Builtin::BI__sync_bool_compare_and_swap_1:
2359 case Builtin::BI__sync_bool_compare_and_swap_2:
2360 case Builtin::BI__sync_bool_compare_and_swap_4:
2361 case Builtin::BI__sync_bool_compare_and_swap_8:
2362 case Builtin::BI__sync_bool_compare_and_swap_16:
2363 case Builtin::BI__sync_lock_test_and_set:
2364 case Builtin::BI__sync_lock_test_and_set_1:
2365 case Builtin::BI__sync_lock_test_and_set_2:
2366 case Builtin::BI__sync_lock_test_and_set_4:
2367 case Builtin::BI__sync_lock_test_and_set_8:
2368 case Builtin::BI__sync_lock_test_and_set_16:
2369 case Builtin::BI__sync_lock_release:
2370 case Builtin::BI__sync_lock_release_1:
2371 case Builtin::BI__sync_lock_release_2:
2372 case Builtin::BI__sync_lock_release_4:
2373 case Builtin::BI__sync_lock_release_8:
2374 case Builtin::BI__sync_lock_release_16:
2375 case Builtin::BI__sync_swap:
2376 case Builtin::BI__sync_swap_1:
2377 case Builtin::BI__sync_swap_2:
2378 case Builtin::BI__sync_swap_4:
2379 case Builtin::BI__sync_swap_8:
2380 case Builtin::BI__sync_swap_16:
2381 return BuiltinAtomicOverloaded(TheCallResult);
2382 case Builtin::BI__sync_synchronize:
2383 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2384 << TheCall->getCallee()->getSourceRange();
2385 break;
2386 case Builtin::BI__builtin_nontemporal_load:
2387 case Builtin::BI__builtin_nontemporal_store:
2388 return BuiltinNontemporalOverloaded(TheCallResult);
2389 case Builtin::BI__builtin_memcpy_inline: {
2390 clang::Expr *SizeOp = TheCall->getArg(2);
2391 // We warn about copying to or from `nullptr` pointers when `size` is
2392 // greater than 0. When `size` is value dependent we cannot evaluate its
2393 // value so we bail out.
2394 if (SizeOp->isValueDependent())
2395 break;
2396 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2397 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2398 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2399 }
2400 break;
2401 }
2402 case Builtin::BI__builtin_memset_inline: {
2403 clang::Expr *SizeOp = TheCall->getArg(2);
2404 // We warn about filling to `nullptr` pointers when `size` is greater than
2405 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2406 // out.
2407 if (SizeOp->isValueDependent())
2408 break;
2409 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2410 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2411 break;
2412 }
2413#define BUILTIN(ID, TYPE, ATTRS)
2414#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2415 case Builtin::BI##ID: \
2416 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2417#include "clang/Basic/Builtins.inc"
2418 case Builtin::BI__annotation:
2419 if (BuiltinMSVCAnnotation(*this, TheCall))
2420 return ExprError();
2421 break;
2422 case Builtin::BI__builtin_annotation:
2423 if (BuiltinAnnotation(*this, TheCall))
2424 return ExprError();
2425 break;
2426 case Builtin::BI__builtin_addressof:
2427 if (BuiltinAddressof(*this, TheCall))
2428 return ExprError();
2429 break;
2430 case Builtin::BI__builtin_function_start:
2431 if (BuiltinFunctionStart(*this, TheCall))
2432 return ExprError();
2433 break;
2434 case Builtin::BI__builtin_is_aligned:
2435 case Builtin::BI__builtin_align_up:
2436 case Builtin::BI__builtin_align_down:
2437 if (BuiltinAlignment(*this, TheCall, BuiltinID))
2438 return ExprError();
2439 break;
2440 case Builtin::BI__builtin_add_overflow:
2441 case Builtin::BI__builtin_sub_overflow:
2442 case Builtin::BI__builtin_mul_overflow:
2443 if (BuiltinOverflow(*this, TheCall, BuiltinID))
2444 return ExprError();
2445 break;
2446 case Builtin::BI__builtin_operator_new:
2447 case Builtin::BI__builtin_operator_delete: {
2448 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2449 ExprResult Res =
2450 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2451 if (Res.isInvalid())
2452 CorrectDelayedTyposInExpr(TheCallResult.get());
2453 return Res;
2454 }
2455 case Builtin::BI__builtin_dump_struct:
2456 return BuiltinDumpStruct(*this, TheCall);
2457 case Builtin::BI__builtin_expect_with_probability: {
2458 // We first want to ensure we are called with 3 arguments
2459 if (checkArgCount(TheCall, 3))
2460 return ExprError();
2461 // then check probability is constant float in range [0.0, 1.0]
2462 const Expr *ProbArg = TheCall->getArg(2);
2464 Expr::EvalResult Eval;
2465 Eval.Diag = &Notes;
2466 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2467 !Eval.Val.isFloat()) {
2468 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2469 << ProbArg->getSourceRange();
2470 for (const PartialDiagnosticAt &PDiag : Notes)
2471 Diag(PDiag.first, PDiag.second);
2472 return ExprError();
2473 }
2474 llvm::APFloat Probability = Eval.Val.getFloat();
2475 bool LoseInfo = false;
2476 Probability.convert(llvm::APFloat::IEEEdouble(),
2477 llvm::RoundingMode::Dynamic, &LoseInfo);
2478 if (!(Probability >= llvm::APFloat(0.0) &&
2479 Probability <= llvm::APFloat(1.0))) {
2480 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2481 << ProbArg->getSourceRange();
2482 return ExprError();
2483 }
2484 break;
2485 }
2486 case Builtin::BI__builtin_preserve_access_index:
2487 if (BuiltinPreserveAI(*this, TheCall))
2488 return ExprError();
2489 break;
2490 case Builtin::BI__builtin_call_with_static_chain:
2491 if (BuiltinCallWithStaticChain(*this, TheCall))
2492 return ExprError();
2493 break;
2494 case Builtin::BI__exception_code:
2495 case Builtin::BI_exception_code:
2496 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2497 diag::err_seh___except_block))
2498 return ExprError();
2499 break;
2500 case Builtin::BI__exception_info:
2501 case Builtin::BI_exception_info:
2502 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2503 diag::err_seh___except_filter))
2504 return ExprError();
2505 break;
2506 case Builtin::BI__GetExceptionInfo:
2507 if (checkArgCount(TheCall, 1))
2508 return ExprError();
2509
2511 TheCall->getBeginLoc(),
2513 TheCall))
2514 return ExprError();
2515
2516 TheCall->setType(Context.VoidPtrTy);
2517 break;
2518 case Builtin::BIaddressof:
2519 case Builtin::BI__addressof:
2520 case Builtin::BIforward:
2521 case Builtin::BIforward_like:
2522 case Builtin::BImove:
2523 case Builtin::BImove_if_noexcept:
2524 case Builtin::BIas_const: {
2525 // These are all expected to be of the form
2526 // T &/&&/* f(U &/&&)
2527 // where T and U only differ in qualification.
2528 if (checkArgCount(TheCall, 1))
2529 return ExprError();
2530 QualType Param = FDecl->getParamDecl(0)->getType();
2531 QualType Result = FDecl->getReturnType();
2532 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2533 BuiltinID == Builtin::BI__addressof;
2534 if (!(Param->isReferenceType() &&
2535 (ReturnsPointer ? Result->isAnyPointerType()
2536 : Result->isReferenceType()) &&
2538 Result->getPointeeType()))) {
2539 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2540 << FDecl;
2541 return ExprError();
2542 }
2543 break;
2544 }
2545 case Builtin::BI__builtin_ptrauth_strip:
2546 return PointerAuthStrip(*this, TheCall);
2547 case Builtin::BI__builtin_ptrauth_blend_discriminator:
2548 return PointerAuthBlendDiscriminator(*this, TheCall);
2549 case Builtin::BI__builtin_ptrauth_sign_constant:
2550 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2551 /*RequireConstant=*/true);
2552 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
2553 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
2554 /*RequireConstant=*/false);
2555 case Builtin::BI__builtin_ptrauth_auth:
2556 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
2557 /*RequireConstant=*/false);
2558 case Builtin::BI__builtin_ptrauth_sign_generic_data:
2559 return PointerAuthSignGenericData(*this, TheCall);
2560 case Builtin::BI__builtin_ptrauth_auth_and_resign:
2561 return PointerAuthAuthAndResign(*this, TheCall);
2562 case Builtin::BI__builtin_ptrauth_string_discriminator:
2563 return PointerAuthStringDiscriminator(*this, TheCall);
2564 // OpenCL v2.0, s6.13.16 - Pipe functions
2565 case Builtin::BIread_pipe:
2566 case Builtin::BIwrite_pipe:
2567 // Since those two functions are declared with var args, we need a semantic
2568 // check for the argument.
2569 if (OpenCL().checkBuiltinRWPipe(TheCall))
2570 return ExprError();
2571 break;
2572 case Builtin::BIreserve_read_pipe:
2573 case Builtin::BIreserve_write_pipe:
2574 case Builtin::BIwork_group_reserve_read_pipe:
2575 case Builtin::BIwork_group_reserve_write_pipe:
2576 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
2577 return ExprError();
2578 break;
2579 case Builtin::BIsub_group_reserve_read_pipe:
2580 case Builtin::BIsub_group_reserve_write_pipe:
2581 if (OpenCL().checkSubgroupExt(TheCall) ||
2582 OpenCL().checkBuiltinReserveRWPipe(TheCall))
2583 return ExprError();
2584 break;
2585 case Builtin::BIcommit_read_pipe:
2586 case Builtin::BIcommit_write_pipe:
2587 case Builtin::BIwork_group_commit_read_pipe:
2588 case Builtin::BIwork_group_commit_write_pipe:
2589 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
2590 return ExprError();
2591 break;
2592 case Builtin::BIsub_group_commit_read_pipe:
2593 case Builtin::BIsub_group_commit_write_pipe:
2594 if (OpenCL().checkSubgroupExt(TheCall) ||
2595 OpenCL().checkBuiltinCommitRWPipe(TheCall))
2596 return ExprError();
2597 break;
2598 case Builtin::BIget_pipe_num_packets:
2599 case Builtin::BIget_pipe_max_packets:
2600 if (OpenCL().checkBuiltinPipePackets(TheCall))
2601 return ExprError();
2602 break;
2603 case Builtin::BIto_global:
2604 case Builtin::BIto_local:
2605 case Builtin::BIto_private:
2606 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
2607 return ExprError();
2608 break;
2609 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2610 case Builtin::BIenqueue_kernel:
2611 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
2612 return ExprError();
2613 break;
2614 case Builtin::BIget_kernel_work_group_size:
2615 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2616 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
2617 return ExprError();
2618 break;
2619 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2620 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2621 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
2622 return ExprError();
2623 break;
2624 case Builtin::BI__builtin_os_log_format:
2626 [[fallthrough]];
2627 case Builtin::BI__builtin_os_log_format_buffer_size:
2628 if (BuiltinOSLogFormat(TheCall))
2629 return ExprError();
2630 break;
2631 case Builtin::BI__builtin_frame_address:
2632 case Builtin::BI__builtin_return_address: {
2633 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2634 return ExprError();
2635
2636 // -Wframe-address warning if non-zero passed to builtin
2637 // return/frame address.
2639 if (!TheCall->getArg(0)->isValueDependent() &&
2640 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2641 Result.Val.getInt() != 0)
2642 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2643 << ((BuiltinID == Builtin::BI__builtin_return_address)
2644 ? "__builtin_return_address"
2645 : "__builtin_frame_address")
2646 << TheCall->getSourceRange();
2647 break;
2648 }
2649
2650 case Builtin::BI__builtin_nondeterministic_value: {
2651 if (BuiltinNonDeterministicValue(TheCall))
2652 return ExprError();
2653 break;
2654 }
2655
2656 // __builtin_elementwise_abs restricts the element type to signed integers or
2657 // floating point types only.
2658 case Builtin::BI__builtin_elementwise_abs: {
2660 return ExprError();
2661
2662 QualType ArgTy = TheCall->getArg(0)->getType();
2663 QualType EltTy = ArgTy;
2664
2665 if (auto *VecTy = EltTy->getAs<VectorType>())
2666 EltTy = VecTy->getElementType();
2667 if (EltTy->isUnsignedIntegerType()) {
2668 Diag(TheCall->getArg(0)->getBeginLoc(),
2669 diag::err_builtin_invalid_arg_type)
2670 << 1 << /* signed integer or float ty*/ 3 << ArgTy;
2671 return ExprError();
2672 }
2673 break;
2674 }
2675
2676 // These builtins restrict the element type to floating point
2677 // types only.
2678 case Builtin::BI__builtin_elementwise_acos:
2679 case Builtin::BI__builtin_elementwise_asin:
2680 case Builtin::BI__builtin_elementwise_atan:
2681 case Builtin::BI__builtin_elementwise_ceil:
2682 case Builtin::BI__builtin_elementwise_cos:
2683 case Builtin::BI__builtin_elementwise_cosh:
2684 case Builtin::BI__builtin_elementwise_exp:
2685 case Builtin::BI__builtin_elementwise_exp2:
2686 case Builtin::BI__builtin_elementwise_floor:
2687 case Builtin::BI__builtin_elementwise_log:
2688 case Builtin::BI__builtin_elementwise_log2:
2689 case Builtin::BI__builtin_elementwise_log10:
2690 case Builtin::BI__builtin_elementwise_roundeven:
2691 case Builtin::BI__builtin_elementwise_round:
2692 case Builtin::BI__builtin_elementwise_rint:
2693 case Builtin::BI__builtin_elementwise_nearbyint:
2694 case Builtin::BI__builtin_elementwise_sin:
2695 case Builtin::BI__builtin_elementwise_sinh:
2696 case Builtin::BI__builtin_elementwise_sqrt:
2697 case Builtin::BI__builtin_elementwise_tan:
2698 case Builtin::BI__builtin_elementwise_tanh:
2699 case Builtin::BI__builtin_elementwise_trunc:
2700 case Builtin::BI__builtin_elementwise_canonicalize: {
2702 return ExprError();
2703
2704 QualType ArgTy = TheCall->getArg(0)->getType();
2705 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2706 ArgTy, 1))
2707 return ExprError();
2708 break;
2709 }
2710 case Builtin::BI__builtin_elementwise_fma: {
2711 if (BuiltinElementwiseTernaryMath(TheCall))
2712 return ExprError();
2713 break;
2714 }
2715
2716 // These builtins restrict the element type to floating point
2717 // types only, and take in two arguments.
2718 case Builtin::BI__builtin_elementwise_pow: {
2719 if (BuiltinElementwiseMath(TheCall))
2720 return ExprError();
2721
2722 QualType ArgTy = TheCall->getArg(0)->getType();
2723 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2724 ArgTy, 1) ||
2725 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2726 ArgTy, 2))
2727 return ExprError();
2728 break;
2729 }
2730
2731 // These builtins restrict the element type to integer
2732 // types only.
2733 case Builtin::BI__builtin_elementwise_add_sat:
2734 case Builtin::BI__builtin_elementwise_sub_sat: {
2735 if (BuiltinElementwiseMath(TheCall))
2736 return ExprError();
2737
2738 const Expr *Arg = TheCall->getArg(0);
2739 QualType ArgTy = Arg->getType();
2740 QualType EltTy = ArgTy;
2741
2742 if (auto *VecTy = EltTy->getAs<VectorType>())
2743 EltTy = VecTy->getElementType();
2744
2745 if (!EltTy->isIntegerType()) {
2746 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2747 << 1 << /* integer ty */ 6 << ArgTy;
2748 return ExprError();
2749 }
2750 break;
2751 }
2752
2753 case Builtin::BI__builtin_elementwise_min:
2754 case Builtin::BI__builtin_elementwise_max:
2755 if (BuiltinElementwiseMath(TheCall))
2756 return ExprError();
2757 break;
2758
2759 case Builtin::BI__builtin_elementwise_bitreverse: {
2761 return ExprError();
2762
2763 const Expr *Arg = TheCall->getArg(0);
2764 QualType ArgTy = Arg->getType();
2765 QualType EltTy = ArgTy;
2766
2767 if (auto *VecTy = EltTy->getAs<VectorType>())
2768 EltTy = VecTy->getElementType();
2769
2770 if (!EltTy->isIntegerType()) {
2771 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2772 << 1 << /* integer ty */ 6 << ArgTy;
2773 return ExprError();
2774 }
2775 break;
2776 }
2777
2778 case Builtin::BI__builtin_elementwise_copysign: {
2779 if (checkArgCount(TheCall, 2))
2780 return ExprError();
2781
2782 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
2783 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
2784 if (Magnitude.isInvalid() || Sign.isInvalid())
2785 return ExprError();
2786
2787 QualType MagnitudeTy = Magnitude.get()->getType();
2788 QualType SignTy = Sign.get()->getType();
2789 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
2790 MagnitudeTy, 1) ||
2791 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
2792 SignTy, 2)) {
2793 return ExprError();
2794 }
2795
2796 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
2797 return Diag(Sign.get()->getBeginLoc(),
2798 diag::err_typecheck_call_different_arg_types)
2799 << MagnitudeTy << SignTy;
2800 }
2801
2802 TheCall->setArg(0, Magnitude.get());
2803 TheCall->setArg(1, Sign.get());
2804 TheCall->setType(Magnitude.get()->getType());
2805 break;
2806 }
2807 case Builtin::BI__builtin_reduce_max:
2808 case Builtin::BI__builtin_reduce_min: {
2809 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2810 return ExprError();
2811
2812 const Expr *Arg = TheCall->getArg(0);
2813 const auto *TyA = Arg->getType()->getAs<VectorType>();
2814
2815 QualType ElTy;
2816 if (TyA)
2817 ElTy = TyA->getElementType();
2818 else if (Arg->getType()->isSizelessVectorType())
2820
2821 if (ElTy.isNull()) {
2822 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2823 << 1 << /* vector ty*/ 4 << Arg->getType();
2824 return ExprError();
2825 }
2826
2827 TheCall->setType(ElTy);
2828 break;
2829 }
2830
2831 // These builtins support vectors of integers only.
2832 // TODO: ADD/MUL should support floating-point types.
2833 case Builtin::BI__builtin_reduce_add:
2834 case Builtin::BI__builtin_reduce_mul:
2835 case Builtin::BI__builtin_reduce_xor:
2836 case Builtin::BI__builtin_reduce_or:
2837 case Builtin::BI__builtin_reduce_and: {
2838 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
2839 return ExprError();
2840
2841 const Expr *Arg = TheCall->getArg(0);
2842 const auto *TyA = Arg->getType()->getAs<VectorType>();
2843
2844 QualType ElTy;
2845 if (TyA)
2846 ElTy = TyA->getElementType();
2847 else if (Arg->getType()->isSizelessVectorType())
2849
2850 if (ElTy.isNull() || !ElTy->isIntegerType()) {
2851 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2852 << 1 << /* vector of integers */ 6 << Arg->getType();
2853 return ExprError();
2854 }
2855
2856 TheCall->setType(ElTy);
2857 break;
2858 }
2859
2860 case Builtin::BI__builtin_matrix_transpose:
2861 return BuiltinMatrixTranspose(TheCall, TheCallResult);
2862
2863 case Builtin::BI__builtin_matrix_column_major_load:
2864 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2865
2866 case Builtin::BI__builtin_matrix_column_major_store:
2867 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2868
2869 case Builtin::BI__builtin_verbose_trap:
2870 if (!checkBuiltinVerboseTrap(TheCall, *this))
2871 return ExprError();
2872 break;
2873
2874 case Builtin::BI__builtin_get_device_side_mangled_name: {
2875 auto Check = [](CallExpr *TheCall) {
2876 if (TheCall->getNumArgs() != 1)
2877 return false;
2878 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2879 if (!DRE)
2880 return false;
2881 auto *D = DRE->getDecl();
2882 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2883 return false;
2884 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2885 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2886 };
2887 if (!Check(TheCall)) {
2888 Diag(TheCall->getBeginLoc(),
2889 diag::err_hip_invalid_args_builtin_mangled_name);
2890 return ExprError();
2891 }
2892 break;
2893 }
2894 case Builtin::BI__builtin_popcountg:
2895 if (BuiltinPopcountg(*this, TheCall))
2896 return ExprError();
2897 break;
2898 case Builtin::BI__builtin_clzg:
2899 case Builtin::BI__builtin_ctzg:
2900 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
2901 return ExprError();
2902 break;
2903
2904 case Builtin::BI__builtin_allow_runtime_check: {
2905 Expr *Arg = TheCall->getArg(0);
2906 // Check if the argument is a string literal.
2907 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
2908 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2909 << Arg->getSourceRange();
2910 return ExprError();
2911 }
2912 break;
2913 }
2914 }
2915
2916 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
2917 return ExprError();
2918
2919 // Since the target specific builtins for each arch overlap, only check those
2920 // of the arch we are compiling for.
2921 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2922 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2923 assert(Context.getAuxTargetInfo() &&
2924 "Aux Target Builtin, but not an aux target?");
2925
2926 if (CheckTSBuiltinFunctionCall(
2928 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2929 return ExprError();
2930 } else {
2931 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2932 TheCall))
2933 return ExprError();
2934 }
2935 }
2936
2937 return TheCallResult;
2938}
2939
2940bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
2941 llvm::APSInt Result;
2942 // We can't check the value of a dependent argument.
2943 Expr *Arg = TheCall->getArg(ArgNum);
2944 if (Arg->isTypeDependent() || Arg->isValueDependent())
2945 return false;
2946
2947 // Check constant-ness first.
2948 if (BuiltinConstantArg(TheCall, ArgNum, Result))
2949 return true;
2950
2951 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
2952 if (Result.isShiftedMask() || (~Result).isShiftedMask())
2953 return false;
2954
2955 return Diag(TheCall->getBeginLoc(),
2956 diag::err_argument_not_contiguous_bit_field)
2957 << ArgNum << Arg->getSourceRange();
2958}
2959
2960bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2961 bool IsVariadic, FormatStringInfo *FSI) {
2962 if (Format->getFirstArg() == 0)
2964 else if (IsVariadic)
2966 else
2968 FSI->FormatIdx = Format->getFormatIdx() - 1;
2969 FSI->FirstDataArg =
2970 FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
2971
2972 // The way the format attribute works in GCC, the implicit this argument
2973 // of member functions is counted. However, it doesn't appear in our own
2974 // lists, so decrement format_idx in that case.
2975 if (IsCXXMember) {
2976 if(FSI->FormatIdx == 0)
2977 return false;
2978 --FSI->FormatIdx;
2979 if (FSI->FirstDataArg != 0)
2980 --FSI->FirstDataArg;
2981 }
2982 return true;
2983}
2984
2985/// Checks if a the given expression evaluates to null.
2986///
2987/// Returns true if the value evaluates to null.
2988static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2989 // Treat (smart) pointers constructed from nullptr as null, whether we can
2990 // const-evaluate them or not.
2991 // This must happen first: the smart pointer expr might have _Nonnull type!
2992 if (isa<CXXNullPtrLiteralExpr>(
2995 return true;
2996
2997 // If the expression has non-null type, it doesn't evaluate to null.
2998 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
2999 if (*nullability == NullabilityKind::NonNull)
3000 return false;
3001 }
3002
3003 // As a special case, transparent unions initialized with zero are
3004 // considered null for the purposes of the nonnull attribute.
3005 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3006 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
3007 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3008 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3009 Expr = ILE->getInit(0);
3010 }
3011
3012 bool Result;
3013 return (!Expr->isValueDependent() &&
3015 !Result);
3016}
3017
3019 const Expr *ArgExpr,
3020 SourceLocation CallSiteLoc) {
3021 if (CheckNonNullExpr(S, ArgExpr))
3022 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3023 S.PDiag(diag::warn_null_arg)
3024 << ArgExpr->getSourceRange());
3025}
3026
3027/// Determine whether the given type has a non-null nullability annotation.
3029 if (auto nullability = type->getNullability())
3030 return *nullability == NullabilityKind::NonNull;
3031
3032 return false;
3033}
3034
3036 const NamedDecl *FDecl,
3037 const FunctionProtoType *Proto,
3039 SourceLocation CallSiteLoc) {
3040 assert((FDecl || Proto) && "Need a function declaration or prototype");
3041
3042 // Already checked by constant evaluator.
3044 return;
3045 // Check the attributes attached to the method/function itself.
3046 llvm::SmallBitVector NonNullArgs;
3047 if (FDecl) {
3048 // Handle the nonnull attribute on the function/method declaration itself.
3049 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3050 if (!NonNull->args_size()) {
3051 // Easy case: all pointer arguments are nonnull.
3052 for (const auto *Arg : Args)
3053 if (S.isValidPointerAttrType(Arg->getType()))
3054 CheckNonNullArgument(S, Arg, CallSiteLoc);
3055 return;
3056 }
3057
3058 for (const ParamIdx &Idx : NonNull->args()) {
3059 unsigned IdxAST = Idx.getASTIndex();
3060 if (IdxAST >= Args.size())
3061 continue;
3062 if (NonNullArgs.empty())
3063 NonNullArgs.resize(Args.size());
3064 NonNullArgs.set(IdxAST);
3065 }
3066 }
3067 }
3068
3069 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3070 // Handle the nonnull attribute on the parameters of the
3071 // function/method.
3073 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3074 parms = FD->parameters();
3075 else
3076 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3077
3078 unsigned ParamIndex = 0;
3079 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3080 I != E; ++I, ++ParamIndex) {
3081 const ParmVarDecl *PVD = *I;
3082 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3083 if (NonNullArgs.empty())
3084 NonNullArgs.resize(Args.size());
3085
3086 NonNullArgs.set(ParamIndex);
3087 }
3088 }
3089 } else {
3090 // If we have a non-function, non-method declaration but no
3091 // function prototype, try to dig out the function prototype.
3092 if (!Proto) {
3093 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3094 QualType type = VD->getType().getNonReferenceType();
3095 if (auto pointerType = type->getAs<PointerType>())
3096 type = pointerType->getPointeeType();
3097 else if (auto blockType = type->getAs<BlockPointerType>())
3098 type = blockType->getPointeeType();
3099 // FIXME: data member pointers?
3100
3101 // Dig out the function prototype, if there is one.
3102 Proto = type->getAs<FunctionProtoType>();
3103 }
3104 }
3105
3106 // Fill in non-null argument information from the nullability
3107 // information on the parameter types (if we have them).
3108 if (Proto) {
3109 unsigned Index = 0;
3110 for (auto paramType : Proto->getParamTypes()) {
3111 if (isNonNullType(paramType)) {
3112 if (NonNullArgs.empty())
3113 NonNullArgs.resize(Args.size());
3114
3115 NonNullArgs.set(Index);
3116 }
3117
3118 ++Index;
3119 }
3120 }
3121 }
3122
3123 // Check for non-null arguments.
3124 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3125 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3126 if (NonNullArgs[ArgIndex])
3127 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3128 }
3129}
3130
3131void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3132 StringRef ParamName, QualType ArgTy,
3133 QualType ParamTy) {
3134
3135 // If a function accepts a pointer or reference type
3136 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3137 return;
3138
3139 // If the parameter is a pointer type, get the pointee type for the
3140 // argument too. If the parameter is a reference type, don't try to get
3141 // the pointee type for the argument.
3142 if (ParamTy->isPointerType())
3143 ArgTy = ArgTy->getPointeeType();
3144
3145 // Remove reference or pointer
3146 ParamTy = ParamTy->getPointeeType();
3147
3148 // Find expected alignment, and the actual alignment of the passed object.
3149 // getTypeAlignInChars requires complete types
3150 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3151 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3152 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3153 return;
3154
3155 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3156 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3157
3158 // If the argument is less aligned than the parameter, there is a
3159 // potential alignment issue.
3160 if (ArgAlign < ParamAlign)
3161 Diag(Loc, diag::warn_param_mismatched_alignment)
3162 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3163 << ParamName << (FDecl != nullptr) << FDecl;
3164}
3165
3167 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3168 bool IsMemberFunction, SourceLocation Loc,
3170 // FIXME: We should check as much as we can in the template definition.
3172 return;
3173
3174 // Printf and scanf checking.
3175 llvm::SmallBitVector CheckedVarArgs;
3176 if (FDecl) {
3177 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3178 // Only create vector if there are format attributes.
3179 CheckedVarArgs.resize(Args.size());
3180
3181 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3182 CheckedVarArgs);
3183 }
3184 }
3185
3186 // Refuse POD arguments that weren't caught by the format string
3187 // checks above.
3188 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3189 if (CallType != VariadicDoesNotApply &&
3190 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3191 unsigned NumParams = Proto ? Proto->getNumParams()
3192 : isa_and_nonnull<FunctionDecl>(FDecl)
3193 ? cast<FunctionDecl>(FDecl)->getNumParams()
3194 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3195 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3196 : 0;
3197
3198 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3199 // Args[ArgIdx] can be null in malformed code.
3200 if (const Expr *Arg = Args[ArgIdx]) {
3201 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3202 checkVariadicArgument(Arg, CallType);
3203 }
3204 }
3205 }
3206
3207 if (FDecl || Proto) {
3208 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3209
3210 // Type safety checking.
3211 if (FDecl) {
3212 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3213 CheckArgumentWithTypeTag(I, Args, Loc);
3214 }
3215 }
3216
3217 // Check that passed arguments match the alignment of original arguments.
3218 // Try to get the missing prototype from the declaration.
3219 if (!Proto && FDecl) {
3220 const auto *FT = FDecl->getFunctionType();
3221 if (isa_and_nonnull<FunctionProtoType>(FT))
3222 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3223 }
3224 if (Proto) {
3225 // For variadic functions, we may have more args than parameters.
3226 // For some K&R functions, we may have less args than parameters.
3227 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3228 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3229 bool IsScalableArg = false;
3230 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3231 // Args[ArgIdx] can be null in malformed code.
3232 if (const Expr *Arg = Args[ArgIdx]) {
3233 if (Arg->containsErrors())
3234 continue;
3235
3236 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3237 FDecl->hasLinkage() &&
3238 FDecl->getFormalLinkage() != Linkage::Internal &&
3239 CallType == VariadicDoesNotApply)
3240 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3241
3242 QualType ParamTy = Proto->getParamType(ArgIdx);
3243 if (ParamTy->isSizelessVectorType())
3244 IsScalableArg = true;
3245 QualType ArgTy = Arg->getType();
3246 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3247 ArgTy, ParamTy);
3248 }
3249 }
3250
3251 // If the callee has an AArch64 SME attribute to indicate that it is an
3252 // __arm_streaming function, then the caller requires SME to be available.
3255 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3256 llvm::StringMap<bool> CallerFeatureMap;
3257 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3258 if (!CallerFeatureMap.contains("sme"))
3259 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3260 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3261 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3262 }
3263 }
3264
3265 // If the call requires a streaming-mode change and has scalable vector
3266 // arguments or return values, then warn the user that the streaming and
3267 // non-streaming vector lengths may be different.
3268 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3269 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3270 (IsScalableArg || IsScalableRet)) {
3271 bool IsCalleeStreaming =
3273 bool IsCalleeStreamingCompatible =
3274 ExtInfo.AArch64SMEAttributes &
3276 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3277 if (!IsCalleeStreamingCompatible &&
3278 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3279 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3280 if (IsScalableArg)
3281 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3282 << /*IsArg=*/true;
3283 if (IsScalableRet)
3284 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3285 << /*IsArg=*/false;
3286 }
3287 }
3288
3289 FunctionType::ArmStateValue CalleeArmZAState =
3291 FunctionType::ArmStateValue CalleeArmZT0State =
3293 if (CalleeArmZAState != FunctionType::ARM_None ||
3294 CalleeArmZT0State != FunctionType::ARM_None) {
3295 bool CallerHasZAState = false;
3296 bool CallerHasZT0State = false;
3297 if (CallerFD) {
3298 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3299 if (Attr && Attr->isNewZA())
3300 CallerHasZAState = true;
3301 if (Attr && Attr->isNewZT0())
3302 CallerHasZT0State = true;
3303 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3304 CallerHasZAState |=
3306 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3308 CallerHasZT0State |=
3310 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3312 }
3313 }
3314
3315 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3316 Diag(Loc, diag::err_sme_za_call_no_za_state);
3317
3318 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3319 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3320
3321 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3322 CalleeArmZT0State != FunctionType::ARM_None) {
3323 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3324 Diag(Loc, diag::note_sme_use_preserves_za);
3325 }
3326 }
3327 }
3328
3329 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3330 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3331 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3332 if (!Arg->isValueDependent()) {
3333 Expr::EvalResult Align;
3334 if (Arg->EvaluateAsInt(Align, Context)) {
3335 const llvm::APSInt &I = Align.Val.getInt();
3336 if (!I.isPowerOf2())
3337 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3338 << Arg->getSourceRange();
3339
3340 if (I > Sema::MaximumAlignment)
3341 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3342 << Arg->getSourceRange() << Sema::MaximumAlignment;
3343 }
3344 }
3345 }
3346
3347 if (FD)
3348 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3349}
3350
3352 if (ConceptDecl *Decl = AutoT->getTypeConstraintConcept()) {
3354 }
3355}
3356
3357void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3359 const FunctionProtoType *Proto,
3361 VariadicCallType CallType =
3363
3364 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
3365 CheckArgAlignment(
3366 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
3367 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
3368
3369 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3370 Loc, SourceRange(), CallType);
3371}
3372
3374 const FunctionProtoType *Proto) {
3375 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3376 isa<CXXMethodDecl>(FDecl);
3377 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3378 IsMemberOperatorCall;
3379 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3380 TheCall->getCallee());
3381 Expr** Args = TheCall->getArgs();
3382 unsigned NumArgs = TheCall->getNumArgs();
3383
3384 Expr *ImplicitThis = nullptr;
3385 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
3386 // If this is a call to a member operator, hide the first
3387 // argument from checkCall.
3388 // FIXME: Our choice of AST representation here is less than ideal.
3389 ImplicitThis = Args[0];
3390 ++Args;
3391 --NumArgs;
3392 } else if (IsMemberFunction && !FDecl->isStatic() &&
3394 ImplicitThis =
3395 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3396
3397 if (ImplicitThis) {
3398 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
3399 // used.
3400 QualType ThisType = ImplicitThis->getType();
3401 if (!ThisType->isPointerType()) {
3402 assert(!ThisType->isReferenceType());
3403 ThisType = Context.getPointerType(ThisType);
3404 }
3405
3406 QualType ThisTypeFromDecl = Context.getPointerType(
3407 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
3408
3409 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
3410 ThisTypeFromDecl);
3411 }
3412
3413 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
3414 IsMemberFunction, TheCall->getRParenLoc(),
3415 TheCall->getCallee()->getSourceRange(), CallType);
3416
3417 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3418 // None of the checks below are needed for functions that don't have
3419 // simple names (e.g., C++ conversion functions).
3420 if (!FnInfo)
3421 return false;
3422
3423 // Enforce TCB except for builtin calls, which are always allowed.
3424 if (FDecl->getBuiltinID() == 0)
3425 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
3426
3427 CheckAbsoluteValueFunction(TheCall, FDecl);
3428 CheckMaxUnsignedZero(TheCall, FDecl);
3429 CheckInfNaNFunction(TheCall, FDecl);
3430
3431 if (getLangOpts().ObjC)
3432 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
3433
3434 unsigned CMId = FDecl->getMemoryFunctionKind();
3435
3436 // Handle memory setting and copying functions.
3437 switch (CMId) {
3438 case 0:
3439 return false;
3440 case Builtin::BIstrlcpy: // fallthrough
3441 case Builtin::BIstrlcat:
3442 CheckStrlcpycatArguments(TheCall, FnInfo);
3443 break;
3444 case Builtin::BIstrncat:
3445 CheckStrncatArguments(TheCall, FnInfo);
3446 break;
3447 case Builtin::BIfree:
3448 CheckFreeArguments(TheCall);
3449 break;
3450 default:
3451 CheckMemaccessArguments(TheCall, CMId, FnInfo);
3452 }
3453
3454 return false;
3455}
3456
3457bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3458 const FunctionProtoType *Proto) {
3459 QualType Ty;
3460 if (const auto *V = dyn_cast<VarDecl>(NDecl))
3461 Ty = V->getType().getNonReferenceType();
3462 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3463 Ty = F->getType().getNonReferenceType();
3464 else
3465 return false;
3466
3467 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3468 !Ty->isFunctionProtoType())
3469 return false;
3470
3471 VariadicCallType CallType;
3472 if (!Proto || !Proto->isVariadic()) {
3473 CallType = VariadicDoesNotApply;
3474 } else if (Ty->isBlockPointerType()) {
3475 CallType = VariadicBlock;
3476 } else { // Ty->isFunctionPointerType()
3477 CallType = VariadicFunction;
3478 }
3479
3480 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3481 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3482 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3483 TheCall->getCallee()->getSourceRange(), CallType);
3484
3485 return false;
3486}
3487
3488bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3489 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3490 TheCall->getCallee());
3491 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3492 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3493 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3494 TheCall->getCallee()->getSourceRange(), CallType);
3495
3496 return false;
3497}
3498
3499static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
3500 if (!llvm::isValidAtomicOrderingCABI(Ordering))
3501 return false;
3502
3503 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3504 switch (Op) {
3505 case AtomicExpr::AO__c11_atomic_init:
3506 case AtomicExpr::AO__opencl_atomic_init:
3507 llvm_unreachable("There is no ordering argument for an init");
3508
3509 case AtomicExpr::AO__c11_atomic_load:
3510 case AtomicExpr::AO__opencl_atomic_load:
3511 case AtomicExpr::AO__hip_atomic_load:
3512 case AtomicExpr::AO__atomic_load_n:
3513 case AtomicExpr::AO__atomic_load:
3514 case AtomicExpr::AO__scoped_atomic_load_n:
3515 case AtomicExpr::AO__scoped_atomic_load:
3516 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3517 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3518
3519 case AtomicExpr::AO__c11_atomic_store:
3520 case AtomicExpr::AO__opencl_atomic_store:
3521 case AtomicExpr::AO__hip_atomic_store:
3522 case AtomicExpr::AO__atomic_store:
3523 case AtomicExpr::AO__atomic_store_n:
3524 case AtomicExpr::AO__scoped_atomic_store:
3525 case AtomicExpr::AO__scoped_atomic_store_n:
3526 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3527 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3528 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3529
3530 default:
3531 return true;
3532 }
3533}
3534
3535ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
3537 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3538 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3539 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
3540 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
3541 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
3542 Op);
3543}
3544
3546 SourceLocation RParenLoc, MultiExprArg Args,
3548 AtomicArgumentOrder ArgOrder) {
3549 // All the non-OpenCL operations take one of the following forms.
3550 // The OpenCL operations take the __c11 forms with one extra argument for
3551 // synchronization scope.
3552 enum {
3553 // C __c11_atomic_init(A *, C)
3554 Init,
3555
3556 // C __c11_atomic_load(A *, int)
3557 Load,
3558
3559 // void __atomic_load(A *, CP, int)
3560 LoadCopy,
3561
3562 // void __atomic_store(A *, CP, int)
3563 Copy,
3564
3565 // C __c11_atomic_add(A *, M, int)
3566 Arithmetic,
3567
3568 // C __atomic_exchange_n(A *, CP, int)
3569 Xchg,
3570
3571 // void __atomic_exchange(A *, C *, CP, int)
3572 GNUXchg,
3573
3574 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3575 C11CmpXchg,
3576
3577 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3578 GNUCmpXchg
3579 } Form = Init;
3580
3581 const unsigned NumForm = GNUCmpXchg + 1;
3582 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3583 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3584 // where:
3585 // C is an appropriate type,
3586 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3587 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3588 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3589 // the int parameters are for orderings.
3590
3591 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3592 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3593 "need to update code for modified forms");
3594 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
3595 AtomicExpr::AO__atomic_xor_fetch + 1 ==
3596 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
3597 "need to update code for modified C11 atomics");
3598 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
3599 Op <= AtomicExpr::AO__opencl_atomic_store;
3600 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
3601 Op <= AtomicExpr::AO__hip_atomic_store;
3602 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
3603 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
3604 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
3605 Op <= AtomicExpr::AO__c11_atomic_store) ||
3606 IsOpenCL;
3607 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3608 Op == AtomicExpr::AO__atomic_store_n ||
3609 Op == AtomicExpr::AO__atomic_exchange_n ||
3610 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
3611 Op == AtomicExpr::AO__scoped_atomic_load_n ||
3612 Op == AtomicExpr::AO__scoped_atomic_store_n ||
3613 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
3614 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
3615 // Bit mask for extra allowed value types other than integers for atomic
3616 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
3617 // allow floating point.
3618 enum ArithOpExtraValueType {
3619 AOEVT_None = 0,
3620 AOEVT_Pointer = 1,
3621 AOEVT_FP = 2,
3622 };
3623 unsigned ArithAllows = AOEVT_None;
3624
3625 switch (Op) {
3626 case AtomicExpr::AO__c11_atomic_init:
3627 case AtomicExpr::AO__opencl_atomic_init:
3628 Form = Init;
3629 break;
3630
3631 case AtomicExpr::AO__c11_atomic_load:
3632 case AtomicExpr::AO__opencl_atomic_load:
3633 case AtomicExpr::AO__hip_atomic_load:
3634 case AtomicExpr::AO__atomic_load_n:
3635 case AtomicExpr::AO__scoped_atomic_load_n:
3636 Form = Load;
3637 break;
3638
3639 case AtomicExpr::AO__atomic_load:
3640 case AtomicExpr::AO__scoped_atomic_load:
3641 Form = LoadCopy;
3642 break;
3643
3644 case AtomicExpr::AO__c11_atomic_store:
3645 case AtomicExpr::AO__opencl_atomic_store:
3646 case AtomicExpr::AO__hip_atomic_store:
3647 case AtomicExpr::AO__atomic_store:
3648 case AtomicExpr::AO__atomic_store_n:
3649 case AtomicExpr::AO__scoped_atomic_store:
3650 case AtomicExpr::AO__scoped_atomic_store_n:
3651 Form = Copy;
3652 break;
3653 case AtomicExpr::AO__atomic_fetch_add:
3654 case AtomicExpr::AO__atomic_fetch_sub:
3655 case AtomicExpr::AO__atomic_add_fetch:
3656 case AtomicExpr::AO__atomic_sub_fetch:
3657 case AtomicExpr::AO__scoped_atomic_fetch_add:
3658 case AtomicExpr::AO__scoped_atomic_fetch_sub:
3659 case AtomicExpr::AO__scoped_atomic_add_fetch:
3660 case AtomicExpr::AO__scoped_atomic_sub_fetch:
3661 case AtomicExpr::AO__c11_atomic_fetch_add:
3662 case AtomicExpr::AO__c11_atomic_fetch_sub:
3663 case AtomicExpr::AO__opencl_atomic_fetch_add:
3664 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3665 case AtomicExpr::AO__hip_atomic_fetch_add:
3666 case AtomicExpr::AO__hip_atomic_fetch_sub:
3667 ArithAllows = AOEVT_Pointer | AOEVT_FP;
3668 Form = Arithmetic;
3669 break;
3670 case AtomicExpr::AO__atomic_fetch_max:
3671 case AtomicExpr::AO__atomic_fetch_min:
3672 case AtomicExpr::AO__atomic_max_fetch:
3673 case AtomicExpr::AO__atomic_min_fetch:
3674 case AtomicExpr::AO__scoped_atomic_fetch_max:
3675 case AtomicExpr::AO__scoped_atomic_fetch_min:
3676 case AtomicExpr::AO__scoped_atomic_max_fetch:
3677 case AtomicExpr::AO__scoped_atomic_min_fetch:
3678 case AtomicExpr::AO__c11_atomic_fetch_max:
3679 case AtomicExpr::AO__c11_atomic_fetch_min:
3680 case AtomicExpr::AO__opencl_atomic_fetch_max:
3681 case AtomicExpr::AO__opencl_atomic_fetch_min:
3682 case AtomicExpr::AO__hip_atomic_fetch_max:
3683 case AtomicExpr::AO__hip_atomic_fetch_min:
3684 ArithAllows = AOEVT_FP;
3685 Form = Arithmetic;
3686 break;
3687 case AtomicExpr::AO__c11_atomic_fetch_and:
3688 case AtomicExpr::AO__c11_atomic_fetch_or:
3689 case AtomicExpr::AO__c11_atomic_fetch_xor:
3690 case AtomicExpr::AO__hip_atomic_fetch_and:
3691 case AtomicExpr::AO__hip_atomic_fetch_or:
3692 case AtomicExpr::AO__hip_atomic_fetch_xor:
3693 case AtomicExpr::AO__c11_atomic_fetch_nand:
3694 case AtomicExpr::AO__opencl_atomic_fetch_and:
3695 case AtomicExpr::AO__opencl_atomic_fetch_or:
3696 case AtomicExpr::AO__opencl_atomic_fetch_xor:
3697 case AtomicExpr::AO__atomic_fetch_and:
3698 case AtomicExpr::AO__atomic_fetch_or:
3699 case AtomicExpr::AO__atomic_fetch_xor:
3700 case AtomicExpr::AO__atomic_fetch_nand:
3701 case AtomicExpr::AO__atomic_and_fetch:
3702 case AtomicExpr::AO__atomic_or_fetch:
3703 case AtomicExpr::AO__atomic_xor_fetch:
3704 case AtomicExpr::AO__atomic_nand_fetch:
3705 case AtomicExpr::AO__scoped_atomic_fetch_and:
3706 case AtomicExpr::AO__scoped_atomic_fetch_or:
3707 case AtomicExpr::AO__scoped_atomic_fetch_xor:
3708 case AtomicExpr::AO__scoped_atomic_fetch_nand:
3709 case AtomicExpr::AO__scoped_atomic_and_fetch:
3710 case AtomicExpr::AO__scoped_atomic_or_fetch:
3711 case AtomicExpr::AO__scoped_atomic_xor_fetch:
3712 case AtomicExpr::AO__scoped_atomic_nand_fetch:
3713 Form = Arithmetic;
3714 break;
3715
3716 case AtomicExpr::AO__c11_atomic_exchange:
3717 case AtomicExpr::AO__hip_atomic_exchange:
3718 case AtomicExpr::AO__opencl_atomic_exchange:
3719 case AtomicExpr::AO__atomic_exchange_n:
3720 case AtomicExpr::AO__scoped_atomic_exchange_n:
3721 Form = Xchg;
3722 break;
3723
3724 case AtomicExpr::AO__atomic_exchange:
3725 case AtomicExpr::AO__scoped_atomic_exchange:
3726 Form = GNUXchg;
3727 break;
3728
3729 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3730 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3731 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
3732 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3733 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3734 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
3735 Form = C11CmpXchg;
3736 break;
3737
3738 case AtomicExpr::AO__atomic_compare_exchange:
3739 case AtomicExpr::AO__atomic_compare_exchange_n:
3740 case AtomicExpr::AO__scoped_atomic_compare_exchange:
3741 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
3742 Form = GNUCmpXchg;
3743 break;
3744 }
3745
3746 unsigned AdjustedNumArgs = NumArgs[Form];
3747 if ((IsOpenCL || IsHIP || IsScoped) &&
3748 Op != AtomicExpr::AO__opencl_atomic_init)
3749 ++AdjustedNumArgs;
3750 // Check we have the right number of arguments.
3751 if (Args.size() < AdjustedNumArgs) {
3752 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
3753 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
3754 << /*is non object*/ 0 << ExprRange;
3755 return ExprError();
3756 } else if (Args.size() > AdjustedNumArgs) {
3757 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
3758 diag::err_typecheck_call_too_many_args)
3759 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
3760 << /*is non object*/ 0 << ExprRange;
3761 return ExprError();
3762 }
3763
3764 // Inspect the first argument of the atomic operation.
3765 Expr *Ptr = Args[0];
3767 if (ConvertedPtr.isInvalid())
3768 return ExprError();
3769
3770 Ptr = ConvertedPtr.get();
3771 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3772 if (!pointerType) {
3773 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
3774 << Ptr->getType() << 0 << Ptr->getSourceRange();
3775 return ExprError();
3776 }
3777
3778 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3779 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3780 QualType ValType = AtomTy; // 'C'
3781 if (IsC11) {
3782 if (!AtomTy->isAtomicType()) {
3783 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
3784 << Ptr->getType() << Ptr->getSourceRange();
3785 return ExprError();
3786 }
3787 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
3789 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
3790 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3791 << Ptr->getSourceRange();
3792 return ExprError();
3793 }
3794 ValType = AtomTy->castAs<AtomicType>()->getValueType();
3795 } else if (Form != Load && Form != LoadCopy) {
3796 if (ValType.isConstQualified()) {
3797 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
3798 << Ptr->getType() << Ptr->getSourceRange();
3799 return ExprError();
3800 }
3801 }
3802
3803 // Pointer to object of size zero is not allowed.
3804 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
3805 diag::err_incomplete_type))
3806 return ExprError();
3807 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
3808 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
3809 << Ptr->getType() << 1 << Ptr->getSourceRange();
3810 return ExprError();
3811 }
3812
3813 // For an arithmetic operation, the implied arithmetic must be well-formed.
3814 if (Form == Arithmetic) {
3815 // GCC does not enforce these rules for GNU atomics, but we do to help catch
3816 // trivial type errors.
3817 auto IsAllowedValueType = [&](QualType ValType,
3818 unsigned AllowedType) -> bool {
3819 if (ValType->isIntegerType())
3820 return true;
3821 if (ValType->isPointerType())
3822 return AllowedType & AOEVT_Pointer;
3823 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
3824 return false;
3825 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
3826 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
3828 &llvm::APFloat::x87DoubleExtended())
3829 return false;
3830 return true;
3831 };
3832 if (!IsAllowedValueType(ValType, ArithAllows)) {
3833 auto DID = ArithAllows & AOEVT_FP
3834 ? (ArithAllows & AOEVT_Pointer
3835 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
3836 : diag::err_atomic_op_needs_atomic_int_or_fp)
3837 : diag::err_atomic_op_needs_atomic_int;
3838 Diag(ExprRange.getBegin(), DID)
3839 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3840 return ExprError();
3841 }
3842 if (IsC11 && ValType->isPointerType() &&
3844 diag::err_incomplete_type)) {
3845 return ExprError();
3846 }
3847 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3848 // For __atomic_*_n operations, the value type must be a scalar integral or
3849 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3850 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3851 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3852 return ExprError();
3853 }
3854
3855 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3856 !AtomTy->isScalarType()) {
3857 // For GNU atomics, require a trivially-copyable type. This is not part of
3858 // the GNU atomics specification but we enforce it for consistency with
3859 // other atomics which generally all require a trivially-copyable type. This
3860 // is because atomics just copy bits.
3861 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
3862 << Ptr->getType() << Ptr->getSourceRange();
3863 return ExprError();
3864 }
3865
3866 switch (ValType.getObjCLifetime()) {
3869 // okay
3870 break;
3871
3875 // FIXME: Can this happen? By this point, ValType should be known
3876 // to be trivially copyable.
3877 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
3878 << ValType << Ptr->getSourceRange();
3879 return ExprError();
3880 }
3881
3882 // All atomic operations have an overload which takes a pointer to a volatile
3883 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3884 // into the result or the other operands. Similarly atomic_load takes a
3885 // pointer to a const 'A'.
3886 ValType.removeLocalVolatile();
3887 ValType.removeLocalConst();
3888 QualType ResultType = ValType;
3889 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3890 Form == Init)
3891 ResultType = Context.VoidTy;
3892 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3893 ResultType = Context.BoolTy;
3894
3895 // The type of a parameter passed 'by value'. In the GNU atomics, such
3896 // arguments are actually passed as pointers.
3897 QualType ByValType = ValType; // 'CP'
3898 bool IsPassedByAddress = false;
3899 if (!IsC11 && !IsHIP && !IsN) {
3900 ByValType = Ptr->getType();
3901 IsPassedByAddress = true;
3902 }
3903
3904 SmallVector<Expr *, 5> APIOrderedArgs;
3905 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
3906 APIOrderedArgs.push_back(Args[0]);
3907 switch (Form) {
3908 case Init:
3909 case Load:
3910 APIOrderedArgs.push_back(Args[1]); // Val1/Order
3911 break;
3912 case LoadCopy:
3913 case Copy:
3914 case Arithmetic:
3915 case Xchg:
3916 APIOrderedArgs.push_back(Args[2]); // Val1
3917 APIOrderedArgs.push_back(Args[1]); // Order
3918 break;
3919 case GNUXchg:
3920 APIOrderedArgs.push_back(Args[2]); // Val1
3921 APIOrderedArgs.push_back(Args[3]); // Val2
3922 APIOrderedArgs.push_back(Args[1]); // Order
3923 break;
3924 case C11CmpXchg:
3925 APIOrderedArgs.push_back(Args[2]); // Val1
3926 APIOrderedArgs.push_back(Args[4]); // Val2
3927 APIOrderedArgs.push_back(Args[1]); // Order
3928 APIOrderedArgs.push_back(Args[3]); // OrderFail
3929 break;
3930 case GNUCmpXchg:
3931 APIOrderedArgs.push_back(Args[2]); // Val1
3932 APIOrderedArgs.push_back(Args[4]); // Val2
3933 APIOrderedArgs.push_back(Args[5]); // Weak
3934 APIOrderedArgs.push_back(Args[1]); // Order
3935 APIOrderedArgs.push_back(Args[3]); // OrderFail
3936 break;
3937 }
3938 } else
3939 APIOrderedArgs.append(Args.begin(), Args.end());
3940
3941 // The first argument's non-CV pointer type is used to deduce the type of
3942 // subsequent arguments, except for:
3943 // - weak flag (always converted to bool)
3944 // - memory order (always converted to int)
3945 // - scope (always converted to int)
3946 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
3947 QualType Ty;
3948 if (i < NumVals[Form] + 1) {
3949 switch (i) {
3950 case 0:
3951 // The first argument is always a pointer. It has a fixed type.
3952 // It is always dereferenced, a nullptr is undefined.
3953 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
3954 // Nothing else to do: we already know all we want about this pointer.
3955 continue;
3956 case 1:
3957 // The second argument is the non-atomic operand. For arithmetic, this
3958 // is always passed by value, and for a compare_exchange it is always
3959 // passed by address. For the rest, GNU uses by-address and C11 uses
3960 // by-value.
3961 assert(Form != Load);
3962 if (Form == Arithmetic && ValType->isPointerType())
3964 else if (Form == Init || Form == Arithmetic)
3965 Ty = ValType;
3966 else if (Form == Copy || Form == Xchg) {
3967 if (IsPassedByAddress) {
3968 // The value pointer is always dereferenced, a nullptr is undefined.
3969 CheckNonNullArgument(*this, APIOrderedArgs[i],
3970 ExprRange.getBegin());
3971 }
3972 Ty = ByValType;
3973 } else {
3974 Expr *ValArg = APIOrderedArgs[i];
3975 // The value pointer is always dereferenced, a nullptr is undefined.
3976 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
3978 // Keep address space of non-atomic pointer type.
3979 if (const PointerType *PtrTy =
3980 ValArg->getType()->getAs<PointerType>()) {
3981 AS = PtrTy->getPointeeType().getAddressSpace();
3982 }
3985 }
3986 break;
3987 case 2:
3988 // The third argument to compare_exchange / GNU exchange is the desired
3989 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3990 if (IsPassedByAddress)
3991 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
3992 Ty = ByValType;
3993 break;
3994 case 3:
3995 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3996 Ty = Context.BoolTy;
3997 break;
3998 }
3999 } else {
4000 // The order(s) and scope are always converted to int.
4001 Ty = Context.IntTy;
4002 }
4003
4004 InitializedEntity Entity =
4006 ExprResult Arg = APIOrderedArgs[i];
4007 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4008 if (Arg.isInvalid())
4009 return true;
4010 APIOrderedArgs[i] = Arg.get();
4011 }
4012
4013 // Permute the arguments into a 'consistent' order.
4014 SmallVector<Expr*, 5> SubExprs;
4015 SubExprs.push_back(Ptr);
4016 switch (Form) {
4017 case Init:
4018 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4019 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4020 break;
4021 case Load:
4022 SubExprs.push_back(APIOrderedArgs[1]); // Order
4023 break;
4024 case LoadCopy:
4025 case Copy:
4026 case Arithmetic:
4027 case Xchg:
4028 SubExprs.push_back(APIOrderedArgs[2]); // Order
4029 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4030 break;
4031 case GNUXchg:
4032 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4033 SubExprs.push_back(APIOrderedArgs[3]); // Order
4034 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4035 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4036 break;
4037 case C11CmpXchg:
4038 SubExprs.push_back(APIOrderedArgs[3]); // Order
4039 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4040 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4041 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4042 break;
4043 case GNUCmpXchg:
4044 SubExprs.push_back(APIOrderedArgs[4]); // Order
4045 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4046 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4047 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4048 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4049 break;
4050 }
4051
4052 // If the memory orders are constants, check they are valid.
4053 if (SubExprs.size() >= 2 && Form != Init) {
4054 std::optional<llvm::APSInt> Success =
4055 SubExprs[1]->getIntegerConstantExpr(Context);
4056 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4057 Diag(SubExprs[1]->getBeginLoc(),
4058 diag::warn_atomic_op_has_invalid_memory_order)
4059 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4060 << SubExprs[1]->getSourceRange();
4061 }
4062 if (SubExprs.size() >= 5) {
4063 if (std::optional<llvm::APSInt> Failure =
4064 SubExprs[3]->getIntegerConstantExpr(Context)) {
4065 if (!llvm::is_contained(
4066 {llvm::AtomicOrderingCABI::relaxed,
4067 llvm::AtomicOrderingCABI::consume,
4068 llvm::AtomicOrderingCABI::acquire,
4069 llvm::AtomicOrderingCABI::seq_cst},
4070 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4071 Diag(SubExprs[3]->getBeginLoc(),
4072 diag::warn_atomic_op_has_invalid_memory_order)
4073 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4074 }
4075 }
4076 }
4077 }
4078
4079 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4080 auto *Scope = Args[Args.size() - 1];
4081 if (std::optional<llvm::APSInt> Result =
4082 Scope->getIntegerConstantExpr(Context)) {
4083 if (!ScopeModel->isValid(Result->getZExtValue()))
4084 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4085 << Scope->getSourceRange();
4086 }
4087 SubExprs.push_back(Scope);
4088 }
4089
4090 AtomicExpr *AE = new (Context)
4091 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4092
4093 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4094 Op == AtomicExpr::AO__c11_atomic_store ||
4095 Op == AtomicExpr::AO__opencl_atomic_load ||
4096 Op == AtomicExpr::AO__hip_atomic_load ||
4097 Op == AtomicExpr::AO__opencl_atomic_store ||
4098 Op == AtomicExpr::AO__hip_atomic_store) &&
4100 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4101 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4102 Op == AtomicExpr::AO__opencl_atomic_load ||
4103 Op == AtomicExpr::AO__hip_atomic_load)
4104 ? 0
4105 : 1);
4106
4107 if (ValType->isBitIntType()) {
4108 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4109 return ExprError();
4110 }
4111
4112 return AE;
4113}
4114
4115/// checkBuiltinArgument - Given a call to a builtin function, perform
4116/// normal type-checking on the given argument, updating the call in
4117/// place. This is useful when a builtin function requires custom
4118/// type-checking for some of its arguments but not necessarily all of
4119/// them.
4120///
4121/// Returns true on error.
4122static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4123 FunctionDecl *Fn = E->getDirectCallee();
4124 assert(Fn && "builtin call without direct callee!");
4125
4126 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4127 InitializedEntity Entity =
4129
4130 ExprResult Arg = E->getArg(ArgIndex);
4131 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4132 if (Arg.isInvalid())
4133 return true;
4134
4135 E->setArg(ArgIndex, Arg.get());
4136 return false;
4137}
4138
4139ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4140 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4141 Expr *Callee = TheCall->getCallee();
4142 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4143 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4144
4145 // Ensure that we have at least one argument to do type inference from.
4146 if (TheCall->getNumArgs() < 1) {
4147 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4148 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4149 << Callee->getSourceRange();
4150 return ExprError();
4151 }
4152
4153 // Inspect the first argument of the atomic builtin. This should always be
4154 // a pointer type, whose element is an integral scalar or pointer type.
4155 // Because it is a pointer type, we don't have to worry about any implicit
4156 // casts here.
4157 // FIXME: We don't allow floating point scalars as input.
4158 Expr *FirstArg = TheCall->getArg(0);
4159 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4160 if (FirstArgResult.isInvalid())
4161 return ExprError();
4162 FirstArg = FirstArgResult.get();
4163 TheCall->setArg(0, FirstArg);
4164
4165 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4166 if (!pointerType) {
4167 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4168 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4169 return ExprError();
4170 }
4171
4172 QualType ValType = pointerType->getPointeeType();
4173 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4174 !ValType->isBlockPointerType()) {
4175 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4176 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4177 return ExprError();
4178 }
4179
4180 if (ValType.isConstQualified()) {
4181 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4182 << FirstArg->getType() << FirstArg->getSourceRange();
4183 return ExprError();
4184 }
4185
4186 switch (ValType.getObjCLifetime()) {
4189 // okay
4190 break;
4191
4195 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4196 << ValType << FirstArg->getSourceRange();
4197 return ExprError();
4198 }
4199
4200 // Strip any qualifiers off ValType.
4201 ValType = ValType.getUnqualifiedType();
4202
4203 // The majority of builtins return a value, but a few have special return
4204 // types, so allow them to override appropriately below.
4205 QualType ResultType = ValType;
4206
4207 // We need to figure out which concrete builtin this maps onto. For example,
4208 // __sync_fetch_and_add with a 2 byte object turns into
4209 // __sync_fetch_and_add_2.
4210#define BUILTIN_ROW(x) \
4211 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4212 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4213
4214 static const unsigned BuiltinIndices[][5] = {
4215 BUILTIN_ROW(__sync_fetch_and_add),
4216 BUILTIN_ROW(__sync_fetch_and_sub),
4217 BUILTIN_ROW(__sync_fetch_and_or),
4218 BUILTIN_ROW(__sync_fetch_and_and),
4219 BUILTIN_ROW(__sync_fetch_and_xor),
4220 BUILTIN_ROW(__sync_fetch_and_nand),
4221
4222 BUILTIN_ROW(__sync_add_and_fetch),
4223 BUILTIN_ROW(__sync_sub_and_fetch),
4224 BUILTIN_ROW(__sync_and_and_fetch),
4225 BUILTIN_ROW(__sync_or_and_fetch),
4226 BUILTIN_ROW(__sync_xor_and_fetch),
4227 BUILTIN_ROW(__sync_nand_and_fetch),
4228
4229 BUILTIN_ROW(__sync_val_compare_and_swap),
4230 BUILTIN_ROW(__sync_bool_compare_and_swap),
4231 BUILTIN_ROW(__sync_lock_test_and_set),
4232 BUILTIN_ROW(__sync_lock_release),
4233 BUILTIN_ROW(__sync_swap)
4234 };
4235#undef BUILTIN_ROW
4236
4237 // Determine the index of the size.
4238 unsigned SizeIndex;
4239 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4240 case 1: SizeIndex = 0; break;
4241 case 2: SizeIndex = 1; break;
4242 case 4: SizeIndex = 2; break;
4243 case 8: SizeIndex = 3; break;
4244 case 16: SizeIndex = 4; break;
4245 default:
4246 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4247 << FirstArg->getType() << FirstArg->getSourceRange();
4248 return ExprError();
4249 }
4250
4251 // Each of these builtins has one pointer argument, followed by some number of
4252 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4253 // that we ignore. Find out which row of BuiltinIndices to read from as well
4254 // as the number of fixed args.
4255 unsigned BuiltinID = FDecl->getBuiltinID();
4256 unsigned BuiltinIndex, NumFixed = 1;
4257 bool WarnAboutSemanticsChange = false;
4258 switch (BuiltinID) {
4259 default: llvm_unreachable("Unknown overloaded atomic builtin!");
4260 case Builtin::BI__sync_fetch_and_add:
4261 case Builtin::BI__sync_fetch_and_add_1:
4262 case Builtin::BI__sync_fetch_and_add_2:
4263 case Builtin::BI__sync_fetch_and_add_4:
4264 case Builtin::BI__sync_fetch_and_add_8:
4265 case Builtin::BI__sync_fetch_and_add_16:
4266 BuiltinIndex = 0;
4267 break;
4268
4269 case Builtin::BI__sync_fetch_and_sub:
4270 case Builtin::BI__sync_fetch_and_sub_1:
4271 case Builtin::BI__sync_fetch_and_sub_2:
4272 case Builtin::BI__sync_fetch_and_sub_4:
4273 case Builtin::BI__sync_fetch_and_sub_8:
4274 case Builtin::BI__sync_fetch_and_sub_16:
4275 BuiltinIndex = 1;
4276 break;
4277
4278 case Builtin::BI__sync_fetch_and_or:
4279 case Builtin::BI__sync_fetch_and_or_1:
4280 case Builtin::BI__sync_fetch_and_or_2:
4281 case Builtin::BI__sync_fetch_and_or_4:
4282 case Builtin::BI__sync_fetch_and_or_8:
4283 case Builtin::BI__sync_fetch_and_or_16:
4284 BuiltinIndex = 2;
4285 break;
4286
4287 case Builtin::BI__sync_fetch_and_and:
4288 case Builtin::BI__sync_fetch_and_and_1:
4289 case Builtin::BI__sync_fetch_and_and_2:
4290 case Builtin::BI__sync_fetch_and_and_4:
4291 case Builtin::BI__sync_fetch_and_and_8:
4292 case Builtin::BI__sync_fetch_and_and_16:
4293 BuiltinIndex = 3;
4294 break;
4295
4296 case Builtin::BI__sync_fetch_and_xor:
4297 case Builtin::BI__sync_fetch_and_xor_1:
4298 case Builtin::BI__sync_fetch_and_xor_2:
4299 case Builtin::BI__sync_fetch_and_xor_4:
4300 case Builtin::BI__sync_fetch_and_xor_8:
4301 case Builtin::BI__sync_fetch_and_xor_16:
4302 BuiltinIndex = 4;
4303 break;
4304
4305 case Builtin::BI__sync_fetch_and_nand:
4306 case Builtin::BI__sync_fetch_and_nand_1:
4307 case Builtin::BI__sync_fetch_and_nand_2:
4308 case Builtin::BI__sync_fetch_and_nand_4:
4309 case Builtin::BI__sync_fetch_and_nand_8:
4310 case Builtin::BI__sync_fetch_and_nand_16:
4311 BuiltinIndex = 5;
4312 WarnAboutSemanticsChange = true;
4313 break;
4314
4315 case Builtin::BI__sync_add_and_fetch:
4316 case Builtin::BI__sync_add_and_fetch_1:
4317 case Builtin::BI__sync_add_and_fetch_2:
4318 case Builtin::BI__sync_add_and_fetch_4:
4319 case Builtin::BI__sync_add_and_fetch_8:
4320 case Builtin::BI__sync_add_and_fetch_16:
4321 BuiltinIndex = 6;
4322 break;
4323
4324 case Builtin::BI__sync_sub_and_fetch:
4325 case Builtin::BI__sync_sub_and_fetch_1:
4326 case Builtin::BI__sync_sub_and_fetch_2:
4327 case Builtin::BI__sync_sub_and_fetch_4:
4328 case Builtin::BI__sync_sub_and_fetch_8:
4329 case Builtin::BI__sync_sub_and_fetch_16:
4330 BuiltinIndex = 7;
4331 break;
4332
4333 case Builtin::BI__sync_and_and_fetch:
4334 case Builtin::BI__sync_and_and_fetch_1:
4335 case Builtin::BI__sync_and_and_fetch_2:
4336 case Builtin::BI__sync_and_and_fetch_4:
4337 case Builtin::BI__sync_and_and_fetch_8:
4338 case Builtin::BI__sync_and_and_fetch_16:
4339 BuiltinIndex = 8;
4340 break;
4341
4342 case Builtin::BI__sync_or_and_fetch:
4343 case Builtin::BI__sync_or_and_fetch_1:
4344 case Builtin::BI__sync_or_and_fetch_2:
4345 case Builtin::BI__sync_or_and_fetch_4:
4346 case Builtin::BI__sync_or_and_fetch_8:
4347 case Builtin::BI__sync_or_and_fetch_16:
4348 BuiltinIndex = 9;
4349 break;
4350
4351 case Builtin::BI__sync_xor_and_fetch:
4352 case Builtin::BI__sync_xor_and_fetch_1:
4353 case Builtin::BI__sync_xor_and_fetch_2:
4354 case Builtin::BI__sync_xor_and_fetch_4:
4355 case Builtin::BI__sync_xor_and_fetch_8:
4356 case Builtin::BI__sync_xor_and_fetch_16:
4357 BuiltinIndex = 10;
4358 break;
4359
4360 case Builtin::BI__sync_nand_and_fetch:
4361 case Builtin::BI__sync_nand_and_fetch_1:
4362 case Builtin::BI__sync_nand_and_fetch_2:
4363 case Builtin::BI__sync_nand_and_fetch_4:
4364 case Builtin::BI__sync_nand_and_fetch_8:
4365 case Builtin::BI__sync_nand_and_fetch_16:
4366 BuiltinIndex = 11;
4367 WarnAboutSemanticsChange = true;
4368 break;
4369
4370 case Builtin::BI__sync_val_compare_and_swap:
4371 case Builtin::BI__sync_val_compare_and_swap_1:
4372 case Builtin::BI__sync_val_compare_and_swap_2:
4373 case Builtin::BI__sync_val_compare_and_swap_4:
4374 case Builtin::BI__sync_val_compare_and_swap_8:
4375 case Builtin::BI__sync_val_compare_and_swap_16:
4376 BuiltinIndex = 12;
4377 NumFixed = 2;
4378 break;
4379
4380 case Builtin::BI__sync_bool_compare_and_swap:
4381 case Builtin::BI__sync_bool_compare_and_swap_1:
4382 case Builtin::BI__sync_bool_compare_and_swap_2:
4383 case Builtin::BI__sync_bool_compare_and_swap_4:
4384 case Builtin::BI__sync_bool_compare_and_swap_8:
4385 case Builtin::BI__sync_bool_compare_and_swap_16:
4386 BuiltinIndex = 13;
4387 NumFixed = 2;
4388 ResultType = Context.BoolTy;
4389 break;
4390
4391 case Builtin::BI__sync_lock_test_and_set:
4392 case Builtin::BI__sync_lock_test_and_set_1:
4393 case Builtin::BI__sync_lock_test_and_set_2:
4394 case Builtin::BI__sync_lock_test_and_set_4:
4395 case Builtin::BI__sync_lock_test_and_set_8:
4396 case Builtin::BI__sync_lock_test_and_set_16:
4397 BuiltinIndex = 14;
4398 break;
4399
4400 case Builtin::BI__sync_lock_release:
4401 case Builtin::BI__sync_lock_release_1:
4402 case Builtin::BI__sync_lock_release_2:
4403 case Builtin::BI__sync_lock_release_4:
4404 case Builtin::BI__sync_lock_release_8:
4405 case Builtin::BI__sync_lock_release_16:
4406 BuiltinIndex = 15;
4407 NumFixed = 0;
4408 ResultType = Context.VoidTy;
4409 break;
4410
4411 case Builtin::BI__sync_swap:
4412 case Builtin::BI__sync_swap_1:
4413 case Builtin::BI__sync_swap_2:
4414 case Builtin::BI__sync_swap_4:
4415 case Builtin::BI__sync_swap_8:
4416 case Builtin::BI__sync_swap_16:
4417 BuiltinIndex = 16;
4418 break;
4419 }
4420
4421 // Now that we know how many fixed arguments we expect, first check that we
4422 // have at least that many.
4423 if (TheCall->getNumArgs() < 1+NumFixed) {
4424 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4425 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
4426 << Callee->getSourceRange();
4427 return ExprError();
4428 }
4429
4430 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4431 << Callee->getSourceRange();
4432
4433 if (WarnAboutSemanticsChange) {
4434 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4435 << Callee->getSourceRange();
4436 }
4437
4438 // Get the decl for the concrete builtin from this, we can tell what the
4439 // concrete integer type we should convert to is.
4440 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4441 StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4442 FunctionDecl *NewBuiltinDecl;
4443 if (NewBuiltinID == BuiltinID)
4444 NewBuiltinDecl = FDecl;
4445 else {
4446 // Perform builtin lookup to avoid redeclaring it.
4447 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4448 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4449 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4450 assert(Res.getFoundDecl());
4451 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4452 if (!NewBuiltinDecl)
4453 return ExprError();
4454 }
4455
4456 // The first argument --- the pointer --- has a fixed type; we
4457 // deduce the types of the rest of the arguments accordingly. Walk
4458 // the remaining arguments, converting them to the deduced value type.
4459 for (unsigned i = 0; i != NumFixed; ++i) {
4460 ExprResult Arg = TheCall->getArg(i+1);
4461
4462 // GCC does an implicit conversion to the pointer or integer ValType. This
4463 // can fail in some cases (1i -> int**), check for this error case now.
4464 // Initialize the argument.
4466 ValType, /*consume*/ false);
4467 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4468 if (Arg.isInvalid())
4469 return ExprError();
4470
4471 // Okay, we have something that *can* be converted to the right type. Check
4472 // to see if there is a potentially weird extension going on here. This can
4473 // happen when you do an atomic operation on something like an char* and
4474 // pass in 42. The 42 gets converted to char. This is even more strange
4475 // for things like 45.123 -> char, etc.
4476 // FIXME: Do this check.
4477 TheCall->setArg(i+1, Arg.get());
4478 }
4479
4480 // Create a new DeclRefExpr to refer to the new decl.
4482 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
4483 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
4484 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
4485
4486 // Set the callee in the CallExpr.
4487 // FIXME: This loses syntactic information.
4488 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4489 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4490 CK_BuiltinFnToFnPtr);
4491 TheCall->setCallee(PromotedCall.get());
4492
4493 // Change the result type of the call to match the original value type. This
4494 // is arbitrary, but the codegen for these builtins ins design to handle it
4495 // gracefully.
4496 TheCall->setType(ResultType);
4497
4498 // Prohibit problematic uses of bit-precise integer types with atomic
4499 // builtins. The arguments would have already been converted to the first
4500 // argument's type, so only need to check the first argument.
4501 const auto *BitIntValType = ValType->getAs<BitIntType>();
4502 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
4503 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
4504 return ExprError();
4505 }
4506
4507 return TheCallResult;
4508}
4509
4510ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4511 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4512 DeclRefExpr *DRE =
4513 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4514 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4515 unsigned BuiltinID = FDecl->getBuiltinID();
4516 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4517 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4518 "Unexpected nontemporal load/store builtin!");
4519 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4520 unsigned numArgs = isStore ? 2 : 1;
4521
4522 // Ensure that we have the proper number of arguments.
4523 if (checkArgCount(TheCall, numArgs))
4524 return ExprError();
4525
4526 // Inspect the last argument of the nontemporal builtin. This should always
4527 // be a pointer type, from which we imply the type of the memory access.
4528 // Because it is a pointer type, we don't have to worry about any implicit
4529 // casts here.
4530 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4531 ExprResult PointerArgResult =
4533
4534 if (PointerArgResult.isInvalid())
4535 return ExprError();
4536 PointerArg = PointerArgResult.get();
4537 TheCall->setArg(numArgs - 1, PointerArg);
4538
4539 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4540 if (!pointerType) {
4541 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
4542 << PointerArg->getType() << PointerArg->getSourceRange();
4543 return ExprError();
4544 }
4545
4546 QualType ValType = pointerType->getPointeeType();
4547
4548 // Strip any qualifiers off ValType.
4549 ValType = ValType.getUnqualifiedType();
4550 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4551 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4552 !ValType->isVectorType()) {
4553 Diag(DRE->getBeginLoc(),
4554 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4555 << PointerArg->getType() << PointerArg->getSourceRange();
4556 return ExprError();
4557 }
4558
4559 if (!isStore) {
4560 TheCall->setType(ValType);
4561 return TheCallResult;
4562 }
4563
4564 ExprResult ValArg = TheCall->getArg(0);
4566 Context, ValType, /*consume*/ false);
4567 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4568 if (ValArg.isInvalid())
4569 return ExprError();
4570
4571 TheCall->setArg(0, ValArg.get());
4572 TheCall->setType(Context.VoidTy);
4573 return TheCallResult;
4574}
4575
4576/// CheckObjCString - Checks that the format string argument to the os_log()
4577/// and os_trace() functions is correct, and converts it to const char *.
4578ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4579 Arg = Arg->IgnoreParenCasts();
4580 auto *Literal = dyn_cast<StringLiteral>(Arg);
4581 if (!Literal) {
4582 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4583 Literal = ObjcLiteral->getString();
4584 }
4585 }
4586
4587 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
4588 return ExprError(
4589 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
4590 << Arg->getSourceRange());
4591 }
4592
4593 ExprResult Result(Literal);
4595 InitializedEntity Entity =
4598 return Result;
4599}
4600
4601/// Check that the user is calling the appropriate va_start builtin for the
4602/// target and calling convention.
4603static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4604 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4605 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
4606 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
4607 TT.getArch() == llvm::Triple::aarch64_32);
4608 bool IsWindows = TT.isOSWindows();
4609 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4610 if (IsX64 || IsAArch64) {
4611 CallingConv CC = CC_C;
4612 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4613 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4614 if (IsMSVAStart) {
4615 // Don't allow this in System V ABI functions.
4616 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
4617 return S.Diag(Fn->getBeginLoc(),
4618 diag::err_ms_va_start_used_in_sysv_function);
4619 } else {
4620 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
4621 // On x64 Windows, don't allow this in System V ABI functions.
4622 // (Yes, that means there's no corresponding way to support variadic
4623 // System V ABI functions on Windows.)
4624 if ((IsWindows && CC == CC_X86_64SysV) ||
4625 (!IsWindows && CC == CC_Win64))
4626 return S.Diag(Fn->getBeginLoc(),
4627 diag::err_va_start_used_in_wrong_abi_function)
4628 << !IsWindows;
4629 }
4630 return false;
4631 }
4632
4633 if (IsMSVAStart)
4634 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
4635 return false;
4636}
4637
4639 ParmVarDecl **LastParam = nullptr) {
4640 // Determine whether the current function, block, or obj-c method is variadic
4641 // and get its parameter list.
4642 bool IsVariadic = false;
4644 DeclContext *Caller = S.CurContext;
4645 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4646 IsVariadic = Block->isVariadic();
4647 Params = Block->parameters();
4648 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
4649 IsVariadic = FD->isVariadic();
4650 Params = FD->parameters();
4651 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
4652 IsVariadic = MD->isVariadic();
4653 // FIXME: This isn't correct for methods (results in bogus warning).
4654 Params = MD->parameters();
4655 } else if (isa<CapturedDecl>(Caller)) {
4656 // We don't support va_start in a CapturedDecl.
4657 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
4658 return true;
4659 } else {
4660 // This must be some other declcontext that parses exprs.
4661 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
4662 return true;
4663 }
4664
4665 if (!IsVariadic) {
4666 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
4667 return true;
4668 }
4669
4670 if (LastParam)
4671 *LastParam = Params.empty() ? nullptr : Params.back();
4672
4673 return false;
4674}
4675
4676bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4677 Expr *Fn = TheCall->getCallee();
4678
4679 if (checkVAStartABI(*this, BuiltinID, Fn))
4680 return true;
4681
4682 // In C23 mode, va_start only needs one argument. However, the builtin still
4683 // requires two arguments (which matches the behavior of the GCC builtin),
4684 // <stdarg.h> passes `0` as the second argument in C23 mode.
4685 if (checkArgCount(TheCall, 2))
4686 return true;
4687
4688 // Type-check the first argument normally.
4689 if (checkBuiltinArgument(*this, TheCall, 0))
4690 return true;
4691
4692 // Check that the current function is variadic, and get its last parameter.
4693 ParmVarDecl *LastParam;
4694 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4695 return true;
4696
4697 // Verify that the second argument to the builtin is the last argument of the
4698 // current function or method. In C23 mode, if the second argument is an
4699 // integer constant expression with value 0, then we don't bother with this
4700 // check.
4701 bool SecondArgIsLastNamedArgument = false;
4702 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4703 if (std::optional<llvm::APSInt> Val =
4705 Val && LangOpts.C23 && *Val == 0)
4706 return false;
4707
4708 // These are valid if SecondArgIsLastNamedArgument is false after the next
4709 // block.
4710 QualType Type;
4711 SourceLocation ParamLoc;
4712 bool IsCRegister = false;
4713
4714 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4715 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4716 SecondArgIsLastNamedArgument = PV == LastParam;
4717
4718 Type = PV->getType();
4719 ParamLoc = PV->getLocation();
4720 IsCRegister =
4721 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4722 }
4723 }
4724
4725 if (!SecondArgIsLastNamedArgument)
4726 Diag(TheCall->getArg(1)->getBeginLoc(),
4727 diag::warn_second_arg_of_va_start_not_last_named_param);
4728 else if (IsCRegister || Type->isReferenceType() ||
4729 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4730 // Promotable integers are UB, but enumerations need a bit of
4731 // extra checking to see what their promotable type actually is.
4732 if (!Context.isPromotableIntegerType(Type))
4733 return false;
4734 if (!Type->isEnumeralType())
4735 return true;
4736 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
4737 return !(ED &&
4738 Context.typesAreCompatible(ED->getPromotionType(), Type));
4739 }()) {
4740 unsigned Reason = 0;
4741 if (Type->isReferenceType()) Reason = 1;
4742 else if (IsCRegister) Reason = 2;
4743 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
4744 Diag(ParamLoc, diag::note_parameter_type) << Type;
4745 }
4746
4747 return false;
4748}
4749
4750bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
4751 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
4752 const LangOptions &LO = getLangOpts();
4753
4754 if (LO.CPlusPlus)
4755 return Arg->getType()
4757 .getTypePtr()
4758 ->getPointeeType()
4760
4761 // In C, allow aliasing through `char *`, this is required for AArch64 at
4762 // least.
4763 return true;
4764 };
4765
4766 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4767 // const char *named_addr);
4768
4769 Expr *Func = Call->getCallee();
4770
4771 if (Call->getNumArgs() < 3)
4772 return Diag(Call->getEndLoc(),
4773 diag::err_typecheck_call_too_few_args_at_least)
4774 << 0 /*function call*/ << 3 << Call->getNumArgs()
4775 << /*is non object*/ 0;
4776
4777 // Type-check the first argument normally.
4778 if (checkBuiltinArgument(*this, Call, 0))
4779 return true;
4780
4781 // Check that the current function is variadic.
4783 return true;
4784
4785 // __va_start on Windows does not validate the parameter qualifiers
4786
4787 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4788 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4789
4790 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4791 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4792
4793 const QualType &ConstCharPtrTy =
4795 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
4796 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
4797 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
4798 << 0 /* qualifier difference */
4799 << 3 /* parameter mismatch */
4800 << 2 << Arg1->getType() << ConstCharPtrTy;
4801
4802 const QualType SizeTy = Context.getSizeType();
4803 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4804 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
4805 << Arg2->getType() << SizeTy << 1 /* different class */
4806 << 0 /* qualifier difference */
4807 << 3 /* parameter mismatch */
4808 << 3 << Arg2->getType() << SizeTy;
4809
4810 return false;
4811}
4812
4813bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
4814 if (checkArgCount(TheCall, 2))
4815 return true;
4816
4817 if (BuiltinID == Builtin::BI__builtin_isunordered &&
4818 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
4819 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
4820 << 1 << 0 << TheCall->getSourceRange();
4821
4822 ExprResult OrigArg0 = TheCall->getArg(0);
4823 ExprResult OrigArg1 = TheCall->getArg(1);
4824
4825 // Do standard promotions between the two arguments, returning their common
4826 // type.
4828 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
4829 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4830 return true;
4831
4832 // Make sure any conversions are pushed back into the call; this is
4833 // type safe since unordered compare builtins are declared as "_Bool
4834 // foo(...)".
4835 TheCall->setArg(0, OrigArg0.get());
4836 TheCall->setArg(1, OrigArg1.get());
4837
4838 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4839 return false;
4840
4841 // If the common type isn't a real floating type, then the arguments were
4842 // invalid for this operation.
4843 if (Res.isNull() || !Res->isRealFloatingType())
4844 return Diag(OrigArg0.get()->getBeginLoc(),
4845 diag::err_typecheck_call_invalid_ordered_compare)
4846 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4847 << SourceRange(OrigArg0.get()->getBeginLoc(),
4848 OrigArg1.get()->getEndLoc());
4849
4850 return false;
4851}
4852
4853bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
4854 unsigned BuiltinID) {
4855 if (checkArgCount(TheCall, NumArgs))
4856 return true;
4857
4859 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
4860 BuiltinID == Builtin::BI__builtin_isinf ||
4861 BuiltinID == Builtin::BI__builtin_isinf_sign))
4862 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
4863 << 0 << 0 << TheCall->getSourceRange();
4864
4865 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
4866 BuiltinID == Builtin::BI__builtin_isunordered))
4867 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
4868 << 1 << 0 << TheCall->getSourceRange();
4869
4870 bool IsFPClass = NumArgs == 2;
4871
4872 // Find out position of floating-point argument.
4873 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
4874
4875 // We can count on all parameters preceding the floating-point just being int.
4876 // Try all of those.
4877 for (unsigned i = 0; i < FPArgNo; ++i) {
4878 Expr *Arg = TheCall->getArg(i);
4879
4880 if (Arg->isTypeDependent())
4881 return false;
4882
4884
4885 if (Res.isInvalid())
4886 return true;
4887 TheCall->setArg(i, Res.get());
4888 }
4889
4890 Expr *OrigArg = TheCall->getArg(FPArgNo);
4891
4892 if (OrigArg->isTypeDependent())
4893 return false;
4894
4895 // Usual Unary Conversions will convert half to float, which we want for
4896 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
4897 // type how it is, but do normal L->Rvalue conversions.
4899 OrigArg = UsualUnaryConversions(OrigArg).get();
4900 else
4901 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
4902 TheCall->setArg(FPArgNo, OrigArg);
4903
4904 QualType VectorResultTy;
4905 QualType ElementTy = OrigArg->getType();
4906 // TODO: When all classification function are implemented with is_fpclass,
4907 // vector argument can be supported in all of them.
4908 if (ElementTy->isVectorType() && IsFPClass) {
4909 VectorResultTy = GetSignedVectorType(ElementTy);
4910 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
4911 }
4912
4913 // This operation requires a non-_Complex floating-point number.
4914 if (!ElementTy->isRealFloatingType())
4915 return Diag(OrigArg->getBeginLoc(),
4916 diag::err_typecheck_call_invalid_unary_fp)
4917 << OrigArg->getType() << OrigArg->getSourceRange();
4918
4919 // __builtin_isfpclass has integer parameter that specify test mask. It is
4920 // passed in (...), so it should be analyzed completely here.
4921 if (IsFPClass)
4922 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
4923 return true;
4924
4925 // TODO: enable this code to all classification functions.
4926 if (IsFPClass) {
4927 QualType ResultTy;
4928 if (!VectorResultTy.isNull())
4929 ResultTy = VectorResultTy;
4930 else
4931 ResultTy = Context.IntTy;
4932 TheCall->setType(ResultTy);
4933 }
4934
4935 return false;
4936}
4937
4938bool Sema::BuiltinComplex(CallExpr *TheCall) {
4939 if (checkArgCount(TheCall, 2))
4940 return true;
4941
4942 bool Dependent = false;
4943 for (unsigned I = 0; I != 2; ++I) {
4944 Expr *Arg = TheCall->getArg(I);
4945 QualType T = Arg->getType();
4946 if (T->isDependentType()) {
4947 Dependent = true;
4948 continue;
4949 }
4950
4951 // Despite supporting _Complex int, GCC requires a real floating point type
4952 // for the operands of __builtin_complex.
4953 if (!T->isRealFloatingType()) {
4954 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
4955 << Arg->getType() << Arg->getSourceRange();
4956 }
4957
4958 ExprResult Converted = DefaultLvalueConversion(Arg);
4959 if (Converted.isInvalid())
4960 return true;
4961 TheCall->setArg(I, Converted.get());
4962 }
4963
4964 if (Dependent) {
4965 TheCall->setType(Context.DependentTy);
4966 return false;
4967 }
4968
4969 Expr *Real = TheCall->getArg(0);
4970 Expr *Imag = TheCall->getArg(1);
4971 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
4972 return Diag(Real->getBeginLoc(),
4973 diag::err_typecheck_call_different_arg_types)
4974 << Real->getType() << Imag->getType()
4975 << Real->getSourceRange() << Imag->getSourceRange();
4976 }
4977
4978 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
4979 // don't allow this builtin to form those types either.
4980 // FIXME: Should we allow these types?
4981 if (Real->getType()->isFloat16Type())
4982 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
4983 << "_Float16";
4984 if (Real->getType()->isHalfType())
4985 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
4986 << "half";
4987
4988 TheCall->setType(Context.getComplexType(Real->getType()));
4989 return false;
4990}
4991
4992/// BuiltinShuffleVector - Handle __builtin_shufflevector.
4993// This is declared to take (...), so we have to check everything.
4995 if (TheCall->getNumArgs() < 2)
4996 return ExprError(Diag(TheCall->getEndLoc(),
4997 diag::err_typecheck_call_too_few_args_at_least)
4998 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4999 << /*is non object*/ 0 << TheCall->getSourceRange());
5000
5001 // Determine which of the following types of shufflevector we're checking:
5002 // 1) unary, vector mask: (lhs, mask)
5003 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5004 QualType resType = TheCall->getArg(0)->getType();
5005 unsigned numElements = 0;
5006
5007 if (!TheCall->getArg(0)->isTypeDependent() &&
5008 !TheCall->getArg(1)->isTypeDependent()) {
5009 QualType LHSType = TheCall->getArg(0)->getType();
5010 QualType RHSType = TheCall->getArg(1)->getType();
5011
5012 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5013 return ExprError(
5014 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5015 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
5016 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5017 TheCall->getArg(1)->getEndLoc()));
5018
5019 numElements = LHSType->castAs<VectorType>()->getNumElements();
5020 unsigned numResElements = TheCall->getNumArgs() - 2;
5021
5022 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5023 // with mask. If so, verify that RHS is an integer vector type with the
5024 // same number of elts as lhs.
5025 if (TheCall->getNumArgs() == 2) {
5026 if (!RHSType->hasIntegerRepresentation() ||
5027 RHSType->castAs<VectorType>()->getNumElements() != numElements)
5028 return ExprError(Diag(TheCall->getBeginLoc(),
5029 diag::err_vec_builtin_incompatible_vector)
5030 << TheCall->getDirectCallee()
5031 << /*isMorethantwoArgs*/ false
5032 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5033 TheCall->getArg(1)->getEndLoc()));
5034 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5035 return ExprError(Diag(TheCall->getBeginLoc(),
5036 diag::err_vec_builtin_incompatible_vector)
5037 << TheCall->getDirectCallee()
5038 << /*isMorethantwoArgs*/ false
5039 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5040 TheCall->getArg(1)->getEndLoc()));
5041 } else if (numElements != numResElements) {
5042 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5043 resType =
5044 Context.getVectorType(eltType, numResElements, VectorKind::Generic);
5045 }
5046 }
5047
5048 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5049 if (TheCall->getArg(i)->isTypeDependent() ||
5050 TheCall->getArg(i)->isValueDependent())
5051 continue;
5052
5053 std::optional<llvm::APSInt> Result;
5054 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
5055 return ExprError(Diag(TheCall->getBeginLoc(),
5056 diag::err_shufflevector_nonconstant_argument)
5057 << TheCall->getArg(i)->getSourceRange());
5058
5059 // Allow -1 which will be translated to undef in the IR.
5060 if (Result->isSigned() && Result->isAllOnes())
5061 continue;
5062
5063 if (Result->getActiveBits() > 64 ||
5064 Result->getZExtValue() >= numElements * 2)
5065 return ExprError(Diag(TheCall->getBeginLoc(),
5066 diag::err_shufflevector_argument_too_large)
5067 << TheCall->getArg(i)->getSourceRange());
5068 }
5069
5071
5072 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5073 exprs.push_back(TheCall->getArg(i));
5074 TheCall->setArg(i, nullptr);
5075 }
5076
5077 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5078 TheCall->getCallee()->getBeginLoc(),
5079 TheCall->getRParenLoc());
5080}
5081
5083 SourceLocation BuiltinLoc,
5084 SourceLocation RParenLoc) {
5087 QualType DstTy = TInfo->getType();
5088 QualType SrcTy = E->getType();
5089
5090 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5091 return ExprError(Diag(BuiltinLoc,
5092 diag::err_convertvector_non_vector)
5093 << E->getSourceRange());
5094 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5095 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5096 << "second"
5097 << "__builtin_convertvector");
5098
5099 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5100 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5101 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5102 if (SrcElts != DstElts)
5103 return ExprError(Diag(BuiltinLoc,
5104 diag::err_convertvector_incompatible_vector)
5105 << E->getSourceRange());
5106 }
5107
5108 return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
5109 BuiltinLoc, RParenLoc);
5110}
5111
5112bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5113 unsigned NumArgs = TheCall->getNumArgs();
5114
5115 if (NumArgs > 3)
5116 return Diag(TheCall->getEndLoc(),
5117 diag::err_typecheck_call_too_many_args_at_most)
5118 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5119 << TheCall->getSourceRange();
5120
5121 // Argument 0 is checked for us and the remaining arguments must be
5122 // constant integers.
5123 for (unsigned i = 1; i != NumArgs; ++i)
5124 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5125 return true;
5126
5127 return false;
5128}
5129
5130bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5132 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5133 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5134 if (checkArgCount(TheCall, 1))
5135 return true;
5136 Expr *Arg = TheCall->getArg(0);
5137 if (Arg->isInstantiationDependent())
5138 return false;
5139
5140 QualType ArgTy = Arg->getType();
5141 if (!ArgTy->hasFloatingRepresentation())
5142 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5143 << ArgTy;
5144 if (Arg->isLValue()) {
5145 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5146 TheCall->setArg(0, FirstArg.get());
5147 }
5148 TheCall->setType(TheCall->getArg(0)->getType());
5149 return false;
5150}
5151
5152bool Sema::BuiltinAssume(CallExpr *TheCall) {
5153 Expr *Arg = TheCall->getArg(0);
5154 if (Arg->isInstantiationDependent()) return false;
5155
5156 if (Arg->HasSideEffects(Context))
5157 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5158 << Arg->getSourceRange()
5159 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5160
5161 return false;
5162}
5163
5164bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5165 // The alignment must be a constant integer.
5166 Expr *Arg = TheCall->getArg(1);
5167
5168 // We can't check the value of a dependent argument.
5169 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5170 if (const auto *UE =
5171 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5172 if (UE->getKind() == UETT_AlignOf ||
5173 UE->getKind() == UETT_PreferredAlignOf)
5174 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5175 << Arg->getSourceRange();
5176
5177 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5178
5179 if (!Result.isPowerOf2())
5180 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5181 << Arg->getSourceRange();
5182
5183 if (Result < Context.getCharWidth())
5184 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5186
5187 if (Result > std::numeric_limits<int32_t>::max())
5188 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5189 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5190 }
5191
5192 return false;
5193}
5194
5195bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5196 if (checkArgCountRange(TheCall, 2, 3))
5197 return true;
5198
5199 unsigned NumArgs = TheCall->getNumArgs();
5200 Expr *FirstArg = TheCall->getArg(0);
5201
5202 {
5203 ExprResult FirstArgResult =
5205 if (checkBuiltinArgument(*this, TheCall, 0))
5206 return true;
5207 /// In-place updation of FirstArg by checkBuiltinArgument is ignored.
5208 TheCall->setArg(0, FirstArgResult.get());
5209 }
5210
5211 // The alignment must be a constant integer.
5212 Expr *SecondArg = TheCall->getArg(1);
5213
5214 // We can't check the value of a dependent argument.
5215 if (!SecondArg->isValueDependent()) {
5216 llvm::APSInt Result;
5217 if (BuiltinConstantArg(TheCall, 1, Result))
5218 return true;
5219
5220 if (!Result.isPowerOf2())
5221 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5222 << SecondArg->getSourceRange();
5223
5225 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5226 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5227 }
5228
5229 if (NumArgs > 2) {
5230 Expr *ThirdArg = TheCall->getArg(2);
5231 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5232 return true;
5233 TheCall->setArg(2, ThirdArg);
5234 }
5235
5236 return false;
5237}
5238
5239bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5240 unsigned BuiltinID =
5241 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5242 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5243
5244 unsigned NumArgs = TheCall->getNumArgs();
5245 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5246 if (NumArgs < NumRequiredArgs) {
5247 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5248 << 0 /* function call */ << NumRequiredArgs << NumArgs
5249 << /*is non object*/ 0 << TheCall->getSourceRange();
5250 }
5251 if (NumArgs >= NumRequiredArgs + 0x100) {
5252 return Diag(TheCall->getEndLoc(),
5253 diag::err_typecheck_call_too_many_args_at_most)
5254 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5255 << /*is non object*/ 0 << TheCall->getSourceRange();
5256 }
5257 unsigned i = 0;
5258
5259 // For formatting call, check buffer arg.
5260 if (!IsSizeCall) {
5261 ExprResult Arg(TheCall->getArg(i));
5263 Context, Context.VoidPtrTy, false);
5264 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5265 if (Arg.isInvalid())
5266 return true;
5267 TheCall->setArg(i, Arg.get());
5268 i++;
5269 }
5270
5271 // Check string literal arg.
5272 unsigned FormatIdx = i;
5273 {
5274 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5275 if (Arg.isInvalid())
5276 return true;
5277 TheCall->setArg(i, Arg.get());
5278 i++;
5279 }
5280
5281 // Make sure variadic args are scalar.
5282 unsigned FirstDataArg = i;
5283 while (i < NumArgs) {
5285 TheCall->getArg(i), VariadicFunction, nullptr);
5286 if (Arg.isInvalid())
5287 return true;
5288 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5289 if (ArgSize.getQuantity() >= 0x100) {
5290 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5291 << i << (int)ArgSize.getQuantity() << 0xff
5292 << TheCall->getSourceRange();
5293 }
5294 TheCall->setArg(i, Arg.get());
5295 i++;
5296 }
5297
5298 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5299 // call to avoid duplicate diagnostics.
5300 if (!IsSizeCall) {
5301 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5302 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5303 bool Success = CheckFormatArguments(
5304 Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
5306 CheckedVarArgs);
5307 if (!Success)
5308 return true;
5309 }
5310
5311 if (IsSizeCall) {
5312 TheCall->setType(Context.getSizeType());
5313 } else {
5314 TheCall->setType(Context.VoidPtrTy);
5315 }
5316 return false;
5317}
5318
5319bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5320 llvm::APSInt &Result) {
5321 Expr *Arg = TheCall->getArg(ArgNum);
5322 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5323 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5324
5325 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5326
5327 std::optional<llvm::APSInt> R;
5328 if (!(R = Arg->getIntegerConstantExpr(Context)))
5329 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5330 << FDecl->getDeclName() << Arg->getSourceRange();
5331 Result = *R;
5332 return false;
5333}
5334
5335bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
5336 int High, bool RangeIsError) {
5338 return false;
5339 llvm::APSInt Result;
5340
5341 // We can't check the value of a dependent argument.
5342 Expr *Arg = TheCall->getArg(ArgNum);
5343 if (Arg->isTypeDependent() || Arg->isValueDependent())
5344 return false;
5345
5346 // Check constant-ness first.
5347 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5348 return true;
5349
5350 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5351 if (RangeIsError)
5352 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5353 << toString(Result, 10) << Low << High << Arg->getSourceRange();
5354 else
5355 // Defer the warning until we know if the code will be emitted so that
5356 // dead code can ignore this.
5357 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5358 PDiag(diag::warn_argument_invalid_range)
5359 << toString(Result, 10) << Low << High
5360 << Arg->getSourceRange());
5361 }
5362
5363 return false;
5364}
5365
5367 unsigned Num) {
5368 llvm::APSInt Result;
5369
5370 // We can't check the value of a dependent argument.
5371 Expr *Arg = TheCall->getArg(ArgNum);
5372 if (Arg->isTypeDependent() || Arg->isValueDependent())
5373 return false;
5374
5375 // Check constant-ness first.
5376 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5377 return true;
5378
5379 if (Result.getSExtValue() % Num != 0)
5380 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5381 << Num << Arg->getSourceRange();
5382
5383 return false;
5384}
5385
5386bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
5387 llvm::APSInt Result;
5388
5389 // We can't check the value of a dependent argument.
5390 Expr *Arg = TheCall->getArg(ArgNum);
5391 if (Arg->isTypeDependent() || Arg->isValueDependent())
5392 return false;
5393
5394 // Check constant-ness first.
5395 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5396 return true;
5397
5398 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
5399 // and only if x is a power of 2.
5400 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
5401 return false;
5402
5403 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
5404 << Arg->getSourceRange();
5405}
5406
5407static bool IsShiftedByte(llvm::APSInt Value) {
5408 if (Value.isNegative())
5409 return false;
5410
5411 // Check if it's a shifted byte, by shifting it down
5412 while (true) {
5413 // If the value fits in the bottom byte, the check passes.
5414 if (Value < 0x100)
5415 return true;
5416
5417 // Otherwise, if the value has _any_ bits in the bottom byte, the check
5418 // fails.
5419 if ((Value & 0xFF) != 0)
5420 return false;
5421
5422 // If the bottom 8 bits are all 0, but something above that is nonzero,
5423 // then shifting the value right by 8 bits won't affect whether it's a
5424 // shifted byte or not. So do that, and go round again.
5425 Value >>= 8;
5426 }
5427}
5428
5430 unsigned ArgBits) {
5431 llvm::APSInt Result;
5432
5433 // We can't check the value of a dependent argument.
5434 Expr *Arg = TheCall->getArg(ArgNum);
5435 if (Arg->isTypeDependent() || Arg->isValueDependent())
5436 return false;
5437
5438 // Check constant-ness first.
5439 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5440 return true;
5441
5442 // Truncate to the given size.
5443 Result = Result.getLoBits(ArgBits);
5444 Result.setIsUnsigned(true);
5445
5446 if (IsShiftedByte(Result))
5447 return false;
5448
5449 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
5450 << Arg->getSourceRange();
5451}
5452
5454 unsigned ArgBits) {
5455 llvm::APSInt Result;
5456
5457 // We can't check the value of a dependent argument.
5458 Expr *Arg = TheCall->getArg(ArgNum);
5459 if (Arg->isTypeDependent() || Arg->isValueDependent())
5460 return false;
5461
5462 // Check constant-ness first.
5463 if (BuiltinConstantArg(TheCall, ArgNum, Result))
5464 return true;
5465
5466 // Truncate to the given size.
5467 Result = Result.getLoBits(ArgBits);
5468 Result.setIsUnsigned(true);
5469
5470 // Check to see if it's in either of the required forms.
5471 if (IsShiftedByte(Result) ||
5472 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
5473 return false;
5474
5475 return Diag(TheCall->getBeginLoc(),
5476 diag::err_argument_not_shifted_byte_or_xxff)
5477 << Arg->getSourceRange();
5478}
5479
5480bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
5482 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
5483 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5484
5485 Expr *Arg = TheCall->getArg(1);
5486 llvm::APSInt Result;
5487
5488 // TODO: This is less than ideal. Overload this to take a value.
5489 if (BuiltinConstantArg(TheCall, 1, Result))
5490 return true;
5491
5492 if (Result != 1)
5493 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
5494 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
5495
5496 return false;
5497}
5498
5499bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
5501 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
5502 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5503 return false;
5504}
5505
5506namespace {
5507
5508class UncoveredArgHandler {
5509 enum { Unknown = -1, AllCovered = -2 };
5510
5511 signed FirstUncoveredArg = Unknown;
5512 SmallVector<const Expr *, 4> DiagnosticExprs;
5513
5514public:
5515 UncoveredArgHandler() = default;
5516
5517 bool hasUncoveredArg() const {
5518 return (FirstUncoveredArg >= 0);
5519 }
5520
5521 unsigned getUncoveredArg() const {
5522 assert(hasUncoveredArg() && "no uncovered argument");
5523 return FirstUncoveredArg;
5524 }
5525
5526 void setAllCovered() {
5527 // A string has been found with all arguments covered, so clear out
5528 // the diagnostics.
5529 DiagnosticExprs.clear();
5530 FirstUncoveredArg = AllCovered;
5531 }
5532
5533 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5534 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5535
5536 // Don't update if a previous string covers all arguments.
5537 if (FirstUncoveredArg == AllCovered)
5538 return;
5539
5540 // UncoveredArgHandler tracks the highest uncovered argument index
5541 // and with it all the strings that match this index.
5542 if (NewFirstUncoveredArg == FirstUncoveredArg)
5543 DiagnosticExprs.push_back(StrExpr);
5544 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5545 DiagnosticExprs.clear();
5546 DiagnosticExprs.push_back(StrExpr);
5547 FirstUncoveredArg = NewFirstUncoveredArg;
5548 }
5549 }
5550
5551 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5552};
5553
5554enum StringLiteralCheckType {
5555 SLCT_NotALiteral,
5556 SLCT_UncheckedLiteral,
5557 SLCT_CheckedLiteral
5558};
5559
5560} // namespace
5561
5562static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5563 BinaryOperatorKind BinOpKind,
5564 bool AddendIsRight) {
5565 unsigned BitWidth = Offset.getBitWidth();
5566 unsigned AddendBitWidth = Addend.getBitWidth();
5567 // There might be negative interim results.
5568 if (Addend.isUnsigned()) {
5569 Addend = Addend.zext(++AddendBitWidth);
5570 Addend.setIsSigned(true);
5571 }
5572 // Adjust the bit width of the APSInts.
5573 if (AddendBitWidth > BitWidth) {
5574 Offset = Offset.sext(AddendBitWidth);
5575 BitWidth = AddendBitWidth;
5576 } else if (BitWidth > AddendBitWidth) {
5577 Addend = Addend.sext(BitWidth);
5578 }
5579
5580 bool Ov = false;
5581 llvm::APSInt ResOffset = Offset;
5582 if (BinOpKind == BO_Add)
5583 ResOffset = Offset.sadd_ov(Addend, Ov);
5584 else {
5585 assert(AddendIsRight && BinOpKind == BO_Sub &&
5586 "operator must be add or sub with addend on the right");
5587 ResOffset = Offset.ssub_ov(Addend, Ov);
5588 }
5589
5590 // We add an offset to a pointer here so we should support an offset as big as
5591 // possible.
5592 if (Ov) {
5593 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5594 "index (intermediate) result too big");
5595 Offset = Offset.sext(2 * BitWidth);
5596 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5597 return;
5598 }
5599
5600 Offset = ResOffset;
5601}
5602
5603namespace {
5604
5605// This is a wrapper class around StringLiteral to support offsetted string
5606// literals as format strings. It takes the offset into account when returning
5607// the string and its length or the source locations to display notes correctly.
5608class FormatStringLiteral {
5609 const StringLiteral *FExpr;
5610 int64_t Offset;
5611
5612 public:
5613 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5614 : FExpr(fexpr), Offset(Offset) {}
5615
5616 StringRef getString() const {
5617 return FExpr->getString().drop_front(Offset);
5618 }
5619
5620 unsigned getByteLength() const {
5621 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5622 }
5623
5624 unsigned getLength() const { return FExpr->getLength() - Offset; }
5625 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5626
5627 StringLiteralKind getKind() const { return FExpr->getKind(); }
5628
5629 QualType getType() const { return FExpr->getType(); }
5630
5631 bool isAscii() const { return FExpr->isOrdinary(); }
5632 bool isWide() const { return FExpr->isWide(); }
5633 bool isUTF8() const { return FExpr->isUTF8(); }
5634 bool isUTF16() const { return FExpr->isUTF16(); }
5635 bool isUTF32() const { return FExpr->isUTF32(); }
5636 bool isPascal() const { return FExpr->isPascal(); }
5637
5638 SourceLocation getLocationOfByte(
5639 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5640 const TargetInfo &Target, unsigned *StartToken = nullptr,
5641 unsigned *StartTokenByteOffset = nullptr) const {
5642 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5643 StartToken, StartTokenByteOffset);
5644 }
5645
5646 SourceLocation getBeginLoc() const LLVM_READONLY {
5647 return FExpr->getBeginLoc().getLocWithOffset(Offset);
5648 }
5649
5650 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
5651};
5652
5653} // namespace
5654
5655static void CheckFormatString(
5656 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
5658 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
5659 bool inFunctionCall, Sema::VariadicCallType CallType,
5660 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
5661 bool IgnoreStringsWithoutSpecifiers);
5662
5663static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
5664 const Expr *E);
5665
5666// Determine if an expression is a string literal or constant string.
5667// If this function returns false on the arguments to a function expecting a
5668// format string, we will usually need to emit a warning.
5669// True string literals are then checked by CheckFormatString.
5670static StringLiteralCheckType
5672 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
5673 unsigned firstDataArg, Sema::FormatStringType Type,
5674 Sema::VariadicCallType CallType, bool InFunctionCall,
5675 llvm::SmallBitVector &CheckedVarArgs,
5676 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
5677 bool IgnoreStringsWithoutSpecifiers = false) {
5679 return SLCT_NotALiteral;
5680tryAgain:
5681 assert(Offset.isSigned() && "invalid offset");
5682
5683 if (E->isTypeDependent() || E->isValueDependent())
5684 return SLCT_NotALiteral;
5685
5686 E = E->IgnoreParenCasts();
5687
5689 // Technically -Wformat-nonliteral does not warn about this case.
5690 // The behavior of printf and friends in this case is implementation
5691 // dependent. Ideally if the format string cannot be null then
5692 // it should have a 'nonnull' attribute in the function prototype.
5693 return SLCT_UncheckedLiteral;
5694
5695 switch (E->getStmtClass()) {
5696 case Stmt::InitListExprClass:
5697 // Handle expressions like {"foobar"}.
5698 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
5699 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
5700 Type, CallType, /*InFunctionCall*/ false,
5701 CheckedVarArgs, UncoveredArg, Offset,
5702 IgnoreStringsWithoutSpecifiers);
5703 }
5704 return SLCT_NotALiteral;
5705 case Stmt::BinaryConditionalOperatorClass:
5706 case Stmt::ConditionalOperatorClass: {
5707 // The expression is a literal if both sub-expressions were, and it was
5708 // completely checked only if both sub-expressions were checked.
5710 cast<AbstractConditionalOperator>(E);
5711
5712 // Determine whether it is necessary to check both sub-expressions, for
5713 // example, because the condition expression is a constant that can be
5714 // evaluated at compile time.
5715 bool CheckLeft = true, CheckRight = true;
5716
5717 bool Cond;
5718 if (C->getCond()->EvaluateAsBooleanCondition(
5719 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
5720 if (Cond)
5721 CheckRight = false;
5722 else
5723 CheckLeft = false;
5724 }
5725
5726 // We need to maintain the offsets for the right and the left hand side
5727 // separately to check if every possible indexed expression is a valid
5728 // string literal. They might have different offsets for different string
5729 // literals in the end.
5730 StringLiteralCheckType Left;
5731 if (!CheckLeft)
5732 Left = SLCT_UncheckedLiteral;
5733 else {
5734 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
5735 firstDataArg, Type, CallType, InFunctionCall,
5736 CheckedVarArgs, UncoveredArg, Offset,
5737 IgnoreStringsWithoutSpecifiers);
5738 if (Left == SLCT_NotALiteral || !CheckRight) {
5739 return Left;
5740 }
5741 }
5742
5743 StringLiteralCheckType Right = checkFormatStringExpr(
5744 S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
5745 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
5746 IgnoreStringsWithoutSpecifiers);
5747
5748 return (CheckLeft && Left < Right) ? Left : Right;
5749 }
5750
5751 case Stmt::ImplicitCastExprClass:
5752 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5753 goto tryAgain;
5754
5755 case Stmt::OpaqueValueExprClass:
5756 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5757 E = src;
5758 goto tryAgain;
5759 }
5760 return SLCT_NotALiteral;
5761
5762 case Stmt::PredefinedExprClass:
5763 // While __func__, etc., are technically not string literals, they
5764 // cannot contain format specifiers and thus are not a security
5765 // liability.
5766 return SLCT_UncheckedLiteral;
5767
5768 case Stmt::DeclRefExprClass: {
5769 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
5770
5771 // As an exception, do not flag errors for variables binding to
5772 // const string literals.
5773 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5774 bool isConstant = false;
5775 QualType T = DR->getType();
5776
5777 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5778 isConstant = AT->getElementType().isConstant(S.Context);
5779 } else if (const PointerType *PT = T->getAs<PointerType>()) {
5780 isConstant = T.isConstant(S.Context) &&
5782 } else if (T->isObjCObjectPointerType()) {
5783 // In ObjC, there is usually no "const ObjectPointer" type,
5784 // so don't check if the pointee type is constant.
5785 isConstant = T.isConstant(S.Context);
5786 }
5787
5788 if (isConstant) {
5789 if (const Expr *Init = VD->getAnyInitializer()) {
5790 // Look through initializers like const char c[] = { "foo" }
5791 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5792 if (InitList->isStringLiteralInit())
5793 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5794 }
5795 return checkFormatStringExpr(
5796 S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
5797 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
5798 }
5799 }
5800
5801 // When the format argument is an argument of this function, and this
5802 // function also has the format attribute, there are several interactions
5803 // for which there shouldn't be a warning. For instance, when calling
5804 // v*printf from a function that has the printf format attribute, we
5805 // should not emit a warning about using `fmt`, even though it's not
5806 // constant, because the arguments have already been checked for the
5807 // caller of `logmessage`:
5808 //
5809 // __attribute__((format(printf, 1, 2)))
5810 // void logmessage(char const *fmt, ...) {
5811 // va_list ap;
5812 // va_start(ap, fmt);
5813 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
5814 // ...
5815 // }
5816 //
5817 // Another interaction that we need to support is calling a variadic
5818 // format function from a format function that has fixed arguments. For
5819 // instance:
5820 //
5821 // __attribute__((format(printf, 1, 2)))
5822 // void logstring(char const *fmt, char const *str) {
5823 // printf(fmt, str); /* do not emit a warning about "fmt" */
5824 // }
5825 //
5826 // Same (and perhaps more relatably) for the variadic template case:
5827 //
5828 // template<typename... Args>
5829 // __attribute__((format(printf, 1, 2)))
5830 // void log(const char *fmt, Args&&... args) {
5831 // printf(fmt, forward<Args>(args)...);
5832 // /* do not emit a warning about "fmt" */
5833 // }
5834 //
5835 // Due to implementation difficulty, we only check the format, not the
5836 // format arguments, in all cases.
5837 //
5838 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
5839 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
5840 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
5841 bool IsCXXMember = false;
5842 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
5843 IsCXXMember = MD->isInstance();
5844
5845 bool IsVariadic = false;
5846 if (const FunctionType *FnTy = D->getFunctionType())
5847 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
5848 else if (const auto *BD = dyn_cast<BlockDecl>(D))
5849 IsVariadic = BD->isVariadic();
5850 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
5851 IsVariadic = OMD->isVariadic();
5852
5853 Sema::FormatStringInfo CallerFSI;
5854 if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
5855 &CallerFSI)) {
5856 // We also check if the formats are compatible.
5857 // We can't pass a 'scanf' string to a 'printf' function.
5858 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
5859 Type == S.GetFormatStringType(PVFormat)) {
5860 // Lastly, check that argument passing kinds transition in a
5861 // way that makes sense:
5862 // from a caller with FAPK_VAList, allow FAPK_VAList
5863 // from a caller with FAPK_Fixed, allow FAPK_Fixed
5864 // from a caller with FAPK_Fixed, allow FAPK_Variadic
5865 // from a caller with FAPK_Variadic, allow FAPK_VAList
5866 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
5871 return SLCT_UncheckedLiteral;
5872 }
5873 }
5874 }
5875 }
5876 }
5877 }
5878 }
5879
5880 return SLCT_NotALiteral;
5881 }
5882
5883 case Stmt::CallExprClass:
5884 case Stmt::CXXMemberCallExprClass: {
5885 const CallExpr *CE = cast<CallExpr>(E);
5886 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5887 bool IsFirst = true;
5888 StringLiteralCheckType CommonResult;
5889 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
5890 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5891 StringLiteralCheckType Result = checkFormatStringExpr(
5892 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
5893 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
5894 IgnoreStringsWithoutSpecifiers);
5895 if (IsFirst) {
5896 CommonResult = Result;
5897 IsFirst = false;
5898 }
5899 }
5900 if (!IsFirst)
5901 return CommonResult;
5902
5903 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
5904 unsigned BuiltinID = FD->getBuiltinID();
5905 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5906 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5907 const Expr *Arg = CE->getArg(0);
5908 return checkFormatStringExpr(
5909 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
5910 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
5911 IgnoreStringsWithoutSpecifiers);
5912 }
5913 }
5914 }
5915 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
5916 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
5917 Type, CallType, /*InFunctionCall*/ false,
5918 CheckedVarArgs, UncoveredArg, Offset,
5919 IgnoreStringsWithoutSpecifiers);
5920 return SLCT_NotALiteral;
5921 }
5922 case Stmt::ObjCMessageExprClass: {
5923 const auto *ME = cast<ObjCMessageExpr>(E);
5924 if (const auto *MD = ME->getMethodDecl()) {
5925 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
5926 // As a special case heuristic, if we're using the method -[NSBundle
5927 // localizedStringForKey:value:table:], ignore any key strings that lack
5928 // format specifiers. The idea is that if the key doesn't have any
5929 // format specifiers then its probably just a key to map to the
5930 // localized strings. If it does have format specifiers though, then its
5931 // likely that the text of the key is the format string in the
5932 // programmer's language, and should be checked.
5933 const ObjCInterfaceDecl *IFace;
5934 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
5935 IFace->getIdentifier()->isStr("NSBundle") &&
5936 MD->getSelector().isKeywordSelector(
5937 {"localizedStringForKey", "value", "table"})) {
5938 IgnoreStringsWithoutSpecifiers = true;
5939 }
5940
5941 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5942 return checkFormatStringExpr(
5943 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
5944 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
5945 IgnoreStringsWithoutSpecifiers);
5946 }
5947 }
5948
5949 return SLCT_NotALiteral;
5950 }
5951 case Stmt::ObjCStringLiteralClass:
5952 case Stmt::StringLiteralClass: {
5953 const StringLiteral *StrE = nullptr;
5954
5955 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5956 StrE = ObjCFExpr->getString();
5957 else
5958 StrE = cast<StringLiteral>(E);
5959
5960 if (StrE) {
5961 if (Offset.isNegative() || Offset > StrE->getLength()) {
5962 // TODO: It would be better to have an explicit warning for out of
5963 // bounds literals.
5964 return SLCT_NotALiteral;
5965 }
5966 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5967 CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
5968 InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
5969 IgnoreStringsWithoutSpecifiers);
5970 return SLCT_CheckedLiteral;
5971 }
5972
5973 return SLCT_NotALiteral;
5974 }
5975 case Stmt::BinaryOperatorClass: {
5976 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5977
5978 // A string literal + an int offset is still a string literal.
5979 if (BinOp->isAdditiveOp()) {
5980 Expr::EvalResult LResult, RResult;
5981
5982 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
5983 LResult, S.Context, Expr::SE_NoSideEffects,
5985 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
5986 RResult, S.Context, Expr::SE_NoSideEffects,
5988
5989 if (LIsInt != RIsInt) {
5990 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5991
5992 if (LIsInt) {
5993 if (BinOpKind == BO_Add) {
5994 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
5995 E = BinOp->getRHS();
5996 goto tryAgain;
5997 }
5998 } else {
5999 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6000 E = BinOp->getLHS();
6001 goto tryAgain;
6002 }
6003 }
6004 }
6005
6006 return SLCT_NotALiteral;
6007 }
6008 case Stmt::UnaryOperatorClass: {
6009 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6010 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6011 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6012 Expr::EvalResult IndexResult;
6013 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6016 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6017 /*RHS is int*/ true);
6018 E = ASE->getBase();
6019 goto tryAgain;
6020 }
6021 }
6022
6023 return SLCT_NotALiteral;
6024 }
6025
6026 default:
6027 return SLCT_NotALiteral;
6028 }
6029}
6030
6031// If this expression can be evaluated at compile-time,
6032// check if the result is a StringLiteral and return it
6033// otherwise return nullptr
6035 const Expr *E) {
6037 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6038 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6039 if (isa_and_nonnull<StringLiteral>(LVE))
6040 return LVE;
6041 }
6042 return nullptr;
6043}
6044
6046 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6047 .Case("scanf", FST_Scanf)
6048 .Cases("printf", "printf0", "syslog", FST_Printf)
6049 .Cases("NSString", "CFString", FST_NSString)
6050 .Case("strftime", FST_Strftime)
6051 .Case("strfmon", FST_Strfmon)
6052 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6053 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6054 .Case("os_trace", FST_OSLog)
6055 .Case("os_log", FST_OSLog)
6056 .Default(FST_Unknown);
6057}
6058
6059bool Sema::CheckFormatArguments(const FormatAttr *Format,
6060 ArrayRef<const Expr *> Args, bool IsCXXMember,
6061 VariadicCallType CallType, SourceLocation Loc,
6063 llvm::SmallBitVector &CheckedVarArgs) {
6064 FormatStringInfo FSI;
6065 if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
6066 &FSI))
6067 return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
6068 FSI.FirstDataArg, GetFormatStringType(Format),
6069 CallType, Loc, Range, CheckedVarArgs);
6070 return false;
6071}
6072
6073bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6075 unsigned format_idx, unsigned firstDataArg,
6076 FormatStringType Type,
6077 VariadicCallType CallType, SourceLocation Loc,
6079 llvm::SmallBitVector &CheckedVarArgs) {
6080 // CHECK: printf/scanf-like function is called with no format string.
6081 if (format_idx >= Args.size()) {
6082 Diag(Loc, diag::warn_missing_format_string) << Range;
6083 return false;
6084 }
6085
6086 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6087
6088 // CHECK: format string is not a string literal.
6089 //
6090 // Dynamically generated format strings are difficult to
6091 // automatically vet at compile time. Requiring that format strings
6092 // are string literals: (1) permits the checking of format strings by
6093 // the compiler and thereby (2) can practically remove the source of
6094 // many format string exploits.
6095
6096 // Format string can be either ObjC string (e.g. @"%d") or
6097 // C string (e.g. "%d")
6098 // ObjC string uses the same format specifiers as C string, so we can use
6099 // the same format string checking logic for both ObjC and C strings.
6100 UncoveredArgHandler UncoveredArg;
6101 StringLiteralCheckType CT = checkFormatStringExpr(
6102 *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
6103 CallType,
6104 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
6105 /*no string offset*/ llvm::APSInt(64, false) = 0);
6106
6107 // Generate a diagnostic where an uncovered argument is detected.
6108 if (UncoveredArg.hasUncoveredArg()) {
6109 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6110 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6111 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6112 }
6113
6114 if (CT != SLCT_NotALiteral)
6115 // Literal format string found, check done!
6116 return CT == SLCT_CheckedLiteral;
6117
6118 // Strftime is particular as it always uses a single 'time' argument,
6119 // so it is safe to pass a non-literal string.
6120 if (Type == FST_Strftime)
6121 return false;
6122
6123 // Do not emit diag when the string param is a macro expansion and the
6124 // format is either NSString or CFString. This is a hack to prevent
6125 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6126 // which are usually used in place of NS and CF string literals.
6127 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6128 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6129 return false;
6130
6131 // If there are no arguments specified, warn with -Wformat-security, otherwise
6132 // warn only with -Wformat-nonliteral.
6133 if (Args.size() == firstDataArg) {
6134 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6135 << OrigFormatExpr->getSourceRange();
6136 switch (Type) {
6137 default:
6138 break;
6139 case FST_Kprintf:
6140 case FST_FreeBSDKPrintf:
6141 case FST_Printf:
6142 case FST_Syslog:
6143 Diag(FormatLoc, diag::note_format_security_fixit)
6144 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6145 break;
6146 case FST_NSString:
6147 Diag(FormatLoc, diag::note_format_security_fixit)
6148 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6149 break;
6150 }
6151 } else {
6152 Diag(FormatLoc, diag::warn_format_nonliteral)
6153 << OrigFormatExpr->getSourceRange();
6154 }
6155 return false;
6156}
6157
6158namespace {
6159
6160class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6161protected:
6162 Sema &S;
6163 const FormatStringLiteral *FExpr;
6164 const Expr *OrigFormatExpr;
6165 const Sema::FormatStringType FSType;
6166 const unsigned FirstDataArg;
6167 const unsigned NumDataArgs;
6168 const char *Beg; // Start of format string.
6169 const Sema::FormatArgumentPassingKind ArgPassingKind;
6171 unsigned FormatIdx;
6172 llvm::SmallBitVector CoveredArgs;
6173 bool usesPositionalArgs = false;
6174 bool atFirstArg = true;
6175 bool inFunctionCall;
6176 Sema::VariadicCallType CallType;
6177 llvm::SmallBitVector &CheckedVarArgs;
6178 UncoveredArgHandler &UncoveredArg;
6179
6180public:
6181 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6182 const Expr *origFormatExpr,
6183 const Sema::FormatStringType type, unsigned firstDataArg,
6184 unsigned numDataArgs, const char *beg,
6186 ArrayRef<const Expr *> Args, unsigned formatIdx,
6187 bool inFunctionCall, Sema::VariadicCallType callType,
6188 llvm::SmallBitVector &CheckedVarArgs,
6189 UncoveredArgHandler &UncoveredArg)
6190 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6191 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6192 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
6193 inFunctionCall(inFunctionCall), CallType(callType),
6194 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6195 CoveredArgs.resize(numDataArgs);
6196 CoveredArgs.reset();
6197 }
6198
6199 void DoneProcessing();
6200
6201 void HandleIncompleteSpecifier(const char *startSpecifier,
6202 unsigned specifierLen) override;
6203
6204 void HandleInvalidLengthModifier(
6207 const char *startSpecifier, unsigned specifierLen,
6208 unsigned DiagID);
6209
6210 void HandleNonStandardLengthModifier(
6212 const char *startSpecifier, unsigned specifierLen);
6213
6214 void HandleNonStandardConversionSpecifier(
6216 const char *startSpecifier, unsigned specifierLen);
6217
6218 void HandlePosition(const char *startPos, unsigned posLen) override;
6219
6220 void HandleInvalidPosition(const char *startSpecifier,
6221 unsigned specifierLen,
6223
6224 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6225
6226 void HandleNullChar(const char *nullCharacter) override;
6227
6228 template <typename Range>
6229 static void
6230 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6231 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6232 bool IsStringLocation, Range StringRange,
6233 ArrayRef<FixItHint> Fixit = std::nullopt);
6234
6235protected:
6236 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6237 const char *startSpec,
6238 unsigned specifierLen,
6239 const char *csStart, unsigned csLen);
6240
6241 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6242 const char *startSpec,
6243 unsigned specifierLen);
6244
6245 SourceRange getFormatStringRange();
6246 CharSourceRange getSpecifierRange(const char *startSpecifier,
6247 unsigned specifierLen);
6248 SourceLocation getLocationOfByte(const char *x);
6249
6250 const Expr *getDataArg(unsigned i) const;
6251
6252 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6254 const char *startSpecifier, unsigned specifierLen,
6255 unsigned argIndex);
6256
6257 template <typename Range>
6258 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6259 bool IsStringLocation, Range StringRange,
6260 ArrayRef<FixItHint> Fixit = std::nullopt);
6261};
6262
6263} // namespace
6264
6265SourceRange CheckFormatHandler::getFormatStringRange() {
6266 return OrigFormatExpr->getSourceRange();
6267}
6268
6269CharSourceRange CheckFormatHandler::
6270getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6271 SourceLocation Start = getLocationOfByte(startSpecifier);
6272 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
6273
6274 // Advance the end SourceLocation by one due to half-open ranges.
6275 End = End.getLocWithOffset(1);
6276
6277 return CharSourceRange::getCharRange(Start, End);
6278}
6279
6280SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6281 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6283}
6284
6285void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6286 unsigned specifierLen){
6287 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6288 getLocationOfByte(startSpecifier),
6289 /*IsStringLocation*/true,
6290 getSpecifierRange(startSpecifier, specifierLen));
6291}
6292
6293void CheckFormatHandler::HandleInvalidLengthModifier(
6296 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6297 using namespace analyze_format_string;
6298
6299 const LengthModifier &LM = FS.getLengthModifier();
6300 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6301
6302 // See if we know how to fix this length modifier.
6303 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6304 if (FixedLM) {
6305 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6306 getLocationOfByte(LM.getStart()),
6307 /*IsStringLocation*/true,
6308 getSpecifierRange(startSpecifier, specifierLen));
6309
6310 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6311 << FixedLM->toString()
6312 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6313
6314 } else {
6315 FixItHint Hint;
6316 if (DiagID == diag::warn_format_nonsensical_length)
6317 Hint = FixItHint::CreateRemoval(LMRange);
6318
6319 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6320 getLocationOfByte(LM.getStart()),
6321 /*IsStringLocation*/true,
6322 getSpecifierRange(startSpecifier, specifierLen),
6323 Hint);
6324 }
6325}
6326
6327void CheckFormatHandler::HandleNonStandardLengthModifier(
6329 const char *startSpecifier, unsigned specifierLen) {
6330 using namespace analyze_format_string;
6331
6332 const LengthModifier &LM = FS.getLengthModifier();
6333 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6334
6335 // See if we know how to fix this length modifier.
6336 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6337 if (FixedLM) {
6338 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6339 << LM.toString() << 0,
6340 getLocationOfByte(LM.getStart()),
6341 /*IsStringLocation*/true,
6342 getSpecifierRange(startSpecifier, specifierLen));
6343
6344 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6345 << FixedLM->toString()
6346 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6347
6348 } else {
6349 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6350 << LM.toString() << 0,
6351 getLocationOfByte(LM.getStart()),
6352 /*IsStringLocation*/true,
6353 getSpecifierRange(startSpecifier, specifierLen));
6354 }
6355}
6356
6357void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6359 const char *startSpecifier, unsigned specifierLen) {
6360 using namespace analyze_format_string;
6361
6362 // See if we know how to fix this conversion specifier.
6363 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6364 if (FixedCS) {
6365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6366 << CS.toString() << /*conversion specifier*/1,
6367 getLocationOfByte(CS.getStart()),
6368 /*IsStringLocation*/true,
6369 getSpecifierRange(startSpecifier, specifierLen));
6370
6371 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6372 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6373 << FixedCS->toString()
6374 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6375 } else {
6376 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6377 << CS.toString() << /*conversion specifier*/1,
6378 getLocationOfByte(CS.getStart()),
6379 /*IsStringLocation*/true,
6380 getSpecifierRange(startSpecifier, specifierLen));
6381 }
6382}
6383
6384void CheckFormatHandler::HandlePosition(const char *startPos,
6385 unsigned posLen) {
6386 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6387 getLocationOfByte(startPos),
6388 /*IsStringLocation*/true,
6389 getSpecifierRange(startPos, posLen));
6390}
6391
6392void CheckFormatHandler::HandleInvalidPosition(
6393 const char *startSpecifier, unsigned specifierLen,
6395 EmitFormatDiagnostic(
6396 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
6397 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
6398 getSpecifierRange(startSpecifier, specifierLen));
6399}
6400
6401void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6402 unsigned posLen) {
6403 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6404 getLocationOfByte(startPos),
6405 /*IsStringLocation*/true,
6406 getSpecifierRange(startPos, posLen));
6407}
6408
6409void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6410 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6411 // The presence of a null character is likely an error.
6412 EmitFormatDiagnostic(
6413 S.PDiag(diag::warn_printf_format_string_contains_null_char),
6414 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6415 getFormatStringRange());
6416 }
6417}
6418
6419// Note that this may return NULL if there was an error parsing or building
6420// one of the argument expressions.
6421const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6422 return Args[FirstDataArg + i];
6423}
6424
6425void CheckFormatHandler::DoneProcessing() {
6426 // Does the number of data arguments exceed the number of
6427 // format conversions in the format string?
6428 if (ArgPassingKind != Sema::FAPK_VAList) {
6429 // Find any arguments that weren't covered.
6430 CoveredArgs.flip();
6431 signed notCoveredArg = CoveredArgs.find_first();
6432 if (notCoveredArg >= 0) {
6433 assert((unsigned)notCoveredArg < NumDataArgs);
6434 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6435 } else {
6436 UncoveredArg.setAllCovered();
6437 }
6438 }
6439}
6440
6441void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6442 const Expr *ArgExpr) {
6443 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
6444 "Invalid state");
6445
6446 if (!ArgExpr)
6447 return;
6448
6449 SourceLocation Loc = ArgExpr->getBeginLoc();
6450
6452 return;
6453
6454 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6455 for (auto E : DiagnosticExprs)
6456 PDiag << E->getSourceRange();
6457
6458 CheckFormatHandler::EmitFormatDiagnostic(
6459 S, IsFunctionCall, DiagnosticExprs[0],
6460 PDiag, Loc, /*IsStringLocation*/false,
6461 DiagnosticExprs[0]->getSourceRange());
6462}
6463
6464bool
6465CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6467 const char *startSpec,
6468 unsigned specifierLen,
6469 const char *csStart,
6470 unsigned csLen) {
6471 bool keepGoing = true;
6472 if (argIndex < NumDataArgs) {
6473 // Consider the argument coverered, even though the specifier doesn't
6474 // make sense.
6475 CoveredArgs.set(argIndex);
6476 }
6477 else {
6478 // If argIndex exceeds the number of data arguments we
6479 // don't issue a warning because that is just a cascade of warnings (and
6480 // they may have intended '%%' anyway). We don't want to continue processing
6481 // the format string after this point, however, as we will like just get
6482 // gibberish when trying to match arguments.
6483 keepGoing = false;
6484 }
6485
6486 StringRef Specifier(csStart, csLen);
6487
6488 // If the specifier in non-printable, it could be the first byte of a UTF-8
6489 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6490 // hex value.
6491 std::string CodePointStr;
6492 if (!llvm::sys::locale::isPrint(*csStart)) {
6493 llvm::UTF32 CodePoint;
6494 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6495 const llvm::UTF8 *E =
6496 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6497 llvm::ConversionResult Result =
6498 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6499
6500 if (Result != llvm::conversionOK) {
6501 unsigned char FirstChar = *csStart;
6502 CodePoint = (llvm::UTF32)FirstChar;
6503 }
6504
6505 llvm::raw_string_ostream OS(CodePointStr);
6506 if (CodePoint < 256)
6507 OS << "\\x" << llvm::format("%02x", CodePoint);
6508 else if (CodePoint <= 0xFFFF)
6509 OS << "\\u" << llvm::format("%04x", CodePoint);
6510 else
6511 OS << "\\U" << llvm::format("%08x", CodePoint);
6512 OS.flush();
6513 Specifier = CodePointStr;
6514 }
6515
6516 EmitFormatDiagnostic(
6517 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6518 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6519
6520 return keepGoing;
6521}
6522
6523void
6524CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6525 const char *startSpec,
6526 unsigned specifierLen) {
6527 EmitFormatDiagnostic(
6528 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6529 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6530}
6531
6532bool
6533CheckFormatHandler::CheckNumArgs(
6536 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6537
6538 if (argIndex >= NumDataArgs) {
6539 PartialDiagnostic PDiag = FS.usesPositionalArg()
6540 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6541 << (argIndex+1) << NumDataArgs)
6542 : S.PDiag(diag::warn_printf_insufficient_data_args);
6543 EmitFormatDiagnostic(
6544 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6545 getSpecifierRange(startSpecifier, specifierLen));
6546
6547 // Since more arguments than conversion tokens are given, by extension
6548 // all arguments are covered, so mark this as so.
6549 UncoveredArg.setAllCovered();
6550 return false;
6551 }
6552 return true;
6553}
6554
6555template<typename Range>
6556void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6558 bool IsStringLocation,
6559 Range StringRange,
6560 ArrayRef<FixItHint> FixIt) {
6561 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6562 Loc, IsStringLocation, StringRange, FixIt);
6563}
6564
6565/// If the format string is not within the function call, emit a note
6566/// so that the function call and string are in diagnostic messages.
6567///
6568/// \param InFunctionCall if true, the format string is within the function
6569/// call and only one diagnostic message will be produced. Otherwise, an
6570/// extra note will be emitted pointing to location of the format string.
6571///
6572/// \param ArgumentExpr the expression that is passed as the format string
6573/// argument in the function call. Used for getting locations when two
6574/// diagnostics are emitted.
6575///
6576/// \param PDiag the callee should already have provided any strings for the
6577/// diagnostic message. This function only adds locations and fixits
6578/// to diagnostics.
6579///
6580/// \param Loc primary location for diagnostic. If two diagnostics are
6581/// required, one will be at Loc and a new SourceLocation will be created for
6582/// the other one.
6583///
6584/// \param IsStringLocation if true, Loc points to the format string should be
6585/// used for the note. Otherwise, Loc points to the argument list and will
6586/// be used with PDiag.
6587///
6588/// \param StringRange some or all of the string to highlight. This is
6589/// templated so it can accept either a CharSourceRange or a SourceRange.
6590///
6591/// \param FixIt optional fix it hint for the format string.
6592template <typename Range>
6593void CheckFormatHandler::EmitFormatDiagnostic(
6594 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6595 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6596 Range StringRange, ArrayRef<FixItHint> FixIt) {
6597 if (InFunctionCall) {
6598 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6599 D << StringRange;
6600 D << FixIt;
6601 } else {
6602 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6603 << ArgumentExpr->getSourceRange();
6604
6606 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6607 diag::note_format_string_defined);
6608
6609 Note << StringRange;
6610 Note << FixIt;
6611 }
6612}
6613
6614//===--- CHECK: Printf format string checking -----------------------------===//
6615
6616namespace {
6617
6618class CheckPrintfHandler : public CheckFormatHandler {
6619public:
6620 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
6621 const Expr *origFormatExpr,
6622 const Sema::FormatStringType type, unsigned firstDataArg,
6623 unsigned numDataArgs, bool isObjC, const char *beg,
6625 ArrayRef<const Expr *> Args, unsigned formatIdx,
6626 bool inFunctionCall, Sema::VariadicCallType CallType,
6627 llvm::SmallBitVector &CheckedVarArgs,
6628 UncoveredArgHandler &UncoveredArg)
6629 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6630 numDataArgs, beg, APK, Args, formatIdx,
6631 inFunctionCall, CallType, CheckedVarArgs,
6632 UncoveredArg) {}
6633
6634 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6635
6636 /// Returns true if '%@' specifiers are allowed in the format string.
6637 bool allowsObjCArg() const {
6638 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6639 FSType == Sema::FST_OSTrace;
6640 }
6641
6642 bool HandleInvalidPrintfConversionSpecifier(
6644 const char *startSpecifier,
6645 unsigned specifierLen) override;
6646
6647 void handleInvalidMaskType(StringRef MaskType) override;
6648
6649 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6650 const char *startSpecifier, unsigned specifierLen,
6651 const TargetInfo &Target) override;
6652 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6653 const char *StartSpecifier,
6654 unsigned SpecifierLen,
6655 const Expr *E);
6656
6657 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6658 const char *startSpecifier, unsigned specifierLen);
6659 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6661 unsigned type,
6662 const char *startSpecifier, unsigned specifierLen);
6663 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6664 const analyze_printf::OptionalFlag &flag,
6665 const char *startSpecifier, unsigned specifierLen);
6666 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6667 const analyze_printf::OptionalFlag &ignoredFlag,
6668 const analyze_printf::OptionalFlag &flag,
6669 const char *startSpecifier, unsigned specifierLen);
6670 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
6671 const Expr *E);
6672
6673 void HandleEmptyObjCModifierFlag(const char *startFlag,
6674 unsigned flagLen) override;
6675
6676 void HandleInvalidObjCModifierFlag(const char *startFlag,
6677 unsigned flagLen) override;
6678
6679 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6680 const char *flagsEnd,
6681 const char *conversionPosition)
6682 override;
6683};
6684
6685} // namespace
6686
6687bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6689 const char *startSpecifier,
6690 unsigned specifierLen) {
6692 FS.getConversionSpecifier();
6693
6694 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6695 getLocationOfByte(CS.getStart()),
6696 startSpecifier, specifierLen,
6697 CS.getStart(), CS.getLength());
6698}
6699
6700void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
6701 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
6702}
6703
6704bool CheckPrintfHandler::HandleAmount(
6705 const analyze_format_string::OptionalAmount &Amt, unsigned k,
6706 const char *startSpecifier, unsigned specifierLen) {
6707 if (Amt.hasDataArgument()) {
6708 if (ArgPassingKind != Sema::FAPK_VAList) {
6709 unsigned argIndex = Amt.getArgIndex();
6710 if (argIndex >= NumDataArgs) {
6711 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6712 << k,
6713 getLocationOfByte(Amt.getStart()),
6714 /*IsStringLocation*/ true,
6715 getSpecifierRange(startSpecifier, specifierLen));
6716 // Don't do any more checking. We will just emit
6717 // spurious errors.
6718 return false;
6719 }
6720
6721 // Type check the data argument. It should be an 'int'.
6722 // Although not in conformance with C99, we also allow the argument to be
6723 // an 'unsigned int' as that is a reasonably safe case. GCC also
6724 // doesn't emit a warning for that case.
6725 CoveredArgs.set(argIndex);
6726 const Expr *Arg = getDataArg(argIndex);
6727 if (!Arg)
6728 return false;
6729
6730 QualType T = Arg->getType();
6731
6732 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6733 assert(AT.isValid());
6734
6735 if (!AT.matchesType(S.Context, T)) {
6736 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
6738 << T << Arg->getSourceRange(),
6739 getLocationOfByte(Amt.getStart()),
6740 /*IsStringLocation*/true,
6741 getSpecifierRange(startSpecifier, specifierLen));
6742 // Don't do any more checking. We will just emit
6743 // spurious errors.
6744 return false;
6745 }
6746 }
6747 }
6748 return true;
6749}
6750
6751void CheckPrintfHandler::HandleInvalidAmount(
6754 unsigned type,
6755 const char *startSpecifier,
6756 unsigned specifierLen) {
6758 FS.getConversionSpecifier();
6759
6760 FixItHint fixit =
6762 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6763 Amt.getConstantLength()))
6764 : FixItHint();
6765
6766 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6767 << type << CS.toString(),
6768 getLocationOfByte(Amt.getStart()),
6769 /*IsStringLocation*/true,
6770 getSpecifierRange(startSpecifier, specifierLen),
6771 fixit);
6772}
6773
6774void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6775 const analyze_printf::OptionalFlag &flag,
6776 const char *startSpecifier,
6777 unsigned specifierLen) {
6778 // Warn about pointless flag with a fixit removal.
6780 FS.getConversionSpecifier();
6781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6782 << flag.toString() << CS.toString(),
6783 getLocationOfByte(flag.getPosition()),
6784 /*IsStringLocation*/true,
6785 getSpecifierRange(startSpecifier, specifierLen),
6787 getSpecifierRange(flag.getPosition(), 1)));
6788}
6789
6790void CheckPrintfHandler::HandleIgnoredFlag(
6792 const analyze_printf::OptionalFlag &ignoredFlag,
6793 const analyze_printf::OptionalFlag &flag,
6794 const char *startSpecifier,
6795 unsigned specifierLen) {
6796 // Warn about ignored flag with a fixit removal.
6797 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6798 << ignoredFlag.toString() << flag.toString(),
6799 getLocationOfByte(ignoredFlag.getPosition()),
6800 /*IsStringLocation*/true,
6801 getSpecifierRange(startSpecifier, specifierLen),
6803 getSpecifierRange(ignoredFlag.getPosition(), 1)));
6804}
6805
6806void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6807 unsigned flagLen) {
6808 // Warn about an empty flag.
6809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6810 getLocationOfByte(startFlag),
6811 /*IsStringLocation*/true,
6812 getSpecifierRange(startFlag, flagLen));
6813}
6814
6815void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6816 unsigned flagLen) {
6817 // Warn about an invalid flag.
6818 auto Range = getSpecifierRange(startFlag, flagLen);
6819 StringRef flag(startFlag, flagLen);
6820 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6821 getLocationOfByte(startFlag),
6822 /*IsStringLocation*/true,
6824}
6825
6826void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6827 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6828 // Warn about using '[...]' without a '@' conversion.
6829 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6830 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6831 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6832 getLocationOfByte(conversionPosition),
6833 /*IsStringLocation*/true,
6835}
6836
6837// Determines if the specified is a C++ class or struct containing
6838// a member with the specified name and kind (e.g. a CXXMethodDecl named
6839// "c_str()").
6840template<typename MemberKind>
6842CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6843 const RecordType *RT = Ty->getAs<RecordType>();
6845
6846 if (!RT)
6847 return Results;
6848 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
6849 if (!RD || !RD->getDefinition())
6850 return Results;
6851
6852 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
6855
6856 // We just need to include all members of the right kind turned up by the
6857 // filter, at this point.
6858 if (S.LookupQualifiedName(R, RT->getDecl()))
6859 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6860 NamedDecl *decl = (*I)->getUnderlyingDecl();
6861 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6862 Results.insert(FK);
6863 }
6864 return Results;
6865}
6866
6867/// Check if we could call '.c_str()' on an object.
6868///
6869/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6870/// allow the call, or if it would be ambiguous).
6872 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6873
6874 MethodSet Results =
6875 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6876 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6877 MI != ME; ++MI)
6878 if ((*MI)->getMinRequiredArguments() == 0)
6879 return true;
6880 return false;
6881}
6882
6883// Check if a (w)string was passed when a (w)char* was needed, and offer a
6884// better diagnostic if so. AT is assumed to be valid.
6885// Returns true when a c_str() conversion method is found.
6886bool CheckPrintfHandler::checkForCStrMembers(
6887 const analyze_printf::ArgType &AT, const Expr *E) {
6888 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6889
6890 MethodSet Results =
6891 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6892
6893 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6894 MI != ME; ++MI) {
6895 const CXXMethodDecl *Method = *MI;
6896 if (Method->getMinRequiredArguments() == 0 &&
6897 AT.matchesType(S.Context, Method->getReturnType())) {
6898 // FIXME: Suggest parens if the expression needs them.
6900 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
6901 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6902 return true;
6903 }
6904 }
6905
6906 return false;
6907}
6908
6909bool CheckPrintfHandler::HandlePrintfSpecifier(
6910 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
6911 unsigned specifierLen, const TargetInfo &Target) {
6912 using namespace analyze_format_string;
6913 using namespace analyze_printf;
6914
6915 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6916
6917 if (FS.consumesDataArgument()) {
6918 if (atFirstArg) {
6919 atFirstArg = false;
6920 usesPositionalArgs = FS.usesPositionalArg();
6921 }
6922 else if (usesPositionalArgs != FS.usesPositionalArg()) {
6923 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6924 startSpecifier, specifierLen);
6925 return false;
6926 }
6927 }
6928
6929 // First check if the field width, precision, and conversion specifier
6930 // have matching data arguments.
6931 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6932 startSpecifier, specifierLen)) {
6933 return false;
6934 }
6935
6936 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6937 startSpecifier, specifierLen)) {
6938 return false;
6939 }
6940
6941 if (!CS.consumesDataArgument()) {
6942 // FIXME: Technically specifying a precision or field width here
6943 // makes no sense. Worth issuing a warning at some point.
6944 return true;
6945 }
6946
6947 // Consume the argument.
6948 unsigned argIndex = FS.getArgIndex();
6949 if (argIndex < NumDataArgs) {
6950 // The check to see if the argIndex is valid will come later.
6951 // We set the bit here because we may exit early from this
6952 // function if we encounter some other error.
6953 CoveredArgs.set(argIndex);
6954 }
6955
6956 // FreeBSD kernel extensions.
6957 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6958 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6959 // We need at least two arguments.
6960 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6961 return false;
6962
6963 // Claim the second argument.
6964 CoveredArgs.set(argIndex + 1);
6965
6966 // Type check the first argument (int for %b, pointer for %D)
6967 const Expr *Ex = getDataArg(argIndex);
6968 const analyze_printf::ArgType &AT =
6969 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6970 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6971 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6972 EmitFormatDiagnostic(
6973 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6974 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6975 << false << Ex->getSourceRange(),
6976 Ex->getBeginLoc(), /*IsStringLocation*/ false,
6977 getSpecifierRange(startSpecifier, specifierLen));
6978
6979 // Type check the second argument (char * for both %b and %D)
6980 Ex = getDataArg(argIndex + 1);
6981 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6982 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6983 EmitFormatDiagnostic(
6984 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6985 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6986 << false << Ex->getSourceRange(),
6987 Ex->getBeginLoc(), /*IsStringLocation*/ false,
6988 getSpecifierRange(startSpecifier, specifierLen));
6989
6990 return true;
6991 }
6992
6993 // Check for using an Objective-C specific conversion specifier
6994 // in a non-ObjC literal.
6995 if (!allowsObjCArg() && CS.isObjCArg()) {
6996 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6997 specifierLen);
6998 }
6999
7000 // %P can only be used with os_log.
7001 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7002 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7003 specifierLen);
7004 }
7005
7006 // %n is not allowed with os_log.
7007 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7008 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7009 getLocationOfByte(CS.getStart()),
7010 /*IsStringLocation*/ false,
7011 getSpecifierRange(startSpecifier, specifierLen));
7012
7013 return true;
7014 }
7015
7016 // Only scalars are allowed for os_trace.
7017 if (FSType == Sema::FST_OSTrace &&
7018 (CS.getKind() == ConversionSpecifier::PArg ||
7019 CS.getKind() == ConversionSpecifier::sArg ||
7020 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7021 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7022 specifierLen);
7023 }
7024
7025 // Check for use of public/private annotation outside of os_log().
7026 if (FSType != Sema::FST_OSLog) {
7027 if (FS.isPublic().isSet()) {
7028 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7029 << "public",
7030 getLocationOfByte(FS.isPublic().getPosition()),
7031 /*IsStringLocation*/ false,
7032 getSpecifierRange(startSpecifier, specifierLen));
7033 }
7034 if (FS.isPrivate().isSet()) {
7035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7036 << "private",
7037 getLocationOfByte(FS.isPrivate().getPosition()),
7038 /*IsStringLocation*/ false,
7039 getSpecifierRange(startSpecifier, specifierLen));
7040 }
7041 }
7042
7043 const llvm::Triple &Triple = Target.getTriple();
7044 if (CS.getKind() == ConversionSpecifier::nArg &&
7045 (Triple.isAndroid() || Triple.isOSFuchsia())) {
7046 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
7047 getLocationOfByte(CS.getStart()),
7048 /*IsStringLocation*/ false,
7049 getSpecifierRange(startSpecifier, specifierLen));
7050 }
7051
7052 // Check for invalid use of field width
7053 if (!FS.hasValidFieldWidth()) {
7054 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7055 startSpecifier, specifierLen);
7056 }
7057
7058 // Check for invalid use of precision
7059 if (!FS.hasValidPrecision()) {
7060 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7061 startSpecifier, specifierLen);
7062 }
7063
7064 // Precision is mandatory for %P specifier.
7065 if (CS.getKind() == ConversionSpecifier::PArg &&
7066 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7067 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7068 getLocationOfByte(startSpecifier),
7069 /*IsStringLocation*/ false,
7070 getSpecifierRange(startSpecifier, specifierLen));
7071 }
7072
7073 // Check each flag does not conflict with any other component.
7074 if (!FS.hasValidThousandsGroupingPrefix())
7075 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7076 if (!FS.hasValidLeadingZeros())
7077 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7078 if (!FS.hasValidPlusPrefix())
7079 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7080 if (!FS.hasValidSpacePrefix())
7081 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7082 if (!FS.hasValidAlternativeForm())
7083 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7084 if (!FS.hasValidLeftJustified())
7085 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7086
7087 // Check that flags are not ignored by another flag
7088 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7089 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7090 startSpecifier, specifierLen);
7091 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7092 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7093 startSpecifier, specifierLen);
7094
7095 // Check the length modifier is valid with the given conversion specifier.
7096 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7097 S.getLangOpts()))
7098 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7099 diag::warn_format_nonsensical_length);
7100 else if (!FS.hasStandardLengthModifier())
7101 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7102 else if (!FS.hasStandardLengthConversionCombination())
7103 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7104 diag::warn_format_non_standard_conversion_spec);
7105
7106 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7107 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7108
7109 // The remaining checks depend on the data arguments.
7110 if (ArgPassingKind == Sema::FAPK_VAList)
7111 return true;
7112
7113 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7114 return false;
7115
7116 const Expr *Arg = getDataArg(argIndex);
7117 if (!Arg)
7118 return true;
7119
7120 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7121}
7122
7123static bool requiresParensToAddCast(const Expr *E) {
7124 // FIXME: We should have a general way to reason about operator
7125 // precedence and whether parens are actually needed here.
7126 // Take care of a few common cases where they aren't.
7127 const Expr *Inside = E->IgnoreImpCasts();
7128 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7129 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7130
7131 switch (Inside->getStmtClass()) {
7132 case Stmt::ArraySubscriptExprClass:
7133 case Stmt::CallExprClass:
7134 case Stmt::CharacterLiteralClass:
7135 case Stmt::CXXBoolLiteralExprClass:
7136 case Stmt::DeclRefExprClass:
7137 case Stmt::FloatingLiteralClass:
7138 case Stmt::IntegerLiteralClass:
7139 case Stmt::MemberExprClass:
7140 case Stmt::ObjCArrayLiteralClass:
7141 case Stmt::ObjCBoolLiteralExprClass:
7142 case Stmt::ObjCBoxedExprClass:
7143 case Stmt::ObjCDictionaryLiteralClass:
7144 case Stmt::ObjCEncodeExprClass:
7145 case Stmt::ObjCIvarRefExprClass:
7146 case Stmt::ObjCMessageExprClass:
7147 case Stmt::ObjCPropertyRefExprClass:
7148 case Stmt::ObjCStringLiteralClass:
7149 case Stmt::ObjCSubscriptRefExprClass:
7150 case Stmt::ParenExprClass:
7151 case Stmt::StringLiteralClass:
7152 case Stmt::UnaryOperatorClass:
7153 return false;
7154 default:
7155 return true;
7156 }
7157}
7158
7159static std::pair<QualType, StringRef>
7161 QualType IntendedTy,
7162 const Expr *E) {
7163 // Use a 'while' to peel off layers of typedefs.
7164 QualType TyTy = IntendedTy;
7165 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7166 StringRef Name = UserTy->getDecl()->getName();
7167 QualType CastTy = llvm::StringSwitch<QualType>(Name)
7168 .Case("CFIndex", Context.getNSIntegerType())
7169 .Case("NSInteger", Context.getNSIntegerType())
7170 .Case("NSUInteger", Context.getNSUIntegerType())
7171 .Case("SInt32", Context.IntTy)
7172 .Case("UInt32", Context.UnsignedIntTy)
7173 .Default(QualType());
7174
7175 if (!CastTy.isNull())
7176 return std::make_pair(CastTy, Name);
7177
7178 TyTy = UserTy->desugar();
7179 }
7180
7181 // Strip parens if necessary.
7182 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7183 return shouldNotPrintDirectly(Context,
7184 PE->getSubExpr()->getType(),
7185 PE->getSubExpr());
7186
7187 // If this is a conditional expression, then its result type is constructed
7188 // via usual arithmetic conversions and thus there might be no necessary
7189 // typedef sugar there. Recurse to operands to check for NSInteger &
7190 // Co. usage condition.
7191 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7192 QualType TrueTy, FalseTy;
7193 StringRef TrueName, FalseName;
7194
7195 std::tie(TrueTy, TrueName) =
7196 shouldNotPrintDirectly(Context,
7197 CO->getTrueExpr()->getType(),
7198 CO->getTrueExpr());
7199 std::tie(FalseTy, FalseName) =
7200 shouldNotPrintDirectly(Context,
7201 CO->getFalseExpr()->getType(),
7202 CO->getFalseExpr());
7203
7204 if (TrueTy == FalseTy)
7205 return std::make_pair(TrueTy, TrueName);
7206 else if (TrueTy.isNull())
7207 return std::make_pair(FalseTy, FalseName);
7208 else if (FalseTy.isNull())
7209 return std::make_pair(TrueTy, TrueName);
7210 }
7211
7212 return std::make_pair(QualType(), StringRef());
7213}
7214
7215/// Return true if \p ICE is an implicit argument promotion of an arithmetic
7216/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7217/// type do not count.
7218static bool
7220 QualType From = ICE->getSubExpr()->getType();
7221 QualType To = ICE->getType();
7222 // It's an integer promotion if the destination type is the promoted
7223 // source type.
7224 if (ICE->getCastKind() == CK_IntegralCast &&
7226 S.Context.getPromotedIntegerType(From) == To)
7227 return true;
7228 // Look through vector types, since we do default argument promotion for
7229 // those in OpenCL.
7230 if (const auto *VecTy = From->getAs<ExtVectorType>())
7231 From = VecTy->getElementType();
7232 if (const auto *VecTy = To->getAs<ExtVectorType>())
7233 To = VecTy->getElementType();
7234 // It's a floating promotion if the source type is a lower rank.
7235 return ICE->getCastKind() == CK_FloatingCast &&
7236 S.Context.getFloatingTypeOrder(From, To) < 0;
7237}
7238
7243 Match =
7244 Diags.isIgnored(
7245 diag::warn_format_conversion_argument_type_mismatch_signedness, Loc)
7248 }
7249 return Match;
7250}
7251
7252bool
7253CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7254 const char *StartSpecifier,
7255 unsigned SpecifierLen,
7256 const Expr *E) {
7257 using namespace analyze_format_string;
7258 using namespace analyze_printf;
7259
7260 // Now type check the data expression that matches the
7261 // format specifier.
7262 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7263 if (!AT.isValid())
7264 return true;
7265
7266 QualType ExprTy = E->getType();
7267 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7268 ExprTy = TET->getUnderlyingExpr()->getType();
7269 }
7270
7271 // When using the format attribute in C++, you can receive a function or an
7272 // array that will necessarily decay to a pointer when passed to the final
7273 // format consumer. Apply decay before type comparison.
7274 if (ExprTy->canDecayToPointerType())
7275 ExprTy = S.Context.getDecayedType(ExprTy);
7276
7277 // Diagnose attempts to print a boolean value as a character. Unlike other
7278 // -Wformat diagnostics, this is fine from a type perspective, but it still
7279 // doesn't make sense.
7280 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
7282 const CharSourceRange &CSR =
7283 getSpecifierRange(StartSpecifier, SpecifierLen);
7284 SmallString<4> FSString;
7285 llvm::raw_svector_ostream os(FSString);
7286 FS.toString(os);
7287 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
7288 << FSString,
7289 E->getExprLoc(), false, CSR);
7290 return true;
7291 }
7292
7293 // Diagnose attempts to use '%P' with ObjC object types, which will result in
7294 // dumping raw class data (like is-a pointer), not actual data.
7295 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
7296 ExprTy->isObjCObjectPointerType()) {
7297 const CharSourceRange &CSR =
7298 getSpecifierRange(StartSpecifier, SpecifierLen);
7299 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
7300 E->getExprLoc(), false, CSR);
7301 return true;
7302 }
7303
7304 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
7305 ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
7306 ArgType::MatchKind OrigMatch = Match;
7307
7308 Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());
7309 if (Match == ArgType::Match)
7310 return true;
7311
7312 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
7313 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
7314
7315 // Look through argument promotions for our error message's reported type.
7316 // This includes the integral and floating promotions, but excludes array
7317 // and function pointer decay (seeing that an argument intended to be a
7318 // string has type 'char [6]' is probably more confusing than 'char *') and
7319 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7320 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7321 if (isArithmeticArgumentPromotion(S, ICE)) {
7322 E = ICE->getSubExpr();
7323 ExprTy = E->getType();
7324
7325 // Check if we didn't match because of an implicit cast from a 'char'
7326 // or 'short' to an 'int'. This is done because printf is a varargs
7327 // function.
7328 if (ICE->getType() == S.Context.IntTy ||
7329 ICE->getType() == S.Context.UnsignedIntTy) {
7330 // All further checking is done on the subexpression
7331 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
7332 if (OrigMatch == ArgType::NoMatchSignedness &&
7333 ImplicitMatch != ArgType::NoMatchSignedness)
7334 // If the original match was a signedness match this match on the
7335 // implicit cast type also need to be signedness match otherwise we
7336 // might introduce new unexpected warnings from -Wformat-signedness.
7337 return true;
7338 ImplicitMatch = handleFormatSignedness(
7339 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
7340 if (ImplicitMatch == ArgType::Match)
7341 return true;
7342 }
7343 }
7344 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7345 // Special case for 'a', which has type 'int' in C.
7346 // Note, however, that we do /not/ want to treat multibyte constants like
7347 // 'MooV' as characters! This form is deprecated but still exists. In
7348 // addition, don't treat expressions as of type 'char' if one byte length
7349 // modifier is provided.
7350 if (ExprTy == S.Context.IntTy &&
7351 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
7352 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
7353 ExprTy = S.Context.CharTy;
7354 // To improve check results, we consider a character literal in C
7355 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
7356 // more likely a type confusion situation, so we will suggest to
7357 // use '%hhd' instead by discarding the MatchPromotion.
7358 if (Match == ArgType::MatchPromotion)
7359 Match = ArgType::NoMatch;
7360 }
7361 }
7362 if (Match == ArgType::MatchPromotion) {
7363 // WG14 N2562 only clarified promotions in *printf
7364 // For NSLog in ObjC, just preserve -Wformat behavior
7365 if (!S.getLangOpts().ObjC &&
7366 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
7367 ImplicitMatch != ArgType::NoMatchTypeConfusion)
7368 return true;
7369 Match = ArgType::NoMatch;
7370 }
7371 if (ImplicitMatch == ArgType::NoMatchPedantic ||
7372 ImplicitMatch == ArgType::NoMatchTypeConfusion)
7373 Match = ImplicitMatch;
7374 assert(Match != ArgType::MatchPromotion);
7375
7376 // Look through unscoped enums to their underlying type.
7377 bool IsEnum = false;
7378 bool IsScopedEnum = false;
7379 QualType IntendedTy = ExprTy;
7380 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7381 IntendedTy = EnumTy->getDecl()->getIntegerType();
7382 if (EnumTy->isUnscopedEnumerationType()) {
7383 ExprTy = IntendedTy;
7384 // This controls whether we're talking about the underlying type or not,
7385 // which we only want to do when it's an unscoped enum.
7386 IsEnum = true;
7387 } else {
7388 IsScopedEnum = true;
7389 }
7390 }
7391
7392 // %C in an Objective-C context prints a unichar, not a wchar_t.
7393 // If the argument is an integer of some kind, believe the %C and suggest
7394 // a cast instead of changing the conversion specifier.
7395 if (isObjCContext() &&
7396 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7398 !ExprTy->isCharType()) {
7399 // 'unichar' is defined as a typedef of unsigned short, but we should
7400 // prefer using the typedef if it is visible.
7401 IntendedTy = S.Context.UnsignedShortTy;
7402
7403 // While we are here, check if the value is an IntegerLiteral that happens
7404 // to be within the valid range.
7405 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7406 const llvm::APInt &V = IL->getValue();
7407 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7408 return true;
7409 }
7410
7411 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7413 if (S.LookupName(Result, S.getCurScope())) {
7414 NamedDecl *ND = Result.getFoundDecl();
7415 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7416 if (TD->getUnderlyingType() == IntendedTy)
7417 IntendedTy = S.Context.getTypedefType(TD);
7418 }
7419 }
7420 }
7421
7422 // Special-case some of Darwin's platform-independence types by suggesting
7423 // casts to primitive types that are known to be large enough.
7424 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7425 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7426 QualType CastTy;
7427 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7428 if (!CastTy.isNull()) {
7429 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7430 // (long in ASTContext). Only complain to pedants or when they're the
7431 // underlying type of a scoped enum (which always needs a cast).
7432 if (!IsScopedEnum &&
7433 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7434 (AT.isSizeT() || AT.isPtrdiffT()) &&
7435 AT.matchesType(S.Context, CastTy))
7436 Match = ArgType::NoMatchPedantic;
7437 IntendedTy = CastTy;
7438 ShouldNotPrintDirectly = true;
7439 }
7440 }
7441
7442 // We may be able to offer a FixItHint if it is a supported type.
7443 PrintfSpecifier fixedFS = FS;
7444 bool Success =
7445 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7446
7447 if (Success) {
7448 // Get the fix string from the fixed format specifier
7449 SmallString<16> buf;
7450 llvm::raw_svector_ostream os(buf);
7451 fixedFS.toString(os);
7452
7453 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7454
7455 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
7456 unsigned Diag;
7457 switch (Match) {
7458 case ArgType::Match:
7459 case ArgType::MatchPromotion:
7460 case ArgType::NoMatchPromotionTypeConfusion:
7461 case ArgType::NoMatchSignedness:
7462 llvm_unreachable("expected non-matching");
7463 case ArgType::NoMatchPedantic:
7464 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7465 break;
7466 case ArgType::NoMatchTypeConfusion:
7467 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7468 break;
7469 case ArgType::NoMatch:
7470 Diag = diag::warn_format_conversion_argument_type_mismatch;
7471 break;
7472 }
7473
7474 // In this case, the specifier is wrong and should be changed to match
7475 // the argument.
7476 EmitFormatDiagnostic(S.PDiag(Diag)
7478 << IntendedTy << IsEnum << E->getSourceRange(),
7479 E->getBeginLoc(),
7480 /*IsStringLocation*/ false, SpecRange,
7481 FixItHint::CreateReplacement(SpecRange, os.str()));
7482 } else {
7483 // The canonical type for formatting this value is different from the
7484 // actual type of the expression. (This occurs, for example, with Darwin's
7485 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7486 // should be printed as 'long' for 64-bit compatibility.)
7487 // Rather than emitting a normal format/argument mismatch, we want to
7488 // add a cast to the recommended type (and correct the format string
7489 // if necessary). We should also do so for scoped enumerations.
7490 SmallString<16> CastBuf;
7491 llvm::raw_svector_ostream CastFix(CastBuf);
7492 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
7493 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7494 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
7495
7497 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
7498 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
7499 E->getExprLoc());
7500 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
7501 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7502
7503 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7504 // If there's already a cast present, just replace it.
7505 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7506 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7507
7508 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
7509 // If the expression has high enough precedence,
7510 // just write the C-style cast.
7511 Hints.push_back(
7512 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7513 } else {
7514 // Otherwise, add parens around the expression as well as the cast.
7515 CastFix << "(";
7516 Hints.push_back(
7517 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7518
7519 // We don't use getLocForEndOfToken because it returns invalid source
7520 // locations for macro expansions (by design).
7524 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7525 }
7526
7527 if (ShouldNotPrintDirectly && !IsScopedEnum) {
7528 // The expression has a type that should not be printed directly.
7529 // We extract the name from the typedef because we don't want to show
7530 // the underlying type in the diagnostic.
7531 StringRef Name;
7532 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
7533 Name = TypedefTy->getDecl()->getName();
7534 else
7535 Name = CastTyName;
7536 unsigned Diag = Match == ArgType::NoMatchPedantic
7537 ? diag::warn_format_argument_needs_cast_pedantic
7538 : diag::warn_format_argument_needs_cast;
7539 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7540 << E->getSourceRange(),
7541 E->getBeginLoc(), /*IsStringLocation=*/false,
7542 SpecRange, Hints);
7543 } else {
7544 // In this case, the expression could be printed using a different
7545 // specifier, but we've decided that the specifier is probably correct
7546 // and we should cast instead. Just use the normal warning message.
7547
7548 unsigned Diag =
7549 IsScopedEnum
7550 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7551 : diag::warn_format_conversion_argument_type_mismatch;
7552
7553 EmitFormatDiagnostic(
7554 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7555 << IsEnum << E->getSourceRange(),
7556 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7557 }
7558 }
7559 } else {
7560 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7561 SpecifierLen);
7562 // Since the warning for passing non-POD types to variadic functions
7563 // was deferred until now, we emit a warning for non-POD
7564 // arguments here.
7565 bool EmitTypeMismatch = false;
7566 switch (S.isValidVarArgType(ExprTy)) {
7567 case Sema::VAK_Valid:
7569 unsigned Diag;
7570 switch (Match) {
7571 case ArgType::Match:
7572 case ArgType::MatchPromotion:
7573 case ArgType::NoMatchPromotionTypeConfusion:
7574 case ArgType::NoMatchSignedness:
7575 llvm_unreachable("expected non-matching");
7576 case ArgType::NoMatchPedantic:
7577 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7578 break;
7579 case ArgType::NoMatchTypeConfusion:
7580 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
7581 break;
7582 case ArgType::NoMatch:
7583 Diag = diag::warn_format_conversion_argument_type_mismatch;
7584 break;
7585 }
7586
7587 EmitFormatDiagnostic(
7588 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7589 << IsEnum << CSR << E->getSourceRange(),
7590 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7591 break;
7592 }
7595 if (CallType == Sema::VariadicDoesNotApply) {
7596 EmitTypeMismatch = true;
7597 } else {
7598 EmitFormatDiagnostic(
7599 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7600 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7601 << AT.getRepresentativeTypeName(S.Context) << CSR
7602 << E->getSourceRange(),
7603 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7604 checkForCStrMembers(AT, E);
7605 }
7606 break;
7607
7608 case Sema::VAK_Invalid:
7609 if (CallType == Sema::VariadicDoesNotApply)
7610 EmitTypeMismatch = true;
7611 else if (ExprTy->isObjCObjectType())
7612 EmitFormatDiagnostic(
7613 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7614 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7615 << AT.getRepresentativeTypeName(S.Context) << CSR
7616 << E->getSourceRange(),
7617 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7618 else
7619 // FIXME: If this is an initializer list, suggest removing the braces
7620 // or inserting a cast to the target type.
7621 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7622 << isa<InitListExpr>(E) << ExprTy << CallType
7624 break;
7625 }
7626
7627 if (EmitTypeMismatch) {
7628 // The function is not variadic, so we do not generate warnings about
7629 // being allowed to pass that object as a variadic argument. Instead,
7630 // since there are inherently no printf specifiers for types which cannot
7631 // be passed as variadic arguments, emit a plain old specifier mismatch
7632 // argument.
7633 EmitFormatDiagnostic(
7634 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7635 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
7636 << E->getSourceRange(),
7637 E->getBeginLoc(), false, CSR);
7638 }
7639
7640 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7641 "format string specifier index out of range");
7642 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7643 }
7644
7645 return true;
7646}
7647
7648//===--- CHECK: Scanf format string checking ------------------------------===//
7649
7650namespace {
7651
7652class CheckScanfHandler : public CheckFormatHandler {
7653public:
7654 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7655 const Expr *origFormatExpr, Sema::FormatStringType type,
7656 unsigned firstDataArg, unsigned numDataArgs,
7657 const char *beg, Sema::FormatArgumentPassingKind APK,
7658 ArrayRef<const Expr *> Args, unsigned formatIdx,
7659 bool inFunctionCall, Sema::VariadicCallType CallType,
7660 llvm::SmallBitVector &CheckedVarArgs,
7661 UncoveredArgHandler &UncoveredArg)
7662 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7663 numDataArgs, beg, APK, Args, formatIdx,
7664 inFunctionCall, CallType, CheckedVarArgs,
7665 UncoveredArg) {}
7666
7667 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7668 const char *startSpecifier,
7669 unsigned specifierLen) override;
7670
7671 bool HandleInvalidScanfConversionSpecifier(
7673 const char *startSpecifier,
7674 unsigned specifierLen) override;
7675
7676 void HandleIncompleteScanList(const char *start, const char *end) override;
7677};
7678
7679} // namespace
7680
7681void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7682 const char *end) {
7683 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7684 getLocationOfByte(end), /*IsStringLocation*/true,
7685 getSpecifierRange(start, end - start));
7686}
7687
7688bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7690 const char *startSpecifier,
7691 unsigned specifierLen) {
7693 FS.getConversionSpecifier();
7694
7695 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7696 getLocationOfByte(CS.getStart()),
7697 startSpecifier, specifierLen,
7698 CS.getStart(), CS.getLength());
7699}
7700
7701bool CheckScanfHandler::HandleScanfSpecifier(
7703 const char *startSpecifier,
7704 unsigned specifierLen) {
7705 using namespace analyze_scanf;
7706 using namespace analyze_format_string;
7707
7708 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
7709
7710 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7711 // be used to decide if we are using positional arguments consistently.
7712 if (FS.consumesDataArgument()) {
7713 if (atFirstArg) {
7714 atFirstArg = false;
7715 usesPositionalArgs = FS.usesPositionalArg();
7716 }
7717 else if (usesPositionalArgs != FS.usesPositionalArg()) {
7718 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7719 startSpecifier, specifierLen);
7720 return false;
7721 }
7722 }
7723
7724 // Check if the field with is non-zero.
7725 const OptionalAmount &Amt = FS.getFieldWidth();
7726 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7727 if (Amt.getConstantAmount() == 0) {
7728 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7729 Amt.getConstantLength());
7730 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7731 getLocationOfByte(Amt.getStart()),
7732 /*IsStringLocation*/true, R,
7734 }
7735 }
7736
7737 if (!FS.consumesDataArgument()) {
7738 // FIXME: Technically specifying a precision or field width here
7739 // makes no sense. Worth issuing a warning at some point.
7740 return true;
7741 }
7742
7743 // Consume the argument.
7744 unsigned argIndex = FS.getArgIndex();
7745 if (argIndex < NumDataArgs) {
7746 // The check to see if the argIndex is valid will come later.
7747 // We set the bit here because we may exit early from this
7748 // function if we encounter some other error.
7749 CoveredArgs.set(argIndex);
7750 }
7751
7752 // Check the length modifier is valid with the given conversion specifier.
7753 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7754 S.getLangOpts()))
7755 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7756 diag::warn_format_nonsensical_length);
7757 else if (!FS.hasStandardLengthModifier())
7758 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7759 else if (!FS.hasStandardLengthConversionCombination())
7760 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7761 diag::warn_format_non_standard_conversion_spec);
7762
7763 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7764 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7765
7766 // The remaining checks depend on the data arguments.
7767 if (ArgPassingKind == Sema::FAPK_VAList)
7768 return true;
7769
7770 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7771 return false;
7772
7773 // Check that the argument type matches the format specifier.
7774 const Expr *Ex = getDataArg(argIndex);
7775 if (!Ex)
7776 return true;
7777
7778 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
7779
7780 if (!AT.isValid()) {
7781 return true;
7782 }
7783
7785 AT.matchesType(S.Context, Ex->getType());
7786 Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());
7789 return true;
7790
7791 ScanfSpecifier fixedFS = FS;
7792 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7793 S.getLangOpts(), S.Context);
7794
7795 unsigned Diag =
7796 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7797 : diag::warn_format_conversion_argument_type_mismatch;
7798
7799 if (Success) {
7800 // Get the fix string from the fixed format specifier.
7801 SmallString<128> buf;
7802 llvm::raw_svector_ostream os(buf);
7803 fixedFS.toString(os);
7804
7805 EmitFormatDiagnostic(
7807 << Ex->getType() << false << Ex->getSourceRange(),
7808 Ex->getBeginLoc(),
7809 /*IsStringLocation*/ false,
7810 getSpecifierRange(startSpecifier, specifierLen),
7812 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7813 } else {
7814 EmitFormatDiagnostic(S.PDiag(Diag)
7816 << Ex->getType() << false << Ex->getSourceRange(),
7817 Ex->getBeginLoc(),
7818 /*IsStringLocation*/ false,
7819 getSpecifierRange(startSpecifier, specifierLen));
7820 }
7821
7822 return true;
7823}
7824
7826 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
7828 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
7829 bool inFunctionCall, Sema::VariadicCallType CallType,
7830 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7831 bool IgnoreStringsWithoutSpecifiers) {
7832 // CHECK: is the format string a wide literal?
7833 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
7834 CheckFormatHandler::EmitFormatDiagnostic(
7835 S, inFunctionCall, Args[format_idx],
7836 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
7837 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
7838 return;
7839 }
7840
7841 // Str - The format string. NOTE: this is NOT null-terminated!
7842 StringRef StrRef = FExpr->getString();
7843 const char *Str = StrRef.data();
7844 // Account for cases where the string literal is truncated in a declaration.
7845 const ConstantArrayType *T =
7846 S.Context.getAsConstantArrayType(FExpr->getType());
7847 assert(T && "String literal not of constant array type!");
7848 size_t TypeSize = T->getZExtSize();
7849 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7850 const unsigned numDataArgs = Args.size() - firstDataArg;
7851
7852 if (IgnoreStringsWithoutSpecifiers &&
7854 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
7855 return;
7856
7857 // Emit a warning if the string literal is truncated and does not contain an
7858 // embedded null character.
7859 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
7860 CheckFormatHandler::EmitFormatDiagnostic(
7861 S, inFunctionCall, Args[format_idx],
7862 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
7863 FExpr->getBeginLoc(),
7864 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7865 return;
7866 }
7867
7868 // CHECK: empty format string?
7869 if (StrLen == 0 && numDataArgs > 0) {
7870 CheckFormatHandler::EmitFormatDiagnostic(
7871 S, inFunctionCall, Args[format_idx],
7872 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
7873 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
7874 return;
7875 }
7876
7880 CheckPrintfHandler H(
7881 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7882 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
7883 Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
7884 UncoveredArg);
7885
7887 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
7889 H.DoneProcessing();
7890 } else if (Type == Sema::FST_Scanf) {
7891 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7892 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
7893 CallType, CheckedVarArgs, UncoveredArg);
7894
7896 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
7897 H.DoneProcessing();
7898 } // TODO: handle other formats
7899}
7900
7902 // Str - The format string. NOTE: this is NOT null-terminated!
7903 StringRef StrRef = FExpr->getString();
7904 const char *Str = StrRef.data();
7905 // Account for cases where the string literal is truncated in a declaration.
7907 assert(T && "String literal not of constant array type!");
7908 size_t TypeSize = T->getZExtSize();
7909 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7910 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7911 getLangOpts(),
7913}
7914
7915//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7916
7917// Returns the related absolute value function that is larger, of 0 if one
7918// does not exist.
7919static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7920 switch (AbsFunction) {
7921 default:
7922 return 0;
7923
7924 case Builtin::BI__builtin_abs:
7925 return Builtin::BI__builtin_labs;
7926 case Builtin::BI__builtin_labs:
7927 return Builtin::BI__builtin_llabs;
7928 case Builtin::BI__builtin_llabs:
7929 return 0;
7930
7931 case Builtin::BI__builtin_fabsf:
7932 return Builtin::BI__builtin_fabs;
7933 case Builtin::BI__builtin_fabs:
7934 return Builtin::BI__builtin_fabsl;
7935 case Builtin::BI__builtin_fabsl:
7936 return 0;
7937
7938 case Builtin::BI__builtin_cabsf:
7939 return Builtin::BI__builtin_cabs;
7940 case Builtin::BI__builtin_cabs:
7941 return Builtin::BI__builtin_cabsl;
7942 case Builtin::BI__builtin_cabsl:
7943 return 0;
7944
7945 case Builtin::BIabs:
7946 return Builtin::BIlabs;
7947 case Builtin::BIlabs:
7948 return Builtin::BIllabs;
7949 case Builtin::BIllabs:
7950 return 0;
7951
7952 case Builtin::BIfabsf:
7953 return Builtin::BIfabs;
7954 case Builtin::BIfabs:
7955 return Builtin::BIfabsl;
7956 case Builtin::BIfabsl:
7957 return 0;
7958
7959 case Builtin::BIcabsf:
7960 return Builtin::BIcabs;
7961 case Builtin::BIcabs:
7962 return Builtin::BIcabsl;
7963 case Builtin::BIcabsl:
7964 return 0;
7965 }
7966}
7967
7968// Returns the argument type of the absolute value function.
7970 unsigned AbsType) {
7971 if (AbsType == 0)
7972 return QualType();
7973
7975 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7976 if (Error != ASTContext::GE_None)
7977 return QualType();
7978
7980 if (!FT)
7981 return QualType();
7982
7983 if (FT->getNumParams() != 1)
7984 return QualType();
7985
7986 return FT->getParamType(0);
7987}
7988
7989// Returns the best absolute value function, or zero, based on type and
7990// current absolute value function.
7991static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7992 unsigned AbsFunctionKind) {
7993 unsigned BestKind = 0;
7994 uint64_t ArgSize = Context.getTypeSize(ArgType);
7995 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7996 Kind = getLargerAbsoluteValueFunction(Kind)) {
7997 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7998 if (Context.getTypeSize(ParamType) >= ArgSize) {
7999 if (BestKind == 0)
8000 BestKind = Kind;
8001 else if (Context.hasSameType(ParamType, ArgType)) {
8002 BestKind = Kind;
8003 break;
8004 }
8005 }
8006 }
8007 return BestKind;
8008}
8009
8015
8018 return AVK_Integer;
8019 if (T->isRealFloatingType())
8020 return AVK_Floating;
8021 if (T->isAnyComplexType())
8022 return AVK_Complex;
8023
8024 llvm_unreachable("Type not integer, floating, or complex");
8025}
8026
8027// Changes the absolute value function to a different type. Preserves whether
8028// the function is a builtin.
8029static unsigned changeAbsFunction(unsigned AbsKind,
8030 AbsoluteValueKind ValueKind) {
8031 switch (ValueKind) {
8032 case AVK_Integer:
8033 switch (AbsKind) {
8034 default:
8035 return 0;
8036 case Builtin::BI__builtin_fabsf:
8037 case Builtin::BI__builtin_fabs:
8038 case Builtin::BI__builtin_fabsl:
8039 case Builtin::BI__builtin_cabsf:
8040 case Builtin::BI__builtin_cabs:
8041 case Builtin::BI__builtin_cabsl:
8042 return Builtin::BI__builtin_abs;
8043 case Builtin::BIfabsf:
8044 case Builtin::BIfabs:
8045 case Builtin::BIfabsl:
8046 case Builtin::BIcabsf:
8047 case Builtin::BIcabs:
8048 case Builtin::BIcabsl:
8049 return Builtin::BIabs;
8050 }
8051 case AVK_Floating:
8052 switch (AbsKind) {
8053 default:
8054 return 0;
8055 case Builtin::BI__builtin_abs:
8056 case Builtin::BI__builtin_labs:
8057 case Builtin::BI__builtin_llabs:
8058 case Builtin::BI__builtin_cabsf:
8059 case Builtin::BI__builtin_cabs:
8060 case Builtin::BI__builtin_cabsl:
8061 return Builtin::BI__builtin_fabsf;
8062 case Builtin::BIabs:
8063 case Builtin::BIlabs:
8064 case Builtin::BIllabs:
8065 case Builtin::BIcabsf:
8066 case Builtin::BIcabs:
8067 case Builtin::BIcabsl:
8068 return Builtin::BIfabsf;
8069 }
8070 case AVK_Complex:
8071 switch (AbsKind) {
8072 default:
8073 return 0;
8074 case Builtin::BI__builtin_abs:
8075 case Builtin::BI__builtin_labs:
8076 case Builtin::BI__builtin_llabs:
8077 case Builtin::BI__builtin_fabsf:
8078 case Builtin::BI__builtin_fabs:
8079 case Builtin::BI__builtin_fabsl:
8080 return Builtin::BI__builtin_cabsf;
8081 case Builtin::BIabs:
8082 case Builtin::BIlabs:
8083 case Builtin::BIllabs:
8084 case Builtin::BIfabsf:
8085 case Builtin::BIfabs:
8086 case Builtin::BIfabsl:
8087 return Builtin::BIcabsf;
8088 }
8089 }
8090 llvm_unreachable("Unable to convert function");
8091}
8092
8093static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8094 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8095 if (!FnInfo)
8096 return 0;
8097
8098 switch (FDecl->getBuiltinID()) {
8099 default:
8100 return 0;
8101 case Builtin::BI__builtin_abs:
8102 case Builtin::BI__builtin_fabs:
8103 case Builtin::BI__builtin_fabsf:
8104 case Builtin::BI__builtin_fabsl:
8105 case Builtin::BI__builtin_labs:
8106 case Builtin::BI__builtin_llabs:
8107 case Builtin::BI__builtin_cabs:
8108 case Builtin::BI__builtin_cabsf:
8109 case Builtin::BI__builtin_cabsl:
8110 case Builtin::BIabs:
8111 case Builtin::BIlabs:
8112 case Builtin::BIllabs:
8113 case Builtin::BIfabs:
8114 case Builtin::BIfabsf:
8115 case Builtin::BIfabsl:
8116 case Builtin::BIcabs:
8117 case Builtin::BIcabsf:
8118 case Builtin::BIcabsl:
8119 return FDecl->getBuiltinID();
8120 }
8121 llvm_unreachable("Unknown Builtin type");
8122}
8123
8124// If the replacement is valid, emit a note with replacement function.
8125// Additionally, suggest including the proper header if not already included.
8127 unsigned AbsKind, QualType ArgType) {
8128 bool EmitHeaderHint = true;
8129 const char *HeaderName = nullptr;
8130 StringRef FunctionName;
8131 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8132 FunctionName = "std::abs";
8133 if (ArgType->isIntegralOrEnumerationType()) {
8134 HeaderName = "cstdlib";
8135 } else if (ArgType->isRealFloatingType()) {
8136 HeaderName = "cmath";
8137 } else {
8138 llvm_unreachable("Invalid Type");
8139 }
8140
8141 // Lookup all std::abs
8142 if (NamespaceDecl *Std = S.getStdNamespace()) {
8146
8147 for (const auto *I : R) {
8148 const FunctionDecl *FDecl = nullptr;
8149 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8150 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8151 } else {
8152 FDecl = dyn_cast<FunctionDecl>(I);
8153 }
8154 if (!FDecl)
8155 continue;
8156
8157 // Found std::abs(), check that they are the right ones.
8158 if (FDecl->getNumParams() != 1)
8159 continue;
8160
8161 // Check that the parameter type can handle the argument.
8162 QualType ParamType = FDecl->getParamDecl(0)->getType();
8163 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8164 S.Context.getTypeSize(ArgType) <=
8165 S.Context.getTypeSize(ParamType)) {
8166 // Found a function, don't need the header hint.
8167 EmitHeaderHint = false;
8168 break;
8169 }
8170 }
8171 }
8172 } else {
8173 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8174 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8175
8176 if (HeaderName) {
8177 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8180 S.LookupName(R, S.getCurScope());
8181
8182 if (R.isSingleResult()) {
8183 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8184 if (FD && FD->getBuiltinID() == AbsKind) {
8185 EmitHeaderHint = false;
8186 } else {
8187 return;
8188 }
8189 } else if (!R.empty()) {
8190 return;
8191 }
8192 }
8193 }
8194
8195 S.Diag(Loc, diag::note_replace_abs_function)
8196 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8197
8198 if (!HeaderName)
8199 return;
8200
8201 if (!EmitHeaderHint)
8202 return;
8203
8204 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8205 << FunctionName;
8206}
8207
8208template <std::size_t StrLen>
8209static bool IsStdFunction(const FunctionDecl *FDecl,
8210 const char (&Str)[StrLen]) {
8211 if (!FDecl)
8212 return false;
8213 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8214 return false;
8215 if (!FDecl->isInStdNamespace())
8216 return false;
8217
8218 return true;
8219}
8220
8221enum class MathCheck { NaN, Inf };
8222static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
8223 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
8224 return std::any_of(names.begin(), names.end(), [&](llvm::StringRef name) {
8225 return calleeName == name;
8226 });
8227 };
8228
8229 switch (Check) {
8230 case MathCheck::NaN:
8231 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
8232 "__builtin_nanf16", "__builtin_nanf128"});
8233 case MathCheck::Inf:
8234 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
8235 "__builtin_inff16", "__builtin_inff128"});
8236 }
8237 llvm_unreachable("unknown MathCheck");
8238}
8239
8240void Sema::CheckInfNaNFunction(const CallExpr *Call,
8241 const FunctionDecl *FDecl) {
8242 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
8243 bool HasIdentifier = FDecl->getIdentifier() != nullptr;
8244 bool IsNaNOrIsUnordered =
8245 IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered");
8246 bool IsSpecialNaN =
8247 HasIdentifier && IsInfOrNanFunction(FDecl->getName(), MathCheck::NaN);
8248 if ((IsNaNOrIsUnordered || IsSpecialNaN) && FPO.getNoHonorNaNs()) {
8249 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8250 << 1 << 0 << Call->getSourceRange();
8251 } else {
8252 bool IsInfOrIsFinite =
8253 IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite");
8254 bool IsInfinityOrIsSpecialInf =
8255 HasIdentifier && ((FDecl->getName() == "infinity") ||
8256 IsInfOrNanFunction(FDecl->getName(), MathCheck::Inf));
8257 if ((IsInfOrIsFinite || IsInfinityOrIsSpecialInf) && FPO.getNoHonorInfs())
8258 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
8259 << 0 << 0 << Call->getSourceRange();
8260 }
8261}
8262
8263void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8264 const FunctionDecl *FDecl) {
8265 if (Call->getNumArgs() != 1)
8266 return;
8267
8268 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8269 bool IsStdAbs = IsStdFunction(FDecl, "abs");
8270 if (AbsKind == 0 && !IsStdAbs)
8271 return;
8272
8273 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8274 QualType ParamType = Call->getArg(0)->getType();
8275
8276 // Unsigned types cannot be negative. Suggest removing the absolute value
8277 // function call.
8278 if (ArgType->isUnsignedIntegerType()) {
8279 StringRef FunctionName =
8280 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8281 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8282 Diag(Call->getExprLoc(), diag::note_remove_abs)
8283 << FunctionName
8284 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8285 return;
8286 }
8287
8288 // Taking the absolute value of a pointer is very suspicious, they probably
8289 // wanted to index into an array, dereference a pointer, call a function, etc.
8290 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8291 unsigned DiagType = 0;
8292 if (ArgType->isFunctionType())
8293 DiagType = 1;
8294 else if (ArgType->isArrayType())
8295 DiagType = 2;
8296
8297 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8298 return;
8299 }
8300
8301 // std::abs has overloads which prevent most of the absolute value problems
8302 // from occurring.
8303 if (IsStdAbs)
8304 return;
8305
8306 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8307 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8308
8309 // The argument and parameter are the same kind. Check if they are the right
8310 // size.
8311 if (ArgValueKind == ParamValueKind) {
8312 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8313 return;
8314
8315 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8316 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8317 << FDecl << ArgType << ParamType;
8318
8319 if (NewAbsKind == 0)
8320 return;
8321
8322 emitReplacement(*this, Call->getExprLoc(),
8323 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8324 return;
8325 }
8326
8327 // ArgValueKind != ParamValueKind
8328 // The wrong type of absolute value function was used. Attempt to find the
8329 // proper one.
8330 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8331 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8332 if (NewAbsKind == 0)
8333 return;
8334
8335 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8336 << FDecl << ParamValueKind << ArgValueKind;
8337
8338 emitReplacement(*this, Call->getExprLoc(),
8339 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8340}
8341
8342//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8343void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8344 const FunctionDecl *FDecl) {
8345 if (!Call || !FDecl) return;
8346
8347 // Ignore template specializations and macros.
8348 if (inTemplateInstantiation()) return;
8349 if (Call->getExprLoc().isMacroID()) return;
8350
8351 // Only care about the one template argument, two function parameter std::max
8352 if (Call->getNumArgs() != 2) return;
8353 if (!IsStdFunction(FDecl, "max")) return;
8354 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8355 if (!ArgList) return;
8356 if (ArgList->size() != 1) return;
8357
8358 // Check that template type argument is unsigned integer.
8359 const auto& TA = ArgList->get(0);
8360 if (TA.getKind() != TemplateArgument::Type) return;
8361 QualType ArgType = TA.getAsType();
8362 if (!ArgType->isUnsignedIntegerType()) return;
8363
8364 // See if either argument is a literal zero.
8365 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8366 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8367 if (!MTE) return false;
8368 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
8369 if (!Num) return false;
8370 if (Num->getValue() != 0) return false;
8371 return true;
8372 };
8373
8374 const Expr *FirstArg = Call->getArg(0);
8375 const Expr *SecondArg = Call->getArg(1);
8376 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8377 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8378
8379 // Only warn when exactly one argument is zero.
8380 if (IsFirstArgZero == IsSecondArgZero) return;
8381
8382 SourceRange FirstRange = FirstArg->getSourceRange();
8383 SourceRange SecondRange = SecondArg->getSourceRange();
8384
8385 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8386
8387 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8388 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8389
8390 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8391 SourceRange RemovalRange;
8392 if (IsFirstArgZero) {
8393 RemovalRange = SourceRange(FirstRange.getBegin(),
8394 SecondRange.getBegin().getLocWithOffset(-1));
8395 } else {
8396 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8397 SecondRange.getEnd());
8398 }
8399
8400 Diag(Call->getExprLoc(), diag::note_remove_max_call)
8401 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8402 << FixItHint::CreateRemoval(RemovalRange);
8403}
8404
8405//===--- CHECK: Standard memory functions ---------------------------------===//
8406
8407/// Takes the expression passed to the size_t parameter of functions
8408/// such as memcmp, strncat, etc and warns if it's a comparison.
8409///
8410/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8412 IdentifierInfo *FnName,
8413 SourceLocation FnLoc,
8414 SourceLocation RParenLoc) {
8415 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8416 if (!Size)
8417 return false;
8418
8419 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8420 if (!Size->isComparisonOp() && !Size->isLogicalOp())
8421 return false;
8422
8423 SourceRange SizeRange = Size->getSourceRange();
8424 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8425 << SizeRange << FnName;
8426 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8427 << FnName
8429 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8430 << FixItHint::CreateRemoval(RParenLoc);
8431 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8432 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8434 ")");
8435
8436 return true;
8437}
8438
8439/// Determine whether the given type is or contains a dynamic class type
8440/// (e.g., whether it has a vtable).
8442 bool &IsContained) {
8443 // Look through array types while ignoring qualifiers.
8444 const Type *Ty = T->getBaseElementTypeUnsafe();
8445 IsContained = false;
8446
8447 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8448 RD = RD ? RD->getDefinition() : nullptr;
8449 if (!RD || RD->isInvalidDecl())
8450 return nullptr;
8451
8452 if (RD->isDynamicClass())
8453 return RD;
8454
8455 // Check all the fields. If any bases were dynamic, the class is dynamic.
8456 // It's impossible for a class to transitively contain itself by value, so
8457 // infinite recursion is impossible.
8458 for (auto *FD : RD->fields()) {
8459 bool SubContained;
8460 if (const CXXRecordDecl *ContainedRD =
8461 getContainedDynamicClass(FD->getType(), SubContained)) {
8462 IsContained = true;
8463 return ContainedRD;
8464 }
8465 }
8466
8467 return nullptr;
8468}
8469
8471 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8472 if (Unary->getKind() == UETT_SizeOf)
8473 return Unary;
8474 return nullptr;
8475}
8476
8477/// If E is a sizeof expression, returns its argument expression,
8478/// otherwise returns NULL.
8479static const Expr *getSizeOfExprArg(const Expr *E) {
8481 if (!SizeOf->isArgumentType())
8482 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8483 return nullptr;
8484}
8485
8486/// If E is a sizeof expression, returns its argument type.
8489 return SizeOf->getTypeOfArgument();
8490 return QualType();
8491}
8492
8493namespace {
8494
8495struct SearchNonTrivialToInitializeField
8496 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8497 using Super =
8499
8500 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8501
8502 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8503 SourceLocation SL) {
8504 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8505 asDerived().visitArray(PDIK, AT, SL);
8506 return;
8507 }
8508
8509 Super::visitWithKind(PDIK, FT, SL);
8510 }
8511
8512 void visitARCStrong(QualType FT, SourceLocation SL) {
8513 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8514 }
8515 void visitARCWeak(QualType FT, SourceLocation SL) {
8516 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8517 }
8518 void visitStruct(QualType FT, SourceLocation SL) {
8519 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8520 visit(FD->getType(), FD->getLocation());
8521 }
8522 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8523 const ArrayType *AT, SourceLocation SL) {
8524 visit(getContext().getBaseElementType(AT), SL);
8525 }
8526 void visitTrivial(QualType FT, SourceLocation SL) {}
8527
8528 static void diag(QualType RT, const Expr *E, Sema &S) {
8529 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8530 }
8531
8532 ASTContext &getContext() { return S.getASTContext(); }
8533
8534 const Expr *E;
8535 Sema &S;
8536};
8537
8538struct SearchNonTrivialToCopyField
8539 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8541
8542 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8543
8544 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8545 SourceLocation SL) {
8546 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8547 asDerived().visitArray(PCK, AT, SL);
8548 return;
8549 }
8550
8551 Super::visitWithKind(PCK, FT, SL);
8552 }
8553
8554 void visitARCStrong(QualType FT, SourceLocation SL) {
8555 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8556 }
8557 void visitARCWeak(QualType FT, SourceLocation SL) {
8558 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8559 }
8560 void visitStruct(QualType FT, SourceLocation SL) {
8561 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8562 visit(FD->getType(), FD->getLocation());
8563 }
8564 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8565 SourceLocation SL) {
8566 visit(getContext().getBaseElementType(AT), SL);
8567 }
8568 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8569 SourceLocation SL) {}
8570 void visitTrivial(QualType FT, SourceLocation SL) {}
8571 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8572
8573 static void diag(QualType RT, const Expr *E, Sema &S) {
8574 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8575 }
8576
8577 ASTContext &getContext() { return S.getASTContext(); }
8578
8579 const Expr *E;
8580 Sema &S;
8581};
8582
8583}
8584
8585/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8586static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8587 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8588
8589 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8590 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8591 return false;
8592
8593 return doesExprLikelyComputeSize(BO->getLHS()) ||
8594 doesExprLikelyComputeSize(BO->getRHS());
8595 }
8596
8597 return getAsSizeOfExpr(SizeofExpr) != nullptr;
8598}
8599
8600/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8601///
8602/// \code
8603/// #define MACRO 0
8604/// foo(MACRO);
8605/// foo(0);
8606/// \endcode
8607///
8608/// This should return true for the first call to foo, but not for the second
8609/// (regardless of whether foo is a macro or function).
8611 SourceLocation CallLoc,
8612 SourceLocation ArgLoc) {
8613 if (!CallLoc.isMacroID())
8614 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8615
8616 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8617 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8618}
8619
8620/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8621/// last two arguments transposed.
8622static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8623 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8624 return;
8625
8626 const Expr *SizeArg =
8627 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8628
8629 auto isLiteralZero = [](const Expr *E) {
8630 return (isa<IntegerLiteral>(E) &&
8631 cast<IntegerLiteral>(E)->getValue() == 0) ||
8632 (isa<CharacterLiteral>(E) &&
8633 cast<CharacterLiteral>(E)->getValue() == 0);
8634 };
8635
8636 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8637 SourceLocation CallLoc = Call->getRParenLoc();
8639 if (isLiteralZero(SizeArg) &&
8640 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8641
8642 SourceLocation DiagLoc = SizeArg->getExprLoc();
8643
8644 // Some platforms #define bzero to __builtin_memset. See if this is the
8645 // case, and if so, emit a better diagnostic.
8646 if (BId == Builtin::BIbzero ||
8648 CallLoc, SM, S.getLangOpts()) == "bzero")) {
8649 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
8650 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
8651 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
8652 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
8653 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
8654 }
8655 return;
8656 }
8657
8658 // If the second argument to a memset is a sizeof expression and the third
8659 // isn't, this is also likely an error. This should catch
8660 // 'memset(buf, sizeof(buf), 0xff)'.
8661 if (BId == Builtin::BImemset &&
8662 doesExprLikelyComputeSize(Call->getArg(1)) &&
8663 !doesExprLikelyComputeSize(Call->getArg(2))) {
8664 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8665 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
8666 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
8667 return;
8668 }
8669}
8670
8671void Sema::CheckMemaccessArguments(const CallExpr *Call,
8672 unsigned BId,
8673 IdentifierInfo *FnName) {
8674 assert(BId != 0);
8675
8676 // It is possible to have a non-standard definition of memset. Validate
8677 // we have enough arguments, and if not, abort further checking.
8678 unsigned ExpectedNumArgs =
8679 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
8680 if (Call->getNumArgs() < ExpectedNumArgs)
8681 return;
8682
8683 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
8684 BId == Builtin::BIstrndup ? 1 : 2);
8685 unsigned LenArg =
8686 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
8687 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
8688
8689 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
8690 Call->getBeginLoc(), Call->getRParenLoc()))
8691 return;
8692
8693 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
8694 CheckMemaccessSize(*this, BId, Call);
8695
8696 // We have special checking when the length is a sizeof expression.
8697 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8698 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8699 llvm::FoldingSetNodeID SizeOfArgID;
8700
8701 // Although widely used, 'bzero' is not a standard function. Be more strict
8702 // with the argument types before allowing diagnostics and only allow the
8703 // form bzero(ptr, sizeof(...)).
8704 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8705 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8706 return;
8707
8708 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8709 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
8710 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
8711
8712 QualType DestTy = Dest->getType();
8713 QualType PointeeTy;
8714 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8715 PointeeTy = DestPtrTy->getPointeeType();
8716
8717 // Never warn about void type pointers. This can be used to suppress
8718 // false positives.
8719 if (PointeeTy->isVoidType())
8720 continue;
8721
8722 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8723 // actually comparing the expressions for equality. Because computing the
8724 // expression IDs can be expensive, we only do this if the diagnostic is
8725 // enabled.
8726 if (SizeOfArg &&
8727 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8728 SizeOfArg->getExprLoc())) {
8729 // We only compute IDs for expressions if the warning is enabled, and
8730 // cache the sizeof arg's ID.
8731 if (SizeOfArgID == llvm::FoldingSetNodeID())
8732 SizeOfArg->Profile(SizeOfArgID, Context, true);
8733 llvm::FoldingSetNodeID DestID;
8734 Dest->Profile(DestID, Context, true);
8735 if (DestID == SizeOfArgID) {
8736 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8737 // over sizeof(src) as well.
8738 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
8739 StringRef ReadableName = FnName->getName();
8740
8741 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
8742 if (UnaryOp->getOpcode() == UO_AddrOf)
8743 ActionIdx = 1; // If its an address-of operator, just remove it.
8744 if (!PointeeTy->isIncompleteType() &&
8745 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
8746 ActionIdx = 2; // If the pointee's size is sizeof(char),
8747 // suggest an explicit length.
8748
8749 // If the function is defined as a builtin macro, do not show macro
8750 // expansion.
8751 SourceLocation SL = SizeOfArg->getExprLoc();
8752 SourceRange DSR = Dest->getSourceRange();
8753 SourceRange SSR = SizeOfArg->getSourceRange();
8755
8756 if (SM.isMacroArgExpansion(SL)) {
8757 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8758 SL = SM.getSpellingLoc(SL);
8759 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8760 SM.getSpellingLoc(DSR.getEnd()));
8761 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8762 SM.getSpellingLoc(SSR.getEnd()));
8763 }
8764
8765 DiagRuntimeBehavior(SL, SizeOfArg,
8766 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
8767 << ReadableName
8768 << PointeeTy
8769 << DestTy
8770 << DSR
8771 << SSR);
8772 DiagRuntimeBehavior(SL, SizeOfArg,
8773 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8774 << ActionIdx
8775 << SSR);
8776
8777 break;
8778 }
8779 }
8780
8781 // Also check for cases where the sizeof argument is the exact same
8782 // type as the memory argument, and where it points to a user-defined
8783 // record type.
8784 if (SizeOfArgTy != QualType()) {
8785 if (PointeeTy->isRecordType() &&
8786 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8787 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8788 PDiag(diag::warn_sizeof_pointer_type_memaccess)
8789 << FnName << SizeOfArgTy << ArgIdx
8790 << PointeeTy << Dest->getSourceRange()
8791 << LenExpr->getSourceRange());
8792 break;
8793 }
8794 }
8795 } else if (DestTy->isArrayType()) {
8796 PointeeTy = DestTy;
8797 }
8798
8799 if (PointeeTy == QualType())
8800 continue;
8801
8802 // Always complain about dynamic classes.
8803 bool IsContained;
8804 if (const CXXRecordDecl *ContainedRD =
8805 getContainedDynamicClass(PointeeTy, IsContained)) {
8806
8807 unsigned OperationType = 0;
8808 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
8809 // "overwritten" if we're warning about the destination for any call
8810 // but memcmp; otherwise a verb appropriate to the call.
8811 if (ArgIdx != 0 || IsCmp) {
8812 if (BId == Builtin::BImemcpy)
8813 OperationType = 1;
8814 else if(BId == Builtin::BImemmove)
8815 OperationType = 2;
8816 else if (IsCmp)
8817 OperationType = 3;
8818 }
8819
8820 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8821 PDiag(diag::warn_dyn_class_memaccess)
8822 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
8823 << IsContained << ContainedRD << OperationType
8824 << Call->getCallee()->getSourceRange());
8825 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8826 BId != Builtin::BImemset)
8828 Dest->getExprLoc(), Dest,
8829 PDiag(diag::warn_arc_object_memaccess)
8830 << ArgIdx << FnName << PointeeTy
8831 << Call->getCallee()->getSourceRange());
8832 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8833 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8834 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8835 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8836 PDiag(diag::warn_cstruct_memaccess)
8837 << ArgIdx << FnName << PointeeTy << 0);
8838 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8839 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8840 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8841 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8842 PDiag(diag::warn_cstruct_memaccess)
8843 << ArgIdx << FnName << PointeeTy << 1);
8844 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8845 } else {
8846 continue;
8847 }
8848 } else
8849 continue;
8850
8852 Dest->getExprLoc(), Dest,
8853 PDiag(diag::note_bad_memaccess_silence)
8854 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8855 break;
8856 }
8857}
8858
8859// A little helper routine: ignore addition and subtraction of integer literals.
8860// This intentionally does not ignore all integer constant expressions because
8861// we don't want to remove sizeof().
8862static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8863 Ex = Ex->IgnoreParenCasts();
8864
8865 while (true) {
8866 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8867 if (!BO || !BO->isAdditiveOp())
8868 break;
8869
8870 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8871 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8872
8873 if (isa<IntegerLiteral>(RHS))
8874 Ex = LHS;
8875 else if (isa<IntegerLiteral>(LHS))
8876 Ex = RHS;
8877 else
8878 break;
8879 }
8880
8881 return Ex;
8882}
8883
8885 ASTContext &Context) {
8886 // Only handle constant-sized or VLAs, but not flexible members.
8887 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8888 // Only issue the FIXIT for arrays of size > 1.
8889 if (CAT->getZExtSize() <= 1)
8890 return false;
8891 } else if (!Ty->isVariableArrayType()) {
8892 return false;
8893 }
8894 return true;
8895}
8896
8897void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8898 IdentifierInfo *FnName) {
8899
8900 // Don't crash if the user has the wrong number of arguments
8901 unsigned NumArgs = Call->getNumArgs();
8902 if ((NumArgs != 3) && (NumArgs != 4))
8903 return;
8904
8905 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8906 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
8907 const Expr *CompareWithSrc = nullptr;
8908
8909 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8910 Call->getBeginLoc(), Call->getRParenLoc()))
8911 return;
8912
8913 // Look for 'strlcpy(dst, x, sizeof(x))'
8914 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8915 CompareWithSrc = Ex;
8916 else {
8917 // Look for 'strlcpy(dst, x, strlen(x))'
8918 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
8919 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8920 SizeCall->getNumArgs() == 1)
8921 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8922 }
8923 }
8924
8925 if (!CompareWithSrc)
8926 return;
8927
8928 // Determine if the argument to sizeof/strlen is equal to the source
8929 // argument. In principle there's all kinds of things you could do
8930 // here, for instance creating an == expression and evaluating it with
8931 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8932 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8933 if (!SrcArgDRE)
8934 return;
8935
8936 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8937 if (!CompareWithSrcDRE ||
8938 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8939 return;
8940
8941 const Expr *OriginalSizeArg = Call->getArg(2);
8942 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
8943 << OriginalSizeArg->getSourceRange() << FnName;
8944
8945 // Output a FIXIT hint if the destination is an array (rather than a
8946 // pointer to an array). This could be enhanced to handle some
8947 // pointers if we know the actual size, like if DstArg is 'array+2'
8948 // we could say 'sizeof(array)-2'.
8949 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
8951 return;
8952
8953 SmallString<128> sizeString;
8954 llvm::raw_svector_ostream OS(sizeString);
8955 OS << "sizeof(";
8956 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8957 OS << ")";
8958
8959 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
8960 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8961 OS.str());
8962}
8963
8964/// Check if two expressions refer to the same declaration.
8965static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8966 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8967 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8968 return D1->getDecl() == D2->getDecl();
8969 return false;
8970}
8971
8972static const Expr *getStrlenExprArg(const Expr *E) {
8973 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8974 const FunctionDecl *FD = CE->getDirectCallee();
8975 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
8976 return nullptr;
8977 return CE->getArg(0)->IgnoreParenCasts();
8978 }
8979 return nullptr;
8980}
8981
8982void Sema::CheckStrncatArguments(const CallExpr *CE,
8983 IdentifierInfo *FnName) {
8984 // Don't crash if the user has the wrong number of arguments.
8985 if (CE->getNumArgs() < 3)
8986 return;
8987 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8988 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8989 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8990
8991 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
8992 CE->getRParenLoc()))
8993 return;
8994
8995 // Identify common expressions, which are wrongly used as the size argument
8996 // to strncat and may lead to buffer overflows.
8997 unsigned PatternType = 0;
8998 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8999 // - sizeof(dst)
9000 if (referToTheSameDecl(SizeOfArg, DstArg))
9001 PatternType = 1;
9002 // - sizeof(src)
9003 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9004 PatternType = 2;
9005 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9006 if (BE->getOpcode() == BO_Sub) {
9007 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9008 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9009 // - sizeof(dst) - strlen(dst)
9010 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9012 PatternType = 1;
9013 // - sizeof(src) - (anything)
9014 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9015 PatternType = 2;
9016 }
9017 }
9018
9019 if (PatternType == 0)
9020 return;
9021
9022 // Generate the diagnostic.
9023 SourceLocation SL = LenArg->getBeginLoc();
9024 SourceRange SR = LenArg->getSourceRange();
9026
9027 // If the function is defined as a builtin macro, do not show macro expansion.
9028 if (SM.isMacroArgExpansion(SL)) {
9029 SL = SM.getSpellingLoc(SL);
9030 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9031 SM.getSpellingLoc(SR.getEnd()));
9032 }
9033
9034 // Check if the destination is an array (rather than a pointer to an array).
9035 QualType DstTy = DstArg->getType();
9036 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9037 Context);
9038 if (!isKnownSizeArray) {
9039 if (PatternType == 1)
9040 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9041 else
9042 Diag(SL, diag::warn_strncat_src_size) << SR;
9043 return;
9044 }
9045
9046 if (PatternType == 1)
9047 Diag(SL, diag::warn_strncat_large_size) << SR;
9048 else
9049 Diag(SL, diag::warn_strncat_src_size) << SR;
9050
9051 SmallString<128> sizeString;
9052 llvm::raw_svector_ostream OS(sizeString);
9053 OS << "sizeof(";
9054 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9055 OS << ") - ";
9056 OS << "strlen(";
9057 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9058 OS << ") - 1";
9059
9060 Diag(SL, diag::note_strncat_wrong_size)
9061 << FixItHint::CreateReplacement(SR, OS.str());
9062}
9063
9064namespace {
9065void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
9066 const UnaryOperator *UnaryExpr, const Decl *D) {
9067 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
9068 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
9069 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
9070 return;
9071 }
9072}
9073
9074void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
9075 const UnaryOperator *UnaryExpr) {
9076 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
9077 const Decl *D = Lvalue->getDecl();
9078 if (isa<DeclaratorDecl>(D))
9079 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
9080 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
9081 }
9082
9083 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
9084 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
9085 Lvalue->getMemberDecl());
9086}
9087
9088void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
9089 const UnaryOperator *UnaryExpr) {
9090 const auto *Lambda = dyn_cast<LambdaExpr>(
9092 if (!Lambda)
9093 return;
9094
9095 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
9096 << CalleeName << 2 /*object: lambda expression*/;
9097}
9098
9099void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
9100 const DeclRefExpr *Lvalue) {
9101 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
9102 if (Var == nullptr)
9103 return;
9104
9105 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
9106 << CalleeName << 0 /*object: */ << Var;
9107}
9108
9109void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
9110 const CastExpr *Cast) {
9111 SmallString<128> SizeString;
9112 llvm::raw_svector_ostream OS(SizeString);
9113
9114 clang::CastKind Kind = Cast->getCastKind();
9115 if (Kind == clang::CK_BitCast &&
9116 !Cast->getSubExpr()->getType()->isFunctionPointerType())
9117 return;
9118 if (Kind == clang::CK_IntegralToPointer &&
9119 !isa<IntegerLiteral>(
9120 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
9121 return;
9122
9123 switch (Cast->getCastKind()) {
9124 case clang::CK_BitCast:
9125 case clang::CK_IntegralToPointer:
9126 case clang::CK_FunctionToPointerDecay:
9127 OS << '\'';
9128 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
9129 OS << '\'';
9130 break;
9131 default:
9132 return;
9133 }
9134
9135 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
9136 << CalleeName << 0 /*object: */ << OS.str();
9137}
9138} // namespace
9139
9140void Sema::CheckFreeArguments(const CallExpr *E) {
9141 const std::string CalleeName =
9142 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
9143
9144 { // Prefer something that doesn't involve a cast to make things simpler.
9145 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
9146 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
9147 switch (UnaryExpr->getOpcode()) {
9148 case UnaryOperator::Opcode::UO_AddrOf:
9149 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
9150 case UnaryOperator::Opcode::UO_Plus:
9151 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
9152 default:
9153 break;
9154 }
9155
9156 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
9157 if (Lvalue->getType()->isArrayType())
9158 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
9159
9160 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
9161 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
9162 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
9163 return;
9164 }
9165
9166 if (isa<BlockExpr>(Arg)) {
9167 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
9168 << CalleeName << 1 /*object: block*/;
9169 return;
9170 }
9171 }
9172 // Maybe the cast was important, check after the other cases.
9173 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
9174 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
9175}
9176
9177void
9178Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9179 SourceLocation ReturnLoc,
9180 bool isObjCMethod,
9181 const AttrVec *Attrs,
9182 const FunctionDecl *FD) {
9183 // Check if the return value is null but should not be.
9184 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9185 (!isObjCMethod && isNonNullType(lhsType))) &&
9186 CheckNonNullExpr(*this, RetValExp))
9187 Diag(ReturnLoc, diag::warn_null_ret)
9188 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9189
9190 // C++11 [basic.stc.dynamic.allocation]p4:
9191 // If an allocation function declared with a non-throwing
9192 // exception-specification fails to allocate storage, it shall return
9193 // a null pointer. Any other allocation function that fails to allocate
9194 // storage shall indicate failure only by throwing an exception [...]
9195 if (FD) {
9197 if (Op == OO_New || Op == OO_Array_New) {
9198 const FunctionProtoType *Proto
9199 = FD->getType()->castAs<FunctionProtoType>();
9200 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9201 CheckNonNullExpr(*this, RetValExp))
9202 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9203 << FD << getLangOpts().CPlusPlus11;
9204 }
9205 }
9206
9207 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
9208 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
9209 }
9210
9211 // PPC MMA non-pointer types are not allowed as return type. Checking the type
9212 // here prevent the user from using a PPC MMA type as trailing return type.
9213 if (Context.getTargetInfo().getTriple().isPPC64())
9214 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
9215}
9216
9218 BinaryOperatorKind Opcode) {
9219 if (!BinaryOperator::isEqualityOp(Opcode))
9220 return;
9221
9222 // Match and capture subexpressions such as "(float) X == 0.1".
9223 FloatingLiteral *FPLiteral;
9224 CastExpr *FPCast;
9225 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
9226 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
9227 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
9228 return FPLiteral && FPCast;
9229 };
9230
9231 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
9232 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
9233 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
9234 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
9235 TargetTy->isFloatingPoint()) {
9236 bool Lossy;
9237 llvm::APFloat TargetC = FPLiteral->getValue();
9238 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
9239 llvm::APFloat::rmNearestTiesToEven, &Lossy);
9240 if (Lossy) {
9241 // If the literal cannot be represented in the source type, then a
9242 // check for == is always false and check for != is always true.
9243 Diag(Loc, diag::warn_float_compare_literal)
9244 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
9245 << LHS->getSourceRange() << RHS->getSourceRange();
9246 return;
9247 }
9248 }
9249 }
9250
9251 // Match a more general floating-point equality comparison (-Wfloat-equal).
9252 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9253 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9254
9255 // Special case: check for x == x (which is OK).
9256 // Do not emit warnings for such cases.
9257 if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9258 if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9259 if (DRL->getDecl() == DRR->getDecl())
9260 return;
9261
9262 // Special case: check for comparisons against literals that can be exactly
9263 // represented by APFloat. In such cases, do not emit a warning. This
9264 // is a heuristic: often comparison against such literals are used to
9265 // detect if a value in a variable has not changed. This clearly can
9266 // lead to false negatives.
9267 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9268 if (FLL->isExact())
9269 return;
9270 } else
9271 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9272 if (FLR->isExact())
9273 return;
9274
9275 // Check for comparisons with builtin types.
9276 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9277 if (CL->getBuiltinCallee())
9278 return;
9279
9280 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9281 if (CR->getBuiltinCallee())
9282 return;
9283
9284 // Emit the diagnostic.
9285 Diag(Loc, diag::warn_floatingpoint_eq)
9286 << LHS->getSourceRange() << RHS->getSourceRange();
9287}
9288
9289//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9290//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9291
9292namespace {
9293
9294/// Structure recording the 'active' range of an integer-valued
9295/// expression.
9296struct IntRange {
9297 /// The number of bits active in the int. Note that this includes exactly one
9298 /// sign bit if !NonNegative.
9299 unsigned Width;
9300
9301 /// True if the int is known not to have negative values. If so, all leading
9302 /// bits before Width are known zero, otherwise they are known to be the
9303 /// same as the MSB within Width.
9304 bool NonNegative;
9305
9306 IntRange(unsigned Width, bool NonNegative)
9307 : Width(Width), NonNegative(NonNegative) {}
9308
9309 /// Number of bits excluding the sign bit.
9310 unsigned valueBits() const {
9311 return NonNegative ? Width : Width - 1;
9312 }
9313
9314 /// Returns the range of the bool type.
9315 static IntRange forBoolType() {
9316 return IntRange(1, true);
9317 }
9318
9319 /// Returns the range of an opaque value of the given integral type.
9320 static IntRange forValueOfType(ASTContext &C, QualType T) {
9321 return forValueOfCanonicalType(C,
9323 }
9324
9325 /// Returns the range of an opaque value of a canonical integral type.
9326 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9327 assert(T->isCanonicalUnqualified());
9328
9329 if (const VectorType *VT = dyn_cast<VectorType>(T))
9330 T = VT->getElementType().getTypePtr();
9331 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9332 T = CT->getElementType().getTypePtr();
9333 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9334 T = AT->getValueType().getTypePtr();
9335
9336 if (!C.getLangOpts().CPlusPlus) {
9337 // For enum types in C code, use the underlying datatype.
9338 if (const EnumType *ET = dyn_cast<EnumType>(T))
9339 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9340 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9341 // For enum types in C++, use the known bit width of the enumerators.
9342 EnumDecl *Enum = ET->getDecl();
9343 // In C++11, enums can have a fixed underlying type. Use this type to
9344 // compute the range.
9345 if (Enum->isFixed()) {
9346 return IntRange(C.getIntWidth(QualType(T, 0)),
9347 !ET->isSignedIntegerOrEnumerationType());
9348 }
9349
9350 unsigned NumPositive = Enum->getNumPositiveBits();
9351 unsigned NumNegative = Enum->getNumNegativeBits();
9352
9353 if (NumNegative == 0)
9354 return IntRange(NumPositive, true/*NonNegative*/);
9355 else
9356 return IntRange(std::max(NumPositive + 1, NumNegative),
9357 false/*NonNegative*/);
9358 }
9359
9360 if (const auto *EIT = dyn_cast<BitIntType>(T))
9361 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9362
9363 const BuiltinType *BT = cast<BuiltinType>(T);
9364 assert(BT->isInteger());
9365
9366 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9367 }
9368
9369 /// Returns the "target" range of a canonical integral type, i.e.
9370 /// the range of values expressible in the type.
9371 ///
9372 /// This matches forValueOfCanonicalType except that enums have the
9373 /// full range of their type, not the range of their enumerators.
9374 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9375 assert(T->isCanonicalUnqualified());
9376
9377 if (const VectorType *VT = dyn_cast<VectorType>(T))
9378 T = VT->getElementType().getTypePtr();
9379 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9380 T = CT->getElementType().getTypePtr();
9381 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9382 T = AT->getValueType().getTypePtr();
9383 if (const EnumType *ET = dyn_cast<EnumType>(T))
9384 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9385
9386 if (const auto *EIT = dyn_cast<BitIntType>(T))
9387 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
9388
9389 const BuiltinType *BT = cast<BuiltinType>(T);
9390 assert(BT->isInteger());
9391
9392 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9393 }
9394
9395 /// Returns the supremum of two ranges: i.e. their conservative merge.
9396 static IntRange join(IntRange L, IntRange R) {
9397 bool Unsigned = L.NonNegative && R.NonNegative;
9398 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
9399 L.NonNegative && R.NonNegative);
9400 }
9401
9402 /// Return the range of a bitwise-AND of the two ranges.
9403 static IntRange bit_and(IntRange L, IntRange R) {
9404 unsigned Bits = std::max(L.Width, R.Width);
9405 bool NonNegative = false;
9406 if (L.NonNegative) {
9407 Bits = std::min(Bits, L.Width);
9408 NonNegative = true;
9409 }
9410 if (R.NonNegative) {
9411 Bits = std::min(Bits, R.Width);
9412 NonNegative = true;
9413 }
9414 return IntRange(Bits, NonNegative);
9415 }
9416
9417 /// Return the range of a sum of the two ranges.
9418 static IntRange sum(IntRange L, IntRange R) {
9419 bool Unsigned = L.NonNegative && R.NonNegative;
9420 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
9421 Unsigned);
9422 }
9423
9424 /// Return the range of a difference of the two ranges.
9425 static IntRange difference(IntRange L, IntRange R) {
9426 // We need a 1-bit-wider range if:
9427 // 1) LHS can be negative: least value can be reduced.
9428 // 2) RHS can be negative: greatest value can be increased.
9429 bool CanWiden = !L.NonNegative || !R.NonNegative;
9430 bool Unsigned = L.NonNegative && R.Width == 0;
9431 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
9432 !Unsigned,
9433 Unsigned);
9434 }
9435
9436 /// Return the range of a product of the two ranges.
9437 static IntRange product(IntRange L, IntRange R) {
9438 // If both LHS and RHS can be negative, we can form
9439 // -2^L * -2^R = 2^(L + R)
9440 // which requires L + R + 1 value bits to represent.
9441 bool CanWiden = !L.NonNegative && !R.NonNegative;
9442 bool Unsigned = L.NonNegative && R.NonNegative;
9443 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
9444 Unsigned);
9445 }
9446
9447 /// Return the range of a remainder operation between the two ranges.
9448 static IntRange rem(IntRange L, IntRange R) {
9449 // The result of a remainder can't be larger than the result of
9450 // either side. The sign of the result is the sign of the LHS.
9451 bool Unsigned = L.NonNegative;
9452 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
9453 Unsigned);
9454 }
9455};
9456
9457} // namespace
9458
9459static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9460 unsigned MaxWidth) {
9461 if (value.isSigned() && value.isNegative())
9462 return IntRange(value.getSignificantBits(), false);
9463
9464 if (value.getBitWidth() > MaxWidth)
9465 value = value.trunc(MaxWidth);
9466
9467 // isNonNegative() just checks the sign bit without considering
9468 // signedness.
9469 return IntRange(value.getActiveBits(), true);
9470}
9471
9472static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9473 unsigned MaxWidth) {
9474 if (result.isInt())
9475 return GetValueRange(C, result.getInt(), MaxWidth);
9476
9477 if (result.isVector()) {
9478 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9479 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9480 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9481 R = IntRange::join(R, El);
9482 }
9483 return R;
9484 }
9485
9486 if (result.isComplexInt()) {
9487 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9488 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9489 return IntRange::join(R, I);
9490 }
9491
9492 // This can happen with lossless casts to intptr_t of "based" lvalues.
9493 // Assume it might use arbitrary bits.
9494 // FIXME: The only reason we need to pass the type in here is to get
9495 // the sign right on this one case. It would be nice if APValue
9496 // preserved this.
9497 assert(result.isLValue() || result.isAddrLabelDiff());
9498 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9499}
9500
9501static QualType GetExprType(const Expr *E) {
9502 QualType Ty = E->getType();
9503 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9504 Ty = AtomicRHS->getValueType();
9505 return Ty;
9506}
9507
9508/// Pseudo-evaluate the given integer expression, estimating the
9509/// range of values it might take.
9510///
9511/// \param MaxWidth The width to which the value will be truncated.
9512/// \param Approximate If \c true, return a likely range for the result: in
9513/// particular, assume that arithmetic on narrower types doesn't leave
9514/// those types. If \c false, return a range including all possible
9515/// result values.
9516static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9517 bool InConstantContext, bool Approximate) {
9518 E = E->IgnoreParens();
9519
9520 // Try a full evaluation first.
9521 Expr::EvalResult result;
9522 if (E->EvaluateAsRValue(result, C, InConstantContext))
9523 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9524
9525 // I think we only want to look through implicit casts here; if the
9526 // user has an explicit widening cast, we should treat the value as
9527 // being of the new, wider type.
9528 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9529 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9530 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
9531 Approximate);
9532
9533 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9534
9535 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9536 CE->getCastKind() == CK_BooleanToSignedIntegral;
9537
9538 // Assume that non-integer casts can span the full range of the type.
9539 if (!isIntegerCast)
9540 return OutputTypeRange;
9541
9542 IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
9543 std::min(MaxWidth, OutputTypeRange.Width),
9544 InConstantContext, Approximate);
9545
9546 // Bail out if the subexpr's range is as wide as the cast type.
9547 if (SubRange.Width >= OutputTypeRange.Width)
9548 return OutputTypeRange;
9549
9550 // Otherwise, we take the smaller width, and we're non-negative if
9551 // either the output type or the subexpr is.
9552 return IntRange(SubRange.Width,
9553 SubRange.NonNegative || OutputTypeRange.NonNegative);
9554 }
9555
9556 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9557 // If we can fold the condition, just take that operand.
9558 bool CondResult;
9559 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9560 return GetExprRange(C,
9561 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
9562 MaxWidth, InConstantContext, Approximate);
9563
9564 // Otherwise, conservatively merge.
9565 // GetExprRange requires an integer expression, but a throw expression
9566 // results in a void type.
9567 Expr *E = CO->getTrueExpr();
9568 IntRange L = E->getType()->isVoidType()
9569 ? IntRange{0, true}
9570 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
9571 E = CO->getFalseExpr();
9572 IntRange R = E->getType()->isVoidType()
9573 ? IntRange{0, true}
9574 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
9575 return IntRange::join(L, R);
9576 }
9577
9578 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9579 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
9580
9581 switch (BO->getOpcode()) {
9582 case BO_Cmp:
9583 llvm_unreachable("builtin <=> should have class type");
9584
9585 // Boolean-valued operations are single-bit and positive.
9586 case BO_LAnd:
9587 case BO_LOr:
9588 case BO_LT:
9589 case BO_GT:
9590 case BO_LE:
9591 case BO_GE:
9592 case BO_EQ:
9593 case BO_NE:
9594 return IntRange::forBoolType();
9595
9596 // The type of the assignments is the type of the LHS, so the RHS
9597 // is not necessarily the same type.
9598 case BO_MulAssign:
9599 case BO_DivAssign:
9600 case BO_RemAssign:
9601 case BO_AddAssign:
9602 case BO_SubAssign:
9603 case BO_XorAssign:
9604 case BO_OrAssign:
9605 // TODO: bitfields?
9606 return IntRange::forValueOfType(C, GetExprType(E));
9607
9608 // Simple assignments just pass through the RHS, which will have
9609 // been coerced to the LHS type.
9610 case BO_Assign:
9611 // TODO: bitfields?
9612 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
9613 Approximate);
9614
9615 // Operations with opaque sources are black-listed.
9616 case BO_PtrMemD:
9617 case BO_PtrMemI:
9618 return IntRange::forValueOfType(C, GetExprType(E));
9619
9620 // Bitwise-and uses the *infinum* of the two source ranges.
9621 case BO_And:
9622 case BO_AndAssign:
9623 Combine = IntRange::bit_and;
9624 break;
9625
9626 // Left shift gets black-listed based on a judgement call.
9627 case BO_Shl:
9628 // ...except that we want to treat '1 << (blah)' as logically
9629 // positive. It's an important idiom.
9630 if (IntegerLiteral *I
9631 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9632 if (I->getValue() == 1) {
9633 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9634 return IntRange(R.Width, /*NonNegative*/ true);
9635 }
9636 }
9637 [[fallthrough]];
9638
9639 case BO_ShlAssign:
9640 return IntRange::forValueOfType(C, GetExprType(E));
9641
9642 // Right shift by a constant can narrow its left argument.
9643 case BO_Shr:
9644 case BO_ShrAssign: {
9645 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
9646 Approximate);
9647
9648 // If the shift amount is a positive constant, drop the width by
9649 // that much.
9650 if (std::optional<llvm::APSInt> shift =
9651 BO->getRHS()->getIntegerConstantExpr(C)) {
9652 if (shift->isNonNegative()) {
9653 if (shift->uge(L.Width))
9654 L.Width = (L.NonNegative ? 0 : 1);
9655 else
9656 L.Width -= shift->getZExtValue();
9657 }
9658 }
9659
9660 return L;
9661 }
9662
9663 // Comma acts as its right operand.
9664 case BO_Comma:
9665 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
9666 Approximate);
9667
9668 case BO_Add:
9669 if (!Approximate)
9670 Combine = IntRange::sum;
9671 break;
9672
9673 case BO_Sub:
9674 if (BO->getLHS()->getType()->isPointerType())
9675 return IntRange::forValueOfType(C, GetExprType(E));
9676 if (!Approximate)
9677 Combine = IntRange::difference;
9678 break;
9679
9680 case BO_Mul:
9681 if (!Approximate)
9682 Combine = IntRange::product;
9683 break;
9684
9685 // The width of a division result is mostly determined by the size
9686 // of the LHS.
9687 case BO_Div: {
9688 // Don't 'pre-truncate' the operands.
9689 unsigned opWidth = C.getIntWidth(GetExprType(E));
9690 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
9691 Approximate);
9692
9693 // If the divisor is constant, use that.
9694 if (std::optional<llvm::APSInt> divisor =
9695 BO->getRHS()->getIntegerConstantExpr(C)) {
9696 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
9697 if (log2 >= L.Width)
9698 L.Width = (L.NonNegative ? 0 : 1);
9699 else
9700 L.Width = std::min(L.Width - log2, MaxWidth);
9701 return L;
9702 }
9703
9704 // Otherwise, just use the LHS's width.
9705 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
9706 // could be -1.
9707 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
9708 Approximate);
9709 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9710 }
9711
9712 case BO_Rem:
9713 Combine = IntRange::rem;
9714 break;
9715
9716 // The default behavior is okay for these.
9717 case BO_Xor:
9718 case BO_Or:
9719 break;
9720 }
9721
9722 // Combine the two ranges, but limit the result to the type in which we
9723 // performed the computation.
9725 unsigned opWidth = C.getIntWidth(T);
9726 IntRange L =
9727 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
9728 IntRange R =
9729 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
9730 IntRange C = Combine(L, R);
9731 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
9732 C.Width = std::min(C.Width, MaxWidth);
9733 return C;
9734 }
9735
9736 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9737 switch (UO->getOpcode()) {
9738 // Boolean-valued operations are white-listed.
9739 case UO_LNot:
9740 return IntRange::forBoolType();
9741
9742 // Operations with opaque sources are black-listed.
9743 case UO_Deref:
9744 case UO_AddrOf: // should be impossible
9745 return IntRange::forValueOfType(C, GetExprType(E));
9746
9747 default:
9748 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
9749 Approximate);
9750 }
9751 }
9752
9753 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9754 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
9755 Approximate);
9756
9757 if (const auto *BitField = E->getSourceBitField())
9758 return IntRange(BitField->getBitWidthValue(C),
9759 BitField->getType()->isUnsignedIntegerOrEnumerationType());
9760
9761 return IntRange::forValueOfType(C, GetExprType(E));
9762}
9763
9764static IntRange GetExprRange(ASTContext &C, const Expr *E,
9765 bool InConstantContext, bool Approximate) {
9766 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
9767 Approximate);
9768}
9769
9770/// Checks whether the given value, which currently has the given
9771/// source semantics, has the same value when coerced through the
9772/// target semantics.
9773static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9774 const llvm::fltSemantics &Src,
9775 const llvm::fltSemantics &Tgt) {
9776 llvm::APFloat truncated = value;
9777
9778 bool ignored;
9779 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9780 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9781
9782 return truncated.bitwiseIsEqual(value);
9783}
9784
9785/// Checks whether the given value, which currently has the given
9786/// source semantics, has the same value when coerced through the
9787/// target semantics.
9788///
9789/// The value might be a vector of floats (or a complex number).
9790static bool IsSameFloatAfterCast(const APValue &value,
9791 const llvm::fltSemantics &Src,
9792 const llvm::fltSemantics &Tgt) {
9793 if (value.isFloat())
9794 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9795
9796 if (value.isVector()) {
9797 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9798 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9799 return false;
9800 return true;
9801 }
9802
9803 assert(value.isComplexFloat());
9804 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9805 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9806}
9807
9809 bool IsListInit = false);
9810
9812 // Suppress cases where we are comparing against an enum constant.
9813 if (const DeclRefExpr *DR =
9814 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9815 if (isa<EnumConstantDecl>(DR->getDecl()))
9816 return true;
9817
9818 // Suppress cases where the value is expanded from a macro, unless that macro
9819 // is how a language represents a boolean literal. This is the case in both C
9820 // and Objective-C.
9821 SourceLocation BeginLoc = E->getBeginLoc();
9822 if (BeginLoc.isMacroID()) {
9823 StringRef MacroName = Lexer::getImmediateMacroName(
9824 BeginLoc, S.getSourceManager(), S.getLangOpts());
9825 return MacroName != "YES" && MacroName != "NO" &&
9826 MacroName != "true" && MacroName != "false";
9827 }
9828
9829 return false;
9830}
9831
9833 return E->getType()->isIntegerType() &&
9834 (!E->getType()->isSignedIntegerType() ||
9836}
9837
9838namespace {
9839/// The promoted range of values of a type. In general this has the
9840/// following structure:
9841///
9842/// |-----------| . . . |-----------|
9843/// ^ ^ ^ ^
9844/// Min HoleMin HoleMax Max
9845///
9846/// ... where there is only a hole if a signed type is promoted to unsigned
9847/// (in which case Min and Max are the smallest and largest representable
9848/// values).
9849struct PromotedRange {
9850 // Min, or HoleMax if there is a hole.
9851 llvm::APSInt PromotedMin;
9852 // Max, or HoleMin if there is a hole.
9853 llvm::APSInt PromotedMax;
9854
9855 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9856 if (R.Width == 0)
9857 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9858 else if (R.Width >= BitWidth && !Unsigned) {
9859 // Promotion made the type *narrower*. This happens when promoting
9860 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9861 // Treat all values of 'signed int' as being in range for now.
9862 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9863 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9864 } else {
9865 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9866 .extOrTrunc(BitWidth);
9867 PromotedMin.setIsUnsigned(Unsigned);
9868
9869 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9870 .extOrTrunc(BitWidth);
9871 PromotedMax.setIsUnsigned(Unsigned);
9872 }
9873 }
9874
9875 // Determine whether this range is contiguous (has no hole).
9876 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9877
9878 // Where a constant value is within the range.
9879 enum ComparisonResult {
9880 LT = 0x1,
9881 LE = 0x2,
9882 GT = 0x4,
9883 GE = 0x8,
9884 EQ = 0x10,
9885 NE = 0x20,
9886 InRangeFlag = 0x40,
9887
9888 Less = LE | LT | NE,
9889 Min = LE | InRangeFlag,
9890 InRange = InRangeFlag,
9891 Max = GE | InRangeFlag,
9892 Greater = GE | GT | NE,
9893
9894 OnlyValue = LE | GE | EQ | InRangeFlag,
9895 InHole = NE
9896 };
9897
9898 ComparisonResult compare(const llvm::APSInt &Value) const {
9899 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9900 Value.isUnsigned() == PromotedMin.isUnsigned());
9901 if (!isContiguous()) {
9902 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9903 if (Value.isMinValue()) return Min;
9904 if (Value.isMaxValue()) return Max;
9905 if (Value >= PromotedMin) return InRange;
9906 if (Value <= PromotedMax) return InRange;
9907 return InHole;
9908 }
9909
9910 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9911 case -1: return Less;
9912 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9913 case 1:
9914 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9915 case -1: return InRange;
9916 case 0: return Max;
9917 case 1: return Greater;
9918 }
9919 }
9920
9921 llvm_unreachable("impossible compare result");
9922 }
9923
9924 static std::optional<StringRef>
9925 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9926 if (Op == BO_Cmp) {
9927 ComparisonResult LTFlag = LT, GTFlag = GT;
9928 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9929
9930 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9931 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9932 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9933 return std::nullopt;
9934 }
9935
9936 ComparisonResult TrueFlag, FalseFlag;
9937 if (Op == BO_EQ) {
9938 TrueFlag = EQ;
9939 FalseFlag = NE;
9940 } else if (Op == BO_NE) {
9941 TrueFlag = NE;
9942 FalseFlag = EQ;
9943 } else {
9944 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9945 TrueFlag = LT;
9946 FalseFlag = GE;
9947 } else {
9948 TrueFlag = GT;
9949 FalseFlag = LE;
9950 }
9951 if (Op == BO_GE || Op == BO_LE)
9952 std::swap(TrueFlag, FalseFlag);
9953 }
9954 if (R & TrueFlag)
9955 return StringRef("true");
9956 if (R & FalseFlag)
9957 return StringRef("false");
9958 return std::nullopt;
9959 }
9960};
9961}
9962
9963static bool HasEnumType(Expr *E) {
9964 // Strip off implicit integral promotions.
9965 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9966 if (ICE->getCastKind() != CK_IntegralCast &&
9967 ICE->getCastKind() != CK_NoOp)
9968 break;
9969 E = ICE->getSubExpr();
9970 }
9971
9972 return E->getType()->isEnumeralType();
9973}
9974
9975static int classifyConstantValue(Expr *Constant) {
9976 // The values of this enumeration are used in the diagnostics
9977 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9978 enum ConstantValueKind {
9979 Miscellaneous = 0,
9980 LiteralTrue,
9981 LiteralFalse
9982 };
9983 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9984 return BL->getValue() ? ConstantValueKind::LiteralTrue
9985 : ConstantValueKind::LiteralFalse;
9986 return ConstantValueKind::Miscellaneous;
9987}
9988
9990 Expr *Constant, Expr *Other,
9991 const llvm::APSInt &Value,
9992 bool RhsConstant) {
9994 return false;
9995
9996 Expr *OriginalOther = Other;
9997
9998 Constant = Constant->IgnoreParenImpCasts();
9999 Other = Other->IgnoreParenImpCasts();
10000
10001 // Suppress warnings on tautological comparisons between values of the same
10002 // enumeration type. There are only two ways we could warn on this:
10003 // - If the constant is outside the range of representable values of
10004 // the enumeration. In such a case, we should warn about the cast
10005 // to enumeration type, not about the comparison.
10006 // - If the constant is the maximum / minimum in-range value. For an
10007 // enumeratin type, such comparisons can be meaningful and useful.
10008 if (Constant->getType()->isEnumeralType() &&
10009 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10010 return false;
10011
10012 IntRange OtherValueRange = GetExprRange(
10013 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
10014
10015 QualType OtherT = Other->getType();
10016 if (const auto *AT = OtherT->getAs<AtomicType>())
10017 OtherT = AT->getValueType();
10018 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
10019
10020 // Special case for ObjC BOOL on targets where its a typedef for a signed char
10021 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
10022 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10023 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
10024 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10025
10026 // Whether we're treating Other as being a bool because of the form of
10027 // expression despite it having another type (typically 'int' in C).
10028 bool OtherIsBooleanDespiteType =
10029 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10030 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10031 OtherTypeRange = OtherValueRange = IntRange::forBoolType();
10032
10033 // Check if all values in the range of possible values of this expression
10034 // lead to the same comparison outcome.
10035 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
10036 Value.isUnsigned());
10037 auto Cmp = OtherPromotedValueRange.compare(Value);
10038 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10039 if (!Result)
10040 return false;
10041
10042 // Also consider the range determined by the type alone. This allows us to
10043 // classify the warning under the proper diagnostic group.
10044 bool TautologicalTypeCompare = false;
10045 {
10046 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
10047 Value.isUnsigned());
10048 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
10049 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
10050 RhsConstant)) {
10051 TautologicalTypeCompare = true;
10052 Cmp = TypeCmp;
10054 }
10055 }
10056
10057 // Don't warn if the non-constant operand actually always evaluates to the
10058 // same value.
10059 if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
10060 return false;
10061
10062 // Suppress the diagnostic for an in-range comparison if the constant comes
10063 // from a macro or enumerator. We don't want to diagnose
10064 //
10065 // some_long_value <= INT_MAX
10066 //
10067 // when sizeof(int) == sizeof(long).
10068 bool InRange = Cmp & PromotedRange::InRangeFlag;
10069 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10070 return false;
10071
10072 // A comparison of an unsigned bit-field against 0 is really a type problem,
10073 // even though at the type level the bit-field might promote to 'signed int'.
10074 if (Other->refersToBitField() && InRange && Value == 0 &&
10075 Other->getType()->isUnsignedIntegerOrEnumerationType())
10076 TautologicalTypeCompare = true;
10077
10078 // If this is a comparison to an enum constant, include that
10079 // constant in the diagnostic.
10080 const EnumConstantDecl *ED = nullptr;
10081 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10082 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10083
10084 // Should be enough for uint128 (39 decimal digits)
10085 SmallString<64> PrettySourceValue;
10086 llvm::raw_svector_ostream OS(PrettySourceValue);
10087 if (ED) {
10088 OS << '\'' << *ED << "' (" << Value << ")";
10089 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10090 Constant->IgnoreParenImpCasts())) {
10091 OS << (BL->getValue() ? "YES" : "NO");
10092 } else {
10093 OS << Value;
10094 }
10095
10096 if (!TautologicalTypeCompare) {
10097 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
10098 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
10099 << E->getOpcodeStr() << OS.str() << *Result
10100 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10101 return true;
10102 }
10103
10104 if (IsObjCSignedCharBool) {
10105 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10106 S.PDiag(diag::warn_tautological_compare_objc_bool)
10107 << OS.str() << *Result);
10108 return true;
10109 }
10110
10111 // FIXME: We use a somewhat different formatting for the in-range cases and
10112 // cases involving boolean values for historical reasons. We should pick a
10113 // consistent way of presenting these diagnostics.
10114 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10115
10117 E->getOperatorLoc(), E,
10118 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10119 : diag::warn_tautological_bool_compare)
10120 << OS.str() << classifyConstantValue(Constant) << OtherT
10121 << OtherIsBooleanDespiteType << *Result
10122 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10123 } else {
10124 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
10125 unsigned Diag =
10126 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10127 ? (HasEnumType(OriginalOther)
10128 ? diag::warn_unsigned_enum_always_true_comparison
10129 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
10130 : diag::warn_unsigned_always_true_comparison)
10131 : diag::warn_tautological_constant_compare;
10132
10133 S.Diag(E->getOperatorLoc(), Diag)
10134 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10135 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10136 }
10137
10138 return true;
10139}
10140
10141/// Analyze the operands of the given comparison. Implements the
10142/// fallback case from AnalyzeComparison.
10144 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10145 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10146}
10147
10148/// Implements -Wsign-compare.
10149///
10150/// \param E the binary operator to check for warnings
10152 // The type the comparison is being performed in.
10153 QualType T = E->getLHS()->getType();
10154
10155 // Only analyze comparison operators where both sides have been converted to
10156 // the same type.
10157 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10158 return AnalyzeImpConvsInComparison(S, E);
10159
10160 // Don't analyze value-dependent comparisons directly.
10161 if (E->isValueDependent())
10162 return AnalyzeImpConvsInComparison(S, E);
10163
10164 Expr *LHS = E->getLHS();
10165 Expr *RHS = E->getRHS();
10166
10167 if (T->isIntegralType(S.Context)) {
10168 std::optional<llvm::APSInt> RHSValue =
10170 std::optional<llvm::APSInt> LHSValue =
10172
10173 // We don't care about expressions whose result is a constant.
10174 if (RHSValue && LHSValue)
10175 return AnalyzeImpConvsInComparison(S, E);
10176
10177 // We only care about expressions where just one side is literal
10178 if ((bool)RHSValue ^ (bool)LHSValue) {
10179 // Is the constant on the RHS or LHS?
10180 const bool RhsConstant = (bool)RHSValue;
10181 Expr *Const = RhsConstant ? RHS : LHS;
10182 Expr *Other = RhsConstant ? LHS : RHS;
10183 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
10184
10185 // Check whether an integer constant comparison results in a value
10186 // of 'true' or 'false'.
10187 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10188 return AnalyzeImpConvsInComparison(S, E);
10189 }
10190 }
10191
10193 // We don't do anything special if this isn't an unsigned integral
10194 // comparison: we're only interested in integral comparisons, and
10195 // signed comparisons only happen in cases we don't care to warn about.
10196 return AnalyzeImpConvsInComparison(S, E);
10197 }
10198
10199 LHS = LHS->IgnoreParenImpCasts();
10200 RHS = RHS->IgnoreParenImpCasts();
10201
10202 if (!S.getLangOpts().CPlusPlus) {
10203 // Avoid warning about comparison of integers with different signs when
10204 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10205 // the type of `E`.
10206 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10207 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10208 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10209 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10210 }
10211
10212 // Check to see if one of the (unmodified) operands is of different
10213 // signedness.
10214 Expr *signedOperand, *unsignedOperand;
10216 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10217 "unsigned comparison between two signed integer expressions?");
10218 signedOperand = LHS;
10219 unsignedOperand = RHS;
10220 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10221 signedOperand = RHS;
10222 unsignedOperand = LHS;
10223 } else {
10224 return AnalyzeImpConvsInComparison(S, E);
10225 }
10226
10227 // Otherwise, calculate the effective range of the signed operand.
10228 IntRange signedRange =
10229 GetExprRange(S.Context, signedOperand, S.isConstantEvaluatedContext(),
10230 /*Approximate=*/true);
10231
10232 // Go ahead and analyze implicit conversions in the operands. Note
10233 // that we skip the implicit conversions on both sides.
10234 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10235 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10236
10237 // If the signed range is non-negative, -Wsign-compare won't fire.
10238 if (signedRange.NonNegative)
10239 return;
10240
10241 // For (in)equality comparisons, if the unsigned operand is a
10242 // constant which cannot collide with a overflowed signed operand,
10243 // then reinterpreting the signed operand as unsigned will not
10244 // change the result of the comparison.
10245 if (E->isEqualityOp()) {
10246 unsigned comparisonWidth = S.Context.getIntWidth(T);
10247 IntRange unsignedRange =
10248 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
10249 /*Approximate=*/true);
10250
10251 // We should never be unable to prove that the unsigned operand is
10252 // non-negative.
10253 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10254
10255 if (unsignedRange.Width < comparisonWidth)
10256 return;
10257 }
10258
10259 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10260 S.PDiag(diag::warn_mixed_sign_comparison)
10261 << LHS->getType() << RHS->getType()
10262 << LHS->getSourceRange() << RHS->getSourceRange());
10263}
10264
10265/// Analyzes an attempt to assign the given value to a bitfield.
10266///
10267/// Returns true if there was something fishy about the attempt.
10269 SourceLocation InitLoc) {
10270 assert(Bitfield->isBitField());
10271 if (Bitfield->isInvalidDecl())
10272 return false;
10273
10274 // White-list bool bitfields.
10275 QualType BitfieldType = Bitfield->getType();
10276 if (BitfieldType->isBooleanType())
10277 return false;
10278
10279 if (BitfieldType->isEnumeralType()) {
10280 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10281 // If the underlying enum type was not explicitly specified as an unsigned
10282 // type and the enum contain only positive values, MSVC++ will cause an
10283 // inconsistency by storing this as a signed type.
10284 if (S.getLangOpts().CPlusPlus11 &&
10285 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10286 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10287 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10288 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10289 << BitfieldEnumDecl;
10290 }
10291 }
10292
10293 // Ignore value- or type-dependent expressions.
10294 if (Bitfield->getBitWidth()->isValueDependent() ||
10295 Bitfield->getBitWidth()->isTypeDependent() ||
10296 Init->isValueDependent() ||
10297 Init->isTypeDependent())
10298 return false;
10299
10300 Expr *OriginalInit = Init->IgnoreParenImpCasts();
10301 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10302
10304 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10306 // The RHS is not constant. If the RHS has an enum type, make sure the
10307 // bitfield is wide enough to hold all the values of the enum without
10308 // truncation.
10309 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10310 EnumDecl *ED = EnumTy->getDecl();
10311 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10312
10313 // Enum types are implicitly signed on Windows, so check if there are any
10314 // negative enumerators to see if the enum was intended to be signed or
10315 // not.
10316 bool SignedEnum = ED->getNumNegativeBits() > 0;
10317
10318 // Check for surprising sign changes when assigning enum values to a
10319 // bitfield of different signedness. If the bitfield is signed and we
10320 // have exactly the right number of bits to store this unsigned enum,
10321 // suggest changing the enum to an unsigned type. This typically happens
10322 // on Windows where unfixed enums always use an underlying type of 'int'.
10323 unsigned DiagID = 0;
10324 if (SignedEnum && !SignedBitfield) {
10325 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10326 } else if (SignedBitfield && !SignedEnum &&
10327 ED->getNumPositiveBits() == FieldWidth) {
10328 DiagID = diag::warn_signed_bitfield_enum_conversion;
10329 }
10330
10331 if (DiagID) {
10332 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10333 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10334 SourceRange TypeRange =
10335 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10336 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10337 << SignedEnum << TypeRange;
10338 }
10339
10340 // Compute the required bitwidth. If the enum has negative values, we need
10341 // one more bit than the normal number of positive bits to represent the
10342 // sign bit.
10343 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10344 ED->getNumNegativeBits())
10345 : ED->getNumPositiveBits();
10346
10347 // Check the bitwidth.
10348 if (BitsNeeded > FieldWidth) {
10349 Expr *WidthExpr = Bitfield->getBitWidth();
10350 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10351 << Bitfield << ED;
10352 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10353 << BitsNeeded << ED << WidthExpr->getSourceRange();
10354 }
10355 }
10356
10357 return false;
10358 }
10359
10360 llvm::APSInt Value = Result.Val.getInt();
10361
10362 unsigned OriginalWidth = Value.getBitWidth();
10363
10364 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
10365 // false positives where the user is demonstrating they intend to use the
10366 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
10367 // to a one-bit bit-field to see if the value came from a macro named 'true'.
10368 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
10369 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
10370 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
10371 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
10372 S.findMacroSpelling(MaybeMacroLoc, "true"))
10373 return false;
10374 }
10375
10376 if (!Value.isSigned() || Value.isNegative())
10377 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10378 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10379 OriginalWidth = Value.getSignificantBits();
10380
10381 if (OriginalWidth <= FieldWidth)
10382 return false;
10383
10384 // Compute the value which the bitfield will contain.
10385 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10386 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10387
10388 // Check whether the stored value is equal to the original value.
10389 TruncatedValue = TruncatedValue.extend(OriginalWidth);
10390 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10391 return false;
10392
10393 std::string PrettyValue = toString(Value, 10);
10394 std::string PrettyTrunc = toString(TruncatedValue, 10);
10395
10396 S.Diag(InitLoc, OneAssignedToOneBitBitfield
10397 ? diag::warn_impcast_single_bit_bitield_precision_constant
10398 : diag::warn_impcast_bitfield_precision_constant)
10399 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10400 << Init->getSourceRange();
10401
10402 return true;
10403}
10404
10405/// Analyze the given simple or compound assignment for warning-worthy
10406/// operations.
10408 // Just recurse on the LHS.
10409 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10410
10411 // We want to recurse on the RHS as normal unless we're assigning to
10412 // a bitfield.
10413 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10414 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10415 E->getOperatorLoc())) {
10416 // Recurse, ignoring any implicit conversions on the RHS.
10417 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10418 E->getOperatorLoc());
10419 }
10420 }
10421
10422 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10423
10424 // Diagnose implicitly sequentially-consistent atomic assignment.
10425 if (E->getLHS()->getType()->isAtomicType())
10426 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10427}
10428
10429/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10430static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10431 SourceLocation CContext, unsigned diag,
10432 bool pruneControlFlow = false) {
10433 if (pruneControlFlow) {
10435 S.PDiag(diag)
10436 << SourceType << T << E->getSourceRange()
10437 << SourceRange(CContext));
10438 return;
10439 }
10440 S.Diag(E->getExprLoc(), diag)
10441 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10442}
10443
10444/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10446 SourceLocation CContext,
10447 unsigned diag, bool pruneControlFlow = false) {
10448 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10449}
10450
10451/// Diagnose an implicit cast from a floating point value to an integer value.
10453 SourceLocation CContext) {
10454 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10455 const bool PruneWarnings = S.inTemplateInstantiation();
10456
10457 Expr *InnerE = E->IgnoreParenImpCasts();
10458 // We also want to warn on, e.g., "int i = -1.234"
10459 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10460 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10461 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10462
10463 const bool IsLiteral =
10464 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10465
10466 llvm::APFloat Value(0.0);
10467 bool IsConstant =
10469 if (!IsConstant) {
10470 if (S.ObjC().isSignedCharBool(T)) {
10472 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10473 << E->getType());
10474 }
10475
10476 return DiagnoseImpCast(S, E, T, CContext,
10477 diag::warn_impcast_float_integer, PruneWarnings);
10478 }
10479
10480 bool isExact = false;
10481
10482 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10484 llvm::APFloat::opStatus Result = Value.convertToInteger(
10485 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10486
10487 // FIXME: Force the precision of the source value down so we don't print
10488 // digits which are usually useless (we don't really care here if we
10489 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10490 // would automatically print the shortest representation, but it's a bit
10491 // tricky to implement.
10492 SmallString<16> PrettySourceValue;
10493 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10494 precision = (precision * 59 + 195) / 196;
10495 Value.toString(PrettySourceValue, precision);
10496
10497 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
10499 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10500 << PrettySourceValue);
10501 }
10502
10503 if (Result == llvm::APFloat::opOK && isExact) {
10504 if (IsLiteral) return;
10505 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10506 PruneWarnings);
10507 }
10508
10509 // Conversion of a floating-point value to a non-bool integer where the
10510 // integral part cannot be represented by the integer type is undefined.
10511 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10512 return DiagnoseImpCast(
10513 S, E, T, CContext,
10514 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10515 : diag::warn_impcast_float_to_integer_out_of_range,
10516 PruneWarnings);
10517
10518 unsigned DiagID = 0;
10519 if (IsLiteral) {
10520 // Warn on floating point literal to integer.
10521 DiagID = diag::warn_impcast_literal_float_to_integer;
10522 } else if (IntegerValue == 0) {
10523 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10524 return DiagnoseImpCast(S, E, T, CContext,
10525 diag::warn_impcast_float_integer, PruneWarnings);
10526 }
10527 // Warn on non-zero to zero conversion.
10528 DiagID = diag::warn_impcast_float_to_integer_zero;
10529 } else {
10530 if (IntegerValue.isUnsigned()) {
10531 if (!IntegerValue.isMaxValue()) {
10532 return DiagnoseImpCast(S, E, T, CContext,
10533 diag::warn_impcast_float_integer, PruneWarnings);
10534 }
10535 } else { // IntegerValue.isSigned()
10536 if (!IntegerValue.isMaxSignedValue() &&
10537 !IntegerValue.isMinSignedValue()) {
10538 return DiagnoseImpCast(S, E, T, CContext,
10539 diag::warn_impcast_float_integer, PruneWarnings);
10540 }
10541 }
10542 // Warn on evaluatable floating point expression to integer conversion.
10543 DiagID = diag::warn_impcast_float_to_integer;
10544 }
10545
10546 SmallString<16> PrettyTargetValue;
10547 if (IsBool)
10548 PrettyTargetValue = Value.isZero() ? "false" : "true";
10549 else
10550 IntegerValue.toString(PrettyTargetValue);
10551
10552 if (PruneWarnings) {
10554 S.PDiag(DiagID)
10555 << E->getType() << T.getUnqualifiedType()
10556 << PrettySourceValue << PrettyTargetValue
10557 << E->getSourceRange() << SourceRange(CContext));
10558 } else {
10559 S.Diag(E->getExprLoc(), DiagID)
10560 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10561 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10562 }
10563}
10564
10565/// Analyze the given compound assignment for the possible losing of
10566/// floating-point precision.
10568 assert(isa<CompoundAssignOperator>(E) &&
10569 "Must be compound assignment operation");
10570 // Recurse on the LHS and RHS in here
10571 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10572 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10573
10574 if (E->getLHS()->getType()->isAtomicType())
10575 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10576
10577 // Now check the outermost expression
10578 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10579 const auto *RBT = cast<CompoundAssignOperator>(E)
10580 ->getComputationResultType()
10581 ->getAs<BuiltinType>();
10582
10583 // The below checks assume source is floating point.
10584 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10585
10586 // If source is floating point but target is an integer.
10587 if (ResultBT->isInteger())
10588 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10589 E->getExprLoc(), diag::warn_impcast_float_integer);
10590
10591 if (!ResultBT->isFloatingPoint())
10592 return;
10593
10594 // If both source and target are floating points, warn about losing precision.
10596 QualType(ResultBT, 0), QualType(RBT, 0));
10597 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10598 // warn about dropping FP rank.
10599 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10600 diag::warn_impcast_float_result_precision);
10601}
10602
10603static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10604 IntRange Range) {
10605 if (!Range.Width) return "0";
10606
10607 llvm::APSInt ValueInRange = Value;
10608 ValueInRange.setIsSigned(!Range.NonNegative);
10609 ValueInRange = ValueInRange.trunc(Range.Width);
10610 return toString(ValueInRange, 10);
10611}
10612
10613static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10614 if (!isa<ImplicitCastExpr>(Ex))
10615 return false;
10616
10617 Expr *InnerE = Ex->IgnoreParenImpCasts();
10619 const Type *Source =
10621 if (Target->isDependentType())
10622 return false;
10623
10624 const BuiltinType *FloatCandidateBT =
10625 dyn_cast<BuiltinType>(ToBool ? Source : Target);
10626 const Type *BoolCandidateType = ToBool ? Target : Source;
10627
10628 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10629 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10630}
10631
10633 SourceLocation CC) {
10634 unsigned NumArgs = TheCall->getNumArgs();
10635 for (unsigned i = 0; i < NumArgs; ++i) {
10636 Expr *CurrA = TheCall->getArg(i);
10637 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10638 continue;
10639
10640 bool IsSwapped = ((i > 0) &&
10641 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10642 IsSwapped |= ((i < (NumArgs - 1)) &&
10643 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10644 if (IsSwapped) {
10645 // Warn on this floating-point to bool conversion.
10647 CurrA->getType(), CC,
10648 diag::warn_impcast_floating_point_to_bool);
10649 }
10650 }
10651}
10652
10654 SourceLocation CC) {
10655 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10656 E->getExprLoc()))
10657 return;
10658
10659 // Don't warn on functions which have return type nullptr_t.
10660 if (isa<CallExpr>(E))
10661 return;
10662
10663 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10664 const Expr *NewE = E->IgnoreParenImpCasts();
10665 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
10666 bool HasNullPtrType = NewE->getType()->isNullPtrType();
10667 if (!IsGNUNullExpr && !HasNullPtrType)
10668 return;
10669
10670 // Return if target type is a safe conversion.
10671 if (T->isAnyPointerType() || T->isBlockPointerType() ||
10673 return;
10674
10676
10677 // Venture through the macro stacks to get to the source of macro arguments.
10678 // The new location is a better location than the complete location that was
10679 // passed in.
10682
10683 // __null is usually wrapped in a macro. Go up a macro if that is the case.
10684 if (IsGNUNullExpr && Loc.isMacroID()) {
10685 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10686 Loc, S.SourceMgr, S.getLangOpts());
10687 if (MacroName == "NULL")
10689 }
10690
10691 // Only warn if the null and context location are in the same macro expansion.
10692 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10693 return;
10694
10695 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10696 << HasNullPtrType << T << SourceRange(CC)
10699}
10700
10701// Helper function to filter out cases for constant width constant conversion.
10702// Don't warn on char array initialization or for non-decimal values.
10704 SourceLocation CC) {
10705 // If initializing from a constant, and the constant starts with '0',
10706 // then it is a binary, octal, or hexadecimal. Allow these constants
10707 // to fill all the bits, even if there is a sign change.
10708 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10709 const char FirstLiteralCharacter =
10710 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10711 if (FirstLiteralCharacter == '0')
10712 return false;
10713 }
10714
10715 // If the CC location points to a '{', and the type is char, then assume
10716 // assume it is an array initialization.
10717 if (CC.isValid() && T->isCharType()) {
10718 const char FirstContextCharacter =
10720 if (FirstContextCharacter == '{')
10721 return false;
10722 }
10723
10724 return true;
10725}
10726
10728 const auto *IL = dyn_cast<IntegerLiteral>(E);
10729 if (!IL) {
10730 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
10731 if (UO->getOpcode() == UO_Minus)
10732 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
10733 }
10734 }
10735
10736 return IL;
10737}
10738
10740 E = E->IgnoreParenImpCasts();
10741 SourceLocation ExprLoc = E->getExprLoc();
10742
10743 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10744 BinaryOperator::Opcode Opc = BO->getOpcode();
10746 // Do not diagnose unsigned shifts.
10747 if (Opc == BO_Shl) {
10748 const auto *LHS = getIntegerLiteral(BO->getLHS());
10749 const auto *RHS = getIntegerLiteral(BO->getRHS());
10750 if (LHS && LHS->getValue() == 0)
10751 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
10752 else if (!E->isValueDependent() && LHS && RHS &&
10753 RHS->getValue().isNonNegative() &&
10755 S.Diag(ExprLoc, diag::warn_left_shift_always)
10756 << (Result.Val.getInt() != 0);
10757 else if (E->getType()->isSignedIntegerType())
10758 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
10759 }
10760 }
10761
10762 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10763 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
10764 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
10765 if (!LHS || !RHS)
10766 return;
10767 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
10768 (RHS->getValue() == 0 || RHS->getValue() == 1))
10769 // Do not diagnose common idioms.
10770 return;
10771 if (LHS->getValue() != 0 && RHS->getValue() != 0)
10772 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
10773 }
10774}
10775
10777 bool *ICContext, bool IsListInit) {
10778 if (E->isTypeDependent() || E->isValueDependent()) return;
10779
10780 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
10782 if (Source == Target) return;
10783 if (Target->isDependentType()) return;
10784
10785 // If the conversion context location is invalid don't complain. We also
10786 // don't want to emit a warning if the issue occurs from the expansion of
10787 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10788 // delay this check as long as possible. Once we detect we are in that
10789 // scenario, we just return.
10790 if (CC.isInvalid())
10791 return;
10792
10793 if (Source->isAtomicType())
10794 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10795
10796 // Diagnose implicit casts to bool.
10797 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10798 if (isa<StringLiteral>(E))
10799 // Warn on string literal to bool. Checks for string literals in logical
10800 // and expressions, for instance, assert(0 && "error here"), are
10801 // prevented by a check in AnalyzeImplicitConversions().
10802 return DiagnoseImpCast(*this, E, T, CC,
10803 diag::warn_impcast_string_literal_to_bool);
10804 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10805 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10806 // This covers the literal expressions that evaluate to Objective-C
10807 // objects.
10808 return DiagnoseImpCast(*this, E, T, CC,
10809 diag::warn_impcast_objective_c_literal_to_bool);
10810 }
10811 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10812 // Warn on pointer to bool conversion that is always true.
10814 SourceRange(CC));
10815 }
10816 }
10817
10818 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
10819 // is a typedef for signed char (macOS), then that constant value has to be 1
10820 // or 0.
10821 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
10824 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
10826 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
10827 << toString(Result.Val.getInt(), 10));
10828 }
10829 return;
10830 }
10831 }
10832
10833 // Check implicit casts from Objective-C collection literals to specialized
10834 // collection types, e.g., NSArray<NSString *> *.
10835 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10836 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
10837 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10838 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
10839
10840 // Strip vector types.
10841 if (isa<VectorType>(Source)) {
10842 if (Target->isSveVLSBuiltinType() &&
10844 QualType(Source, 0)) ||
10846 QualType(Source, 0))))
10847 return;
10848
10849 if (Target->isRVVVLSBuiltinType() &&
10851 QualType(Source, 0)) ||
10853 QualType(Source, 0))))
10854 return;
10855
10856 if (!isa<VectorType>(Target)) {
10857 if (SourceMgr.isInSystemMacro(CC))
10858 return;
10859 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
10860 } else if (getLangOpts().HLSL &&
10861 Target->castAs<VectorType>()->getNumElements() <
10862 Source->castAs<VectorType>()->getNumElements()) {
10863 // Diagnose vector truncation but don't return. We may also want to
10864 // diagnose an element conversion.
10865 DiagnoseImpCast(*this, E, T, CC,
10866 diag::warn_hlsl_impcast_vector_truncation);
10867 }
10868
10869 // If the vector cast is cast between two vectors of the same size, it is
10870 // a bitcast, not a conversion, except under HLSL where it is a conversion.
10871 if (!getLangOpts().HLSL &&
10873 return;
10874
10875 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10876 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10877 }
10878 if (auto VecTy = dyn_cast<VectorType>(Target))
10879 Target = VecTy->getElementType().getTypePtr();
10880
10881 // Strip complex types.
10882 if (isa<ComplexType>(Source)) {
10883 if (!isa<ComplexType>(Target)) {
10884 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10885 return;
10886
10887 return DiagnoseImpCast(*this, E, T, CC,
10889 ? diag::err_impcast_complex_scalar
10890 : diag::warn_impcast_complex_scalar);
10891 }
10892
10893 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10894 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10895 }
10896
10897 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10898 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10899
10900 // Strip SVE vector types
10901 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
10902 // Need the original target type for vector type checks
10903 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
10904 // Handle conversion from scalable to fixed when msve-vector-bits is
10905 // specified
10906 if (Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
10907 QualType(Source, 0)) ||
10908 Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
10909 QualType(Source, 0)))
10910 return;
10911
10912 // If the vector cast is cast between two vectors of the same size, it is
10913 // a bitcast, not a conversion.
10915 return;
10916
10917 Source = SourceBT->getSveEltType(Context).getTypePtr();
10918 }
10919
10920 if (TargetBT && TargetBT->isSveVLSBuiltinType())
10921 Target = TargetBT->getSveEltType(Context).getTypePtr();
10922
10923 // If the source is floating point...
10924 if (SourceBT && SourceBT->isFloatingPoint()) {
10925 // ...and the target is floating point...
10926 if (TargetBT && TargetBT->isFloatingPoint()) {
10927 // ...then warn if we're dropping FP rank.
10928
10930 QualType(SourceBT, 0), QualType(TargetBT, 0));
10931 if (Order > 0) {
10932 // Don't warn about float constants that are precisely
10933 // representable in the target type.
10934 Expr::EvalResult result;
10935 if (E->EvaluateAsRValue(result, Context)) {
10936 // Value might be a float, a float vector, or a float complex.
10938 result.Val,
10940 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10941 return;
10942 }
10943
10944 if (SourceMgr.isInSystemMacro(CC))
10945 return;
10946
10947 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
10948 }
10949 // ... or possibly if we're increasing rank, too
10950 else if (Order < 0) {
10951 if (SourceMgr.isInSystemMacro(CC))
10952 return;
10953
10954 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
10955 }
10956 return;
10957 }
10958
10959 // If the target is integral, always warn.
10960 if (TargetBT && TargetBT->isInteger()) {
10961 if (SourceMgr.isInSystemMacro(CC))
10962 return;
10963
10964 DiagnoseFloatingImpCast(*this, E, T, CC);
10965 }
10966
10967 // Detect the case where a call result is converted from floating-point to
10968 // to bool, and the final argument to the call is converted from bool, to
10969 // discover this typo:
10970 //
10971 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10972 //
10973 // FIXME: This is an incredibly special case; is there some more general
10974 // way to detect this class of misplaced-parentheses bug?
10975 if (Target->isBooleanType() && isa<CallExpr>(E)) {
10976 // Check last argument of function call to see if it is an
10977 // implicit cast from a type matching the type the result
10978 // is being cast to.
10979 CallExpr *CEx = cast<CallExpr>(E);
10980 if (unsigned NumArgs = CEx->getNumArgs()) {
10981 Expr *LastA = CEx->getArg(NumArgs - 1);
10982 Expr *InnerE = LastA->IgnoreParenImpCasts();
10983 if (isa<ImplicitCastExpr>(LastA) &&
10984 InnerE->getType()->isBooleanType()) {
10985 // Warn on this floating-point to bool conversion
10986 DiagnoseImpCast(*this, E, T, CC,
10987 diag::warn_impcast_floating_point_to_bool);
10988 }
10989 }
10990 }
10991 return;
10992 }
10993
10994 // Valid casts involving fixed point types should be accounted for here.
10995 if (Source->isFixedPointType()) {
10996 if (Target->isUnsaturatedFixedPointType()) {
11000 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
11001 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
11002 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
11003 if (Value > MaxVal || Value < MinVal) {
11005 PDiag(diag::warn_impcast_fixed_point_range)
11006 << Value.toString() << T
11007 << E->getSourceRange()
11008 << clang::SourceRange(CC));
11009 return;
11010 }
11011 }
11012 } else if (Target->isIntegerType()) {
11016 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
11017
11018 bool Overflowed;
11019 llvm::APSInt IntResult = FXResult.convertToInt(
11020 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
11021 &Overflowed);
11022
11023 if (Overflowed) {
11025 PDiag(diag::warn_impcast_fixed_point_range)
11026 << FXResult.toString() << T
11027 << E->getSourceRange()
11028 << clang::SourceRange(CC));
11029 return;
11030 }
11031 }
11032 }
11033 } else if (Target->isUnsaturatedFixedPointType()) {
11034 if (Source->isIntegerType()) {
11038 llvm::APSInt Value = Result.Val.getInt();
11039
11040 bool Overflowed;
11041 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
11042 Value, Context.getFixedPointSemantics(T), &Overflowed);
11043
11044 if (Overflowed) {
11046 PDiag(diag::warn_impcast_fixed_point_range)
11047 << toString(Value, /*Radix=*/10) << T
11048 << E->getSourceRange()
11049 << clang::SourceRange(CC));
11050 return;
11051 }
11052 }
11053 }
11054 }
11055
11056 // If we are casting an integer type to a floating point type without
11057 // initialization-list syntax, we might lose accuracy if the floating
11058 // point type has a narrower significand than the integer type.
11059 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11060 TargetBT->isFloatingType() && !IsListInit) {
11061 // Determine the number of precision bits in the source integer type.
11062 IntRange SourceRange =
11064 /*Approximate=*/true);
11065 unsigned int SourcePrecision = SourceRange.Width;
11066
11067 // Determine the number of precision bits in the
11068 // target floating point type.
11069 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11070 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11071
11072 if (SourcePrecision > 0 && TargetPrecision > 0 &&
11073 SourcePrecision > TargetPrecision) {
11074
11075 if (std::optional<llvm::APSInt> SourceInt =
11077 // If the source integer is a constant, convert it to the target
11078 // floating point type. Issue a warning if the value changes
11079 // during the whole conversion.
11080 llvm::APFloat TargetFloatValue(
11081 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11082 llvm::APFloat::opStatus ConversionStatus =
11083 TargetFloatValue.convertFromAPInt(
11084 *SourceInt, SourceBT->isSignedInteger(),
11085 llvm::APFloat::rmNearestTiesToEven);
11086
11087 if (ConversionStatus != llvm::APFloat::opOK) {
11088 SmallString<32> PrettySourceValue;
11089 SourceInt->toString(PrettySourceValue, 10);
11090 SmallString<32> PrettyTargetValue;
11091 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11092
11094 E->getExprLoc(), E,
11095 PDiag(diag::warn_impcast_integer_float_precision_constant)
11096 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11097 << E->getSourceRange() << clang::SourceRange(CC));
11098 }
11099 } else {
11100 // Otherwise, the implicit conversion may lose precision.
11101 DiagnoseImpCast(*this, E, T, CC,
11102 diag::warn_impcast_integer_float_precision);
11103 }
11104 }
11105 }
11106
11107 DiagnoseNullConversion(*this, E, T, CC);
11108
11110
11111 if (Target->isBooleanType())
11113
11114 if (!Source->isIntegerType() || !Target->isIntegerType())
11115 return;
11116
11117 // TODO: remove this early return once the false positives for constant->bool
11118 // in templates, macros, etc, are reduced or removed.
11119 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11120 return;
11121
11122 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
11123 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11125 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11126 << E->getType());
11127 }
11128
11129 IntRange SourceTypeRange =
11130 IntRange::forTargetOfCanonicalType(Context, Source);
11131 IntRange LikelySourceRange = GetExprRange(
11132 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
11133 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
11134
11135 if (LikelySourceRange.Width > TargetRange.Width) {
11136 // If the source is a constant, use a default-on diagnostic.
11137 // TODO: this should happen for bitfield stores, too.
11141 llvm::APSInt Value(32);
11142 Value = Result.Val.getInt();
11143
11144 if (SourceMgr.isInSystemMacro(CC))
11145 return;
11146
11147 std::string PrettySourceValue = toString(Value, 10);
11148 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11149
11151 PDiag(diag::warn_impcast_integer_precision_constant)
11152 << PrettySourceValue << PrettyTargetValue
11153 << E->getType() << T << E->getSourceRange()
11154 << SourceRange(CC));
11155 return;
11156 }
11157
11158 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11159 if (SourceMgr.isInSystemMacro(CC))
11160 return;
11161
11162 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
11163 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
11164 /* pruneControlFlow */ true);
11165 return DiagnoseImpCast(*this, E, T, CC,
11166 diag::warn_impcast_integer_precision);
11167 }
11168
11169 if (TargetRange.Width > SourceTypeRange.Width) {
11170 if (auto *UO = dyn_cast<UnaryOperator>(E))
11171 if (UO->getOpcode() == UO_Minus)
11172 if (Source->isUnsignedIntegerType()) {
11173 if (Target->isUnsignedIntegerType())
11174 return DiagnoseImpCast(*this, E, T, CC,
11175 diag::warn_impcast_high_order_zero_bits);
11176 if (Target->isSignedIntegerType())
11177 return DiagnoseImpCast(*this, E, T, CC,
11178 diag::warn_impcast_nonnegative_result);
11179 }
11180 }
11181
11182 if (TargetRange.Width == LikelySourceRange.Width &&
11183 !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
11184 Source->isSignedIntegerType()) {
11185 // Warn when doing a signed to signed conversion, warn if the positive
11186 // source value is exactly the width of the target type, which will
11187 // cause a negative value to be stored.
11188
11192 llvm::APSInt Value = Result.Val.getInt();
11193 if (isSameWidthConstantConversion(*this, E, T, CC)) {
11194 std::string PrettySourceValue = toString(Value, 10);
11195 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11196
11197 Diag(E->getExprLoc(),
11198 PDiag(diag::warn_impcast_integer_precision_constant)
11199 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11200 << E->getSourceRange() << SourceRange(CC));
11201 return;
11202 }
11203 }
11204
11205 // Fall through for non-constants to give a sign conversion warning.
11206 }
11207
11208 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
11209 ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
11210 (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
11211 LikelySourceRange.Width == TargetRange.Width))) {
11212 if (SourceMgr.isInSystemMacro(CC))
11213 return;
11214
11215 if (SourceBT && SourceBT->isInteger() && TargetBT &&
11216 TargetBT->isInteger() &&
11217 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
11218 return;
11219 }
11220
11221 unsigned DiagID = diag::warn_impcast_integer_sign;
11222
11223 // Traditionally, gcc has warned about this under -Wsign-compare.
11224 // We also want to warn about it in -Wconversion.
11225 // So if -Wconversion is off, use a completely identical diagnostic
11226 // in the sign-compare group.
11227 // The conditional-checking code will
11228 if (ICContext) {
11229 DiagID = diag::warn_impcast_integer_sign_conditional;
11230 *ICContext = true;
11231 }
11232
11233 return DiagnoseImpCast(*this, E, T, CC, DiagID);
11234 }
11235
11236 // Diagnose conversions between different enumeration types.
11237 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11238 // type, to give us better diagnostics.
11239 QualType SourceType = E->getEnumCoercedType(Context);
11240 Source = Context.getCanonicalType(SourceType).getTypePtr();
11241
11242 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11243 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11244 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11245 TargetEnum->getDecl()->hasNameForLinkage() &&
11246 SourceEnum != TargetEnum) {
11247 if (SourceMgr.isInSystemMacro(CC))
11248 return;
11249
11250 return DiagnoseImpCast(*this, E, SourceType, T, CC,
11251 diag::warn_impcast_different_enum_types);
11252 }
11253}
11254
11257
11259 SourceLocation CC, bool &ICContext) {
11260 E = E->IgnoreParenImpCasts();
11261 // Diagnose incomplete type for second or third operand in C.
11262 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
11263 S.RequireCompleteExprType(E, diag::err_incomplete_type);
11264
11265 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
11266 return CheckConditionalOperator(S, CO, CC, T);
11267
11269 if (E->getType() != T)
11270 return S.CheckImplicitConversion(E, T, CC, &ICContext);
11271}
11272
11275 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11276
11277 Expr *TrueExpr = E->getTrueExpr();
11278 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
11279 TrueExpr = BCO->getCommon();
11280
11281 bool Suspicious = false;
11282 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
11283 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11284
11285 if (T->isBooleanType())
11287
11288 // If -Wconversion would have warned about either of the candidates
11289 // for a signedness conversion to the context type...
11290 if (!Suspicious) return;
11291
11292 // ...but it's currently ignored...
11293 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11294 return;
11295
11296 // ...then check whether it would have warned about either of the
11297 // candidates for a signedness conversion to the condition type.
11298 if (E->getType() == T) return;
11299
11300 Suspicious = false;
11302 &Suspicious);
11303 if (!Suspicious)
11304 S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(),
11305 E->getType(), CC, &Suspicious);
11306}
11307
11308/// Check conversion of given expression to boolean.
11309/// Input argument E is a logical expression.
11311 // Run the bool-like conversion checks only for C since there bools are
11312 // still not used as the return type from "boolean" operators or as the input
11313 // type for conditional operators.
11314 if (S.getLangOpts().CPlusPlus)
11315 return;
11317 return;
11319}
11320
11321namespace {
11322struct AnalyzeImplicitConversionsWorkItem {
11323 Expr *E;
11324 SourceLocation CC;
11325 bool IsListInit;
11326};
11327}
11328
11329/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
11330/// that should be visited are added to WorkList.
11332 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
11334 Expr *OrigE = Item.E;
11335 SourceLocation CC = Item.CC;
11336
11337 QualType T = OrigE->getType();
11338 Expr *E = OrigE->IgnoreParenImpCasts();
11339
11340 // Propagate whether we are in a C++ list initialization expression.
11341 // If so, we do not issue warnings for implicit int-float conversion
11342 // precision loss, because C++11 narrowing already handles it.
11343 bool IsListInit = Item.IsListInit ||
11344 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11345
11346 if (E->isTypeDependent() || E->isValueDependent())
11347 return;
11348
11349 Expr *SourceExpr = E;
11350 // Examine, but don't traverse into the source expression of an
11351 // OpaqueValueExpr, since it may have multiple parents and we don't want to
11352 // emit duplicate diagnostics. Its fine to examine the form or attempt to
11353 // evaluate it in the context of checking the specific conversion to T though.
11354 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11355 if (auto *Src = OVE->getSourceExpr())
11356 SourceExpr = Src;
11357
11358 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
11359 if (UO->getOpcode() == UO_Not &&
11360 UO->getSubExpr()->isKnownToHaveBooleanValue())
11361 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11362 << OrigE->getSourceRange() << T->isBooleanType()
11363 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11364
11365 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
11366 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
11367 BO->getLHS()->isKnownToHaveBooleanValue() &&
11368 BO->getRHS()->isKnownToHaveBooleanValue() &&
11369 BO->getLHS()->HasSideEffects(S.Context) &&
11370 BO->getRHS()->HasSideEffects(S.Context)) {
11372 const LangOptions &LO = S.getLangOpts();
11373 SourceLocation BLoc = BO->getOperatorLoc();
11374 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
11375 StringRef SR = clang::Lexer::getSourceText(
11376 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
11377 // To reduce false positives, only issue the diagnostic if the operator
11378 // is explicitly spelled as a punctuator. This suppresses the diagnostic
11379 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
11380 // in C, along with other macro spellings the user might invent.
11381 if (SR.str() == "&" || SR.str() == "|") {
11382
11383 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
11384 << (BO->getOpcode() == BO_And ? "&" : "|")
11385 << OrigE->getSourceRange()
11387 BO->getOperatorLoc(),
11388 (BO->getOpcode() == BO_And ? "&&" : "||"));
11389 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
11390 }
11391 }
11392
11393 // For conditional operators, we analyze the arguments as if they
11394 // were being fed directly into the output.
11395 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
11396 CheckConditionalOperator(S, CO, CC, T);
11397 return;
11398 }
11399
11400 // Check implicit argument conversions for function calls.
11401 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
11403
11404 // Go ahead and check any implicit conversions we might have skipped.
11405 // The non-canonical typecheck is just an optimization;
11406 // CheckImplicitConversion will filter out dead implicit conversions.
11407 if (SourceExpr->getType() != T)
11408 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
11409
11410 // Now continue drilling into this expression.
11411
11412 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11413 // The bound subexpressions in a PseudoObjectExpr are not reachable
11414 // as transitive children.
11415 // FIXME: Use a more uniform representation for this.
11416 for (auto *SE : POE->semantics())
11417 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11418 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
11419 }
11420
11421 // Skip past explicit casts.
11422 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11423 E = CE->getSubExpr()->IgnoreParenImpCasts();
11424 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11425 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11426 WorkList.push_back({E, CC, IsListInit});
11427 return;
11428 }
11429
11430 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11431 // Do a somewhat different check with comparison operators.
11432 if (BO->isComparisonOp())
11433 return AnalyzeComparison(S, BO);
11434
11435 // And with simple assignments.
11436 if (BO->getOpcode() == BO_Assign)
11437 return AnalyzeAssignment(S, BO);
11438 // And with compound assignments.
11439 if (BO->isAssignmentOp())
11440 return AnalyzeCompoundAssignment(S, BO);
11441 }
11442
11443 // These break the otherwise-useful invariant below. Fortunately,
11444 // we don't really need to recurse into them, because any internal
11445 // expressions should have been analyzed already when they were
11446 // built into statements.
11447 if (isa<StmtExpr>(E)) return;
11448
11449 // Don't descend into unevaluated contexts.
11450 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11451
11452 // Now just recurse over the expression's children.
11453 CC = E->getExprLoc();
11454 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11455 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11456 for (Stmt *SubStmt : E->children()) {
11457 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11458 if (!ChildExpr)
11459 continue;
11460
11461 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
11462 if (ChildExpr == CSE->getOperand())
11463 // Do not recurse over a CoroutineSuspendExpr's operand.
11464 // The operand is also a subexpression of getCommonExpr(), and
11465 // recursing into it directly would produce duplicate diagnostics.
11466 continue;
11467
11468 if (IsLogicalAndOperator &&
11469 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11470 // Ignore checking string literals that are in logical and operators.
11471 // This is a common pattern for asserts.
11472 continue;
11473 WorkList.push_back({ChildExpr, CC, IsListInit});
11474 }
11475
11476 if (BO && BO->isLogicalOp()) {
11477 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11478 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11479 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11480
11481 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11482 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11483 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11484 }
11485
11486 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11487 if (U->getOpcode() == UO_LNot) {
11488 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11489 } else if (U->getOpcode() != UO_AddrOf) {
11490 if (U->getSubExpr()->getType()->isAtomicType())
11491 S.Diag(U->getSubExpr()->getBeginLoc(),
11492 diag::warn_atomic_implicit_seq_cst);
11493 }
11494 }
11495}
11496
11497/// AnalyzeImplicitConversions - Find and report any interesting
11498/// implicit conversions in the given expression. There are a couple
11499/// of competing diagnostics here, -Wconversion and -Wsign-compare.
11501 bool IsListInit/*= false*/) {
11503 WorkList.push_back({OrigE, CC, IsListInit});
11504 while (!WorkList.empty())
11505 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
11506}
11507
11508// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11509// Returns true when emitting a warning about taking the address of a reference.
11510static bool CheckForReference(Sema &SemaRef, const Expr *E,
11511 const PartialDiagnostic &PD) {
11512 E = E->IgnoreParenImpCasts();
11513
11514 const FunctionDecl *FD = nullptr;
11515
11516 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11517 if (!DRE->getDecl()->getType()->isReferenceType())
11518 return false;
11519 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11520 if (!M->getMemberDecl()->getType()->isReferenceType())
11521 return false;
11522 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11523 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11524 return false;
11525 FD = Call->getDirectCallee();
11526 } else {
11527 return false;
11528 }
11529
11530 SemaRef.Diag(E->getExprLoc(), PD);
11531
11532 // If possible, point to location of function.
11533 if (FD) {
11534 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11535 }
11536
11537 return true;
11538}
11539
11540// Returns true if the SourceLocation is expanded from any macro body.
11541// Returns false if the SourceLocation is invalid, is from not in a macro
11542// expansion, or is from expanded from a top-level macro argument.
11544 if (Loc.isInvalid())
11545 return false;
11546
11547 while (Loc.isMacroID()) {
11548 if (SM.isMacroBodyExpansion(Loc))
11549 return true;
11550 Loc = SM.getImmediateMacroCallerLoc(Loc);
11551 }
11552
11553 return false;
11554}
11555
11558 bool IsEqual, SourceRange Range) {
11559 if (!E)
11560 return;
11561
11562 // Don't warn inside macros.
11563 if (E->getExprLoc().isMacroID()) {
11565 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11567 return;
11568 }
11569 E = E->IgnoreImpCasts();
11570
11571 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11572
11573 if (isa<CXXThisExpr>(E)) {
11574 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11575 : diag::warn_this_bool_conversion;
11576 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11577 return;
11578 }
11579
11580 bool IsAddressOf = false;
11581
11582 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
11583 if (UO->getOpcode() != UO_AddrOf)
11584 return;
11585 IsAddressOf = true;
11586 E = UO->getSubExpr();
11587 }
11588
11589 if (IsAddressOf) {
11590 unsigned DiagID = IsCompare
11591 ? diag::warn_address_of_reference_null_compare
11592 : diag::warn_address_of_reference_bool_conversion;
11593 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11594 << IsEqual;
11595 if (CheckForReference(*this, E, PD)) {
11596 return;
11597 }
11598 }
11599
11600 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11601 bool IsParam = isa<NonNullAttr>(NonnullAttr);
11602 std::string Str;
11603 llvm::raw_string_ostream S(Str);
11604 E->printPretty(S, nullptr, getPrintingPolicy());
11605 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11606 : diag::warn_cast_nonnull_to_bool;
11607 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11608 << E->getSourceRange() << Range << IsEqual;
11609 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11610 };
11611
11612 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11613 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11614 if (auto *Callee = Call->getDirectCallee()) {
11615 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11616 ComplainAboutNonnullParamOrCall(A);
11617 return;
11618 }
11619 }
11620 }
11621
11622 // Complain if we are converting a lambda expression to a boolean value
11623 // outside of instantiation.
11624 if (!inTemplateInstantiation()) {
11625 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
11626 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
11627 MRecordDecl && MRecordDecl->isLambda()) {
11628 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
11629 << /*LambdaPointerConversionOperatorType=*/3
11630 << MRecordDecl->getSourceRange() << Range << IsEqual;
11631 return;
11632 }
11633 }
11634 }
11635
11636 // Expect to find a single Decl. Skip anything more complicated.
11637 ValueDecl *D = nullptr;
11638 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11639 D = R->getDecl();
11640 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11641 D = M->getMemberDecl();
11642 }
11643
11644 // Weak Decls can be null.
11645 if (!D || D->isWeak())
11646 return;
11647
11648 // Check for parameter decl with nonnull attribute
11649 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11650 if (getCurFunction() &&
11651 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11652 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11653 ComplainAboutNonnullParamOrCall(A);
11654 return;
11655 }
11656
11657 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11658 // Skip function template not specialized yet.
11660 return;
11661 auto ParamIter = llvm::find(FD->parameters(), PV);
11662 assert(ParamIter != FD->param_end());
11663 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11664
11665 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11666 if (!NonNull->args_size()) {
11667 ComplainAboutNonnullParamOrCall(NonNull);
11668 return;
11669 }
11670
11671 for (const ParamIdx &ArgNo : NonNull->args()) {
11672 if (ArgNo.getASTIndex() == ParamNo) {
11673 ComplainAboutNonnullParamOrCall(NonNull);
11674 return;
11675 }
11676 }
11677 }
11678 }
11679 }
11680 }
11681
11682 QualType T = D->getType();
11683 const bool IsArray = T->isArrayType();
11684 const bool IsFunction = T->isFunctionType();
11685
11686 // Address of function is used to silence the function warning.
11687 if (IsAddressOf && IsFunction) {
11688 return;
11689 }
11690
11691 // Found nothing.
11692 if (!IsAddressOf && !IsFunction && !IsArray)
11693 return;
11694
11695 // Pretty print the expression for the diagnostic.
11696 std::string Str;
11697 llvm::raw_string_ostream S(Str);
11698 E->printPretty(S, nullptr, getPrintingPolicy());
11699
11700 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11701 : diag::warn_impcast_pointer_to_bool;
11702 enum {
11703 AddressOf,
11704 FunctionPointer,
11705 ArrayPointer
11706 } DiagType;
11707 if (IsAddressOf)
11708 DiagType = AddressOf;
11709 else if (IsFunction)
11710 DiagType = FunctionPointer;
11711 else if (IsArray)
11712 DiagType = ArrayPointer;
11713 else
11714 llvm_unreachable("Could not determine diagnostic.");
11715 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11716 << Range << IsEqual;
11717
11718 if (!IsFunction)
11719 return;
11720
11721 // Suggest '&' to silence the function warning.
11722 Diag(E->getExprLoc(), diag::note_function_warning_silence)
11724
11725 // Check to see if '()' fixit should be emitted.
11726 QualType ReturnType;
11727 UnresolvedSet<4> NonTemplateOverloads;
11728 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11729 if (ReturnType.isNull())
11730 return;
11731
11732 if (IsCompare) {
11733 // There are two cases here. If there is null constant, the only suggest
11734 // for a pointer return type. If the null is 0, then suggest if the return
11735 // type is a pointer or an integer type.
11736 if (!ReturnType->isPointerType()) {
11737 if (NullKind == Expr::NPCK_ZeroExpression ||
11738 NullKind == Expr::NPCK_ZeroLiteral) {
11739 if (!ReturnType->isIntegerType())
11740 return;
11741 } else {
11742 return;
11743 }
11744 }
11745 } else { // !IsCompare
11746 // For function to bool, only suggest if the function pointer has bool
11747 // return type.
11748 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11749 return;
11750 }
11751 Diag(E->getExprLoc(), diag::note_function_to_function_call)
11753}
11754
11755void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11756 // Don't diagnose in unevaluated contexts.
11758 return;
11759
11760 // Don't diagnose for value- or type-dependent expressions.
11761 if (E->isTypeDependent() || E->isValueDependent())
11762 return;
11763
11764 // Check for array bounds violations in cases where the check isn't triggered
11765 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11766 // ArraySubscriptExpr is on the RHS of a variable initialization.
11767 CheckArrayAccess(E);
11768
11769 // This is not the right CC for (e.g.) a variable initialization.
11770 AnalyzeImplicitConversions(*this, E, CC);
11771}
11772
11773void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11774 ::CheckBoolLikeConversion(*this, E, CC);
11775}
11776
11777void Sema::CheckForIntOverflow (const Expr *E) {
11778 // Use a work list to deal with nested struct initializers.
11780
11781 do {
11782 const Expr *OriginalE = Exprs.pop_back_val();
11783 const Expr *E = OriginalE->IgnoreParenCasts();
11784
11785 if (isa<BinaryOperator, UnaryOperator>(E)) {
11787 continue;
11788 }
11789
11790 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
11791 Exprs.append(InitList->inits().begin(), InitList->inits().end());
11792 else if (isa<ObjCBoxedExpr>(OriginalE))
11794 else if (const auto *Call = dyn_cast<CallExpr>(E))
11795 Exprs.append(Call->arg_begin(), Call->arg_end());
11796 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
11797 Exprs.append(Message->arg_begin(), Message->arg_end());
11798 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
11799 Exprs.append(Construct->arg_begin(), Construct->arg_end());
11800 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
11801 Exprs.push_back(Temporary->getSubExpr());
11802 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
11803 Exprs.push_back(Array->getIdx());
11804 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
11805 Exprs.push_back(Compound->getInitializer());
11806 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
11807 New && New->isArray()) {
11808 if (auto ArraySize = New->getArraySize())
11809 Exprs.push_back(*ArraySize);
11810 }
11811 } while (!Exprs.empty());
11812}
11813
11814namespace {
11815
11816/// Visitor for expressions which looks for unsequenced operations on the
11817/// same object.
11818class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
11820
11821 /// A tree of sequenced regions within an expression. Two regions are
11822 /// unsequenced if one is an ancestor or a descendent of the other. When we
11823 /// finish processing an expression with sequencing, such as a comma
11824 /// expression, we fold its tree nodes into its parent, since they are
11825 /// unsequenced with respect to nodes we will visit later.
11826 class SequenceTree {
11827 struct Value {
11828 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11829 unsigned Parent : 31;
11830 LLVM_PREFERRED_TYPE(bool)
11831 unsigned Merged : 1;
11832 };
11833 SmallVector<Value, 8> Values;
11834
11835 public:
11836 /// A region within an expression which may be sequenced with respect
11837 /// to some other region.
11838 class Seq {
11839 friend class SequenceTree;
11840
11841 unsigned Index;
11842
11843 explicit Seq(unsigned N) : Index(N) {}
11844
11845 public:
11846 Seq() : Index(0) {}
11847 };
11848
11849 SequenceTree() { Values.push_back(Value(0)); }
11850 Seq root() const { return Seq(0); }
11851
11852 /// Create a new sequence of operations, which is an unsequenced
11853 /// subset of \p Parent. This sequence of operations is sequenced with
11854 /// respect to other children of \p Parent.
11855 Seq allocate(Seq Parent) {
11856 Values.push_back(Value(Parent.Index));
11857 return Seq(Values.size() - 1);
11858 }
11859
11860 /// Merge a sequence of operations into its parent.
11861 void merge(Seq S) {
11862 Values[S.Index].Merged = true;
11863 }
11864
11865 /// Determine whether two operations are unsequenced. This operation
11866 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11867 /// should have been merged into its parent as appropriate.
11868 bool isUnsequenced(Seq Cur, Seq Old) {
11869 unsigned C = representative(Cur.Index);
11870 unsigned Target = representative(Old.Index);
11871 while (C >= Target) {
11872 if (C == Target)
11873 return true;
11874 C = Values[C].Parent;
11875 }
11876 return false;
11877 }
11878
11879 private:
11880 /// Pick a representative for a sequence.
11881 unsigned representative(unsigned K) {
11882 if (Values[K].Merged)
11883 // Perform path compression as we go.
11884 return Values[K].Parent = representative(Values[K].Parent);
11885 return K;
11886 }
11887 };
11888
11889 /// An object for which we can track unsequenced uses.
11890 using Object = const NamedDecl *;
11891
11892 /// Different flavors of object usage which we track. We only track the
11893 /// least-sequenced usage of each kind.
11894 enum UsageKind {
11895 /// A read of an object. Multiple unsequenced reads are OK.
11896 UK_Use,
11897
11898 /// A modification of an object which is sequenced before the value
11899 /// computation of the expression, such as ++n in C++.
11900 UK_ModAsValue,
11901
11902 /// A modification of an object which is not sequenced before the value
11903 /// computation of the expression, such as n++.
11904 UK_ModAsSideEffect,
11905
11906 UK_Count = UK_ModAsSideEffect + 1
11907 };
11908
11909 /// Bundle together a sequencing region and the expression corresponding
11910 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
11911 struct Usage {
11912 const Expr *UsageExpr = nullptr;
11913 SequenceTree::Seq Seq;
11914
11915 Usage() = default;
11916 };
11917
11918 struct UsageInfo {
11919 Usage Uses[UK_Count];
11920
11921 /// Have we issued a diagnostic for this object already?
11922 bool Diagnosed = false;
11923
11924 UsageInfo();
11925 };
11926 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11927
11928 Sema &SemaRef;
11929
11930 /// Sequenced regions within the expression.
11931 SequenceTree Tree;
11932
11933 /// Declaration modifications and references which we have seen.
11934 UsageInfoMap UsageMap;
11935
11936 /// The region we are currently within.
11937 SequenceTree::Seq Region;
11938
11939 /// Filled in with declarations which were modified as a side-effect
11940 /// (that is, post-increment operations).
11941 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11942
11943 /// Expressions to check later. We defer checking these to reduce
11944 /// stack usage.
11946
11947 /// RAII object wrapping the visitation of a sequenced subexpression of an
11948 /// expression. At the end of this process, the side-effects of the evaluation
11949 /// become sequenced with respect to the value computation of the result, so
11950 /// we downgrade any UK_ModAsSideEffect within the evaluation to
11951 /// UK_ModAsValue.
11952 struct SequencedSubexpression {
11953 SequencedSubexpression(SequenceChecker &Self)
11954 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11955 Self.ModAsSideEffect = &ModAsSideEffect;
11956 }
11957
11958 ~SequencedSubexpression() {
11959 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
11960 // Add a new usage with usage kind UK_ModAsValue, and then restore
11961 // the previous usage with UK_ModAsSideEffect (thus clearing it if
11962 // the previous one was empty).
11963 UsageInfo &UI = Self.UsageMap[M.first];
11964 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
11965 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
11966 SideEffectUsage = M.second;
11967 }
11968 Self.ModAsSideEffect = OldModAsSideEffect;
11969 }
11970
11971 SequenceChecker &Self;
11972 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11973 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11974 };
11975
11976 /// RAII object wrapping the visitation of a subexpression which we might
11977 /// choose to evaluate as a constant. If any subexpression is evaluated and
11978 /// found to be non-constant, this allows us to suppress the evaluation of
11979 /// the outer expression.
11980 class EvaluationTracker {
11981 public:
11982 EvaluationTracker(SequenceChecker &Self)
11983 : Self(Self), Prev(Self.EvalTracker) {
11984 Self.EvalTracker = this;
11985 }
11986
11987 ~EvaluationTracker() {
11988 Self.EvalTracker = Prev;
11989 if (Prev)
11990 Prev->EvalOK &= EvalOK;
11991 }
11992
11993 bool evaluate(const Expr *E, bool &Result) {
11994 if (!EvalOK || E->isValueDependent())
11995 return false;
11996 EvalOK = E->EvaluateAsBooleanCondition(
11997 Result, Self.SemaRef.Context,
11998 Self.SemaRef.isConstantEvaluatedContext());
11999 return EvalOK;
12000 }
12001
12002 private:
12003 SequenceChecker &Self;
12004 EvaluationTracker *Prev;
12005 bool EvalOK = true;
12006 } *EvalTracker = nullptr;
12007
12008 /// Find the object which is produced by the specified expression,
12009 /// if any.
12010 Object getObject(const Expr *E, bool Mod) const {
12011 E = E->IgnoreParenCasts();
12012 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12013 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12014 return getObject(UO->getSubExpr(), Mod);
12015 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12016 if (BO->getOpcode() == BO_Comma)
12017 return getObject(BO->getRHS(), Mod);
12018 if (Mod && BO->isAssignmentOp())
12019 return getObject(BO->getLHS(), Mod);
12020 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12021 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12022 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12023 return ME->getMemberDecl();
12024 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12025 // FIXME: If this is a reference, map through to its value.
12026 return DRE->getDecl();
12027 return nullptr;
12028 }
12029
12030 /// Note that an object \p O was modified or used by an expression
12031 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12032 /// the object \p O as obtained via the \p UsageMap.
12033 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12034 // Get the old usage for the given object and usage kind.
12035 Usage &U = UI.Uses[UK];
12036 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12037 // If we have a modification as side effect and are in a sequenced
12038 // subexpression, save the old Usage so that we can restore it later
12039 // in SequencedSubexpression::~SequencedSubexpression.
12040 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12041 ModAsSideEffect->push_back(std::make_pair(O, U));
12042 // Then record the new usage with the current sequencing region.
12043 U.UsageExpr = UsageExpr;
12044 U.Seq = Region;
12045 }
12046 }
12047
12048 /// Check whether a modification or use of an object \p O in an expression
12049 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12050 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12051 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12052 /// usage and false we are checking for a mod-use unsequenced usage.
12053 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12054 UsageKind OtherKind, bool IsModMod) {
12055 if (UI.Diagnosed)
12056 return;
12057
12058 const Usage &U = UI.Uses[OtherKind];
12059 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12060 return;
12061
12062 const Expr *Mod = U.UsageExpr;
12063 const Expr *ModOrUse = UsageExpr;
12064 if (OtherKind == UK_Use)
12065 std::swap(Mod, ModOrUse);
12066
12067 SemaRef.DiagRuntimeBehavior(
12068 Mod->getExprLoc(), {Mod, ModOrUse},
12069 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12070 : diag::warn_unsequenced_mod_use)
12071 << O << SourceRange(ModOrUse->getExprLoc()));
12072 UI.Diagnosed = true;
12073 }
12074
12075 // A note on note{Pre, Post}{Use, Mod}:
12076 //
12077 // (It helps to follow the algorithm with an expression such as
12078 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12079 // operations before C++17 and both are well-defined in C++17).
12080 //
12081 // When visiting a node which uses/modify an object we first call notePreUse
12082 // or notePreMod before visiting its sub-expression(s). At this point the
12083 // children of the current node have not yet been visited and so the eventual
12084 // uses/modifications resulting from the children of the current node have not
12085 // been recorded yet.
12086 //
12087 // We then visit the children of the current node. After that notePostUse or
12088 // notePostMod is called. These will 1) detect an unsequenced modification
12089 // as side effect (as in "k++ + k") and 2) add a new usage with the
12090 // appropriate usage kind.
12091 //
12092 // We also have to be careful that some operation sequences modification as
12093 // side effect as well (for example: || or ,). To account for this we wrap
12094 // the visitation of such a sub-expression (for example: the LHS of || or ,)
12095 // with SequencedSubexpression. SequencedSubexpression is an RAII object
12096 // which record usages which are modifications as side effect, and then
12097 // downgrade them (or more accurately restore the previous usage which was a
12098 // modification as side effect) when exiting the scope of the sequenced
12099 // subexpression.
12100
12101 void notePreUse(Object O, const Expr *UseExpr) {
12102 UsageInfo &UI = UsageMap[O];
12103 // Uses conflict with other modifications.
12104 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12105 }
12106
12107 void notePostUse(Object O, const Expr *UseExpr) {
12108 UsageInfo &UI = UsageMap[O];
12109 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12110 /*IsModMod=*/false);
12111 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12112 }
12113
12114 void notePreMod(Object O, const Expr *ModExpr) {
12115 UsageInfo &UI = UsageMap[O];
12116 // Modifications conflict with other modifications and with uses.
12117 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12118 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12119 }
12120
12121 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12122 UsageInfo &UI = UsageMap[O];
12123 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12124 /*IsModMod=*/true);
12125 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12126 }
12127
12128public:
12129 SequenceChecker(Sema &S, const Expr *E,
12131 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12132 Visit(E);
12133 // Silence a -Wunused-private-field since WorkList is now unused.
12134 // TODO: Evaluate if it can be used, and if not remove it.
12135 (void)this->WorkList;
12136 }
12137
12138 void VisitStmt(const Stmt *S) {
12139 // Skip all statements which aren't expressions for now.
12140 }
12141
12142 void VisitExpr(const Expr *E) {
12143 // By default, just recurse to evaluated subexpressions.
12144 Base::VisitStmt(E);
12145 }
12146
12147 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
12148 for (auto *Sub : CSE->children()) {
12149 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
12150 if (!ChildExpr)
12151 continue;
12152
12153 if (ChildExpr == CSE->getOperand())
12154 // Do not recurse over a CoroutineSuspendExpr's operand.
12155 // The operand is also a subexpression of getCommonExpr(), and
12156 // recursing into it directly could confuse object management
12157 // for the sake of sequence tracking.
12158 continue;
12159
12160 Visit(Sub);
12161 }
12162 }
12163
12164 void VisitCastExpr(const CastExpr *E) {
12165 Object O = Object();
12166 if (E->getCastKind() == CK_LValueToRValue)
12167 O = getObject(E->getSubExpr(), false);
12168
12169 if (O)
12170 notePreUse(O, E);
12171 VisitExpr(E);
12172 if (O)
12173 notePostUse(O, E);
12174 }
12175
12176 void VisitSequencedExpressions(const Expr *SequencedBefore,
12177 const Expr *SequencedAfter) {
12178 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12179 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12180 SequenceTree::Seq OldRegion = Region;
12181
12182 {
12183 SequencedSubexpression SeqBefore(*this);
12184 Region = BeforeRegion;
12185 Visit(SequencedBefore);
12186 }
12187
12188 Region = AfterRegion;
12189 Visit(SequencedAfter);
12190
12191 Region = OldRegion;
12192
12193 Tree.merge(BeforeRegion);
12194 Tree.merge(AfterRegion);
12195 }
12196
12197 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12198 // C++17 [expr.sub]p1:
12199 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12200 // expression E1 is sequenced before the expression E2.
12201 if (SemaRef.getLangOpts().CPlusPlus17)
12202 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12203 else {
12204 Visit(ASE->getLHS());
12205 Visit(ASE->getRHS());
12206 }
12207 }
12208
12209 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12210 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12211 void VisitBinPtrMem(const BinaryOperator *BO) {
12212 // C++17 [expr.mptr.oper]p4:
12213 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12214 // the expression E1 is sequenced before the expression E2.
12215 if (SemaRef.getLangOpts().CPlusPlus17)
12216 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12217 else {
12218 Visit(BO->getLHS());
12219 Visit(BO->getRHS());
12220 }
12221 }
12222
12223 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12224 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12225 void VisitBinShlShr(const BinaryOperator *BO) {
12226 // C++17 [expr.shift]p4:
12227 // The expression E1 is sequenced before the expression E2.
12228 if (SemaRef.getLangOpts().CPlusPlus17)
12229 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12230 else {
12231 Visit(BO->getLHS());
12232 Visit(BO->getRHS());
12233 }
12234 }
12235
12236 void VisitBinComma(const BinaryOperator *BO) {
12237 // C++11 [expr.comma]p1:
12238 // Every value computation and side effect associated with the left
12239 // expression is sequenced before every value computation and side
12240 // effect associated with the right expression.
12241 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12242 }
12243
12244 void VisitBinAssign(const BinaryOperator *BO) {
12245 SequenceTree::Seq RHSRegion;
12246 SequenceTree::Seq LHSRegion;
12247 if (SemaRef.getLangOpts().CPlusPlus17) {
12248 RHSRegion = Tree.allocate(Region);
12249 LHSRegion = Tree.allocate(Region);
12250 } else {
12251 RHSRegion = Region;
12252 LHSRegion = Region;
12253 }
12254 SequenceTree::Seq OldRegion = Region;
12255
12256 // C++11 [expr.ass]p1:
12257 // [...] the assignment is sequenced after the value computation
12258 // of the right and left operands, [...]
12259 //
12260 // so check it before inspecting the operands and update the
12261 // map afterwards.
12262 Object O = getObject(BO->getLHS(), /*Mod=*/true);
12263 if (O)
12264 notePreMod(O, BO);
12265
12266 if (SemaRef.getLangOpts().CPlusPlus17) {
12267 // C++17 [expr.ass]p1:
12268 // [...] The right operand is sequenced before the left operand. [...]
12269 {
12270 SequencedSubexpression SeqBefore(*this);
12271 Region = RHSRegion;
12272 Visit(BO->getRHS());
12273 }
12274
12275 Region = LHSRegion;
12276 Visit(BO->getLHS());
12277
12278 if (O && isa<CompoundAssignOperator>(BO))
12279 notePostUse(O, BO);
12280
12281 } else {
12282 // C++11 does not specify any sequencing between the LHS and RHS.
12283 Region = LHSRegion;
12284 Visit(BO->getLHS());
12285
12286 if (O && isa<CompoundAssignOperator>(BO))
12287 notePostUse(O, BO);
12288
12289 Region = RHSRegion;
12290 Visit(BO->getRHS());
12291 }
12292
12293 // C++11 [expr.ass]p1:
12294 // the assignment is sequenced [...] before the value computation of the
12295 // assignment expression.
12296 // C11 6.5.16/3 has no such rule.
12297 Region = OldRegion;
12298 if (O)
12299 notePostMod(O, BO,
12300 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12301 : UK_ModAsSideEffect);
12302 if (SemaRef.getLangOpts().CPlusPlus17) {
12303 Tree.merge(RHSRegion);
12304 Tree.merge(LHSRegion);
12305 }
12306 }
12307
12308 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
12309 VisitBinAssign(CAO);
12310 }
12311
12312 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12313 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12314 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
12315 Object O = getObject(UO->getSubExpr(), true);
12316 if (!O)
12317 return VisitExpr(UO);
12318
12319 notePreMod(O, UO);
12320 Visit(UO->getSubExpr());
12321 // C++11 [expr.pre.incr]p1:
12322 // the expression ++x is equivalent to x+=1
12323 notePostMod(O, UO,
12324 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12325 : UK_ModAsSideEffect);
12326 }
12327
12328 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12329 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12330 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
12331 Object O = getObject(UO->getSubExpr(), true);
12332 if (!O)
12333 return VisitExpr(UO);
12334
12335 notePreMod(O, UO);
12336 Visit(UO->getSubExpr());
12337 notePostMod(O, UO, UK_ModAsSideEffect);
12338 }
12339
12340 void VisitBinLOr(const BinaryOperator *BO) {
12341 // C++11 [expr.log.or]p2:
12342 // If the second expression is evaluated, every value computation and
12343 // side effect associated with the first expression is sequenced before
12344 // every value computation and side effect associated with the
12345 // second expression.
12346 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12347 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12348 SequenceTree::Seq OldRegion = Region;
12349
12350 EvaluationTracker Eval(*this);
12351 {
12352 SequencedSubexpression Sequenced(*this);
12353 Region = LHSRegion;
12354 Visit(BO->getLHS());
12355 }
12356
12357 // C++11 [expr.log.or]p1:
12358 // [...] the second operand is not evaluated if the first operand
12359 // evaluates to true.
12360 bool EvalResult = false;
12361 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12362 bool ShouldVisitRHS = !EvalOK || !EvalResult;
12363 if (ShouldVisitRHS) {
12364 Region = RHSRegion;
12365 Visit(BO->getRHS());
12366 }
12367
12368 Region = OldRegion;
12369 Tree.merge(LHSRegion);
12370 Tree.merge(RHSRegion);
12371 }
12372
12373 void VisitBinLAnd(const BinaryOperator *BO) {
12374 // C++11 [expr.log.and]p2:
12375 // If the second expression is evaluated, every value computation and
12376 // side effect associated with the first expression is sequenced before
12377 // every value computation and side effect associated with the
12378 // second expression.
12379 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
12380 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
12381 SequenceTree::Seq OldRegion = Region;
12382
12383 EvaluationTracker Eval(*this);
12384 {
12385 SequencedSubexpression Sequenced(*this);
12386 Region = LHSRegion;
12387 Visit(BO->getLHS());
12388 }
12389
12390 // C++11 [expr.log.and]p1:
12391 // [...] the second operand is not evaluated if the first operand is false.
12392 bool EvalResult = false;
12393 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
12394 bool ShouldVisitRHS = !EvalOK || EvalResult;
12395 if (ShouldVisitRHS) {
12396 Region = RHSRegion;
12397 Visit(BO->getRHS());
12398 }
12399
12400 Region = OldRegion;
12401 Tree.merge(LHSRegion);
12402 Tree.merge(RHSRegion);
12403 }
12404
12405 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
12406 // C++11 [expr.cond]p1:
12407 // [...] Every value computation and side effect associated with the first
12408 // expression is sequenced before every value computation and side effect
12409 // associated with the second or third expression.
12410 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
12411
12412 // No sequencing is specified between the true and false expression.
12413 // However since exactly one of both is going to be evaluated we can
12414 // consider them to be sequenced. This is needed to avoid warning on
12415 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
12416 // both the true and false expressions because we can't evaluate x.
12417 // This will still allow us to detect an expression like (pre C++17)
12418 // "(x ? y += 1 : y += 2) = y".
12419 //
12420 // We don't wrap the visitation of the true and false expression with
12421 // SequencedSubexpression because we don't want to downgrade modifications
12422 // as side effect in the true and false expressions after the visition
12423 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
12424 // not warn between the two "y++", but we should warn between the "y++"
12425 // and the "y".
12426 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
12427 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
12428 SequenceTree::Seq OldRegion = Region;
12429
12430 EvaluationTracker Eval(*this);
12431 {
12432 SequencedSubexpression Sequenced(*this);
12433 Region = ConditionRegion;
12434 Visit(CO->getCond());
12435 }
12436
12437 // C++11 [expr.cond]p1:
12438 // [...] The first expression is contextually converted to bool (Clause 4).
12439 // It is evaluated and if it is true, the result of the conditional
12440 // expression is the value of the second expression, otherwise that of the
12441 // third expression. Only one of the second and third expressions is
12442 // evaluated. [...]
12443 bool EvalResult = false;
12444 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
12445 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
12446 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
12447 if (ShouldVisitTrueExpr) {
12448 Region = TrueRegion;
12449 Visit(CO->getTrueExpr());
12450 }
12451 if (ShouldVisitFalseExpr) {
12452 Region = FalseRegion;
12453 Visit(CO->getFalseExpr());
12454 }
12455
12456 Region = OldRegion;
12457 Tree.merge(ConditionRegion);
12458 Tree.merge(TrueRegion);
12459 Tree.merge(FalseRegion);
12460 }
12461
12462 void VisitCallExpr(const CallExpr *CE) {
12463 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12464
12465 if (CE->isUnevaluatedBuiltinCall(Context))
12466 return;
12467
12468 // C++11 [intro.execution]p15:
12469 // When calling a function [...], every value computation and side effect
12470 // associated with any argument expression, or with the postfix expression
12471 // designating the called function, is sequenced before execution of every
12472 // expression or statement in the body of the function [and thus before
12473 // the value computation of its result].
12474 SequencedSubexpression Sequenced(*this);
12475 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
12476 // C++17 [expr.call]p5
12477 // The postfix-expression is sequenced before each expression in the
12478 // expression-list and any default argument. [...]
12479 SequenceTree::Seq CalleeRegion;
12480 SequenceTree::Seq OtherRegion;
12481 if (SemaRef.getLangOpts().CPlusPlus17) {
12482 CalleeRegion = Tree.allocate(Region);
12483 OtherRegion = Tree.allocate(Region);
12484 } else {
12485 CalleeRegion = Region;
12486 OtherRegion = Region;
12487 }
12488 SequenceTree::Seq OldRegion = Region;
12489
12490 // Visit the callee expression first.
12491 Region = CalleeRegion;
12492 if (SemaRef.getLangOpts().CPlusPlus17) {
12493 SequencedSubexpression Sequenced(*this);
12494 Visit(CE->getCallee());
12495 } else {
12496 Visit(CE->getCallee());
12497 }
12498
12499 // Then visit the argument expressions.
12500 Region = OtherRegion;
12501 for (const Expr *Argument : CE->arguments())
12502 Visit(Argument);
12503
12504 Region = OldRegion;
12505 if (SemaRef.getLangOpts().CPlusPlus17) {
12506 Tree.merge(CalleeRegion);
12507 Tree.merge(OtherRegion);
12508 }
12509 });
12510 }
12511
12512 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
12513 // C++17 [over.match.oper]p2:
12514 // [...] the operator notation is first transformed to the equivalent
12515 // function-call notation as summarized in Table 12 (where @ denotes one
12516 // of the operators covered in the specified subclause). However, the
12517 // operands are sequenced in the order prescribed for the built-in
12518 // operator (Clause 8).
12519 //
12520 // From the above only overloaded binary operators and overloaded call
12521 // operators have sequencing rules in C++17 that we need to handle
12522 // separately.
12523 if (!SemaRef.getLangOpts().CPlusPlus17 ||
12524 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
12525 return VisitCallExpr(CXXOCE);
12526
12527 enum {
12528 NoSequencing,
12529 LHSBeforeRHS,
12530 RHSBeforeLHS,
12531 LHSBeforeRest
12532 } SequencingKind;
12533 switch (CXXOCE->getOperator()) {
12534 case OO_Equal:
12535 case OO_PlusEqual:
12536 case OO_MinusEqual:
12537 case OO_StarEqual:
12538 case OO_SlashEqual:
12539 case OO_PercentEqual:
12540 case OO_CaretEqual:
12541 case OO_AmpEqual:
12542 case OO_PipeEqual:
12543 case OO_LessLessEqual:
12544 case OO_GreaterGreaterEqual:
12545 SequencingKind = RHSBeforeLHS;
12546 break;
12547
12548 case OO_LessLess:
12549 case OO_GreaterGreater:
12550 case OO_AmpAmp:
12551 case OO_PipePipe:
12552 case OO_Comma:
12553 case OO_ArrowStar:
12554 case OO_Subscript:
12555 SequencingKind = LHSBeforeRHS;
12556 break;
12557
12558 case OO_Call:
12559 SequencingKind = LHSBeforeRest;
12560 break;
12561
12562 default:
12563 SequencingKind = NoSequencing;
12564 break;
12565 }
12566
12567 if (SequencingKind == NoSequencing)
12568 return VisitCallExpr(CXXOCE);
12569
12570 // This is a call, so all subexpressions are sequenced before the result.
12571 SequencedSubexpression Sequenced(*this);
12572
12573 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
12574 assert(SemaRef.getLangOpts().CPlusPlus17 &&
12575 "Should only get there with C++17 and above!");
12576 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
12577 "Should only get there with an overloaded binary operator"
12578 " or an overloaded call operator!");
12579
12580 if (SequencingKind == LHSBeforeRest) {
12581 assert(CXXOCE->getOperator() == OO_Call &&
12582 "We should only have an overloaded call operator here!");
12583
12584 // This is very similar to VisitCallExpr, except that we only have the
12585 // C++17 case. The postfix-expression is the first argument of the
12586 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
12587 // are in the following arguments.
12588 //
12589 // Note that we intentionally do not visit the callee expression since
12590 // it is just a decayed reference to a function.
12591 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
12592 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
12593 SequenceTree::Seq OldRegion = Region;
12594
12595 assert(CXXOCE->getNumArgs() >= 1 &&
12596 "An overloaded call operator must have at least one argument"
12597 " for the postfix-expression!");
12598 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
12599 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
12600 CXXOCE->getNumArgs() - 1);
12601
12602 // Visit the postfix-expression first.
12603 {
12604 Region = PostfixExprRegion;
12605 SequencedSubexpression Sequenced(*this);
12606 Visit(PostfixExpr);
12607 }
12608
12609 // Then visit the argument expressions.
12610 Region = ArgsRegion;
12611 for (const Expr *Arg : Args)
12612 Visit(Arg);
12613
12614 Region = OldRegion;
12615 Tree.merge(PostfixExprRegion);
12616 Tree.merge(ArgsRegion);
12617 } else {
12618 assert(CXXOCE->getNumArgs() == 2 &&
12619 "Should only have two arguments here!");
12620 assert((SequencingKind == LHSBeforeRHS ||
12621 SequencingKind == RHSBeforeLHS) &&
12622 "Unexpected sequencing kind!");
12623
12624 // We do not visit the callee expression since it is just a decayed
12625 // reference to a function.
12626 const Expr *E1 = CXXOCE->getArg(0);
12627 const Expr *E2 = CXXOCE->getArg(1);
12628 if (SequencingKind == RHSBeforeLHS)
12629 std::swap(E1, E2);
12630
12631 return VisitSequencedExpressions(E1, E2);
12632 }
12633 });
12634 }
12635
12636 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
12637 // This is a call, so all subexpressions are sequenced before the result.
12638 SequencedSubexpression Sequenced(*this);
12639
12640 if (!CCE->isListInitialization())
12641 return VisitExpr(CCE);
12642
12643 // In C++11, list initializations are sequenced.
12644 SequenceExpressionsInOrder(
12645 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
12646 }
12647
12648 void VisitInitListExpr(const InitListExpr *ILE) {
12649 if (!SemaRef.getLangOpts().CPlusPlus11)
12650 return VisitExpr(ILE);
12651
12652 // In C++11, list initializations are sequenced.
12653 SequenceExpressionsInOrder(ILE->inits());
12654 }
12655
12656 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
12657 // C++20 parenthesized list initializations are sequenced. See C++20
12658 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
12659 SequenceExpressionsInOrder(PLIE->getInitExprs());
12660 }
12661
12662private:
12663 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
12665 SequenceTree::Seq Parent = Region;
12666 for (const Expr *E : ExpressionList) {
12667 if (!E)
12668 continue;
12669 Region = Tree.allocate(Parent);
12670 Elts.push_back(Region);
12671 Visit(E);
12672 }
12673
12674 // Forget that the initializers are sequenced.
12675 Region = Parent;
12676 for (unsigned I = 0; I < Elts.size(); ++I)
12677 Tree.merge(Elts[I]);
12678 }
12679};
12680
12681SequenceChecker::UsageInfo::UsageInfo() = default;
12682
12683} // namespace
12684
12685void Sema::CheckUnsequencedOperations(const Expr *E) {
12687 WorkList.push_back(E);
12688 while (!WorkList.empty()) {
12689 const Expr *Item = WorkList.pop_back_val();
12690 SequenceChecker(*this, Item, WorkList);
12691 }
12692}
12693
12694void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12695 bool IsConstexpr) {
12697 IsConstexpr || isa<ConstantExpr>(E));
12698 CheckImplicitConversions(E, CheckLoc);
12700 CheckUnsequencedOperations(E);
12701 if (!IsConstexpr && !E->isValueDependent())
12702 CheckForIntOverflow(E);
12704}
12705
12706void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12707 FieldDecl *BitField,
12708 Expr *Init) {
12709 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12710}
12711
12714 if (!PType->isVariablyModifiedType())
12715 return;
12716 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12717 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12718 return;
12719 }
12720 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12721 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12722 return;
12723 }
12724 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12725 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12726 return;
12727 }
12728
12729 const ArrayType *AT = S.Context.getAsArrayType(PType);
12730 if (!AT)
12731 return;
12732
12735 return;
12736 }
12737
12738 S.Diag(Loc, diag::err_array_star_in_function_definition);
12739}
12740
12742 bool CheckParameterNames) {
12743 bool HasInvalidParm = false;
12744 for (ParmVarDecl *Param : Parameters) {
12745 assert(Param && "null in a parameter list");
12746 // C99 6.7.5.3p4: the parameters in a parameter type list in a
12747 // function declarator that is part of a function definition of
12748 // that function shall not have incomplete type.
12749 //
12750 // C++23 [dcl.fct.def.general]/p2
12751 // The type of a parameter [...] for a function definition
12752 // shall not be a (possibly cv-qualified) class type that is incomplete
12753 // or abstract within the function body unless the function is deleted.
12754 if (!Param->isInvalidDecl() &&
12755 (RequireCompleteType(Param->getLocation(), Param->getType(),
12756 diag::err_typecheck_decl_incomplete_type) ||
12757 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
12758 diag::err_abstract_type_in_decl,
12760 Param->setInvalidDecl();
12761 HasInvalidParm = true;
12762 }
12763
12764 // C99 6.9.1p5: If the declarator includes a parameter type list, the
12765 // declaration of each parameter shall include an identifier.
12766 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
12767 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
12768 // Diagnose this as an extension in C17 and earlier.
12769 if (!getLangOpts().C23)
12770 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
12771 }
12772
12773 // C99 6.7.5.3p12:
12774 // If the function declarator is not part of a definition of that
12775 // function, parameters may have incomplete type and may use the [*]
12776 // notation in their sequences of declarator specifiers to specify
12777 // variable length array types.
12778 QualType PType = Param->getOriginalType();
12779 // FIXME: This diagnostic should point the '[*]' if source-location
12780 // information is added for it.
12781 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12782
12783 // If the parameter is a c++ class type and it has to be destructed in the
12784 // callee function, declare the destructor so that it can be called by the
12785 // callee function. Do not perform any direct access check on the dtor here.
12786 if (!Param->isInvalidDecl()) {
12787 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12788 if (!ClassDecl->isInvalidDecl() &&
12789 !ClassDecl->hasIrrelevantDestructor() &&
12790 !ClassDecl->isDependentContext() &&
12791 ClassDecl->isParamDestroyedInCallee()) {
12793 MarkFunctionReferenced(Param->getLocation(), Destructor);
12794 DiagnoseUseOfDecl(Destructor, Param->getLocation());
12795 }
12796 }
12797 }
12798
12799 // Parameters with the pass_object_size attribute only need to be marked
12800 // constant at function definitions. Because we lack information about
12801 // whether we're on a declaration or definition when we're instantiating the
12802 // attribute, we need to check for constness here.
12803 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12804 if (!Param->getType().isConstQualified())
12805 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12806 << Attr->getSpelling() << 1;
12807
12808 // Check for parameter names shadowing fields from the class.
12809 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12810 // The owning context for the parameter should be the function, but we
12811 // want to see if this function's declaration context is a record.
12812 DeclContext *DC = Param->getDeclContext();
12813 if (DC && DC->isFunctionOrMethod()) {
12814 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12815 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12816 RD, /*DeclIsField*/ false);
12817 }
12818 }
12819
12820 if (!Param->isInvalidDecl() &&
12821 Param->getOriginalType()->isWebAssemblyTableType()) {
12822 Param->setInvalidDecl();
12823 HasInvalidParm = true;
12824 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
12825 }
12826 }
12827
12828 return HasInvalidParm;
12829}
12830
12831std::optional<std::pair<
12833 *E,
12835 &Ctx);
12836
12837/// Compute the alignment and offset of the base class object given the
12838/// derived-to-base cast expression and the alignment and offset of the derived
12839/// class object.
12840static std::pair<CharUnits, CharUnits>
12842 CharUnits BaseAlignment, CharUnits Offset,
12843 ASTContext &Ctx) {
12844 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
12845 ++PathI) {
12846 const CXXBaseSpecifier *Base = *PathI;
12847 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
12848 if (Base->isVirtual()) {
12849 // The complete object may have a lower alignment than the non-virtual
12850 // alignment of the base, in which case the base may be misaligned. Choose
12851 // the smaller of the non-virtual alignment and BaseAlignment, which is a
12852 // conservative lower bound of the complete object alignment.
12853 CharUnits NonVirtualAlignment =
12855 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
12856 Offset = CharUnits::Zero();
12857 } else {
12858 const ASTRecordLayout &RL =
12859 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
12860 Offset += RL.getBaseClassOffset(BaseDecl);
12861 }
12862 DerivedType = Base->getType();
12863 }
12864
12865 return std::make_pair(BaseAlignment, Offset);
12866}
12867
12868/// Compute the alignment and offset of a binary additive operator.
12869static std::optional<std::pair<CharUnits, CharUnits>>
12871 bool IsSub, ASTContext &Ctx) {
12872 QualType PointeeType = PtrE->getType()->getPointeeType();
12873
12874 if (!PointeeType->isConstantSizeType())
12875 return std::nullopt;
12876
12877 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
12878
12879 if (!P)
12880 return std::nullopt;
12881
12882 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
12883 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
12884 CharUnits Offset = EltSize * IdxRes->getExtValue();
12885 if (IsSub)
12886 Offset = -Offset;
12887 return std::make_pair(P->first, P->second + Offset);
12888 }
12889
12890 // If the integer expression isn't a constant expression, compute the lower
12891 // bound of the alignment using the alignment and offset of the pointer
12892 // expression and the element size.
12893 return std::make_pair(
12894 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
12895 CharUnits::Zero());
12896}
12897
12898/// This helper function takes an lvalue expression and returns the alignment of
12899/// a VarDecl and a constant offset from the VarDecl.
12900std::optional<std::pair<
12901 CharUnits,
12903 ASTContext &Ctx) {
12904 E = E->IgnoreParens();
12905 switch (E->getStmtClass()) {
12906 default:
12907 break;
12908 case Stmt::CStyleCastExprClass:
12909 case Stmt::CXXStaticCastExprClass:
12910 case Stmt::ImplicitCastExprClass: {
12911 auto *CE = cast<CastExpr>(E);
12912 const Expr *From = CE->getSubExpr();
12913 switch (CE->getCastKind()) {
12914 default:
12915 break;
12916 case CK_NoOp:
12917 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
12918 case CK_UncheckedDerivedToBase:
12919 case CK_DerivedToBase: {
12920 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
12921 if (!P)
12922 break;
12923 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
12924 P->second, Ctx);
12925 }
12926 }
12927 break;
12928 }
12929 case Stmt::ArraySubscriptExprClass: {
12930 auto *ASE = cast<ArraySubscriptExpr>(E);
12932 false, Ctx);
12933 }
12934 case Stmt::DeclRefExprClass: {
12935 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
12936 // FIXME: If VD is captured by copy or is an escaping __block variable,
12937 // use the alignment of VD's type.
12938 if (!VD->getType()->isReferenceType()) {
12939 // Dependent alignment cannot be resolved -> bail out.
12940 if (VD->hasDependentAlignment())
12941 break;
12942 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
12943 }
12944 if (VD->hasInit())
12945 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
12946 }
12947 break;
12948 }
12949 case Stmt::MemberExprClass: {
12950 auto *ME = cast<MemberExpr>(E);
12951 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12952 if (!FD || FD->getType()->isReferenceType() ||
12953 FD->getParent()->isInvalidDecl())
12954 break;
12955 std::optional<std::pair<CharUnits, CharUnits>> P;
12956 if (ME->isArrow())
12957 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
12958 else
12959 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
12960 if (!P)
12961 break;
12962 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
12963 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
12964 return std::make_pair(P->first,
12965 P->second + CharUnits::fromQuantity(Offset));
12966 }
12967 case Stmt::UnaryOperatorClass: {
12968 auto *UO = cast<UnaryOperator>(E);
12969 switch (UO->getOpcode()) {
12970 default:
12971 break;
12972 case UO_Deref:
12974 }
12975 break;
12976 }
12977 case Stmt::BinaryOperatorClass: {
12978 auto *BO = cast<BinaryOperator>(E);
12979 auto Opcode = BO->getOpcode();
12980 switch (Opcode) {
12981 default:
12982 break;
12983 case BO_Comma:
12985 }
12986 break;
12987 }
12988 }
12989 return std::nullopt;
12990}
12991
12992/// This helper function takes a pointer expression and returns the alignment of
12993/// a VarDecl and a constant offset from the VarDecl.
12994std::optional<std::pair<
12996 *E,
12998 &Ctx) {
12999 E = E->IgnoreParens();
13000 switch (E->getStmtClass()) {
13001 default:
13002 break;
13003 case Stmt::CStyleCastExprClass:
13004 case Stmt::CXXStaticCastExprClass:
13005 case Stmt::ImplicitCastExprClass: {
13006 auto *CE = cast<CastExpr>(E);
13007 const Expr *From = CE->getSubExpr();
13008 switch (CE->getCastKind()) {
13009 default:
13010 break;
13011 case CK_NoOp:
13012 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13013 case CK_ArrayToPointerDecay:
13014 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13015 case CK_UncheckedDerivedToBase:
13016 case CK_DerivedToBase: {
13017 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
13018 if (!P)
13019 break;
13021 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
13022 }
13023 }
13024 break;
13025 }
13026 case Stmt::CXXThisExprClass: {
13027 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
13029 return std::make_pair(Alignment, CharUnits::Zero());
13030 }
13031 case Stmt::UnaryOperatorClass: {
13032 auto *UO = cast<UnaryOperator>(E);
13033 if (UO->getOpcode() == UO_AddrOf)
13035 break;
13036 }
13037 case Stmt::BinaryOperatorClass: {
13038 auto *BO = cast<BinaryOperator>(E);
13039 auto Opcode = BO->getOpcode();
13040 switch (Opcode) {
13041 default:
13042 break;
13043 case BO_Add:
13044 case BO_Sub: {
13045 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
13046 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
13047 std::swap(LHS, RHS);
13048 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
13049 Ctx);
13050 }
13051 case BO_Comma:
13052 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
13053 }
13054 break;
13055 }
13056 }
13057 return std::nullopt;
13058}
13059
13061 // See if we can compute the alignment of a VarDecl and an offset from it.
13062 std::optional<std::pair<CharUnits, CharUnits>> P =
13064
13065 if (P)
13066 return P->first.alignmentAtOffset(P->second);
13067
13068 // If that failed, return the type's alignment.
13070}
13071
13073 // This is actually a lot of work to potentially be doing on every
13074 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13075 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13076 return;
13077
13078 // Ignore dependent types.
13079 if (T->isDependentType() || Op->getType()->isDependentType())
13080 return;
13081
13082 // Require that the destination be a pointer type.
13083 const PointerType *DestPtr = T->getAs<PointerType>();
13084 if (!DestPtr) return;
13085
13086 // If the destination has alignment 1, we're done.
13087 QualType DestPointee = DestPtr->getPointeeType();
13088 if (DestPointee->isIncompleteType()) return;
13089 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13090 if (DestAlign.isOne()) return;
13091
13092 // Require that the source be a pointer type.
13093 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13094 if (!SrcPtr) return;
13095 QualType SrcPointee = SrcPtr->getPointeeType();
13096
13097 // Explicitly allow casts from cv void*. We already implicitly
13098 // allowed casts to cv void*, since they have alignment 1.
13099 // Also allow casts involving incomplete types, which implicitly
13100 // includes 'void'.
13101 if (SrcPointee->isIncompleteType()) return;
13102
13103 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
13104
13105 if (SrcAlign >= DestAlign) return;
13106
13107 Diag(TRange.getBegin(), diag::warn_cast_align)
13108 << Op->getType() << T
13109 << static_cast<unsigned>(SrcAlign.getQuantity())
13110 << static_cast<unsigned>(DestAlign.getQuantity())
13111 << TRange << Op->getSourceRange();
13112}
13113
13114void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13115 const ArraySubscriptExpr *ASE,
13116 bool AllowOnePastEnd, bool IndexNegated) {
13117 // Already diagnosed by the constant evaluator.
13119 return;
13120
13121 IndexExpr = IndexExpr->IgnoreParenImpCasts();
13122 if (IndexExpr->isValueDependent())
13123 return;
13124
13125 const Type *EffectiveType =
13127 BaseExpr = BaseExpr->IgnoreParenCasts();
13128 const ConstantArrayType *ArrayTy =
13130
13132 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
13133
13134 const Type *BaseType =
13135 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
13136 bool IsUnboundedArray =
13137 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
13138 Context, StrictFlexArraysLevel,
13139 /*IgnoreTemplateOrMacroSubstitution=*/true);
13140 if (EffectiveType->isDependentType() ||
13141 (!IsUnboundedArray && BaseType->isDependentType()))
13142 return;
13143
13146 return;
13147
13148 llvm::APSInt index = Result.Val.getInt();
13149 if (IndexNegated) {
13150 index.setIsUnsigned(false);
13151 index = -index;
13152 }
13153
13154 if (IsUnboundedArray) {
13155 if (EffectiveType->isFunctionType())
13156 return;
13157 if (index.isUnsigned() || !index.isNegative()) {
13158 const auto &ASTC = getASTContext();
13159 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
13160 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
13161 if (index.getBitWidth() < AddrBits)
13162 index = index.zext(AddrBits);
13163 std::optional<CharUnits> ElemCharUnits =
13164 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
13165 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
13166 // pointer) bounds-checking isn't meaningful.
13167 if (!ElemCharUnits || ElemCharUnits->isZero())
13168 return;
13169 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
13170 // If index has more active bits than address space, we already know
13171 // we have a bounds violation to warn about. Otherwise, compute
13172 // address of (index + 1)th element, and warn about bounds violation
13173 // only if that address exceeds address space.
13174 if (index.getActiveBits() <= AddrBits) {
13175 bool Overflow;
13176 llvm::APInt Product(index);
13177 Product += 1;
13178 Product = Product.umul_ov(ElemBytes, Overflow);
13179 if (!Overflow && Product.getActiveBits() <= AddrBits)
13180 return;
13181 }
13182
13183 // Need to compute max possible elements in address space, since that
13184 // is included in diag message.
13185 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
13186 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
13187 MaxElems += 1;
13188 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
13189 MaxElems = MaxElems.udiv(ElemBytes);
13190
13191 unsigned DiagID =
13192 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
13193 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
13194
13195 // Diag message shows element size in bits and in "bytes" (platform-
13196 // dependent CharUnits)
13197 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13198 PDiag(DiagID)
13199 << toString(index, 10, true) << AddrBits
13200 << (unsigned)ASTC.toBits(*ElemCharUnits)
13201 << toString(ElemBytes, 10, false)
13202 << toString(MaxElems, 10, false)
13203 << (unsigned)MaxElems.getLimitedValue(~0U)
13204 << IndexExpr->getSourceRange());
13205
13206 const NamedDecl *ND = nullptr;
13207 // Try harder to find a NamedDecl to point at in the note.
13208 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
13209 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13210 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13211 ND = DRE->getDecl();
13212 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
13213 ND = ME->getMemberDecl();
13214
13215 if (ND)
13216 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13217 PDiag(diag::note_array_declared_here) << ND);
13218 }
13219 return;
13220 }
13221
13222 if (index.isUnsigned() || !index.isNegative()) {
13223 // It is possible that the type of the base expression after
13224 // IgnoreParenCasts is incomplete, even though the type of the base
13225 // expression before IgnoreParenCasts is complete (see PR39746 for an
13226 // example). In this case we have no information about whether the array
13227 // access exceeds the array bounds. However we can still diagnose an array
13228 // access which precedes the array bounds.
13229 if (BaseType->isIncompleteType())
13230 return;
13231
13232 llvm::APInt size = ArrayTy->getSize();
13233
13234 if (BaseType != EffectiveType) {
13235 // Make sure we're comparing apples to apples when comparing index to
13236 // size.
13237 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13238 uint64_t array_typesize = Context.getTypeSize(BaseType);
13239
13240 // Handle ptrarith_typesize being zero, such as when casting to void*.
13241 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
13242 if (!ptrarith_typesize)
13243 ptrarith_typesize = Context.getCharWidth();
13244
13245 if (ptrarith_typesize != array_typesize) {
13246 // There's a cast to a different size type involved.
13247 uint64_t ratio = array_typesize / ptrarith_typesize;
13248
13249 // TODO: Be smarter about handling cases where array_typesize is not a
13250 // multiple of ptrarith_typesize.
13251 if (ptrarith_typesize * ratio == array_typesize)
13252 size *= llvm::APInt(size.getBitWidth(), ratio);
13253 }
13254 }
13255
13256 if (size.getBitWidth() > index.getBitWidth())
13257 index = index.zext(size.getBitWidth());
13258 else if (size.getBitWidth() < index.getBitWidth())
13259 size = size.zext(index.getBitWidth());
13260
13261 // For array subscripting the index must be less than size, but for pointer
13262 // arithmetic also allow the index (offset) to be equal to size since
13263 // computing the next address after the end of the array is legal and
13264 // commonly done e.g. in C++ iterators and range-based for loops.
13265 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13266 return;
13267
13268 // Suppress the warning if the subscript expression (as identified by the
13269 // ']' location) and the index expression are both from macro expansions
13270 // within a system header.
13271 if (ASE) {
13273 ASE->getRBracketLoc());
13274 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13275 SourceLocation IndexLoc =
13276 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13277 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13278 return;
13279 }
13280 }
13281
13282 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
13283 : diag::warn_ptr_arith_exceeds_bounds;
13284 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
13285 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
13286
13288 BaseExpr->getBeginLoc(), BaseExpr,
13289 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
13290 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
13291 } else {
13292 unsigned DiagID = diag::warn_array_index_precedes_bounds;
13293 if (!ASE) {
13294 DiagID = diag::warn_ptr_arith_precedes_bounds;
13295 if (index.isNegative()) index = -index;
13296 }
13297
13298 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13299 PDiag(DiagID) << toString(index, 10, true)
13300 << IndexExpr->getSourceRange());
13301 }
13302
13303 const NamedDecl *ND = nullptr;
13304 // Try harder to find a NamedDecl to point at in the note.
13305 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
13306 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13307 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13308 ND = DRE->getDecl();
13309 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
13310 ND = ME->getMemberDecl();
13311
13312 if (ND)
13313 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13314 PDiag(diag::note_array_declared_here) << ND);
13315}
13316
13317void Sema::CheckArrayAccess(const Expr *expr) {
13318 int AllowOnePastEnd = 0;
13319 while (expr) {
13320 expr = expr->IgnoreParenImpCasts();
13321 switch (expr->getStmtClass()) {
13322 case Stmt::ArraySubscriptExprClass: {
13323 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13324 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13325 AllowOnePastEnd > 0);
13326 expr = ASE->getBase();
13327 break;
13328 }
13329 case Stmt::MemberExprClass: {
13330 expr = cast<MemberExpr>(expr)->getBase();
13331 break;
13332 }
13333 case Stmt::ArraySectionExprClass: {
13334 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
13335 // FIXME: We should probably be checking all of the elements to the
13336 // 'length' here as well.
13337 if (ASE->getLowerBound())
13338 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13339 /*ASE=*/nullptr, AllowOnePastEnd > 0);
13340 return;
13341 }
13342 case Stmt::UnaryOperatorClass: {
13343 // Only unwrap the * and & unary operators
13344 const UnaryOperator *UO = cast<UnaryOperator>(expr);
13345 expr = UO->getSubExpr();
13346 switch (UO->getOpcode()) {
13347 case UO_AddrOf:
13348 AllowOnePastEnd++;
13349 break;
13350 case UO_Deref:
13351 AllowOnePastEnd--;
13352 break;
13353 default:
13354 return;
13355 }
13356 break;
13357 }
13358 case Stmt::ConditionalOperatorClass: {
13359 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13360 if (const Expr *lhs = cond->getLHS())
13361 CheckArrayAccess(lhs);
13362 if (const Expr *rhs = cond->getRHS())
13363 CheckArrayAccess(rhs);
13364 return;
13365 }
13366 case Stmt::CXXOperatorCallExprClass: {
13367 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13368 for (const auto *Arg : OCE->arguments())
13369 CheckArrayAccess(Arg);
13370 return;
13371 }
13372 default:
13373 return;
13374 }
13375 }
13376}
13377
13379 Expr *RHS, bool isProperty) {
13380 // Check if RHS is an Objective-C object literal, which also can get
13381 // immediately zapped in a weak reference. Note that we explicitly
13382 // allow ObjCStringLiterals, since those are designed to never really die.
13383 RHS = RHS->IgnoreParenImpCasts();
13384
13385 // This enum needs to match with the 'select' in
13386 // warn_objc_arc_literal_assign (off-by-1).
13388 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
13389 return false;
13390
13391 S.Diag(Loc, diag::warn_arc_literal_assign)
13392 << (unsigned) Kind
13393 << (isProperty ? 0 : 1)
13394 << RHS->getSourceRange();
13395
13396 return true;
13397}
13398
13401 Expr *RHS, bool isProperty) {
13402 // Strip off any implicit cast added to get to the one ARC-specific.
13403 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13404 if (cast->getCastKind() == CK_ARCConsumeObject) {
13405 S.Diag(Loc, diag::warn_arc_retained_assign)
13407 << (isProperty ? 0 : 1)
13408 << RHS->getSourceRange();
13409 return true;
13410 }
13411 RHS = cast->getSubExpr();
13412 }
13413
13414 if (LT == Qualifiers::OCL_Weak &&
13415 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13416 return true;
13417
13418 return false;
13419}
13420
13422 QualType LHS, Expr *RHS) {
13424
13426 return false;
13427
13428 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13429 return true;
13430
13431 return false;
13432}
13433
13435 Expr *LHS, Expr *RHS) {
13436 QualType LHSType;
13437 // PropertyRef on LHS type need be directly obtained from
13438 // its declaration as it has a PseudoType.
13440 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13441 if (PRE && !PRE->isImplicitProperty()) {
13442 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13443 if (PD)
13444 LHSType = PD->getType();
13445 }
13446
13447 if (LHSType.isNull())
13448 LHSType = LHS->getType();
13449
13451
13452 if (LT == Qualifiers::OCL_Weak) {
13453 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13455 }
13456
13457 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13458 return;
13459
13460 // FIXME. Check for other life times.
13461 if (LT != Qualifiers::OCL_None)
13462 return;
13463
13464 if (PRE) {
13465 if (PRE->isImplicitProperty())
13466 return;
13467 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13468 if (!PD)
13469 return;
13470
13471 unsigned Attributes = PD->getPropertyAttributes();
13472 if (Attributes & ObjCPropertyAttribute::kind_assign) {
13473 // when 'assign' attribute was not explicitly specified
13474 // by user, ignore it and rely on property type itself
13475 // for lifetime info.
13476 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13477 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
13478 LHSType->isObjCRetainableType())
13479 return;
13480
13481 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13482 if (cast->getCastKind() == CK_ARCConsumeObject) {
13483 Diag(Loc, diag::warn_arc_retained_property_assign)
13484 << RHS->getSourceRange();
13485 return;
13486 }
13487 RHS = cast->getSubExpr();
13488 }
13489 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
13490 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13491 return;
13492 }
13493 }
13494}
13495
13496//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13497
13498static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13499 SourceLocation StmtLoc,
13500 const NullStmt *Body) {
13501 // Do not warn if the body is a macro that expands to nothing, e.g:
13502 //
13503 // #define CALL(x)
13504 // if (condition)
13505 // CALL(0);
13506 if (Body->hasLeadingEmptyMacro())
13507 return false;
13508
13509 // Get line numbers of statement and body.
13510 bool StmtLineInvalid;
13511 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13512 &StmtLineInvalid);
13513 if (StmtLineInvalid)
13514 return false;
13515
13516 bool BodyLineInvalid;
13517 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13518 &BodyLineInvalid);
13519 if (BodyLineInvalid)
13520 return false;
13521
13522 // Warn if null statement and body are on the same line.
13523 if (StmtLine != BodyLine)
13524 return false;
13525
13526 return true;
13527}
13528
13530 const Stmt *Body,
13531 unsigned DiagID) {
13532 // Since this is a syntactic check, don't emit diagnostic for template
13533 // instantiations, this just adds noise.
13535 return;
13536
13537 // The body should be a null statement.
13538 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13539 if (!NBody)
13540 return;
13541
13542 // Do the usual checks.
13543 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13544 return;
13545
13546 Diag(NBody->getSemiLoc(), DiagID);
13547 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13548}
13549
13551 const Stmt *PossibleBody) {
13552 assert(!CurrentInstantiationScope); // Ensured by caller
13553
13554 SourceLocation StmtLoc;
13555 const Stmt *Body;
13556 unsigned DiagID;
13557 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13558 StmtLoc = FS->getRParenLoc();
13559 Body = FS->getBody();
13560 DiagID = diag::warn_empty_for_body;
13561 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13562 StmtLoc = WS->getRParenLoc();
13563 Body = WS->getBody();
13564 DiagID = diag::warn_empty_while_body;
13565 } else
13566 return; // Neither `for' nor `while'.
13567
13568 // The body should be a null statement.
13569 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13570 if (!NBody)
13571 return;
13572
13573 // Skip expensive checks if diagnostic is disabled.
13574 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13575 return;
13576
13577 // Do the usual checks.
13578 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13579 return;
13580
13581 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13582 // noise level low, emit diagnostics only if for/while is followed by a
13583 // CompoundStmt, e.g.:
13584 // for (int i = 0; i < n; i++);
13585 // {
13586 // a(i);
13587 // }
13588 // or if for/while is followed by a statement with more indentation
13589 // than for/while itself:
13590 // for (int i = 0; i < n; i++);
13591 // a(i);
13592 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13593 if (!ProbableTypo) {
13594 bool BodyColInvalid;
13595 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13596 PossibleBody->getBeginLoc(), &BodyColInvalid);
13597 if (BodyColInvalid)
13598 return;
13599
13600 bool StmtColInvalid;
13601 unsigned StmtCol =
13602 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13603 if (StmtColInvalid)
13604 return;
13605
13606 if (BodyCol > StmtCol)
13607 ProbableTypo = true;
13608 }
13609
13610 if (ProbableTypo) {
13611 Diag(NBody->getSemiLoc(), DiagID);
13612 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13613 }
13614}
13615
13616//===--- CHECK: Warn on self move with std::move. -------------------------===//
13617
13618void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13619 SourceLocation OpLoc) {
13620 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13621 return;
13622
13624 return;
13625
13626 // Strip parens and casts away.
13627 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13628 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13629
13630 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
13631 // which we can treat as an inlined std::move
13632 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
13633 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
13634 RHSExpr = CE->getArg(0);
13635 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
13636 CXXSCE && CXXSCE->isXValue())
13637 RHSExpr = CXXSCE->getSubExpr();
13638 else
13639 return;
13640
13641 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13642 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13643
13644 // Two DeclRefExpr's, check that the decls are the same.
13645 if (LHSDeclRef && RHSDeclRef) {
13646 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13647 return;
13648 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13649 RHSDeclRef->getDecl()->getCanonicalDecl())
13650 return;
13651
13652 auto D = Diag(OpLoc, diag::warn_self_move)
13653 << LHSExpr->getType() << LHSExpr->getSourceRange()
13654 << RHSExpr->getSourceRange();
13655 if (const FieldDecl *F =
13657 D << 1 << F
13658 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
13659 else
13660 D << 0;
13661 return;
13662 }
13663
13664 // Member variables require a different approach to check for self moves.
13665 // MemberExpr's are the same if every nested MemberExpr refers to the same
13666 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13667 // the base Expr's are CXXThisExpr's.
13668 const Expr *LHSBase = LHSExpr;
13669 const Expr *RHSBase = RHSExpr;
13670 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13671 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13672 if (!LHSME || !RHSME)
13673 return;
13674
13675 while (LHSME && RHSME) {
13676 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13677 RHSME->getMemberDecl()->getCanonicalDecl())
13678 return;
13679
13680 LHSBase = LHSME->getBase();
13681 RHSBase = RHSME->getBase();
13682 LHSME = dyn_cast<MemberExpr>(LHSBase);
13683 RHSME = dyn_cast<MemberExpr>(RHSBase);
13684 }
13685
13686 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13687 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13688 if (LHSDeclRef && RHSDeclRef) {
13689 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13690 return;
13691 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13692 RHSDeclRef->getDecl()->getCanonicalDecl())
13693 return;
13694
13695 Diag(OpLoc, diag::warn_self_move)
13696 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
13697 << RHSExpr->getSourceRange();
13698 return;
13699 }
13700
13701 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13702 Diag(OpLoc, diag::warn_self_move)
13703 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
13704 << RHSExpr->getSourceRange();
13705}
13706
13707//===--- Layout compatibility ----------------------------------------------//
13708
13709static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
13710
13711/// Check if two enumeration types are layout-compatible.
13712static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
13713 const EnumDecl *ED2) {
13714 // C++11 [dcl.enum] p8:
13715 // Two enumeration types are layout-compatible if they have the same
13716 // underlying type.
13717 return ED1->isComplete() && ED2->isComplete() &&
13718 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13719}
13720
13721/// Check if two fields are layout-compatible.
13722/// Can be used on union members, which are exempt from alignment requirement
13723/// of common initial sequence.
13724static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
13725 const FieldDecl *Field2,
13726 bool AreUnionMembers = false) {
13727 [[maybe_unused]] const Type *Field1Parent =
13728 Field1->getParent()->getTypeForDecl();
13729 [[maybe_unused]] const Type *Field2Parent =
13730 Field2->getParent()->getTypeForDecl();
13731 assert(((Field1Parent->isStructureOrClassType() &&
13732 Field2Parent->isStructureOrClassType()) ||
13733 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
13734 "Can't evaluate layout compatibility between a struct field and a "
13735 "union field.");
13736 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
13737 (AreUnionMembers && Field1Parent->isUnionType())) &&
13738 "AreUnionMembers should be 'true' for union fields (only).");
13739
13740 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13741 return false;
13742
13743 if (Field1->isBitField() != Field2->isBitField())
13744 return false;
13745
13746 if (Field1->isBitField()) {
13747 // Make sure that the bit-fields are the same length.
13748 unsigned Bits1 = Field1->getBitWidthValue(C);
13749 unsigned Bits2 = Field2->getBitWidthValue(C);
13750
13751 if (Bits1 != Bits2)
13752 return false;
13753 }
13754
13755 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
13756 Field2->hasAttr<clang::NoUniqueAddressAttr>())
13757 return false;
13758
13759 if (!AreUnionMembers &&
13760 Field1->getMaxAlignment() != Field2->getMaxAlignment())
13761 return false;
13762
13763 return true;
13764}
13765
13766/// Check if two standard-layout structs are layout-compatible.
13767/// (C++11 [class.mem] p17)
13768static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
13769 const RecordDecl *RD2) {
13770 // Get to the class where the fields are declared
13771 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
13772 RD1 = D1CXX->getStandardLayoutBaseWithFields();
13773
13774 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
13775 RD2 = D2CXX->getStandardLayoutBaseWithFields();
13776
13777 // Check the fields.
13778 return llvm::equal(RD1->fields(), RD2->fields(),
13779 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
13780 return isLayoutCompatible(C, F1, F2);
13781 });
13782}
13783
13784/// Check if two standard-layout unions are layout-compatible.
13785/// (C++11 [class.mem] p18)
13786static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
13787 const RecordDecl *RD2) {
13789 for (auto *Field2 : RD2->fields())
13790 UnmatchedFields.insert(Field2);
13791
13792 for (auto *Field1 : RD1->fields()) {
13793 auto I = UnmatchedFields.begin();
13794 auto E = UnmatchedFields.end();
13795
13796 for ( ; I != E; ++I) {
13797 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
13798 bool Result = UnmatchedFields.erase(*I);
13799 (void) Result;
13800 assert(Result);
13801 break;
13802 }
13803 }
13804 if (I == E)
13805 return false;
13806 }
13807
13808 return UnmatchedFields.empty();
13809}
13810
13811static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
13812 const RecordDecl *RD2) {
13813 if (RD1->isUnion() != RD2->isUnion())
13814 return false;
13815
13816 if (RD1->isUnion())
13817 return isLayoutCompatibleUnion(C, RD1, RD2);
13818 else
13819 return isLayoutCompatibleStruct(C, RD1, RD2);
13820}
13821
13822/// Check if two types are layout-compatible in C++11 sense.
13823static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
13824 if (T1.isNull() || T2.isNull())
13825 return false;
13826
13827 // C++20 [basic.types] p11:
13828 // Two types cv1 T1 and cv2 T2 are layout-compatible types
13829 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
13830 // or layout-compatible standard-layout class types (11.4).
13833
13834 if (C.hasSameType(T1, T2))
13835 return true;
13836
13837 const Type::TypeClass TC1 = T1->getTypeClass();
13838 const Type::TypeClass TC2 = T2->getTypeClass();
13839
13840 if (TC1 != TC2)
13841 return false;
13842
13843 if (TC1 == Type::Enum) {
13844 return isLayoutCompatible(C,
13845 cast<EnumType>(T1)->getDecl(),
13846 cast<EnumType>(T2)->getDecl());
13847 } else if (TC1 == Type::Record) {
13848 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13849 return false;
13850
13851 return isLayoutCompatible(C,
13852 cast<RecordType>(T1)->getDecl(),
13853 cast<RecordType>(T2)->getDecl());
13854 }
13855
13856 return false;
13857}
13858
13860 return isLayoutCompatible(getASTContext(), T1, T2);
13861}
13862
13863//===-------------- Pointer interconvertibility ----------------------------//
13864
13866 const TypeSourceInfo *Derived) {
13867 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
13868 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
13869
13870 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
13871 getASTContext().hasSameType(BaseT, DerivedT))
13872 return true;
13873
13874 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
13875 return false;
13876
13877 // Per [basic.compound]/4.3, containing object has to be standard-layout.
13878 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
13879 return true;
13880
13881 return false;
13882}
13883
13884//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13885
13886/// Given a type tag expression find the type tag itself.
13887///
13888/// \param TypeExpr Type tag expression, as it appears in user's code.
13889///
13890/// \param VD Declaration of an identifier that appears in a type tag.
13891///
13892/// \param MagicValue Type tag magic value.
13893///
13894/// \param isConstantEvaluated whether the evalaution should be performed in
13895
13896/// constant context.
13897static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13898 const ValueDecl **VD, uint64_t *MagicValue,
13899 bool isConstantEvaluated) {
13900 while(true) {
13901 if (!TypeExpr)
13902 return false;
13903
13904 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13905
13906 switch (TypeExpr->getStmtClass()) {
13907 case Stmt::UnaryOperatorClass: {
13908 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13909 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13910 TypeExpr = UO->getSubExpr();
13911 continue;
13912 }
13913 return false;
13914 }
13915
13916 case Stmt::DeclRefExprClass: {
13917 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13918 *VD = DRE->getDecl();
13919 return true;
13920 }
13921
13922 case Stmt::IntegerLiteralClass: {
13923 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13924 llvm::APInt MagicValueAPInt = IL->getValue();
13925 if (MagicValueAPInt.getActiveBits() <= 64) {
13926 *MagicValue = MagicValueAPInt.getZExtValue();
13927 return true;
13928 } else
13929 return false;
13930 }
13931
13932 case Stmt::BinaryConditionalOperatorClass:
13933 case Stmt::ConditionalOperatorClass: {
13934 const AbstractConditionalOperator *ACO =
13935 cast<AbstractConditionalOperator>(TypeExpr);
13936 bool Result;
13937 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
13938 isConstantEvaluated)) {
13939 if (Result)
13940 TypeExpr = ACO->getTrueExpr();
13941 else
13942 TypeExpr = ACO->getFalseExpr();
13943 continue;
13944 }
13945 return false;
13946 }
13947
13948 case Stmt::BinaryOperatorClass: {
13949 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13950 if (BO->getOpcode() == BO_Comma) {
13951 TypeExpr = BO->getRHS();
13952 continue;
13953 }
13954 return false;
13955 }
13956
13957 default:
13958 return false;
13959 }
13960 }
13961}
13962
13963/// Retrieve the C type corresponding to type tag TypeExpr.
13964///
13965/// \param TypeExpr Expression that specifies a type tag.
13966///
13967/// \param MagicValues Registered magic values.
13968///
13969/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13970/// kind.
13971///
13972/// \param TypeInfo Information about the corresponding C type.
13973///
13974/// \param isConstantEvaluated whether the evalaution should be performed in
13975/// constant context.
13976///
13977/// \returns true if the corresponding C type was found.
13979 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
13980 const ASTContext &Ctx,
13981 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
13982 *MagicValues,
13983 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
13984 bool isConstantEvaluated) {
13985 FoundWrongKind = false;
13986
13987 // Variable declaration that has type_tag_for_datatype attribute.
13988 const ValueDecl *VD = nullptr;
13989
13990 uint64_t MagicValue;
13991
13992 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
13993 return false;
13994
13995 if (VD) {
13996 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13997 if (I->getArgumentKind() != ArgumentKind) {
13998 FoundWrongKind = true;
13999 return false;
14000 }
14001 TypeInfo.Type = I->getMatchingCType();
14002 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14003 TypeInfo.MustBeNull = I->getMustBeNull();
14004 return true;
14005 }
14006 return false;
14007 }
14008
14009 if (!MagicValues)
14010 return false;
14011
14012 llvm::DenseMap<Sema::TypeTagMagicValue,
14013 Sema::TypeTagData>::const_iterator I =
14014 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14015 if (I == MagicValues->end())
14016 return false;
14017
14018 TypeInfo = I->second;
14019 return true;
14020}
14021
14023 uint64_t MagicValue, QualType Type,
14024 bool LayoutCompatible,
14025 bool MustBeNull) {
14026 if (!TypeTagForDatatypeMagicValues)
14027 TypeTagForDatatypeMagicValues.reset(
14028 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14029
14030 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14031 (*TypeTagForDatatypeMagicValues)[Magic] =
14032 TypeTagData(Type, LayoutCompatible, MustBeNull);
14033}
14034
14035static bool IsSameCharType(QualType T1, QualType T2) {
14036 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14037 if (!BT1)
14038 return false;
14039
14040 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14041 if (!BT2)
14042 return false;
14043
14044 BuiltinType::Kind T1Kind = BT1->getKind();
14045 BuiltinType::Kind T2Kind = BT2->getKind();
14046
14047 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
14048 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
14049 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14050 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14051}
14052
14053void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14054 const ArrayRef<const Expr *> ExprArgs,
14055 SourceLocation CallSiteLoc) {
14056 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14057 bool IsPointerAttr = Attr->getIsPointer();
14058
14059 // Retrieve the argument representing the 'type_tag'.
14060 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14061 if (TypeTagIdxAST >= ExprArgs.size()) {
14062 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14063 << 0 << Attr->getTypeTagIdx().getSourceIndex();
14064 return;
14065 }
14066 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14067 bool FoundWrongKind;
14068 TypeTagData TypeInfo;
14069 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14070 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14072 if (FoundWrongKind)
14073 Diag(TypeTagExpr->getExprLoc(),
14074 diag::warn_type_tag_for_datatype_wrong_kind)
14075 << TypeTagExpr->getSourceRange();
14076 return;
14077 }
14078
14079 // Retrieve the argument representing the 'arg_idx'.
14080 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14081 if (ArgumentIdxAST >= ExprArgs.size()) {
14082 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14083 << 1 << Attr->getArgumentIdx().getSourceIndex();
14084 return;
14085 }
14086 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14087 if (IsPointerAttr) {
14088 // Skip implicit cast of pointer to `void *' (as a function argument).
14089 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14090 if (ICE->getType()->isVoidPointerType() &&
14091 ICE->getCastKind() == CK_BitCast)
14092 ArgumentExpr = ICE->getSubExpr();
14093 }
14094 QualType ArgumentType = ArgumentExpr->getType();
14095
14096 // Passing a `void*' pointer shouldn't trigger a warning.
14097 if (IsPointerAttr && ArgumentType->isVoidPointerType())
14098 return;
14099
14100 if (TypeInfo.MustBeNull) {
14101 // Type tag with matching void type requires a null pointer.
14102 if (!ArgumentExpr->isNullPointerConstant(Context,
14104 Diag(ArgumentExpr->getExprLoc(),
14105 diag::warn_type_safety_null_pointer_required)
14106 << ArgumentKind->getName()
14107 << ArgumentExpr->getSourceRange()
14108 << TypeTagExpr->getSourceRange();
14109 }
14110 return;
14111 }
14112
14113 QualType RequiredType = TypeInfo.Type;
14114 if (IsPointerAttr)
14115 RequiredType = Context.getPointerType(RequiredType);
14116
14117 bool mismatch = false;
14118 if (!TypeInfo.LayoutCompatible) {
14119 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14120
14121 // C++11 [basic.fundamental] p1:
14122 // Plain char, signed char, and unsigned char are three distinct types.
14123 //
14124 // But we treat plain `char' as equivalent to `signed char' or `unsigned
14125 // char' depending on the current char signedness mode.
14126 if (mismatch)
14127 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14128 RequiredType->getPointeeType())) ||
14129 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14130 mismatch = false;
14131 } else
14132 if (IsPointerAttr)
14133 mismatch = !isLayoutCompatible(Context,
14134 ArgumentType->getPointeeType(),
14135 RequiredType->getPointeeType());
14136 else
14137 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14138
14139 if (mismatch)
14140 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14141 << ArgumentType << ArgumentKind
14142 << TypeInfo.LayoutCompatible << RequiredType
14143 << ArgumentExpr->getSourceRange()
14144 << TypeTagExpr->getSourceRange();
14145}
14146
14147void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14148 CharUnits Alignment) {
14149 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14150}
14151
14153 for (MisalignedMember &m : MisalignedMembers) {
14154 const NamedDecl *ND = m.RD;
14155 if (ND->getName().empty()) {
14156 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14157 ND = TD;
14158 }
14159 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14160 << m.MD << ND << m.E->getSourceRange();
14161 }
14162 MisalignedMembers.clear();
14163}
14164
14166 E = E->IgnoreParens();
14167 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
14168 return;
14169 if (isa<UnaryOperator>(E) &&
14170 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14171 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14172 if (isa<MemberExpr>(Op)) {
14173 auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14174 if (MA != MisalignedMembers.end() &&
14175 (T->isDependentType() || T->isIntegerType() ||
14178 T->getPointeeType()) <= MA->Alignment))))
14179 MisalignedMembers.erase(MA);
14180 }
14181 }
14182}
14183
14185 Expr *E,
14186 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14187 Action) {
14188 const auto *ME = dyn_cast<MemberExpr>(E);
14189 if (!ME)
14190 return;
14191
14192 // No need to check expressions with an __unaligned-qualified type.
14194 return;
14195
14196 // For a chain of MemberExpr like "a.b.c.d" this list
14197 // will keep FieldDecl's like [d, c, b].
14198 SmallVector<FieldDecl *, 4> ReverseMemberChain;
14199 const MemberExpr *TopME = nullptr;
14200 bool AnyIsPacked = false;
14201 do {
14202 QualType BaseType = ME->getBase()->getType();
14203 if (BaseType->isDependentType())
14204 return;
14205 if (ME->isArrow())
14206 BaseType = BaseType->getPointeeType();
14207 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14208 if (RD->isInvalidDecl())
14209 return;
14210
14211 ValueDecl *MD = ME->getMemberDecl();
14212 auto *FD = dyn_cast<FieldDecl>(MD);
14213 // We do not care about non-data members.
14214 if (!FD || FD->isInvalidDecl())
14215 return;
14216
14217 AnyIsPacked =
14218 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14219 ReverseMemberChain.push_back(FD);
14220
14221 TopME = ME;
14222 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14223 } while (ME);
14224 assert(TopME && "We did not compute a topmost MemberExpr!");
14225
14226 // Not the scope of this diagnostic.
14227 if (!AnyIsPacked)
14228 return;
14229
14230 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14231 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14232 // TODO: The innermost base of the member expression may be too complicated.
14233 // For now, just disregard these cases. This is left for future
14234 // improvement.
14235 if (!DRE && !isa<CXXThisExpr>(TopBase))
14236 return;
14237
14238 // Alignment expected by the whole expression.
14239 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14240
14241 // No need to do anything else with this case.
14242 if (ExpectedAlignment.isOne())
14243 return;
14244
14245 // Synthesize offset of the whole access.
14246 CharUnits Offset;
14247 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
14249
14250 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14251 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14252 ReverseMemberChain.back()->getParent()->getTypeForDecl());
14253
14254 // The base expression of the innermost MemberExpr may give
14255 // stronger guarantees than the class containing the member.
14256 if (DRE && !TopME->isArrow()) {
14257 const ValueDecl *VD = DRE->getDecl();
14258 if (!VD->getType()->isReferenceType())
14259 CompleteObjectAlignment =
14260 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14261 }
14262
14263 // Check if the synthesized offset fulfills the alignment.
14264 if (Offset % ExpectedAlignment != 0 ||
14265 // It may fulfill the offset it but the effective alignment may still be
14266 // lower than the expected expression alignment.
14267 CompleteObjectAlignment < ExpectedAlignment) {
14268 // If this happens, we want to determine a sensible culprit of this.
14269 // Intuitively, watching the chain of member expressions from right to
14270 // left, we start with the required alignment (as required by the field
14271 // type) but some packed attribute in that chain has reduced the alignment.
14272 // It may happen that another packed structure increases it again. But if
14273 // we are here such increase has not been enough. So pointing the first
14274 // FieldDecl that either is packed or else its RecordDecl is,
14275 // seems reasonable.
14276 FieldDecl *FD = nullptr;
14277 CharUnits Alignment;
14278 for (FieldDecl *FDI : ReverseMemberChain) {
14279 if (FDI->hasAttr<PackedAttr>() ||
14280 FDI->getParent()->hasAttr<PackedAttr>()) {
14281 FD = FDI;
14282 Alignment = std::min(
14285 break;
14286 }
14287 }
14288 assert(FD && "We did not find a packed FieldDecl!");
14289 Action(E, FD->getParent(), FD, Alignment);
14290 }
14291}
14292
14293void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14294 using namespace std::placeholders;
14295
14297 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14298 _2, _3, _4));
14299}
14300
14302 if (checkArgCount(TheCall, 1))
14303 return true;
14304
14305 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
14306 if (A.isInvalid())
14307 return true;
14308
14309 TheCall->setArg(0, A.get());
14310 QualType TyA = A.get()->getType();
14311
14312 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14313 return true;
14314
14315 TheCall->setType(TyA);
14316 return false;
14317}
14318
14319bool Sema::BuiltinElementwiseMath(CallExpr *TheCall) {
14320 QualType Res;
14321 if (BuiltinVectorMath(TheCall, Res))
14322 return true;
14323 TheCall->setType(Res);
14324 return false;
14325}
14326
14328 QualType Res;
14329 if (BuiltinVectorMath(TheCall, Res))
14330 return true;
14331
14332 if (auto *VecTy0 = Res->getAs<VectorType>())
14333 TheCall->setType(VecTy0->getElementType());
14334 else
14335 TheCall->setType(Res);
14336
14337 return false;
14338}
14339
14341 if (checkArgCount(TheCall, 2))
14342 return true;
14343
14344 ExprResult A = TheCall->getArg(0);
14345 ExprResult B = TheCall->getArg(1);
14346 // Do standard promotions between the two arguments, returning their common
14347 // type.
14348 Res = UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
14349 if (A.isInvalid() || B.isInvalid())
14350 return true;
14351
14352 QualType TyA = A.get()->getType();
14353 QualType TyB = B.get()->getType();
14354
14355 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
14356 return Diag(A.get()->getBeginLoc(),
14357 diag::err_typecheck_call_different_arg_types)
14358 << TyA << TyB;
14359
14360 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
14361 return true;
14362
14363 TheCall->setArg(0, A.get());
14364 TheCall->setArg(1, B.get());
14365 return false;
14366}
14367
14369 bool CheckForFloatArgs) {
14370 if (checkArgCount(TheCall, 3))
14371 return true;
14372
14373 Expr *Args[3];
14374 for (int I = 0; I < 3; ++I) {
14375 ExprResult Converted = UsualUnaryConversions(TheCall->getArg(I));
14376 if (Converted.isInvalid())
14377 return true;
14378 Args[I] = Converted.get();
14379 }
14380
14381 if (CheckForFloatArgs) {
14382 int ArgOrdinal = 1;
14383 for (Expr *Arg : Args) {
14385 Arg->getType(), ArgOrdinal++))
14386 return true;
14387 }
14388 } else {
14389 int ArgOrdinal = 1;
14390 for (Expr *Arg : Args) {
14391 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
14392 ArgOrdinal++))
14393 return true;
14394 }
14395 }
14396
14397 for (int I = 1; I < 3; ++I) {
14398 if (Args[0]->getType().getCanonicalType() !=
14399 Args[I]->getType().getCanonicalType()) {
14400 return Diag(Args[0]->getBeginLoc(),
14401 diag::err_typecheck_call_different_arg_types)
14402 << Args[0]->getType() << Args[I]->getType();
14403 }
14404
14405 TheCall->setArg(I, Args[I]);
14406 }
14407
14408 TheCall->setType(Args[0]->getType());
14409 return false;
14410}
14411
14412bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
14413 if (checkArgCount(TheCall, 1))
14414 return true;
14415
14416 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
14417 if (A.isInvalid())
14418 return true;
14419
14420 TheCall->setArg(0, A.get());
14421 return false;
14422}
14423
14424bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
14425 if (checkArgCount(TheCall, 1))
14426 return true;
14427
14428 ExprResult Arg = TheCall->getArg(0);
14429 QualType TyArg = Arg.get()->getType();
14430
14431 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
14432 return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14433 << 1 << /*vector, integer or floating point ty*/ 0 << TyArg;
14434
14435 TheCall->setType(TyArg);
14436 return false;
14437}
14438
14439ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
14440 ExprResult CallResult) {
14441 if (checkArgCount(TheCall, 1))
14442 return ExprError();
14443
14444 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
14445 if (MatrixArg.isInvalid())
14446 return MatrixArg;
14447 Expr *Matrix = MatrixArg.get();
14448
14449 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
14450 if (!MType) {
14451 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14452 << 1 << /* matrix ty*/ 1 << Matrix->getType();
14453 return ExprError();
14454 }
14455
14456 // Create returned matrix type by swapping rows and columns of the argument
14457 // matrix type.
14459 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
14460
14461 // Change the return type to the type of the returned matrix.
14462 TheCall->setType(ResultType);
14463
14464 // Update call argument to use the possibly converted matrix argument.
14465 TheCall->setArg(0, Matrix);
14466 return CallResult;
14467}
14468
14469// Get and verify the matrix dimensions.
14470static std::optional<unsigned>
14472 SourceLocation ErrorPos;
14473 std::optional<llvm::APSInt> Value =
14474 Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
14475 if (!Value) {
14476 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
14477 << Name;
14478 return {};
14479 }
14480 uint64_t Dim = Value->getZExtValue();
14482 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
14484 return {};
14485 }
14486 return Dim;
14487}
14488
14489ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
14490 ExprResult CallResult) {
14491 if (!getLangOpts().MatrixTypes) {
14492 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
14493 return ExprError();
14494 }
14495
14496 if (checkArgCount(TheCall, 4))
14497 return ExprError();
14498
14499 unsigned PtrArgIdx = 0;
14500 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
14501 Expr *RowsExpr = TheCall->getArg(1);
14502 Expr *ColumnsExpr = TheCall->getArg(2);
14503 Expr *StrideExpr = TheCall->getArg(3);
14504
14505 bool ArgError = false;
14506
14507 // Check pointer argument.
14508 {
14510 if (PtrConv.isInvalid())
14511 return PtrConv;
14512 PtrExpr = PtrConv.get();
14513 TheCall->setArg(0, PtrExpr);
14514 if (PtrExpr->isTypeDependent()) {
14515 TheCall->setType(Context.DependentTy);
14516 return TheCall;
14517 }
14518 }
14519
14520 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
14521 QualType ElementTy;
14522 if (!PtrTy) {
14523 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14524 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
14525 ArgError = true;
14526 } else {
14527 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
14528
14530 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14531 << PtrArgIdx + 1 << /* pointer to element ty*/ 2
14532 << PtrExpr->getType();
14533 ArgError = true;
14534 }
14535 }
14536
14537 // Apply default Lvalue conversions and convert the expression to size_t.
14538 auto ApplyArgumentConversions = [this](Expr *E) {
14540 if (Conv.isInvalid())
14541 return Conv;
14542
14543 return tryConvertExprToType(Conv.get(), Context.getSizeType());
14544 };
14545
14546 // Apply conversion to row and column expressions.
14547 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
14548 if (!RowsConv.isInvalid()) {
14549 RowsExpr = RowsConv.get();
14550 TheCall->setArg(1, RowsExpr);
14551 } else
14552 RowsExpr = nullptr;
14553
14554 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
14555 if (!ColumnsConv.isInvalid()) {
14556 ColumnsExpr = ColumnsConv.get();
14557 TheCall->setArg(2, ColumnsExpr);
14558 } else
14559 ColumnsExpr = nullptr;
14560
14561 // If any part of the result matrix type is still pending, just use
14562 // Context.DependentTy, until all parts are resolved.
14563 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
14564 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
14565 TheCall->setType(Context.DependentTy);
14566 return CallResult;
14567 }
14568
14569 // Check row and column dimensions.
14570 std::optional<unsigned> MaybeRows;
14571 if (RowsExpr)
14572 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
14573
14574 std::optional<unsigned> MaybeColumns;
14575 if (ColumnsExpr)
14576 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
14577
14578 // Check stride argument.
14579 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
14580 if (StrideConv.isInvalid())
14581 return ExprError();
14582 StrideExpr = StrideConv.get();
14583 TheCall->setArg(3, StrideExpr);
14584
14585 if (MaybeRows) {
14586 if (std::optional<llvm::APSInt> Value =
14587 StrideExpr->getIntegerConstantExpr(Context)) {
14588 uint64_t Stride = Value->getZExtValue();
14589 if (Stride < *MaybeRows) {
14590 Diag(StrideExpr->getBeginLoc(),
14591 diag::err_builtin_matrix_stride_too_small);
14592 ArgError = true;
14593 }
14594 }
14595 }
14596
14597 if (ArgError || !MaybeRows || !MaybeColumns)
14598 return ExprError();
14599
14600 TheCall->setType(
14601 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
14602 return CallResult;
14603}
14604
14605ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
14606 ExprResult CallResult) {
14607 if (checkArgCount(TheCall, 3))
14608 return ExprError();
14609
14610 unsigned PtrArgIdx = 1;
14611 Expr *MatrixExpr = TheCall->getArg(0);
14612 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
14613 Expr *StrideExpr = TheCall->getArg(2);
14614
14615 bool ArgError = false;
14616
14617 {
14618 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
14619 if (MatrixConv.isInvalid())
14620 return MatrixConv;
14621 MatrixExpr = MatrixConv.get();
14622 TheCall->setArg(0, MatrixExpr);
14623 }
14624 if (MatrixExpr->isTypeDependent()) {
14625 TheCall->setType(Context.DependentTy);
14626 return TheCall;
14627 }
14628
14629 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
14630 if (!MatrixTy) {
14631 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14632 << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
14633 ArgError = true;
14634 }
14635
14636 {
14638 if (PtrConv.isInvalid())
14639 return PtrConv;
14640 PtrExpr = PtrConv.get();
14641 TheCall->setArg(1, PtrExpr);
14642 if (PtrExpr->isTypeDependent()) {
14643 TheCall->setType(Context.DependentTy);
14644 return TheCall;
14645 }
14646 }
14647
14648 // Check pointer argument.
14649 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
14650 if (!PtrTy) {
14651 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
14652 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
14653 ArgError = true;
14654 } else {
14655 QualType ElementTy = PtrTy->getPointeeType();
14656 if (ElementTy.isConstQualified()) {
14657 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
14658 ArgError = true;
14659 }
14660 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
14661 if (MatrixTy &&
14662 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
14663 Diag(PtrExpr->getBeginLoc(),
14664 diag::err_builtin_matrix_pointer_arg_mismatch)
14665 << ElementTy << MatrixTy->getElementType();
14666 ArgError = true;
14667 }
14668 }
14669
14670 // Apply default Lvalue conversions and convert the stride expression to
14671 // size_t.
14672 {
14673 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
14674 if (StrideConv.isInvalid())
14675 return StrideConv;
14676
14677 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
14678 if (StrideConv.isInvalid())
14679 return StrideConv;
14680 StrideExpr = StrideConv.get();
14681 TheCall->setArg(2, StrideExpr);
14682 }
14683
14684 // Check stride argument.
14685 if (MatrixTy) {
14686 if (std::optional<llvm::APSInt> Value =
14687 StrideExpr->getIntegerConstantExpr(Context)) {
14688 uint64_t Stride = Value->getZExtValue();
14689 if (Stride < MatrixTy->getNumRows()) {
14690 Diag(StrideExpr->getBeginLoc(),
14691 diag::err_builtin_matrix_stride_too_small);
14692 ArgError = true;
14693 }
14694 }
14695 }
14696
14697 if (ArgError)
14698 return ExprError();
14699
14700 return CallResult;
14701}
14702
14704 const NamedDecl *Callee) {
14705 // This warning does not make sense in code that has no runtime behavior.
14707 return;
14708
14709 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
14710
14711 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
14712 return;
14713
14714 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
14715 // all TCBs the callee is a part of.
14716 llvm::StringSet<> CalleeTCBs;
14717 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
14718 CalleeTCBs.insert(A->getTCBName());
14719 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
14720 CalleeTCBs.insert(A->getTCBName());
14721
14722 // Go through the TCBs the caller is a part of and emit warnings if Caller
14723 // is in a TCB that the Callee is not.
14724 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
14725 StringRef CallerTCB = A->getTCBName();
14726 if (CalleeTCBs.count(CallerTCB) == 0) {
14727 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
14728 << Callee << CallerTCB;
14729 }
14730 }
14731}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
NodeId Parent
Definition: ASTDiff.cpp:191
SyntaxTree::Impl & Tree
Definition: ASTDiff.cpp:192
ASTImporterLookupTable & LT
StringRef P
Provides definitions for the various language-specific address spaces.
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
const Decl * D
Expr * E
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:632
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
LangStandard::Kind Std
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
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 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Pseudo-evaluate the given integer expression, estimating the range of values it might take.
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 CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
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 DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
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 StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers=false)
static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth)
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
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 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, SourceLocation CC)
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool isKnownToHaveUnsignedValue(Expr *E)
static ExprResult BuiltinDumpStruct(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 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 bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
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 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)
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 bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
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 void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
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 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 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 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.
#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 bool requiresParensToAddCast(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
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 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 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 IsEnumConstOrFromMacro(Sema &S, Expr *E)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
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)
MathCheck
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 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 bool HasEnumType(Expr *E)
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 checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
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.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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 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.
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
std::string Label
__DEVICE__ int min(int __a, int __b)
__device__ int
__device__ __2f16 float __ockl_bool s
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
bool isVector() const
Definition: APValue.h:407
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isComplexInt() const
Definition: APValue.h:404
bool isFloat() const
Definition: APValue.h:402
bool isComplexFloat() const
Definition: APValue.h:405
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
bool isInt() const
Definition: APValue.h:401
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
bool isAddrLabelDiff() const
Definition: APValue.h:412
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getRecordType(const RecordDecl *Decl) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
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
Definition: ASTContext.h:1147
IdentifierTable & Idents
Definition: ASTContext.h:660
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
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.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
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
Definition: ASTContext.h:1120
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:780
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1121
CanQualType IntTy
Definition: ASTContext.h:1128
TypeInfoChars getTypeInfoInChars(const Type *T) const
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:713
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
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.
Definition: ASTContext.h:2394
CanQualType BuiltinFnTy
Definition: ASTContext.h:1149
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
QualType getExceptionObjectType(QualType T) const
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1129
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
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...
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
@ GE_None
No error.
Definition: ASTContext.h:2296
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2398
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:218
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4175
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4353
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4359
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4365
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition: Expr.h:6926
Expr * getBase()
Get base of the array section.
Definition: Expr.h:6992
Expr * getLowerBound()
Get lower bound of array section.
Definition: Expr.h:6996
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
SourceLocation getRBracketLoc() const
Definition: Expr.h:2722
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2703
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3580
QualType getElementType() const
Definition: Type.h:3578
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6629
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:6770
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6736
Attr - This represents one attribute.
Definition: Attr.h:42
const char * getSpelling() const
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6375
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6390
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3993
Expr * getLHS() const
Definition: Expr.h:3910
SourceLocation getExprLoc() const
Definition: Expr.h:3901
Expr * getRHS() const
Definition: Expr.h:3912
bool isEqualityOp() const
Definition: Expr.h:3958
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3946
Opcode getOpcode() const
Definition: Expr.h:3905
A fixed int type of a specified bitwidth.
Definition: Type.h:7633
Pointer to a block type.
Definition: Type.h:3397
This class is used for builtin types like 'int'.
Definition: Type.h:3023
bool isInteger() const
Definition: Type.h:3084
bool isFloatingPoint() const
Definition: Type.h:3096
bool isSignedInteger() const
Definition: Type.h:3088
bool isUnsignedInteger() const
Definition: Type.h:3092
Kind getKind() const
Definition: Type.h:3071
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
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:222
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition: Builtins.h:268
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3791
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1628
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1686
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprCXX.h:151
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:111
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4954
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:4994
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1230
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
bool isDynamicClass() const
Definition: DeclCXX.h:586
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3021
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3034
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
arg_iterator arg_begin()
Definition: Expr.h:3074
arg_iterator arg_end()
Definition: Expr.h:3077
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
bool isCallToStdMove() const
Definition: Expr.cpp:3521
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1647
Expr * getCallee()
Definition: Expr.h:2980
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3008
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:3111
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3011
arg_range arguments()
Definition: Expr.h:3069
SourceLocation getRParenLoc() const
Definition: Expr.h:3145
Decl * getCalleeDecl()
Definition: Expr.h:2994
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:1584
void setCallee(Expr *F)
Definition: Expr.h:2982
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.
Definition: CanonicalType.h:83
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3498
path_iterator path_begin()
Definition: Expr.h:3568
CastKind getCastKind() const
Definition: Expr.h:3542
path_iterator path_end()
Definition: Expr.h:3569
Expr * getSubExpr()
Definition: Expr.h:3548
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
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
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
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4122
Declaration of a C++20 concept.
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
Expr * getLHS() const
Definition: Expr.h:4247
Expr * getRHS() const
Definition: Expr.h:4248
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
QualType desugar() const
Definition: Type.h:3705
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3660
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4219
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition: Type.h:4253
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4248
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4533
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:5071
Expr * getOperand() const
Definition: ExprCXX.h:5140
child_range children()
Definition: ExprCXX.h:5170
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:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1352
ValueDecl * getDecl()
Definition: Expr.h:1333
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1457
SourceLocation getLocation() const
Definition: Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
T * getAttr() const
Definition: DeclBase.h:580
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:537
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1178
bool isInvalidDecl() const
Definition: DeclBase.h:595
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
SourceLocation getLocation() const
Definition: DeclBase.h:446
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool hasAttr() const
Definition: DeclBase.h:584
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
The name of a declaration.
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1970
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1077
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1088
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3274
Represents an enum.
Definition: Decl.h:3844
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4041
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4063
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4020
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4004
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4030
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
This represents one expression.
Definition: Expr.h:110
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:671
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:668
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3075
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
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...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3058
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
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:3066
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4102
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
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:3062
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:3567
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:221
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:797
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:809
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:799
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:3941
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isFlexibleArrayMemberLike(ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition: Expr.cpp:206
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
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:226
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition: Type.h:4113
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4578
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3134
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
llvm::APFloat getValue() const
Definition: Expr.h:1652
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2791
Represents a function declaration or definition.
Definition: Decl.h:1932
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4385
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3699
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
param_iterator param_end()
Definition: Decl.h:2659
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3717
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
param_iterator param_begin()
Definition: Decl.h:2658
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4164
bool isStatic() const
Definition: Decl.h:2801
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
unsigned getNumParams() const
Definition: Type.h:5255
QualType getParamType(unsigned i) const
Definition: Type.h:5257
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5374
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4600
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4596
QualType getReturnType() const
Definition: Type.h:4630
@ SME_PStateSMEnabledMask
Definition: Type.h:4574
@ SME_PStateSMCompatibleMask
Definition: Type.h:4575
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:3675
Describes an C or C++ initializer list.
Definition: Expr.h:5039
ArrayRef< Expr * > inits()
Definition: Expr.h:5079
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:977
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
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:1024
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1060
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:499
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1107
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:850
Represents the results of name lookup.
Definition: Lookup.h:46
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:568
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
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: Type.h:4204
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3270
Expr * getBase() const
Definition: Expr.h:3264
bool isArrow() const
Definition: Expr.h:3371
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1912
Represent a C++ namespace.
Definition: Decl.h:547
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1574
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1588
SourceLocation getSemiLoc() const
Definition: Stmt.h:1585
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
QualType getType() const
Definition: DeclObjC.h:803
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:826
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:617
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:706
bool isImplicitProperty() const
Definition: ExprObjC.h:703
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
Represents a parameter to a function.
Definition: Decl.h:1722
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6497
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4953
A (possibly-)qualified type.
Definition: Type.h:941
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2751
PrimitiveDefaultInitializeKind
Definition: Type.h:1463
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1221
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1101
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
void removeLocalVolatile()
Definition: Type.h:7866
void removeLocalConst()
Definition: Type.h:7858
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7871
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
bool hasUnaligned() const
Definition: Type.h:498
Represents a struct/union/class.
Definition: Decl.h:4145
field_range fields() const
Definition: Decl.h:4351
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
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)
Definition: SemaAMDGPU.cpp:25
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaARM.cpp:986
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition: SemaARM.h:35
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition: SemaARM.h:36
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaARM.cpp:1064
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaBPF.cpp:111
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
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.
Definition: SemaObjC.cpp:2357
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
bool isSignedCharBool(QualType Ty)
Definition: SemaObjC.cpp:2308
void adornBoolConversionDiagWithTernaryFixit(Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
Definition: SemaObjC.cpp:2313
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...
Definition: SemaObjC.cpp:2271
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
Definition: SemaObjC.cpp:2382
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:601
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaPPC.cpp:96
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition: SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition: SemaPPC.cpp:259
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaRISCV.cpp:565
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaSystemZ.cpp:24
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaWasm.cpp:219
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition: SemaX86.cpp:631
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
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...
Definition: SemaExpr.cpp:14387
SemaAMDGPU & AMDGPU()
Definition: Sema.h:1099
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...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12656
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:763
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2491
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9023
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9060
VariadicCallType
Definition: Sema.h:2346
@ VariadicDoesNotApply
Definition: Sema.h:2351
@ VariadicFunction
Definition: Sema.h:2347
@ VariadicConstructor
Definition: Sema.h:2350
@ VariadicBlock
Definition: Sema.h:2348
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
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...
bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
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.
bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
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....
Definition: SemaExpr.cpp:1551
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, bool IsVariadic, FormatStringInfo *FSI)
Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo parameter with the Format...
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
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...
SemaHexagon & Hexagon()
Definition: Sema.h:1134
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:1567
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:784
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
SemaX86 & X86()
Definition: Sema.h:1219
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1036
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4979
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:13991
ASTContext & Context
Definition: Sema.h:962
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
static FormatStringType GetFormatStringType(const FormatAttr *Format)
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:1164
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
ASTContext & getASTContext() const
Definition: Sema.h:560
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)
Definition: SemaExpr.cpp:15567
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:702
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition: Sema.h:2180
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:868
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:2288
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition: Sema.h:553
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:8896
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:1114
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5650
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.
Definition: SemaExpr.cpp:6408
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
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:960
static const uint64_t MaximumAlignment
Definition: Sema.h:891
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall)
SemaHLSL & HLSL()
Definition: Sema.h:1129
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
SemaMIPS & MIPS()
Definition: Sema.h:1149
SemaRISCV & RISCV()
Definition: Sema.h:1194
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.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6487
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1579
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:936
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3341
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:993
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:2266
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:2148
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:640
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res)
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:1097
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
@ VAK_Invalid
Definition: Sema.h:7559
@ VAK_Valid
Definition: Sema.h:7555
@ VAK_ValidInCXX11
Definition: Sema.h:7556
@ VAK_MSVCUndefined
Definition: Sema.h:7558
@ VAK_Undefined
Definition: Sema.h:7557
SemaOpenCL & OpenCL()
Definition: Sema.h:1174
FormatArgumentPassingKind
Definition: Sema.h:2190
@ FAPK_Fixed
Definition: Sema.h:2191
@ FAPK_Variadic
Definition: Sema.h:2192
@ FAPK_VAList
Definition: Sema.h:2193
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7796
@ ACK_Comparison
A comparison.
Definition: Sema.h:7424
bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20717
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13497
SourceManager & getSourceManager() const
Definition: Sema.h:558
@ AA_Passing
Definition: Sema.h:6497
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, bool CheckForFloatArgs=true)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
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 DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20001
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 BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
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:216
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
bool isConstantEvaluatedContext() const
Definition: Sema.h:2182
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.
Definition: SemaExpr.cpp:12538
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
SemaPPC & PPC()
Definition: Sema.h:1184
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:923
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SemaSystemZ & SystemZ()
Definition: Sema.h:1209
SourceManager & SourceMgr
Definition: Sema.h:965
DiagnosticsEngine & Diags
Definition: Sema.h:964
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9656
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...
Definition: SemaExpr.cpp:991
FormatStringType
Definition: Sema.h:2219
@ FST_NSString
Definition: Sema.h:2222
@ FST_Syslog
Definition: Sema.h:2229
@ FST_Unknown
Definition: Sema.h:2230
@ FST_Strftime
Definition: Sema.h:2223
@ FST_Printf
Definition: Sema.h:2221
@ FST_FreeBSDKPrintf
Definition: Sema.h:2226
@ FST_Scanf
Definition: Sema.h:2220
@ FST_Strfmon
Definition: Sema.h:2224
@ FST_OSLog
Definition: Sema.h:2228
@ FST_Kprintf
Definition: Sema.h:2225
@ FST_OSTrace
Definition: Sema.h:2227
SemaNVPTX & NVPTX()
Definition: Sema.h:1159
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:574
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,...
Definition: SemaExpr.cpp:17862
@ AbstractParamType
Definition: Sema.h:5768
bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
SemaLoongArch & LoongArch()
Definition: Sema.h:1139
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
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:1214
SemaARM & ARM()
Definition: Sema.h:1104
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
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:4465
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.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
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.
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
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.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const
Returns true if the spelling locations for both SourceLocations are part of the same file buffer.
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
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:287
StmtClass getStmtClass() const
Definition: Stmt.h:1363
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
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:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1959
bool isUTF8() const
Definition: Expr.h:1904
bool isWide() const
Definition: Expr.h:1903
bool isPascal() const
Definition: Expr.h:1908
unsigned getLength() const
Definition: Expr.h:1895
StringLiteralKind getKind() const
Definition: Expr.h:1898
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:1329
bool isUTF32() const
Definition: Expr.h:1906
unsigned getByteLength() const
Definition: Expr.h:1894
StringRef getString() const
Definition: Expr.h:1855
bool isUTF16() const
Definition: Expr.h:1905
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1960
bool isOrdinary() const
Definition: Expr.h:1902
unsigned getCharByteWidth() const
Definition: Expr.h:1896
bool isUnion() const
Definition: Decl.h:3767
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const
Determine whether the given pointer-authentication key is valid.
Definition: TargetInfo.cpp:939
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1513
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1533
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1515
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:992
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
IntType getSizeType() const
Definition: TargetInfo.h:371
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1519
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1514
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
Definition: TargetInfo.h:1672
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1487
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm....
Definition: TargetInfo.h:1721
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
const Type * getTypeForDecl() const
Definition: Decl.h:3391
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5697
A container of type source information.
Definition: Type.h:7721
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7732
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBlockPointerType() const
Definition: Type.h:8017
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8497
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isFloat16Type() const
Definition: Type.h:8328
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2217
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8477
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:2021
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isArrayType() const
Definition: Type.h:8075
bool isCharType() const
Definition: Type.cpp:2089
bool isFunctionPointerType() const
Definition: Type.h:8043
bool isPointerType() const
Definition: Type.h:8003
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isEnumeralType() const
Definition: Type.h:8107
bool isScalarType() const
Definition: Type.h:8418
bool isVariableArrayType() const
Definition: Type.h:8087
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2510
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8434
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2236
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2548
bool isBitIntType() const
Definition: Type.h:8241
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8288
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8099
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isAnyComplexType() const
Definition: Type.h:8111
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8372
bool isHalfType() const
Definition: Type.h:8323
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2186
QualType getCanonicalTypeInternal() const
Definition: Type.h:2978
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2467
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8490
bool isMemberPointerType() const
Definition: Type.h:8057
bool isAtomicType() const
Definition: Type.h:8158
bool isFunctionProtoType() const
Definition: Type.h:2528
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2973
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2713
bool isObjCObjectType() const
Definition: Type.h:8149
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8593
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2439
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2258
bool isStructureOrClassType() const
Definition: Type.cpp:657
bool isVectorType() const
Definition: Type.h:8115
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isFloatingType() const
Definition: Type.cpp:2249
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:2196
bool isAnyPointerType() const
Definition: Type.h:8011
TypeClass getTypeClass() const
Definition: Type.h:2334
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2360
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isNullPtrType() const
Definition: Type.h:8352
bool isRecordType() const
Definition: Type.h:8103
bool isObjCRetainableType() const
Definition: Type.cpp:4950
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
bool isUnionType() const
Definition: Type.cpp:671
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2479
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition: Type.cpp:2536
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2578
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Expr * getSubExpr() const
Definition: Expr.h:2233
Opcode getOpcode() const
Definition: Expr.h:2228
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2310
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
Represents a GCC generic vector type.
Definition: Type.h:4021
unsigned getNumElements() const
Definition: Type.h:4036
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2594
MatchKind
How well a given conversion specifier matches its argument.
Definition: FormatString.h:271
@ NoMatch
The conversion specifier and the argument types are incompatible.
Definition: FormatString.h:274
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
Definition: FormatString.h:286
@ Match
The conversion specifier and the argument type are compatible.
Definition: FormatString.h:277
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
Definition: FormatString.h:288
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
Definition: FormatString.h:34
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:161
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition: larchintrin.h:181
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)
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
ComparisonResult
Indicates the result of a tentative comparison.
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
@ 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:1112
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1090
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1104
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1131
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2052
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1059
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1119
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ CPlusPlus
Definition: LangStandard.h:56
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition: IgnoreExpr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ NonNull
Values of this type can never be null.
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:34
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
BinaryOperatorKind
@ SC_Register
Definition: Specifiers.h:257
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition: SemaARM.cpp:548
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
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())
const FunctionProtoType * T
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition: IgnoreExpr.h:137
StringLiteralKind
Definition: Expr.h:1749
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Success
Template argument deduction was successful.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_Win64
Definition: Specifiers.h:285
@ CC_C
Definition: Specifiers.h:279
@ CC_X86_64SysV
Definition: Specifiers.h:286
@ Generic
not a target-specific vector type
U cast(CodeGen::Address addr)
Definition: Address.h:325
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
long int64_t
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
Extra information about a function prototype.
Definition: Type.h:5087
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
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.
Definition: PrettyPrinter.h:93
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12673
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12790
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition: Sema.h:12816
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition: Sema.h:12806
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12771
FormatArgumentPassingKind ArgPassingKind
Definition: Sema.h:2201
#define log2(__x)
Definition: tgmath.h:970