clang 22.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeLoc.h"
46#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"
68#include "clang/Sema/SemaHLSL.h"
71#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaWasm.h"
80#include "clang/Sema/SemaX86.h"
81#include "llvm/ADT/APFloat.h"
82#include "llvm/ADT/APInt.h"
83#include "llvm/ADT/APSInt.h"
84#include "llvm/ADT/ArrayRef.h"
85#include "llvm/ADT/DenseMap.h"
86#include "llvm/ADT/FoldingSet.h"
87#include "llvm/ADT/STLExtras.h"
88#include "llvm/ADT/STLForwardCompat.h"
89#include "llvm/ADT/SmallBitVector.h"
90#include "llvm/ADT/SmallPtrSet.h"
91#include "llvm/ADT/SmallString.h"
92#include "llvm/ADT/SmallVector.h"
93#include "llvm/ADT/StringExtras.h"
94#include "llvm/ADT/StringRef.h"
95#include "llvm/ADT/StringSet.h"
96#include "llvm/ADT/StringSwitch.h"
97#include "llvm/Support/AtomicOrdering.h"
98#include "llvm/Support/Compiler.h"
99#include "llvm/Support/ConvertUTF.h"
100#include "llvm/Support/ErrorHandling.h"
101#include "llvm/Support/Format.h"
102#include "llvm/Support/Locale.h"
103#include "llvm/Support/MathExtras.h"
104#include "llvm/Support/SaveAndRestore.h"
105#include "llvm/Support/raw_ostream.h"
106#include "llvm/TargetParser/RISCVTargetParser.h"
107#include "llvm/TargetParser/Triple.h"
108#include <algorithm>
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,
126 Context.getTargetInfo());
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 << Range;
175}
176
178 bool HasError = false;
179
180 for (const Expr *Arg : Call->arguments()) {
181 if (Arg->isValueDependent())
182 continue;
183
184 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
185 int DiagMsgKind = -1;
186 // Arguments must be pointers to constant strings and cannot use '$'.
187 if (!ArgString.has_value())
188 DiagMsgKind = 0;
189 else if (ArgString->find('$') != std::string::npos)
190 DiagMsgKind = 1;
191
192 if (DiagMsgKind >= 0) {
193 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
194 << DiagMsgKind << Arg->getSourceRange();
195 HasError = true;
196 }
197 }
198
199 return !HasError;
200}
201
203 if (Value->isTypeDependent())
204 return false;
205
206 InitializedEntity Entity =
208 ExprResult Result =
210 if (Result.isInvalid())
211 return true;
212 Value = Result.get();
213 return false;
214}
215
216/// Check that the first argument to __builtin_annotation is an integer
217/// and the second argument is a non-wide string literal.
218static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
219 if (S.checkArgCount(TheCall, 2))
220 return true;
221
222 // First argument should be an integer.
223 Expr *ValArg = TheCall->getArg(0);
224 QualType Ty = ValArg->getType();
225 if (!Ty->isIntegerType()) {
226 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
227 << ValArg->getSourceRange();
228 return true;
229 }
230
231 // Second argument should be a constant string.
232 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
233 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
234 if (!Literal || !Literal->isOrdinary()) {
235 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
236 << StrArg->getSourceRange();
237 return true;
238 }
239
240 TheCall->setType(Ty);
241 return false;
242}
243
244static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
245 // We need at least one argument.
246 if (TheCall->getNumArgs() < 1) {
247 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
248 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
249 << TheCall->getCallee()->getSourceRange();
250 return true;
251 }
252
253 // All arguments should be wide string literals.
254 for (Expr *Arg : TheCall->arguments()) {
255 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
256 if (!Literal || !Literal->isWide()) {
257 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
258 << Arg->getSourceRange();
259 return true;
260 }
261 }
262
263 return false;
264}
265
266/// Check that the argument to __builtin_addressof is a glvalue, and set the
267/// result type to the corresponding pointer type.
268static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
269 if (S.checkArgCount(TheCall, 1))
270 return true;
271
272 ExprResult Arg(TheCall->getArg(0));
273 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
274 if (ResultType.isNull())
275 return true;
276
277 TheCall->setArg(0, Arg.get());
278 TheCall->setType(ResultType);
279 return false;
280}
281
282/// Check that the argument to __builtin_function_start is a function.
283static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
284 if (S.checkArgCount(TheCall, 1))
285 return true;
286
287 if (TheCall->getArg(0)->containsErrors())
288 return true;
289
291 if (Arg.isInvalid())
292 return true;
293
294 TheCall->setArg(0, Arg.get());
295 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
297
298 if (!FD) {
299 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
300 << TheCall->getSourceRange();
301 return true;
302 }
303
304 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
305 TheCall->getBeginLoc());
306}
307
308/// Check the number of arguments and set the result type to
309/// the argument type.
310static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
311 if (S.checkArgCount(TheCall, 1))
312 return true;
313
314 TheCall->setType(TheCall->getArg(0)->getType());
315 return false;
316}
317
318/// Check that the value argument for __builtin_is_aligned(value, alignment) and
319/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
320/// type (but not a function pointer) and that the alignment is a power-of-two.
321static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
322 if (S.checkArgCount(TheCall, 2))
323 return true;
324
325 clang::Expr *Source = TheCall->getArg(0);
326 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
327
328 auto IsValidIntegerType = [](QualType Ty) {
329 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
330 };
331 QualType SrcTy = Source->getType();
332 // We should also be able to use it with arrays (but not functions!).
333 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
334 SrcTy = S.Context.getDecayedType(SrcTy);
335 }
336 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
337 SrcTy->isFunctionPointerType()) {
338 // FIXME: this is not quite the right error message since we don't allow
339 // floating point types, or member pointers.
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 return true;
343 }
344
345 clang::Expr *AlignOp = TheCall->getArg(1);
346 if (!IsValidIntegerType(AlignOp->getType())) {
347 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
348 << AlignOp->getType();
349 return true;
350 }
351 Expr::EvalResult AlignResult;
352 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
353 // We can't check validity of alignment if it is value dependent.
354 if (!AlignOp->isValueDependent() &&
355 AlignOp->EvaluateAsInt(AlignResult, S.Context,
357 llvm::APSInt AlignValue = AlignResult.Val.getInt();
358 llvm::APSInt MaxValue(
359 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
360 if (AlignValue < 1) {
361 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
362 return true;
363 }
364 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
365 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
366 << toString(MaxValue, 10);
367 return true;
368 }
369 if (!AlignValue.isPowerOf2()) {
370 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
371 return true;
372 }
373 if (AlignValue == 1) {
374 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
375 << IsBooleanAlignBuiltin;
376 }
377 }
378
381 SourceLocation(), Source);
382 if (SrcArg.isInvalid())
383 return true;
384 TheCall->setArg(0, SrcArg.get());
385 ExprResult AlignArg =
387 S.Context, AlignOp->getType(), false),
388 SourceLocation(), AlignOp);
389 if (AlignArg.isInvalid())
390 return true;
391 TheCall->setArg(1, AlignArg.get());
392 // For align_up/align_down, the return type is the same as the (potentially
393 // decayed) argument type including qualifiers. For is_aligned(), the result
394 // is always bool.
395 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
396 return false;
397}
398
399static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
400 if (S.checkArgCount(TheCall, 3))
401 return true;
402
403 std::pair<unsigned, const char *> Builtins[] = {
404 { Builtin::BI__builtin_add_overflow, "ckd_add" },
405 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
406 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
407 };
408
409 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
410 const char *> &P) {
411 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
413 S.getSourceManager(), S.getLangOpts()) == P.second;
414 });
415
416 auto ValidCkdIntType = [](QualType QT) {
417 // A valid checked integer type is an integer type other than a plain char,
418 // bool, a bit-precise type, or an enumeration type.
419 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
420 return (BT->getKind() >= BuiltinType::Short &&
421 BT->getKind() <= BuiltinType::Int128) || (
422 BT->getKind() >= BuiltinType::UShort &&
423 BT->getKind() <= BuiltinType::UInt128) ||
424 BT->getKind() == BuiltinType::UChar ||
425 BT->getKind() == BuiltinType::SChar;
426 return false;
427 };
428
429 // First two arguments should be integers.
430 for (unsigned I = 0; I < 2; ++I) {
432 if (Arg.isInvalid()) return true;
433 TheCall->setArg(I, Arg.get());
434
435 QualType Ty = Arg.get()->getType();
436 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
437 if (!IsValid) {
438 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
439 << CkdOperation << Ty << Arg.get()->getSourceRange();
440 return true;
441 }
442 }
443
444 // Third argument should be a pointer to a non-const integer.
445 // IRGen correctly handles volatile, restrict, and address spaces, and
446 // the other qualifiers aren't possible.
447 {
449 if (Arg.isInvalid()) return true;
450 TheCall->setArg(2, Arg.get());
451
452 QualType Ty = Arg.get()->getType();
453 const auto *PtrTy = Ty->getAs<PointerType>();
454 if (!PtrTy ||
455 !PtrTy->getPointeeType()->isIntegerType() ||
456 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
457 PtrTy->getPointeeType().isConstQualified()) {
458 S.Diag(Arg.get()->getBeginLoc(),
459 diag::err_overflow_builtin_must_be_ptr_int)
460 << CkdOperation << Ty << Arg.get()->getSourceRange();
461 return true;
462 }
463 }
464
465 // Disallow signed bit-precise integer args larger than 128 bits to mul
466 // function until we improve backend support.
467 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
468 for (unsigned I = 0; I < 3; ++I) {
469 const auto Arg = TheCall->getArg(I);
470 // Third argument will be a pointer.
471 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
472 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
473 S.getASTContext().getIntWidth(Ty) > 128)
474 return S.Diag(Arg->getBeginLoc(),
475 diag::err_overflow_builtin_bit_int_max_size)
476 << 128;
477 }
478 }
479
480 return false;
481}
482
483namespace {
484struct BuiltinDumpStructGenerator {
485 Sema &S;
486 CallExpr *TheCall;
487 SourceLocation Loc = TheCall->getBeginLoc();
488 SmallVector<Expr *, 32> Actions;
489 DiagnosticErrorTrap ErrorTracker;
490 PrintingPolicy Policy;
491
492 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
493 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
494 Policy(S.Context.getPrintingPolicy()) {
495 Policy.AnonymousTagLocations = false;
496 }
497
498 Expr *makeOpaqueValueExpr(Expr *Inner) {
499 auto *OVE = new (S.Context)
500 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
501 Inner->getObjectKind(), Inner);
502 Actions.push_back(OVE);
503 return OVE;
504 }
505
506 Expr *getStringLiteral(llvm::StringRef Str) {
508 // Wrap the literal in parentheses to attach a source location.
509 return new (S.Context) ParenExpr(Loc, Loc, Lit);
510 }
511
512 bool callPrintFunction(llvm::StringRef Format,
513 llvm::ArrayRef<Expr *> Exprs = {}) {
514 SmallVector<Expr *, 8> Args;
515 assert(TheCall->getNumArgs() >= 2);
516 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
517 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
518 Args.push_back(getStringLiteral(Format));
519 llvm::append_range(Args, Exprs);
520
521 // Register a note to explain why we're performing the call.
522 Sema::CodeSynthesisContext Ctx;
524 Ctx.PointOfInstantiation = Loc;
525 Ctx.CallArgs = Args.data();
526 Ctx.NumCallArgs = Args.size();
528
529 ExprResult RealCall =
530 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
531 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
532
534 if (!RealCall.isInvalid())
535 Actions.push_back(RealCall.get());
536 // Bail out if we've hit any errors, even if we managed to build the
537 // call. We don't want to produce more than one error.
538 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
539 }
540
541 Expr *getIndentString(unsigned Depth) {
542 if (!Depth)
543 return nullptr;
544
545 llvm::SmallString<32> Indent;
546 Indent.resize(Depth * Policy.Indentation, ' ');
547 return getStringLiteral(Indent);
548 }
549
550 Expr *getTypeString(QualType T) {
551 return getStringLiteral(T.getAsString(Policy));
552 }
553
554 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
555 llvm::raw_svector_ostream OS(Str);
556
557 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
558 // than trying to print a single character.
559 if (auto *BT = T->getAs<BuiltinType>()) {
560 switch (BT->getKind()) {
561 case BuiltinType::Bool:
562 OS << "%d";
563 return true;
564 case BuiltinType::Char_U:
565 case BuiltinType::UChar:
566 OS << "%hhu";
567 return true;
568 case BuiltinType::Char_S:
569 case BuiltinType::SChar:
570 OS << "%hhd";
571 return true;
572 default:
573 break;
574 }
575 }
576
577 analyze_printf::PrintfSpecifier Specifier;
578 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
579 // We were able to guess how to format this.
580 if (Specifier.getConversionSpecifier().getKind() ==
581 analyze_printf::PrintfConversionSpecifier::sArg) {
582 // Wrap double-quotes around a '%s' specifier and limit its maximum
583 // length. Ideally we'd also somehow escape special characters in the
584 // contents but printf doesn't support that.
585 // FIXME: '%s' formatting is not safe in general.
586 OS << '"';
587 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
588 Specifier.toString(OS);
589 OS << '"';
590 // FIXME: It would be nice to include a '...' if the string doesn't fit
591 // in the length limit.
592 } else {
593 Specifier.toString(OS);
594 }
595 return true;
596 }
597
598 if (T->isPointerType()) {
599 // Format all pointers with '%p'.
600 OS << "%p";
601 return true;
602 }
603
604 return false;
605 }
606
607 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
608 Expr *IndentLit = getIndentString(Depth);
609 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
610 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
611 : callPrintFunction("%s", {TypeLit}))
612 return true;
613
614 return dumpRecordValue(RD, E, IndentLit, Depth);
615 }
616
617 // Dump a record value. E should be a pointer or lvalue referring to an RD.
618 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
619 unsigned Depth) {
620 // FIXME: Decide what to do if RD is a union. At least we should probably
621 // turn off printing `const char*` members with `%s`, because that is very
622 // likely to crash if that's not the active member. Whatever we decide, we
623 // should document it.
624
625 // Build an OpaqueValueExpr so we can refer to E more than once without
626 // triggering re-evaluation.
627 Expr *RecordArg = makeOpaqueValueExpr(E);
628 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
629
630 if (callPrintFunction(" {\n"))
631 return true;
632
633 // Dump each base class, regardless of whether they're aggregates.
634 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
635 for (const auto &Base : CXXRD->bases()) {
636 QualType BaseType =
637 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
638 : S.Context.getLValueReferenceType(Base.getType());
640 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
641 RecordArg);
642 if (BasePtr.isInvalid() ||
643 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
644 Depth + 1))
645 return true;
646 }
647 }
648
649 Expr *FieldIndentArg = getIndentString(Depth + 1);
650
651 // Dump each field.
652 for (auto *D : RD->decls()) {
653 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
654 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
655 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
656 continue;
657
658 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
659 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
660 getTypeString(FD->getType()),
661 getStringLiteral(FD->getName())};
662
663 if (FD->isBitField()) {
664 Format += ": %zu ";
665 QualType SizeT = S.Context.getSizeType();
666 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
667 FD->getBitWidthValue());
668 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
669 }
670
671 Format += "=";
672
675 CXXScopeSpec(), Loc, IFD,
676 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
678 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
680 DeclarationNameInfo(FD->getDeclName(), Loc));
681 if (Field.isInvalid())
682 return true;
683
684 auto *InnerRD = FD->getType()->getAsRecordDecl();
685 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
686 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
687 // Recursively print the values of members of aggregate record type.
688 if (callPrintFunction(Format, Args) ||
689 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
690 return true;
691 } else {
692 Format += " ";
693 if (appendFormatSpecifier(FD->getType(), Format)) {
694 // We know how to print this field.
695 Args.push_back(Field.get());
696 } else {
697 // We don't know how to print this field. Print out its address
698 // with a format specifier that a smart tool will be able to
699 // recognize and treat specially.
700 Format += "*%p";
701 ExprResult FieldAddr =
702 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
703 if (FieldAddr.isInvalid())
704 return true;
705 Args.push_back(FieldAddr.get());
706 }
707 Format += "\n";
708 if (callPrintFunction(Format, Args))
709 return true;
710 }
711 }
712
713 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
714 : callPrintFunction("}\n");
715 }
716
717 Expr *buildWrapper() {
718 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
720 TheCall->setType(Wrapper->getType());
721 TheCall->setValueKind(Wrapper->getValueKind());
722 return Wrapper;
723 }
724};
725} // namespace
726
728 if (S.checkArgCountAtLeast(TheCall, 2))
729 return ExprError();
730
731 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
732 if (PtrArgResult.isInvalid())
733 return ExprError();
734 TheCall->setArg(0, PtrArgResult.get());
735
736 // First argument should be a pointer to a struct.
737 QualType PtrArgType = PtrArgResult.get()->getType();
738 if (!PtrArgType->isPointerType() ||
739 !PtrArgType->getPointeeType()->isRecordType()) {
740 S.Diag(PtrArgResult.get()->getBeginLoc(),
741 diag::err_expected_struct_pointer_argument)
742 << 1 << TheCall->getDirectCallee() << PtrArgType;
743 return ExprError();
744 }
745 QualType Pointee = PtrArgType->getPointeeType();
746 const RecordDecl *RD = Pointee->getAsRecordDecl();
747 // Try to instantiate the class template as appropriate; otherwise, access to
748 // its data() may lead to a crash.
749 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
750 diag::err_incomplete_type))
751 return ExprError();
752 // Second argument is a callable, but we can't fully validate it until we try
753 // calling it.
754 QualType FnArgType = TheCall->getArg(1)->getType();
755 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
756 !FnArgType->isBlockPointerType() &&
757 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
758 auto *BT = FnArgType->getAs<BuiltinType>();
759 switch (BT ? BT->getKind() : BuiltinType::Void) {
760 case BuiltinType::Dependent:
761 case BuiltinType::Overload:
762 case BuiltinType::BoundMember:
763 case BuiltinType::PseudoObject:
764 case BuiltinType::UnknownAny:
765 case BuiltinType::BuiltinFn:
766 // This might be a callable.
767 break;
768
769 default:
770 S.Diag(TheCall->getArg(1)->getBeginLoc(),
771 diag::err_expected_callable_argument)
772 << 2 << TheCall->getDirectCallee() << FnArgType;
773 return ExprError();
774 }
775 }
776
777 BuiltinDumpStructGenerator Generator(S, TheCall);
778
779 // Wrap parentheses around the given pointer. This is not necessary for
780 // correct code generation, but it means that when we pretty-print the call
781 // arguments in our diagnostics we will produce '(&s)->n' instead of the
782 // incorrect '&s->n'.
783 Expr *PtrArg = PtrArgResult.get();
784 PtrArg = new (S.Context)
785 ParenExpr(PtrArg->getBeginLoc(),
786 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
787 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
788 return ExprError();
789
790 return Generator.buildWrapper();
791}
792
793static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
794 if (S.checkArgCount(BuiltinCall, 2))
795 return true;
796
797 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
798 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
799 Expr *Call = BuiltinCall->getArg(0);
800 Expr *Chain = BuiltinCall->getArg(1);
801
802 if (Call->getStmtClass() != Stmt::CallExprClass) {
803 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
804 << Call->getSourceRange();
805 return true;
806 }
807
808 auto CE = cast<CallExpr>(Call);
809 if (CE->getCallee()->getType()->isBlockPointerType()) {
810 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
811 << Call->getSourceRange();
812 return true;
813 }
814
815 const Decl *TargetDecl = CE->getCalleeDecl();
816 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
817 if (FD->getBuiltinID()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
824 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
825 << Call->getSourceRange();
826 return true;
827 }
828
829 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
830 if (ChainResult.isInvalid())
831 return true;
832 if (!ChainResult.get()->getType()->isPointerType()) {
833 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
834 << Chain->getSourceRange();
835 return true;
836 }
837
838 QualType ReturnTy = CE->getCallReturnType(S.Context);
839 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
840 QualType BuiltinTy = S.Context.getFunctionType(
841 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
842 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
843
844 Builtin =
845 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
846
847 BuiltinCall->setType(CE->getType());
848 BuiltinCall->setValueKind(CE->getValueKind());
849 BuiltinCall->setObjectKind(CE->getObjectKind());
850 BuiltinCall->setCallee(Builtin);
851 BuiltinCall->setArg(1, ChainResult.get());
852
853 return false;
854}
855
856namespace {
857
858class ScanfDiagnosticFormatHandler
860 // Accepts the argument index (relative to the first destination index) of the
861 // argument whose size we want.
862 using ComputeSizeFunction =
863 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
864
865 // Accepts the argument index (relative to the first destination index), the
866 // destination size, and the source size).
867 using DiagnoseFunction =
868 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
869
870 ComputeSizeFunction ComputeSizeArgument;
871 DiagnoseFunction Diagnose;
872
873public:
874 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
875 DiagnoseFunction Diagnose)
876 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
877
878 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
879 const char *StartSpecifier,
880 unsigned specifierLen) override {
881 if (!FS.consumesDataArgument())
882 return true;
883
884 unsigned NulByte = 0;
885 switch ((FS.getConversionSpecifier().getKind())) {
886 default:
887 return true;
890 NulByte = 1;
891 break;
893 break;
894 }
895
896 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
897 if (FW.getHowSpecified() !=
898 analyze_format_string::OptionalAmount::HowSpecified::Constant)
899 return true;
900
901 unsigned SourceSize = FW.getConstantAmount() + NulByte;
902
903 std::optional<llvm::APSInt> DestSizeAPS =
904 ComputeSizeArgument(FS.getArgIndex());
905 if (!DestSizeAPS)
906 return true;
907
908 unsigned DestSize = DestSizeAPS->getZExtValue();
909
910 if (DestSize < SourceSize)
911 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
912
913 return true;
914 }
915};
916
917class EstimateSizeFormatHandler
919 size_t Size;
920 /// Whether the format string contains Linux kernel's format specifier
921 /// extension.
922 bool IsKernelCompatible = true;
923
924public:
925 EstimateSizeFormatHandler(StringRef Format)
926 : Size(std::min(Format.find(0), Format.size()) +
927 1 /* null byte always written by sprintf */) {}
928
929 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
930 const char *, unsigned SpecifierLen,
931 const TargetInfo &) override {
932
933 const size_t FieldWidth = computeFieldWidth(FS);
934 const size_t Precision = computePrecision(FS);
935
936 // The actual format.
937 switch (FS.getConversionSpecifier().getKind()) {
938 // Just a char.
941 Size += std::max(FieldWidth, (size_t)1);
942 break;
943 // Just an integer.
953 Size += std::max(FieldWidth, Precision);
954 break;
955
956 // %g style conversion switches between %f or %e style dynamically.
957 // %g removes trailing zeros, and does not print decimal point if there are
958 // no digits that follow it. Thus %g can print a single digit.
959 // FIXME: If it is alternative form:
960 // For g and G conversions, trailing zeros are not removed from the result.
963 Size += 1;
964 break;
965
966 // Floating point number in the form '[+]ddd.ddd'.
969 Size += std::max(FieldWidth, 1 /* integer part */ +
970 (Precision ? 1 + Precision
971 : 0) /* period + decimal */);
972 break;
973
974 // Floating point number in the form '[-]d.ddde[+-]dd'.
977 Size +=
978 std::max(FieldWidth,
979 1 /* integer part */ +
980 (Precision ? 1 + Precision : 0) /* period + decimal */ +
981 1 /* e or E letter */ + 2 /* exponent */);
982 break;
983
984 // Floating point number in the form '[-]0xh.hhhhp±dd'.
987 Size +=
988 std::max(FieldWidth,
989 2 /* 0x */ + 1 /* integer part */ +
990 (Precision ? 1 + Precision : 0) /* period + decimal */ +
991 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
992 break;
993
994 // Just a string.
997 Size += FieldWidth;
998 break;
999
1000 // Just a pointer in the form '0xddd'.
1002 // Linux kernel has its own extesion for `%p` specifier.
1003 // Kernel Document:
1004 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1005 IsKernelCompatible = false;
1006 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1007 break;
1008
1009 // A plain percent.
1011 Size += 1;
1012 break;
1013
1014 default:
1015 break;
1016 }
1017
1018 // If field width is specified, the sign/space is already accounted for
1019 // within the field width, so no additional size is needed.
1020 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1021 Size += 1;
1022
1023 if (FS.hasAlternativeForm()) {
1024 switch (FS.getConversionSpecifier().getKind()) {
1025 // For o conversion, it increases the precision, if and only if necessary,
1026 // to force the first digit of the result to be a zero
1027 // (if the value and precision are both 0, a single 0 is printed)
1029 // For b conversion, a nonzero result has 0b prefixed to it.
1031 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1032 // it.
1035 // Note: even when the prefix is added, if
1036 // (prefix_width <= FieldWidth - formatted_length) holds,
1037 // the prefix does not increase the format
1038 // size. e.g.(("%#3x", 0xf) is "0xf")
1039
1040 // If the result is zero, o, b, x, X adds nothing.
1041 break;
1042 // For a, A, e, E, f, F, g, and G conversions,
1043 // the result of converting a floating-point number always contains a
1044 // decimal-point
1053 Size += (Precision ? 0 : 1);
1054 break;
1055 // For other conversions, the behavior is undefined.
1056 default:
1057 break;
1058 }
1059 }
1060 assert(SpecifierLen <= Size && "no underflow");
1061 Size -= SpecifierLen;
1062 return true;
1063 }
1064
1065 size_t getSizeLowerBound() const { return Size; }
1066 bool isKernelCompatible() const { return IsKernelCompatible; }
1067
1068private:
1069 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1070 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1071 size_t FieldWidth = 0;
1073 FieldWidth = FW.getConstantAmount();
1074 return FieldWidth;
1075 }
1076
1077 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1079 size_t Precision = 0;
1080
1081 // See man 3 printf for default precision value based on the specifier.
1082 switch (FW.getHowSpecified()) {
1084 switch (FS.getConversionSpecifier().getKind()) {
1085 default:
1086 break;
1090 Precision = 1;
1091 break;
1098 Precision = 1;
1099 break;
1106 Precision = 6;
1107 break;
1109 Precision = 1;
1110 break;
1111 }
1112 break;
1114 Precision = FW.getConstantAmount();
1115 break;
1116 default:
1117 break;
1118 }
1119 return Precision;
1120 }
1121};
1122
1123} // namespace
1124
1125static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1126 StringRef &FormatStrRef, size_t &StrLen,
1127 ASTContext &Context) {
1128 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1129 Format && (Format->isOrdinary() || Format->isUTF8())) {
1130 FormatStrRef = Format->getString();
1131 const ConstantArrayType *T =
1132 Context.getAsConstantArrayType(Format->getType());
1133 assert(T && "String literal not of constant array type!");
1134 size_t TypeSize = T->getZExtSize();
1135 // In case there's a null byte somewhere.
1136 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1137 return true;
1138 }
1139 return false;
1140}
1141
1142void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1143 CallExpr *TheCall) {
1144 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1146 return;
1147
1148 bool UseDABAttr = false;
1149 const FunctionDecl *UseDecl = FD;
1150
1151 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1152 if (DABAttr) {
1153 UseDecl = DABAttr->getFunction();
1154 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1155 UseDABAttr = true;
1156 }
1157
1158 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1159
1160 if (!BuiltinID)
1161 return;
1162
1163 const TargetInfo &TI = getASTContext().getTargetInfo();
1164 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1165
1166 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1167 // If we refer to a diagnose_as_builtin attribute, we need to change the
1168 // argument index to refer to the arguments of the called function. Unless
1169 // the index is out of bounds, which presumably means it's a variadic
1170 // function.
1171 if (!UseDABAttr)
1172 return Index;
1173 unsigned DABIndices = DABAttr->argIndices_size();
1174 unsigned NewIndex = Index < DABIndices
1175 ? DABAttr->argIndices_begin()[Index]
1176 : Index - DABIndices + FD->getNumParams();
1177 if (NewIndex >= TheCall->getNumArgs())
1178 return std::nullopt;
1179 return NewIndex;
1180 };
1181
1182 auto ComputeExplicitObjectSizeArgument =
1183 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1184 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1185 if (!IndexOptional)
1186 return std::nullopt;
1187 unsigned NewIndex = *IndexOptional;
1188 Expr::EvalResult Result;
1189 Expr *SizeArg = TheCall->getArg(NewIndex);
1190 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1191 return std::nullopt;
1192 llvm::APSInt Integer = Result.Val.getInt();
1193 Integer.setIsUnsigned(true);
1194 return Integer;
1195 };
1196
1197 auto ComputeSizeArgument =
1198 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1199 // If the parameter has a pass_object_size attribute, then we should use its
1200 // (potentially) more strict checking mode. Otherwise, conservatively assume
1201 // type 0.
1202 int BOSType = 0;
1203 // This check can fail for variadic functions.
1204 if (Index < FD->getNumParams()) {
1205 if (const auto *POS =
1206 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1207 BOSType = POS->getType();
1208 }
1209
1210 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1211 if (!IndexOptional)
1212 return std::nullopt;
1213 unsigned NewIndex = *IndexOptional;
1214
1215 if (NewIndex >= TheCall->getNumArgs())
1216 return std::nullopt;
1217
1218 const Expr *ObjArg = TheCall->getArg(NewIndex);
1220 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1221 return std::nullopt;
1222
1223 // Get the object size in the target's size_t width.
1224 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1225 };
1226
1227 auto ComputeStrLenArgument =
1228 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1229 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1230 if (!IndexOptional)
1231 return std::nullopt;
1232 unsigned NewIndex = *IndexOptional;
1233
1234 const Expr *ObjArg = TheCall->getArg(NewIndex);
1236 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1237 return std::nullopt;
1238 // Add 1 for null byte.
1239 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1240 };
1241
1242 std::optional<llvm::APSInt> SourceSize;
1243 std::optional<llvm::APSInt> DestinationSize;
1244 unsigned DiagID = 0;
1245 bool IsChkVariant = false;
1246
1247 auto GetFunctionName = [&]() {
1248 std::string FunctionNameStr =
1249 getASTContext().BuiltinInfo.getName(BuiltinID);
1250 llvm::StringRef FunctionName = FunctionNameStr;
1251 // Skim off the details of whichever builtin was called to produce a better
1252 // diagnostic, as it's unlikely that the user wrote the __builtin
1253 // explicitly.
1254 if (IsChkVariant) {
1255 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1256 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1257 } else {
1258 FunctionName.consume_front("__builtin_");
1259 }
1260 return FunctionName.str();
1261 };
1262
1263 switch (BuiltinID) {
1264 default:
1265 return;
1266 case Builtin::BI__builtin_stpcpy:
1267 case Builtin::BIstpcpy:
1268 case Builtin::BI__builtin_strcpy:
1269 case Builtin::BIstrcpy: {
1270 DiagID = diag::warn_fortify_strlen_overflow;
1271 SourceSize = ComputeStrLenArgument(1);
1272 DestinationSize = ComputeSizeArgument(0);
1273 break;
1274 }
1275
1276 case Builtin::BI__builtin___stpcpy_chk:
1277 case Builtin::BI__builtin___strcpy_chk: {
1278 DiagID = diag::warn_fortify_strlen_overflow;
1279 SourceSize = ComputeStrLenArgument(1);
1280 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1281 IsChkVariant = true;
1282 break;
1283 }
1284
1285 case Builtin::BIscanf:
1286 case Builtin::BIfscanf:
1287 case Builtin::BIsscanf: {
1288 unsigned FormatIndex = 1;
1289 unsigned DataIndex = 2;
1290 if (BuiltinID == Builtin::BIscanf) {
1291 FormatIndex = 0;
1292 DataIndex = 1;
1293 }
1294
1295 const auto *FormatExpr =
1296 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1297
1298 StringRef FormatStrRef;
1299 size_t StrLen;
1300 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1301 return;
1302
1303 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1304 unsigned SourceSize) {
1305 DiagID = diag::warn_fortify_scanf_overflow;
1306 unsigned Index = ArgIndex + DataIndex;
1307 std::string FunctionName = GetFunctionName();
1308 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1309 PDiag(DiagID) << FunctionName << (Index + 1)
1310 << DestSize << SourceSize);
1311 };
1312
1313 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1314 return ComputeSizeArgument(Index + DataIndex);
1315 };
1316 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1317 const char *FormatBytes = FormatStrRef.data();
1319 FormatBytes + StrLen, getLangOpts(),
1320 Context.getTargetInfo());
1321
1322 // Unlike the other cases, in this one we have already issued the diagnostic
1323 // here, so no need to continue (because unlike the other cases, here the
1324 // diagnostic refers to the argument number).
1325 return;
1326 }
1327
1328 case Builtin::BIsprintf:
1329 case Builtin::BI__builtin___sprintf_chk: {
1330 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1331 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1332
1333 StringRef FormatStrRef;
1334 size_t StrLen;
1335 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1336 EstimateSizeFormatHandler H(FormatStrRef);
1337 const char *FormatBytes = FormatStrRef.data();
1339 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1340 Context.getTargetInfo(), false)) {
1341 DiagID = H.isKernelCompatible()
1342 ? diag::warn_format_overflow
1343 : diag::warn_format_overflow_non_kprintf;
1344 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1345 .extOrTrunc(SizeTypeWidth);
1346 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1347 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1348 IsChkVariant = true;
1349 } else {
1350 DestinationSize = ComputeSizeArgument(0);
1351 }
1352 break;
1353 }
1354 }
1355 return;
1356 }
1357 case Builtin::BI__builtin___memcpy_chk:
1358 case Builtin::BI__builtin___memmove_chk:
1359 case Builtin::BI__builtin___memset_chk:
1360 case Builtin::BI__builtin___strlcat_chk:
1361 case Builtin::BI__builtin___strlcpy_chk:
1362 case Builtin::BI__builtin___strncat_chk:
1363 case Builtin::BI__builtin___strncpy_chk:
1364 case Builtin::BI__builtin___stpncpy_chk:
1365 case Builtin::BI__builtin___memccpy_chk:
1366 case Builtin::BI__builtin___mempcpy_chk: {
1367 DiagID = diag::warn_builtin_chk_overflow;
1368 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1369 DestinationSize =
1370 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1371 IsChkVariant = true;
1372 break;
1373 }
1374
1375 case Builtin::BI__builtin___snprintf_chk:
1376 case Builtin::BI__builtin___vsnprintf_chk: {
1377 DiagID = diag::warn_builtin_chk_overflow;
1378 SourceSize = ComputeExplicitObjectSizeArgument(1);
1379 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1380 IsChkVariant = true;
1381 break;
1382 }
1383
1384 case Builtin::BIstrncat:
1385 case Builtin::BI__builtin_strncat:
1386 case Builtin::BIstrncpy:
1387 case Builtin::BI__builtin_strncpy:
1388 case Builtin::BIstpncpy:
1389 case Builtin::BI__builtin_stpncpy: {
1390 // Whether these functions overflow depends on the runtime strlen of the
1391 // string, not just the buffer size, so emitting the "always overflow"
1392 // diagnostic isn't quite right. We should still diagnose passing a buffer
1393 // size larger than the destination buffer though; this is a runtime abort
1394 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1395 DiagID = diag::warn_fortify_source_size_mismatch;
1396 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1397 DestinationSize = ComputeSizeArgument(0);
1398 break;
1399 }
1400
1401 case Builtin::BImemcpy:
1402 case Builtin::BI__builtin_memcpy:
1403 case Builtin::BImemmove:
1404 case Builtin::BI__builtin_memmove:
1405 case Builtin::BImemset:
1406 case Builtin::BI__builtin_memset:
1407 case Builtin::BImempcpy:
1408 case Builtin::BI__builtin_mempcpy: {
1409 DiagID = diag::warn_fortify_source_overflow;
1410 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1411 DestinationSize = ComputeSizeArgument(0);
1412 break;
1413 }
1414 case Builtin::BIsnprintf:
1415 case Builtin::BI__builtin_snprintf:
1416 case Builtin::BIvsnprintf:
1417 case Builtin::BI__builtin_vsnprintf: {
1418 DiagID = diag::warn_fortify_source_size_mismatch;
1419 SourceSize = ComputeExplicitObjectSizeArgument(1);
1420 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1421 StringRef FormatStrRef;
1422 size_t StrLen;
1423 if (SourceSize &&
1424 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1425 EstimateSizeFormatHandler H(FormatStrRef);
1426 const char *FormatBytes = FormatStrRef.data();
1428 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1429 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1430 llvm::APSInt FormatSize =
1431 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1432 .extOrTrunc(SizeTypeWidth);
1433 if (FormatSize > *SourceSize && *SourceSize != 0) {
1434 unsigned TruncationDiagID =
1435 H.isKernelCompatible() ? diag::warn_format_truncation
1436 : diag::warn_format_truncation_non_kprintf;
1437 SmallString<16> SpecifiedSizeStr;
1438 SmallString<16> FormatSizeStr;
1439 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1440 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1441 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1442 PDiag(TruncationDiagID)
1443 << GetFunctionName() << SpecifiedSizeStr
1444 << FormatSizeStr);
1445 }
1446 }
1447 }
1448 DestinationSize = ComputeSizeArgument(0);
1449 }
1450 }
1451
1452 if (!SourceSize || !DestinationSize ||
1453 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1454 return;
1455
1456 std::string FunctionName = GetFunctionName();
1457
1458 SmallString<16> DestinationStr;
1459 SmallString<16> SourceStr;
1460 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1461 SourceSize->toString(SourceStr, /*Radix=*/10);
1462 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1463 PDiag(DiagID)
1464 << FunctionName << DestinationStr << SourceStr);
1465}
1466
1467static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1468 Scope::ScopeFlags NeededScopeFlags,
1469 unsigned DiagID) {
1470 // Scopes aren't available during instantiation. Fortunately, builtin
1471 // functions cannot be template args so they cannot be formed through template
1472 // instantiation. Therefore checking once during the parse is sufficient.
1473 if (SemaRef.inTemplateInstantiation())
1474 return false;
1475
1476 Scope *S = SemaRef.getCurScope();
1477 while (S && !S->isSEHExceptScope())
1478 S = S->getParent();
1479 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1480 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1481 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1482 << DRE->getDecl()->getIdentifier();
1483 return true;
1484 }
1485
1486 return false;
1487}
1488
1489// In OpenCL, __builtin_alloca_* should return a pointer to address space
1490// that corresponds to the stack address space i.e private address space.
1491static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1492 QualType RT = TheCall->getType();
1493 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1494 "__builtin_alloca has invalid address space");
1495
1496 RT = RT->getPointeeType();
1498 TheCall->setType(S.Context.getPointerType(RT));
1499}
1500
1501static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1502 if (S.checkArgCountAtLeast(TheCall, 1))
1503 return true;
1504
1505 for (Expr *Arg : TheCall->arguments()) {
1506 // If argument is dependent on a template parameter, we can't resolve now.
1507 if (Arg->isTypeDependent() || Arg->isValueDependent())
1508 continue;
1509 // Reject void types.
1510 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1511 if (ArgTy->isVoidType())
1512 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1513 }
1514
1516 return false;
1517}
1518
1519namespace {
1520enum PointerAuthOpKind {
1521 PAO_Strip,
1522 PAO_Sign,
1523 PAO_Auth,
1524 PAO_SignGeneric,
1525 PAO_Discriminator,
1526 PAO_BlendPointer,
1527 PAO_BlendInteger
1528};
1529}
1530
1532 if (getLangOpts().PointerAuthIntrinsics)
1533 return false;
1534
1535 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1536 return true;
1537}
1538
1539static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1541}
1542
1543static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1544 // Convert it to type 'int'.
1545 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1546 return true;
1547
1548 // Value-dependent expressions are okay; wait for template instantiation.
1549 if (Arg->isValueDependent())
1550 return false;
1551
1552 unsigned KeyValue;
1553 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1554}
1555
1557 // Attempt to constant-evaluate the expression.
1558 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1559 if (!KeyValue) {
1560 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1561 << 0 << Arg->getSourceRange();
1562 return true;
1563 }
1564
1565 // Ask the target to validate the key parameter.
1566 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1568 {
1569 llvm::raw_svector_ostream Str(Value);
1570 Str << *KeyValue;
1571 }
1572
1573 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1574 << Value << Arg->getSourceRange();
1575 return true;
1576 }
1577
1578 Result = KeyValue->getZExtValue();
1579 return false;
1580}
1581
1584 unsigned &IntVal) {
1585 if (!Arg) {
1586 IntVal = 0;
1587 return true;
1588 }
1589
1590 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1591 if (!Result) {
1592 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1593 return false;
1594 }
1595
1596 unsigned Max;
1597 bool IsAddrDiscArg = false;
1598
1599 switch (Kind) {
1601 Max = 1;
1602 IsAddrDiscArg = true;
1603 break;
1606 break;
1607 };
1608
1610 if (IsAddrDiscArg)
1611 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1612 << Result->getExtValue();
1613 else
1614 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1615 << Result->getExtValue() << Max;
1616
1617 return false;
1618 };
1619
1620 IntVal = Result->getZExtValue();
1621 return true;
1622}
1623
1624static std::pair<const ValueDecl *, CharUnits>
1626 // Must evaluate as a pointer.
1627 Expr::EvalResult Result;
1628 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1629 return {nullptr, CharUnits()};
1630
1631 const auto *BaseDecl =
1632 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1633 if (!BaseDecl)
1634 return {nullptr, CharUnits()};
1635
1636 return {BaseDecl, Result.Val.getLValueOffset()};
1637}
1638
1639static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1640 bool RequireConstant = false) {
1641 if (Arg->hasPlaceholderType()) {
1643 if (R.isInvalid())
1644 return true;
1645 Arg = R.get();
1646 }
1647
1648 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1649 return OpKind != PAO_BlendInteger;
1650 };
1651 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1652 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1653 OpKind == PAO_SignGeneric;
1654 };
1655
1656 // Require the value to have the right range of type.
1657 QualType ExpectedTy;
1658 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1659 ExpectedTy = Arg->getType().getUnqualifiedType();
1660 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1661 ExpectedTy = S.Context.VoidPtrTy;
1662 } else if (AllowsInteger(OpKind) &&
1664 ExpectedTy = S.Context.getUIntPtrType();
1665
1666 } else {
1667 // Diagnose the failures.
1668 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1669 << unsigned(OpKind == PAO_Discriminator ? 1
1670 : OpKind == PAO_BlendPointer ? 2
1671 : OpKind == PAO_BlendInteger ? 3
1672 : 0)
1673 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1674 << Arg->getType() << Arg->getSourceRange();
1675 return true;
1676 }
1677
1678 // Convert to that type. This should just be an lvalue-to-rvalue
1679 // conversion.
1680 if (convertArgumentToType(S, Arg, ExpectedTy))
1681 return true;
1682
1683 if (!RequireConstant) {
1684 // Warn about null pointers for non-generic sign and auth operations.
1685 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1687 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1688 ? diag::warn_ptrauth_sign_null_pointer
1689 : diag::warn_ptrauth_auth_null_pointer)
1690 << Arg->getSourceRange();
1691 }
1692
1693 return false;
1694 }
1695
1696 // Perform special checking on the arguments to ptrauth_sign_constant.
1697
1698 // The main argument.
1699 if (OpKind == PAO_Sign) {
1700 // Require the value we're signing to have a special form.
1701 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1702 bool Invalid;
1703
1704 // Must be rooted in a declaration reference.
1705 if (!BaseDecl)
1706 Invalid = true;
1707
1708 // If it's a function declaration, we can't have an offset.
1709 else if (isa<FunctionDecl>(BaseDecl))
1710 Invalid = !Offset.isZero();
1711
1712 // Otherwise we're fine.
1713 else
1714 Invalid = false;
1715
1716 if (Invalid)
1717 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1718 return Invalid;
1719 }
1720
1721 // The discriminator argument.
1722 assert(OpKind == PAO_Discriminator);
1723
1724 // Must be a pointer or integer or blend thereof.
1725 Expr *Pointer = nullptr;
1726 Expr *Integer = nullptr;
1727 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1728 if (Call->getBuiltinCallee() ==
1729 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1730 Pointer = Call->getArg(0);
1731 Integer = Call->getArg(1);
1732 }
1733 }
1734 if (!Pointer && !Integer) {
1735 if (Arg->getType()->isPointerType())
1736 Pointer = Arg;
1737 else
1738 Integer = Arg;
1739 }
1740
1741 // Check the pointer.
1742 bool Invalid = false;
1743 if (Pointer) {
1744 assert(Pointer->getType()->isPointerType());
1745
1746 // TODO: if we're initializing a global, check that the address is
1747 // somehow related to what we're initializing. This probably will
1748 // never really be feasible and we'll have to catch it at link-time.
1749 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1750 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1751 Invalid = true;
1752 }
1753
1754 // Check the integer.
1755 if (Integer) {
1756 assert(Integer->getType()->isIntegerType());
1757 if (!Integer->isEvaluatable(S.Context))
1758 Invalid = true;
1759 }
1760
1761 if (Invalid)
1762 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1763 return Invalid;
1764}
1765
1767 if (S.checkArgCount(Call, 2))
1768 return ExprError();
1770 return ExprError();
1771 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1772 checkPointerAuthKey(S, Call->getArgs()[1]))
1773 return ExprError();
1774
1775 Call->setType(Call->getArgs()[0]->getType());
1776 return Call;
1777}
1778
1780 if (S.checkArgCount(Call, 2))
1781 return ExprError();
1783 return ExprError();
1784 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1785 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1786 return ExprError();
1787
1788 Call->setType(S.Context.getUIntPtrType());
1789 return Call;
1790}
1791
1793 if (S.checkArgCount(Call, 2))
1794 return ExprError();
1796 return ExprError();
1797 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1798 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1799 return ExprError();
1800
1801 Call->setType(S.Context.getUIntPtrType());
1802 return Call;
1803}
1804
1806 PointerAuthOpKind OpKind,
1807 bool RequireConstant) {
1808 if (S.checkArgCount(Call, 3))
1809 return ExprError();
1811 return ExprError();
1812 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1813 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1814 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1815 RequireConstant))
1816 return ExprError();
1817
1818 Call->setType(Call->getArgs()[0]->getType());
1819 return Call;
1820}
1821
1823 if (S.checkArgCount(Call, 5))
1824 return ExprError();
1826 return ExprError();
1827 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1828 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1829 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1830 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1831 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1832 return ExprError();
1833
1834 Call->setType(Call->getArgs()[0]->getType());
1835 return Call;
1836}
1837
1840 return ExprError();
1841
1842 // We've already performed normal call type-checking.
1843 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1844
1845 // Operand must be an ordinary or UTF-8 string literal.
1846 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1847 if (!Literal || Literal->getCharByteWidth() != 1) {
1848 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1849 << (Literal ? 1 : 0) << Arg->getSourceRange();
1850 return ExprError();
1851 }
1852
1853 return Call;
1854}
1855
1857 if (S.checkArgCount(Call, 1))
1858 return ExprError();
1859 Expr *FirstArg = Call->getArg(0);
1860 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1861 if (FirstValue.isInvalid())
1862 return ExprError();
1863 Call->setArg(0, FirstValue.get());
1864 QualType FirstArgType = FirstArg->getType();
1865 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1866 FirstArgType = S.Context.getDecayedType(FirstArgType);
1867
1868 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1869 if (!FirstArgRecord) {
1870 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1871 << /*isPolymorphic=*/0 << FirstArgType;
1872 return ExprError();
1873 }
1874 if (S.RequireCompleteType(
1875 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1876 diag::err_get_vtable_pointer_requires_complete_type)) {
1877 return ExprError();
1878 }
1879
1880 if (!FirstArgRecord->isPolymorphic()) {
1881 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1882 << /*isPolymorphic=*/1 << FirstArgRecord;
1883 return ExprError();
1884 }
1886 Call->setType(ReturnType);
1887 return Call;
1888}
1889
1891 if (S.checkArgCount(TheCall, 1))
1892 return ExprError();
1893
1894 // Compute __builtin_launder's parameter type from the argument.
1895 // The parameter type is:
1896 // * The type of the argument if it's not an array or function type,
1897 // Otherwise,
1898 // * The decayed argument type.
1899 QualType ParamTy = [&]() {
1900 QualType ArgTy = TheCall->getArg(0)->getType();
1901 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1902 return S.Context.getPointerType(Ty->getElementType());
1903 if (ArgTy->isFunctionType()) {
1904 return S.Context.getPointerType(ArgTy);
1905 }
1906 return ArgTy;
1907 }();
1908
1909 TheCall->setType(ParamTy);
1910
1911 auto DiagSelect = [&]() -> std::optional<unsigned> {
1912 if (!ParamTy->isPointerType())
1913 return 0;
1914 if (ParamTy->isFunctionPointerType())
1915 return 1;
1916 if (ParamTy->isVoidPointerType())
1917 return 2;
1918 return std::optional<unsigned>{};
1919 }();
1920 if (DiagSelect) {
1921 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1922 << *DiagSelect << TheCall->getSourceRange();
1923 return ExprError();
1924 }
1925
1926 // We either have an incomplete class type, or we have a class template
1927 // whose instantiation has not been forced. Example:
1928 //
1929 // template <class T> struct Foo { T value; };
1930 // Foo<int> *p = nullptr;
1931 // auto *d = __builtin_launder(p);
1932 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1933 diag::err_incomplete_type))
1934 return ExprError();
1935
1936 assert(ParamTy->getPointeeType()->isObjectType() &&
1937 "Unhandled non-object pointer case");
1938
1939 InitializedEntity Entity =
1941 ExprResult Arg =
1942 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1943 if (Arg.isInvalid())
1944 return ExprError();
1945 TheCall->setArg(0, Arg.get());
1946
1947 return TheCall;
1948}
1949
1951 if (S.checkArgCount(TheCall, 1))
1952 return ExprError();
1953
1955 if (Arg.isInvalid())
1956 return ExprError();
1957 QualType ParamTy = Arg.get()->getType();
1958 TheCall->setArg(0, Arg.get());
1959 TheCall->setType(S.Context.BoolTy);
1960
1961 // Only accept pointers to objects as arguments, which should have object
1962 // pointer or void pointer types.
1963 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1964 // LWG4138: Function pointer types not allowed
1965 if (PT->getPointeeType()->isFunctionType()) {
1966 S.Diag(TheCall->getArg(0)->getExprLoc(),
1967 diag::err_builtin_is_within_lifetime_invalid_arg)
1968 << 1;
1969 return ExprError();
1970 }
1971 // Disallow VLAs too since those shouldn't be able to
1972 // be a template parameter for `std::is_within_lifetime`
1973 if (PT->getPointeeType()->isVariableArrayType()) {
1974 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1975 << 1 << "__builtin_is_within_lifetime";
1976 return ExprError();
1977 }
1978 } else {
1979 S.Diag(TheCall->getArg(0)->getExprLoc(),
1980 diag::err_builtin_is_within_lifetime_invalid_arg)
1981 << 0;
1982 return ExprError();
1983 }
1984 return TheCall;
1985}
1986
1988 if (S.checkArgCount(TheCall, 3))
1989 return ExprError();
1990
1991 QualType Dest = TheCall->getArg(0)->getType();
1992 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
1993 S.Diag(TheCall->getArg(0)->getExprLoc(),
1994 diag::err_builtin_trivially_relocate_invalid_arg_type)
1995 << /*a pointer*/ 0;
1996 return ExprError();
1997 }
1998
1999 QualType T = Dest->getPointeeType();
2000 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2001 diag::err_incomplete_type))
2002 return ExprError();
2003
2004 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2005 T->isIncompleteArrayType()) {
2006 S.Diag(TheCall->getArg(0)->getExprLoc(),
2007 diag::err_builtin_trivially_relocate_invalid_arg_type)
2008 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2009 return ExprError();
2010 }
2011
2012 TheCall->setType(Dest);
2013
2014 QualType Src = TheCall->getArg(1)->getType();
2015 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2016 S.Diag(TheCall->getArg(1)->getExprLoc(),
2017 diag::err_builtin_trivially_relocate_invalid_arg_type)
2018 << /*the same*/ 3;
2019 return ExprError();
2020 }
2021
2022 Expr *SizeExpr = TheCall->getArg(2);
2023 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2024 if (Size.isInvalid())
2025 return ExprError();
2026
2027 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2028 if (Size.isInvalid())
2029 return ExprError();
2030 SizeExpr = Size.get();
2031 TheCall->setArg(2, SizeExpr);
2032
2033 return TheCall;
2034}
2035
2036// Emit an error and return true if the current object format type is in the
2037// list of unsupported types.
2039 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2040 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2041 llvm::Triple::ObjectFormatType CurObjFormat =
2042 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2043 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2044 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2045 << TheCall->getSourceRange();
2046 return true;
2047 }
2048 return false;
2049}
2050
2051// Emit an error and return true if the current architecture is not in the list
2052// of supported architectures.
2053static bool
2055 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2056 llvm::Triple::ArchType CurArch =
2057 S.getASTContext().getTargetInfo().getTriple().getArch();
2058 if (llvm::is_contained(SupportedArchs, CurArch))
2059 return false;
2060 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2061 << TheCall->getSourceRange();
2062 return true;
2063}
2064
2065static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2066 SourceLocation CallSiteLoc);
2067
2068bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2069 CallExpr *TheCall) {
2070 switch (TI.getTriple().getArch()) {
2071 default:
2072 // Some builtins don't require additional checking, so just consider these
2073 // acceptable.
2074 return false;
2075 case llvm::Triple::arm:
2076 case llvm::Triple::armeb:
2077 case llvm::Triple::thumb:
2078 case llvm::Triple::thumbeb:
2079 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2080 case llvm::Triple::aarch64:
2081 case llvm::Triple::aarch64_32:
2082 case llvm::Triple::aarch64_be:
2083 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2084 case llvm::Triple::bpfeb:
2085 case llvm::Triple::bpfel:
2086 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2087 case llvm::Triple::dxil:
2088 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2089 case llvm::Triple::hexagon:
2090 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2091 case llvm::Triple::mips:
2092 case llvm::Triple::mipsel:
2093 case llvm::Triple::mips64:
2094 case llvm::Triple::mips64el:
2095 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2096 case llvm::Triple::spirv:
2097 case llvm::Triple::spirv32:
2098 case llvm::Triple::spirv64:
2099 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2100 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2101 return false;
2102 case llvm::Triple::systemz:
2103 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2104 case llvm::Triple::x86:
2105 case llvm::Triple::x86_64:
2106 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2107 case llvm::Triple::ppc:
2108 case llvm::Triple::ppcle:
2109 case llvm::Triple::ppc64:
2110 case llvm::Triple::ppc64le:
2111 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2112 case llvm::Triple::amdgcn:
2113 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2114 case llvm::Triple::riscv32:
2115 case llvm::Triple::riscv64:
2116 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2117 case llvm::Triple::loongarch32:
2118 case llvm::Triple::loongarch64:
2119 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2120 TheCall);
2121 case llvm::Triple::wasm32:
2122 case llvm::Triple::wasm64:
2123 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2124 case llvm::Triple::nvptx:
2125 case llvm::Triple::nvptx64:
2126 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2127 }
2128}
2129
2130// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2131// not a valid type, emit an error message and return true. Otherwise return
2132// false.
2133static bool
2136 int ArgOrdinal) {
2137 QualType EltTy = ArgTy;
2138 if (auto *VecTy = EltTy->getAs<VectorType>())
2139 EltTy = VecTy->getElementType();
2140
2141 switch (ArgTyRestr) {
2143 if (!ArgTy->getAs<VectorType>() &&
2145 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2146 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2147 << ArgTy;
2148 }
2149 break;
2151 if (!EltTy->isRealFloatingType()) {
2152 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2153 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2154 << /* floating-point */ 1 << ArgTy;
2155 }
2156 break;
2158 if (!EltTy->isIntegerType()) {
2159 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2160 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2161 << /* no fp */ 0 << ArgTy;
2162 }
2163 break;
2165 if (EltTy->isUnsignedIntegerType()) {
2166 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2167 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2168 << /* or fp */ 1 << ArgTy;
2169 }
2170 break;
2171 }
2172
2173 return false;
2174}
2175
2176/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2177/// This checks that the target supports the builtin and that the string
2178/// argument is constant and valid.
2179static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2180 const TargetInfo *AuxTI, unsigned BuiltinID) {
2181 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2182 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2183 "Expecting __builtin_cpu_...");
2184
2185 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2186 const TargetInfo *TheTI = &TI;
2187 auto SupportsBI = [=](const TargetInfo *TInfo) {
2188 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2189 (!IsCPUSupports && TInfo->supportsCpuIs()));
2190 };
2191 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2192 TheTI = AuxTI;
2193
2194 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2195 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2196 return S.Diag(TheCall->getBeginLoc(),
2197 TI.getTriple().isOSAIX()
2198 ? diag::err_builtin_aix_os_unsupported
2199 : diag::err_builtin_target_unsupported)
2200 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2201
2202 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2203 // Check if the argument is a string literal.
2204 if (!isa<StringLiteral>(Arg))
2205 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2206 << Arg->getSourceRange();
2207
2208 // Check the contents of the string.
2209 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2210 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2211 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2212 << Arg->getSourceRange();
2213 return false;
2214 }
2215 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2216 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2217 << Arg->getSourceRange();
2218 return false;
2219}
2220
2221/// Checks that __builtin_popcountg was called with a single argument, which is
2222/// an unsigned integer.
2223static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2224 if (S.checkArgCount(TheCall, 1))
2225 return true;
2226
2227 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2228 if (ArgRes.isInvalid())
2229 return true;
2230
2231 Expr *Arg = ArgRes.get();
2232 TheCall->setArg(0, Arg);
2233
2234 QualType ArgTy = Arg->getType();
2235
2236 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2237 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2238 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2239 << ArgTy;
2240 return true;
2241 }
2242 return false;
2243}
2244
2245/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2246/// an unsigned integer, and an optional second argument, which is promoted to
2247/// an 'int'.
2248static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2249 if (S.checkArgCountRange(TheCall, 1, 2))
2250 return true;
2251
2252 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2253 if (Arg0Res.isInvalid())
2254 return true;
2255
2256 Expr *Arg0 = Arg0Res.get();
2257 TheCall->setArg(0, Arg0);
2258
2259 QualType Arg0Ty = Arg0->getType();
2260
2261 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2262 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2263 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2264 << Arg0Ty;
2265 return true;
2266 }
2267
2268 if (TheCall->getNumArgs() > 1) {
2269 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2270 if (Arg1Res.isInvalid())
2271 return true;
2272
2273 Expr *Arg1 = Arg1Res.get();
2274 TheCall->setArg(1, Arg1);
2275
2276 QualType Arg1Ty = Arg1->getType();
2277
2278 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2279 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2280 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2281 return true;
2282 }
2283 }
2284
2285 return false;
2286}
2287
2288static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2289 unsigned Pos, bool AllowConst,
2290 bool AllowAS) {
2291 QualType MaskTy = MaskArg->getType();
2292 if (!MaskTy->isExtVectorBoolType())
2293 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2294 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2295 << MaskTy;
2296
2297 QualType PtrTy = PtrArg->getType();
2298 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2299 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2300 << Pos << "scalar pointer";
2301
2302 QualType PointeeTy = PtrTy->getPointeeType();
2303 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2304 (!AllowConst && PointeeTy.isConstQualified()) ||
2305 (!AllowAS && PointeeTy.hasAddressSpace())) {
2308 return S.Diag(PtrArg->getExprLoc(),
2309 diag::err_typecheck_convert_incompatible)
2310 << PtrTy << Target << /*different qualifiers=*/5
2311 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2312 << PtrTy << Target;
2313 }
2314 return false;
2315}
2316
2317static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2318 bool TypeDependent = false;
2319 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2320 ExprResult Converted =
2322 if (Converted.isInvalid())
2323 return true;
2324 TheCall->setArg(Arg, Converted.get());
2325 TypeDependent |= Converted.get()->isTypeDependent();
2326 }
2327
2328 if (TypeDependent)
2329 TheCall->setType(S.Context.DependentTy);
2330 return false;
2331}
2332
2334 if (S.checkArgCountRange(TheCall, 2, 3))
2335 return ExprError();
2336
2337 if (ConvertMaskedBuiltinArgs(S, TheCall))
2338 return ExprError();
2339
2340 Expr *MaskArg = TheCall->getArg(0);
2341 Expr *PtrArg = TheCall->getArg(1);
2342 if (TheCall->isTypeDependent())
2343 return TheCall;
2344
2345 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2346 TheCall->getBuiltinCallee() ==
2347 Builtin::BI__builtin_masked_load))
2348 return ExprError();
2349
2350 QualType MaskTy = MaskArg->getType();
2351 QualType PtrTy = PtrArg->getType();
2352 QualType PointeeTy = PtrTy->getPointeeType();
2353 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2354
2356 MaskVecTy->getNumElements());
2357 if (TheCall->getNumArgs() == 3) {
2358 Expr *PassThruArg = TheCall->getArg(2);
2359 QualType PassThruTy = PassThruArg->getType();
2360 if (!S.Context.hasSameType(PassThruTy, RetTy))
2361 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2362 << /* third argument */ 3 << RetTy;
2363 }
2364
2365 TheCall->setType(RetTy);
2366 return TheCall;
2367}
2368
2370 if (S.checkArgCount(TheCall, 3))
2371 return ExprError();
2372
2373 if (ConvertMaskedBuiltinArgs(S, TheCall))
2374 return ExprError();
2375
2376 Expr *MaskArg = TheCall->getArg(0);
2377 Expr *ValArg = TheCall->getArg(1);
2378 Expr *PtrArg = TheCall->getArg(2);
2379 if (TheCall->isTypeDependent())
2380 return TheCall;
2381
2382 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2383 TheCall->getBuiltinCallee() ==
2384 Builtin::BI__builtin_masked_store))
2385 return ExprError();
2386
2387 QualType MaskTy = MaskArg->getType();
2388 QualType PtrTy = PtrArg->getType();
2389 QualType ValTy = ValArg->getType();
2390 if (!ValTy->isVectorType())
2391 return ExprError(
2392 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2393 << 2 << "vector");
2394
2395 QualType PointeeTy = PtrTy->getPointeeType();
2396 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2397 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2398 MaskVecTy->getNumElements());
2399 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2400 MemoryTy.getUnqualifiedType()))
2401 return ExprError(S.Diag(TheCall->getBeginLoc(),
2402 diag::err_vec_builtin_incompatible_vector)
2403 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2404 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2405 TheCall->getArg(1)->getEndLoc()));
2406
2407 TheCall->setType(S.Context.VoidTy);
2408 return TheCall;
2409}
2410
2412 if (S.checkArgCountRange(TheCall, 3, 4))
2413 return ExprError();
2414
2415 if (ConvertMaskedBuiltinArgs(S, TheCall))
2416 return ExprError();
2417
2418 Expr *MaskArg = TheCall->getArg(0);
2419 Expr *IdxArg = TheCall->getArg(1);
2420 Expr *PtrArg = TheCall->getArg(2);
2421 if (TheCall->isTypeDependent())
2422 return TheCall;
2423
2424 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2425 /*AllowAS=*/true))
2426 return ExprError();
2427
2428 QualType IdxTy = IdxArg->getType();
2429 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2430 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2431 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2432 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2433 << IdxTy;
2434
2435 QualType MaskTy = MaskArg->getType();
2436 QualType PtrTy = PtrArg->getType();
2437 QualType PointeeTy = PtrTy->getPointeeType();
2438 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2439 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2440 return ExprError(
2441 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2443 TheCall->getBuiltinCallee())
2444 << MaskTy << IdxTy);
2445
2447 MaskVecTy->getNumElements());
2448 if (TheCall->getNumArgs() == 4) {
2449 Expr *PassThruArg = TheCall->getArg(3);
2450 QualType PassThruTy = PassThruArg->getType();
2451 if (!S.Context.hasSameType(PassThruTy, RetTy))
2452 return S.Diag(PassThruArg->getExprLoc(),
2453 diag::err_vec_masked_load_store_ptr)
2454 << /* fourth argument */ 4 << RetTy;
2455 }
2456
2457 TheCall->setType(RetTy);
2458 return TheCall;
2459}
2460
2462 if (S.checkArgCount(TheCall, 4))
2463 return ExprError();
2464
2465 if (ConvertMaskedBuiltinArgs(S, TheCall))
2466 return ExprError();
2467
2468 Expr *MaskArg = TheCall->getArg(0);
2469 Expr *IdxArg = TheCall->getArg(1);
2470 Expr *ValArg = TheCall->getArg(2);
2471 Expr *PtrArg = TheCall->getArg(3);
2472 if (TheCall->isTypeDependent())
2473 return TheCall;
2474
2475 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2476 /*AllowAS=*/true))
2477 return ExprError();
2478
2479 QualType IdxTy = IdxArg->getType();
2480 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2481 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2482 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2483 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2484 << IdxTy;
2485
2486 QualType ValTy = ValArg->getType();
2487 QualType MaskTy = MaskArg->getType();
2488 QualType PtrTy = PtrArg->getType();
2489 QualType PointeeTy = PtrTy->getPointeeType();
2490
2491 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2492 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2493 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2494 return ExprError(
2495 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2497 TheCall->getBuiltinCallee())
2498 << MaskTy << IdxTy);
2499 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2500 return ExprError(
2501 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2503 TheCall->getBuiltinCallee())
2504 << MaskTy << ValTy);
2505
2507 MaskVecTy->getNumElements());
2508 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2509 return ExprError(S.Diag(TheCall->getBeginLoc(),
2510 diag::err_vec_builtin_incompatible_vector)
2511 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2512 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2513 TheCall->getArg(1)->getEndLoc()));
2514
2515 TheCall->setType(S.Context.VoidTy);
2516 return TheCall;
2517}
2518
2520 SourceLocation Loc = TheCall->getBeginLoc();
2521 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2522 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2523
2524 if (Args.size() == 0) {
2525 S.Diag(TheCall->getBeginLoc(),
2526 diag::err_typecheck_call_too_few_args_at_least)
2527 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2528 << /*is_non_object=*/0 << TheCall->getSourceRange();
2529 return ExprError();
2530 }
2531
2532 QualType FuncT = Args[0]->getType();
2533
2534 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2535 if (Args.size() < 2) {
2536 S.Diag(TheCall->getBeginLoc(),
2537 diag::err_typecheck_call_too_few_args_at_least)
2538 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2539 << /*is_non_object=*/0 << TheCall->getSourceRange();
2540 return ExprError();
2541 }
2542
2543 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2544 QualType ObjectT = Args[1]->getType();
2545
2546 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2547 return ExprError();
2548
2549 ExprResult ObjectArg = [&]() -> ExprResult {
2550 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2551 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2552 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2553 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2554 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2555 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2556 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2557 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2558 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2559 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2560 return Args[1];
2561 }
2562
2563 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2564 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2565 // reference_wrapper;
2566 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2567 if (RD->isInStdNamespace() &&
2568 RD->getDeclName().getAsString() == "reference_wrapper") {
2569 CXXScopeSpec SS;
2570 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2571 UnqualifiedId GetID;
2572 GetID.setIdentifier(GetName, Loc);
2573
2575 S.getCurScope(), Args[1], Loc, tok::period, SS,
2576 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2577
2578 if (MemExpr.isInvalid())
2579 return ExprError();
2580
2581 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2582 }
2583 }
2584
2585 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2586 // class T and t1 does not satisfy the previous two items;
2587
2588 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2589 }();
2590
2591 if (ObjectArg.isInvalid())
2592 return ExprError();
2593
2594 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2595 tok::periodstar, ObjectArg.get(), Args[0]);
2596 if (BinOp.isInvalid())
2597 return ExprError();
2598
2599 if (MPT->isMemberDataPointer())
2600 return BinOp;
2601
2602 auto *MemCall = new (S.Context)
2604
2605 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2606 Args.drop_front(2), TheCall->getRParenLoc());
2607 }
2608 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2609 Args.drop_front(), TheCall->getRParenLoc());
2610}
2611
2612// Performs a similar job to Sema::UsualUnaryConversions, but without any
2613// implicit promotion of integral/enumeration types.
2615 // First, convert to an r-value.
2617 if (Res.isInvalid())
2618 return ExprError();
2619
2620 // Promote floating-point types.
2621 return S.UsualUnaryFPConversions(Res.get());
2622}
2623
2625Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2626 CallExpr *TheCall) {
2627 ExprResult TheCallResult(TheCall);
2628
2629 // Find out if any arguments are required to be integer constant expressions.
2630 unsigned ICEArguments = 0;
2632 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2634 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2635
2636 // If any arguments are required to be ICE's, check and diagnose.
2637 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2638 // Skip arguments not required to be ICE's.
2639 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2640
2641 llvm::APSInt Result;
2642 // If we don't have enough arguments, continue so we can issue better
2643 // diagnostic in checkArgCount(...)
2644 if (ArgNo < TheCall->getNumArgs() &&
2645 BuiltinConstantArg(TheCall, ArgNo, Result))
2646 return true;
2647 ICEArguments &= ~(1 << ArgNo);
2648 }
2649
2650 FPOptions FPO;
2651 switch (BuiltinID) {
2652 case Builtin::BI__builtin_cpu_supports:
2653 case Builtin::BI__builtin_cpu_is:
2654 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2655 Context.getAuxTargetInfo(), BuiltinID))
2656 return ExprError();
2657 break;
2658 case Builtin::BI__builtin_cpu_init:
2659 if (!Context.getTargetInfo().supportsCpuInit()) {
2660 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2661 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2662 return ExprError();
2663 }
2664 break;
2665 case Builtin::BI__builtin___CFStringMakeConstantString:
2666 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2667 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2669 *this, BuiltinID, TheCall,
2670 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2671 return ExprError();
2672 assert(TheCall->getNumArgs() == 1 &&
2673 "Wrong # arguments to builtin CFStringMakeConstantString");
2674 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2675 return ExprError();
2676 break;
2677 case Builtin::BI__builtin_ms_va_start:
2678 case Builtin::BI__builtin_stdarg_start:
2679 case Builtin::BI__builtin_va_start:
2680 case Builtin::BI__builtin_c23_va_start:
2681 if (BuiltinVAStart(BuiltinID, TheCall))
2682 return ExprError();
2683 break;
2684 case Builtin::BI__va_start: {
2685 switch (Context.getTargetInfo().getTriple().getArch()) {
2686 case llvm::Triple::aarch64:
2687 case llvm::Triple::arm:
2688 case llvm::Triple::thumb:
2689 if (BuiltinVAStartARMMicrosoft(TheCall))
2690 return ExprError();
2691 break;
2692 default:
2693 if (BuiltinVAStart(BuiltinID, TheCall))
2694 return ExprError();
2695 break;
2696 }
2697 break;
2698 }
2699
2700 // The acquire, release, and no fence variants are ARM and AArch64 only.
2701 case Builtin::BI_interlockedbittestandset_acq:
2702 case Builtin::BI_interlockedbittestandset_rel:
2703 case Builtin::BI_interlockedbittestandset_nf:
2704 case Builtin::BI_interlockedbittestandreset_acq:
2705 case Builtin::BI_interlockedbittestandreset_rel:
2706 case Builtin::BI_interlockedbittestandreset_nf:
2708 *this, TheCall,
2709 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2710 return ExprError();
2711 break;
2712
2713 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2714 case Builtin::BI_bittest64:
2715 case Builtin::BI_bittestandcomplement64:
2716 case Builtin::BI_bittestandreset64:
2717 case Builtin::BI_bittestandset64:
2718 case Builtin::BI_interlockedbittestandreset64:
2719 case Builtin::BI_interlockedbittestandset64:
2721 *this, TheCall,
2722 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2723 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2724 return ExprError();
2725 break;
2726
2727 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2728 case Builtin::BI_interlockedbittestandreset64_acq:
2729 case Builtin::BI_interlockedbittestandreset64_rel:
2730 case Builtin::BI_interlockedbittestandreset64_nf:
2731 case Builtin::BI_interlockedbittestandset64_acq:
2732 case Builtin::BI_interlockedbittestandset64_rel:
2733 case Builtin::BI_interlockedbittestandset64_nf:
2734 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2735 return ExprError();
2736 break;
2737
2738 case Builtin::BI__builtin_set_flt_rounds:
2740 *this, TheCall,
2741 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2742 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2743 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2744 llvm::Triple::ppc64le}))
2745 return ExprError();
2746 break;
2747
2748 case Builtin::BI__builtin_isgreater:
2749 case Builtin::BI__builtin_isgreaterequal:
2750 case Builtin::BI__builtin_isless:
2751 case Builtin::BI__builtin_islessequal:
2752 case Builtin::BI__builtin_islessgreater:
2753 case Builtin::BI__builtin_isunordered:
2754 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2755 return ExprError();
2756 break;
2757 case Builtin::BI__builtin_fpclassify:
2758 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2759 return ExprError();
2760 break;
2761 case Builtin::BI__builtin_isfpclass:
2762 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2763 return ExprError();
2764 break;
2765 case Builtin::BI__builtin_isfinite:
2766 case Builtin::BI__builtin_isinf:
2767 case Builtin::BI__builtin_isinf_sign:
2768 case Builtin::BI__builtin_isnan:
2769 case Builtin::BI__builtin_issignaling:
2770 case Builtin::BI__builtin_isnormal:
2771 case Builtin::BI__builtin_issubnormal:
2772 case Builtin::BI__builtin_iszero:
2773 case Builtin::BI__builtin_signbit:
2774 case Builtin::BI__builtin_signbitf:
2775 case Builtin::BI__builtin_signbitl:
2776 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2777 return ExprError();
2778 break;
2779 case Builtin::BI__builtin_shufflevector:
2780 return BuiltinShuffleVector(TheCall);
2781 // TheCall will be freed by the smart pointer here, but that's fine, since
2782 // BuiltinShuffleVector guts it, but then doesn't release it.
2783 case Builtin::BI__builtin_masked_load:
2784 case Builtin::BI__builtin_masked_expand_load:
2785 return BuiltinMaskedLoad(*this, TheCall);
2786 case Builtin::BI__builtin_masked_store:
2787 case Builtin::BI__builtin_masked_compress_store:
2788 return BuiltinMaskedStore(*this, TheCall);
2789 case Builtin::BI__builtin_masked_gather:
2790 return BuiltinMaskedGather(*this, TheCall);
2791 case Builtin::BI__builtin_masked_scatter:
2792 return BuiltinMaskedScatter(*this, TheCall);
2793 case Builtin::BI__builtin_invoke:
2794 return BuiltinInvoke(*this, TheCall);
2795 case Builtin::BI__builtin_prefetch:
2796 if (BuiltinPrefetch(TheCall))
2797 return ExprError();
2798 break;
2799 case Builtin::BI__builtin_alloca_with_align:
2800 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2801 if (BuiltinAllocaWithAlign(TheCall))
2802 return ExprError();
2803 [[fallthrough]];
2804 case Builtin::BI__builtin_alloca:
2805 case Builtin::BI__builtin_alloca_uninitialized:
2806 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2807 << TheCall->getDirectCallee();
2808 if (getLangOpts().OpenCL) {
2809 builtinAllocaAddrSpace(*this, TheCall);
2810 }
2811 break;
2812 case Builtin::BI__builtin_infer_alloc_token:
2813 if (checkBuiltinInferAllocToken(*this, TheCall))
2814 return ExprError();
2815 break;
2816 case Builtin::BI__arithmetic_fence:
2817 if (BuiltinArithmeticFence(TheCall))
2818 return ExprError();
2819 break;
2820 case Builtin::BI__assume:
2821 case Builtin::BI__builtin_assume:
2822 if (BuiltinAssume(TheCall))
2823 return ExprError();
2824 break;
2825 case Builtin::BI__builtin_assume_aligned:
2826 if (BuiltinAssumeAligned(TheCall))
2827 return ExprError();
2828 break;
2829 case Builtin::BI__builtin_dynamic_object_size:
2830 case Builtin::BI__builtin_object_size:
2831 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2832 return ExprError();
2833 break;
2834 case Builtin::BI__builtin_longjmp:
2835 if (BuiltinLongjmp(TheCall))
2836 return ExprError();
2837 break;
2838 case Builtin::BI__builtin_setjmp:
2839 if (BuiltinSetjmp(TheCall))
2840 return ExprError();
2841 break;
2842 case Builtin::BI__builtin_classify_type:
2843 if (checkArgCount(TheCall, 1))
2844 return true;
2845 TheCall->setType(Context.IntTy);
2846 break;
2847 case Builtin::BI__builtin_complex:
2848 if (BuiltinComplex(TheCall))
2849 return ExprError();
2850 break;
2851 case Builtin::BI__builtin_constant_p: {
2852 if (checkArgCount(TheCall, 1))
2853 return true;
2855 if (Arg.isInvalid()) return true;
2856 TheCall->setArg(0, Arg.get());
2857 TheCall->setType(Context.IntTy);
2858 break;
2859 }
2860 case Builtin::BI__builtin_launder:
2861 return BuiltinLaunder(*this, TheCall);
2862 case Builtin::BI__builtin_is_within_lifetime:
2863 return BuiltinIsWithinLifetime(*this, TheCall);
2864 case Builtin::BI__builtin_trivially_relocate:
2865 return BuiltinTriviallyRelocate(*this, TheCall);
2866
2867 case Builtin::BI__sync_fetch_and_add:
2868 case Builtin::BI__sync_fetch_and_add_1:
2869 case Builtin::BI__sync_fetch_and_add_2:
2870 case Builtin::BI__sync_fetch_and_add_4:
2871 case Builtin::BI__sync_fetch_and_add_8:
2872 case Builtin::BI__sync_fetch_and_add_16:
2873 case Builtin::BI__sync_fetch_and_sub:
2874 case Builtin::BI__sync_fetch_and_sub_1:
2875 case Builtin::BI__sync_fetch_and_sub_2:
2876 case Builtin::BI__sync_fetch_and_sub_4:
2877 case Builtin::BI__sync_fetch_and_sub_8:
2878 case Builtin::BI__sync_fetch_and_sub_16:
2879 case Builtin::BI__sync_fetch_and_or:
2880 case Builtin::BI__sync_fetch_and_or_1:
2881 case Builtin::BI__sync_fetch_and_or_2:
2882 case Builtin::BI__sync_fetch_and_or_4:
2883 case Builtin::BI__sync_fetch_and_or_8:
2884 case Builtin::BI__sync_fetch_and_or_16:
2885 case Builtin::BI__sync_fetch_and_and:
2886 case Builtin::BI__sync_fetch_and_and_1:
2887 case Builtin::BI__sync_fetch_and_and_2:
2888 case Builtin::BI__sync_fetch_and_and_4:
2889 case Builtin::BI__sync_fetch_and_and_8:
2890 case Builtin::BI__sync_fetch_and_and_16:
2891 case Builtin::BI__sync_fetch_and_xor:
2892 case Builtin::BI__sync_fetch_and_xor_1:
2893 case Builtin::BI__sync_fetch_and_xor_2:
2894 case Builtin::BI__sync_fetch_and_xor_4:
2895 case Builtin::BI__sync_fetch_and_xor_8:
2896 case Builtin::BI__sync_fetch_and_xor_16:
2897 case Builtin::BI__sync_fetch_and_nand:
2898 case Builtin::BI__sync_fetch_and_nand_1:
2899 case Builtin::BI__sync_fetch_and_nand_2:
2900 case Builtin::BI__sync_fetch_and_nand_4:
2901 case Builtin::BI__sync_fetch_and_nand_8:
2902 case Builtin::BI__sync_fetch_and_nand_16:
2903 case Builtin::BI__sync_add_and_fetch:
2904 case Builtin::BI__sync_add_and_fetch_1:
2905 case Builtin::BI__sync_add_and_fetch_2:
2906 case Builtin::BI__sync_add_and_fetch_4:
2907 case Builtin::BI__sync_add_and_fetch_8:
2908 case Builtin::BI__sync_add_and_fetch_16:
2909 case Builtin::BI__sync_sub_and_fetch:
2910 case Builtin::BI__sync_sub_and_fetch_1:
2911 case Builtin::BI__sync_sub_and_fetch_2:
2912 case Builtin::BI__sync_sub_and_fetch_4:
2913 case Builtin::BI__sync_sub_and_fetch_8:
2914 case Builtin::BI__sync_sub_and_fetch_16:
2915 case Builtin::BI__sync_and_and_fetch:
2916 case Builtin::BI__sync_and_and_fetch_1:
2917 case Builtin::BI__sync_and_and_fetch_2:
2918 case Builtin::BI__sync_and_and_fetch_4:
2919 case Builtin::BI__sync_and_and_fetch_8:
2920 case Builtin::BI__sync_and_and_fetch_16:
2921 case Builtin::BI__sync_or_and_fetch:
2922 case Builtin::BI__sync_or_and_fetch_1:
2923 case Builtin::BI__sync_or_and_fetch_2:
2924 case Builtin::BI__sync_or_and_fetch_4:
2925 case Builtin::BI__sync_or_and_fetch_8:
2926 case Builtin::BI__sync_or_and_fetch_16:
2927 case Builtin::BI__sync_xor_and_fetch:
2928 case Builtin::BI__sync_xor_and_fetch_1:
2929 case Builtin::BI__sync_xor_and_fetch_2:
2930 case Builtin::BI__sync_xor_and_fetch_4:
2931 case Builtin::BI__sync_xor_and_fetch_8:
2932 case Builtin::BI__sync_xor_and_fetch_16:
2933 case Builtin::BI__sync_nand_and_fetch:
2934 case Builtin::BI__sync_nand_and_fetch_1:
2935 case Builtin::BI__sync_nand_and_fetch_2:
2936 case Builtin::BI__sync_nand_and_fetch_4:
2937 case Builtin::BI__sync_nand_and_fetch_8:
2938 case Builtin::BI__sync_nand_and_fetch_16:
2939 case Builtin::BI__sync_val_compare_and_swap:
2940 case Builtin::BI__sync_val_compare_and_swap_1:
2941 case Builtin::BI__sync_val_compare_and_swap_2:
2942 case Builtin::BI__sync_val_compare_and_swap_4:
2943 case Builtin::BI__sync_val_compare_and_swap_8:
2944 case Builtin::BI__sync_val_compare_and_swap_16:
2945 case Builtin::BI__sync_bool_compare_and_swap:
2946 case Builtin::BI__sync_bool_compare_and_swap_1:
2947 case Builtin::BI__sync_bool_compare_and_swap_2:
2948 case Builtin::BI__sync_bool_compare_and_swap_4:
2949 case Builtin::BI__sync_bool_compare_and_swap_8:
2950 case Builtin::BI__sync_bool_compare_and_swap_16:
2951 case Builtin::BI__sync_lock_test_and_set:
2952 case Builtin::BI__sync_lock_test_and_set_1:
2953 case Builtin::BI__sync_lock_test_and_set_2:
2954 case Builtin::BI__sync_lock_test_and_set_4:
2955 case Builtin::BI__sync_lock_test_and_set_8:
2956 case Builtin::BI__sync_lock_test_and_set_16:
2957 case Builtin::BI__sync_lock_release:
2958 case Builtin::BI__sync_lock_release_1:
2959 case Builtin::BI__sync_lock_release_2:
2960 case Builtin::BI__sync_lock_release_4:
2961 case Builtin::BI__sync_lock_release_8:
2962 case Builtin::BI__sync_lock_release_16:
2963 case Builtin::BI__sync_swap:
2964 case Builtin::BI__sync_swap_1:
2965 case Builtin::BI__sync_swap_2:
2966 case Builtin::BI__sync_swap_4:
2967 case Builtin::BI__sync_swap_8:
2968 case Builtin::BI__sync_swap_16:
2969 return BuiltinAtomicOverloaded(TheCallResult);
2970 case Builtin::BI__sync_synchronize:
2971 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2972 << TheCall->getCallee()->getSourceRange();
2973 break;
2974 case Builtin::BI__builtin_nontemporal_load:
2975 case Builtin::BI__builtin_nontemporal_store:
2976 return BuiltinNontemporalOverloaded(TheCallResult);
2977 case Builtin::BI__builtin_memcpy_inline: {
2978 clang::Expr *SizeOp = TheCall->getArg(2);
2979 // We warn about copying to or from `nullptr` pointers when `size` is
2980 // greater than 0. When `size` is value dependent we cannot evaluate its
2981 // value so we bail out.
2982 if (SizeOp->isValueDependent())
2983 break;
2984 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2985 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2986 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2987 }
2988 break;
2989 }
2990 case Builtin::BI__builtin_memset_inline: {
2991 clang::Expr *SizeOp = TheCall->getArg(2);
2992 // We warn about filling to `nullptr` pointers when `size` is greater than
2993 // 0. When `size` is value dependent we cannot evaluate its value so we bail
2994 // out.
2995 if (SizeOp->isValueDependent())
2996 break;
2997 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2998 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2999 break;
3000 }
3001#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3002 case Builtin::BI##ID: \
3003 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3004#include "clang/Basic/Builtins.inc"
3005 case Builtin::BI__annotation:
3006 if (BuiltinMSVCAnnotation(*this, TheCall))
3007 return ExprError();
3008 break;
3009 case Builtin::BI__builtin_annotation:
3010 if (BuiltinAnnotation(*this, TheCall))
3011 return ExprError();
3012 break;
3013 case Builtin::BI__builtin_addressof:
3014 if (BuiltinAddressof(*this, TheCall))
3015 return ExprError();
3016 break;
3017 case Builtin::BI__builtin_function_start:
3018 if (BuiltinFunctionStart(*this, TheCall))
3019 return ExprError();
3020 break;
3021 case Builtin::BI__builtin_is_aligned:
3022 case Builtin::BI__builtin_align_up:
3023 case Builtin::BI__builtin_align_down:
3024 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3025 return ExprError();
3026 break;
3027 case Builtin::BI__builtin_add_overflow:
3028 case Builtin::BI__builtin_sub_overflow:
3029 case Builtin::BI__builtin_mul_overflow:
3030 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3031 return ExprError();
3032 break;
3033 case Builtin::BI__builtin_operator_new:
3034 case Builtin::BI__builtin_operator_delete: {
3035 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3036 ExprResult Res =
3037 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3038 return Res;
3039 }
3040 case Builtin::BI__builtin_dump_struct:
3041 return BuiltinDumpStruct(*this, TheCall);
3042 case Builtin::BI__builtin_expect_with_probability: {
3043 // We first want to ensure we are called with 3 arguments
3044 if (checkArgCount(TheCall, 3))
3045 return ExprError();
3046 // then check probability is constant float in range [0.0, 1.0]
3047 const Expr *ProbArg = TheCall->getArg(2);
3048 SmallVector<PartialDiagnosticAt, 8> Notes;
3049 Expr::EvalResult Eval;
3050 Eval.Diag = &Notes;
3051 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3052 !Eval.Val.isFloat()) {
3053 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3054 << ProbArg->getSourceRange();
3055 for (const PartialDiagnosticAt &PDiag : Notes)
3056 Diag(PDiag.first, PDiag.second);
3057 return ExprError();
3058 }
3059 llvm::APFloat Probability = Eval.Val.getFloat();
3060 bool LoseInfo = false;
3061 Probability.convert(llvm::APFloat::IEEEdouble(),
3062 llvm::RoundingMode::Dynamic, &LoseInfo);
3063 if (!(Probability >= llvm::APFloat(0.0) &&
3064 Probability <= llvm::APFloat(1.0))) {
3065 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3066 << ProbArg->getSourceRange();
3067 return ExprError();
3068 }
3069 break;
3070 }
3071 case Builtin::BI__builtin_preserve_access_index:
3072 if (BuiltinPreserveAI(*this, TheCall))
3073 return ExprError();
3074 break;
3075 case Builtin::BI__builtin_call_with_static_chain:
3076 if (BuiltinCallWithStaticChain(*this, TheCall))
3077 return ExprError();
3078 break;
3079 case Builtin::BI__exception_code:
3080 case Builtin::BI_exception_code:
3081 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3082 diag::err_seh___except_block))
3083 return ExprError();
3084 break;
3085 case Builtin::BI__exception_info:
3086 case Builtin::BI_exception_info:
3087 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3088 diag::err_seh___except_filter))
3089 return ExprError();
3090 break;
3091 case Builtin::BI__GetExceptionInfo:
3092 if (checkArgCount(TheCall, 1))
3093 return ExprError();
3094
3096 TheCall->getBeginLoc(),
3097 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3098 TheCall))
3099 return ExprError();
3100
3101 TheCall->setType(Context.VoidPtrTy);
3102 break;
3103 case Builtin::BIaddressof:
3104 case Builtin::BI__addressof:
3105 case Builtin::BIforward:
3106 case Builtin::BIforward_like:
3107 case Builtin::BImove:
3108 case Builtin::BImove_if_noexcept:
3109 case Builtin::BIas_const: {
3110 // These are all expected to be of the form
3111 // T &/&&/* f(U &/&&)
3112 // where T and U only differ in qualification.
3113 if (checkArgCount(TheCall, 1))
3114 return ExprError();
3115 QualType Param = FDecl->getParamDecl(0)->getType();
3116 QualType Result = FDecl->getReturnType();
3117 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3118 BuiltinID == Builtin::BI__addressof;
3119 if (!(Param->isReferenceType() &&
3120 (ReturnsPointer ? Result->isAnyPointerType()
3121 : Result->isReferenceType()) &&
3122 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3123 Result->getPointeeType()))) {
3124 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3125 << FDecl;
3126 return ExprError();
3127 }
3128 break;
3129 }
3130 case Builtin::BI__builtin_ptrauth_strip:
3131 return PointerAuthStrip(*this, TheCall);
3132 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3133 return PointerAuthBlendDiscriminator(*this, TheCall);
3134 case Builtin::BI__builtin_ptrauth_sign_constant:
3135 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3136 /*RequireConstant=*/true);
3137 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3138 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3139 /*RequireConstant=*/false);
3140 case Builtin::BI__builtin_ptrauth_auth:
3141 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3142 /*RequireConstant=*/false);
3143 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3144 return PointerAuthSignGenericData(*this, TheCall);
3145 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3146 return PointerAuthAuthAndResign(*this, TheCall);
3147 case Builtin::BI__builtin_ptrauth_string_discriminator:
3148 return PointerAuthStringDiscriminator(*this, TheCall);
3149
3150 case Builtin::BI__builtin_get_vtable_pointer:
3151 return GetVTablePointer(*this, TheCall);
3152
3153 // OpenCL v2.0, s6.13.16 - Pipe functions
3154 case Builtin::BIread_pipe:
3155 case Builtin::BIwrite_pipe:
3156 // Since those two functions are declared with var args, we need a semantic
3157 // check for the argument.
3158 if (OpenCL().checkBuiltinRWPipe(TheCall))
3159 return ExprError();
3160 break;
3161 case Builtin::BIreserve_read_pipe:
3162 case Builtin::BIreserve_write_pipe:
3163 case Builtin::BIwork_group_reserve_read_pipe:
3164 case Builtin::BIwork_group_reserve_write_pipe:
3165 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3166 return ExprError();
3167 break;
3168 case Builtin::BIsub_group_reserve_read_pipe:
3169 case Builtin::BIsub_group_reserve_write_pipe:
3170 if (OpenCL().checkSubgroupExt(TheCall) ||
3171 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3172 return ExprError();
3173 break;
3174 case Builtin::BIcommit_read_pipe:
3175 case Builtin::BIcommit_write_pipe:
3176 case Builtin::BIwork_group_commit_read_pipe:
3177 case Builtin::BIwork_group_commit_write_pipe:
3178 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3179 return ExprError();
3180 break;
3181 case Builtin::BIsub_group_commit_read_pipe:
3182 case Builtin::BIsub_group_commit_write_pipe:
3183 if (OpenCL().checkSubgroupExt(TheCall) ||
3184 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3185 return ExprError();
3186 break;
3187 case Builtin::BIget_pipe_num_packets:
3188 case Builtin::BIget_pipe_max_packets:
3189 if (OpenCL().checkBuiltinPipePackets(TheCall))
3190 return ExprError();
3191 break;
3192 case Builtin::BIto_global:
3193 case Builtin::BIto_local:
3194 case Builtin::BIto_private:
3195 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3196 return ExprError();
3197 break;
3198 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3199 case Builtin::BIenqueue_kernel:
3200 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3201 return ExprError();
3202 break;
3203 case Builtin::BIget_kernel_work_group_size:
3204 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3205 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3206 return ExprError();
3207 break;
3208 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3209 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3210 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3211 return ExprError();
3212 break;
3213 case Builtin::BI__builtin_os_log_format:
3214 Cleanup.setExprNeedsCleanups(true);
3215 [[fallthrough]];
3216 case Builtin::BI__builtin_os_log_format_buffer_size:
3217 if (BuiltinOSLogFormat(TheCall))
3218 return ExprError();
3219 break;
3220 case Builtin::BI__builtin_frame_address:
3221 case Builtin::BI__builtin_return_address: {
3222 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3223 return ExprError();
3224
3225 // -Wframe-address warning if non-zero passed to builtin
3226 // return/frame address.
3227 Expr::EvalResult Result;
3228 if (!TheCall->getArg(0)->isValueDependent() &&
3229 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3230 Result.Val.getInt() != 0)
3231 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3232 << ((BuiltinID == Builtin::BI__builtin_return_address)
3233 ? "__builtin_return_address"
3234 : "__builtin_frame_address")
3235 << TheCall->getSourceRange();
3236 break;
3237 }
3238
3239 case Builtin::BI__builtin_nondeterministic_value: {
3240 if (BuiltinNonDeterministicValue(TheCall))
3241 return ExprError();
3242 break;
3243 }
3244
3245 // __builtin_elementwise_abs restricts the element type to signed integers or
3246 // floating point types only.
3247 case Builtin::BI__builtin_elementwise_abs:
3250 return ExprError();
3251 break;
3252
3253 // These builtins restrict the element type to floating point
3254 // types only.
3255 case Builtin::BI__builtin_elementwise_acos:
3256 case Builtin::BI__builtin_elementwise_asin:
3257 case Builtin::BI__builtin_elementwise_atan:
3258 case Builtin::BI__builtin_elementwise_ceil:
3259 case Builtin::BI__builtin_elementwise_cos:
3260 case Builtin::BI__builtin_elementwise_cosh:
3261 case Builtin::BI__builtin_elementwise_exp:
3262 case Builtin::BI__builtin_elementwise_exp2:
3263 case Builtin::BI__builtin_elementwise_exp10:
3264 case Builtin::BI__builtin_elementwise_floor:
3265 case Builtin::BI__builtin_elementwise_log:
3266 case Builtin::BI__builtin_elementwise_log2:
3267 case Builtin::BI__builtin_elementwise_log10:
3268 case Builtin::BI__builtin_elementwise_roundeven:
3269 case Builtin::BI__builtin_elementwise_round:
3270 case Builtin::BI__builtin_elementwise_rint:
3271 case Builtin::BI__builtin_elementwise_nearbyint:
3272 case Builtin::BI__builtin_elementwise_sin:
3273 case Builtin::BI__builtin_elementwise_sinh:
3274 case Builtin::BI__builtin_elementwise_sqrt:
3275 case Builtin::BI__builtin_elementwise_tan:
3276 case Builtin::BI__builtin_elementwise_tanh:
3277 case Builtin::BI__builtin_elementwise_trunc:
3278 case Builtin::BI__builtin_elementwise_canonicalize:
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_elementwise_fma:
3284 if (BuiltinElementwiseTernaryMath(TheCall))
3285 return ExprError();
3286 break;
3287
3288 case Builtin::BI__builtin_elementwise_ldexp: {
3289 if (checkArgCount(TheCall, 2))
3290 return ExprError();
3291
3292 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3293 if (A.isInvalid())
3294 return ExprError();
3295 QualType TyA = A.get()->getType();
3296 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3298 return ExprError();
3299
3300 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3301 if (Exp.isInvalid())
3302 return ExprError();
3303 QualType TyExp = Exp.get()->getType();
3304 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3306 2))
3307 return ExprError();
3308
3309 // Check the two arguments are either scalars or vectors of equal length.
3310 const auto *Vec0 = TyA->getAs<VectorType>();
3311 const auto *Vec1 = TyExp->getAs<VectorType>();
3312 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3313 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3314 if (Arg0Length != Arg1Length) {
3315 Diag(Exp.get()->getBeginLoc(),
3316 diag::err_typecheck_vector_lengths_not_equal)
3317 << TyA << TyExp << A.get()->getSourceRange()
3318 << Exp.get()->getSourceRange();
3319 return ExprError();
3320 }
3321
3322 TheCall->setArg(0, A.get());
3323 TheCall->setArg(1, Exp.get());
3324 TheCall->setType(TyA);
3325 break;
3326 }
3327
3328 // These builtins restrict the element type to floating point
3329 // types only, and take in two arguments.
3330 case Builtin::BI__builtin_elementwise_minnum:
3331 case Builtin::BI__builtin_elementwise_maxnum:
3332 case Builtin::BI__builtin_elementwise_minimum:
3333 case Builtin::BI__builtin_elementwise_maximum:
3334 case Builtin::BI__builtin_elementwise_minimumnum:
3335 case Builtin::BI__builtin_elementwise_maximumnum:
3336 case Builtin::BI__builtin_elementwise_atan2:
3337 case Builtin::BI__builtin_elementwise_fmod:
3338 case Builtin::BI__builtin_elementwise_pow:
3339 if (BuiltinElementwiseMath(TheCall,
3341 return ExprError();
3342 break;
3343 // These builtins restrict the element type to integer
3344 // types only.
3345 case Builtin::BI__builtin_elementwise_add_sat:
3346 case Builtin::BI__builtin_elementwise_sub_sat:
3347 if (BuiltinElementwiseMath(TheCall,
3349 return ExprError();
3350 break;
3351 case Builtin::BI__builtin_elementwise_fshl:
3352 case Builtin::BI__builtin_elementwise_fshr:
3355 return ExprError();
3356 break;
3357 case Builtin::BI__builtin_elementwise_min:
3358 case Builtin::BI__builtin_elementwise_max:
3359 if (BuiltinElementwiseMath(TheCall))
3360 return ExprError();
3361 break;
3362 case Builtin::BI__builtin_elementwise_popcount:
3363 case Builtin::BI__builtin_elementwise_bitreverse:
3366 return ExprError();
3367 break;
3368 case Builtin::BI__builtin_elementwise_copysign: {
3369 if (checkArgCount(TheCall, 2))
3370 return ExprError();
3371
3372 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3373 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3374 if (Magnitude.isInvalid() || Sign.isInvalid())
3375 return ExprError();
3376
3377 QualType MagnitudeTy = Magnitude.get()->getType();
3378 QualType SignTy = Sign.get()->getType();
3380 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3383 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3385 return ExprError();
3386 }
3387
3388 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3389 return Diag(Sign.get()->getBeginLoc(),
3390 diag::err_typecheck_call_different_arg_types)
3391 << MagnitudeTy << SignTy;
3392 }
3393
3394 TheCall->setArg(0, Magnitude.get());
3395 TheCall->setArg(1, Sign.get());
3396 TheCall->setType(Magnitude.get()->getType());
3397 break;
3398 }
3399 case Builtin::BI__builtin_elementwise_clzg:
3400 case Builtin::BI__builtin_elementwise_ctzg:
3401 // These builtins can be unary or binary. Note for empty calls we call the
3402 // unary checker in order to not emit an error that says the function
3403 // expects 2 arguments, which would be misleading.
3404 if (TheCall->getNumArgs() <= 1) {
3407 return ExprError();
3408 } else if (BuiltinElementwiseMath(
3410 return ExprError();
3411 break;
3412 case Builtin::BI__builtin_reduce_max:
3413 case Builtin::BI__builtin_reduce_min: {
3414 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3415 return ExprError();
3416
3417 const Expr *Arg = TheCall->getArg(0);
3418 const auto *TyA = Arg->getType()->getAs<VectorType>();
3419
3420 QualType ElTy;
3421 if (TyA)
3422 ElTy = TyA->getElementType();
3423 else if (Arg->getType()->isSizelessVectorType())
3425
3426 if (ElTy.isNull()) {
3427 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3428 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3429 << Arg->getType();
3430 return ExprError();
3431 }
3432
3433 TheCall->setType(ElTy);
3434 break;
3435 }
3436 case Builtin::BI__builtin_reduce_maximum:
3437 case Builtin::BI__builtin_reduce_minimum: {
3438 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3439 return ExprError();
3440
3441 const Expr *Arg = TheCall->getArg(0);
3442 const auto *TyA = Arg->getType()->getAs<VectorType>();
3443
3444 QualType ElTy;
3445 if (TyA)
3446 ElTy = TyA->getElementType();
3447 else if (Arg->getType()->isSizelessVectorType())
3449
3450 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3451 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3452 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3453 << Arg->getType();
3454 return ExprError();
3455 }
3456
3457 TheCall->setType(ElTy);
3458 break;
3459 }
3460
3461 // These builtins support vectors of integers only.
3462 // TODO: ADD/MUL should support floating-point types.
3463 case Builtin::BI__builtin_reduce_add:
3464 case Builtin::BI__builtin_reduce_mul:
3465 case Builtin::BI__builtin_reduce_xor:
3466 case Builtin::BI__builtin_reduce_or:
3467 case Builtin::BI__builtin_reduce_and: {
3468 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3469 return ExprError();
3470
3471 const Expr *Arg = TheCall->getArg(0);
3472 const auto *TyA = Arg->getType()->getAs<VectorType>();
3473
3474 QualType ElTy;
3475 if (TyA)
3476 ElTy = TyA->getElementType();
3477 else if (Arg->getType()->isSizelessVectorType())
3479
3480 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3481 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3482 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3483 << Arg->getType();
3484 return ExprError();
3485 }
3486
3487 TheCall->setType(ElTy);
3488 break;
3489 }
3490
3491 case Builtin::BI__builtin_matrix_transpose:
3492 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3493
3494 case Builtin::BI__builtin_matrix_column_major_load:
3495 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3496
3497 case Builtin::BI__builtin_matrix_column_major_store:
3498 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3499
3500 case Builtin::BI__builtin_verbose_trap:
3501 if (!checkBuiltinVerboseTrap(TheCall, *this))
3502 return ExprError();
3503 break;
3504
3505 case Builtin::BI__builtin_get_device_side_mangled_name: {
3506 auto Check = [](CallExpr *TheCall) {
3507 if (TheCall->getNumArgs() != 1)
3508 return false;
3509 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3510 if (!DRE)
3511 return false;
3512 auto *D = DRE->getDecl();
3513 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3514 return false;
3515 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3516 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3517 };
3518 if (!Check(TheCall)) {
3519 Diag(TheCall->getBeginLoc(),
3520 diag::err_hip_invalid_args_builtin_mangled_name);
3521 return ExprError();
3522 }
3523 break;
3524 }
3525 case Builtin::BI__builtin_popcountg:
3526 if (BuiltinPopcountg(*this, TheCall))
3527 return ExprError();
3528 break;
3529 case Builtin::BI__builtin_clzg:
3530 case Builtin::BI__builtin_ctzg:
3531 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3532 return ExprError();
3533 break;
3534
3535 case Builtin::BI__builtin_allow_runtime_check: {
3536 Expr *Arg = TheCall->getArg(0);
3537 // Check if the argument is a string literal.
3539 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3540 << Arg->getSourceRange();
3541 return ExprError();
3542 }
3543 break;
3544 }
3545 case Builtin::BI__builtin_counted_by_ref:
3546 if (BuiltinCountedByRef(TheCall))
3547 return ExprError();
3548 break;
3549 }
3550
3551 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3552 return ExprError();
3553
3554 // Since the target specific builtins for each arch overlap, only check those
3555 // of the arch we are compiling for.
3556 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3557 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3558 assert(Context.getAuxTargetInfo() &&
3559 "Aux Target Builtin, but not an aux target?");
3560
3561 if (CheckTSBuiltinFunctionCall(
3562 *Context.getAuxTargetInfo(),
3563 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3564 return ExprError();
3565 } else {
3566 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3567 TheCall))
3568 return ExprError();
3569 }
3570 }
3571
3572 return TheCallResult;
3573}
3574
3575bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3576 llvm::APSInt Result;
3577 // We can't check the value of a dependent argument.
3578 Expr *Arg = TheCall->getArg(ArgNum);
3579 if (Arg->isTypeDependent() || Arg->isValueDependent())
3580 return false;
3581
3582 // Check constant-ness first.
3583 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3584 return true;
3585
3586 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3587 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3588 return false;
3589
3590 return Diag(TheCall->getBeginLoc(),
3591 diag::err_argument_not_contiguous_bit_field)
3592 << ArgNum << Arg->getSourceRange();
3593}
3594
3595bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3596 unsigned FirstArg, FormatStringInfo *FSI) {
3597 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3598 bool IsVariadic = false;
3599 if (const FunctionType *FnTy = D->getFunctionType())
3600 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3601 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3602 IsVariadic = BD->isVariadic();
3603 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3604 IsVariadic = OMD->isVariadic();
3605
3606 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3607 IsVariadic, FSI);
3608}
3609
3610bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3611 bool HasImplicitThisParam, bool IsVariadic,
3612 FormatStringInfo *FSI) {
3613 if (FirstArg == 0)
3615 else if (IsVariadic)
3617 else
3619 FSI->FormatIdx = FormatIdx - 1;
3620 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3621
3622 // The way the format attribute works in GCC, the implicit this argument
3623 // of member functions is counted. However, it doesn't appear in our own
3624 // lists, so decrement format_idx in that case.
3625 if (HasImplicitThisParam) {
3626 if(FSI->FormatIdx == 0)
3627 return false;
3628 --FSI->FormatIdx;
3629 if (FSI->FirstDataArg != 0)
3630 --FSI->FirstDataArg;
3631 }
3632 return true;
3633}
3634
3635/// Checks if a the given expression evaluates to null.
3636///
3637/// Returns true if the value evaluates to null.
3638static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3639 // Treat (smart) pointers constructed from nullptr as null, whether we can
3640 // const-evaluate them or not.
3641 // This must happen first: the smart pointer expr might have _Nonnull type!
3645 return true;
3646
3647 // If the expression has non-null type, it doesn't evaluate to null.
3648 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3649 if (*nullability == NullabilityKind::NonNull)
3650 return false;
3651 }
3652
3653 // As a special case, transparent unions initialized with zero are
3654 // considered null for the purposes of the nonnull attribute.
3655 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3656 UT &&
3657 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3658 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3659 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3660 Expr = ILE->getInit(0);
3661 }
3662
3663 bool Result;
3664 return (!Expr->isValueDependent() &&
3666 !Result);
3667}
3668
3670 const Expr *ArgExpr,
3671 SourceLocation CallSiteLoc) {
3672 if (CheckNonNullExpr(S, ArgExpr))
3673 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3674 S.PDiag(diag::warn_null_arg)
3675 << ArgExpr->getSourceRange());
3676}
3677
3678/// Determine whether the given type has a non-null nullability annotation.
3680 if (auto nullability = type->getNullability())
3681 return *nullability == NullabilityKind::NonNull;
3682
3683 return false;
3684}
3685
3687 const NamedDecl *FDecl,
3688 const FunctionProtoType *Proto,
3690 SourceLocation CallSiteLoc) {
3691 assert((FDecl || Proto) && "Need a function declaration or prototype");
3692
3693 // Already checked by constant evaluator.
3695 return;
3696 // Check the attributes attached to the method/function itself.
3697 llvm::SmallBitVector NonNullArgs;
3698 if (FDecl) {
3699 // Handle the nonnull attribute on the function/method declaration itself.
3700 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3701 if (!NonNull->args_size()) {
3702 // Easy case: all pointer arguments are nonnull.
3703 for (const auto *Arg : Args)
3704 if (S.isValidPointerAttrType(Arg->getType()))
3705 CheckNonNullArgument(S, Arg, CallSiteLoc);
3706 return;
3707 }
3708
3709 for (const ParamIdx &Idx : NonNull->args()) {
3710 unsigned IdxAST = Idx.getASTIndex();
3711 if (IdxAST >= Args.size())
3712 continue;
3713 if (NonNullArgs.empty())
3714 NonNullArgs.resize(Args.size());
3715 NonNullArgs.set(IdxAST);
3716 }
3717 }
3718 }
3719
3720 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3721 // Handle the nonnull attribute on the parameters of the
3722 // function/method.
3724 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3725 parms = FD->parameters();
3726 else
3727 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3728
3729 unsigned ParamIndex = 0;
3730 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3731 I != E; ++I, ++ParamIndex) {
3732 const ParmVarDecl *PVD = *I;
3733 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3734 if (NonNullArgs.empty())
3735 NonNullArgs.resize(Args.size());
3736
3737 NonNullArgs.set(ParamIndex);
3738 }
3739 }
3740 } else {
3741 // If we have a non-function, non-method declaration but no
3742 // function prototype, try to dig out the function prototype.
3743 if (!Proto) {
3744 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3745 QualType type = VD->getType().getNonReferenceType();
3746 if (auto pointerType = type->getAs<PointerType>())
3747 type = pointerType->getPointeeType();
3748 else if (auto blockType = type->getAs<BlockPointerType>())
3749 type = blockType->getPointeeType();
3750 // FIXME: data member pointers?
3751
3752 // Dig out the function prototype, if there is one.
3753 Proto = type->getAs<FunctionProtoType>();
3754 }
3755 }
3756
3757 // Fill in non-null argument information from the nullability
3758 // information on the parameter types (if we have them).
3759 if (Proto) {
3760 unsigned Index = 0;
3761 for (auto paramType : Proto->getParamTypes()) {
3762 if (isNonNullType(paramType)) {
3763 if (NonNullArgs.empty())
3764 NonNullArgs.resize(Args.size());
3765
3766 NonNullArgs.set(Index);
3767 }
3768
3769 ++Index;
3770 }
3771 }
3772 }
3773
3774 // Check for non-null arguments.
3775 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3776 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3777 if (NonNullArgs[ArgIndex])
3778 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3779 }
3780}
3781
3782void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3783 StringRef ParamName, QualType ArgTy,
3784 QualType ParamTy) {
3785
3786 // If a function accepts a pointer or reference type
3787 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3788 return;
3789
3790 // If the parameter is a pointer type, get the pointee type for the
3791 // argument too. If the parameter is a reference type, don't try to get
3792 // the pointee type for the argument.
3793 if (ParamTy->isPointerType())
3794 ArgTy = ArgTy->getPointeeType();
3795
3796 // Remove reference or pointer
3797 ParamTy = ParamTy->getPointeeType();
3798
3799 // Find expected alignment, and the actual alignment of the passed object.
3800 // getTypeAlignInChars requires complete types
3801 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3802 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3803 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3804 return;
3805
3806 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3807 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3808
3809 // If the argument is less aligned than the parameter, there is a
3810 // potential alignment issue.
3811 if (ArgAlign < ParamAlign)
3812 Diag(Loc, diag::warn_param_mismatched_alignment)
3813 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3814 << ParamName << (FDecl != nullptr) << FDecl;
3815}
3816
3817void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3818 const Expr *ThisArg,
3820 if (!FD || Args.empty())
3821 return;
3822 auto GetArgAt = [&](int Idx) -> const Expr * {
3823 if (Idx == LifetimeCaptureByAttr::Global ||
3824 Idx == LifetimeCaptureByAttr::Unknown)
3825 return nullptr;
3826 if (IsMemberFunction && Idx == 0)
3827 return ThisArg;
3828 return Args[Idx - IsMemberFunction];
3829 };
3830 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3831 unsigned ArgIdx) {
3832 if (!Attr)
3833 return;
3834
3835 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3836 for (int CapturingParamIdx : Attr->params()) {
3837 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3838 // initialization codepath.
3839 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3841 continue;
3842 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3843 CapturingEntity CE{Capturing};
3844 // Ensure that 'Captured' outlives the 'Capturing' entity.
3845 checkCaptureByLifetime(*this, CE, Captured);
3846 }
3847 };
3848 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3849 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3850 I + IsMemberFunction);
3851 // Check when the implicit object param is captured.
3852 if (IsMemberFunction) {
3853 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3854 if (!TSI)
3855 return;
3857 for (TypeLoc TL = TSI->getTypeLoc();
3858 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3859 TL = ATL.getModifiedLoc())
3860 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3861 }
3862}
3863
3865 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3866 bool IsMemberFunction, SourceLocation Loc,
3867 SourceRange Range, VariadicCallType CallType) {
3868 // FIXME: We should check as much as we can in the template definition.
3869 if (CurContext->isDependentContext())
3870 return;
3871
3872 // Printf and scanf checking.
3873 llvm::SmallBitVector CheckedVarArgs;
3874 if (FDecl) {
3875 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3876 // Only create vector if there are format attributes.
3877 CheckedVarArgs.resize(Args.size());
3878 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3879 CheckedVarArgs);
3880 }
3881
3882 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3883 CheckedVarArgs.resize(Args.size());
3884 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3885 CheckedVarArgs);
3886 }
3887 }
3888
3889 // Refuse POD arguments that weren't caught by the format string
3890 // checks above.
3891 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3892 if (CallType != VariadicCallType::DoesNotApply &&
3893 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3894 unsigned NumParams = Proto ? Proto->getNumParams()
3895 : isa_and_nonnull<FunctionDecl>(FDecl)
3896 ? cast<FunctionDecl>(FDecl)->getNumParams()
3897 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3898 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3899 : 0;
3900
3901 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3902 // Args[ArgIdx] can be null in malformed code.
3903 if (const Expr *Arg = Args[ArgIdx]) {
3904 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3905 checkVariadicArgument(Arg, CallType);
3906 }
3907 }
3908 }
3909 if (FD)
3910 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3911 if (FDecl || Proto) {
3912 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3913
3914 // Type safety checking.
3915 if (FDecl) {
3916 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3917 CheckArgumentWithTypeTag(I, Args, Loc);
3918 }
3919 }
3920
3921 // Check that passed arguments match the alignment of original arguments.
3922 // Try to get the missing prototype from the declaration.
3923 if (!Proto && FDecl) {
3924 const auto *FT = FDecl->getFunctionType();
3925 if (isa_and_nonnull<FunctionProtoType>(FT))
3926 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3927 }
3928 if (Proto) {
3929 // For variadic functions, we may have more args than parameters.
3930 // For some K&R functions, we may have less args than parameters.
3931 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3932 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3933 bool IsScalableArg = false;
3934 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3935 // Args[ArgIdx] can be null in malformed code.
3936 if (const Expr *Arg = Args[ArgIdx]) {
3937 if (Arg->containsErrors())
3938 continue;
3939
3940 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3941 FDecl->hasLinkage() &&
3942 FDecl->getFormalLinkage() != Linkage::Internal &&
3944 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3945
3946 QualType ParamTy = Proto->getParamType(ArgIdx);
3947 if (ParamTy->isSizelessVectorType())
3948 IsScalableArg = true;
3949 QualType ArgTy = Arg->getType();
3950 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3951 ArgTy, ParamTy);
3952 }
3953 }
3954
3955 // If the callee has an AArch64 SME attribute to indicate that it is an
3956 // __arm_streaming function, then the caller requires SME to be available.
3959 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3960 llvm::StringMap<bool> CallerFeatureMap;
3961 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3962 if (!CallerFeatureMap.contains("sme"))
3963 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3964 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3965 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3966 }
3967 }
3968
3969 // If the call requires a streaming-mode change and has scalable vector
3970 // arguments or return values, then warn the user that the streaming and
3971 // non-streaming vector lengths may be different.
3972 // When both streaming and non-streaming vector lengths are defined and
3973 // mismatched, produce an error.
3974 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3975 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3976 (IsScalableArg || IsScalableRet)) {
3977 bool IsCalleeStreaming =
3979 bool IsCalleeStreamingCompatible =
3980 ExtInfo.AArch64SMEAttributes &
3982 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3983 if (!IsCalleeStreamingCompatible &&
3984 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3985 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3986 const LangOptions &LO = getLangOpts();
3987 unsigned VL = LO.VScaleMin * 128;
3988 unsigned SVL = LO.VScaleStreamingMin * 128;
3989 bool IsVLMismatch = VL && SVL && VL != SVL;
3990
3991 auto EmitDiag = [&](bool IsArg) {
3992 if (IsVLMismatch) {
3993 if (CallerFnType == SemaARM::ArmStreamingCompatible)
3994 // Emit warning for streaming-compatible callers
3995 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
3996 << IsArg << IsCalleeStreaming << SVL << VL;
3997 else
3998 // Emit error otherwise
3999 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4000 << IsArg << SVL << VL;
4001 } else
4002 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4003 << IsArg;
4004 };
4005
4006 if (IsScalableArg)
4007 EmitDiag(true);
4008 if (IsScalableRet)
4009 EmitDiag(false);
4010 }
4011 }
4012
4013 FunctionType::ArmStateValue CalleeArmZAState =
4015 FunctionType::ArmStateValue CalleeArmZT0State =
4017 if (CalleeArmZAState != FunctionType::ARM_None ||
4018 CalleeArmZT0State != FunctionType::ARM_None) {
4019 bool CallerHasZAState = false;
4020 bool CallerHasZT0State = false;
4021 if (CallerFD) {
4022 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4023 if (Attr && Attr->isNewZA())
4024 CallerHasZAState = true;
4025 if (Attr && Attr->isNewZT0())
4026 CallerHasZT0State = true;
4027 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4028 CallerHasZAState |=
4030 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4032 CallerHasZT0State |=
4034 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4036 }
4037 }
4038
4039 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4040 Diag(Loc, diag::err_sme_za_call_no_za_state);
4041
4042 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4043 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4044
4045 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4046 CalleeArmZT0State != FunctionType::ARM_None) {
4047 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4048 Diag(Loc, diag::note_sme_use_preserves_za);
4049 }
4050 }
4051 }
4052
4053 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4054 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4055 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4056 if (!Arg->isValueDependent()) {
4057 Expr::EvalResult Align;
4058 if (Arg->EvaluateAsInt(Align, Context)) {
4059 const llvm::APSInt &I = Align.Val.getInt();
4060 if (!I.isPowerOf2())
4061 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4062 << Arg->getSourceRange();
4063
4064 if (I > Sema::MaximumAlignment)
4065 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4066 << Arg->getSourceRange() << Sema::MaximumAlignment;
4067 }
4068 }
4069 }
4070
4071 if (FD)
4072 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4073}
4074
4075void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4076 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4077 DiagnoseUseOfDecl(Decl, Loc);
4078 }
4079}
4080
4081void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4083 const FunctionProtoType *Proto,
4084 SourceLocation Loc) {
4085 VariadicCallType CallType = Proto->isVariadic()
4088
4089 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4090 CheckArgAlignment(
4091 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4092 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4093
4094 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4095 Loc, SourceRange(), CallType);
4096}
4097
4099 const FunctionProtoType *Proto) {
4100 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4101 isa<CXXMethodDecl>(FDecl);
4102 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4103 IsMemberOperatorCall;
4104 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4105 TheCall->getCallee());
4106 Expr** Args = TheCall->getArgs();
4107 unsigned NumArgs = TheCall->getNumArgs();
4108
4109 Expr *ImplicitThis = nullptr;
4110 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4111 // If this is a call to a member operator, hide the first
4112 // argument from checkCall.
4113 // FIXME: Our choice of AST representation here is less than ideal.
4114 ImplicitThis = Args[0];
4115 ++Args;
4116 --NumArgs;
4117 } else if (IsMemberFunction && !FDecl->isStatic() &&
4119 ImplicitThis =
4120 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4121
4122 if (ImplicitThis) {
4123 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4124 // used.
4125 QualType ThisType = ImplicitThis->getType();
4126 if (!ThisType->isPointerType()) {
4127 assert(!ThisType->isReferenceType());
4128 ThisType = Context.getPointerType(ThisType);
4129 }
4130
4131 QualType ThisTypeFromDecl = Context.getPointerType(
4132 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4133
4134 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4135 ThisTypeFromDecl);
4136 }
4137
4138 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4139 IsMemberFunction, TheCall->getRParenLoc(),
4140 TheCall->getCallee()->getSourceRange(), CallType);
4141
4142 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4143 // None of the checks below are needed for functions that don't have
4144 // simple names (e.g., C++ conversion functions).
4145 if (!FnInfo)
4146 return false;
4147
4148 // Enforce TCB except for builtin calls, which are always allowed.
4149 if (FDecl->getBuiltinID() == 0)
4150 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4151
4152 CheckAbsoluteValueFunction(TheCall, FDecl);
4153 CheckMaxUnsignedZero(TheCall, FDecl);
4154 CheckInfNaNFunction(TheCall, FDecl);
4155
4156 if (getLangOpts().ObjC)
4157 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4158
4159 unsigned CMId = FDecl->getMemoryFunctionKind();
4160
4161 // Handle memory setting and copying functions.
4162 switch (CMId) {
4163 case 0:
4164 return false;
4165 case Builtin::BIstrlcpy: // fallthrough
4166 case Builtin::BIstrlcat:
4167 CheckStrlcpycatArguments(TheCall, FnInfo);
4168 break;
4169 case Builtin::BIstrncat:
4170 CheckStrncatArguments(TheCall, FnInfo);
4171 break;
4172 case Builtin::BIfree:
4173 CheckFreeArguments(TheCall);
4174 break;
4175 default:
4176 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4177 }
4178
4179 return false;
4180}
4181
4182bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4183 const FunctionProtoType *Proto) {
4184 QualType Ty;
4185 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4186 Ty = V->getType().getNonReferenceType();
4187 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4188 Ty = F->getType().getNonReferenceType();
4189 else
4190 return false;
4191
4192 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4193 !Ty->isFunctionProtoType())
4194 return false;
4195
4196 VariadicCallType CallType;
4197 if (!Proto || !Proto->isVariadic()) {
4199 } else if (Ty->isBlockPointerType()) {
4200 CallType = VariadicCallType::Block;
4201 } else { // Ty->isFunctionPointerType()
4202 CallType = VariadicCallType::Function;
4203 }
4204
4205 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4206 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4207 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4208 TheCall->getCallee()->getSourceRange(), CallType);
4209
4210 return false;
4211}
4212
4213bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4214 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4215 TheCall->getCallee());
4216 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4217 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4218 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4219 TheCall->getCallee()->getSourceRange(), CallType);
4220
4221 return false;
4222}
4223
4224static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4225 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4226 return false;
4227
4228 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4229 switch (Op) {
4230 case AtomicExpr::AO__c11_atomic_init:
4231 case AtomicExpr::AO__opencl_atomic_init:
4232 llvm_unreachable("There is no ordering argument for an init");
4233
4234 case AtomicExpr::AO__c11_atomic_load:
4235 case AtomicExpr::AO__opencl_atomic_load:
4236 case AtomicExpr::AO__hip_atomic_load:
4237 case AtomicExpr::AO__atomic_load_n:
4238 case AtomicExpr::AO__atomic_load:
4239 case AtomicExpr::AO__scoped_atomic_load_n:
4240 case AtomicExpr::AO__scoped_atomic_load:
4241 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4242 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4243
4244 case AtomicExpr::AO__c11_atomic_store:
4245 case AtomicExpr::AO__opencl_atomic_store:
4246 case AtomicExpr::AO__hip_atomic_store:
4247 case AtomicExpr::AO__atomic_store:
4248 case AtomicExpr::AO__atomic_store_n:
4249 case AtomicExpr::AO__scoped_atomic_store:
4250 case AtomicExpr::AO__scoped_atomic_store_n:
4251 case AtomicExpr::AO__atomic_clear:
4252 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4253 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4254 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4255
4256 default:
4257 return true;
4258 }
4259}
4260
4261ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4263 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4264 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4265 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4266 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4267 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4268 Op);
4269}
4270
4272 SourceLocation RParenLoc, MultiExprArg Args,
4274 AtomicArgumentOrder ArgOrder) {
4275 // All the non-OpenCL operations take one of the following forms.
4276 // The OpenCL operations take the __c11 forms with one extra argument for
4277 // synchronization scope.
4278 enum {
4279 // C __c11_atomic_init(A *, C)
4280 Init,
4281
4282 // C __c11_atomic_load(A *, int)
4283 Load,
4284
4285 // void __atomic_load(A *, CP, int)
4286 LoadCopy,
4287
4288 // void __atomic_store(A *, CP, int)
4289 Copy,
4290
4291 // C __c11_atomic_add(A *, M, int)
4292 Arithmetic,
4293
4294 // C __atomic_exchange_n(A *, CP, int)
4295 Xchg,
4296
4297 // void __atomic_exchange(A *, C *, CP, int)
4298 GNUXchg,
4299
4300 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4301 C11CmpXchg,
4302
4303 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4304 GNUCmpXchg,
4305
4306 // bool __atomic_test_and_set(A *, int)
4307 TestAndSetByte,
4308
4309 // void __atomic_clear(A *, int)
4310 ClearByte,
4311 } Form = Init;
4312
4313 const unsigned NumForm = ClearByte + 1;
4314 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4315 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4316 // where:
4317 // C is an appropriate type,
4318 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4319 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4320 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4321 // the int parameters are for orderings.
4322
4323 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4324 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4325 "need to update code for modified forms");
4326 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4327 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4328 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4329 "need to update code for modified C11 atomics");
4330 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4331 Op <= AtomicExpr::AO__opencl_atomic_store;
4332 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4333 Op <= AtomicExpr::AO__hip_atomic_store;
4334 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4335 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4336 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4337 Op <= AtomicExpr::AO__c11_atomic_store) ||
4338 IsOpenCL;
4339 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4340 Op == AtomicExpr::AO__atomic_store_n ||
4341 Op == AtomicExpr::AO__atomic_exchange_n ||
4342 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4343 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4344 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4345 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4346 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4347 // Bit mask for extra allowed value types other than integers for atomic
4348 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4349 // allow floating point.
4350 enum ArithOpExtraValueType {
4351 AOEVT_None = 0,
4352 AOEVT_Pointer = 1,
4353 AOEVT_FP = 2,
4354 };
4355 unsigned ArithAllows = AOEVT_None;
4356
4357 switch (Op) {
4358 case AtomicExpr::AO__c11_atomic_init:
4359 case AtomicExpr::AO__opencl_atomic_init:
4360 Form = Init;
4361 break;
4362
4363 case AtomicExpr::AO__c11_atomic_load:
4364 case AtomicExpr::AO__opencl_atomic_load:
4365 case AtomicExpr::AO__hip_atomic_load:
4366 case AtomicExpr::AO__atomic_load_n:
4367 case AtomicExpr::AO__scoped_atomic_load_n:
4368 Form = Load;
4369 break;
4370
4371 case AtomicExpr::AO__atomic_load:
4372 case AtomicExpr::AO__scoped_atomic_load:
4373 Form = LoadCopy;
4374 break;
4375
4376 case AtomicExpr::AO__c11_atomic_store:
4377 case AtomicExpr::AO__opencl_atomic_store:
4378 case AtomicExpr::AO__hip_atomic_store:
4379 case AtomicExpr::AO__atomic_store:
4380 case AtomicExpr::AO__atomic_store_n:
4381 case AtomicExpr::AO__scoped_atomic_store:
4382 case AtomicExpr::AO__scoped_atomic_store_n:
4383 Form = Copy;
4384 break;
4385 case AtomicExpr::AO__atomic_fetch_add:
4386 case AtomicExpr::AO__atomic_fetch_sub:
4387 case AtomicExpr::AO__atomic_add_fetch:
4388 case AtomicExpr::AO__atomic_sub_fetch:
4389 case AtomicExpr::AO__scoped_atomic_fetch_add:
4390 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4391 case AtomicExpr::AO__scoped_atomic_add_fetch:
4392 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4393 case AtomicExpr::AO__c11_atomic_fetch_add:
4394 case AtomicExpr::AO__c11_atomic_fetch_sub:
4395 case AtomicExpr::AO__opencl_atomic_fetch_add:
4396 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4397 case AtomicExpr::AO__hip_atomic_fetch_add:
4398 case AtomicExpr::AO__hip_atomic_fetch_sub:
4399 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4400 Form = Arithmetic;
4401 break;
4402 case AtomicExpr::AO__atomic_fetch_max:
4403 case AtomicExpr::AO__atomic_fetch_min:
4404 case AtomicExpr::AO__atomic_max_fetch:
4405 case AtomicExpr::AO__atomic_min_fetch:
4406 case AtomicExpr::AO__scoped_atomic_fetch_max:
4407 case AtomicExpr::AO__scoped_atomic_fetch_min:
4408 case AtomicExpr::AO__scoped_atomic_max_fetch:
4409 case AtomicExpr::AO__scoped_atomic_min_fetch:
4410 case AtomicExpr::AO__c11_atomic_fetch_max:
4411 case AtomicExpr::AO__c11_atomic_fetch_min:
4412 case AtomicExpr::AO__opencl_atomic_fetch_max:
4413 case AtomicExpr::AO__opencl_atomic_fetch_min:
4414 case AtomicExpr::AO__hip_atomic_fetch_max:
4415 case AtomicExpr::AO__hip_atomic_fetch_min:
4416 ArithAllows = AOEVT_FP;
4417 Form = Arithmetic;
4418 break;
4419 case AtomicExpr::AO__c11_atomic_fetch_and:
4420 case AtomicExpr::AO__c11_atomic_fetch_or:
4421 case AtomicExpr::AO__c11_atomic_fetch_xor:
4422 case AtomicExpr::AO__hip_atomic_fetch_and:
4423 case AtomicExpr::AO__hip_atomic_fetch_or:
4424 case AtomicExpr::AO__hip_atomic_fetch_xor:
4425 case AtomicExpr::AO__c11_atomic_fetch_nand:
4426 case AtomicExpr::AO__opencl_atomic_fetch_and:
4427 case AtomicExpr::AO__opencl_atomic_fetch_or:
4428 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4429 case AtomicExpr::AO__atomic_fetch_and:
4430 case AtomicExpr::AO__atomic_fetch_or:
4431 case AtomicExpr::AO__atomic_fetch_xor:
4432 case AtomicExpr::AO__atomic_fetch_nand:
4433 case AtomicExpr::AO__atomic_and_fetch:
4434 case AtomicExpr::AO__atomic_or_fetch:
4435 case AtomicExpr::AO__atomic_xor_fetch:
4436 case AtomicExpr::AO__atomic_nand_fetch:
4437 case AtomicExpr::AO__scoped_atomic_fetch_and:
4438 case AtomicExpr::AO__scoped_atomic_fetch_or:
4439 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4440 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4441 case AtomicExpr::AO__scoped_atomic_and_fetch:
4442 case AtomicExpr::AO__scoped_atomic_or_fetch:
4443 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4444 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4445 Form = Arithmetic;
4446 break;
4447
4448 case AtomicExpr::AO__c11_atomic_exchange:
4449 case AtomicExpr::AO__hip_atomic_exchange:
4450 case AtomicExpr::AO__opencl_atomic_exchange:
4451 case AtomicExpr::AO__atomic_exchange_n:
4452 case AtomicExpr::AO__scoped_atomic_exchange_n:
4453 Form = Xchg;
4454 break;
4455
4456 case AtomicExpr::AO__atomic_exchange:
4457 case AtomicExpr::AO__scoped_atomic_exchange:
4458 Form = GNUXchg;
4459 break;
4460
4461 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4462 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4463 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4464 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4465 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4466 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4467 Form = C11CmpXchg;
4468 break;
4469
4470 case AtomicExpr::AO__atomic_compare_exchange:
4471 case AtomicExpr::AO__atomic_compare_exchange_n:
4472 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4473 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4474 Form = GNUCmpXchg;
4475 break;
4476
4477 case AtomicExpr::AO__atomic_test_and_set:
4478 Form = TestAndSetByte;
4479 break;
4480
4481 case AtomicExpr::AO__atomic_clear:
4482 Form = ClearByte;
4483 break;
4484 }
4485
4486 unsigned AdjustedNumArgs = NumArgs[Form];
4487 if ((IsOpenCL || IsHIP || IsScoped) &&
4488 Op != AtomicExpr::AO__opencl_atomic_init)
4489 ++AdjustedNumArgs;
4490 // Check we have the right number of arguments.
4491 if (Args.size() < AdjustedNumArgs) {
4492 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4493 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4494 << /*is non object*/ 0 << ExprRange;
4495 return ExprError();
4496 } else if (Args.size() > AdjustedNumArgs) {
4497 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4498 diag::err_typecheck_call_too_many_args)
4499 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4500 << /*is non object*/ 0 << ExprRange;
4501 return ExprError();
4502 }
4503
4504 // Inspect the first argument of the atomic operation.
4505 Expr *Ptr = Args[0];
4507 if (ConvertedPtr.isInvalid())
4508 return ExprError();
4509
4510 Ptr = ConvertedPtr.get();
4511 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4512 if (!pointerType) {
4513 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4514 << Ptr->getType() << 0 << Ptr->getSourceRange();
4515 return ExprError();
4516 }
4517
4518 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4519 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4520 QualType ValType = AtomTy; // 'C'
4521 if (IsC11) {
4522 if (!AtomTy->isAtomicType()) {
4523 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4524 << Ptr->getType() << Ptr->getSourceRange();
4525 return ExprError();
4526 }
4527 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4529 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4530 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4531 << Ptr->getSourceRange();
4532 return ExprError();
4533 }
4534 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4535 } else if (Form != Load && Form != LoadCopy) {
4536 if (ValType.isConstQualified()) {
4537 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4538 << Ptr->getType() << Ptr->getSourceRange();
4539 return ExprError();
4540 }
4541 }
4542
4543 if (Form != TestAndSetByte && Form != ClearByte) {
4544 // Pointer to object of size zero is not allowed.
4545 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4546 diag::err_incomplete_type))
4547 return ExprError();
4548
4549 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4550 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4551 << Ptr->getType() << 1 << Ptr->getSourceRange();
4552 return ExprError();
4553 }
4554 } else {
4555 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4556 // non-const pointer type, including void* and pointers to incomplete
4557 // structs, but only access the first byte.
4558 AtomTy = Context.CharTy;
4559 AtomTy = AtomTy.withCVRQualifiers(
4560 pointerType->getPointeeType().getCVRQualifiers());
4561 QualType PointerQT = Context.getPointerType(AtomTy);
4562 pointerType = PointerQT->getAs<PointerType>();
4563 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4564 ValType = AtomTy;
4565 }
4566
4567 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4568 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4569 Diag(ExprRange.getBegin(),
4570 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4571 << 0 << Ptr->getType() << Ptr->getSourceRange();
4572 return ExprError();
4573 }
4574
4575 // For an arithmetic operation, the implied arithmetic must be well-formed.
4576 if (Form == Arithmetic) {
4577 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4578 // trivial type errors.
4579 auto IsAllowedValueType = [&](QualType ValType,
4580 unsigned AllowedType) -> bool {
4581 if (ValType->isIntegerType())
4582 return true;
4583 if (ValType->isPointerType())
4584 return AllowedType & AOEVT_Pointer;
4585 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4586 return false;
4587 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4588 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4589 &Context.getTargetInfo().getLongDoubleFormat() ==
4590 &llvm::APFloat::x87DoubleExtended())
4591 return false;
4592 return true;
4593 };
4594 if (!IsAllowedValueType(ValType, ArithAllows)) {
4595 auto DID = ArithAllows & AOEVT_FP
4596 ? (ArithAllows & AOEVT_Pointer
4597 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4598 : diag::err_atomic_op_needs_atomic_int_or_fp)
4599 : diag::err_atomic_op_needs_atomic_int;
4600 Diag(ExprRange.getBegin(), DID)
4601 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4602 return ExprError();
4603 }
4604 if (IsC11 && ValType->isPointerType() &&
4606 diag::err_incomplete_type)) {
4607 return ExprError();
4608 }
4609 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4610 // For __atomic_*_n operations, the value type must be a scalar integral or
4611 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4612 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4613 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4614 return ExprError();
4615 }
4616
4617 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4618 !AtomTy->isScalarType()) {
4619 // For GNU atomics, require a trivially-copyable type. This is not part of
4620 // the GNU atomics specification but we enforce it for consistency with
4621 // other atomics which generally all require a trivially-copyable type. This
4622 // is because atomics just copy bits.
4623 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4624 << Ptr->getType() << Ptr->getSourceRange();
4625 return ExprError();
4626 }
4627
4628 switch (ValType.getObjCLifetime()) {
4631 // okay
4632 break;
4633
4637 // FIXME: Can this happen? By this point, ValType should be known
4638 // to be trivially copyable.
4639 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4640 << ValType << Ptr->getSourceRange();
4641 return ExprError();
4642 }
4643
4644 // All atomic operations have an overload which takes a pointer to a volatile
4645 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4646 // into the result or the other operands. Similarly atomic_load takes a
4647 // pointer to a const 'A'.
4648 ValType.removeLocalVolatile();
4649 ValType.removeLocalConst();
4650 QualType ResultType = ValType;
4651 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4652 Form == ClearByte)
4653 ResultType = Context.VoidTy;
4654 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4655 ResultType = Context.BoolTy;
4656
4657 // The type of a parameter passed 'by value'. In the GNU atomics, such
4658 // arguments are actually passed as pointers.
4659 QualType ByValType = ValType; // 'CP'
4660 bool IsPassedByAddress = false;
4661 if (!IsC11 && !IsHIP && !IsN) {
4662 ByValType = Ptr->getType();
4663 IsPassedByAddress = true;
4664 }
4665
4666 SmallVector<Expr *, 5> APIOrderedArgs;
4667 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4668 APIOrderedArgs.push_back(Args[0]);
4669 switch (Form) {
4670 case Init:
4671 case Load:
4672 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4673 break;
4674 case LoadCopy:
4675 case Copy:
4676 case Arithmetic:
4677 case Xchg:
4678 APIOrderedArgs.push_back(Args[2]); // Val1
4679 APIOrderedArgs.push_back(Args[1]); // Order
4680 break;
4681 case GNUXchg:
4682 APIOrderedArgs.push_back(Args[2]); // Val1
4683 APIOrderedArgs.push_back(Args[3]); // Val2
4684 APIOrderedArgs.push_back(Args[1]); // Order
4685 break;
4686 case C11CmpXchg:
4687 APIOrderedArgs.push_back(Args[2]); // Val1
4688 APIOrderedArgs.push_back(Args[4]); // Val2
4689 APIOrderedArgs.push_back(Args[1]); // Order
4690 APIOrderedArgs.push_back(Args[3]); // OrderFail
4691 break;
4692 case GNUCmpXchg:
4693 APIOrderedArgs.push_back(Args[2]); // Val1
4694 APIOrderedArgs.push_back(Args[4]); // Val2
4695 APIOrderedArgs.push_back(Args[5]); // Weak
4696 APIOrderedArgs.push_back(Args[1]); // Order
4697 APIOrderedArgs.push_back(Args[3]); // OrderFail
4698 break;
4699 case TestAndSetByte:
4700 case ClearByte:
4701 APIOrderedArgs.push_back(Args[1]); // Order
4702 break;
4703 }
4704 } else
4705 APIOrderedArgs.append(Args.begin(), Args.end());
4706
4707 // The first argument's non-CV pointer type is used to deduce the type of
4708 // subsequent arguments, except for:
4709 // - weak flag (always converted to bool)
4710 // - memory order (always converted to int)
4711 // - scope (always converted to int)
4712 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4713 QualType Ty;
4714 if (i < NumVals[Form] + 1) {
4715 switch (i) {
4716 case 0:
4717 // The first argument is always a pointer. It has a fixed type.
4718 // It is always dereferenced, a nullptr is undefined.
4719 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4720 // Nothing else to do: we already know all we want about this pointer.
4721 continue;
4722 case 1:
4723 // The second argument is the non-atomic operand. For arithmetic, this
4724 // is always passed by value, and for a compare_exchange it is always
4725 // passed by address. For the rest, GNU uses by-address and C11 uses
4726 // by-value.
4727 assert(Form != Load);
4728 if (Form == Arithmetic && ValType->isPointerType())
4729 Ty = Context.getPointerDiffType();
4730 else if (Form == Init || Form == Arithmetic)
4731 Ty = ValType;
4732 else if (Form == Copy || Form == Xchg) {
4733 if (IsPassedByAddress) {
4734 // The value pointer is always dereferenced, a nullptr is undefined.
4735 CheckNonNullArgument(*this, APIOrderedArgs[i],
4736 ExprRange.getBegin());
4737 }
4738 Ty = ByValType;
4739 } else {
4740 Expr *ValArg = APIOrderedArgs[i];
4741 // The value pointer is always dereferenced, a nullptr is undefined.
4742 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4744 // Keep address space of non-atomic pointer type.
4745 if (const PointerType *PtrTy =
4746 ValArg->getType()->getAs<PointerType>()) {
4747 AS = PtrTy->getPointeeType().getAddressSpace();
4748 }
4749 Ty = Context.getPointerType(
4750 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4751 }
4752 break;
4753 case 2:
4754 // The third argument to compare_exchange / GNU exchange is the desired
4755 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4756 if (IsPassedByAddress)
4757 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4758 Ty = ByValType;
4759 break;
4760 case 3:
4761 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4762 Ty = Context.BoolTy;
4763 break;
4764 }
4765 } else {
4766 // The order(s) and scope are always converted to int.
4767 Ty = Context.IntTy;
4768 }
4769
4770 InitializedEntity Entity =
4772 ExprResult Arg = APIOrderedArgs[i];
4773 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4774 if (Arg.isInvalid())
4775 return true;
4776 APIOrderedArgs[i] = Arg.get();
4777 }
4778
4779 // Permute the arguments into a 'consistent' order.
4780 SmallVector<Expr*, 5> SubExprs;
4781 SubExprs.push_back(Ptr);
4782 switch (Form) {
4783 case Init:
4784 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4785 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4786 break;
4787 case Load:
4788 case TestAndSetByte:
4789 case ClearByte:
4790 SubExprs.push_back(APIOrderedArgs[1]); // Order
4791 break;
4792 case LoadCopy:
4793 case Copy:
4794 case Arithmetic:
4795 case Xchg:
4796 SubExprs.push_back(APIOrderedArgs[2]); // Order
4797 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4798 break;
4799 case GNUXchg:
4800 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4801 SubExprs.push_back(APIOrderedArgs[3]); // Order
4802 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4803 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4804 break;
4805 case C11CmpXchg:
4806 SubExprs.push_back(APIOrderedArgs[3]); // Order
4807 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4808 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4809 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4810 break;
4811 case GNUCmpXchg:
4812 SubExprs.push_back(APIOrderedArgs[4]); // Order
4813 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4814 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4815 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4816 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4817 break;
4818 }
4819
4820 // If the memory orders are constants, check they are valid.
4821 if (SubExprs.size() >= 2 && Form != Init) {
4822 std::optional<llvm::APSInt> Success =
4823 SubExprs[1]->getIntegerConstantExpr(Context);
4824 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4825 Diag(SubExprs[1]->getBeginLoc(),
4826 diag::warn_atomic_op_has_invalid_memory_order)
4827 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4828 << SubExprs[1]->getSourceRange();
4829 }
4830 if (SubExprs.size() >= 5) {
4831 if (std::optional<llvm::APSInt> Failure =
4832 SubExprs[3]->getIntegerConstantExpr(Context)) {
4833 if (!llvm::is_contained(
4834 {llvm::AtomicOrderingCABI::relaxed,
4835 llvm::AtomicOrderingCABI::consume,
4836 llvm::AtomicOrderingCABI::acquire,
4837 llvm::AtomicOrderingCABI::seq_cst},
4838 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4839 Diag(SubExprs[3]->getBeginLoc(),
4840 diag::warn_atomic_op_has_invalid_memory_order)
4841 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4842 }
4843 }
4844 }
4845 }
4846
4847 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4848 auto *Scope = Args[Args.size() - 1];
4849 if (std::optional<llvm::APSInt> Result =
4850 Scope->getIntegerConstantExpr(Context)) {
4851 if (!ScopeModel->isValid(Result->getZExtValue()))
4852 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4853 << Scope->getSourceRange();
4854 }
4855 SubExprs.push_back(Scope);
4856 }
4857
4858 AtomicExpr *AE = new (Context)
4859 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4860
4861 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4862 Op == AtomicExpr::AO__c11_atomic_store ||
4863 Op == AtomicExpr::AO__opencl_atomic_load ||
4864 Op == AtomicExpr::AO__hip_atomic_load ||
4865 Op == AtomicExpr::AO__opencl_atomic_store ||
4866 Op == AtomicExpr::AO__hip_atomic_store) &&
4867 Context.AtomicUsesUnsupportedLibcall(AE))
4868 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4869 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4870 Op == AtomicExpr::AO__opencl_atomic_load ||
4871 Op == AtomicExpr::AO__hip_atomic_load)
4872 ? 0
4873 : 1);
4874
4875 if (ValType->isBitIntType()) {
4876 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4877 return ExprError();
4878 }
4879
4880 return AE;
4881}
4882
4883/// checkBuiltinArgument - Given a call to a builtin function, perform
4884/// normal type-checking on the given argument, updating the call in
4885/// place. This is useful when a builtin function requires custom
4886/// type-checking for some of its arguments but not necessarily all of
4887/// them.
4888///
4889/// Returns true on error.
4890static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4891 FunctionDecl *Fn = E->getDirectCallee();
4892 assert(Fn && "builtin call without direct callee!");
4893
4894 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4895 InitializedEntity Entity =
4897
4898 ExprResult Arg = E->getArg(ArgIndex);
4899 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4900 if (Arg.isInvalid())
4901 return true;
4902
4903 E->setArg(ArgIndex, Arg.get());
4904 return false;
4905}
4906
4907ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4908 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4909 Expr *Callee = TheCall->getCallee();
4910 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4911 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4912
4913 // Ensure that we have at least one argument to do type inference from.
4914 if (TheCall->getNumArgs() < 1) {
4915 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4916 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4917 << Callee->getSourceRange();
4918 return ExprError();
4919 }
4920
4921 // Inspect the first argument of the atomic builtin. This should always be
4922 // a pointer type, whose element is an integral scalar or pointer type.
4923 // Because it is a pointer type, we don't have to worry about any implicit
4924 // casts here.
4925 // FIXME: We don't allow floating point scalars as input.
4926 Expr *FirstArg = TheCall->getArg(0);
4927 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4928 if (FirstArgResult.isInvalid())
4929 return ExprError();
4930 FirstArg = FirstArgResult.get();
4931 TheCall->setArg(0, FirstArg);
4932
4933 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4934 if (!pointerType) {
4935 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4936 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4937 return ExprError();
4938 }
4939
4940 QualType ValType = pointerType->getPointeeType();
4941 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4942 !ValType->isBlockPointerType()) {
4943 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4944 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4945 return ExprError();
4946 }
4947 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4948 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4949 Diag(FirstArg->getBeginLoc(),
4950 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4951 << 1 << ValType << FirstArg->getSourceRange();
4952 return ExprError();
4953 }
4954
4955 if (ValType.isConstQualified()) {
4956 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4957 << FirstArg->getType() << FirstArg->getSourceRange();
4958 return ExprError();
4959 }
4960
4961 switch (ValType.getObjCLifetime()) {
4964 // okay
4965 break;
4966
4970 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4971 << ValType << FirstArg->getSourceRange();
4972 return ExprError();
4973 }
4974
4975 // Strip any qualifiers off ValType.
4976 ValType = ValType.getUnqualifiedType();
4977
4978 // The majority of builtins return a value, but a few have special return
4979 // types, so allow them to override appropriately below.
4980 QualType ResultType = ValType;
4981
4982 // We need to figure out which concrete builtin this maps onto. For example,
4983 // __sync_fetch_and_add with a 2 byte object turns into
4984 // __sync_fetch_and_add_2.
4985#define BUILTIN_ROW(x) \
4986 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4987 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4988
4989 static const unsigned BuiltinIndices[][5] = {
4990 BUILTIN_ROW(__sync_fetch_and_add),
4991 BUILTIN_ROW(__sync_fetch_and_sub),
4992 BUILTIN_ROW(__sync_fetch_and_or),
4993 BUILTIN_ROW(__sync_fetch_and_and),
4994 BUILTIN_ROW(__sync_fetch_and_xor),
4995 BUILTIN_ROW(__sync_fetch_and_nand),
4996
4997 BUILTIN_ROW(__sync_add_and_fetch),
4998 BUILTIN_ROW(__sync_sub_and_fetch),
4999 BUILTIN_ROW(__sync_and_and_fetch),
5000 BUILTIN_ROW(__sync_or_and_fetch),
5001 BUILTIN_ROW(__sync_xor_and_fetch),
5002 BUILTIN_ROW(__sync_nand_and_fetch),
5003
5004 BUILTIN_ROW(__sync_val_compare_and_swap),
5005 BUILTIN_ROW(__sync_bool_compare_and_swap),
5006 BUILTIN_ROW(__sync_lock_test_and_set),
5007 BUILTIN_ROW(__sync_lock_release),
5008 BUILTIN_ROW(__sync_swap)
5009 };
5010#undef BUILTIN_ROW
5011
5012 // Determine the index of the size.
5013 unsigned SizeIndex;
5014 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5015 case 1: SizeIndex = 0; break;
5016 case 2: SizeIndex = 1; break;
5017 case 4: SizeIndex = 2; break;
5018 case 8: SizeIndex = 3; break;
5019 case 16: SizeIndex = 4; break;
5020 default:
5021 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5022 << FirstArg->getType() << FirstArg->getSourceRange();
5023 return ExprError();
5024 }
5025
5026 // Each of these builtins has one pointer argument, followed by some number of
5027 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5028 // that we ignore. Find out which row of BuiltinIndices to read from as well
5029 // as the number of fixed args.
5030 unsigned BuiltinID = FDecl->getBuiltinID();
5031 unsigned BuiltinIndex, NumFixed = 1;
5032 bool WarnAboutSemanticsChange = false;
5033 switch (BuiltinID) {
5034 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5035 case Builtin::BI__sync_fetch_and_add:
5036 case Builtin::BI__sync_fetch_and_add_1:
5037 case Builtin::BI__sync_fetch_and_add_2:
5038 case Builtin::BI__sync_fetch_and_add_4:
5039 case Builtin::BI__sync_fetch_and_add_8:
5040 case Builtin::BI__sync_fetch_and_add_16:
5041 BuiltinIndex = 0;
5042 break;
5043
5044 case Builtin::BI__sync_fetch_and_sub:
5045 case Builtin::BI__sync_fetch_and_sub_1:
5046 case Builtin::BI__sync_fetch_and_sub_2:
5047 case Builtin::BI__sync_fetch_and_sub_4:
5048 case Builtin::BI__sync_fetch_and_sub_8:
5049 case Builtin::BI__sync_fetch_and_sub_16:
5050 BuiltinIndex = 1;
5051 break;
5052
5053 case Builtin::BI__sync_fetch_and_or:
5054 case Builtin::BI__sync_fetch_and_or_1:
5055 case Builtin::BI__sync_fetch_and_or_2:
5056 case Builtin::BI__sync_fetch_and_or_4:
5057 case Builtin::BI__sync_fetch_and_or_8:
5058 case Builtin::BI__sync_fetch_and_or_16:
5059 BuiltinIndex = 2;
5060 break;
5061
5062 case Builtin::BI__sync_fetch_and_and:
5063 case Builtin::BI__sync_fetch_and_and_1:
5064 case Builtin::BI__sync_fetch_and_and_2:
5065 case Builtin::BI__sync_fetch_and_and_4:
5066 case Builtin::BI__sync_fetch_and_and_8:
5067 case Builtin::BI__sync_fetch_and_and_16:
5068 BuiltinIndex = 3;
5069 break;
5070
5071 case Builtin::BI__sync_fetch_and_xor:
5072 case Builtin::BI__sync_fetch_and_xor_1:
5073 case Builtin::BI__sync_fetch_and_xor_2:
5074 case Builtin::BI__sync_fetch_and_xor_4:
5075 case Builtin::BI__sync_fetch_and_xor_8:
5076 case Builtin::BI__sync_fetch_and_xor_16:
5077 BuiltinIndex = 4;
5078 break;
5079
5080 case Builtin::BI__sync_fetch_and_nand:
5081 case Builtin::BI__sync_fetch_and_nand_1:
5082 case Builtin::BI__sync_fetch_and_nand_2:
5083 case Builtin::BI__sync_fetch_and_nand_4:
5084 case Builtin::BI__sync_fetch_and_nand_8:
5085 case Builtin::BI__sync_fetch_and_nand_16:
5086 BuiltinIndex = 5;
5087 WarnAboutSemanticsChange = true;
5088 break;
5089
5090 case Builtin::BI__sync_add_and_fetch:
5091 case Builtin::BI__sync_add_and_fetch_1:
5092 case Builtin::BI__sync_add_and_fetch_2:
5093 case Builtin::BI__sync_add_and_fetch_4:
5094 case Builtin::BI__sync_add_and_fetch_8:
5095 case Builtin::BI__sync_add_and_fetch_16:
5096 BuiltinIndex = 6;
5097 break;
5098
5099 case Builtin::BI__sync_sub_and_fetch:
5100 case Builtin::BI__sync_sub_and_fetch_1:
5101 case Builtin::BI__sync_sub_and_fetch_2:
5102 case Builtin::BI__sync_sub_and_fetch_4:
5103 case Builtin::BI__sync_sub_and_fetch_8:
5104 case Builtin::BI__sync_sub_and_fetch_16:
5105 BuiltinIndex = 7;
5106 break;
5107
5108 case Builtin::BI__sync_and_and_fetch:
5109 case Builtin::BI__sync_and_and_fetch_1:
5110 case Builtin::BI__sync_and_and_fetch_2:
5111 case Builtin::BI__sync_and_and_fetch_4:
5112 case Builtin::BI__sync_and_and_fetch_8:
5113 case Builtin::BI__sync_and_and_fetch_16:
5114 BuiltinIndex = 8;
5115 break;
5116
5117 case Builtin::BI__sync_or_and_fetch:
5118 case Builtin::BI__sync_or_and_fetch_1:
5119 case Builtin::BI__sync_or_and_fetch_2:
5120 case Builtin::BI__sync_or_and_fetch_4:
5121 case Builtin::BI__sync_or_and_fetch_8:
5122 case Builtin::BI__sync_or_and_fetch_16:
5123 BuiltinIndex = 9;
5124 break;
5125
5126 case Builtin::BI__sync_xor_and_fetch:
5127 case Builtin::BI__sync_xor_and_fetch_1:
5128 case Builtin::BI__sync_xor_and_fetch_2:
5129 case Builtin::BI__sync_xor_and_fetch_4:
5130 case Builtin::BI__sync_xor_and_fetch_8:
5131 case Builtin::BI__sync_xor_and_fetch_16:
5132 BuiltinIndex = 10;
5133 break;
5134
5135 case Builtin::BI__sync_nand_and_fetch:
5136 case Builtin::BI__sync_nand_and_fetch_1:
5137 case Builtin::BI__sync_nand_and_fetch_2:
5138 case Builtin::BI__sync_nand_and_fetch_4:
5139 case Builtin::BI__sync_nand_and_fetch_8:
5140 case Builtin::BI__sync_nand_and_fetch_16:
5141 BuiltinIndex = 11;
5142 WarnAboutSemanticsChange = true;
5143 break;
5144
5145 case Builtin::BI__sync_val_compare_and_swap:
5146 case Builtin::BI__sync_val_compare_and_swap_1:
5147 case Builtin::BI__sync_val_compare_and_swap_2:
5148 case Builtin::BI__sync_val_compare_and_swap_4:
5149 case Builtin::BI__sync_val_compare_and_swap_8:
5150 case Builtin::BI__sync_val_compare_and_swap_16:
5151 BuiltinIndex = 12;
5152 NumFixed = 2;
5153 break;
5154
5155 case Builtin::BI__sync_bool_compare_and_swap:
5156 case Builtin::BI__sync_bool_compare_and_swap_1:
5157 case Builtin::BI__sync_bool_compare_and_swap_2:
5158 case Builtin::BI__sync_bool_compare_and_swap_4:
5159 case Builtin::BI__sync_bool_compare_and_swap_8:
5160 case Builtin::BI__sync_bool_compare_and_swap_16:
5161 BuiltinIndex = 13;
5162 NumFixed = 2;
5163 ResultType = Context.BoolTy;
5164 break;
5165
5166 case Builtin::BI__sync_lock_test_and_set:
5167 case Builtin::BI__sync_lock_test_and_set_1:
5168 case Builtin::BI__sync_lock_test_and_set_2:
5169 case Builtin::BI__sync_lock_test_and_set_4:
5170 case Builtin::BI__sync_lock_test_and_set_8:
5171 case Builtin::BI__sync_lock_test_and_set_16:
5172 BuiltinIndex = 14;
5173 break;
5174
5175 case Builtin::BI__sync_lock_release:
5176 case Builtin::BI__sync_lock_release_1:
5177 case Builtin::BI__sync_lock_release_2:
5178 case Builtin::BI__sync_lock_release_4:
5179 case Builtin::BI__sync_lock_release_8:
5180 case Builtin::BI__sync_lock_release_16:
5181 BuiltinIndex = 15;
5182 NumFixed = 0;
5183 ResultType = Context.VoidTy;
5184 break;
5185
5186 case Builtin::BI__sync_swap:
5187 case Builtin::BI__sync_swap_1:
5188 case Builtin::BI__sync_swap_2:
5189 case Builtin::BI__sync_swap_4:
5190 case Builtin::BI__sync_swap_8:
5191 case Builtin::BI__sync_swap_16:
5192 BuiltinIndex = 16;
5193 break;
5194 }
5195
5196 // Now that we know how many fixed arguments we expect, first check that we
5197 // have at least that many.
5198 if (TheCall->getNumArgs() < 1+NumFixed) {
5199 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5200 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5201 << Callee->getSourceRange();
5202 return ExprError();
5203 }
5204
5205 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5206 << Callee->getSourceRange();
5207
5208 if (WarnAboutSemanticsChange) {
5209 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5210 << Callee->getSourceRange();
5211 }
5212
5213 // Get the decl for the concrete builtin from this, we can tell what the
5214 // concrete integer type we should convert to is.
5215 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5216 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5217 FunctionDecl *NewBuiltinDecl;
5218 if (NewBuiltinID == BuiltinID)
5219 NewBuiltinDecl = FDecl;
5220 else {
5221 // Perform builtin lookup to avoid redeclaring it.
5222 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5223 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5224 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5225 assert(Res.getFoundDecl());
5226 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5227 if (!NewBuiltinDecl)
5228 return ExprError();
5229 }
5230
5231 // The first argument --- the pointer --- has a fixed type; we
5232 // deduce the types of the rest of the arguments accordingly. Walk
5233 // the remaining arguments, converting them to the deduced value type.
5234 for (unsigned i = 0; i != NumFixed; ++i) {
5235 ExprResult Arg = TheCall->getArg(i+1);
5236
5237 // GCC does an implicit conversion to the pointer or integer ValType. This
5238 // can fail in some cases (1i -> int**), check for this error case now.
5239 // Initialize the argument.
5240 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5241 ValType, /*consume*/ false);
5242 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5243 if (Arg.isInvalid())
5244 return ExprError();
5245
5246 // Okay, we have something that *can* be converted to the right type. Check
5247 // to see if there is a potentially weird extension going on here. This can
5248 // happen when you do an atomic operation on something like an char* and
5249 // pass in 42. The 42 gets converted to char. This is even more strange
5250 // for things like 45.123 -> char, etc.
5251 // FIXME: Do this check.
5252 TheCall->setArg(i+1, Arg.get());
5253 }
5254
5255 // Create a new DeclRefExpr to refer to the new decl.
5256 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5257 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5258 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5259 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5260
5261 // Set the callee in the CallExpr.
5262 // FIXME: This loses syntactic information.
5263 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5264 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5265 CK_BuiltinFnToFnPtr);
5266 TheCall->setCallee(PromotedCall.get());
5267
5268 // Change the result type of the call to match the original value type. This
5269 // is arbitrary, but the codegen for these builtins ins design to handle it
5270 // gracefully.
5271 TheCall->setType(ResultType);
5272
5273 // Prohibit problematic uses of bit-precise integer types with atomic
5274 // builtins. The arguments would have already been converted to the first
5275 // argument's type, so only need to check the first argument.
5276 const auto *BitIntValType = ValType->getAs<BitIntType>();
5277 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5278 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5279 return ExprError();
5280 }
5281
5282 return TheCallResult;
5283}
5284
5285ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5286 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5287 DeclRefExpr *DRE =
5289 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5290 unsigned BuiltinID = FDecl->getBuiltinID();
5291 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5292 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5293 "Unexpected nontemporal load/store builtin!");
5294 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5295 unsigned numArgs = isStore ? 2 : 1;
5296
5297 // Ensure that we have the proper number of arguments.
5298 if (checkArgCount(TheCall, numArgs))
5299 return ExprError();
5300
5301 // Inspect the last argument of the nontemporal builtin. This should always
5302 // be a pointer type, from which we imply the type of the memory access.
5303 // Because it is a pointer type, we don't have to worry about any implicit
5304 // casts here.
5305 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5306 ExprResult PointerArgResult =
5308
5309 if (PointerArgResult.isInvalid())
5310 return ExprError();
5311 PointerArg = PointerArgResult.get();
5312 TheCall->setArg(numArgs - 1, PointerArg);
5313
5314 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5315 if (!pointerType) {
5316 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5317 << PointerArg->getType() << PointerArg->getSourceRange();
5318 return ExprError();
5319 }
5320
5321 QualType ValType = pointerType->getPointeeType();
5322
5323 // Strip any qualifiers off ValType.
5324 ValType = ValType.getUnqualifiedType();
5325 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5326 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5327 !ValType->isVectorType()) {
5328 Diag(DRE->getBeginLoc(),
5329 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5330 << PointerArg->getType() << PointerArg->getSourceRange();
5331 return ExprError();
5332 }
5333
5334 if (!isStore) {
5335 TheCall->setType(ValType);
5336 return TheCallResult;
5337 }
5338
5339 ExprResult ValArg = TheCall->getArg(0);
5340 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5341 Context, ValType, /*consume*/ false);
5342 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5343 if (ValArg.isInvalid())
5344 return ExprError();
5345
5346 TheCall->setArg(0, ValArg.get());
5347 TheCall->setType(Context.VoidTy);
5348 return TheCallResult;
5349}
5350
5351/// CheckObjCString - Checks that the format string argument to the os_log()
5352/// and os_trace() functions is correct, and converts it to const char *.
5353ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5354 Arg = Arg->IgnoreParenCasts();
5355 auto *Literal = dyn_cast<StringLiteral>(Arg);
5356 if (!Literal) {
5357 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5358 Literal = ObjcLiteral->getString();
5359 }
5360 }
5361
5362 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5363 return ExprError(
5364 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5365 << Arg->getSourceRange());
5366 }
5367
5368 ExprResult Result(Literal);
5369 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5370 InitializedEntity Entity =
5372 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5373 return Result;
5374}
5375
5376/// Check that the user is calling the appropriate va_start builtin for the
5377/// target and calling convention.
5378static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5379 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5380 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5381 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5382 TT.getArch() == llvm::Triple::aarch64_32);
5383 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5384 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5385 if (IsX64 || IsAArch64) {
5386 CallingConv CC = CC_C;
5387 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5388 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5389 if (IsMSVAStart) {
5390 // Don't allow this in System V ABI functions.
5391 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5392 return S.Diag(Fn->getBeginLoc(),
5393 diag::err_ms_va_start_used_in_sysv_function);
5394 } else {
5395 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5396 // On x64 Windows, don't allow this in System V ABI functions.
5397 // (Yes, that means there's no corresponding way to support variadic
5398 // System V ABI functions on Windows.)
5399 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5400 (!IsWindowsOrUEFI && CC == CC_Win64))
5401 return S.Diag(Fn->getBeginLoc(),
5402 diag::err_va_start_used_in_wrong_abi_function)
5403 << !IsWindowsOrUEFI;
5404 }
5405 return false;
5406 }
5407
5408 if (IsMSVAStart)
5409 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5410 return false;
5411}
5412
5414 ParmVarDecl **LastParam = nullptr) {
5415 // Determine whether the current function, block, or obj-c method is variadic
5416 // and get its parameter list.
5417 bool IsVariadic = false;
5419 DeclContext *Caller = S.CurContext;
5420 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5421 IsVariadic = Block->isVariadic();
5422 Params = Block->parameters();
5423 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5424 IsVariadic = FD->isVariadic();
5425 Params = FD->parameters();
5426 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5427 IsVariadic = MD->isVariadic();
5428 // FIXME: This isn't correct for methods (results in bogus warning).
5429 Params = MD->parameters();
5430 } else if (isa<CapturedDecl>(Caller)) {
5431 // We don't support va_start in a CapturedDecl.
5432 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5433 return true;
5434 } else {
5435 // This must be some other declcontext that parses exprs.
5436 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5437 return true;
5438 }
5439
5440 if (!IsVariadic) {
5441 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5442 return true;
5443 }
5444
5445 if (LastParam)
5446 *LastParam = Params.empty() ? nullptr : Params.back();
5447
5448 return false;
5449}
5450
5451bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5452 Expr *Fn = TheCall->getCallee();
5453 if (checkVAStartABI(*this, BuiltinID, Fn))
5454 return true;
5455
5456 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5457 // This builtin requires one argument (the va_list), allows two arguments,
5458 // but diagnoses more than two arguments. e.g.,
5459 // __builtin_c23_va_start(); // error
5460 // __builtin_c23_va_start(list); // ok
5461 // __builtin_c23_va_start(list, param); // ok
5462 // __builtin_c23_va_start(list, anything, anything); // error
5463 // This differs from the GCC behavior in that they accept the last case
5464 // with a warning, but it doesn't seem like a useful behavior to allow.
5465 if (checkArgCountRange(TheCall, 1, 2))
5466 return true;
5467 } else {
5468 // In C23 mode, va_start only needs one argument. However, the builtin still
5469 // requires two arguments (which matches the behavior of the GCC builtin),
5470 // <stdarg.h> passes `0` as the second argument in C23 mode.
5471 if (checkArgCount(TheCall, 2))
5472 return true;
5473 }
5474
5475 // Type-check the first argument normally.
5476 if (checkBuiltinArgument(*this, TheCall, 0))
5477 return true;
5478
5479 // Check that the current function is variadic, and get its last parameter.
5480 ParmVarDecl *LastParam;
5481 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5482 return true;
5483
5484 // Verify that the second argument to the builtin is the last non-variadic
5485 // argument of the current function or method. In C23 mode, if the call is
5486 // not to __builtin_c23_va_start, and the second argument is an integer
5487 // constant expression with value 0, then we don't bother with this check.
5488 // For __builtin_c23_va_start, we only perform the check for the second
5489 // argument being the last argument to the current function if there is a
5490 // second argument present.
5491 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5492 TheCall->getNumArgs() < 2) {
5493 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5494 return false;
5495 }
5496
5497 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5498 if (std::optional<llvm::APSInt> Val =
5500 Val && LangOpts.C23 && *Val == 0 &&
5501 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5502 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5503 return false;
5504 }
5505
5506 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5507 // next block.
5508 QualType Type;
5509 SourceLocation ParamLoc;
5510 bool IsCRegister = false;
5511 bool SecondArgIsLastNonVariadicArgument = false;
5512 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5513 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5514 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5515
5516 Type = PV->getType();
5517 ParamLoc = PV->getLocation();
5518 IsCRegister =
5519 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5520 }
5521 }
5522
5523 if (!SecondArgIsLastNonVariadicArgument)
5524 Diag(TheCall->getArg(1)->getBeginLoc(),
5525 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5526 else if (IsCRegister || Type->isReferenceType() ||
5527 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5528 // Promotable integers are UB, but enumerations need a bit of
5529 // extra checking to see what their promotable type actually is.
5530 if (!Context.isPromotableIntegerType(Type))
5531 return false;
5532 const auto *ED = Type->getAsEnumDecl();
5533 if (!ED)
5534 return true;
5535 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5536 }()) {
5537 unsigned Reason = 0;
5538 if (Type->isReferenceType()) Reason = 1;
5539 else if (IsCRegister) Reason = 2;
5540 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5541 Diag(ParamLoc, diag::note_parameter_type) << Type;
5542 }
5543
5544 return false;
5545}
5546
5547bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5548 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5549 const LangOptions &LO = getLangOpts();
5550
5551 if (LO.CPlusPlus)
5552 return Arg->getType()
5554 .getTypePtr()
5555 ->getPointeeType()
5557
5558 // In C, allow aliasing through `char *`, this is required for AArch64 at
5559 // least.
5560 return true;
5561 };
5562
5563 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5564 // const char *named_addr);
5565
5566 Expr *Func = Call->getCallee();
5567
5568 if (Call->getNumArgs() < 3)
5569 return Diag(Call->getEndLoc(),
5570 diag::err_typecheck_call_too_few_args_at_least)
5571 << 0 /*function call*/ << 3 << Call->getNumArgs()
5572 << /*is non object*/ 0;
5573
5574 // Type-check the first argument normally.
5575 if (checkBuiltinArgument(*this, Call, 0))
5576 return true;
5577
5578 // Check that the current function is variadic.
5580 return true;
5581
5582 // __va_start on Windows does not validate the parameter qualifiers
5583
5584 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5585 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5586
5587 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5588 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5589
5590 const QualType &ConstCharPtrTy =
5591 Context.getPointerType(Context.CharTy.withConst());
5592 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5593 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5594 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5595 << 0 /* qualifier difference */
5596 << 3 /* parameter mismatch */
5597 << 2 << Arg1->getType() << ConstCharPtrTy;
5598
5599 const QualType SizeTy = Context.getSizeType();
5600 if (!Context.hasSameType(
5602 SizeTy))
5603 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5604 << Arg2->getType() << SizeTy << 1 /* different class */
5605 << 0 /* qualifier difference */
5606 << 3 /* parameter mismatch */
5607 << 3 << Arg2->getType() << SizeTy;
5608
5609 return false;
5610}
5611
5612bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5613 if (checkArgCount(TheCall, 2))
5614 return true;
5615
5616 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5617 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5618 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5619 << 1 << 0 << TheCall->getSourceRange();
5620
5621 ExprResult OrigArg0 = TheCall->getArg(0);
5622 ExprResult OrigArg1 = TheCall->getArg(1);
5623
5624 // Do standard promotions between the two arguments, returning their common
5625 // type.
5626 QualType Res = UsualArithmeticConversions(
5627 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5628 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5629 return true;
5630
5631 // Make sure any conversions are pushed back into the call; this is
5632 // type safe since unordered compare builtins are declared as "_Bool
5633 // foo(...)".
5634 TheCall->setArg(0, OrigArg0.get());
5635 TheCall->setArg(1, OrigArg1.get());
5636
5637 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5638 return false;
5639
5640 // If the common type isn't a real floating type, then the arguments were
5641 // invalid for this operation.
5642 if (Res.isNull() || !Res->isRealFloatingType())
5643 return Diag(OrigArg0.get()->getBeginLoc(),
5644 diag::err_typecheck_call_invalid_ordered_compare)
5645 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5646 << SourceRange(OrigArg0.get()->getBeginLoc(),
5647 OrigArg1.get()->getEndLoc());
5648
5649 return false;
5650}
5651
5652bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5653 unsigned BuiltinID) {
5654 if (checkArgCount(TheCall, NumArgs))
5655 return true;
5656
5657 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5658 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5659 BuiltinID == Builtin::BI__builtin_isinf ||
5660 BuiltinID == Builtin::BI__builtin_isinf_sign))
5661 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5662 << 0 << 0 << TheCall->getSourceRange();
5663
5664 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5665 BuiltinID == Builtin::BI__builtin_isunordered))
5666 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5667 << 1 << 0 << TheCall->getSourceRange();
5668
5669 bool IsFPClass = NumArgs == 2;
5670
5671 // Find out position of floating-point argument.
5672 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5673
5674 // We can count on all parameters preceding the floating-point just being int.
5675 // Try all of those.
5676 for (unsigned i = 0; i < FPArgNo; ++i) {
5677 Expr *Arg = TheCall->getArg(i);
5678
5679 if (Arg->isTypeDependent())
5680 return false;
5681
5684
5685 if (Res.isInvalid())
5686 return true;
5687 TheCall->setArg(i, Res.get());
5688 }
5689
5690 Expr *OrigArg = TheCall->getArg(FPArgNo);
5691
5692 if (OrigArg->isTypeDependent())
5693 return false;
5694
5695 // Usual Unary Conversions will convert half to float, which we want for
5696 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5697 // type how it is, but do normal L->Rvalue conversions.
5698 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5699 ExprResult Res = UsualUnaryConversions(OrigArg);
5700
5701 if (!Res.isUsable())
5702 return true;
5703 OrigArg = Res.get();
5704 } else {
5706
5707 if (!Res.isUsable())
5708 return true;
5709 OrigArg = Res.get();
5710 }
5711 TheCall->setArg(FPArgNo, OrigArg);
5712
5713 QualType VectorResultTy;
5714 QualType ElementTy = OrigArg->getType();
5715 // TODO: When all classification function are implemented with is_fpclass,
5716 // vector argument can be supported in all of them.
5717 if (ElementTy->isVectorType() && IsFPClass) {
5718 VectorResultTy = GetSignedVectorType(ElementTy);
5719 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5720 }
5721
5722 // This operation requires a non-_Complex floating-point number.
5723 if (!ElementTy->isRealFloatingType())
5724 return Diag(OrigArg->getBeginLoc(),
5725 diag::err_typecheck_call_invalid_unary_fp)
5726 << OrigArg->getType() << OrigArg->getSourceRange();
5727
5728 // __builtin_isfpclass has integer parameter that specify test mask. It is
5729 // passed in (...), so it should be analyzed completely here.
5730 if (IsFPClass)
5731 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5732 return true;
5733
5734 // TODO: enable this code to all classification functions.
5735 if (IsFPClass) {
5736 QualType ResultTy;
5737 if (!VectorResultTy.isNull())
5738 ResultTy = VectorResultTy;
5739 else
5740 ResultTy = Context.IntTy;
5741 TheCall->setType(ResultTy);
5742 }
5743
5744 return false;
5745}
5746
5747bool Sema::BuiltinComplex(CallExpr *TheCall) {
5748 if (checkArgCount(TheCall, 2))
5749 return true;
5750
5751 bool Dependent = false;
5752 for (unsigned I = 0; I != 2; ++I) {
5753 Expr *Arg = TheCall->getArg(I);
5754 QualType T = Arg->getType();
5755 if (T->isDependentType()) {
5756 Dependent = true;
5757 continue;
5758 }
5759
5760 // Despite supporting _Complex int, GCC requires a real floating point type
5761 // for the operands of __builtin_complex.
5762 if (!T->isRealFloatingType()) {
5763 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5764 << Arg->getType() << Arg->getSourceRange();
5765 }
5766
5767 ExprResult Converted = DefaultLvalueConversion(Arg);
5768 if (Converted.isInvalid())
5769 return true;
5770 TheCall->setArg(I, Converted.get());
5771 }
5772
5773 if (Dependent) {
5774 TheCall->setType(Context.DependentTy);
5775 return false;
5776 }
5777
5778 Expr *Real = TheCall->getArg(0);
5779 Expr *Imag = TheCall->getArg(1);
5780 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5781 return Diag(Real->getBeginLoc(),
5782 diag::err_typecheck_call_different_arg_types)
5783 << Real->getType() << Imag->getType()
5784 << Real->getSourceRange() << Imag->getSourceRange();
5785 }
5786
5787 TheCall->setType(Context.getComplexType(Real->getType()));
5788 return false;
5789}
5790
5791/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5792// This is declared to take (...), so we have to check everything.
5794 unsigned NumArgs = TheCall->getNumArgs();
5795 if (NumArgs < 2)
5796 return ExprError(Diag(TheCall->getEndLoc(),
5797 diag::err_typecheck_call_too_few_args_at_least)
5798 << 0 /*function call*/ << 2 << NumArgs
5799 << /*is non object*/ 0 << TheCall->getSourceRange());
5800
5801 // Determine which of the following types of shufflevector we're checking:
5802 // 1) unary, vector mask: (lhs, mask)
5803 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5804 QualType ResType = TheCall->getArg(0)->getType();
5805 unsigned NumElements = 0;
5806
5807 if (!TheCall->getArg(0)->isTypeDependent() &&
5808 !TheCall->getArg(1)->isTypeDependent()) {
5809 QualType LHSType = TheCall->getArg(0)->getType();
5810 QualType RHSType = TheCall->getArg(1)->getType();
5811
5812 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5813 return ExprError(
5814 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5815 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5816 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5817 TheCall->getArg(1)->getEndLoc()));
5818
5819 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5820 unsigned NumResElements = NumArgs - 2;
5821
5822 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5823 // with mask. If so, verify that RHS is an integer vector type with the
5824 // same number of elts as lhs.
5825 if (NumArgs == 2) {
5826 if (!RHSType->hasIntegerRepresentation() ||
5827 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5828 return ExprError(Diag(TheCall->getBeginLoc(),
5829 diag::err_vec_builtin_incompatible_vector)
5830 << TheCall->getDirectCallee()
5831 << /*isMoreThanTwoArgs*/ false
5832 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5833 TheCall->getArg(1)->getEndLoc()));
5834 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5835 return ExprError(Diag(TheCall->getBeginLoc(),
5836 diag::err_vec_builtin_incompatible_vector)
5837 << TheCall->getDirectCallee()
5838 << /*isMoreThanTwoArgs*/ false
5839 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5840 TheCall->getArg(1)->getEndLoc()));
5841 } else if (NumElements != NumResElements) {
5842 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5843 ResType = ResType->isExtVectorType()
5844 ? Context.getExtVectorType(EltType, NumResElements)
5845 : Context.getVectorType(EltType, NumResElements,
5847 }
5848 }
5849
5850 for (unsigned I = 2; I != NumArgs; ++I) {
5851 Expr *Arg = TheCall->getArg(I);
5852 if (Arg->isTypeDependent() || Arg->isValueDependent())
5853 continue;
5854
5855 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5856 if (!Result)
5857 return ExprError(Diag(TheCall->getBeginLoc(),
5858 diag::err_shufflevector_nonconstant_argument)
5859 << Arg->getSourceRange());
5860
5861 // Allow -1 which will be translated to undef in the IR.
5862 if (Result->isSigned() && Result->isAllOnes())
5863 ;
5864 else if (Result->getActiveBits() > 64 ||
5865 Result->getZExtValue() >= NumElements * 2)
5866 return ExprError(Diag(TheCall->getBeginLoc(),
5867 diag::err_shufflevector_argument_too_large)
5868 << Arg->getSourceRange());
5869
5870 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5871 }
5872
5873 auto *Result = new (Context) ShuffleVectorExpr(
5874 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5875 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5876
5877 // All moved to Result.
5878 TheCall->shrinkNumArgs(0);
5879 return Result;
5880}
5881
5883 SourceLocation BuiltinLoc,
5884 SourceLocation RParenLoc) {
5887 QualType DstTy = TInfo->getType();
5888 QualType SrcTy = E->getType();
5889
5890 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5891 return ExprError(Diag(BuiltinLoc,
5892 diag::err_convertvector_non_vector)
5893 << E->getSourceRange());
5894 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5895 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5896 << "second"
5897 << "__builtin_convertvector");
5898
5899 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5900 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5901 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5902 if (SrcElts != DstElts)
5903 return ExprError(Diag(BuiltinLoc,
5904 diag::err_convertvector_incompatible_vector)
5905 << E->getSourceRange());
5906 }
5907
5908 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5909 RParenLoc, CurFPFeatureOverrides());
5910}
5911
5912bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5913 unsigned NumArgs = TheCall->getNumArgs();
5914
5915 if (NumArgs > 3)
5916 return Diag(TheCall->getEndLoc(),
5917 diag::err_typecheck_call_too_many_args_at_most)
5918 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5919 << TheCall->getSourceRange();
5920
5921 // Argument 0 is checked for us and the remaining arguments must be
5922 // constant integers.
5923 for (unsigned i = 1; i != NumArgs; ++i)
5924 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5925 return true;
5926
5927 return false;
5928}
5929
5930bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5931 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
5932 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5933 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5934 if (checkArgCount(TheCall, 1))
5935 return true;
5936 Expr *Arg = TheCall->getArg(0);
5937 if (Arg->isInstantiationDependent())
5938 return false;
5939
5940 QualType ArgTy = Arg->getType();
5941 if (!ArgTy->hasFloatingRepresentation())
5942 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5943 << ArgTy;
5944 if (Arg->isLValue()) {
5945 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5946 TheCall->setArg(0, FirstArg.get());
5947 }
5948 TheCall->setType(TheCall->getArg(0)->getType());
5949 return false;
5950}
5951
5952bool Sema::BuiltinAssume(CallExpr *TheCall) {
5953 Expr *Arg = TheCall->getArg(0);
5954 if (Arg->isInstantiationDependent()) return false;
5955
5956 if (Arg->HasSideEffects(Context))
5957 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5958 << Arg->getSourceRange()
5959 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5960
5961 return false;
5962}
5963
5964bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5965 // The alignment must be a constant integer.
5966 Expr *Arg = TheCall->getArg(1);
5967
5968 // We can't check the value of a dependent argument.
5969 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5970 if (const auto *UE =
5971 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5972 if (UE->getKind() == UETT_AlignOf ||
5973 UE->getKind() == UETT_PreferredAlignOf)
5974 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5975 << Arg->getSourceRange();
5976
5977 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5978
5979 if (!Result.isPowerOf2())
5980 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5981 << Arg->getSourceRange();
5982
5983 if (Result < Context.getCharWidth())
5984 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5985 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5986
5987 if (Result > std::numeric_limits<int32_t>::max())
5988 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5989 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5990 }
5991
5992 return false;
5993}
5994
5995bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5996 if (checkArgCountRange(TheCall, 2, 3))
5997 return true;
5998
5999 unsigned NumArgs = TheCall->getNumArgs();
6000 Expr *FirstArg = TheCall->getArg(0);
6001
6002 {
6003 ExprResult FirstArgResult =
6005 if (!FirstArgResult.get()->getType()->isPointerType()) {
6006 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6007 << TheCall->getSourceRange();
6008 return true;
6009 }
6010 TheCall->setArg(0, FirstArgResult.get());
6011 }
6012
6013 // The alignment must be a constant integer.
6014 Expr *SecondArg = TheCall->getArg(1);
6015
6016 // We can't check the value of a dependent argument.
6017 if (!SecondArg->isValueDependent()) {
6018 llvm::APSInt Result;
6019 if (BuiltinConstantArg(TheCall, 1, Result))
6020 return true;
6021
6022 if (!Result.isPowerOf2())
6023 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6024 << SecondArg->getSourceRange();
6025
6027 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6028 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6029
6030 TheCall->setArg(1,
6032 }
6033
6034 if (NumArgs > 2) {
6035 Expr *ThirdArg = TheCall->getArg(2);
6036 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6037 return true;
6038 TheCall->setArg(2, ThirdArg);
6039 }
6040
6041 return false;
6042}
6043
6044bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6045 unsigned BuiltinID =
6046 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6047 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6048
6049 unsigned NumArgs = TheCall->getNumArgs();
6050 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6051 if (NumArgs < NumRequiredArgs) {
6052 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6053 << 0 /* function call */ << NumRequiredArgs << NumArgs
6054 << /*is non object*/ 0 << TheCall->getSourceRange();
6055 }
6056 if (NumArgs >= NumRequiredArgs + 0x100) {
6057 return Diag(TheCall->getEndLoc(),
6058 diag::err_typecheck_call_too_many_args_at_most)
6059 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6060 << /*is non object*/ 0 << TheCall->getSourceRange();
6061 }
6062 unsigned i = 0;
6063
6064 // For formatting call, check buffer arg.
6065 if (!IsSizeCall) {
6066 ExprResult Arg(TheCall->getArg(i));
6067 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6068 Context, Context.VoidPtrTy, false);
6069 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6070 if (Arg.isInvalid())
6071 return true;
6072 TheCall->setArg(i, Arg.get());
6073 i++;
6074 }
6075
6076 // Check string literal arg.
6077 unsigned FormatIdx = i;
6078 {
6079 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6080 if (Arg.isInvalid())
6081 return true;
6082 TheCall->setArg(i, Arg.get());
6083 i++;
6084 }
6085
6086 // Make sure variadic args are scalar.
6087 unsigned FirstDataArg = i;
6088 while (i < NumArgs) {
6090 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6091 if (Arg.isInvalid())
6092 return true;
6093 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6094 if (ArgSize.getQuantity() >= 0x100) {
6095 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6096 << i << (int)ArgSize.getQuantity() << 0xff
6097 << TheCall->getSourceRange();
6098 }
6099 TheCall->setArg(i, Arg.get());
6100 i++;
6101 }
6102
6103 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6104 // call to avoid duplicate diagnostics.
6105 if (!IsSizeCall) {
6106 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6107 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6108 bool Success = CheckFormatArguments(
6109 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6111 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6112 if (!Success)
6113 return true;
6114 }
6115
6116 if (IsSizeCall) {
6117 TheCall->setType(Context.getSizeType());
6118 } else {
6119 TheCall->setType(Context.VoidPtrTy);
6120 }
6121 return false;
6122}
6123
6124bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6125 llvm::APSInt &Result) {
6126 Expr *Arg = TheCall->getArg(ArgNum);
6127
6128 if (Arg->isTypeDependent() || Arg->isValueDependent())
6129 return false;
6130
6131 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6132 if (!R) {
6133 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6134 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6135 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6136 << FDecl->getDeclName() << Arg->getSourceRange();
6137 }
6138 Result = *R;
6139
6140 return false;
6141}
6142
6143bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6144 int High, bool RangeIsError) {
6146 return false;
6147 llvm::APSInt Result;
6148
6149 // We can't check the value of a dependent argument.
6150 Expr *Arg = TheCall->getArg(ArgNum);
6151 if (Arg->isTypeDependent() || Arg->isValueDependent())
6152 return false;
6153
6154 // Check constant-ness first.
6155 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6156 return true;
6157
6158 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6159 if (RangeIsError)
6160 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6161 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6162 else
6163 // Defer the warning until we know if the code will be emitted so that
6164 // dead code can ignore this.
6165 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6166 PDiag(diag::warn_argument_invalid_range)
6167 << toString(Result, 10) << Low << High
6168 << Arg->getSourceRange());
6169 }
6170
6171 return false;
6172}
6173
6174bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6175 unsigned Num) {
6176 llvm::APSInt Result;
6177
6178 // We can't check the value of a dependent argument.
6179 Expr *Arg = TheCall->getArg(ArgNum);
6180 if (Arg->isTypeDependent() || Arg->isValueDependent())
6181 return false;
6182
6183 // Check constant-ness first.
6184 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6185 return true;
6186
6187 if (Result.getSExtValue() % Num != 0)
6188 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6189 << Num << Arg->getSourceRange();
6190
6191 return false;
6192}
6193
6194bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6195 llvm::APSInt Result;
6196
6197 // We can't check the value of a dependent argument.
6198 Expr *Arg = TheCall->getArg(ArgNum);
6199 if (Arg->isTypeDependent() || Arg->isValueDependent())
6200 return false;
6201
6202 // Check constant-ness first.
6203 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6204 return true;
6205
6206 if (Result.isPowerOf2())
6207 return false;
6208
6209 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6210 << Arg->getSourceRange();
6211}
6212
6213static bool IsShiftedByte(llvm::APSInt Value) {
6214 if (Value.isNegative())
6215 return false;
6216
6217 // Check if it's a shifted byte, by shifting it down
6218 while (true) {
6219 // If the value fits in the bottom byte, the check passes.
6220 if (Value < 0x100)
6221 return true;
6222
6223 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6224 // fails.
6225 if ((Value & 0xFF) != 0)
6226 return false;
6227
6228 // If the bottom 8 bits are all 0, but something above that is nonzero,
6229 // then shifting the value right by 8 bits won't affect whether it's a
6230 // shifted byte or not. So do that, and go round again.
6231 Value >>= 8;
6232 }
6233}
6234
6235bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6236 unsigned ArgBits) {
6237 llvm::APSInt Result;
6238
6239 // We can't check the value of a dependent argument.
6240 Expr *Arg = TheCall->getArg(ArgNum);
6241 if (Arg->isTypeDependent() || Arg->isValueDependent())
6242 return false;
6243
6244 // Check constant-ness first.
6245 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6246 return true;
6247
6248 // Truncate to the given size.
6249 Result = Result.getLoBits(ArgBits);
6250 Result.setIsUnsigned(true);
6251
6252 if (IsShiftedByte(Result))
6253 return false;
6254
6255 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6256 << Arg->getSourceRange();
6257}
6258
6260 unsigned ArgNum,
6261 unsigned ArgBits) {
6262 llvm::APSInt Result;
6263
6264 // We can't check the value of a dependent argument.
6265 Expr *Arg = TheCall->getArg(ArgNum);
6266 if (Arg->isTypeDependent() || Arg->isValueDependent())
6267 return false;
6268
6269 // Check constant-ness first.
6270 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6271 return true;
6272
6273 // Truncate to the given size.
6274 Result = Result.getLoBits(ArgBits);
6275 Result.setIsUnsigned(true);
6276
6277 // Check to see if it's in either of the required forms.
6278 if (IsShiftedByte(Result) ||
6279 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6280 return false;
6281
6282 return Diag(TheCall->getBeginLoc(),
6283 diag::err_argument_not_shifted_byte_or_xxff)
6284 << Arg->getSourceRange();
6285}
6286
6287bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6288 if (!Context.getTargetInfo().hasSjLjLowering())
6289 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6290 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6291
6292 Expr *Arg = TheCall->getArg(1);
6293 llvm::APSInt Result;
6294
6295 // TODO: This is less than ideal. Overload this to take a value.
6296 if (BuiltinConstantArg(TheCall, 1, Result))
6297 return true;
6298
6299 if (Result != 1)
6300 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6301 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6302
6303 return false;
6304}
6305
6306bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6307 if (!Context.getTargetInfo().hasSjLjLowering())
6308 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6309 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6310 return false;
6311}
6312
6313bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6314 if (checkArgCount(TheCall, 1))
6315 return true;
6316
6317 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6318 if (ArgRes.isInvalid())
6319 return true;
6320
6321 // For simplicity, we support only limited expressions for the argument.
6322 // Specifically a pointer to a flexible array member:'ptr->array'. This
6323 // allows us to reject arguments with complex casting, which really shouldn't
6324 // be a huge problem.
6325 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6326 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
6327 return Diag(Arg->getBeginLoc(),
6328 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6329 << Arg->getSourceRange();
6330
6331 if (Arg->HasSideEffects(Context))
6332 return Diag(Arg->getBeginLoc(),
6333 diag::err_builtin_counted_by_ref_has_side_effects)
6334 << Arg->getSourceRange();
6335
6336 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6337 if (!ME->isFlexibleArrayMemberLike(
6338 Context, getLangOpts().getStrictFlexArraysLevel()))
6339 return Diag(Arg->getBeginLoc(),
6340 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6341 << Arg->getSourceRange();
6342
6343 if (auto *CATy =
6344 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6345 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6346 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
6347 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
6348 TheCall->setType(Context.getPointerType(CountFD->getType()));
6349 return false;
6350 }
6351 }
6352 } else {
6353 return Diag(Arg->getBeginLoc(),
6354 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6355 << Arg->getSourceRange();
6356 }
6357
6358 TheCall->setType(Context.getPointerType(Context.VoidTy));
6359 return false;
6360}
6361
6362/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6363/// It allows leaking and modification of bounds safety information.
6364bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6366 const CallExpr *CE =
6367 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6368 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6369 return false;
6370
6371 switch (K) {
6374 Diag(E->getExprLoc(),
6375 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6376 << 0 << E->getSourceRange();
6377 break;
6379 Diag(E->getExprLoc(),
6380 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6381 << 1 << E->getSourceRange();
6382 break;
6384 Diag(E->getExprLoc(),
6385 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6386 << 2 << E->getSourceRange();
6387 break;
6389 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6390 << 0 << E->getSourceRange();
6391 break;
6393 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6394 << 1 << E->getSourceRange();
6395 break;
6396 }
6397
6398 return true;
6399}
6400
6401namespace {
6402
6403class UncoveredArgHandler {
6404 enum { Unknown = -1, AllCovered = -2 };
6405
6406 signed FirstUncoveredArg = Unknown;
6407 SmallVector<const Expr *, 4> DiagnosticExprs;
6408
6409public:
6410 UncoveredArgHandler() = default;
6411
6412 bool hasUncoveredArg() const {
6413 return (FirstUncoveredArg >= 0);
6414 }
6415
6416 unsigned getUncoveredArg() const {
6417 assert(hasUncoveredArg() && "no uncovered argument");
6418 return FirstUncoveredArg;
6419 }
6420
6421 void setAllCovered() {
6422 // A string has been found with all arguments covered, so clear out
6423 // the diagnostics.
6424 DiagnosticExprs.clear();
6425 FirstUncoveredArg = AllCovered;
6426 }
6427
6428 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6429 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6430
6431 // Don't update if a previous string covers all arguments.
6432 if (FirstUncoveredArg == AllCovered)
6433 return;
6434
6435 // UncoveredArgHandler tracks the highest uncovered argument index
6436 // and with it all the strings that match this index.
6437 if (NewFirstUncoveredArg == FirstUncoveredArg)
6438 DiagnosticExprs.push_back(StrExpr);
6439 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6440 DiagnosticExprs.clear();
6441 DiagnosticExprs.push_back(StrExpr);
6442 FirstUncoveredArg = NewFirstUncoveredArg;
6443 }
6444 }
6445
6446 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6447};
6448
6449enum StringLiteralCheckType {
6450 SLCT_NotALiteral,
6451 SLCT_UncheckedLiteral,
6452 SLCT_CheckedLiteral
6453};
6454
6455} // namespace
6456
6457static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6458 BinaryOperatorKind BinOpKind,
6459 bool AddendIsRight) {
6460 unsigned BitWidth = Offset.getBitWidth();
6461 unsigned AddendBitWidth = Addend.getBitWidth();
6462 // There might be negative interim results.
6463 if (Addend.isUnsigned()) {
6464 Addend = Addend.zext(++AddendBitWidth);
6465 Addend.setIsSigned(true);
6466 }
6467 // Adjust the bit width of the APSInts.
6468 if (AddendBitWidth > BitWidth) {
6469 Offset = Offset.sext(AddendBitWidth);
6470 BitWidth = AddendBitWidth;
6471 } else if (BitWidth > AddendBitWidth) {
6472 Addend = Addend.sext(BitWidth);
6473 }
6474
6475 bool Ov = false;
6476 llvm::APSInt ResOffset = Offset;
6477 if (BinOpKind == BO_Add)
6478 ResOffset = Offset.sadd_ov(Addend, Ov);
6479 else {
6480 assert(AddendIsRight && BinOpKind == BO_Sub &&
6481 "operator must be add or sub with addend on the right");
6482 ResOffset = Offset.ssub_ov(Addend, Ov);
6483 }
6484
6485 // We add an offset to a pointer here so we should support an offset as big as
6486 // possible.
6487 if (Ov) {
6488 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6489 "index (intermediate) result too big");
6490 Offset = Offset.sext(2 * BitWidth);
6491 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6492 return;
6493 }
6494
6495 Offset = ResOffset;
6496}
6497
6498namespace {
6499
6500// This is a wrapper class around StringLiteral to support offsetted string
6501// literals as format strings. It takes the offset into account when returning
6502// the string and its length or the source locations to display notes correctly.
6503class FormatStringLiteral {
6504 const StringLiteral *FExpr;
6505 int64_t Offset;
6506
6507public:
6508 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6509 : FExpr(fexpr), Offset(Offset) {}
6510
6511 const StringLiteral *getFormatString() const { return FExpr; }
6512
6513 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6514
6515 unsigned getByteLength() const {
6516 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6517 }
6518
6519 unsigned getLength() const { return FExpr->getLength() - Offset; }
6520 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6521
6522 StringLiteralKind getKind() const { return FExpr->getKind(); }
6523
6524 QualType getType() const { return FExpr->getType(); }
6525
6526 bool isAscii() const { return FExpr->isOrdinary(); }
6527 bool isWide() const { return FExpr->isWide(); }
6528 bool isUTF8() const { return FExpr->isUTF8(); }
6529 bool isUTF16() const { return FExpr->isUTF16(); }
6530 bool isUTF32() const { return FExpr->isUTF32(); }
6531 bool isPascal() const { return FExpr->isPascal(); }
6532
6533 SourceLocation getLocationOfByte(
6534 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6535 const TargetInfo &Target, unsigned *StartToken = nullptr,
6536 unsigned *StartTokenByteOffset = nullptr) const {
6537 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6538 StartToken, StartTokenByteOffset);
6539 }
6540
6541 SourceLocation getBeginLoc() const LLVM_READONLY {
6542 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6543 }
6544
6545 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6546};
6547
6548} // namespace
6549
6550static void CheckFormatString(
6551 Sema &S, const FormatStringLiteral *FExpr,
6552 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6554 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6555 bool inFunctionCall, VariadicCallType CallType,
6556 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6557 bool IgnoreStringsWithoutSpecifiers);
6558
6559static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6560 const Expr *E);
6561
6562// Determine if an expression is a string literal or constant string.
6563// If this function returns false on the arguments to a function expecting a
6564// format string, we will usually need to emit a warning.
6565// True string literals are then checked by CheckFormatString.
6566static StringLiteralCheckType checkFormatStringExpr(
6567 Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E,
6569 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6570 VariadicCallType CallType, bool InFunctionCall,
6571 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6572 llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) {
6574 return SLCT_NotALiteral;
6575tryAgain:
6576 assert(Offset.isSigned() && "invalid offset");
6577
6578 if (E->isTypeDependent() || E->isValueDependent())
6579 return SLCT_NotALiteral;
6580
6581 E = E->IgnoreParenCasts();
6582
6584 // Technically -Wformat-nonliteral does not warn about this case.
6585 // The behavior of printf and friends in this case is implementation
6586 // dependent. Ideally if the format string cannot be null then
6587 // it should have a 'nonnull' attribute in the function prototype.
6588 return SLCT_UncheckedLiteral;
6589
6590 switch (E->getStmtClass()) {
6591 case Stmt::InitListExprClass:
6592 // Handle expressions like {"foobar"}.
6593 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6594 return checkFormatStringExpr(
6595 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6596 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6597 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6598 }
6599 return SLCT_NotALiteral;
6600 case Stmt::BinaryConditionalOperatorClass:
6601 case Stmt::ConditionalOperatorClass: {
6602 // The expression is a literal if both sub-expressions were, and it was
6603 // completely checked only if both sub-expressions were checked.
6606
6607 // Determine whether it is necessary to check both sub-expressions, for
6608 // example, because the condition expression is a constant that can be
6609 // evaluated at compile time.
6610 bool CheckLeft = true, CheckRight = true;
6611
6612 bool Cond;
6613 if (C->getCond()->EvaluateAsBooleanCondition(
6615 if (Cond)
6616 CheckRight = false;
6617 else
6618 CheckLeft = false;
6619 }
6620
6621 // We need to maintain the offsets for the right and the left hand side
6622 // separately to check if every possible indexed expression is a valid
6623 // string literal. They might have different offsets for different string
6624 // literals in the end.
6625 StringLiteralCheckType Left;
6626 if (!CheckLeft)
6627 Left = SLCT_UncheckedLiteral;
6628 else {
6629 Left = checkFormatStringExpr(
6630 S, ReferenceFormatString, C->getTrueExpr(), Args, APK, format_idx,
6631 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6632 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6633 if (Left == SLCT_NotALiteral || !CheckRight) {
6634 return Left;
6635 }
6636 }
6637
6638 StringLiteralCheckType Right = checkFormatStringExpr(
6639 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6640 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6641 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6642
6643 return (CheckLeft && Left < Right) ? Left : Right;
6644 }
6645
6646 case Stmt::ImplicitCastExprClass:
6647 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6648 goto tryAgain;
6649
6650 case Stmt::OpaqueValueExprClass:
6651 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6652 E = src;
6653 goto tryAgain;
6654 }
6655 return SLCT_NotALiteral;
6656
6657 case Stmt::PredefinedExprClass:
6658 // While __func__, etc., are technically not string literals, they
6659 // cannot contain format specifiers and thus are not a security
6660 // liability.
6661 return SLCT_UncheckedLiteral;
6662
6663 case Stmt::DeclRefExprClass: {
6664 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6665
6666 // As an exception, do not flag errors for variables binding to
6667 // const string literals.
6668 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6669 bool isConstant = false;
6670 QualType T = DR->getType();
6671
6672 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6673 isConstant = AT->getElementType().isConstant(S.Context);
6674 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6675 isConstant = T.isConstant(S.Context) &&
6676 PT->getPointeeType().isConstant(S.Context);
6677 } else if (T->isObjCObjectPointerType()) {
6678 // In ObjC, there is usually no "const ObjectPointer" type,
6679 // so don't check if the pointee type is constant.
6680 isConstant = T.isConstant(S.Context);
6681 }
6682
6683 if (isConstant) {
6684 if (const Expr *Init = VD->getAnyInitializer()) {
6685 // Look through initializers like const char c[] = { "foo" }
6686 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6687 if (InitList->isStringLiteralInit())
6688 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6689 }
6690 return checkFormatStringExpr(
6691 S, ReferenceFormatString, Init, Args, APK, format_idx,
6692 firstDataArg, Type, CallType,
6693 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6694 }
6695 }
6696
6697 // When the format argument is an argument of this function, and this
6698 // function also has the format attribute, there are several interactions
6699 // for which there shouldn't be a warning. For instance, when calling
6700 // v*printf from a function that has the printf format attribute, we
6701 // should not emit a warning about using `fmt`, even though it's not
6702 // constant, because the arguments have already been checked for the
6703 // caller of `logmessage`:
6704 //
6705 // __attribute__((format(printf, 1, 2)))
6706 // void logmessage(char const *fmt, ...) {
6707 // va_list ap;
6708 // va_start(ap, fmt);
6709 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6710 // ...
6711 // }
6712 //
6713 // Another interaction that we need to support is using a format string
6714 // specified by the format_matches attribute:
6715 //
6716 // __attribute__((format_matches(printf, 1, "%s %d")))
6717 // void logmessage(char const *fmt, const char *a, int b) {
6718 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6719 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6720 // ...
6721 // }
6722 //
6723 // Yet another interaction that we need to support is calling a variadic
6724 // format function from a format function that has fixed arguments. For
6725 // instance:
6726 //
6727 // __attribute__((format(printf, 1, 2)))
6728 // void logstring(char const *fmt, char const *str) {
6729 // printf(fmt, str); /* do not emit a warning about "fmt" */
6730 // }
6731 //
6732 // Same (and perhaps more relatably) for the variadic template case:
6733 //
6734 // template<typename... Args>
6735 // __attribute__((format(printf, 1, 2)))
6736 // void log(const char *fmt, Args&&... args) {
6737 // printf(fmt, forward<Args>(args)...);
6738 // /* do not emit a warning about "fmt" */
6739 // }
6740 //
6741 // Due to implementation difficulty, we only check the format, not the
6742 // format arguments, in all cases.
6743 //
6744 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6745 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6746 for (const auto *PVFormatMatches :
6747 D->specific_attrs<FormatMatchesAttr>()) {
6748 Sema::FormatStringInfo CalleeFSI;
6749 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6750 0, &CalleeFSI))
6751 continue;
6752 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6753 // If using the wrong type of format string, emit a diagnostic
6754 // here and stop checking to avoid irrelevant diagnostics.
6755 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6756 S.Diag(Args[format_idx]->getBeginLoc(),
6757 diag::warn_format_string_type_incompatible)
6758 << PVFormatMatches->getType()->getName()
6760 if (!InFunctionCall) {
6761 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6762 diag::note_format_string_defined);
6763 }
6764 return SLCT_UncheckedLiteral;
6765 }
6766 return checkFormatStringExpr(
6767 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6768 Args, APK, format_idx, firstDataArg, Type, CallType,
6769 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6770 Offset, IgnoreStringsWithoutSpecifiers);
6771 }
6772 }
6773
6774 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6775 Sema::FormatStringInfo CallerFSI;
6776 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6777 PVFormat->getFirstArg(), &CallerFSI))
6778 continue;
6779 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6780 // We also check if the formats are compatible.
6781 // We can't pass a 'scanf' string to a 'printf' function.
6782 if (Type != S.GetFormatStringType(PVFormat)) {
6783 S.Diag(Args[format_idx]->getBeginLoc(),
6784 diag::warn_format_string_type_incompatible)
6785 << PVFormat->getType()->getName()
6787 if (!InFunctionCall) {
6788 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6789 }
6790 return SLCT_UncheckedLiteral;
6791 }
6792 // Lastly, check that argument passing kinds transition in a
6793 // way that makes sense:
6794 // from a caller with FAPK_VAList, allow FAPK_VAList
6795 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6796 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6797 // from a caller with FAPK_Variadic, allow FAPK_VAList
6798 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6803 return SLCT_UncheckedLiteral;
6804 }
6805 }
6806 }
6807 }
6808 }
6809 }
6810
6811 return SLCT_NotALiteral;
6812 }
6813
6814 case Stmt::CallExprClass:
6815 case Stmt::CXXMemberCallExprClass: {
6816 const CallExpr *CE = cast<CallExpr>(E);
6817 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6818 bool IsFirst = true;
6819 StringLiteralCheckType CommonResult;
6820 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6821 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6822 StringLiteralCheckType Result = checkFormatStringExpr(
6823 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6824 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6825 Offset, IgnoreStringsWithoutSpecifiers);
6826 if (IsFirst) {
6827 CommonResult = Result;
6828 IsFirst = false;
6829 }
6830 }
6831 if (!IsFirst)
6832 return CommonResult;
6833
6834 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6835 unsigned BuiltinID = FD->getBuiltinID();
6836 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6837 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6838 const Expr *Arg = CE->getArg(0);
6839 return checkFormatStringExpr(
6840 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6841 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6842 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6843 }
6844 }
6845 }
6846 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6847 return checkFormatStringExpr(
6848 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6849 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6850 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6851 return SLCT_NotALiteral;
6852 }
6853 case Stmt::ObjCMessageExprClass: {
6854 const auto *ME = cast<ObjCMessageExpr>(E);
6855 if (const auto *MD = ME->getMethodDecl()) {
6856 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6857 // As a special case heuristic, if we're using the method -[NSBundle
6858 // localizedStringForKey:value:table:], ignore any key strings that lack
6859 // format specifiers. The idea is that if the key doesn't have any
6860 // format specifiers then its probably just a key to map to the
6861 // localized strings. If it does have format specifiers though, then its
6862 // likely that the text of the key is the format string in the
6863 // programmer's language, and should be checked.
6864 const ObjCInterfaceDecl *IFace;
6865 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6866 IFace->getIdentifier()->isStr("NSBundle") &&
6867 MD->getSelector().isKeywordSelector(
6868 {"localizedStringForKey", "value", "table"})) {
6869 IgnoreStringsWithoutSpecifiers = true;
6870 }
6871
6872 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6873 return checkFormatStringExpr(
6874 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6875 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6876 Offset, IgnoreStringsWithoutSpecifiers);
6877 }
6878 }
6879
6880 return SLCT_NotALiteral;
6881 }
6882 case Stmt::ObjCStringLiteralClass:
6883 case Stmt::StringLiteralClass: {
6884 const StringLiteral *StrE = nullptr;
6885
6886 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6887 StrE = ObjCFExpr->getString();
6888 else
6889 StrE = cast<StringLiteral>(E);
6890
6891 if (StrE) {
6892 if (Offset.isNegative() || Offset > StrE->getLength()) {
6893 // TODO: It would be better to have an explicit warning for out of
6894 // bounds literals.
6895 return SLCT_NotALiteral;
6896 }
6897 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6898 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6899 format_idx, firstDataArg, Type, InFunctionCall,
6900 CallType, CheckedVarArgs, UncoveredArg,
6901 IgnoreStringsWithoutSpecifiers);
6902 return SLCT_CheckedLiteral;
6903 }
6904
6905 return SLCT_NotALiteral;
6906 }
6907 case Stmt::BinaryOperatorClass: {
6908 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6909
6910 // A string literal + an int offset is still a string literal.
6911 if (BinOp->isAdditiveOp()) {
6912 Expr::EvalResult LResult, RResult;
6913
6914 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6915 LResult, S.Context, Expr::SE_NoSideEffects,
6917 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6918 RResult, S.Context, Expr::SE_NoSideEffects,
6920
6921 if (LIsInt != RIsInt) {
6922 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6923
6924 if (LIsInt) {
6925 if (BinOpKind == BO_Add) {
6926 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6927 E = BinOp->getRHS();
6928 goto tryAgain;
6929 }
6930 } else {
6931 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6932 E = BinOp->getLHS();
6933 goto tryAgain;
6934 }
6935 }
6936 }
6937
6938 return SLCT_NotALiteral;
6939 }
6940 case Stmt::UnaryOperatorClass: {
6941 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6942 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6943 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6944 Expr::EvalResult IndexResult;
6945 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6948 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6949 /*RHS is int*/ true);
6950 E = ASE->getBase();
6951 goto tryAgain;
6952 }
6953 }
6954
6955 return SLCT_NotALiteral;
6956 }
6957
6958 default:
6959 return SLCT_NotALiteral;
6960 }
6961}
6962
6963// If this expression can be evaluated at compile-time,
6964// check if the result is a StringLiteral and return it
6965// otherwise return nullptr
6967 const Expr *E) {
6968 Expr::EvalResult Result;
6969 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6970 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6971 if (isa_and_nonnull<StringLiteral>(LVE))
6972 return LVE;
6973 }
6974 return nullptr;
6975}
6976
6978 switch (FST) {
6980 return "scanf";
6982 return "printf";
6984 return "NSString";
6986 return "strftime";
6988 return "strfmon";
6990 return "kprintf";
6992 return "freebsd_kprintf";
6994 return "os_log";
6995 default:
6996 return "<unknown>";
6997 }
6998}
6999
7001 return llvm::StringSwitch<FormatStringType>(Flavor)
7002 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7003 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7005 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7006 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7007 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7008 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7010 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7011 .Case("os_trace", FormatStringType::OSLog)
7012 .Case("os_log", FormatStringType::OSLog)
7013 .Default(FormatStringType::Unknown);
7014}
7015
7017 return GetFormatStringType(Format->getType()->getName());
7018}
7019
7020FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7021 return GetFormatStringType(Format->getType()->getName());
7022}
7023
7024bool Sema::CheckFormatArguments(const FormatAttr *Format,
7025 ArrayRef<const Expr *> Args, bool IsCXXMember,
7026 VariadicCallType CallType, SourceLocation Loc,
7027 SourceRange Range,
7028 llvm::SmallBitVector &CheckedVarArgs) {
7029 FormatStringInfo FSI;
7030 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7031 IsCXXMember,
7032 CallType != VariadicCallType::DoesNotApply, &FSI))
7033 return CheckFormatArguments(
7034 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7035 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7036 return false;
7037}
7038
7039bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7040 ArrayRef<const Expr *> Args, bool IsCXXMember,
7041 VariadicCallType CallType, SourceLocation Loc,
7042 SourceRange Range,
7043 llvm::SmallBitVector &CheckedVarArgs) {
7044 FormatStringInfo FSI;
7045 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7046 &FSI)) {
7047 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7048 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7049 Format->getFormatString(), FSI.FormatIdx,
7050 FSI.FirstDataArg, GetFormatStringType(Format),
7051 CallType, Loc, Range, CheckedVarArgs);
7052 }
7053 return false;
7054}
7055
7056bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7058 const StringLiteral *ReferenceFormatString,
7059 unsigned format_idx, unsigned firstDataArg,
7061 VariadicCallType CallType, SourceLocation Loc,
7062 SourceRange Range,
7063 llvm::SmallBitVector &CheckedVarArgs) {
7064 // CHECK: printf/scanf-like function is called with no format string.
7065 if (format_idx >= Args.size()) {
7066 Diag(Loc, diag::warn_missing_format_string) << Range;
7067 return false;
7068 }
7069
7070 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7071
7072 // CHECK: format string is not a string literal.
7073 //
7074 // Dynamically generated format strings are difficult to
7075 // automatically vet at compile time. Requiring that format strings
7076 // are string literals: (1) permits the checking of format strings by
7077 // the compiler and thereby (2) can practically remove the source of
7078 // many format string exploits.
7079
7080 // Format string can be either ObjC string (e.g. @"%d") or
7081 // C string (e.g. "%d")
7082 // ObjC string uses the same format specifiers as C string, so we can use
7083 // the same format string checking logic for both ObjC and C strings.
7084 UncoveredArgHandler UncoveredArg;
7085 StringLiteralCheckType CT = checkFormatStringExpr(
7086 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7087 firstDataArg, Type, CallType,
7088 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7089 /*no string offset*/ llvm::APSInt(64, false) = 0);
7090
7091 // Generate a diagnostic where an uncovered argument is detected.
7092 if (UncoveredArg.hasUncoveredArg()) {
7093 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7094 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7095 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7096 }
7097
7098 if (CT != SLCT_NotALiteral)
7099 // Literal format string found, check done!
7100 return CT == SLCT_CheckedLiteral;
7101
7102 // Strftime is particular as it always uses a single 'time' argument,
7103 // so it is safe to pass a non-literal string.
7105 return false;
7106
7107 // Do not emit diag when the string param is a macro expansion and the
7108 // format is either NSString or CFString. This is a hack to prevent
7109 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7110 // which are usually used in place of NS and CF string literals.
7111 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7113 SourceMgr.isInSystemMacro(FormatLoc))
7114 return false;
7115
7116 // If there are no arguments specified, warn with -Wformat-security, otherwise
7117 // warn only with -Wformat-nonliteral.
7118 if (Args.size() == firstDataArg) {
7119 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7120 << OrigFormatExpr->getSourceRange();
7121 switch (Type) {
7122 default:
7123 break;
7127 Diag(FormatLoc, diag::note_format_security_fixit)
7128 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7129 break;
7131 Diag(FormatLoc, diag::note_format_security_fixit)
7132 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7133 break;
7134 }
7135 } else {
7136 Diag(FormatLoc, diag::warn_format_nonliteral)
7137 << OrigFormatExpr->getSourceRange();
7138 }
7139 return false;
7140}
7141
7142namespace {
7143
7144class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7145protected:
7146 Sema &S;
7147 const FormatStringLiteral *FExpr;
7148 const Expr *OrigFormatExpr;
7149 const FormatStringType FSType;
7150 const unsigned FirstDataArg;
7151 const unsigned NumDataArgs;
7152 const char *Beg; // Start of format string.
7153 const Sema::FormatArgumentPassingKind ArgPassingKind;
7154 ArrayRef<const Expr *> Args;
7155 unsigned FormatIdx;
7156 llvm::SmallBitVector CoveredArgs;
7157 bool usesPositionalArgs = false;
7158 bool atFirstArg = true;
7159 bool inFunctionCall;
7160 VariadicCallType CallType;
7161 llvm::SmallBitVector &CheckedVarArgs;
7162 UncoveredArgHandler &UncoveredArg;
7163
7164public:
7165 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7166 const Expr *origFormatExpr, const FormatStringType type,
7167 unsigned firstDataArg, unsigned numDataArgs,
7168 const char *beg, Sema::FormatArgumentPassingKind APK,
7169 ArrayRef<const Expr *> Args, unsigned formatIdx,
7170 bool inFunctionCall, VariadicCallType callType,
7171 llvm::SmallBitVector &CheckedVarArgs,
7172 UncoveredArgHandler &UncoveredArg)
7173 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7174 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7175 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7176 inFunctionCall(inFunctionCall), CallType(callType),
7177 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7178 CoveredArgs.resize(numDataArgs);
7179 CoveredArgs.reset();
7180 }
7181
7182 bool HasFormatArguments() const {
7183 return ArgPassingKind == Sema::FAPK_Fixed ||
7184 ArgPassingKind == Sema::FAPK_Variadic;
7185 }
7186
7187 void DoneProcessing();
7188
7189 void HandleIncompleteSpecifier(const char *startSpecifier,
7190 unsigned specifierLen) override;
7191
7192 void HandleInvalidLengthModifier(
7193 const analyze_format_string::FormatSpecifier &FS,
7194 const analyze_format_string::ConversionSpecifier &CS,
7195 const char *startSpecifier, unsigned specifierLen,
7196 unsigned DiagID);
7197
7198 void HandleNonStandardLengthModifier(
7199 const analyze_format_string::FormatSpecifier &FS,
7200 const char *startSpecifier, unsigned specifierLen);
7201
7202 void HandleNonStandardConversionSpecifier(
7203 const analyze_format_string::ConversionSpecifier &CS,
7204 const char *startSpecifier, unsigned specifierLen);
7205
7206 void HandlePosition(const char *startPos, unsigned posLen) override;
7207
7208 void HandleInvalidPosition(const char *startSpecifier,
7209 unsigned specifierLen,
7211
7212 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7213
7214 void HandleNullChar(const char *nullCharacter) override;
7215
7216 template <typename Range>
7217 static void
7218 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7219 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7220 bool IsStringLocation, Range StringRange,
7221 ArrayRef<FixItHint> Fixit = {});
7222
7223protected:
7224 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7225 const char *startSpec,
7226 unsigned specifierLen,
7227 const char *csStart, unsigned csLen);
7228
7229 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7230 const char *startSpec,
7231 unsigned specifierLen);
7232
7233 SourceRange getFormatStringRange();
7234 CharSourceRange getSpecifierRange(const char *startSpecifier,
7235 unsigned specifierLen);
7236 SourceLocation getLocationOfByte(const char *x);
7237
7238 const Expr *getDataArg(unsigned i) const;
7239
7240 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7241 const analyze_format_string::ConversionSpecifier &CS,
7242 const char *startSpecifier, unsigned specifierLen,
7243 unsigned argIndex);
7244
7245 template <typename Range>
7246 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7247 bool IsStringLocation, Range StringRange,
7248 ArrayRef<FixItHint> Fixit = {});
7249};
7250
7251} // namespace
7252
7253SourceRange CheckFormatHandler::getFormatStringRange() {
7254 return OrigFormatExpr->getSourceRange();
7255}
7256
7257CharSourceRange CheckFormatHandler::
7258getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7259 SourceLocation Start = getLocationOfByte(startSpecifier);
7260 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7261
7262 // Advance the end SourceLocation by one due to half-open ranges.
7263 End = End.getLocWithOffset(1);
7264
7265 return CharSourceRange::getCharRange(Start, End);
7266}
7267
7268SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7269 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7271}
7272
7273void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7274 unsigned specifierLen){
7275 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7276 getLocationOfByte(startSpecifier),
7277 /*IsStringLocation*/true,
7278 getSpecifierRange(startSpecifier, specifierLen));
7279}
7280
7281void CheckFormatHandler::HandleInvalidLengthModifier(
7284 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7285 using namespace analyze_format_string;
7286
7287 const LengthModifier &LM = FS.getLengthModifier();
7288 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7289
7290 // See if we know how to fix this length modifier.
7291 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7292 if (FixedLM) {
7293 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7294 getLocationOfByte(LM.getStart()),
7295 /*IsStringLocation*/true,
7296 getSpecifierRange(startSpecifier, specifierLen));
7297
7298 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7299 << FixedLM->toString()
7300 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7301
7302 } else {
7303 FixItHint Hint;
7304 if (DiagID == diag::warn_format_nonsensical_length)
7305 Hint = FixItHint::CreateRemoval(LMRange);
7306
7307 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7308 getLocationOfByte(LM.getStart()),
7309 /*IsStringLocation*/true,
7310 getSpecifierRange(startSpecifier, specifierLen),
7311 Hint);
7312 }
7313}
7314
7315void CheckFormatHandler::HandleNonStandardLengthModifier(
7317 const char *startSpecifier, unsigned specifierLen) {
7318 using namespace analyze_format_string;
7319
7320 const LengthModifier &LM = FS.getLengthModifier();
7321 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7322
7323 // See if we know how to fix this length modifier.
7324 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7325 if (FixedLM) {
7326 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7327 << LM.toString() << 0,
7328 getLocationOfByte(LM.getStart()),
7329 /*IsStringLocation*/true,
7330 getSpecifierRange(startSpecifier, specifierLen));
7331
7332 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7333 << FixedLM->toString()
7334 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7335
7336 } else {
7337 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7338 << LM.toString() << 0,
7339 getLocationOfByte(LM.getStart()),
7340 /*IsStringLocation*/true,
7341 getSpecifierRange(startSpecifier, specifierLen));
7342 }
7343}
7344
7345void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7347 const char *startSpecifier, unsigned specifierLen) {
7348 using namespace analyze_format_string;
7349
7350 // See if we know how to fix this conversion specifier.
7351 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7352 if (FixedCS) {
7353 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7354 << CS.toString() << /*conversion specifier*/1,
7355 getLocationOfByte(CS.getStart()),
7356 /*IsStringLocation*/true,
7357 getSpecifierRange(startSpecifier, specifierLen));
7358
7359 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7360 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7361 << FixedCS->toString()
7362 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7363 } else {
7364 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7365 << CS.toString() << /*conversion specifier*/1,
7366 getLocationOfByte(CS.getStart()),
7367 /*IsStringLocation*/true,
7368 getSpecifierRange(startSpecifier, specifierLen));
7369 }
7370}
7371
7372void CheckFormatHandler::HandlePosition(const char *startPos,
7373 unsigned posLen) {
7374 if (!S.getDiagnostics().isIgnored(
7375 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7376 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7377 getLocationOfByte(startPos),
7378 /*IsStringLocation*/ true,
7379 getSpecifierRange(startPos, posLen));
7380}
7381
7382void CheckFormatHandler::HandleInvalidPosition(
7383 const char *startSpecifier, unsigned specifierLen,
7385 if (!S.getDiagnostics().isIgnored(
7386 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7387 EmitFormatDiagnostic(
7388 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7389 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7390 getSpecifierRange(startSpecifier, specifierLen));
7391}
7392
7393void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7394 unsigned posLen) {
7395 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7396 SourceLocation()))
7397 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7398 getLocationOfByte(startPos),
7399 /*IsStringLocation*/ true,
7400 getSpecifierRange(startPos, posLen));
7401}
7402
7403void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7404 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7405 // The presence of a null character is likely an error.
7406 EmitFormatDiagnostic(
7407 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7408 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7409 getFormatStringRange());
7410 }
7411}
7412
7413// Note that this may return NULL if there was an error parsing or building
7414// one of the argument expressions.
7415const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7416 return Args[FirstDataArg + i];
7417}
7418
7419void CheckFormatHandler::DoneProcessing() {
7420 // Does the number of data arguments exceed the number of
7421 // format conversions in the format string?
7422 if (HasFormatArguments()) {
7423 // Find any arguments that weren't covered.
7424 CoveredArgs.flip();
7425 signed notCoveredArg = CoveredArgs.find_first();
7426 if (notCoveredArg >= 0) {
7427 assert((unsigned)notCoveredArg < NumDataArgs);
7428 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7429 } else {
7430 UncoveredArg.setAllCovered();
7431 }
7432 }
7433}
7434
7435void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7436 const Expr *ArgExpr) {
7437 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7438 "Invalid state");
7439
7440 if (!ArgExpr)
7441 return;
7442
7443 SourceLocation Loc = ArgExpr->getBeginLoc();
7444
7445 if (S.getSourceManager().isInSystemMacro(Loc))
7446 return;
7447
7448 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7449 for (auto E : DiagnosticExprs)
7450 PDiag << E->getSourceRange();
7451
7452 CheckFormatHandler::EmitFormatDiagnostic(
7453 S, IsFunctionCall, DiagnosticExprs[0],
7454 PDiag, Loc, /*IsStringLocation*/false,
7455 DiagnosticExprs[0]->getSourceRange());
7456}
7457
7458bool
7459CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7460 SourceLocation Loc,
7461 const char *startSpec,
7462 unsigned specifierLen,
7463 const char *csStart,
7464 unsigned csLen) {
7465 bool keepGoing = true;
7466 if (argIndex < NumDataArgs) {
7467 // Consider the argument coverered, even though the specifier doesn't
7468 // make sense.
7469 CoveredArgs.set(argIndex);
7470 }
7471 else {
7472 // If argIndex exceeds the number of data arguments we
7473 // don't issue a warning because that is just a cascade of warnings (and
7474 // they may have intended '%%' anyway). We don't want to continue processing
7475 // the format string after this point, however, as we will like just get
7476 // gibberish when trying to match arguments.
7477 keepGoing = false;
7478 }
7479
7480 StringRef Specifier(csStart, csLen);
7481
7482 // If the specifier in non-printable, it could be the first byte of a UTF-8
7483 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7484 // hex value.
7485 std::string CodePointStr;
7486 if (!llvm::sys::locale::isPrint(*csStart)) {
7487 llvm::UTF32 CodePoint;
7488 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7489 const llvm::UTF8 *E =
7490 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7491 llvm::ConversionResult Result =
7492 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7493
7494 if (Result != llvm::conversionOK) {
7495 unsigned char FirstChar = *csStart;
7496 CodePoint = (llvm::UTF32)FirstChar;
7497 }
7498
7499 llvm::raw_string_ostream OS(CodePointStr);
7500 if (CodePoint < 256)
7501 OS << "\\x" << llvm::format("%02x", CodePoint);
7502 else if (CodePoint <= 0xFFFF)
7503 OS << "\\u" << llvm::format("%04x", CodePoint);
7504 else
7505 OS << "\\U" << llvm::format("%08x", CodePoint);
7506 Specifier = CodePointStr;
7507 }
7508
7509 EmitFormatDiagnostic(
7510 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7511 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7512
7513 return keepGoing;
7514}
7515
7516void
7517CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7518 const char *startSpec,
7519 unsigned specifierLen) {
7520 EmitFormatDiagnostic(
7521 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7522 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7523}
7524
7525bool
7526CheckFormatHandler::CheckNumArgs(
7529 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7530
7531 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7533 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7534 << (argIndex+1) << NumDataArgs)
7535 : S.PDiag(diag::warn_printf_insufficient_data_args);
7536 EmitFormatDiagnostic(
7537 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7538 getSpecifierRange(startSpecifier, specifierLen));
7539
7540 // Since more arguments than conversion tokens are given, by extension
7541 // all arguments are covered, so mark this as so.
7542 UncoveredArg.setAllCovered();
7543 return false;
7544 }
7545 return true;
7546}
7547
7548template<typename Range>
7549void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7550 SourceLocation Loc,
7551 bool IsStringLocation,
7552 Range StringRange,
7553 ArrayRef<FixItHint> FixIt) {
7554 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7555 Loc, IsStringLocation, StringRange, FixIt);
7556}
7557
7558/// If the format string is not within the function call, emit a note
7559/// so that the function call and string are in diagnostic messages.
7560///
7561/// \param InFunctionCall if true, the format string is within the function
7562/// call and only one diagnostic message will be produced. Otherwise, an
7563/// extra note will be emitted pointing to location of the format string.
7564///
7565/// \param ArgumentExpr the expression that is passed as the format string
7566/// argument in the function call. Used for getting locations when two
7567/// diagnostics are emitted.
7568///
7569/// \param PDiag the callee should already have provided any strings for the
7570/// diagnostic message. This function only adds locations and fixits
7571/// to diagnostics.
7572///
7573/// \param Loc primary location for diagnostic. If two diagnostics are
7574/// required, one will be at Loc and a new SourceLocation will be created for
7575/// the other one.
7576///
7577/// \param IsStringLocation if true, Loc points to the format string should be
7578/// used for the note. Otherwise, Loc points to the argument list and will
7579/// be used with PDiag.
7580///
7581/// \param StringRange some or all of the string to highlight. This is
7582/// templated so it can accept either a CharSourceRange or a SourceRange.
7583///
7584/// \param FixIt optional fix it hint for the format string.
7585template <typename Range>
7586void CheckFormatHandler::EmitFormatDiagnostic(
7587 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7588 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7589 Range StringRange, ArrayRef<FixItHint> FixIt) {
7590 if (InFunctionCall) {
7591 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7592 D << StringRange;
7593 D << FixIt;
7594 } else {
7595 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7596 << ArgumentExpr->getSourceRange();
7597
7599 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7600 diag::note_format_string_defined);
7601
7602 Note << StringRange;
7603 Note << FixIt;
7604 }
7605}
7606
7607//===--- CHECK: Printf format string checking -----------------------------===//
7608
7609namespace {
7610
7611class CheckPrintfHandler : public CheckFormatHandler {
7612public:
7613 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7614 const Expr *origFormatExpr, const FormatStringType type,
7615 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7616 const char *beg, Sema::FormatArgumentPassingKind APK,
7617 ArrayRef<const Expr *> Args, unsigned formatIdx,
7618 bool inFunctionCall, VariadicCallType CallType,
7619 llvm::SmallBitVector &CheckedVarArgs,
7620 UncoveredArgHandler &UncoveredArg)
7621 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7622 numDataArgs, beg, APK, Args, formatIdx,
7623 inFunctionCall, CallType, CheckedVarArgs,
7624 UncoveredArg) {}
7625
7626 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7627
7628 /// Returns true if '%@' specifiers are allowed in the format string.
7629 bool allowsObjCArg() const {
7630 return FSType == FormatStringType::NSString ||
7631 FSType == FormatStringType::OSLog ||
7632 FSType == FormatStringType::OSTrace;
7633 }
7634
7635 bool HandleInvalidPrintfConversionSpecifier(
7636 const analyze_printf::PrintfSpecifier &FS,
7637 const char *startSpecifier,
7638 unsigned specifierLen) override;
7639
7640 void handleInvalidMaskType(StringRef MaskType) override;
7641
7642 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7643 const char *startSpecifier, unsigned specifierLen,
7644 const TargetInfo &Target) override;
7645 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7646 const char *StartSpecifier,
7647 unsigned SpecifierLen,
7648 const Expr *E);
7649
7650 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7651 const char *startSpecifier, unsigned specifierLen);
7652 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7653 const analyze_printf::OptionalAmount &Amt,
7654 unsigned type,
7655 const char *startSpecifier, unsigned specifierLen);
7656 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7657 const analyze_printf::OptionalFlag &flag,
7658 const char *startSpecifier, unsigned specifierLen);
7659 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7660 const analyze_printf::OptionalFlag &ignoredFlag,
7661 const analyze_printf::OptionalFlag &flag,
7662 const char *startSpecifier, unsigned specifierLen);
7663 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7664 const Expr *E);
7665
7666 void HandleEmptyObjCModifierFlag(const char *startFlag,
7667 unsigned flagLen) override;
7668
7669 void HandleInvalidObjCModifierFlag(const char *startFlag,
7670 unsigned flagLen) override;
7671
7672 void
7673 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7674 const char *flagsEnd,
7675 const char *conversionPosition) override;
7676};
7677
7678/// Keeps around the information needed to verify that two specifiers are
7679/// compatible.
7680class EquatableFormatArgument {
7681public:
7682 enum SpecifierSensitivity : unsigned {
7683 SS_None,
7684 SS_Private,
7685 SS_Public,
7686 SS_Sensitive
7687 };
7688
7689 enum FormatArgumentRole : unsigned {
7690 FAR_Data,
7691 FAR_FieldWidth,
7692 FAR_Precision,
7693 FAR_Auxiliary, // FreeBSD kernel %b and %D
7694 };
7695
7696private:
7697 analyze_format_string::ArgType ArgType;
7699 StringRef SpecifierLetter;
7700 CharSourceRange Range;
7701 SourceLocation ElementLoc;
7702 FormatArgumentRole Role : 2;
7703 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7704 unsigned Position : 14;
7705 unsigned ModifierFor : 14; // not set for FAR_Data
7706
7707 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7708 bool InFunctionCall) const;
7709
7710public:
7711 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7713 StringRef SpecifierLetter,
7714 analyze_format_string::ArgType ArgType,
7715 FormatArgumentRole Role,
7716 SpecifierSensitivity Sensitivity, unsigned Position,
7717 unsigned ModifierFor)
7718 : ArgType(ArgType), LengthMod(LengthMod),
7719 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7720 Role(Role), Sensitivity(Sensitivity), Position(Position),
7721 ModifierFor(ModifierFor) {}
7722
7723 unsigned getPosition() const { return Position; }
7724 SourceLocation getSourceLocation() const { return ElementLoc; }
7725 CharSourceRange getSourceRange() const { return Range; }
7726 analyze_format_string::LengthModifier getLengthModifier() const {
7727 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7728 }
7729 void setModifierFor(unsigned V) { ModifierFor = V; }
7730
7731 std::string buildFormatSpecifier() const {
7732 std::string result;
7733 llvm::raw_string_ostream(result)
7734 << getLengthModifier().toString() << SpecifierLetter;
7735 return result;
7736 }
7737
7738 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7739 const Expr *FmtExpr, bool InFunctionCall) const;
7740};
7741
7742/// Turns format strings into lists of EquatableSpecifier objects.
7743class DecomposePrintfHandler : public CheckPrintfHandler {
7744 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7745 bool HadError;
7746
7747 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7748 const Expr *origFormatExpr,
7749 const FormatStringType type, unsigned firstDataArg,
7750 unsigned numDataArgs, bool isObjC, const char *beg,
7752 ArrayRef<const Expr *> Args, unsigned formatIdx,
7753 bool inFunctionCall, VariadicCallType CallType,
7754 llvm::SmallBitVector &CheckedVarArgs,
7755 UncoveredArgHandler &UncoveredArg,
7756 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7757 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7758 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7759 inFunctionCall, CallType, CheckedVarArgs,
7760 UncoveredArg),
7761 Specs(Specs), HadError(false) {}
7762
7763public:
7764 static bool
7765 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7766 FormatStringType type, bool IsObjC, bool InFunctionCall,
7767 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7768
7769 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7770 const char *startSpecifier,
7771 unsigned specifierLen,
7772 const TargetInfo &Target) override;
7773};
7774
7775} // namespace
7776
7777bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7778 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7779 unsigned specifierLen) {
7782
7783 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7784 getLocationOfByte(CS.getStart()),
7785 startSpecifier, specifierLen,
7786 CS.getStart(), CS.getLength());
7787}
7788
7789void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7790 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7791}
7792
7793// Error out if struct or complex type argments are passed to os_log.
7795 QualType T) {
7796 if (FSType != FormatStringType::OSLog)
7797 return false;
7798 return T->isRecordType() || T->isComplexType();
7799}
7800
7801bool CheckPrintfHandler::HandleAmount(
7802 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7803 const char *startSpecifier, unsigned specifierLen) {
7804 if (Amt.hasDataArgument()) {
7805 if (HasFormatArguments()) {
7806 unsigned argIndex = Amt.getArgIndex();
7807 if (argIndex >= NumDataArgs) {
7808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7809 << k,
7810 getLocationOfByte(Amt.getStart()),
7811 /*IsStringLocation*/ true,
7812 getSpecifierRange(startSpecifier, specifierLen));
7813 // Don't do any more checking. We will just emit
7814 // spurious errors.
7815 return false;
7816 }
7817
7818 // Type check the data argument. It should be an 'int'.
7819 // Although not in conformance with C99, we also allow the argument to be
7820 // an 'unsigned int' as that is a reasonably safe case. GCC also
7821 // doesn't emit a warning for that case.
7822 CoveredArgs.set(argIndex);
7823 const Expr *Arg = getDataArg(argIndex);
7824 if (!Arg)
7825 return false;
7826
7827 QualType T = Arg->getType();
7828
7829 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7830 assert(AT.isValid());
7831
7832 if (!AT.matchesType(S.Context, T)) {
7833 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
7834 ? diag::err_printf_asterisk_wrong_type
7835 : diag::warn_printf_asterisk_wrong_type;
7836 EmitFormatDiagnostic(S.PDiag(DiagID)
7838 << T << Arg->getSourceRange(),
7839 getLocationOfByte(Amt.getStart()),
7840 /*IsStringLocation*/ true,
7841 getSpecifierRange(startSpecifier, specifierLen));
7842 // Don't do any more checking. We will just emit
7843 // spurious errors.
7844 return false;
7845 }
7846 }
7847 }
7848 return true;
7849}
7850
7851void CheckPrintfHandler::HandleInvalidAmount(
7854 unsigned type,
7855 const char *startSpecifier,
7856 unsigned specifierLen) {
7859
7860 FixItHint fixit =
7862 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7863 Amt.getConstantLength()))
7864 : FixItHint();
7865
7866 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7867 << type << CS.toString(),
7868 getLocationOfByte(Amt.getStart()),
7869 /*IsStringLocation*/true,
7870 getSpecifierRange(startSpecifier, specifierLen),
7871 fixit);
7872}
7873
7874void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7875 const analyze_printf::OptionalFlag &flag,
7876 const char *startSpecifier,
7877 unsigned specifierLen) {
7878 // Warn about pointless flag with a fixit removal.
7881 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7882 << flag.toString() << CS.toString(),
7883 getLocationOfByte(flag.getPosition()),
7884 /*IsStringLocation*/true,
7885 getSpecifierRange(startSpecifier, specifierLen),
7887 getSpecifierRange(flag.getPosition(), 1)));
7888}
7889
7890void CheckPrintfHandler::HandleIgnoredFlag(
7892 const analyze_printf::OptionalFlag &ignoredFlag,
7893 const analyze_printf::OptionalFlag &flag,
7894 const char *startSpecifier,
7895 unsigned specifierLen) {
7896 // Warn about ignored flag with a fixit removal.
7897 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7898 << ignoredFlag.toString() << flag.toString(),
7899 getLocationOfByte(ignoredFlag.getPosition()),
7900 /*IsStringLocation*/true,
7901 getSpecifierRange(startSpecifier, specifierLen),
7903 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7904}
7905
7906void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7907 unsigned flagLen) {
7908 // Warn about an empty flag.
7909 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7910 getLocationOfByte(startFlag),
7911 /*IsStringLocation*/true,
7912 getSpecifierRange(startFlag, flagLen));
7913}
7914
7915void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7916 unsigned flagLen) {
7917 // Warn about an invalid flag.
7918 auto Range = getSpecifierRange(startFlag, flagLen);
7919 StringRef flag(startFlag, flagLen);
7920 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7921 getLocationOfByte(startFlag),
7922 /*IsStringLocation*/true,
7923 Range, FixItHint::CreateRemoval(Range));
7924}
7925
7926void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7927 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7928 // Warn about using '[...]' without a '@' conversion.
7929 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7930 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7931 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7932 getLocationOfByte(conversionPosition),
7933 /*IsStringLocation*/ true, Range,
7935}
7936
7937void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
7938 const Expr *FmtExpr,
7939 bool InFunctionCall) const {
7940 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
7941 ElementLoc, true, Range);
7942}
7943
7944bool EquatableFormatArgument::VerifyCompatible(
7945 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
7946 bool InFunctionCall) const {
7948 if (Role != Other.Role) {
7949 // diagnose and stop
7950 EmitDiagnostic(
7951 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
7952 FmtExpr, InFunctionCall);
7953 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7954 return false;
7955 }
7956
7957 if (Role != FAR_Data) {
7958 if (ModifierFor != Other.ModifierFor) {
7959 // diagnose and stop
7960 EmitDiagnostic(S,
7961 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
7962 << (ModifierFor + 1) << (Other.ModifierFor + 1),
7963 FmtExpr, InFunctionCall);
7964 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7965 return false;
7966 }
7967 return true;
7968 }
7969
7970 bool HadError = false;
7971 if (Sensitivity != Other.Sensitivity) {
7972 // diagnose and continue
7973 EmitDiagnostic(S,
7974 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
7975 << Sensitivity << Other.Sensitivity,
7976 FmtExpr, InFunctionCall);
7977 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7978 << 0 << Other.Range;
7979 }
7980
7981 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
7982 case MK::Match:
7983 break;
7984
7985 case MK::MatchPromotion:
7986 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
7987 // MatchPromotion is treated as a failure by format_matches.
7988 case MK::NoMatch:
7989 case MK::NoMatchTypeConfusion:
7990 case MK::NoMatchPromotionTypeConfusion:
7991 EmitDiagnostic(S,
7992 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
7993 << buildFormatSpecifier()
7994 << Other.buildFormatSpecifier(),
7995 FmtExpr, InFunctionCall);
7996 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7997 << 0 << Other.Range;
7998 break;
7999
8000 case MK::NoMatchPedantic:
8001 EmitDiagnostic(S,
8002 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8003 << buildFormatSpecifier()
8004 << Other.buildFormatSpecifier(),
8005 FmtExpr, InFunctionCall);
8006 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8007 << 0 << Other.Range;
8008 break;
8009
8010 case MK::NoMatchSignedness:
8011 EmitDiagnostic(S,
8012 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8013 << buildFormatSpecifier()
8014 << Other.buildFormatSpecifier(),
8015 FmtExpr, InFunctionCall);
8016 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8017 << 0 << Other.Range;
8018 break;
8019 }
8020 return !HadError;
8021}
8022
8023bool DecomposePrintfHandler::GetSpecifiers(
8024 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8025 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8027 StringRef Data = FSL->getString();
8028 const char *Str = Data.data();
8029 llvm::SmallBitVector BV;
8030 UncoveredArgHandler UA;
8031 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8032 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8033 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8034 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8035 UA, Args);
8036
8038 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8040 H.DoneProcessing();
8041 if (H.HadError)
8042 return false;
8043
8044 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8045 const EquatableFormatArgument &B) {
8046 return A.getPosition() < B.getPosition();
8047 });
8048 return true;
8049}
8050
8051bool DecomposePrintfHandler::HandlePrintfSpecifier(
8052 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8053 unsigned specifierLen, const TargetInfo &Target) {
8054 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8055 specifierLen, Target)) {
8056 HadError = true;
8057 return false;
8058 }
8059
8060 // Do not add any specifiers to the list for %%. This is possibly incorrect
8061 // if using a precision/width with a data argument, but that combination is
8062 // meaningless and we wouldn't know which format to attach the
8063 // precision/width to.
8064 const auto &CS = FS.getConversionSpecifier();
8066 return true;
8067
8068 // have to patch these to have the right ModifierFor if they are used
8069 const unsigned Unset = ~0;
8070 unsigned FieldWidthIndex = Unset;
8071 unsigned PrecisionIndex = Unset;
8072
8073 // field width?
8074 const auto &FieldWidth = FS.getFieldWidth();
8075 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8076 FieldWidthIndex = Specs.size();
8077 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8078 getLocationOfByte(FieldWidth.getStart()),
8080 FieldWidth.getArgType(S.Context),
8081 EquatableFormatArgument::FAR_FieldWidth,
8082 EquatableFormatArgument::SS_None,
8083 FieldWidth.usesPositionalArg()
8084 ? FieldWidth.getPositionalArgIndex() - 1
8085 : FieldWidthIndex,
8086 0);
8087 }
8088 // precision?
8089 const auto &Precision = FS.getPrecision();
8090 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8091 PrecisionIndex = Specs.size();
8092 Specs.emplace_back(
8093 getSpecifierRange(startSpecifier, specifierLen),
8094 getLocationOfByte(Precision.getStart()),
8096 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8097 EquatableFormatArgument::SS_None,
8098 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8099 : PrecisionIndex,
8100 0);
8101 }
8102
8103 // this specifier
8104 unsigned SpecIndex =
8105 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8106 if (FieldWidthIndex != Unset)
8107 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8108 if (PrecisionIndex != Unset)
8109 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8110
8111 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8112 if (FS.isPrivate())
8113 Sensitivity = EquatableFormatArgument::SS_Private;
8114 else if (FS.isPublic())
8115 Sensitivity = EquatableFormatArgument::SS_Public;
8116 else if (FS.isSensitive())
8117 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8118 else
8119 Sensitivity = EquatableFormatArgument::SS_None;
8120
8121 Specs.emplace_back(
8122 getSpecifierRange(startSpecifier, specifierLen),
8123 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8124 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8125 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8126
8127 // auxiliary argument?
8130 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8131 getLocationOfByte(CS.getStart()),
8133 CS.getCharacters(),
8135 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8136 SpecIndex + 1, SpecIndex);
8137 }
8138 return true;
8139}
8140
8141// Determines if the specified is a C++ class or struct containing
8142// a member with the specified name and kind (e.g. a CXXMethodDecl named
8143// "c_str()").
8144template<typename MemberKind>
8146CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8147 auto *RD = Ty->getAsCXXRecordDecl();
8149
8150 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8151 return Results;
8152
8153 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8156
8157 // We just need to include all members of the right kind turned up by the
8158 // filter, at this point.
8159 if (S.LookupQualifiedName(R, RD))
8160 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8161 NamedDecl *decl = (*I)->getUnderlyingDecl();
8162 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8163 Results.insert(FK);
8164 }
8165 return Results;
8166}
8167
8168/// Check if we could call '.c_str()' on an object.
8169///
8170/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8171/// allow the call, or if it would be ambiguous).
8173 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8174
8175 MethodSet Results =
8176 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8177 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8178 MI != ME; ++MI)
8179 if ((*MI)->getMinRequiredArguments() == 0)
8180 return true;
8181 return false;
8182}
8183
8184// Check if a (w)string was passed when a (w)char* was needed, and offer a
8185// better diagnostic if so. AT is assumed to be valid.
8186// Returns true when a c_str() conversion method is found.
8187bool CheckPrintfHandler::checkForCStrMembers(
8188 const analyze_printf::ArgType &AT, const Expr *E) {
8189 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8190
8191 MethodSet Results =
8193
8194 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8195 MI != ME; ++MI) {
8196 const CXXMethodDecl *Method = *MI;
8197 if (Method->getMinRequiredArguments() == 0 &&
8198 AT.matchesType(S.Context, Method->getReturnType())) {
8199 // FIXME: Suggest parens if the expression needs them.
8201 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8202 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8203 return true;
8204 }
8205 }
8206
8207 return false;
8208}
8209
8210bool CheckPrintfHandler::HandlePrintfSpecifier(
8211 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8212 unsigned specifierLen, const TargetInfo &Target) {
8213 using namespace analyze_format_string;
8214 using namespace analyze_printf;
8215
8216 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8217
8218 if (FS.consumesDataArgument()) {
8219 if (atFirstArg) {
8220 atFirstArg = false;
8221 usesPositionalArgs = FS.usesPositionalArg();
8222 }
8223 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8224 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8225 startSpecifier, specifierLen);
8226 return false;
8227 }
8228 }
8229
8230 // First check if the field width, precision, and conversion specifier
8231 // have matching data arguments.
8232 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8233 startSpecifier, specifierLen)) {
8234 return false;
8235 }
8236
8237 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8238 startSpecifier, specifierLen)) {
8239 return false;
8240 }
8241
8242 if (!CS.consumesDataArgument()) {
8243 // FIXME: Technically specifying a precision or field width here
8244 // makes no sense. Worth issuing a warning at some point.
8245 return true;
8246 }
8247
8248 // Consume the argument.
8249 unsigned argIndex = FS.getArgIndex();
8250 if (argIndex < NumDataArgs) {
8251 // The check to see if the argIndex is valid will come later.
8252 // We set the bit here because we may exit early from this
8253 // function if we encounter some other error.
8254 CoveredArgs.set(argIndex);
8255 }
8256
8257 // FreeBSD kernel extensions.
8258 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8259 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8260 // We need at least two arguments.
8261 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8262 return false;
8263
8264 if (HasFormatArguments()) {
8265 // Claim the second argument.
8266 CoveredArgs.set(argIndex + 1);
8267
8268 // Type check the first argument (int for %b, pointer for %D)
8269 const Expr *Ex = getDataArg(argIndex);
8270 const analyze_printf::ArgType &AT =
8271 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8272 ? ArgType(S.Context.IntTy)
8273 : ArgType::CPointerTy;
8274 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8275 EmitFormatDiagnostic(
8276 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8277 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8278 << false << Ex->getSourceRange(),
8279 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8280 getSpecifierRange(startSpecifier, specifierLen));
8281
8282 // Type check the second argument (char * for both %b and %D)
8283 Ex = getDataArg(argIndex + 1);
8285 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8286 EmitFormatDiagnostic(
8287 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8288 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8289 << false << Ex->getSourceRange(),
8290 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8291 getSpecifierRange(startSpecifier, specifierLen));
8292 }
8293 return true;
8294 }
8295
8296 // Check for using an Objective-C specific conversion specifier
8297 // in a non-ObjC literal.
8298 if (!allowsObjCArg() && CS.isObjCArg()) {
8299 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8300 specifierLen);
8301 }
8302
8303 // %P can only be used with os_log.
8304 if (FSType != FormatStringType::OSLog &&
8305 CS.getKind() == ConversionSpecifier::PArg) {
8306 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8307 specifierLen);
8308 }
8309
8310 // %n is not allowed with os_log.
8311 if (FSType == FormatStringType::OSLog &&
8312 CS.getKind() == ConversionSpecifier::nArg) {
8313 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8314 getLocationOfByte(CS.getStart()),
8315 /*IsStringLocation*/ false,
8316 getSpecifierRange(startSpecifier, specifierLen));
8317
8318 return true;
8319 }
8320
8321 // Only scalars are allowed for os_trace.
8322 if (FSType == FormatStringType::OSTrace &&
8323 (CS.getKind() == ConversionSpecifier::PArg ||
8324 CS.getKind() == ConversionSpecifier::sArg ||
8325 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8326 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8327 specifierLen);
8328 }
8329
8330 // Check for use of public/private annotation outside of os_log().
8331 if (FSType != FormatStringType::OSLog) {
8332 if (FS.isPublic().isSet()) {
8333 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8334 << "public",
8335 getLocationOfByte(FS.isPublic().getPosition()),
8336 /*IsStringLocation*/ false,
8337 getSpecifierRange(startSpecifier, specifierLen));
8338 }
8339 if (FS.isPrivate().isSet()) {
8340 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8341 << "private",
8342 getLocationOfByte(FS.isPrivate().getPosition()),
8343 /*IsStringLocation*/ false,
8344 getSpecifierRange(startSpecifier, specifierLen));
8345 }
8346 }
8347
8348 const llvm::Triple &Triple = Target.getTriple();
8349 if (CS.getKind() == ConversionSpecifier::nArg &&
8350 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8351 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8352 getLocationOfByte(CS.getStart()),
8353 /*IsStringLocation*/ false,
8354 getSpecifierRange(startSpecifier, specifierLen));
8355 }
8356
8357 // Check for invalid use of field width
8358 if (!FS.hasValidFieldWidth()) {
8359 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8360 startSpecifier, specifierLen);
8361 }
8362
8363 // Check for invalid use of precision
8364 if (!FS.hasValidPrecision()) {
8365 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8366 startSpecifier, specifierLen);
8367 }
8368
8369 // Precision is mandatory for %P specifier.
8370 if (CS.getKind() == ConversionSpecifier::PArg &&
8372 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8373 getLocationOfByte(startSpecifier),
8374 /*IsStringLocation*/ false,
8375 getSpecifierRange(startSpecifier, specifierLen));
8376 }
8377
8378 // Check each flag does not conflict with any other component.
8380 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8381 if (!FS.hasValidLeadingZeros())
8382 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8383 if (!FS.hasValidPlusPrefix())
8384 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8385 if (!FS.hasValidSpacePrefix())
8386 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8387 if (!FS.hasValidAlternativeForm())
8388 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8389 if (!FS.hasValidLeftJustified())
8390 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8391
8392 // Check that flags are not ignored by another flag
8393 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8394 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8395 startSpecifier, specifierLen);
8396 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8397 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8398 startSpecifier, specifierLen);
8399
8400 // Check the length modifier is valid with the given conversion specifier.
8402 S.getLangOpts()))
8403 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8404 diag::warn_format_nonsensical_length);
8405 else if (!FS.hasStandardLengthModifier())
8406 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8408 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8409 diag::warn_format_non_standard_conversion_spec);
8410
8412 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8413
8414 // The remaining checks depend on the data arguments.
8415 if (!HasFormatArguments())
8416 return true;
8417
8418 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8419 return false;
8420
8421 const Expr *Arg = getDataArg(argIndex);
8422 if (!Arg)
8423 return true;
8424
8425 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8426}
8427
8428static bool requiresParensToAddCast(const Expr *E) {
8429 // FIXME: We should have a general way to reason about operator
8430 // precedence and whether parens are actually needed here.
8431 // Take care of a few common cases where they aren't.
8432 const Expr *Inside = E->IgnoreImpCasts();
8433 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8434 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8435
8436 switch (Inside->getStmtClass()) {
8437 case Stmt::ArraySubscriptExprClass:
8438 case Stmt::CallExprClass:
8439 case Stmt::CharacterLiteralClass:
8440 case Stmt::CXXBoolLiteralExprClass:
8441 case Stmt::DeclRefExprClass:
8442 case Stmt::FloatingLiteralClass:
8443 case Stmt::IntegerLiteralClass:
8444 case Stmt::MemberExprClass:
8445 case Stmt::ObjCArrayLiteralClass:
8446 case Stmt::ObjCBoolLiteralExprClass:
8447 case Stmt::ObjCBoxedExprClass:
8448 case Stmt::ObjCDictionaryLiteralClass:
8449 case Stmt::ObjCEncodeExprClass:
8450 case Stmt::ObjCIvarRefExprClass:
8451 case Stmt::ObjCMessageExprClass:
8452 case Stmt::ObjCPropertyRefExprClass:
8453 case Stmt::ObjCStringLiteralClass:
8454 case Stmt::ObjCSubscriptRefExprClass:
8455 case Stmt::ParenExprClass:
8456 case Stmt::StringLiteralClass:
8457 case Stmt::UnaryOperatorClass:
8458 return false;
8459 default:
8460 return true;
8461 }
8462}
8463
8464static std::pair<QualType, StringRef>
8466 QualType IntendedTy,
8467 const Expr *E) {
8468 // Use a 'while' to peel off layers of typedefs.
8469 QualType TyTy = IntendedTy;
8470 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8471 StringRef Name = UserTy->getDecl()->getName();
8472 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8473 .Case("CFIndex", Context.getNSIntegerType())
8474 .Case("NSInteger", Context.getNSIntegerType())
8475 .Case("NSUInteger", Context.getNSUIntegerType())
8476 .Case("SInt32", Context.IntTy)
8477 .Case("UInt32", Context.UnsignedIntTy)
8478 .Default(QualType());
8479
8480 if (!CastTy.isNull())
8481 return std::make_pair(CastTy, Name);
8482
8483 TyTy = UserTy->desugar();
8484 }
8485
8486 // Strip parens if necessary.
8487 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8488 return shouldNotPrintDirectly(Context,
8489 PE->getSubExpr()->getType(),
8490 PE->getSubExpr());
8491
8492 // If this is a conditional expression, then its result type is constructed
8493 // via usual arithmetic conversions and thus there might be no necessary
8494 // typedef sugar there. Recurse to operands to check for NSInteger &
8495 // Co. usage condition.
8496 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8497 QualType TrueTy, FalseTy;
8498 StringRef TrueName, FalseName;
8499
8500 std::tie(TrueTy, TrueName) =
8501 shouldNotPrintDirectly(Context,
8502 CO->getTrueExpr()->getType(),
8503 CO->getTrueExpr());
8504 std::tie(FalseTy, FalseName) =
8505 shouldNotPrintDirectly(Context,
8506 CO->getFalseExpr()->getType(),
8507 CO->getFalseExpr());
8508
8509 if (TrueTy == FalseTy)
8510 return std::make_pair(TrueTy, TrueName);
8511 else if (TrueTy.isNull())
8512 return std::make_pair(FalseTy, FalseName);
8513 else if (FalseTy.isNull())
8514 return std::make_pair(TrueTy, TrueName);
8515 }
8516
8517 return std::make_pair(QualType(), StringRef());
8518}
8519
8520/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8521/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8522/// type do not count.
8523static bool
8525 QualType From = ICE->getSubExpr()->getType();
8526 QualType To = ICE->getType();
8527 // It's an integer promotion if the destination type is the promoted
8528 // source type.
8529 if (ICE->getCastKind() == CK_IntegralCast &&
8531 S.Context.getPromotedIntegerType(From) == To)
8532 return true;
8533 // Look through vector types, since we do default argument promotion for
8534 // those in OpenCL.
8535 if (const auto *VecTy = From->getAs<ExtVectorType>())
8536 From = VecTy->getElementType();
8537 if (const auto *VecTy = To->getAs<ExtVectorType>())
8538 To = VecTy->getElementType();
8539 // It's a floating promotion if the source type is a lower rank.
8540 return ICE->getCastKind() == CK_FloatingCast &&
8541 S.Context.getFloatingTypeOrder(From, To) < 0;
8542}
8543
8546 DiagnosticsEngine &Diags, SourceLocation Loc) {
8548 if (Diags.isIgnored(
8549 diag::warn_format_conversion_argument_type_mismatch_signedness,
8550 Loc) ||
8551 Diags.isIgnored(
8552 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8553 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8555 }
8556 }
8557 return Match;
8558}
8559
8560bool
8561CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8562 const char *StartSpecifier,
8563 unsigned SpecifierLen,
8564 const Expr *E) {
8565 using namespace analyze_format_string;
8566 using namespace analyze_printf;
8567
8568 // Now type check the data expression that matches the
8569 // format specifier.
8570 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8571 if (!AT.isValid())
8572 return true;
8573
8574 QualType ExprTy = E->getType();
8575 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8576 ExprTy = TET->getUnderlyingExpr()->getType();
8577 }
8578
8579 // When using the format attribute in C++, you can receive a function or an
8580 // array that will necessarily decay to a pointer when passed to the final
8581 // format consumer. Apply decay before type comparison.
8582 if (ExprTy->canDecayToPointerType())
8583 ExprTy = S.Context.getDecayedType(ExprTy);
8584
8585 // Diagnose attempts to print a boolean value as a character. Unlike other
8586 // -Wformat diagnostics, this is fine from a type perspective, but it still
8587 // doesn't make sense.
8590 const CharSourceRange &CSR =
8591 getSpecifierRange(StartSpecifier, SpecifierLen);
8592 SmallString<4> FSString;
8593 llvm::raw_svector_ostream os(FSString);
8594 FS.toString(os);
8595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8596 << FSString,
8597 E->getExprLoc(), false, CSR);
8598 return true;
8599 }
8600
8601 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8602 // dumping raw class data (like is-a pointer), not actual data.
8604 ExprTy->isObjCObjectPointerType()) {
8605 const CharSourceRange &CSR =
8606 getSpecifierRange(StartSpecifier, SpecifierLen);
8607 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8608 E->getExprLoc(), false, CSR);
8609 return true;
8610 }
8611
8612 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8614 ArgType::MatchKind OrigMatch = Match;
8615
8617 if (Match == ArgType::Match)
8618 return true;
8619
8620 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8621 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8622
8623 // Look through argument promotions for our error message's reported type.
8624 // This includes the integral and floating promotions, but excludes array
8625 // and function pointer decay (seeing that an argument intended to be a
8626 // string has type 'char [6]' is probably more confusing than 'char *') and
8627 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8628 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8629 if (isArithmeticArgumentPromotion(S, ICE)) {
8630 E = ICE->getSubExpr();
8631 ExprTy = E->getType();
8632
8633 // Check if we didn't match because of an implicit cast from a 'char'
8634 // or 'short' to an 'int'. This is done because printf is a varargs
8635 // function.
8636 if (ICE->getType() == S.Context.IntTy ||
8637 ICE->getType() == S.Context.UnsignedIntTy) {
8638 // All further checking is done on the subexpression
8639 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8640 if (OrigMatch == ArgType::NoMatchSignedness &&
8641 ImplicitMatch != ArgType::NoMatchSignedness)
8642 // If the original match was a signedness match this match on the
8643 // implicit cast type also need to be signedness match otherwise we
8644 // might introduce new unexpected warnings from -Wformat-signedness.
8645 return true;
8646 ImplicitMatch = handleFormatSignedness(
8647 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8648 if (ImplicitMatch == ArgType::Match)
8649 return true;
8650 }
8651 }
8652 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8653 // Special case for 'a', which has type 'int' in C.
8654 // Note, however, that we do /not/ want to treat multibyte constants like
8655 // 'MooV' as characters! This form is deprecated but still exists. In
8656 // addition, don't treat expressions as of type 'char' if one byte length
8657 // modifier is provided.
8658 if (ExprTy == S.Context.IntTy &&
8660 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8661 ExprTy = S.Context.CharTy;
8662 // To improve check results, we consider a character literal in C
8663 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8664 // more likely a type confusion situation, so we will suggest to
8665 // use '%hhd' instead by discarding the MatchPromotion.
8666 if (Match == ArgType::MatchPromotion)
8668 }
8669 }
8670 if (Match == ArgType::MatchPromotion) {
8671 // WG14 N2562 only clarified promotions in *printf
8672 // For NSLog in ObjC, just preserve -Wformat behavior
8673 if (!S.getLangOpts().ObjC &&
8674 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8675 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8676 return true;
8678 }
8679 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8680 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8681 Match = ImplicitMatch;
8682 assert(Match != ArgType::MatchPromotion);
8683
8684 // Look through unscoped enums to their underlying type.
8685 bool IsEnum = false;
8686 bool IsScopedEnum = false;
8687 QualType IntendedTy = ExprTy;
8688 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8689 IntendedTy = ED->getIntegerType();
8690 if (!ED->isScoped()) {
8691 ExprTy = IntendedTy;
8692 // This controls whether we're talking about the underlying type or not,
8693 // which we only want to do when it's an unscoped enum.
8694 IsEnum = true;
8695 } else {
8696 IsScopedEnum = true;
8697 }
8698 }
8699
8700 // %C in an Objective-C context prints a unichar, not a wchar_t.
8701 // If the argument is an integer of some kind, believe the %C and suggest
8702 // a cast instead of changing the conversion specifier.
8703 if (isObjCContext() &&
8706 !ExprTy->isCharType()) {
8707 // 'unichar' is defined as a typedef of unsigned short, but we should
8708 // prefer using the typedef if it is visible.
8709 IntendedTy = S.Context.UnsignedShortTy;
8710
8711 // While we are here, check if the value is an IntegerLiteral that happens
8712 // to be within the valid range.
8713 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8714 const llvm::APInt &V = IL->getValue();
8715 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8716 return true;
8717 }
8718
8719 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8721 if (S.LookupName(Result, S.getCurScope())) {
8722 NamedDecl *ND = Result.getFoundDecl();
8723 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8724 if (TD->getUnderlyingType() == IntendedTy)
8725 IntendedTy =
8727 /*Qualifier=*/std::nullopt, TD);
8728 }
8729 }
8730 }
8731
8732 // Special-case some of Darwin's platform-independence types by suggesting
8733 // casts to primitive types that are known to be large enough.
8734 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8735 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8736 QualType CastTy;
8737 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8738 if (!CastTy.isNull()) {
8739 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8740 // (long in ASTContext). Only complain to pedants or when they're the
8741 // underlying type of a scoped enum (which always needs a cast).
8742 if (!IsScopedEnum &&
8743 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8744 (AT.isSizeT() || AT.isPtrdiffT()) &&
8745 AT.matchesType(S.Context, CastTy))
8747 IntendedTy = CastTy;
8748 ShouldNotPrintDirectly = true;
8749 }
8750 }
8751
8752 // We may be able to offer a FixItHint if it is a supported type.
8753 PrintfSpecifier fixedFS = FS;
8754 bool Success =
8755 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8756
8757 if (Success) {
8758 // Get the fix string from the fixed format specifier
8759 SmallString<16> buf;
8760 llvm::raw_svector_ostream os(buf);
8761 fixedFS.toString(os);
8762
8763 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8764
8765 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8766 unsigned Diag;
8767 switch (Match) {
8768 case ArgType::Match:
8771 llvm_unreachable("expected non-matching");
8773 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8774 break;
8776 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8777 break;
8779 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8780 break;
8781 case ArgType::NoMatch:
8782 Diag = diag::warn_format_conversion_argument_type_mismatch;
8783 break;
8784 }
8785
8786 // In this case, the specifier is wrong and should be changed to match
8787 // the argument.
8788 EmitFormatDiagnostic(S.PDiag(Diag)
8790 << IntendedTy << IsEnum << E->getSourceRange(),
8791 E->getBeginLoc(),
8792 /*IsStringLocation*/ false, SpecRange,
8793 FixItHint::CreateReplacement(SpecRange, os.str()));
8794 } else {
8795 // The canonical type for formatting this value is different from the
8796 // actual type of the expression. (This occurs, for example, with Darwin's
8797 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8798 // should be printed as 'long' for 64-bit compatibility.)
8799 // Rather than emitting a normal format/argument mismatch, we want to
8800 // add a cast to the recommended type (and correct the format string
8801 // if necessary). We should also do so for scoped enumerations.
8802 SmallString<16> CastBuf;
8803 llvm::raw_svector_ostream CastFix(CastBuf);
8804 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
8805 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8806 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
8807
8809 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
8810 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
8811 E->getExprLoc());
8812 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
8813 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8814
8815 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8816 // If there's already a cast present, just replace it.
8817 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8818 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8819
8820 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
8821 // If the expression has high enough precedence,
8822 // just write the C-style cast.
8823 Hints.push_back(
8824 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8825 } else {
8826 // Otherwise, add parens around the expression as well as the cast.
8827 CastFix << "(";
8828 Hints.push_back(
8829 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8830
8831 // We don't use getLocForEndOfToken because it returns invalid source
8832 // locations for macro expansions (by design).
8836 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8837 }
8838
8839 if (ShouldNotPrintDirectly && !IsScopedEnum) {
8840 // The expression has a type that should not be printed directly.
8841 // We extract the name from the typedef because we don't want to show
8842 // the underlying type in the diagnostic.
8843 StringRef Name;
8844 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
8845 Name = TypedefTy->getDecl()->getName();
8846 else
8847 Name = CastTyName;
8848 unsigned Diag = Match == ArgType::NoMatchPedantic
8849 ? diag::warn_format_argument_needs_cast_pedantic
8850 : diag::warn_format_argument_needs_cast;
8851 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8852 << E->getSourceRange(),
8853 E->getBeginLoc(), /*IsStringLocation=*/false,
8854 SpecRange, Hints);
8855 } else {
8856 // In this case, the expression could be printed using a different
8857 // specifier, but we've decided that the specifier is probably correct
8858 // and we should cast instead. Just use the normal warning message.
8859
8860 unsigned Diag =
8861 IsScopedEnum
8862 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8863 : diag::warn_format_conversion_argument_type_mismatch;
8864
8865 EmitFormatDiagnostic(
8866 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8867 << IsEnum << E->getSourceRange(),
8868 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8869 }
8870 }
8871 } else {
8872 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8873 SpecifierLen);
8874 // Since the warning for passing non-POD types to variadic functions
8875 // was deferred until now, we emit a warning for non-POD
8876 // arguments here.
8877 bool EmitTypeMismatch = false;
8878 switch (S.isValidVarArgType(ExprTy)) {
8879 case VarArgKind::Valid:
8881 unsigned Diag;
8882 switch (Match) {
8883 case ArgType::Match:
8886 llvm_unreachable("expected non-matching");
8888 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8889 break;
8891 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8892 break;
8894 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8895 break;
8896 case ArgType::NoMatch:
8897 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
8898 ? diag::err_format_conversion_argument_type_mismatch
8899 : diag::warn_format_conversion_argument_type_mismatch;
8900 break;
8901 }
8902
8903 EmitFormatDiagnostic(
8904 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8905 << IsEnum << CSR << E->getSourceRange(),
8906 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8907 break;
8908 }
8911 if (CallType == VariadicCallType::DoesNotApply) {
8912 EmitTypeMismatch = true;
8913 } else {
8914 EmitFormatDiagnostic(
8915 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8916 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8917 << AT.getRepresentativeTypeName(S.Context) << CSR
8918 << E->getSourceRange(),
8919 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8920 checkForCStrMembers(AT, E);
8921 }
8922 break;
8923
8925 if (CallType == VariadicCallType::DoesNotApply)
8926 EmitTypeMismatch = true;
8927 else if (ExprTy->isObjCObjectType())
8928 EmitFormatDiagnostic(
8929 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8930 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8931 << AT.getRepresentativeTypeName(S.Context) << CSR
8932 << E->getSourceRange(),
8933 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8934 else
8935 // FIXME: If this is an initializer list, suggest removing the braces
8936 // or inserting a cast to the target type.
8937 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8938 << isa<InitListExpr>(E) << ExprTy << CallType
8940 break;
8941 }
8942
8943 if (EmitTypeMismatch) {
8944 // The function is not variadic, so we do not generate warnings about
8945 // being allowed to pass that object as a variadic argument. Instead,
8946 // since there are inherently no printf specifiers for types which cannot
8947 // be passed as variadic arguments, emit a plain old specifier mismatch
8948 // argument.
8949 EmitFormatDiagnostic(
8950 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8951 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8952 << E->getSourceRange(),
8953 E->getBeginLoc(), false, CSR);
8954 }
8955
8956 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8957 "format string specifier index out of range");
8958 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8959 }
8960
8961 return true;
8962}
8963
8964//===--- CHECK: Scanf format string checking ------------------------------===//
8965
8966namespace {
8967
8968class CheckScanfHandler : public CheckFormatHandler {
8969public:
8970 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8971 const Expr *origFormatExpr, FormatStringType type,
8972 unsigned firstDataArg, unsigned numDataArgs,
8973 const char *beg, Sema::FormatArgumentPassingKind APK,
8974 ArrayRef<const Expr *> Args, unsigned formatIdx,
8975 bool inFunctionCall, VariadicCallType CallType,
8976 llvm::SmallBitVector &CheckedVarArgs,
8977 UncoveredArgHandler &UncoveredArg)
8978 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8979 numDataArgs, beg, APK, Args, formatIdx,
8980 inFunctionCall, CallType, CheckedVarArgs,
8981 UncoveredArg) {}
8982
8983 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8984 const char *startSpecifier,
8985 unsigned specifierLen) override;
8986
8987 bool HandleInvalidScanfConversionSpecifier(
8988 const analyze_scanf::ScanfSpecifier &FS,
8989 const char *startSpecifier,
8990 unsigned specifierLen) override;
8991
8992 void HandleIncompleteScanList(const char *start, const char *end) override;
8993};
8994
8995} // namespace
8996
8997void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8998 const char *end) {
8999 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9000 getLocationOfByte(end), /*IsStringLocation*/true,
9001 getSpecifierRange(start, end - start));
9002}
9003
9004bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9006 const char *startSpecifier,
9007 unsigned specifierLen) {
9010
9011 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9012 getLocationOfByte(CS.getStart()),
9013 startSpecifier, specifierLen,
9014 CS.getStart(), CS.getLength());
9015}
9016
9017bool CheckScanfHandler::HandleScanfSpecifier(
9019 const char *startSpecifier,
9020 unsigned specifierLen) {
9021 using namespace analyze_scanf;
9022 using namespace analyze_format_string;
9023
9024 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9025
9026 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9027 // be used to decide if we are using positional arguments consistently.
9028 if (FS.consumesDataArgument()) {
9029 if (atFirstArg) {
9030 atFirstArg = false;
9031 usesPositionalArgs = FS.usesPositionalArg();
9032 }
9033 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9034 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9035 startSpecifier, specifierLen);
9036 return false;
9037 }
9038 }
9039
9040 // Check if the field with is non-zero.
9041 const OptionalAmount &Amt = FS.getFieldWidth();
9043 if (Amt.getConstantAmount() == 0) {
9044 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9045 Amt.getConstantLength());
9046 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9047 getLocationOfByte(Amt.getStart()),
9048 /*IsStringLocation*/true, R,
9050 }
9051 }
9052
9053 if (!FS.consumesDataArgument()) {
9054 // FIXME: Technically specifying a precision or field width here
9055 // makes no sense. Worth issuing a warning at some point.
9056 return true;
9057 }
9058
9059 // Consume the argument.
9060 unsigned argIndex = FS.getArgIndex();
9061 if (argIndex < NumDataArgs) {
9062 // The check to see if the argIndex is valid will come later.
9063 // We set the bit here because we may exit early from this
9064 // function if we encounter some other error.
9065 CoveredArgs.set(argIndex);
9066 }
9067
9068 // Check the length modifier is valid with the given conversion specifier.
9070 S.getLangOpts()))
9071 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9072 diag::warn_format_nonsensical_length);
9073 else if (!FS.hasStandardLengthModifier())
9074 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9076 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9077 diag::warn_format_non_standard_conversion_spec);
9078
9080 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9081
9082 // The remaining checks depend on the data arguments.
9083 if (!HasFormatArguments())
9084 return true;
9085
9086 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9087 return false;
9088
9089 // Check that the argument type matches the format specifier.
9090 const Expr *Ex = getDataArg(argIndex);
9091 if (!Ex)
9092 return true;
9093
9095
9096 if (!AT.isValid()) {
9097 return true;
9098 }
9099
9101 AT.matchesType(S.Context, Ex->getType());
9104 return true;
9107
9108 ScanfSpecifier fixedFS = FS;
9109 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9110 S.getLangOpts(), S.Context);
9111
9112 unsigned Diag =
9113 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9114 : Signedness
9115 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9116 : diag::warn_format_conversion_argument_type_mismatch;
9117
9118 if (Success) {
9119 // Get the fix string from the fixed format specifier.
9120 SmallString<128> buf;
9121 llvm::raw_svector_ostream os(buf);
9122 fixedFS.toString(os);
9123
9124 EmitFormatDiagnostic(
9126 << Ex->getType() << false << Ex->getSourceRange(),
9127 Ex->getBeginLoc(),
9128 /*IsStringLocation*/ false,
9129 getSpecifierRange(startSpecifier, specifierLen),
9131 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9132 } else {
9133 EmitFormatDiagnostic(S.PDiag(Diag)
9135 << Ex->getType() << false << Ex->getSourceRange(),
9136 Ex->getBeginLoc(),
9137 /*IsStringLocation*/ false,
9138 getSpecifierRange(startSpecifier, specifierLen));
9139 }
9140
9141 return true;
9142}
9143
9144static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9146 const StringLiteral *Fmt,
9148 const Expr *FmtExpr, bool InFunctionCall) {
9149 bool HadError = false;
9150 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9151 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9152 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9153 // In positional-style format strings, the same specifier can appear
9154 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9155 // are sorted by getPosition(), and we process each range of equal
9156 // getPosition() values as one group.
9157 // RefArgs are taken from a string literal that was given to
9158 // attribute(format_matches), and if we got this far, we have already
9159 // verified that if it has positional specifiers that appear in multiple
9160 // locations, then they are all mutually compatible. What's left for us to
9161 // do is verify that all specifiers with the same position in FmtArgs are
9162 // compatible with the RefArgs specifiers. We check each specifier from
9163 // FmtArgs against the first member of the RefArgs group.
9164 for (; FmtIter < FmtEnd; ++FmtIter) {
9165 // Clang does not diagnose missing format specifiers in positional-style
9166 // strings (TODO: which it probably should do, as it is UB to skip over a
9167 // format argument). Skip specifiers if needed.
9168 if (FmtIter->getPosition() < RefIter->getPosition())
9169 continue;
9170
9171 // Delimits a new getPosition() value.
9172 if (FmtIter->getPosition() > RefIter->getPosition())
9173 break;
9174
9175 HadError |=
9176 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9177 }
9178
9179 // Jump RefIter to the start of the next group.
9180 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9181 return Arg.getPosition() != RefIter->getPosition();
9182 });
9183 }
9184
9185 if (FmtIter < FmtEnd) {
9186 CheckFormatHandler::EmitFormatDiagnostic(
9187 S, InFunctionCall, FmtExpr,
9188 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9189 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9190 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9191 } else if (RefIter < RefEnd) {
9192 CheckFormatHandler::EmitFormatDiagnostic(
9193 S, InFunctionCall, FmtExpr,
9194 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9195 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9196 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9197 << 1 << RefIter->getSourceRange();
9198 }
9199 return !HadError;
9200}
9201
9203 Sema &S, const FormatStringLiteral *FExpr,
9204 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9206 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9207 bool inFunctionCall, VariadicCallType CallType,
9208 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9209 bool IgnoreStringsWithoutSpecifiers) {
9210 // CHECK: is the format string a wide literal?
9211 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9212 CheckFormatHandler::EmitFormatDiagnostic(
9213 S, inFunctionCall, Args[format_idx],
9214 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9215 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9216 return;
9217 }
9218
9219 // Str - The format string. NOTE: this is NOT null-terminated!
9220 StringRef StrRef = FExpr->getString();
9221 const char *Str = StrRef.data();
9222 // Account for cases where the string literal is truncated in a declaration.
9223 const ConstantArrayType *T =
9224 S.Context.getAsConstantArrayType(FExpr->getType());
9225 assert(T && "String literal not of constant array type!");
9226 size_t TypeSize = T->getZExtSize();
9227 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9228 const unsigned numDataArgs = Args.size() - firstDataArg;
9229
9230 if (IgnoreStringsWithoutSpecifiers &&
9232 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9233 return;
9234
9235 // Emit a warning if the string literal is truncated and does not contain an
9236 // embedded null character.
9237 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9238 CheckFormatHandler::EmitFormatDiagnostic(
9239 S, inFunctionCall, Args[format_idx],
9240 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9241 FExpr->getBeginLoc(),
9242 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9243 return;
9244 }
9245
9246 // CHECK: empty format string?
9247 if (StrLen == 0 && numDataArgs > 0) {
9248 CheckFormatHandler::EmitFormatDiagnostic(
9249 S, inFunctionCall, Args[format_idx],
9250 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9251 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9252 return;
9253 }
9254
9259 bool IsObjC =
9261 if (ReferenceFormatString == nullptr) {
9262 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9263 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9264 inFunctionCall, CallType, CheckedVarArgs,
9265 UncoveredArg);
9266
9268 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9271 H.DoneProcessing();
9272 } else {
9274 Type, ReferenceFormatString, FExpr->getFormatString(),
9275 inFunctionCall ? nullptr : Args[format_idx]);
9276 }
9277 } else if (Type == FormatStringType::Scanf) {
9278 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9279 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9280 CallType, CheckedVarArgs, UncoveredArg);
9281
9283 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9284 H.DoneProcessing();
9285 } // TODO: handle other formats
9286}
9287
9289 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9290 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9295 return true;
9296
9297 bool IsObjC =
9300 FormatStringLiteral RefLit = AuthoritativeFormatString;
9301 FormatStringLiteral TestLit = TestedFormatString;
9302 const Expr *Arg;
9303 bool DiagAtStringLiteral;
9304 if (FunctionCallArg) {
9305 Arg = FunctionCallArg;
9306 DiagAtStringLiteral = false;
9307 } else {
9308 Arg = TestedFormatString;
9309 DiagAtStringLiteral = true;
9310 }
9311 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9312 AuthoritativeFormatString, Type,
9313 IsObjC, true, RefArgs) &&
9314 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9315 DiagAtStringLiteral, FmtArgs)) {
9316 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9317 TestedFormatString, FmtArgs, Arg,
9318 DiagAtStringLiteral);
9319 }
9320 return false;
9321}
9322
9324 const StringLiteral *Str) {
9329 return true;
9330
9331 FormatStringLiteral RefLit = Str;
9333 bool IsObjC =
9335 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9336 true, Args))
9337 return false;
9338
9339 // Group arguments by getPosition() value, and check that each member of the
9340 // group is compatible with the first member. This verifies that when
9341 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9342 // are mutually compatible. As an optimization, don't test the first member
9343 // against itself.
9344 bool HadError = false;
9345 auto Iter = Args.begin();
9346 auto End = Args.end();
9347 while (Iter != End) {
9348 const auto &FirstInGroup = *Iter;
9349 for (++Iter;
9350 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9351 ++Iter) {
9352 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9353 }
9354 }
9355 return !HadError;
9356}
9357
9359 // Str - The format string. NOTE: this is NOT null-terminated!
9360 StringRef StrRef = FExpr->getString();
9361 const char *Str = StrRef.data();
9362 // Account for cases where the string literal is truncated in a declaration.
9363 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9364 assert(T && "String literal not of constant array type!");
9365 size_t TypeSize = T->getZExtSize();
9366 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9367 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9368 getLangOpts(),
9369 Context.getTargetInfo());
9370}
9371
9372//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9373
9374// Returns the related absolute value function that is larger, of 0 if one
9375// does not exist.
9376static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9377 switch (AbsFunction) {
9378 default:
9379 return 0;
9380
9381 case Builtin::BI__builtin_abs:
9382 return Builtin::BI__builtin_labs;
9383 case Builtin::BI__builtin_labs:
9384 return Builtin::BI__builtin_llabs;
9385 case Builtin::BI__builtin_llabs:
9386 return 0;
9387
9388 case Builtin::BI__builtin_fabsf:
9389 return Builtin::BI__builtin_fabs;
9390 case Builtin::BI__builtin_fabs:
9391 return Builtin::BI__builtin_fabsl;
9392 case Builtin::BI__builtin_fabsl:
9393 return 0;
9394
9395 case Builtin::BI__builtin_cabsf:
9396 return Builtin::BI__builtin_cabs;
9397 case Builtin::BI__builtin_cabs:
9398 return Builtin::BI__builtin_cabsl;
9399 case Builtin::BI__builtin_cabsl:
9400 return 0;
9401
9402 case Builtin::BIabs:
9403 return Builtin::BIlabs;
9404 case Builtin::BIlabs:
9405 return Builtin::BIllabs;
9406 case Builtin::BIllabs:
9407 return 0;
9408
9409 case Builtin::BIfabsf:
9410 return Builtin::BIfabs;
9411 case Builtin::BIfabs:
9412 return Builtin::BIfabsl;
9413 case Builtin::BIfabsl:
9414 return 0;
9415
9416 case Builtin::BIcabsf:
9417 return Builtin::BIcabs;
9418 case Builtin::BIcabs:
9419 return Builtin::BIcabsl;
9420 case Builtin::BIcabsl:
9421 return 0;
9422 }
9423}
9424
9425// Returns the argument type of the absolute value function.
9427 unsigned AbsType) {
9428 if (AbsType == 0)
9429 return QualType();
9430
9432 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9434 return QualType();
9435
9437 if (!FT)
9438 return QualType();
9439
9440 if (FT->getNumParams() != 1)
9441 return QualType();
9442
9443 return FT->getParamType(0);
9444}
9445
9446// Returns the best absolute value function, or zero, based on type and
9447// current absolute value function.
9448static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9449 unsigned AbsFunctionKind) {
9450 unsigned BestKind = 0;
9451 uint64_t ArgSize = Context.getTypeSize(ArgType);
9452 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9453 Kind = getLargerAbsoluteValueFunction(Kind)) {
9454 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9455 if (Context.getTypeSize(ParamType) >= ArgSize) {
9456 if (BestKind == 0)
9457 BestKind = Kind;
9458 else if (Context.hasSameType(ParamType, ArgType)) {
9459 BestKind = Kind;
9460 break;
9461 }
9462 }
9463 }
9464 return BestKind;
9465}
9466
9472
9474 if (T->isIntegralOrEnumerationType())
9475 return AVK_Integer;
9476 if (T->isRealFloatingType())
9477 return AVK_Floating;
9478 if (T->isAnyComplexType())
9479 return AVK_Complex;
9480
9481 llvm_unreachable("Type not integer, floating, or complex");
9482}
9483
9484// Changes the absolute value function to a different type. Preserves whether
9485// the function is a builtin.
9486static unsigned changeAbsFunction(unsigned AbsKind,
9487 AbsoluteValueKind ValueKind) {
9488 switch (ValueKind) {
9489 case AVK_Integer:
9490 switch (AbsKind) {
9491 default:
9492 return 0;
9493 case Builtin::BI__builtin_fabsf:
9494 case Builtin::BI__builtin_fabs:
9495 case Builtin::BI__builtin_fabsl:
9496 case Builtin::BI__builtin_cabsf:
9497 case Builtin::BI__builtin_cabs:
9498 case Builtin::BI__builtin_cabsl:
9499 return Builtin::BI__builtin_abs;
9500 case Builtin::BIfabsf:
9501 case Builtin::BIfabs:
9502 case Builtin::BIfabsl:
9503 case Builtin::BIcabsf:
9504 case Builtin::BIcabs:
9505 case Builtin::BIcabsl:
9506 return Builtin::BIabs;
9507 }
9508 case AVK_Floating:
9509 switch (AbsKind) {
9510 default:
9511 return 0;
9512 case Builtin::BI__builtin_abs:
9513 case Builtin::BI__builtin_labs:
9514 case Builtin::BI__builtin_llabs:
9515 case Builtin::BI__builtin_cabsf:
9516 case Builtin::BI__builtin_cabs:
9517 case Builtin::BI__builtin_cabsl:
9518 return Builtin::BI__builtin_fabsf;
9519 case Builtin::BIabs:
9520 case Builtin::BIlabs:
9521 case Builtin::BIllabs:
9522 case Builtin::BIcabsf:
9523 case Builtin::BIcabs:
9524 case Builtin::BIcabsl:
9525 return Builtin::BIfabsf;
9526 }
9527 case AVK_Complex:
9528 switch (AbsKind) {
9529 default:
9530 return 0;
9531 case Builtin::BI__builtin_abs:
9532 case Builtin::BI__builtin_labs:
9533 case Builtin::BI__builtin_llabs:
9534 case Builtin::BI__builtin_fabsf:
9535 case Builtin::BI__builtin_fabs:
9536 case Builtin::BI__builtin_fabsl:
9537 return Builtin::BI__builtin_cabsf;
9538 case Builtin::BIabs:
9539 case Builtin::BIlabs:
9540 case Builtin::BIllabs:
9541 case Builtin::BIfabsf:
9542 case Builtin::BIfabs:
9543 case Builtin::BIfabsl:
9544 return Builtin::BIcabsf;
9545 }
9546 }
9547 llvm_unreachable("Unable to convert function");
9548}
9549
9550static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9551 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9552 if (!FnInfo)
9553 return 0;
9554
9555 switch (FDecl->getBuiltinID()) {
9556 default:
9557 return 0;
9558 case Builtin::BI__builtin_abs:
9559 case Builtin::BI__builtin_fabs:
9560 case Builtin::BI__builtin_fabsf:
9561 case Builtin::BI__builtin_fabsl:
9562 case Builtin::BI__builtin_labs:
9563 case Builtin::BI__builtin_llabs:
9564 case Builtin::BI__builtin_cabs:
9565 case Builtin::BI__builtin_cabsf:
9566 case Builtin::BI__builtin_cabsl:
9567 case Builtin::BIabs:
9568 case Builtin::BIlabs:
9569 case Builtin::BIllabs:
9570 case Builtin::BIfabs:
9571 case Builtin::BIfabsf:
9572 case Builtin::BIfabsl:
9573 case Builtin::BIcabs:
9574 case Builtin::BIcabsf:
9575 case Builtin::BIcabsl:
9576 return FDecl->getBuiltinID();
9577 }
9578 llvm_unreachable("Unknown Builtin type");
9579}
9580
9581// If the replacement is valid, emit a note with replacement function.
9582// Additionally, suggest including the proper header if not already included.
9584 unsigned AbsKind, QualType ArgType) {
9585 bool EmitHeaderHint = true;
9586 const char *HeaderName = nullptr;
9587 std::string FunctionName;
9588 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9589 FunctionName = "std::abs";
9590 if (ArgType->isIntegralOrEnumerationType()) {
9591 HeaderName = "cstdlib";
9592 } else if (ArgType->isRealFloatingType()) {
9593 HeaderName = "cmath";
9594 } else {
9595 llvm_unreachable("Invalid Type");
9596 }
9597
9598 // Lookup all std::abs
9599 if (NamespaceDecl *Std = S.getStdNamespace()) {
9600 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9602 S.LookupQualifiedName(R, Std);
9603
9604 for (const auto *I : R) {
9605 const FunctionDecl *FDecl = nullptr;
9606 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9607 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9608 } else {
9609 FDecl = dyn_cast<FunctionDecl>(I);
9610 }
9611 if (!FDecl)
9612 continue;
9613
9614 // Found std::abs(), check that they are the right ones.
9615 if (FDecl->getNumParams() != 1)
9616 continue;
9617
9618 // Check that the parameter type can handle the argument.
9619 QualType ParamType = FDecl->getParamDecl(0)->getType();
9620 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9621 S.Context.getTypeSize(ArgType) <=
9622 S.Context.getTypeSize(ParamType)) {
9623 // Found a function, don't need the header hint.
9624 EmitHeaderHint = false;
9625 break;
9626 }
9627 }
9628 }
9629 } else {
9630 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9631 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9632
9633 if (HeaderName) {
9634 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9635 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9637 S.LookupName(R, S.getCurScope());
9638
9639 if (R.isSingleResult()) {
9640 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9641 if (FD && FD->getBuiltinID() == AbsKind) {
9642 EmitHeaderHint = false;
9643 } else {
9644 return;
9645 }
9646 } else if (!R.empty()) {
9647 return;
9648 }
9649 }
9650 }
9651
9652 S.Diag(Loc, diag::note_replace_abs_function)
9653 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9654
9655 if (!HeaderName)
9656 return;
9657
9658 if (!EmitHeaderHint)
9659 return;
9660
9661 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9662 << FunctionName;
9663}
9664
9665template <std::size_t StrLen>
9666static bool IsStdFunction(const FunctionDecl *FDecl,
9667 const char (&Str)[StrLen]) {
9668 if (!FDecl)
9669 return false;
9670 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9671 return false;
9672 if (!FDecl->isInStdNamespace())
9673 return false;
9674
9675 return true;
9676}
9677
9678enum class MathCheck { NaN, Inf };
9679static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9680 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9681 return llvm::is_contained(names, calleeName);
9682 };
9683
9684 switch (Check) {
9685 case MathCheck::NaN:
9686 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9687 "__builtin_nanf16", "__builtin_nanf128"});
9688 case MathCheck::Inf:
9689 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9690 "__builtin_inff16", "__builtin_inff128"});
9691 }
9692 llvm_unreachable("unknown MathCheck");
9693}
9694
9695static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9696 if (FDecl->getName() != "infinity")
9697 return false;
9698
9699 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9700 const CXXRecordDecl *RDecl = MDecl->getParent();
9701 if (RDecl->getName() != "numeric_limits")
9702 return false;
9703
9704 if (const NamespaceDecl *NSDecl =
9705 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9706 return NSDecl->isStdNamespace();
9707 }
9708
9709 return false;
9710}
9711
9712void Sema::CheckInfNaNFunction(const CallExpr *Call,
9713 const FunctionDecl *FDecl) {
9714 if (!FDecl->getIdentifier())
9715 return;
9716
9717 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9718 if (FPO.getNoHonorNaNs() &&
9719 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9721 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9722 << 1 << 0 << Call->getSourceRange();
9723 return;
9724 }
9725
9726 if (FPO.getNoHonorInfs() &&
9727 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9728 IsInfinityFunction(FDecl) ||
9730 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9731 << 0 << 0 << Call->getSourceRange();
9732 }
9733}
9734
9735void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9736 const FunctionDecl *FDecl) {
9737 if (Call->getNumArgs() != 1)
9738 return;
9739
9740 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9741 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9742 if (AbsKind == 0 && !IsStdAbs)
9743 return;
9744
9745 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9746 QualType ParamType = Call->getArg(0)->getType();
9747
9748 // Unsigned types cannot be negative. Suggest removing the absolute value
9749 // function call.
9750 if (ArgType->isUnsignedIntegerType()) {
9751 std::string FunctionName =
9752 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9753 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9754 Diag(Call->getExprLoc(), diag::note_remove_abs)
9755 << FunctionName
9756 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9757 return;
9758 }
9759
9760 // Taking the absolute value of a pointer is very suspicious, they probably
9761 // wanted to index into an array, dereference a pointer, call a function, etc.
9762 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9763 unsigned DiagType = 0;
9764 if (ArgType->isFunctionType())
9765 DiagType = 1;
9766 else if (ArgType->isArrayType())
9767 DiagType = 2;
9768
9769 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9770 return;
9771 }
9772
9773 // std::abs has overloads which prevent most of the absolute value problems
9774 // from occurring.
9775 if (IsStdAbs)
9776 return;
9777
9778 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9779 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9780
9781 // The argument and parameter are the same kind. Check if they are the right
9782 // size.
9783 if (ArgValueKind == ParamValueKind) {
9784 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9785 return;
9786
9787 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9788 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9789 << FDecl << ArgType << ParamType;
9790
9791 if (NewAbsKind == 0)
9792 return;
9793
9794 emitReplacement(*this, Call->getExprLoc(),
9795 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9796 return;
9797 }
9798
9799 // ArgValueKind != ParamValueKind
9800 // The wrong type of absolute value function was used. Attempt to find the
9801 // proper one.
9802 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9803 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9804 if (NewAbsKind == 0)
9805 return;
9806
9807 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9808 << FDecl << ParamValueKind << ArgValueKind;
9809
9810 emitReplacement(*this, Call->getExprLoc(),
9811 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9812}
9813
9814//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9815void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9816 const FunctionDecl *FDecl) {
9817 if (!Call || !FDecl) return;
9818
9819 // Ignore template specializations and macros.
9820 if (inTemplateInstantiation()) return;
9821 if (Call->getExprLoc().isMacroID()) return;
9822
9823 // Only care about the one template argument, two function parameter std::max
9824 if (Call->getNumArgs() != 2) return;
9825 if (!IsStdFunction(FDecl, "max")) return;
9826 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9827 if (!ArgList) return;
9828 if (ArgList->size() != 1) return;
9829
9830 // Check that template type argument is unsigned integer.
9831 const auto& TA = ArgList->get(0);
9832 if (TA.getKind() != TemplateArgument::Type) return;
9833 QualType ArgType = TA.getAsType();
9834 if (!ArgType->isUnsignedIntegerType()) return;
9835
9836 // See if either argument is a literal zero.
9837 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9838 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9839 if (!MTE) return false;
9840 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9841 if (!Num) return false;
9842 if (Num->getValue() != 0) return false;
9843 return true;
9844 };
9845
9846 const Expr *FirstArg = Call->getArg(0);
9847 const Expr *SecondArg = Call->getArg(1);
9848 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9849 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9850
9851 // Only warn when exactly one argument is zero.
9852 if (IsFirstArgZero == IsSecondArgZero) return;
9853
9854 SourceRange FirstRange = FirstArg->getSourceRange();
9855 SourceRange SecondRange = SecondArg->getSourceRange();
9856
9857 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9858
9859 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9860 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9861
9862 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9863 SourceRange RemovalRange;
9864 if (IsFirstArgZero) {
9865 RemovalRange = SourceRange(FirstRange.getBegin(),
9866 SecondRange.getBegin().getLocWithOffset(-1));
9867 } else {
9868 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9869 SecondRange.getEnd());
9870 }
9871
9872 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9873 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9874 << FixItHint::CreateRemoval(RemovalRange);
9875}
9876
9877//===--- CHECK: Standard memory functions ---------------------------------===//
9878
9879/// Takes the expression passed to the size_t parameter of functions
9880/// such as memcmp, strncat, etc and warns if it's a comparison.
9881///
9882/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9884 const IdentifierInfo *FnName,
9885 SourceLocation FnLoc,
9886 SourceLocation RParenLoc) {
9887 const auto *Size = dyn_cast<BinaryOperator>(E);
9888 if (!Size)
9889 return false;
9890
9891 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9892 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9893 return false;
9894
9895 SourceRange SizeRange = Size->getSourceRange();
9896 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9897 << SizeRange << FnName;
9898 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9899 << FnName
9901 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9902 << FixItHint::CreateRemoval(RParenLoc);
9903 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9904 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9906 ")");
9907
9908 return true;
9909}
9910
9911/// Determine whether the given type is or contains a dynamic class type
9912/// (e.g., whether it has a vtable).
9914 bool &IsContained) {
9915 // Look through array types while ignoring qualifiers.
9916 const Type *Ty = T->getBaseElementTypeUnsafe();
9917 IsContained = false;
9918
9919 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9920 RD = RD ? RD->getDefinition() : nullptr;
9921 if (!RD || RD->isInvalidDecl())
9922 return nullptr;
9923
9924 if (RD->isDynamicClass())
9925 return RD;
9926
9927 // Check all the fields. If any bases were dynamic, the class is dynamic.
9928 // It's impossible for a class to transitively contain itself by value, so
9929 // infinite recursion is impossible.
9930 for (auto *FD : RD->fields()) {
9931 bool SubContained;
9932 if (const CXXRecordDecl *ContainedRD =
9933 getContainedDynamicClass(FD->getType(), SubContained)) {
9934 IsContained = true;
9935 return ContainedRD;
9936 }
9937 }
9938
9939 return nullptr;
9940}
9941
9943 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9944 if (Unary->getKind() == UETT_SizeOf)
9945 return Unary;
9946 return nullptr;
9947}
9948
9949/// If E is a sizeof expression, returns its argument expression,
9950/// otherwise returns NULL.
9951static const Expr *getSizeOfExprArg(const Expr *E) {
9953 if (!SizeOf->isArgumentType())
9954 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9955 return nullptr;
9956}
9957
9958/// If E is a sizeof expression, returns its argument type.
9961 return SizeOf->getTypeOfArgument();
9962 return QualType();
9963}
9964
9965namespace {
9966
9967struct SearchNonTrivialToInitializeField
9968 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9969 using Super =
9970 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9971
9972 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9973
9974 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9975 SourceLocation SL) {
9976 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9977 asDerived().visitArray(PDIK, AT, SL);
9978 return;
9979 }
9980
9981 Super::visitWithKind(PDIK, FT, SL);
9982 }
9983
9984 void visitARCStrong(QualType FT, SourceLocation SL) {
9985 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9986 }
9987 void visitARCWeak(QualType FT, SourceLocation SL) {
9988 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9989 }
9990 void visitStruct(QualType FT, SourceLocation SL) {
9991 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9992 visit(FD->getType(), FD->getLocation());
9993 }
9994 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9995 const ArrayType *AT, SourceLocation SL) {
9996 visit(getContext().getBaseElementType(AT), SL);
9997 }
9998 void visitTrivial(QualType FT, SourceLocation SL) {}
9999
10000 static void diag(QualType RT, const Expr *E, Sema &S) {
10001 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10002 }
10003
10004 ASTContext &getContext() { return S.getASTContext(); }
10005
10006 const Expr *E;
10007 Sema &S;
10008};
10009
10010struct SearchNonTrivialToCopyField
10011 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10012 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10013
10014 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10015
10016 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10017 SourceLocation SL) {
10018 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10019 asDerived().visitArray(PCK, AT, SL);
10020 return;
10021 }
10022
10023 Super::visitWithKind(PCK, FT, SL);
10024 }
10025
10026 void visitARCStrong(QualType FT, SourceLocation SL) {
10027 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10028 }
10029 void visitARCWeak(QualType FT, SourceLocation SL) {
10030 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10031 }
10032 void visitPtrAuth(QualType FT, SourceLocation SL) {
10033 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10034 }
10035 void visitStruct(QualType FT, SourceLocation SL) {
10036 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10037 visit(FD->getType(), FD->getLocation());
10038 }
10039 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10040 SourceLocation SL) {
10041 visit(getContext().getBaseElementType(AT), SL);
10042 }
10043 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10044 SourceLocation SL) {}
10045 void visitTrivial(QualType FT, SourceLocation SL) {}
10046 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10047
10048 static void diag(QualType RT, const Expr *E, Sema &S) {
10049 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10050 }
10051
10052 ASTContext &getContext() { return S.getASTContext(); }
10053
10054 const Expr *E;
10055 Sema &S;
10056};
10057
10058}
10059
10060/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10061static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10062 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10063
10064 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10065 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10066 return false;
10067
10068 return doesExprLikelyComputeSize(BO->getLHS()) ||
10069 doesExprLikelyComputeSize(BO->getRHS());
10070 }
10071
10072 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10073}
10074
10075/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10076///
10077/// \code
10078/// #define MACRO 0
10079/// foo(MACRO);
10080/// foo(0);
10081/// \endcode
10082///
10083/// This should return true for the first call to foo, but not for the second
10084/// (regardless of whether foo is a macro or function).
10086 SourceLocation CallLoc,
10087 SourceLocation ArgLoc) {
10088 if (!CallLoc.isMacroID())
10089 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10090
10091 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10092 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10093}
10094
10095/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10096/// last two arguments transposed.
10097static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10098 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10099 return;
10100
10101 const Expr *SizeArg =
10102 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10103
10104 auto isLiteralZero = [](const Expr *E) {
10105 return (isa<IntegerLiteral>(E) &&
10106 cast<IntegerLiteral>(E)->getValue() == 0) ||
10108 cast<CharacterLiteral>(E)->getValue() == 0);
10109 };
10110
10111 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10112 SourceLocation CallLoc = Call->getRParenLoc();
10114 if (isLiteralZero(SizeArg) &&
10115 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10116
10117 SourceLocation DiagLoc = SizeArg->getExprLoc();
10118
10119 // Some platforms #define bzero to __builtin_memset. See if this is the
10120 // case, and if so, emit a better diagnostic.
10121 if (BId == Builtin::BIbzero ||
10123 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10124 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10125 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10126 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10127 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10128 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10129 }
10130 return;
10131 }
10132
10133 // If the second argument to a memset is a sizeof expression and the third
10134 // isn't, this is also likely an error. This should catch
10135 // 'memset(buf, sizeof(buf), 0xff)'.
10136 if (BId == Builtin::BImemset &&
10137 doesExprLikelyComputeSize(Call->getArg(1)) &&
10138 !doesExprLikelyComputeSize(Call->getArg(2))) {
10139 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10140 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10141 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10142 return;
10143 }
10144}
10145
10146void Sema::CheckMemaccessArguments(const CallExpr *Call,
10147 unsigned BId,
10148 IdentifierInfo *FnName) {
10149 assert(BId != 0);
10150
10151 // It is possible to have a non-standard definition of memset. Validate
10152 // we have enough arguments, and if not, abort further checking.
10153 unsigned ExpectedNumArgs =
10154 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10155 if (Call->getNumArgs() < ExpectedNumArgs)
10156 return;
10157
10158 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10159 BId == Builtin::BIstrndup ? 1 : 2);
10160 unsigned LenArg =
10161 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10162 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10163
10164 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10165 Call->getBeginLoc(), Call->getRParenLoc()))
10166 return;
10167
10168 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10169 CheckMemaccessSize(*this, BId, Call);
10170
10171 // We have special checking when the length is a sizeof expression.
10172 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10173 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10174 llvm::FoldingSetNodeID SizeOfArgID;
10175
10176 // Although widely used, 'bzero' is not a standard function. Be more strict
10177 // with the argument types before allowing diagnostics and only allow the
10178 // form bzero(ptr, sizeof(...)).
10179 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10180 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10181 return;
10182
10183 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10184 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10185 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10186
10187 QualType DestTy = Dest->getType();
10188 QualType PointeeTy;
10189 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10190 PointeeTy = DestPtrTy->getPointeeType();
10191
10192 // Never warn about void type pointers. This can be used to suppress
10193 // false positives.
10194 if (PointeeTy->isVoidType())
10195 continue;
10196
10197 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10198 // actually comparing the expressions for equality. Because computing the
10199 // expression IDs can be expensive, we only do this if the diagnostic is
10200 // enabled.
10201 if (SizeOfArg &&
10202 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10203 SizeOfArg->getExprLoc())) {
10204 // We only compute IDs for expressions if the warning is enabled, and
10205 // cache the sizeof arg's ID.
10206 if (SizeOfArgID == llvm::FoldingSetNodeID())
10207 SizeOfArg->Profile(SizeOfArgID, Context, true);
10208 llvm::FoldingSetNodeID DestID;
10209 Dest->Profile(DestID, Context, true);
10210 if (DestID == SizeOfArgID) {
10211 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10212 // over sizeof(src) as well.
10213 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10214 StringRef ReadableName = FnName->getName();
10215
10216 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10217 if (UnaryOp->getOpcode() == UO_AddrOf)
10218 ActionIdx = 1; // If its an address-of operator, just remove it.
10219 if (!PointeeTy->isIncompleteType() &&
10220 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10221 ActionIdx = 2; // If the pointee's size is sizeof(char),
10222 // suggest an explicit length.
10223
10224 // If the function is defined as a builtin macro, do not show macro
10225 // expansion.
10226 SourceLocation SL = SizeOfArg->getExprLoc();
10227 SourceRange DSR = Dest->getSourceRange();
10228 SourceRange SSR = SizeOfArg->getSourceRange();
10229 SourceManager &SM = getSourceManager();
10230
10231 if (SM.isMacroArgExpansion(SL)) {
10232 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10233 SL = SM.getSpellingLoc(SL);
10234 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10235 SM.getSpellingLoc(DSR.getEnd()));
10236 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10237 SM.getSpellingLoc(SSR.getEnd()));
10238 }
10239
10240 DiagRuntimeBehavior(SL, SizeOfArg,
10241 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10242 << ReadableName
10243 << PointeeTy
10244 << DestTy
10245 << DSR
10246 << SSR);
10247 DiagRuntimeBehavior(SL, SizeOfArg,
10248 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10249 << ActionIdx
10250 << SSR);
10251
10252 break;
10253 }
10254 }
10255
10256 // Also check for cases where the sizeof argument is the exact same
10257 // type as the memory argument, and where it points to a user-defined
10258 // record type.
10259 if (SizeOfArgTy != QualType()) {
10260 if (PointeeTy->isRecordType() &&
10261 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10262 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10263 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10264 << FnName << SizeOfArgTy << ArgIdx
10265 << PointeeTy << Dest->getSourceRange()
10266 << LenExpr->getSourceRange());
10267 break;
10268 }
10269 }
10270 } else if (DestTy->isArrayType()) {
10271 PointeeTy = DestTy;
10272 }
10273
10274 if (PointeeTy == QualType())
10275 continue;
10276
10277 // Always complain about dynamic classes.
10278 bool IsContained;
10279 if (const CXXRecordDecl *ContainedRD =
10280 getContainedDynamicClass(PointeeTy, IsContained)) {
10281
10282 unsigned OperationType = 0;
10283 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10284 // "overwritten" if we're warning about the destination for any call
10285 // but memcmp; otherwise a verb appropriate to the call.
10286 if (ArgIdx != 0 || IsCmp) {
10287 if (BId == Builtin::BImemcpy)
10288 OperationType = 1;
10289 else if(BId == Builtin::BImemmove)
10290 OperationType = 2;
10291 else if (IsCmp)
10292 OperationType = 3;
10293 }
10294
10295 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10296 PDiag(diag::warn_dyn_class_memaccess)
10297 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10298 << IsContained << ContainedRD << OperationType
10299 << Call->getCallee()->getSourceRange());
10300 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10301 BId != Builtin::BImemset)
10303 Dest->getExprLoc(), Dest,
10304 PDiag(diag::warn_arc_object_memaccess)
10305 << ArgIdx << FnName << PointeeTy
10306 << Call->getCallee()->getSourceRange());
10307 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10308
10309 // FIXME: Do not consider incomplete types even though they may be
10310 // completed later. GCC does not diagnose such code, but we may want to
10311 // consider diagnosing it in the future, perhaps under a different, but
10312 // related, diagnostic group.
10313 bool NonTriviallyCopyableCXXRecord =
10314 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10315 !PointeeTy.isTriviallyCopyableType(Context);
10316
10317 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10319 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10320 PDiag(diag::warn_cstruct_memaccess)
10321 << ArgIdx << FnName << PointeeTy << 0);
10322 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10323 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10324 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10325 // FIXME: Limiting this warning to dest argument until we decide
10326 // whether it's valid for source argument too.
10327 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10328 PDiag(diag::warn_cxxstruct_memaccess)
10329 << FnName << PointeeTy);
10330 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10332 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10333 PDiag(diag::warn_cstruct_memaccess)
10334 << ArgIdx << FnName << PointeeTy << 1);
10335 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10336 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10337 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10338 // FIXME: Limiting this warning to dest argument until we decide
10339 // whether it's valid for source argument too.
10340 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10341 PDiag(diag::warn_cxxstruct_memaccess)
10342 << FnName << PointeeTy);
10343 } else {
10344 continue;
10345 }
10346 } else
10347 continue;
10348
10350 Dest->getExprLoc(), Dest,
10351 PDiag(diag::note_bad_memaccess_silence)
10352 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10353 break;
10354 }
10355}
10356
10357// A little helper routine: ignore addition and subtraction of integer literals.
10358// This intentionally does not ignore all integer constant expressions because
10359// we don't want to remove sizeof().
10360static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10361 Ex = Ex->IgnoreParenCasts();
10362
10363 while (true) {
10364 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10365 if (!BO || !BO->isAdditiveOp())
10366 break;
10367
10368 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10369 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10370
10371 if (isa<IntegerLiteral>(RHS))
10372 Ex = LHS;
10373 else if (isa<IntegerLiteral>(LHS))
10374 Ex = RHS;
10375 else
10376 break;
10377 }
10378
10379 return Ex;
10380}
10381
10383 ASTContext &Context) {
10384 // Only handle constant-sized or VLAs, but not flexible members.
10385 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10386 // Only issue the FIXIT for arrays of size > 1.
10387 if (CAT->getZExtSize() <= 1)
10388 return false;
10389 } else if (!Ty->isVariableArrayType()) {
10390 return false;
10391 }
10392 return true;
10393}
10394
10395void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10396 IdentifierInfo *FnName) {
10397
10398 // Don't crash if the user has the wrong number of arguments
10399 unsigned NumArgs = Call->getNumArgs();
10400 if ((NumArgs != 3) && (NumArgs != 4))
10401 return;
10402
10403 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10404 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10405 const Expr *CompareWithSrc = nullptr;
10406
10407 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10408 Call->getBeginLoc(), Call->getRParenLoc()))
10409 return;
10410
10411 // Look for 'strlcpy(dst, x, sizeof(x))'
10412 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10413 CompareWithSrc = Ex;
10414 else {
10415 // Look for 'strlcpy(dst, x, strlen(x))'
10416 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10417 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10418 SizeCall->getNumArgs() == 1)
10419 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10420 }
10421 }
10422
10423 if (!CompareWithSrc)
10424 return;
10425
10426 // Determine if the argument to sizeof/strlen is equal to the source
10427 // argument. In principle there's all kinds of things you could do
10428 // here, for instance creating an == expression and evaluating it with
10429 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10430 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10431 if (!SrcArgDRE)
10432 return;
10433
10434 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10435 if (!CompareWithSrcDRE ||
10436 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10437 return;
10438
10439 const Expr *OriginalSizeArg = Call->getArg(2);
10440 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10441 << OriginalSizeArg->getSourceRange() << FnName;
10442
10443 // Output a FIXIT hint if the destination is an array (rather than a
10444 // pointer to an array). This could be enhanced to handle some
10445 // pointers if we know the actual size, like if DstArg is 'array+2'
10446 // we could say 'sizeof(array)-2'.
10447 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10449 return;
10450
10451 SmallString<128> sizeString;
10452 llvm::raw_svector_ostream OS(sizeString);
10453 OS << "sizeof(";
10454 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10455 OS << ")";
10456
10457 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10458 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10459 OS.str());
10460}
10461
10462/// Check if two expressions refer to the same declaration.
10463static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10464 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10465 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10466 return D1->getDecl() == D2->getDecl();
10467 return false;
10468}
10469
10470static const Expr *getStrlenExprArg(const Expr *E) {
10471 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10472 const FunctionDecl *FD = CE->getDirectCallee();
10473 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10474 return nullptr;
10475 return CE->getArg(0)->IgnoreParenCasts();
10476 }
10477 return nullptr;
10478}
10479
10480void Sema::CheckStrncatArguments(const CallExpr *CE,
10481 const IdentifierInfo *FnName) {
10482 // Don't crash if the user has the wrong number of arguments.
10483 if (CE->getNumArgs() < 3)
10484 return;
10485 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10486 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10487 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10488
10489 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10490 CE->getRParenLoc()))
10491 return;
10492
10493 // Identify common expressions, which are wrongly used as the size argument
10494 // to strncat and may lead to buffer overflows.
10495 unsigned PatternType = 0;
10496 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10497 // - sizeof(dst)
10498 if (referToTheSameDecl(SizeOfArg, DstArg))
10499 PatternType = 1;
10500 // - sizeof(src)
10501 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10502 PatternType = 2;
10503 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10504 if (BE->getOpcode() == BO_Sub) {
10505 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10506 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10507 // - sizeof(dst) - strlen(dst)
10508 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10510 PatternType = 1;
10511 // - sizeof(src) - (anything)
10512 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10513 PatternType = 2;
10514 }
10515 }
10516
10517 if (PatternType == 0)
10518 return;
10519
10520 // Generate the diagnostic.
10521 SourceLocation SL = LenArg->getBeginLoc();
10522 SourceRange SR = LenArg->getSourceRange();
10523 SourceManager &SM = getSourceManager();
10524
10525 // If the function is defined as a builtin macro, do not show macro expansion.
10526 if (SM.isMacroArgExpansion(SL)) {
10527 SL = SM.getSpellingLoc(SL);
10528 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10529 SM.getSpellingLoc(SR.getEnd()));
10530 }
10531
10532 // Check if the destination is an array (rather than a pointer to an array).
10533 QualType DstTy = DstArg->getType();
10534 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10535 Context);
10536 if (!isKnownSizeArray) {
10537 if (PatternType == 1)
10538 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10539 else
10540 Diag(SL, diag::warn_strncat_src_size) << SR;
10541 return;
10542 }
10543
10544 if (PatternType == 1)
10545 Diag(SL, diag::warn_strncat_large_size) << SR;
10546 else
10547 Diag(SL, diag::warn_strncat_src_size) << SR;
10548
10549 SmallString<128> sizeString;
10550 llvm::raw_svector_ostream OS(sizeString);
10551 OS << "sizeof(";
10552 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10553 OS << ") - ";
10554 OS << "strlen(";
10555 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10556 OS << ") - 1";
10557
10558 Diag(SL, diag::note_strncat_wrong_size)
10559 << FixItHint::CreateReplacement(SR, OS.str());
10560}
10561
10562namespace {
10563void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10564 const UnaryOperator *UnaryExpr, const Decl *D) {
10566 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10567 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10568 return;
10569 }
10570}
10571
10572void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10573 const UnaryOperator *UnaryExpr) {
10574 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10575 const Decl *D = Lvalue->getDecl();
10576 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10577 if (!DD->getType()->isReferenceType())
10578 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10579 }
10580 }
10581
10582 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10583 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10584 Lvalue->getMemberDecl());
10585}
10586
10587void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10588 const UnaryOperator *UnaryExpr) {
10589 const auto *Lambda = dyn_cast<LambdaExpr>(
10591 if (!Lambda)
10592 return;
10593
10594 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10595 << CalleeName << 2 /*object: lambda expression*/;
10596}
10597
10598void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10599 const DeclRefExpr *Lvalue) {
10600 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10601 if (Var == nullptr)
10602 return;
10603
10604 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10605 << CalleeName << 0 /*object: */ << Var;
10606}
10607
10608void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10609 const CastExpr *Cast) {
10610 SmallString<128> SizeString;
10611 llvm::raw_svector_ostream OS(SizeString);
10612
10613 clang::CastKind Kind = Cast->getCastKind();
10614 if (Kind == clang::CK_BitCast &&
10615 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10616 return;
10617 if (Kind == clang::CK_IntegralToPointer &&
10619 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10620 return;
10621
10622 switch (Cast->getCastKind()) {
10623 case clang::CK_BitCast:
10624 case clang::CK_IntegralToPointer:
10625 case clang::CK_FunctionToPointerDecay:
10626 OS << '\'';
10627 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10628 OS << '\'';
10629 break;
10630 default:
10631 return;
10632 }
10633
10634 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10635 << CalleeName << 0 /*object: */ << OS.str();
10636}
10637} // namespace
10638
10639void Sema::CheckFreeArguments(const CallExpr *E) {
10640 const std::string CalleeName =
10641 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10642
10643 { // Prefer something that doesn't involve a cast to make things simpler.
10644 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10645 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10646 switch (UnaryExpr->getOpcode()) {
10647 case UnaryOperator::Opcode::UO_AddrOf:
10648 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10649 case UnaryOperator::Opcode::UO_Plus:
10650 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10651 default:
10652 break;
10653 }
10654
10655 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10656 if (Lvalue->getType()->isArrayType())
10657 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10658
10659 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10660 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10661 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10662 return;
10663 }
10664
10665 if (isa<BlockExpr>(Arg)) {
10666 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10667 << CalleeName << 1 /*object: block*/;
10668 return;
10669 }
10670 }
10671 // Maybe the cast was important, check after the other cases.
10672 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10673 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10674}
10675
10676void
10677Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10678 SourceLocation ReturnLoc,
10679 bool isObjCMethod,
10680 const AttrVec *Attrs,
10681 const FunctionDecl *FD) {
10682 // Check if the return value is null but should not be.
10683 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10684 (!isObjCMethod && isNonNullType(lhsType))) &&
10685 CheckNonNullExpr(*this, RetValExp))
10686 Diag(ReturnLoc, diag::warn_null_ret)
10687 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10688
10689 // C++11 [basic.stc.dynamic.allocation]p4:
10690 // If an allocation function declared with a non-throwing
10691 // exception-specification fails to allocate storage, it shall return
10692 // a null pointer. Any other allocation function that fails to allocate
10693 // storage shall indicate failure only by throwing an exception [...]
10694 if (FD) {
10696 if (Op == OO_New || Op == OO_Array_New) {
10697 const FunctionProtoType *Proto
10698 = FD->getType()->castAs<FunctionProtoType>();
10699 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10700 CheckNonNullExpr(*this, RetValExp))
10701 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10702 << FD << getLangOpts().CPlusPlus11;
10703 }
10704 }
10705
10706 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10707 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10708 }
10709
10710 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10711 // here prevent the user from using a PPC MMA type as trailing return type.
10712 if (Context.getTargetInfo().getTriple().isPPC64())
10713 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10714}
10715
10717 const Expr *RHS, BinaryOperatorKind Opcode) {
10718 if (!BinaryOperator::isEqualityOp(Opcode))
10719 return;
10720
10721 // Match and capture subexpressions such as "(float) X == 0.1".
10722 const FloatingLiteral *FPLiteral;
10723 const CastExpr *FPCast;
10724 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10725 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10726 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10727 return FPLiteral && FPCast;
10728 };
10729
10730 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10731 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10732 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10733 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10734 TargetTy->isFloatingPoint()) {
10735 bool Lossy;
10736 llvm::APFloat TargetC = FPLiteral->getValue();
10737 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10738 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10739 if (Lossy) {
10740 // If the literal cannot be represented in the source type, then a
10741 // check for == is always false and check for != is always true.
10742 Diag(Loc, diag::warn_float_compare_literal)
10743 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10744 << LHS->getSourceRange() << RHS->getSourceRange();
10745 return;
10746 }
10747 }
10748 }
10749
10750 // Match a more general floating-point equality comparison (-Wfloat-equal).
10751 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10752 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10753
10754 // Special case: check for x == x (which is OK).
10755 // Do not emit warnings for such cases.
10756 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10757 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10758 if (DRL->getDecl() == DRR->getDecl())
10759 return;
10760
10761 // Special case: check for comparisons against literals that can be exactly
10762 // represented by APFloat. In such cases, do not emit a warning. This
10763 // is a heuristic: often comparison against such literals are used to
10764 // detect if a value in a variable has not changed. This clearly can
10765 // lead to false negatives.
10766 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10767 if (FLL->isExact())
10768 return;
10769 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10770 if (FLR->isExact())
10771 return;
10772
10773 // Check for comparisons with builtin types.
10774 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10775 CL && CL->getBuiltinCallee())
10776 return;
10777
10778 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10779 CR && CR->getBuiltinCallee())
10780 return;
10781
10782 // Emit the diagnostic.
10783 Diag(Loc, diag::warn_floatingpoint_eq)
10784 << LHS->getSourceRange() << RHS->getSourceRange();
10785}
10786
10787//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10788//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10789
10790namespace {
10791
10792/// Structure recording the 'active' range of an integer-valued
10793/// expression.
10794struct IntRange {
10795 /// The number of bits active in the int. Note that this includes exactly one
10796 /// sign bit if !NonNegative.
10797 unsigned Width;
10798
10799 /// True if the int is known not to have negative values. If so, all leading
10800 /// bits before Width are known zero, otherwise they are known to be the
10801 /// same as the MSB within Width.
10802 bool NonNegative;
10803
10804 IntRange(unsigned Width, bool NonNegative)
10805 : Width(Width), NonNegative(NonNegative) {}
10806
10807 /// Number of bits excluding the sign bit.
10808 unsigned valueBits() const {
10809 return NonNegative ? Width : Width - 1;
10810 }
10811
10812 /// Returns the range of the bool type.
10813 static IntRange forBoolType() {
10814 return IntRange(1, true);
10815 }
10816
10817 /// Returns the range of an opaque value of the given integral type.
10818 static IntRange forValueOfType(ASTContext &C, QualType T) {
10819 return forValueOfCanonicalType(C,
10821 }
10822
10823 /// Returns the range of an opaque value of a canonical integral type.
10824 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10825 assert(T->isCanonicalUnqualified());
10826
10827 if (const auto *VT = dyn_cast<VectorType>(T))
10828 T = VT->getElementType().getTypePtr();
10829 if (const auto *CT = dyn_cast<ComplexType>(T))
10830 T = CT->getElementType().getTypePtr();
10831 if (const auto *AT = dyn_cast<AtomicType>(T))
10832 T = AT->getValueType().getTypePtr();
10833
10834 if (!C.getLangOpts().CPlusPlus) {
10835 // For enum types in C code, use the underlying datatype.
10836 if (const auto *ED = T->getAsEnumDecl())
10837 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
10838 } else if (auto *Enum = T->getAsEnumDecl()) {
10839 // For enum types in C++, use the known bit width of the enumerators.
10840 // In C++11, enums can have a fixed underlying type. Use this type to
10841 // compute the range.
10842 if (Enum->isFixed()) {
10843 return IntRange(C.getIntWidth(QualType(T, 0)),
10844 !Enum->getIntegerType()->isSignedIntegerType());
10845 }
10846
10847 unsigned NumPositive = Enum->getNumPositiveBits();
10848 unsigned NumNegative = Enum->getNumNegativeBits();
10849
10850 if (NumNegative == 0)
10851 return IntRange(NumPositive, true/*NonNegative*/);
10852 else
10853 return IntRange(std::max(NumPositive + 1, NumNegative),
10854 false/*NonNegative*/);
10855 }
10856
10857 if (const auto *EIT = dyn_cast<BitIntType>(T))
10858 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10859
10860 const BuiltinType *BT = cast<BuiltinType>(T);
10861 assert(BT->isInteger());
10862
10863 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10864 }
10865
10866 /// Returns the "target" range of a canonical integral type, i.e.
10867 /// the range of values expressible in the type.
10868 ///
10869 /// This matches forValueOfCanonicalType except that enums have the
10870 /// full range of their type, not the range of their enumerators.
10871 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10872 assert(T->isCanonicalUnqualified());
10873
10874 if (const VectorType *VT = dyn_cast<VectorType>(T))
10875 T = VT->getElementType().getTypePtr();
10876 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10877 T = CT->getElementType().getTypePtr();
10878 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10879 T = AT->getValueType().getTypePtr();
10880 if (const auto *ED = T->getAsEnumDecl())
10881 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
10882
10883 if (const auto *EIT = dyn_cast<BitIntType>(T))
10884 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10885
10886 const BuiltinType *BT = cast<BuiltinType>(T);
10887 assert(BT->isInteger());
10888
10889 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10890 }
10891
10892 /// Returns the supremum of two ranges: i.e. their conservative merge.
10893 static IntRange join(IntRange L, IntRange R) {
10894 bool Unsigned = L.NonNegative && R.NonNegative;
10895 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10896 L.NonNegative && R.NonNegative);
10897 }
10898
10899 /// Return the range of a bitwise-AND of the two ranges.
10900 static IntRange bit_and(IntRange L, IntRange R) {
10901 unsigned Bits = std::max(L.Width, R.Width);
10902 bool NonNegative = false;
10903 if (L.NonNegative) {
10904 Bits = std::min(Bits, L.Width);
10905 NonNegative = true;
10906 }
10907 if (R.NonNegative) {
10908 Bits = std::min(Bits, R.Width);
10909 NonNegative = true;
10910 }
10911 return IntRange(Bits, NonNegative);
10912 }
10913
10914 /// Return the range of a sum of the two ranges.
10915 static IntRange sum(IntRange L, IntRange R) {
10916 bool Unsigned = L.NonNegative && R.NonNegative;
10917 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10918 Unsigned);
10919 }
10920
10921 /// Return the range of a difference of the two ranges.
10922 static IntRange difference(IntRange L, IntRange R) {
10923 // We need a 1-bit-wider range if:
10924 // 1) LHS can be negative: least value can be reduced.
10925 // 2) RHS can be negative: greatest value can be increased.
10926 bool CanWiden = !L.NonNegative || !R.NonNegative;
10927 bool Unsigned = L.NonNegative && R.Width == 0;
10928 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10929 !Unsigned,
10930 Unsigned);
10931 }
10932
10933 /// Return the range of a product of the two ranges.
10934 static IntRange product(IntRange L, IntRange R) {
10935 // If both LHS and RHS can be negative, we can form
10936 // -2^L * -2^R = 2^(L + R)
10937 // which requires L + R + 1 value bits to represent.
10938 bool CanWiden = !L.NonNegative && !R.NonNegative;
10939 bool Unsigned = L.NonNegative && R.NonNegative;
10940 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10941 Unsigned);
10942 }
10943
10944 /// Return the range of a remainder operation between the two ranges.
10945 static IntRange rem(IntRange L, IntRange R) {
10946 // The result of a remainder can't be larger than the result of
10947 // either side. The sign of the result is the sign of the LHS.
10948 bool Unsigned = L.NonNegative;
10949 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10950 Unsigned);
10951 }
10952};
10953
10954} // namespace
10955
10956static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
10957 if (value.isSigned() && value.isNegative())
10958 return IntRange(value.getSignificantBits(), false);
10959
10960 if (value.getBitWidth() > MaxWidth)
10961 value = value.trunc(MaxWidth);
10962
10963 // isNonNegative() just checks the sign bit without considering
10964 // signedness.
10965 return IntRange(value.getActiveBits(), true);
10966}
10967
10968static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
10969 if (result.isInt())
10970 return GetValueRange(result.getInt(), MaxWidth);
10971
10972 if (result.isVector()) {
10973 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
10974 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10975 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
10976 R = IntRange::join(R, El);
10977 }
10978 return R;
10979 }
10980
10981 if (result.isComplexInt()) {
10982 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
10983 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
10984 return IntRange::join(R, I);
10985 }
10986
10987 // This can happen with lossless casts to intptr_t of "based" lvalues.
10988 // Assume it might use arbitrary bits.
10989 // FIXME: The only reason we need to pass the type in here is to get
10990 // the sign right on this one case. It would be nice if APValue
10991 // preserved this.
10992 assert(result.isLValue() || result.isAddrLabelDiff());
10993 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10994}
10995
10996static QualType GetExprType(const Expr *E) {
10997 QualType Ty = E->getType();
10998 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
10999 Ty = AtomicRHS->getValueType();
11000 return Ty;
11001}
11002
11003/// Attempts to estimate an approximate range for the given integer expression.
11004/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11005/// reliable estimation cannot be determined.
11006///
11007/// \param MaxWidth The width to which the value will be truncated.
11008/// \param InConstantContext If \c true, interpret the expression within a
11009/// constant context.
11010/// \param Approximate If \c true, provide a likely range of values by assuming
11011/// that arithmetic on narrower types remains within those types.
11012/// If \c false, return a range that includes all possible values
11013/// resulting from the expression.
11014/// \returns A range of values that the expression might take, or
11015/// std::nullopt if a reliable estimation cannot be determined.
11016static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11017 unsigned MaxWidth,
11018 bool InConstantContext,
11019 bool Approximate) {
11020 E = E->IgnoreParens();
11021
11022 // Try a full evaluation first.
11023 Expr::EvalResult result;
11024 if (E->EvaluateAsRValue(result, C, InConstantContext))
11025 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11026
11027 // I think we only want to look through implicit casts here; if the
11028 // user has an explicit widening cast, we should treat the value as
11029 // being of the new, wider type.
11030 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11031 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11032 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11033 Approximate);
11034
11035 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11036
11037 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11038 CE->getCastKind() == CK_BooleanToSignedIntegral;
11039
11040 // Assume that non-integer casts can span the full range of the type.
11041 if (!isIntegerCast)
11042 return OutputTypeRange;
11043
11044 std::optional<IntRange> SubRange = TryGetExprRange(
11045 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11046 InConstantContext, Approximate);
11047 if (!SubRange)
11048 return std::nullopt;
11049
11050 // Bail out if the subexpr's range is as wide as the cast type.
11051 if (SubRange->Width >= OutputTypeRange.Width)
11052 return OutputTypeRange;
11053
11054 // Otherwise, we take the smaller width, and we're non-negative if
11055 // either the output type or the subexpr is.
11056 return IntRange(SubRange->Width,
11057 SubRange->NonNegative || OutputTypeRange.NonNegative);
11058 }
11059
11060 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11061 // If we can fold the condition, just take that operand.
11062 bool CondResult;
11063 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11064 return TryGetExprRange(
11065 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11066 InConstantContext, Approximate);
11067
11068 // Otherwise, conservatively merge.
11069 // TryGetExprRange requires an integer expression, but a throw expression
11070 // results in a void type.
11071 Expr *TrueExpr = CO->getTrueExpr();
11072 if (TrueExpr->getType()->isVoidType())
11073 return std::nullopt;
11074
11075 std::optional<IntRange> L =
11076 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11077 if (!L)
11078 return std::nullopt;
11079
11080 Expr *FalseExpr = CO->getFalseExpr();
11081 if (FalseExpr->getType()->isVoidType())
11082 return std::nullopt;
11083
11084 std::optional<IntRange> R =
11085 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11086 if (!R)
11087 return std::nullopt;
11088
11089 return IntRange::join(*L, *R);
11090 }
11091
11092 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11093 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11094
11095 switch (BO->getOpcode()) {
11096 case BO_Cmp:
11097 llvm_unreachable("builtin <=> should have class type");
11098
11099 // Boolean-valued operations are single-bit and positive.
11100 case BO_LAnd:
11101 case BO_LOr:
11102 case BO_LT:
11103 case BO_GT:
11104 case BO_LE:
11105 case BO_GE:
11106 case BO_EQ:
11107 case BO_NE:
11108 return IntRange::forBoolType();
11109
11110 // The type of the assignments is the type of the LHS, so the RHS
11111 // is not necessarily the same type.
11112 case BO_MulAssign:
11113 case BO_DivAssign:
11114 case BO_RemAssign:
11115 case BO_AddAssign:
11116 case BO_SubAssign:
11117 case BO_XorAssign:
11118 case BO_OrAssign:
11119 // TODO: bitfields?
11120 return IntRange::forValueOfType(C, GetExprType(E));
11121
11122 // Simple assignments just pass through the RHS, which will have
11123 // been coerced to the LHS type.
11124 case BO_Assign:
11125 // TODO: bitfields?
11126 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11127 Approximate);
11128
11129 // Operations with opaque sources are black-listed.
11130 case BO_PtrMemD:
11131 case BO_PtrMemI:
11132 return IntRange::forValueOfType(C, GetExprType(E));
11133
11134 // Bitwise-and uses the *infinum* of the two source ranges.
11135 case BO_And:
11136 case BO_AndAssign:
11137 Combine = IntRange::bit_and;
11138 break;
11139
11140 // Left shift gets black-listed based on a judgement call.
11141 case BO_Shl:
11142 // ...except that we want to treat '1 << (blah)' as logically
11143 // positive. It's an important idiom.
11144 if (IntegerLiteral *I
11145 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11146 if (I->getValue() == 1) {
11147 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11148 return IntRange(R.Width, /*NonNegative*/ true);
11149 }
11150 }
11151 [[fallthrough]];
11152
11153 case BO_ShlAssign:
11154 return IntRange::forValueOfType(C, GetExprType(E));
11155
11156 // Right shift by a constant can narrow its left argument.
11157 case BO_Shr:
11158 case BO_ShrAssign: {
11159 std::optional<IntRange> L = TryGetExprRange(
11160 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11161 if (!L)
11162 return std::nullopt;
11163
11164 // If the shift amount is a positive constant, drop the width by
11165 // that much.
11166 if (std::optional<llvm::APSInt> shift =
11167 BO->getRHS()->getIntegerConstantExpr(C)) {
11168 if (shift->isNonNegative()) {
11169 if (shift->uge(L->Width))
11170 L->Width = (L->NonNegative ? 0 : 1);
11171 else
11172 L->Width -= shift->getZExtValue();
11173 }
11174 }
11175
11176 return L;
11177 }
11178
11179 // Comma acts as its right operand.
11180 case BO_Comma:
11181 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11182 Approximate);
11183
11184 case BO_Add:
11185 if (!Approximate)
11186 Combine = IntRange::sum;
11187 break;
11188
11189 case BO_Sub:
11190 if (BO->getLHS()->getType()->isPointerType())
11191 return IntRange::forValueOfType(C, GetExprType(E));
11192 if (!Approximate)
11193 Combine = IntRange::difference;
11194 break;
11195
11196 case BO_Mul:
11197 if (!Approximate)
11198 Combine = IntRange::product;
11199 break;
11200
11201 // The width of a division result is mostly determined by the size
11202 // of the LHS.
11203 case BO_Div: {
11204 // Don't 'pre-truncate' the operands.
11205 unsigned opWidth = C.getIntWidth(GetExprType(E));
11206 std::optional<IntRange> L = TryGetExprRange(
11207 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11208 if (!L)
11209 return std::nullopt;
11210
11211 // If the divisor is constant, use that.
11212 if (std::optional<llvm::APSInt> divisor =
11213 BO->getRHS()->getIntegerConstantExpr(C)) {
11214 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11215 if (log2 >= L->Width)
11216 L->Width = (L->NonNegative ? 0 : 1);
11217 else
11218 L->Width = std::min(L->Width - log2, MaxWidth);
11219 return L;
11220 }
11221
11222 // Otherwise, just use the LHS's width.
11223 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11224 // could be -1.
11225 std::optional<IntRange> R = TryGetExprRange(
11226 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11227 if (!R)
11228 return std::nullopt;
11229
11230 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11231 }
11232
11233 case BO_Rem:
11234 Combine = IntRange::rem;
11235 break;
11236
11237 // The default behavior is okay for these.
11238 case BO_Xor:
11239 case BO_Or:
11240 break;
11241 }
11242
11243 // Combine the two ranges, but limit the result to the type in which we
11244 // performed the computation.
11245 QualType T = GetExprType(E);
11246 unsigned opWidth = C.getIntWidth(T);
11247 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11248 InConstantContext, Approximate);
11249 if (!L)
11250 return std::nullopt;
11251
11252 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11253 InConstantContext, Approximate);
11254 if (!R)
11255 return std::nullopt;
11256
11257 IntRange C = Combine(*L, *R);
11258 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11259 C.Width = std::min(C.Width, MaxWidth);
11260 return C;
11261 }
11262
11263 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11264 switch (UO->getOpcode()) {
11265 // Boolean-valued operations are white-listed.
11266 case UO_LNot:
11267 return IntRange::forBoolType();
11268
11269 // Operations with opaque sources are black-listed.
11270 case UO_Deref:
11271 case UO_AddrOf: // should be impossible
11272 return IntRange::forValueOfType(C, GetExprType(E));
11273
11274 case UO_Minus: {
11275 if (E->getType()->isUnsignedIntegerType()) {
11276 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11277 Approximate);
11278 }
11279
11280 std::optional<IntRange> SubRange = TryGetExprRange(
11281 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11282
11283 if (!SubRange)
11284 return std::nullopt;
11285
11286 // If the range was previously non-negative, we need an extra bit for the
11287 // sign bit. Otherwise, we need an extra bit because the negation of the
11288 // most-negative value is one bit wider than that value.
11289 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11290 }
11291
11292 case UO_Not: {
11293 if (E->getType()->isUnsignedIntegerType()) {
11294 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11295 Approximate);
11296 }
11297
11298 std::optional<IntRange> SubRange = TryGetExprRange(
11299 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11300
11301 if (!SubRange)
11302 return std::nullopt;
11303
11304 // The width increments by 1 if the sub-expression cannot be negative
11305 // since it now can be.
11306 return IntRange(
11307 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11308 false);
11309 }
11310
11311 default:
11312 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11313 Approximate);
11314 }
11315 }
11316
11317 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11318 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11319 Approximate);
11320
11321 if (const auto *BitField = E->getSourceBitField())
11322 return IntRange(BitField->getBitWidthValue(),
11323 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11324
11325 if (GetExprType(E)->isVoidType())
11326 return std::nullopt;
11327
11328 return IntRange::forValueOfType(C, GetExprType(E));
11329}
11330
11331static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11332 bool InConstantContext,
11333 bool Approximate) {
11334 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11335 Approximate);
11336}
11337
11338/// Checks whether the given value, which currently has the given
11339/// source semantics, has the same value when coerced through the
11340/// target semantics.
11341static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11342 const llvm::fltSemantics &Src,
11343 const llvm::fltSemantics &Tgt) {
11344 llvm::APFloat truncated = value;
11345
11346 bool ignored;
11347 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11348 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11349
11350 return truncated.bitwiseIsEqual(value);
11351}
11352
11353/// Checks whether the given value, which currently has the given
11354/// source semantics, has the same value when coerced through the
11355/// target semantics.
11356///
11357/// The value might be a vector of floats (or a complex number).
11358static bool IsSameFloatAfterCast(const APValue &value,
11359 const llvm::fltSemantics &Src,
11360 const llvm::fltSemantics &Tgt) {
11361 if (value.isFloat())
11362 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11363
11364 if (value.isVector()) {
11365 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11366 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11367 return false;
11368 return true;
11369 }
11370
11371 assert(value.isComplexFloat());
11372 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11373 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11374}
11375
11376static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11377 bool IsListInit = false);
11378
11379static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11380 // Suppress cases where we are comparing against an enum constant.
11381 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11382 if (isa<EnumConstantDecl>(DR->getDecl()))
11383 return true;
11384
11385 // Suppress cases where the value is expanded from a macro, unless that macro
11386 // is how a language represents a boolean literal. This is the case in both C
11387 // and Objective-C.
11388 SourceLocation BeginLoc = E->getBeginLoc();
11389 if (BeginLoc.isMacroID()) {
11390 StringRef MacroName = Lexer::getImmediateMacroName(
11391 BeginLoc, S.getSourceManager(), S.getLangOpts());
11392 return MacroName != "YES" && MacroName != "NO" &&
11393 MacroName != "true" && MacroName != "false";
11394 }
11395
11396 return false;
11397}
11398
11399static bool isKnownToHaveUnsignedValue(const Expr *E) {
11400 return E->getType()->isIntegerType() &&
11401 (!E->getType()->isSignedIntegerType() ||
11403}
11404
11405namespace {
11406/// The promoted range of values of a type. In general this has the
11407/// following structure:
11408///
11409/// |-----------| . . . |-----------|
11410/// ^ ^ ^ ^
11411/// Min HoleMin HoleMax Max
11412///
11413/// ... where there is only a hole if a signed type is promoted to unsigned
11414/// (in which case Min and Max are the smallest and largest representable
11415/// values).
11416struct PromotedRange {
11417 // Min, or HoleMax if there is a hole.
11418 llvm::APSInt PromotedMin;
11419 // Max, or HoleMin if there is a hole.
11420 llvm::APSInt PromotedMax;
11421
11422 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11423 if (R.Width == 0)
11424 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11425 else if (R.Width >= BitWidth && !Unsigned) {
11426 // Promotion made the type *narrower*. This happens when promoting
11427 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11428 // Treat all values of 'signed int' as being in range for now.
11429 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11430 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11431 } else {
11432 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11433 .extOrTrunc(BitWidth);
11434 PromotedMin.setIsUnsigned(Unsigned);
11435
11436 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11437 .extOrTrunc(BitWidth);
11438 PromotedMax.setIsUnsigned(Unsigned);
11439 }
11440 }
11441
11442 // Determine whether this range is contiguous (has no hole).
11443 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11444
11445 // Where a constant value is within the range.
11446 enum ComparisonResult {
11447 LT = 0x1,
11448 LE = 0x2,
11449 GT = 0x4,
11450 GE = 0x8,
11451 EQ = 0x10,
11452 NE = 0x20,
11453 InRangeFlag = 0x40,
11454
11455 Less = LE | LT | NE,
11456 Min = LE | InRangeFlag,
11457 InRange = InRangeFlag,
11458 Max = GE | InRangeFlag,
11459 Greater = GE | GT | NE,
11460
11461 OnlyValue = LE | GE | EQ | InRangeFlag,
11462 InHole = NE
11463 };
11464
11465 ComparisonResult compare(const llvm::APSInt &Value) const {
11466 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11467 Value.isUnsigned() == PromotedMin.isUnsigned());
11468 if (!isContiguous()) {
11469 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11470 if (Value.isMinValue()) return Min;
11471 if (Value.isMaxValue()) return Max;
11472 if (Value >= PromotedMin) return InRange;
11473 if (Value <= PromotedMax) return InRange;
11474 return InHole;
11475 }
11476
11477 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11478 case -1: return Less;
11479 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11480 case 1:
11481 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11482 case -1: return InRange;
11483 case 0: return Max;
11484 case 1: return Greater;
11485 }
11486 }
11487
11488 llvm_unreachable("impossible compare result");
11489 }
11490
11491 static std::optional<StringRef>
11492 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11493 if (Op == BO_Cmp) {
11494 ComparisonResult LTFlag = LT, GTFlag = GT;
11495 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11496
11497 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11498 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11499 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11500 return std::nullopt;
11501 }
11502
11503 ComparisonResult TrueFlag, FalseFlag;
11504 if (Op == BO_EQ) {
11505 TrueFlag = EQ;
11506 FalseFlag = NE;
11507 } else if (Op == BO_NE) {
11508 TrueFlag = NE;
11509 FalseFlag = EQ;
11510 } else {
11511 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11512 TrueFlag = LT;
11513 FalseFlag = GE;
11514 } else {
11515 TrueFlag = GT;
11516 FalseFlag = LE;
11517 }
11518 if (Op == BO_GE || Op == BO_LE)
11519 std::swap(TrueFlag, FalseFlag);
11520 }
11521 if (R & TrueFlag)
11522 return StringRef("true");
11523 if (R & FalseFlag)
11524 return StringRef("false");
11525 return std::nullopt;
11526 }
11527};
11528}
11529
11530static bool HasEnumType(const Expr *E) {
11531 // Strip off implicit integral promotions.
11532 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11533 if (ICE->getCastKind() != CK_IntegralCast &&
11534 ICE->getCastKind() != CK_NoOp)
11535 break;
11536 E = ICE->getSubExpr();
11537 }
11538
11539 return E->getType()->isEnumeralType();
11540}
11541
11542static int classifyConstantValue(Expr *Constant) {
11543 // The values of this enumeration are used in the diagnostics
11544 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11545 enum ConstantValueKind {
11546 Miscellaneous = 0,
11547 LiteralTrue,
11548 LiteralFalse
11549 };
11550 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11551 return BL->getValue() ? ConstantValueKind::LiteralTrue
11552 : ConstantValueKind::LiteralFalse;
11553 return ConstantValueKind::Miscellaneous;
11554}
11555
11557 Expr *Constant, Expr *Other,
11558 const llvm::APSInt &Value,
11559 bool RhsConstant) {
11561 return false;
11562
11563 Expr *OriginalOther = Other;
11564
11565 Constant = Constant->IgnoreParenImpCasts();
11566 Other = Other->IgnoreParenImpCasts();
11567
11568 // Suppress warnings on tautological comparisons between values of the same
11569 // enumeration type. There are only two ways we could warn on this:
11570 // - If the constant is outside the range of representable values of
11571 // the enumeration. In such a case, we should warn about the cast
11572 // to enumeration type, not about the comparison.
11573 // - If the constant is the maximum / minimum in-range value. For an
11574 // enumeratin type, such comparisons can be meaningful and useful.
11575 if (Constant->getType()->isEnumeralType() &&
11576 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11577 return false;
11578
11579 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11580 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11581 if (!OtherValueRange)
11582 return false;
11583
11584 QualType OtherT = Other->getType();
11585 if (const auto *AT = OtherT->getAs<AtomicType>())
11586 OtherT = AT->getValueType();
11587 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11588
11589 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11590 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11591 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11592 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11593 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11594
11595 // Whether we're treating Other as being a bool because of the form of
11596 // expression despite it having another type (typically 'int' in C).
11597 bool OtherIsBooleanDespiteType =
11598 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11599 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11600 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11601
11602 // Check if all values in the range of possible values of this expression
11603 // lead to the same comparison outcome.
11604 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11605 Value.isUnsigned());
11606 auto Cmp = OtherPromotedValueRange.compare(Value);
11607 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11608 if (!Result)
11609 return false;
11610
11611 // Also consider the range determined by the type alone. This allows us to
11612 // classify the warning under the proper diagnostic group.
11613 bool TautologicalTypeCompare = false;
11614 {
11615 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11616 Value.isUnsigned());
11617 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11618 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11619 RhsConstant)) {
11620 TautologicalTypeCompare = true;
11621 Cmp = TypeCmp;
11622 Result = TypeResult;
11623 }
11624 }
11625
11626 // Don't warn if the non-constant operand actually always evaluates to the
11627 // same value.
11628 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11629 return false;
11630
11631 // Suppress the diagnostic for an in-range comparison if the constant comes
11632 // from a macro or enumerator. We don't want to diagnose
11633 //
11634 // some_long_value <= INT_MAX
11635 //
11636 // when sizeof(int) == sizeof(long).
11637 bool InRange = Cmp & PromotedRange::InRangeFlag;
11638 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11639 return false;
11640
11641 // A comparison of an unsigned bit-field against 0 is really a type problem,
11642 // even though at the type level the bit-field might promote to 'signed int'.
11643 if (Other->refersToBitField() && InRange && Value == 0 &&
11644 Other->getType()->isUnsignedIntegerOrEnumerationType())
11645 TautologicalTypeCompare = true;
11646
11647 // If this is a comparison to an enum constant, include that
11648 // constant in the diagnostic.
11649 const EnumConstantDecl *ED = nullptr;
11650 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11651 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11652
11653 // Should be enough for uint128 (39 decimal digits)
11654 SmallString<64> PrettySourceValue;
11655 llvm::raw_svector_ostream OS(PrettySourceValue);
11656 if (ED) {
11657 OS << '\'' << *ED << "' (" << Value << ")";
11658 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11659 Constant->IgnoreParenImpCasts())) {
11660 OS << (BL->getValue() ? "YES" : "NO");
11661 } else {
11662 OS << Value;
11663 }
11664
11665 if (!TautologicalTypeCompare) {
11666 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11667 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11668 << E->getOpcodeStr() << OS.str() << *Result
11669 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11670 return true;
11671 }
11672
11673 if (IsObjCSignedCharBool) {
11675 S.PDiag(diag::warn_tautological_compare_objc_bool)
11676 << OS.str() << *Result);
11677 return true;
11678 }
11679
11680 // FIXME: We use a somewhat different formatting for the in-range cases and
11681 // cases involving boolean values for historical reasons. We should pick a
11682 // consistent way of presenting these diagnostics.
11683 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11684
11686 E->getOperatorLoc(), E,
11687 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11688 : diag::warn_tautological_bool_compare)
11689 << OS.str() << classifyConstantValue(Constant) << OtherT
11690 << OtherIsBooleanDespiteType << *Result
11691 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11692 } else {
11693 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11694 unsigned Diag =
11695 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11696 ? (HasEnumType(OriginalOther)
11697 ? diag::warn_unsigned_enum_always_true_comparison
11698 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11699 : diag::warn_unsigned_always_true_comparison)
11700 : diag::warn_tautological_constant_compare;
11701
11702 S.Diag(E->getOperatorLoc(), Diag)
11703 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11704 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11705 }
11706
11707 return true;
11708}
11709
11710/// Analyze the operands of the given comparison. Implements the
11711/// fallback case from AnalyzeComparison.
11716
11717/// Implements -Wsign-compare.
11718///
11719/// \param E the binary operator to check for warnings
11721 // The type the comparison is being performed in.
11722 QualType T = E->getLHS()->getType();
11723
11724 // Only analyze comparison operators where both sides have been converted to
11725 // the same type.
11727 return AnalyzeImpConvsInComparison(S, E);
11728
11729 // Don't analyze value-dependent comparisons directly.
11730 if (E->isValueDependent())
11731 return AnalyzeImpConvsInComparison(S, E);
11732
11733 Expr *LHS = E->getLHS();
11734 Expr *RHS = E->getRHS();
11735
11736 if (T->isIntegralType(S.Context)) {
11737 std::optional<llvm::APSInt> RHSValue =
11739 std::optional<llvm::APSInt> LHSValue =
11741
11742 // We don't care about expressions whose result is a constant.
11743 if (RHSValue && LHSValue)
11744 return AnalyzeImpConvsInComparison(S, E);
11745
11746 // We only care about expressions where just one side is literal
11747 if ((bool)RHSValue ^ (bool)LHSValue) {
11748 // Is the constant on the RHS or LHS?
11749 const bool RhsConstant = (bool)RHSValue;
11750 Expr *Const = RhsConstant ? RHS : LHS;
11751 Expr *Other = RhsConstant ? LHS : RHS;
11752 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11753
11754 // Check whether an integer constant comparison results in a value
11755 // of 'true' or 'false'.
11756 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11757 return AnalyzeImpConvsInComparison(S, E);
11758 }
11759 }
11760
11761 if (!T->hasUnsignedIntegerRepresentation()) {
11762 // We don't do anything special if this isn't an unsigned integral
11763 // comparison: we're only interested in integral comparisons, and
11764 // signed comparisons only happen in cases we don't care to warn about.
11765 return AnalyzeImpConvsInComparison(S, E);
11766 }
11767
11768 LHS = LHS->IgnoreParenImpCasts();
11769 RHS = RHS->IgnoreParenImpCasts();
11770
11771 if (!S.getLangOpts().CPlusPlus) {
11772 // Avoid warning about comparison of integers with different signs when
11773 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11774 // the type of `E`.
11775 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11776 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11777 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11778 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11779 }
11780
11781 // Check to see if one of the (unmodified) operands is of different
11782 // signedness.
11783 Expr *signedOperand, *unsignedOperand;
11785 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11786 "unsigned comparison between two signed integer expressions?");
11787 signedOperand = LHS;
11788 unsignedOperand = RHS;
11789 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11790 signedOperand = RHS;
11791 unsignedOperand = LHS;
11792 } else {
11793 return AnalyzeImpConvsInComparison(S, E);
11794 }
11795
11796 // Otherwise, calculate the effective range of the signed operand.
11797 std::optional<IntRange> signedRange =
11799 /*Approximate=*/true);
11800 if (!signedRange)
11801 return;
11802
11803 // Go ahead and analyze implicit conversions in the operands. Note
11804 // that we skip the implicit conversions on both sides.
11807
11808 // If the signed range is non-negative, -Wsign-compare won't fire.
11809 if (signedRange->NonNegative)
11810 return;
11811
11812 // For (in)equality comparisons, if the unsigned operand is a
11813 // constant which cannot collide with a overflowed signed operand,
11814 // then reinterpreting the signed operand as unsigned will not
11815 // change the result of the comparison.
11816 if (E->isEqualityOp()) {
11817 unsigned comparisonWidth = S.Context.getIntWidth(T);
11818 std::optional<IntRange> unsignedRange = TryGetExprRange(
11819 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
11820 /*Approximate=*/true);
11821 if (!unsignedRange)
11822 return;
11823
11824 // We should never be unable to prove that the unsigned operand is
11825 // non-negative.
11826 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
11827
11828 if (unsignedRange->Width < comparisonWidth)
11829 return;
11830 }
11831
11833 S.PDiag(diag::warn_mixed_sign_comparison)
11834 << LHS->getType() << RHS->getType()
11835 << LHS->getSourceRange() << RHS->getSourceRange());
11836}
11837
11838/// Analyzes an attempt to assign the given value to a bitfield.
11839///
11840/// Returns true if there was something fishy about the attempt.
11842 SourceLocation InitLoc) {
11843 assert(Bitfield->isBitField());
11844 if (Bitfield->isInvalidDecl())
11845 return false;
11846
11847 // White-list bool bitfields.
11848 QualType BitfieldType = Bitfield->getType();
11849 if (BitfieldType->isBooleanType())
11850 return false;
11851
11852 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
11853 // If the underlying enum type was not explicitly specified as an unsigned
11854 // type and the enum contain only positive values, MSVC++ will cause an
11855 // inconsistency by storing this as a signed type.
11856 if (S.getLangOpts().CPlusPlus11 &&
11857 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11858 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11859 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11860 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11861 << BitfieldEnumDecl;
11862 }
11863 }
11864
11865 // Ignore value- or type-dependent expressions.
11866 if (Bitfield->getBitWidth()->isValueDependent() ||
11867 Bitfield->getBitWidth()->isTypeDependent() ||
11868 Init->isValueDependent() ||
11869 Init->isTypeDependent())
11870 return false;
11871
11872 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11873 unsigned FieldWidth = Bitfield->getBitWidthValue();
11874
11875 Expr::EvalResult Result;
11876 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11878 // The RHS is not constant. If the RHS has an enum type, make sure the
11879 // bitfield is wide enough to hold all the values of the enum without
11880 // truncation.
11881 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
11882 const PreferredTypeAttr *PTAttr = nullptr;
11883 if (!ED) {
11884 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
11885 if (PTAttr)
11886 ED = PTAttr->getType()->getAsEnumDecl();
11887 }
11888 if (ED) {
11889 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
11890
11891 // Enum types are implicitly signed on Windows, so check if there are any
11892 // negative enumerators to see if the enum was intended to be signed or
11893 // not.
11894 bool SignedEnum = ED->getNumNegativeBits() > 0;
11895
11896 // Check for surprising sign changes when assigning enum values to a
11897 // bitfield of different signedness. If the bitfield is signed and we
11898 // have exactly the right number of bits to store this unsigned enum,
11899 // suggest changing the enum to an unsigned type. This typically happens
11900 // on Windows where unfixed enums always use an underlying type of 'int'.
11901 unsigned DiagID = 0;
11902 if (SignedEnum && !SignedBitfield) {
11903 DiagID =
11904 PTAttr == nullptr
11905 ? diag::warn_unsigned_bitfield_assigned_signed_enum
11906 : diag::
11907 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
11908 } else if (SignedBitfield && !SignedEnum &&
11909 ED->getNumPositiveBits() == FieldWidth) {
11910 DiagID =
11911 PTAttr == nullptr
11912 ? diag::warn_signed_bitfield_enum_conversion
11913 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
11914 }
11915 if (DiagID) {
11916 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11917 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11918 SourceRange TypeRange =
11919 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11920 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11921 << SignedEnum << TypeRange;
11922 if (PTAttr)
11923 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11924 << ED;
11925 }
11926
11927 // Compute the required bitwidth. If the enum has negative values, we need
11928 // one more bit than the normal number of positive bits to represent the
11929 // sign bit.
11930 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11931 ED->getNumNegativeBits())
11932 : ED->getNumPositiveBits();
11933
11934 // Check the bitwidth.
11935 if (BitsNeeded > FieldWidth) {
11936 Expr *WidthExpr = Bitfield->getBitWidth();
11937 auto DiagID =
11938 PTAttr == nullptr
11939 ? diag::warn_bitfield_too_small_for_enum
11940 : diag::warn_preferred_type_bitfield_too_small_for_enum;
11941 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11942 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11943 << BitsNeeded << ED << WidthExpr->getSourceRange();
11944 if (PTAttr)
11945 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11946 << ED;
11947 }
11948 }
11949
11950 return false;
11951 }
11952
11953 llvm::APSInt Value = Result.Val.getInt();
11954
11955 unsigned OriginalWidth = Value.getBitWidth();
11956
11957 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
11958 // false positives where the user is demonstrating they intend to use the
11959 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
11960 // to a one-bit bit-field to see if the value came from a macro named 'true'.
11961 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
11962 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
11963 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
11964 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
11965 S.findMacroSpelling(MaybeMacroLoc, "true"))
11966 return false;
11967 }
11968
11969 if (!Value.isSigned() || Value.isNegative())
11970 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11971 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11972 OriginalWidth = Value.getSignificantBits();
11973
11974 if (OriginalWidth <= FieldWidth)
11975 return false;
11976
11977 // Compute the value which the bitfield will contain.
11978 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11979 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11980
11981 // Check whether the stored value is equal to the original value.
11982 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11983 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11984 return false;
11985
11986 std::string PrettyValue = toString(Value, 10);
11987 std::string PrettyTrunc = toString(TruncatedValue, 10);
11988
11989 S.Diag(InitLoc, OneAssignedToOneBitBitfield
11990 ? diag::warn_impcast_single_bit_bitield_precision_constant
11991 : diag::warn_impcast_bitfield_precision_constant)
11992 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11993 << Init->getSourceRange();
11994
11995 return true;
11996}
11997
11998/// Analyze the given simple or compound assignment for warning-worthy
11999/// operations.
12001 // Just recurse on the LHS.
12003
12004 // We want to recurse on the RHS as normal unless we're assigning to
12005 // a bitfield.
12006 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12007 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12008 E->getOperatorLoc())) {
12009 // Recurse, ignoring any implicit conversions on the RHS.
12011 E->getOperatorLoc());
12012 }
12013 }
12014
12016
12017 // Diagnose implicitly sequentially-consistent atomic assignment.
12018 if (E->getLHS()->getType()->isAtomicType())
12019 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12020}
12021
12022/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12023static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12024 QualType T, SourceLocation CContext, unsigned diag,
12025 bool PruneControlFlow = false) {
12026 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12027 // address space annotations isn't really useful. The warnings aren't because
12028 // you're converting a `private int` to `unsigned int`, it is because you're
12029 // conerting `int` to `unsigned int`.
12030 if (SourceType.hasAddressSpace())
12031 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12032 if (T.hasAddressSpace())
12034 if (PruneControlFlow) {
12036 S.PDiag(diag)
12037 << SourceType << T << E->getSourceRange()
12038 << SourceRange(CContext));
12039 return;
12040 }
12041 S.Diag(E->getExprLoc(), diag)
12042 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12043}
12044
12045/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12046static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12047 SourceLocation CContext, unsigned diag,
12048 bool PruneControlFlow = false) {
12049 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12050}
12051
12052/// Diagnose an implicit cast from a floating point value to an integer value.
12053static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12054 SourceLocation CContext) {
12055 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12056 bool PruneWarnings = S.inTemplateInstantiation();
12057
12058 const Expr *InnerE = E->IgnoreParenImpCasts();
12059 // We also want to warn on, e.g., "int i = -1.234"
12060 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12061 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12062 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12063
12064 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12065
12066 llvm::APFloat Value(0.0);
12067 bool IsConstant =
12069 if (!IsConstant) {
12070 if (S.ObjC().isSignedCharBool(T)) {
12072 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12073 << E->getType());
12074 }
12075
12076 return DiagnoseImpCast(S, E, T, CContext,
12077 diag::warn_impcast_float_integer, PruneWarnings);
12078 }
12079
12080 bool isExact = false;
12081
12082 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12083 T->hasUnsignedIntegerRepresentation());
12084 llvm::APFloat::opStatus Result = Value.convertToInteger(
12085 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12086
12087 // FIXME: Force the precision of the source value down so we don't print
12088 // digits which are usually useless (we don't really care here if we
12089 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12090 // would automatically print the shortest representation, but it's a bit
12091 // tricky to implement.
12092 SmallString<16> PrettySourceValue;
12093 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12094 precision = (precision * 59 + 195) / 196;
12095 Value.toString(PrettySourceValue, precision);
12096
12097 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12099 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12100 << PrettySourceValue);
12101 }
12102
12103 if (Result == llvm::APFloat::opOK && isExact) {
12104 if (IsLiteral) return;
12105 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12106 PruneWarnings);
12107 }
12108
12109 // Conversion of a floating-point value to a non-bool integer where the
12110 // integral part cannot be represented by the integer type is undefined.
12111 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12112 return DiagnoseImpCast(
12113 S, E, T, CContext,
12114 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12115 : diag::warn_impcast_float_to_integer_out_of_range,
12116 PruneWarnings);
12117
12118 unsigned DiagID = 0;
12119 if (IsLiteral) {
12120 // Warn on floating point literal to integer.
12121 DiagID = diag::warn_impcast_literal_float_to_integer;
12122 } else if (IntegerValue == 0) {
12123 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12124 return DiagnoseImpCast(S, E, T, CContext,
12125 diag::warn_impcast_float_integer, PruneWarnings);
12126 }
12127 // Warn on non-zero to zero conversion.
12128 DiagID = diag::warn_impcast_float_to_integer_zero;
12129 } else {
12130 if (IntegerValue.isUnsigned()) {
12131 if (!IntegerValue.isMaxValue()) {
12132 return DiagnoseImpCast(S, E, T, CContext,
12133 diag::warn_impcast_float_integer, PruneWarnings);
12134 }
12135 } else { // IntegerValue.isSigned()
12136 if (!IntegerValue.isMaxSignedValue() &&
12137 !IntegerValue.isMinSignedValue()) {
12138 return DiagnoseImpCast(S, E, T, CContext,
12139 diag::warn_impcast_float_integer, PruneWarnings);
12140 }
12141 }
12142 // Warn on evaluatable floating point expression to integer conversion.
12143 DiagID = diag::warn_impcast_float_to_integer;
12144 }
12145
12146 SmallString<16> PrettyTargetValue;
12147 if (IsBool)
12148 PrettyTargetValue = Value.isZero() ? "false" : "true";
12149 else
12150 IntegerValue.toString(PrettyTargetValue);
12151
12152 if (PruneWarnings) {
12154 S.PDiag(DiagID)
12155 << E->getType() << T.getUnqualifiedType()
12156 << PrettySourceValue << PrettyTargetValue
12157 << E->getSourceRange() << SourceRange(CContext));
12158 } else {
12159 S.Diag(E->getExprLoc(), DiagID)
12160 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12161 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12162 }
12163}
12164
12165/// Analyze the given compound assignment for the possible losing of
12166/// floating-point precision.
12168 assert(isa<CompoundAssignOperator>(E) &&
12169 "Must be compound assignment operation");
12170 // Recurse on the LHS and RHS in here
12173
12174 if (E->getLHS()->getType()->isAtomicType())
12175 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12176
12177 // Now check the outermost expression
12178 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12179 const auto *RBT = cast<CompoundAssignOperator>(E)
12180 ->getComputationResultType()
12181 ->getAs<BuiltinType>();
12182
12183 // The below checks assume source is floating point.
12184 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12185
12186 // If source is floating point but target is an integer.
12187 if (ResultBT->isInteger())
12188 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12189 E->getExprLoc(), diag::warn_impcast_float_integer);
12190
12191 if (!ResultBT->isFloatingPoint())
12192 return;
12193
12194 // If both source and target are floating points, warn about losing precision.
12196 QualType(ResultBT, 0), QualType(RBT, 0));
12197 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12198 // warn about dropping FP rank.
12199 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12200 diag::warn_impcast_float_result_precision);
12201}
12202
12203static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12204 IntRange Range) {
12205 if (!Range.Width) return "0";
12206
12207 llvm::APSInt ValueInRange = Value;
12208 ValueInRange.setIsSigned(!Range.NonNegative);
12209 ValueInRange = ValueInRange.trunc(Range.Width);
12210 return toString(ValueInRange, 10);
12211}
12212
12213static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12214 bool ToBool) {
12215 if (!isa<ImplicitCastExpr>(Ex))
12216 return false;
12217
12218 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12220 const Type *Source =
12222 if (Target->isDependentType())
12223 return false;
12224
12225 const auto *FloatCandidateBT =
12226 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12227 const Type *BoolCandidateType = ToBool ? Target : Source;
12228
12229 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12230 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12231}
12232
12233static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12234 SourceLocation CC) {
12235 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12236 const Expr *CurrA = TheCall->getArg(I);
12237 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12238 continue;
12239
12240 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12241 S, TheCall->getArg(I - 1), false));
12242 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12243 S, TheCall->getArg(I + 1), false));
12244 if (IsSwapped) {
12245 // Warn on this floating-point to bool conversion.
12247 CurrA->getType(), CC,
12248 diag::warn_impcast_floating_point_to_bool);
12249 }
12250 }
12251}
12252
12254 SourceLocation CC) {
12255 // Don't warn on functions which have return type nullptr_t.
12256 if (isa<CallExpr>(E))
12257 return;
12258
12259 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12260 const Expr *NewE = E->IgnoreParenImpCasts();
12261 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12262 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12263 if (!IsGNUNullExpr && !HasNullPtrType)
12264 return;
12265
12266 // Return if target type is a safe conversion.
12267 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12268 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12269 return;
12270
12271 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12272 E->getExprLoc()))
12273 return;
12274
12276
12277 // Venture through the macro stacks to get to the source of macro arguments.
12278 // The new location is a better location than the complete location that was
12279 // passed in.
12280 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12282
12283 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12284 if (IsGNUNullExpr && Loc.isMacroID()) {
12285 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12286 Loc, S.SourceMgr, S.getLangOpts());
12287 if (MacroName == "NULL")
12289 }
12290
12291 // Only warn if the null and context location are in the same macro expansion.
12292 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12293 return;
12294
12295 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12296 << HasNullPtrType << T << SourceRange(CC)
12299}
12300
12301// Helper function to filter out cases for constant width constant conversion.
12302// Don't warn on char array initialization or for non-decimal values.
12304 SourceLocation CC) {
12305 // If initializing from a constant, and the constant starts with '0',
12306 // then it is a binary, octal, or hexadecimal. Allow these constants
12307 // to fill all the bits, even if there is a sign change.
12308 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12309 const char FirstLiteralCharacter =
12310 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12311 if (FirstLiteralCharacter == '0')
12312 return false;
12313 }
12314
12315 // If the CC location points to a '{', and the type is char, then assume
12316 // assume it is an array initialization.
12317 if (CC.isValid() && T->isCharType()) {
12318 const char FirstContextCharacter =
12320 if (FirstContextCharacter == '{')
12321 return false;
12322 }
12323
12324 return true;
12325}
12326
12328 const auto *IL = dyn_cast<IntegerLiteral>(E);
12329 if (!IL) {
12330 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12331 if (UO->getOpcode() == UO_Minus)
12332 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12333 }
12334 }
12335
12336 return IL;
12337}
12338
12340 E = E->IgnoreParenImpCasts();
12341 SourceLocation ExprLoc = E->getExprLoc();
12342
12343 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12344 BinaryOperator::Opcode Opc = BO->getOpcode();
12345 Expr::EvalResult Result;
12346 // Do not diagnose unsigned shifts.
12347 if (Opc == BO_Shl) {
12348 const auto *LHS = getIntegerLiteral(BO->getLHS());
12349 const auto *RHS = getIntegerLiteral(BO->getRHS());
12350 if (LHS && LHS->getValue() == 0)
12351 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12352 else if (!E->isValueDependent() && LHS && RHS &&
12353 RHS->getValue().isNonNegative() &&
12355 S.Diag(ExprLoc, diag::warn_left_shift_always)
12356 << (Result.Val.getInt() != 0);
12357 else if (E->getType()->isSignedIntegerType())
12358 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12361 ") != 0");
12362 }
12363 }
12364
12365 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12366 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12367 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12368 if (!LHS || !RHS)
12369 return;
12370 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12371 (RHS->getValue() == 0 || RHS->getValue() == 1))
12372 // Do not diagnose common idioms.
12373 return;
12374 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12375 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12376 }
12377}
12378
12380 const Type *Target, Expr *E,
12381 QualType T,
12382 SourceLocation CC) {
12383 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12384 Source != Target);
12385
12386 // Lone surrogates have a distinct representation in UTF-32.
12387 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12388 // so don't warn on such conversion.
12389 if (Source->isChar16Type() && Target->isChar32Type())
12390 return;
12391
12392 Expr::EvalResult Result;
12395 llvm::APSInt Value(32);
12396 Value = Result.Val.getInt();
12397 bool IsASCII = Value <= 0x7F;
12398 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12399 bool ConversionPreservesSemantics =
12400 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12401
12402 if (!ConversionPreservesSemantics) {
12403 auto IsSingleCodeUnitCP = [](const QualType &T,
12404 const llvm::APSInt &Value) {
12405 if (T->isChar8Type())
12406 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12407 if (T->isChar16Type())
12408 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12409 assert(T->isChar32Type());
12410 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12411 };
12412
12413 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12414 << E->getType() << T
12415 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12416 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12417 }
12418 } else {
12419 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12421 DiagnoseImpCast(S, E, T, CC,
12422 LosesPrecision ? diag::warn_impcast_unicode_precision
12423 : diag::warn_impcast_unicode_char_type);
12424 }
12425}
12426
12428 From = Context.getCanonicalType(From);
12429 To = Context.getCanonicalType(To);
12430 QualType MaybePointee = From->getPointeeType();
12431 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12432 From = MaybePointee;
12433 MaybePointee = To->getPointeeType();
12434 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12435 To = MaybePointee;
12436
12437 if (const auto *FromFn = From->getAs<FunctionType>()) {
12438 if (const auto *ToFn = To->getAs<FunctionType>()) {
12439 if (FromFn->getCFIUncheckedCalleeAttr() &&
12440 !ToFn->getCFIUncheckedCalleeAttr())
12441 return true;
12442 }
12443 }
12444 return false;
12445}
12446
12448 bool *ICContext, bool IsListInit) {
12449 if (E->isTypeDependent() || E->isValueDependent()) return;
12450
12451 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12452 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12453 if (Source == Target) return;
12454 if (Target->isDependentType()) return;
12455
12456 // If the conversion context location is invalid don't complain. We also
12457 // don't want to emit a warning if the issue occurs from the expansion of
12458 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12459 // delay this check as long as possible. Once we detect we are in that
12460 // scenario, we just return.
12461 if (CC.isInvalid())
12462 return;
12463
12464 if (Source->isAtomicType())
12465 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12466
12467 // Diagnose implicit casts to bool.
12468 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12469 if (isa<StringLiteral>(E))
12470 // Warn on string literal to bool. Checks for string literals in logical
12471 // and expressions, for instance, assert(0 && "error here"), are
12472 // prevented by a check in AnalyzeImplicitConversions().
12473 return DiagnoseImpCast(*this, E, T, CC,
12474 diag::warn_impcast_string_literal_to_bool);
12477 // This covers the literal expressions that evaluate to Objective-C
12478 // objects.
12479 return DiagnoseImpCast(*this, E, T, CC,
12480 diag::warn_impcast_objective_c_literal_to_bool);
12481 }
12482 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12483 // Warn on pointer to bool conversion that is always true.
12485 SourceRange(CC));
12486 }
12487 }
12488
12489 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12490 // is a typedef for signed char (macOS), then that constant value has to be 1
12491 // or 0.
12492 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12495 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12497 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12498 << toString(Result.Val.getInt(), 10));
12499 }
12500 return;
12501 }
12502 }
12503
12504 // Check implicit casts from Objective-C collection literals to specialized
12505 // collection types, e.g., NSArray<NSString *> *.
12506 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12507 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12508 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12509 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12510
12511 // Strip vector types.
12512 if (isa<VectorType>(Source)) {
12513 if (Target->isSveVLSBuiltinType() &&
12514 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12515 QualType(Source, 0)) ||
12516 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12517 QualType(Source, 0))))
12518 return;
12519
12520 if (Target->isRVVVLSBuiltinType() &&
12521 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12522 QualType(Source, 0)) ||
12523 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12524 QualType(Source, 0))))
12525 return;
12526
12527 if (!isa<VectorType>(Target)) {
12528 if (SourceMgr.isInSystemMacro(CC))
12529 return;
12530 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12531 } else if (getLangOpts().HLSL &&
12532 Target->castAs<VectorType>()->getNumElements() <
12533 Source->castAs<VectorType>()->getNumElements()) {
12534 // Diagnose vector truncation but don't return. We may also want to
12535 // diagnose an element conversion.
12536 DiagnoseImpCast(*this, E, T, CC,
12537 diag::warn_hlsl_impcast_vector_truncation);
12538 }
12539
12540 // If the vector cast is cast between two vectors of the same size, it is
12541 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12542 if (!getLangOpts().HLSL &&
12543 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12544 return;
12545
12546 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12547 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12548 }
12549 if (auto VecTy = dyn_cast<VectorType>(Target))
12550 Target = VecTy->getElementType().getTypePtr();
12551
12552 // Strip complex types.
12553 if (isa<ComplexType>(Source)) {
12554 if (!isa<ComplexType>(Target)) {
12555 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12556 return;
12557
12558 return DiagnoseImpCast(*this, E, T, CC,
12560 ? diag::err_impcast_complex_scalar
12561 : diag::warn_impcast_complex_scalar);
12562 }
12563
12564 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12565 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12566 }
12567
12568 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12569 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12570
12571 // Strip SVE vector types
12572 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12573 // Need the original target type for vector type checks
12574 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12575 // Handle conversion from scalable to fixed when msve-vector-bits is
12576 // specified
12577 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12578 QualType(Source, 0)) ||
12579 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12580 QualType(Source, 0)))
12581 return;
12582
12583 // If the vector cast is cast between two vectors of the same size, it is
12584 // a bitcast, not a conversion.
12585 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12586 return;
12587
12588 Source = SourceBT->getSveEltType(Context).getTypePtr();
12589 }
12590
12591 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12592 Target = TargetBT->getSveEltType(Context).getTypePtr();
12593
12594 // If the source is floating point...
12595 if (SourceBT && SourceBT->isFloatingPoint()) {
12596 // ...and the target is floating point...
12597 if (TargetBT && TargetBT->isFloatingPoint()) {
12598 // ...then warn if we're dropping FP rank.
12599
12601 QualType(SourceBT, 0), QualType(TargetBT, 0));
12602 if (Order > 0) {
12603 // Don't warn about float constants that are precisely
12604 // representable in the target type.
12605 Expr::EvalResult result;
12606 if (E->EvaluateAsRValue(result, Context)) {
12607 // Value might be a float, a float vector, or a float complex.
12609 result.Val,
12610 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12611 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12612 return;
12613 }
12614
12615 if (SourceMgr.isInSystemMacro(CC))
12616 return;
12617
12618 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12619 }
12620 // ... or possibly if we're increasing rank, too
12621 else if (Order < 0) {
12622 if (SourceMgr.isInSystemMacro(CC))
12623 return;
12624
12625 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12626 }
12627 return;
12628 }
12629
12630 // If the target is integral, always warn.
12631 if (TargetBT && TargetBT->isInteger()) {
12632 if (SourceMgr.isInSystemMacro(CC))
12633 return;
12634
12635 DiagnoseFloatingImpCast(*this, E, T, CC);
12636 }
12637
12638 // Detect the case where a call result is converted from floating-point to
12639 // to bool, and the final argument to the call is converted from bool, to
12640 // discover this typo:
12641 //
12642 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12643 //
12644 // FIXME: This is an incredibly special case; is there some more general
12645 // way to detect this class of misplaced-parentheses bug?
12646 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12647 // Check last argument of function call to see if it is an
12648 // implicit cast from a type matching the type the result
12649 // is being cast to.
12650 CallExpr *CEx = cast<CallExpr>(E);
12651 if (unsigned NumArgs = CEx->getNumArgs()) {
12652 Expr *LastA = CEx->getArg(NumArgs - 1);
12653 Expr *InnerE = LastA->IgnoreParenImpCasts();
12654 if (isa<ImplicitCastExpr>(LastA) &&
12655 InnerE->getType()->isBooleanType()) {
12656 // Warn on this floating-point to bool conversion
12657 DiagnoseImpCast(*this, E, T, CC,
12658 diag::warn_impcast_floating_point_to_bool);
12659 }
12660 }
12661 }
12662 return;
12663 }
12664
12665 // Valid casts involving fixed point types should be accounted for here.
12666 if (Source->isFixedPointType()) {
12667 if (Target->isUnsaturatedFixedPointType()) {
12671 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12672 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12673 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12674 if (Value > MaxVal || Value < MinVal) {
12676 PDiag(diag::warn_impcast_fixed_point_range)
12677 << Value.toString() << T
12678 << E->getSourceRange()
12679 << clang::SourceRange(CC));
12680 return;
12681 }
12682 }
12683 } else if (Target->isIntegerType()) {
12687 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12688
12689 bool Overflowed;
12690 llvm::APSInt IntResult = FXResult.convertToInt(
12691 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12692 &Overflowed);
12693
12694 if (Overflowed) {
12696 PDiag(diag::warn_impcast_fixed_point_range)
12697 << FXResult.toString() << T
12698 << E->getSourceRange()
12699 << clang::SourceRange(CC));
12700 return;
12701 }
12702 }
12703 }
12704 } else if (Target->isUnsaturatedFixedPointType()) {
12705 if (Source->isIntegerType()) {
12709 llvm::APSInt Value = Result.Val.getInt();
12710
12711 bool Overflowed;
12712 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12713 Value, Context.getFixedPointSemantics(T), &Overflowed);
12714
12715 if (Overflowed) {
12717 PDiag(diag::warn_impcast_fixed_point_range)
12718 << toString(Value, /*Radix=*/10) << T
12719 << E->getSourceRange()
12720 << clang::SourceRange(CC));
12721 return;
12722 }
12723 }
12724 }
12725 }
12726
12727 // If we are casting an integer type to a floating point type without
12728 // initialization-list syntax, we might lose accuracy if the floating
12729 // point type has a narrower significand than the integer type.
12730 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12731 TargetBT->isFloatingType() && !IsListInit) {
12732 // Determine the number of precision bits in the source integer type.
12733 std::optional<IntRange> SourceRange =
12735 /*Approximate=*/true);
12736 if (!SourceRange)
12737 return;
12738 unsigned int SourcePrecision = SourceRange->Width;
12739
12740 // Determine the number of precision bits in the
12741 // target floating point type.
12742 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12743 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12744
12745 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12746 SourcePrecision > TargetPrecision) {
12747
12748 if (std::optional<llvm::APSInt> SourceInt =
12750 // If the source integer is a constant, convert it to the target
12751 // floating point type. Issue a warning if the value changes
12752 // during the whole conversion.
12753 llvm::APFloat TargetFloatValue(
12754 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12755 llvm::APFloat::opStatus ConversionStatus =
12756 TargetFloatValue.convertFromAPInt(
12757 *SourceInt, SourceBT->isSignedInteger(),
12758 llvm::APFloat::rmNearestTiesToEven);
12759
12760 if (ConversionStatus != llvm::APFloat::opOK) {
12761 SmallString<32> PrettySourceValue;
12762 SourceInt->toString(PrettySourceValue, 10);
12763 SmallString<32> PrettyTargetValue;
12764 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12765
12767 E->getExprLoc(), E,
12768 PDiag(diag::warn_impcast_integer_float_precision_constant)
12769 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12770 << E->getSourceRange() << clang::SourceRange(CC));
12771 }
12772 } else {
12773 // Otherwise, the implicit conversion may lose precision.
12774 DiagnoseImpCast(*this, E, T, CC,
12775 diag::warn_impcast_integer_float_precision);
12776 }
12777 }
12778 }
12779
12780 DiagnoseNullConversion(*this, E, T, CC);
12781
12783
12784 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12785 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12786 return;
12787 }
12788
12789 if (Target->isBooleanType())
12790 DiagnoseIntInBoolContext(*this, E);
12791
12793 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
12794 << QualType(Source, 0) << QualType(Target, 0);
12795 }
12796
12797 if (!Source->isIntegerType() || !Target->isIntegerType())
12798 return;
12799
12800 // TODO: remove this early return once the false positives for constant->bool
12801 // in templates, macros, etc, are reduced or removed.
12802 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12803 return;
12804
12805 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
12806 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12808 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12809 << E->getType());
12810 }
12811 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
12812 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
12813 if (!LikelySourceRange)
12814 return;
12815
12816 IntRange SourceTypeRange =
12817 IntRange::forTargetOfCanonicalType(Context, Source);
12818 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
12819
12820 if (LikelySourceRange->Width > TargetRange.Width) {
12821 // If the source is a constant, use a default-on diagnostic.
12822 // TODO: this should happen for bitfield stores, too.
12826 llvm::APSInt Value(32);
12827 Value = Result.Val.getInt();
12828
12829 if (SourceMgr.isInSystemMacro(CC))
12830 return;
12831
12832 std::string PrettySourceValue = toString(Value, 10);
12833 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12834
12836 PDiag(diag::warn_impcast_integer_precision_constant)
12837 << PrettySourceValue << PrettyTargetValue
12838 << E->getType() << T << E->getSourceRange()
12839 << SourceRange(CC));
12840 return;
12841 }
12842
12843 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12844 if (SourceMgr.isInSystemMacro(CC))
12845 return;
12846
12847 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12848 if (UO->getOpcode() == UO_Minus)
12849 return DiagnoseImpCast(
12850 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
12851 }
12852
12853 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
12854 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
12855 /* pruneControlFlow */ true);
12856 return DiagnoseImpCast(*this, E, T, CC,
12857 diag::warn_impcast_integer_precision);
12858 }
12859
12860 if (TargetRange.Width > SourceTypeRange.Width) {
12861 if (auto *UO = dyn_cast<UnaryOperator>(E))
12862 if (UO->getOpcode() == UO_Minus)
12863 if (Source->isUnsignedIntegerType()) {
12864 if (Target->isUnsignedIntegerType())
12865 return DiagnoseImpCast(*this, E, T, CC,
12866 diag::warn_impcast_high_order_zero_bits);
12867 if (Target->isSignedIntegerType())
12868 return DiagnoseImpCast(*this, E, T, CC,
12869 diag::warn_impcast_nonnegative_result);
12870 }
12871 }
12872
12873 if (TargetRange.Width == LikelySourceRange->Width &&
12874 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12875 Source->isSignedIntegerType()) {
12876 // Warn when doing a signed to signed conversion, warn if the positive
12877 // source value is exactly the width of the target type, which will
12878 // cause a negative value to be stored.
12879
12882 !SourceMgr.isInSystemMacro(CC)) {
12883 llvm::APSInt Value = Result.Val.getInt();
12884 if (isSameWidthConstantConversion(*this, E, T, CC)) {
12885 std::string PrettySourceValue = toString(Value, 10);
12886 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12887
12888 Diag(E->getExprLoc(),
12889 PDiag(diag::warn_impcast_integer_precision_constant)
12890 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12891 << E->getSourceRange() << SourceRange(CC));
12892 return;
12893 }
12894 }
12895
12896 // Fall through for non-constants to give a sign conversion warning.
12897 }
12898
12899 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
12900 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
12901 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12902 LikelySourceRange->Width == TargetRange.Width))) {
12903 if (SourceMgr.isInSystemMacro(CC))
12904 return;
12905
12906 if (SourceBT && SourceBT->isInteger() && TargetBT &&
12907 TargetBT->isInteger() &&
12908 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
12909 return;
12910 }
12911
12912 unsigned DiagID = diag::warn_impcast_integer_sign;
12913
12914 // Traditionally, gcc has warned about this under -Wsign-compare.
12915 // We also want to warn about it in -Wconversion.
12916 // So if -Wconversion is off, use a completely identical diagnostic
12917 // in the sign-compare group.
12918 // The conditional-checking code will
12919 if (ICContext) {
12920 DiagID = diag::warn_impcast_integer_sign_conditional;
12921 *ICContext = true;
12922 }
12923
12924 DiagnoseImpCast(*this, E, T, CC, DiagID);
12925 }
12926
12927 // If we're implicitly converting from an integer into an enumeration, that
12928 // is valid in C but invalid in C++.
12929 QualType SourceType = E->getEnumCoercedType(Context);
12930 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
12931 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
12932 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
12933
12934 // Diagnose conversions between different enumeration types.
12935 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12936 // type, to give us better diagnostics.
12937 Source = Context.getCanonicalType(SourceType).getTypePtr();
12938
12939 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
12940 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
12941 if (SourceEnum->getDecl()->hasNameForLinkage() &&
12942 TargetEnum->getDecl()->hasNameForLinkage() &&
12943 SourceEnum != TargetEnum) {
12944 if (SourceMgr.isInSystemMacro(CC))
12945 return;
12946
12947 return DiagnoseImpCast(*this, E, SourceType, T, CC,
12948 diag::warn_impcast_different_enum_types);
12949 }
12950}
12951
12954
12956 SourceLocation CC, bool &ICContext) {
12957 E = E->IgnoreParenImpCasts();
12958 // Diagnose incomplete type for second or third operand in C.
12959 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
12960 S.RequireCompleteExprType(E, diag::err_incomplete_type);
12961
12962 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12963 return CheckConditionalOperator(S, CO, CC, T);
12964
12966 if (E->getType() != T)
12967 return S.CheckImplicitConversion(E, T, CC, &ICContext);
12968}
12969
12973
12974 Expr *TrueExpr = E->getTrueExpr();
12975 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12976 TrueExpr = BCO->getCommon();
12977
12978 bool Suspicious = false;
12979 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12980 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12981
12982 if (T->isBooleanType())
12984
12985 // If -Wconversion would have warned about either of the candidates
12986 // for a signedness conversion to the context type...
12987 if (!Suspicious) return;
12988
12989 // ...but it's currently ignored...
12990 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12991 return;
12992
12993 // ...then check whether it would have warned about either of the
12994 // candidates for a signedness conversion to the condition type.
12995 if (E->getType() == T) return;
12996
12997 Suspicious = false;
12998 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
12999 &Suspicious);
13000 if (!Suspicious)
13002 E->getType(), CC, &Suspicious);
13003}
13004
13005/// Check conversion of given expression to boolean.
13006/// Input argument E is a logical expression.
13008 // Run the bool-like conversion checks only for C since there bools are
13009 // still not used as the return type from "boolean" operators or as the input
13010 // type for conditional operators.
13011 if (S.getLangOpts().CPlusPlus)
13012 return;
13014 return;
13016}
13017
13018namespace {
13019struct AnalyzeImplicitConversionsWorkItem {
13020 Expr *E;
13021 SourceLocation CC;
13022 bool IsListInit;
13023};
13024}
13025
13027 Sema &S, Expr *E, QualType T, SourceLocation CC,
13028 bool ExtraCheckForImplicitConversion,
13030 E = E->IgnoreParenImpCasts();
13031 WorkList.push_back({E, CC, false});
13032
13033 if (ExtraCheckForImplicitConversion && E->getType() != T)
13034 S.CheckImplicitConversion(E, T, CC);
13035}
13036
13037/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13038/// that should be visited are added to WorkList.
13040 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13042 Expr *OrigE = Item.E;
13043 SourceLocation CC = Item.CC;
13044
13045 QualType T = OrigE->getType();
13046 Expr *E = OrigE->IgnoreParenImpCasts();
13047
13048 // Propagate whether we are in a C++ list initialization expression.
13049 // If so, we do not issue warnings for implicit int-float conversion
13050 // precision loss, because C++11 narrowing already handles it.
13051 //
13052 // HLSL's initialization lists are special, so they shouldn't observe the C++
13053 // behavior here.
13054 bool IsListInit =
13055 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13056 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13057
13058 if (E->isTypeDependent() || E->isValueDependent())
13059 return;
13060
13061 Expr *SourceExpr = E;
13062 // Examine, but don't traverse into the source expression of an
13063 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13064 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13065 // evaluate it in the context of checking the specific conversion to T though.
13066 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13067 if (auto *Src = OVE->getSourceExpr())
13068 SourceExpr = Src;
13069
13070 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13071 if (UO->getOpcode() == UO_Not &&
13072 UO->getSubExpr()->isKnownToHaveBooleanValue())
13073 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13074 << OrigE->getSourceRange() << T->isBooleanType()
13075 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13076
13077 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13078 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13079 BO->getLHS()->isKnownToHaveBooleanValue() &&
13080 BO->getRHS()->isKnownToHaveBooleanValue() &&
13081 BO->getLHS()->HasSideEffects(S.Context) &&
13082 BO->getRHS()->HasSideEffects(S.Context)) {
13084 const LangOptions &LO = S.getLangOpts();
13085 SourceLocation BLoc = BO->getOperatorLoc();
13086 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13087 StringRef SR = clang::Lexer::getSourceText(
13088 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13089 // To reduce false positives, only issue the diagnostic if the operator
13090 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13091 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13092 // in C, along with other macro spellings the user might invent.
13093 if (SR.str() == "&" || SR.str() == "|") {
13094
13095 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13096 << (BO->getOpcode() == BO_And ? "&" : "|")
13097 << OrigE->getSourceRange()
13099 BO->getOperatorLoc(),
13100 (BO->getOpcode() == BO_And ? "&&" : "||"));
13101 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13102 }
13103 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13104 /// Analyze the given comma operator. The basic idea behind the analysis
13105 /// is to analyze the left and right operands slightly differently. The
13106 /// left operand needs to check whether the operand itself has an implicit
13107 /// conversion, but not whether the left operand induces an implicit
13108 /// conversion for the entire comma expression itself. This is similar to
13109 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13110 /// were directly used for the implicit conversion check.
13111 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13112 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13113 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13114 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13115 return;
13116 }
13117 }
13118
13119 // For conditional operators, we analyze the arguments as if they
13120 // were being fed directly into the output.
13121 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13122 CheckConditionalOperator(S, CO, CC, T);
13123 return;
13124 }
13125
13126 // Check implicit argument conversions for function calls.
13127 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13129
13130 // Go ahead and check any implicit conversions we might have skipped.
13131 // The non-canonical typecheck is just an optimization;
13132 // CheckImplicitConversion will filter out dead implicit conversions.
13133 if (SourceExpr->getType() != T)
13134 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13135
13136 // Now continue drilling into this expression.
13137
13138 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13139 // The bound subexpressions in a PseudoObjectExpr are not reachable
13140 // as transitive children.
13141 // FIXME: Use a more uniform representation for this.
13142 for (auto *SE : POE->semantics())
13143 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13144 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13145 }
13146
13147 // Skip past explicit casts.
13148 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13149 E = CE->getSubExpr();
13150 // In the special case of a C++ function-style cast with braces,
13151 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13152 // initializer. This InitListExpr basically belongs to the cast itself, so
13153 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13155 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13156 if (InitListE->getNumInits() == 1) {
13157 E = InitListE->getInit(0);
13158 }
13159 }
13160 }
13161 E = E->IgnoreParenImpCasts();
13162 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13163 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13164 WorkList.push_back({E, CC, IsListInit});
13165 return;
13166 }
13167
13168 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13169 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13170 // The base expression is only used to initialize the parameter for
13171 // arguments to `inout` parameters, so we only traverse down the base
13172 // expression for `inout` cases.
13173 if (OutArgE->isInOut())
13174 WorkList.push_back(
13175 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13176 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13177 return;
13178 }
13179
13180 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13181 // Do a somewhat different check with comparison operators.
13182 if (BO->isComparisonOp())
13183 return AnalyzeComparison(S, BO);
13184
13185 // And with simple assignments.
13186 if (BO->getOpcode() == BO_Assign)
13187 return AnalyzeAssignment(S, BO);
13188 // And with compound assignments.
13189 if (BO->isAssignmentOp())
13190 return AnalyzeCompoundAssignment(S, BO);
13191 }
13192
13193 // These break the otherwise-useful invariant below. Fortunately,
13194 // we don't really need to recurse into them, because any internal
13195 // expressions should have been analyzed already when they were
13196 // built into statements.
13197 if (isa<StmtExpr>(E)) return;
13198
13199 // Don't descend into unevaluated contexts.
13200 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13201
13202 // Now just recurse over the expression's children.
13203 CC = E->getExprLoc();
13204 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13205 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13206 for (Stmt *SubStmt : E->children()) {
13207 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13208 if (!ChildExpr)
13209 continue;
13210
13211 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13212 if (ChildExpr == CSE->getOperand())
13213 // Do not recurse over a CoroutineSuspendExpr's operand.
13214 // The operand is also a subexpression of getCommonExpr(), and
13215 // recursing into it directly would produce duplicate diagnostics.
13216 continue;
13217
13218 if (IsLogicalAndOperator &&
13220 // Ignore checking string literals that are in logical and operators.
13221 // This is a common pattern for asserts.
13222 continue;
13223 WorkList.push_back({ChildExpr, CC, IsListInit});
13224 }
13225
13226 if (BO && BO->isLogicalOp()) {
13227 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13228 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13229 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13230
13231 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13232 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13233 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13234 }
13235
13236 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13237 if (U->getOpcode() == UO_LNot) {
13238 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13239 } else if (U->getOpcode() != UO_AddrOf) {
13240 if (U->getSubExpr()->getType()->isAtomicType())
13241 S.Diag(U->getSubExpr()->getBeginLoc(),
13242 diag::warn_atomic_implicit_seq_cst);
13243 }
13244 }
13245}
13246
13247/// AnalyzeImplicitConversions - Find and report any interesting
13248/// implicit conversions in the given expression. There are a couple
13249/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13251 bool IsListInit/*= false*/) {
13253 WorkList.push_back({OrigE, CC, IsListInit});
13254 while (!WorkList.empty())
13255 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13256}
13257
13258// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13259// Returns true when emitting a warning about taking the address of a reference.
13260static bool CheckForReference(Sema &SemaRef, const Expr *E,
13261 const PartialDiagnostic &PD) {
13262 E = E->IgnoreParenImpCasts();
13263
13264 const FunctionDecl *FD = nullptr;
13265
13266 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13267 if (!DRE->getDecl()->getType()->isReferenceType())
13268 return false;
13269 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13270 if (!M->getMemberDecl()->getType()->isReferenceType())
13271 return false;
13272 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13273 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13274 return false;
13275 FD = Call->getDirectCallee();
13276 } else {
13277 return false;
13278 }
13279
13280 SemaRef.Diag(E->getExprLoc(), PD);
13281
13282 // If possible, point to location of function.
13283 if (FD) {
13284 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13285 }
13286
13287 return true;
13288}
13289
13290// Returns true if the SourceLocation is expanded from any macro body.
13291// Returns false if the SourceLocation is invalid, is from not in a macro
13292// expansion, or is from expanded from a top-level macro argument.
13294 if (Loc.isInvalid())
13295 return false;
13296
13297 while (Loc.isMacroID()) {
13298 if (SM.isMacroBodyExpansion(Loc))
13299 return true;
13300 Loc = SM.getImmediateMacroCallerLoc(Loc);
13301 }
13302
13303 return false;
13304}
13305
13308 bool IsEqual, SourceRange Range) {
13309 if (!E)
13310 return;
13311
13312 // Don't warn inside macros.
13313 if (E->getExprLoc().isMacroID()) {
13315 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13316 IsInAnyMacroBody(SM, Range.getBegin()))
13317 return;
13318 }
13319 E = E->IgnoreImpCasts();
13320
13321 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13322
13323 if (isa<CXXThisExpr>(E)) {
13324 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13325 : diag::warn_this_bool_conversion;
13326 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13327 return;
13328 }
13329
13330 bool IsAddressOf = false;
13331
13332 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13333 if (UO->getOpcode() != UO_AddrOf)
13334 return;
13335 IsAddressOf = true;
13336 E = UO->getSubExpr();
13337 }
13338
13339 if (IsAddressOf) {
13340 unsigned DiagID = IsCompare
13341 ? diag::warn_address_of_reference_null_compare
13342 : diag::warn_address_of_reference_bool_conversion;
13343 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13344 << IsEqual;
13345 if (CheckForReference(*this, E, PD)) {
13346 return;
13347 }
13348 }
13349
13350 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13351 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13352 std::string Str;
13353 llvm::raw_string_ostream S(Str);
13354 E->printPretty(S, nullptr, getPrintingPolicy());
13355 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13356 : diag::warn_cast_nonnull_to_bool;
13357 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13358 << E->getSourceRange() << Range << IsEqual;
13359 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13360 };
13361
13362 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13363 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13364 if (auto *Callee = Call->getDirectCallee()) {
13365 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13366 ComplainAboutNonnullParamOrCall(A);
13367 return;
13368 }
13369 }
13370 }
13371
13372 // Complain if we are converting a lambda expression to a boolean value
13373 // outside of instantiation.
13374 if (!inTemplateInstantiation()) {
13375 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13376 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13377 MRecordDecl && MRecordDecl->isLambda()) {
13378 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13379 << /*LambdaPointerConversionOperatorType=*/3
13380 << MRecordDecl->getSourceRange() << Range << IsEqual;
13381 return;
13382 }
13383 }
13384 }
13385
13386 // Expect to find a single Decl. Skip anything more complicated.
13387 ValueDecl *D = nullptr;
13388 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13389 D = R->getDecl();
13390 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13391 D = M->getMemberDecl();
13392 }
13393
13394 // Weak Decls can be null.
13395 if (!D || D->isWeak())
13396 return;
13397
13398 // Check for parameter decl with nonnull attribute
13399 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13400 if (getCurFunction() &&
13401 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13402 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13403 ComplainAboutNonnullParamOrCall(A);
13404 return;
13405 }
13406
13407 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13408 // Skip function template not specialized yet.
13410 return;
13411 auto ParamIter = llvm::find(FD->parameters(), PV);
13412 assert(ParamIter != FD->param_end());
13413 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13414
13415 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13416 if (!NonNull->args_size()) {
13417 ComplainAboutNonnullParamOrCall(NonNull);
13418 return;
13419 }
13420
13421 for (const ParamIdx &ArgNo : NonNull->args()) {
13422 if (ArgNo.getASTIndex() == ParamNo) {
13423 ComplainAboutNonnullParamOrCall(NonNull);
13424 return;
13425 }
13426 }
13427 }
13428 }
13429 }
13430 }
13431
13432 QualType T = D->getType();
13433 const bool IsArray = T->isArrayType();
13434 const bool IsFunction = T->isFunctionType();
13435
13436 // Address of function is used to silence the function warning.
13437 if (IsAddressOf && IsFunction) {
13438 return;
13439 }
13440
13441 // Found nothing.
13442 if (!IsAddressOf && !IsFunction && !IsArray)
13443 return;
13444
13445 // Pretty print the expression for the diagnostic.
13446 std::string Str;
13447 llvm::raw_string_ostream S(Str);
13448 E->printPretty(S, nullptr, getPrintingPolicy());
13449
13450 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13451 : diag::warn_impcast_pointer_to_bool;
13452 enum {
13453 AddressOf,
13454 FunctionPointer,
13455 ArrayPointer
13456 } DiagType;
13457 if (IsAddressOf)
13458 DiagType = AddressOf;
13459 else if (IsFunction)
13460 DiagType = FunctionPointer;
13461 else if (IsArray)
13462 DiagType = ArrayPointer;
13463 else
13464 llvm_unreachable("Could not determine diagnostic.");
13465 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13466 << Range << IsEqual;
13467
13468 if (!IsFunction)
13469 return;
13470
13471 // Suggest '&' to silence the function warning.
13472 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13474
13475 // Check to see if '()' fixit should be emitted.
13476 QualType ReturnType;
13477 UnresolvedSet<4> NonTemplateOverloads;
13478 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13479 if (ReturnType.isNull())
13480 return;
13481
13482 if (IsCompare) {
13483 // There are two cases here. If there is null constant, the only suggest
13484 // for a pointer return type. If the null is 0, then suggest if the return
13485 // type is a pointer or an integer type.
13486 if (!ReturnType->isPointerType()) {
13487 if (NullKind == Expr::NPCK_ZeroExpression ||
13488 NullKind == Expr::NPCK_ZeroLiteral) {
13489 if (!ReturnType->isIntegerType())
13490 return;
13491 } else {
13492 return;
13493 }
13494 }
13495 } else { // !IsCompare
13496 // For function to bool, only suggest if the function pointer has bool
13497 // return type.
13498 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13499 return;
13500 }
13501 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13503}
13504
13505void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13506 // Don't diagnose in unevaluated contexts.
13508 return;
13509
13510 // Don't diagnose for value- or type-dependent expressions.
13511 if (E->isTypeDependent() || E->isValueDependent())
13512 return;
13513
13514 // Check for array bounds violations in cases where the check isn't triggered
13515 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13516 // ArraySubscriptExpr is on the RHS of a variable initialization.
13517 CheckArrayAccess(E);
13518
13519 // This is not the right CC for (e.g.) a variable initialization.
13520 AnalyzeImplicitConversions(*this, E, CC);
13521}
13522
13523void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13524 ::CheckBoolLikeConversion(*this, E, CC);
13525}
13526
13527void Sema::CheckForIntOverflow (const Expr *E) {
13528 // Use a work list to deal with nested struct initializers.
13529 SmallVector<const Expr *, 2> Exprs(1, E);
13530
13531 do {
13532 const Expr *OriginalE = Exprs.pop_back_val();
13533 const Expr *E = OriginalE->IgnoreParenCasts();
13534
13537 continue;
13538 }
13539
13540 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13541 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13542 else if (isa<ObjCBoxedExpr>(OriginalE))
13544 else if (const auto *Call = dyn_cast<CallExpr>(E))
13545 Exprs.append(Call->arg_begin(), Call->arg_end());
13546 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13547 Exprs.append(Message->arg_begin(), Message->arg_end());
13548 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13549 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13550 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13551 Exprs.push_back(Temporary->getSubExpr());
13552 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13553 Exprs.push_back(Array->getIdx());
13554 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13555 Exprs.push_back(Compound->getInitializer());
13556 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13557 New && New->isArray()) {
13558 if (auto ArraySize = New->getArraySize())
13559 Exprs.push_back(*ArraySize);
13560 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13561 Exprs.push_back(MTE->getSubExpr());
13562 } while (!Exprs.empty());
13563}
13564
13565namespace {
13566
13567/// Visitor for expressions which looks for unsequenced operations on the
13568/// same object.
13569class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13570 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13571
13572 /// A tree of sequenced regions within an expression. Two regions are
13573 /// unsequenced if one is an ancestor or a descendent of the other. When we
13574 /// finish processing an expression with sequencing, such as a comma
13575 /// expression, we fold its tree nodes into its parent, since they are
13576 /// unsequenced with respect to nodes we will visit later.
13577 class SequenceTree {
13578 struct Value {
13579 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13580 unsigned Parent : 31;
13581 LLVM_PREFERRED_TYPE(bool)
13582 unsigned Merged : 1;
13583 };
13584 SmallVector<Value, 8> Values;
13585
13586 public:
13587 /// A region within an expression which may be sequenced with respect
13588 /// to some other region.
13589 class Seq {
13590 friend class SequenceTree;
13591
13592 unsigned Index;
13593
13594 explicit Seq(unsigned N) : Index(N) {}
13595
13596 public:
13597 Seq() : Index(0) {}
13598 };
13599
13600 SequenceTree() { Values.push_back(Value(0)); }
13601 Seq root() const { return Seq(0); }
13602
13603 /// Create a new sequence of operations, which is an unsequenced
13604 /// subset of \p Parent. This sequence of operations is sequenced with
13605 /// respect to other children of \p Parent.
13606 Seq allocate(Seq Parent) {
13607 Values.push_back(Value(Parent.Index));
13608 return Seq(Values.size() - 1);
13609 }
13610
13611 /// Merge a sequence of operations into its parent.
13612 void merge(Seq S) {
13613 Values[S.Index].Merged = true;
13614 }
13615
13616 /// Determine whether two operations are unsequenced. This operation
13617 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13618 /// should have been merged into its parent as appropriate.
13619 bool isUnsequenced(Seq Cur, Seq Old) {
13620 unsigned C = representative(Cur.Index);
13621 unsigned Target = representative(Old.Index);
13622 while (C >= Target) {
13623 if (C == Target)
13624 return true;
13625 C = Values[C].Parent;
13626 }
13627 return false;
13628 }
13629
13630 private:
13631 /// Pick a representative for a sequence.
13632 unsigned representative(unsigned K) {
13633 if (Values[K].Merged)
13634 // Perform path compression as we go.
13635 return Values[K].Parent = representative(Values[K].Parent);
13636 return K;
13637 }
13638 };
13639
13640 /// An object for which we can track unsequenced uses.
13641 using Object = const NamedDecl *;
13642
13643 /// Different flavors of object usage which we track. We only track the
13644 /// least-sequenced usage of each kind.
13645 enum UsageKind {
13646 /// A read of an object. Multiple unsequenced reads are OK.
13647 UK_Use,
13648
13649 /// A modification of an object which is sequenced before the value
13650 /// computation of the expression, such as ++n in C++.
13651 UK_ModAsValue,
13652
13653 /// A modification of an object which is not sequenced before the value
13654 /// computation of the expression, such as n++.
13655 UK_ModAsSideEffect,
13656
13657 UK_Count = UK_ModAsSideEffect + 1
13658 };
13659
13660 /// Bundle together a sequencing region and the expression corresponding
13661 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13662 struct Usage {
13663 const Expr *UsageExpr = nullptr;
13664 SequenceTree::Seq Seq;
13665
13666 Usage() = default;
13667 };
13668
13669 struct UsageInfo {
13670 Usage Uses[UK_Count];
13671
13672 /// Have we issued a diagnostic for this object already?
13673 bool Diagnosed = false;
13674
13675 UsageInfo();
13676 };
13677 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13678
13679 Sema &SemaRef;
13680
13681 /// Sequenced regions within the expression.
13682 SequenceTree Tree;
13683
13684 /// Declaration modifications and references which we have seen.
13685 UsageInfoMap UsageMap;
13686
13687 /// The region we are currently within.
13688 SequenceTree::Seq Region;
13689
13690 /// Filled in with declarations which were modified as a side-effect
13691 /// (that is, post-increment operations).
13692 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13693
13694 /// Expressions to check later. We defer checking these to reduce
13695 /// stack usage.
13696 SmallVectorImpl<const Expr *> &WorkList;
13697
13698 /// RAII object wrapping the visitation of a sequenced subexpression of an
13699 /// expression. At the end of this process, the side-effects of the evaluation
13700 /// become sequenced with respect to the value computation of the result, so
13701 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13702 /// UK_ModAsValue.
13703 struct SequencedSubexpression {
13704 SequencedSubexpression(SequenceChecker &Self)
13705 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13706 Self.ModAsSideEffect = &ModAsSideEffect;
13707 }
13708
13709 ~SequencedSubexpression() {
13710 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13711 // Add a new usage with usage kind UK_ModAsValue, and then restore
13712 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13713 // the previous one was empty).
13714 UsageInfo &UI = Self.UsageMap[M.first];
13715 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13716 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13717 SideEffectUsage = M.second;
13718 }
13719 Self.ModAsSideEffect = OldModAsSideEffect;
13720 }
13721
13722 SequenceChecker &Self;
13723 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13724 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13725 };
13726
13727 /// RAII object wrapping the visitation of a subexpression which we might
13728 /// choose to evaluate as a constant. If any subexpression is evaluated and
13729 /// found to be non-constant, this allows us to suppress the evaluation of
13730 /// the outer expression.
13731 class EvaluationTracker {
13732 public:
13733 EvaluationTracker(SequenceChecker &Self)
13734 : Self(Self), Prev(Self.EvalTracker) {
13735 Self.EvalTracker = this;
13736 }
13737
13738 ~EvaluationTracker() {
13739 Self.EvalTracker = Prev;
13740 if (Prev)
13741 Prev->EvalOK &= EvalOK;
13742 }
13743
13744 bool evaluate(const Expr *E, bool &Result) {
13745 if (!EvalOK || E->isValueDependent())
13746 return false;
13747 EvalOK = E->EvaluateAsBooleanCondition(
13748 Result, Self.SemaRef.Context,
13749 Self.SemaRef.isConstantEvaluatedContext());
13750 return EvalOK;
13751 }
13752
13753 private:
13754 SequenceChecker &Self;
13755 EvaluationTracker *Prev;
13756 bool EvalOK = true;
13757 } *EvalTracker = nullptr;
13758
13759 /// Find the object which is produced by the specified expression,
13760 /// if any.
13761 Object getObject(const Expr *E, bool Mod) const {
13762 E = E->IgnoreParenCasts();
13763 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13764 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13765 return getObject(UO->getSubExpr(), Mod);
13766 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13767 if (BO->getOpcode() == BO_Comma)
13768 return getObject(BO->getRHS(), Mod);
13769 if (Mod && BO->isAssignmentOp())
13770 return getObject(BO->getLHS(), Mod);
13771 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13772 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13773 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13774 return ME->getMemberDecl();
13775 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13776 // FIXME: If this is a reference, map through to its value.
13777 return DRE->getDecl();
13778 return nullptr;
13779 }
13780
13781 /// Note that an object \p O was modified or used by an expression
13782 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13783 /// the object \p O as obtained via the \p UsageMap.
13784 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13785 // Get the old usage for the given object and usage kind.
13786 Usage &U = UI.Uses[UK];
13787 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13788 // If we have a modification as side effect and are in a sequenced
13789 // subexpression, save the old Usage so that we can restore it later
13790 // in SequencedSubexpression::~SequencedSubexpression.
13791 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13792 ModAsSideEffect->push_back(std::make_pair(O, U));
13793 // Then record the new usage with the current sequencing region.
13794 U.UsageExpr = UsageExpr;
13795 U.Seq = Region;
13796 }
13797 }
13798
13799 /// Check whether a modification or use of an object \p O in an expression
13800 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13801 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13802 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13803 /// usage and false we are checking for a mod-use unsequenced usage.
13804 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13805 UsageKind OtherKind, bool IsModMod) {
13806 if (UI.Diagnosed)
13807 return;
13808
13809 const Usage &U = UI.Uses[OtherKind];
13810 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13811 return;
13812
13813 const Expr *Mod = U.UsageExpr;
13814 const Expr *ModOrUse = UsageExpr;
13815 if (OtherKind == UK_Use)
13816 std::swap(Mod, ModOrUse);
13817
13818 SemaRef.DiagRuntimeBehavior(
13819 Mod->getExprLoc(), {Mod, ModOrUse},
13820 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13821 : diag::warn_unsequenced_mod_use)
13822 << O << SourceRange(ModOrUse->getExprLoc()));
13823 UI.Diagnosed = true;
13824 }
13825
13826 // A note on note{Pre, Post}{Use, Mod}:
13827 //
13828 // (It helps to follow the algorithm with an expression such as
13829 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13830 // operations before C++17 and both are well-defined in C++17).
13831 //
13832 // When visiting a node which uses/modify an object we first call notePreUse
13833 // or notePreMod before visiting its sub-expression(s). At this point the
13834 // children of the current node have not yet been visited and so the eventual
13835 // uses/modifications resulting from the children of the current node have not
13836 // been recorded yet.
13837 //
13838 // We then visit the children of the current node. After that notePostUse or
13839 // notePostMod is called. These will 1) detect an unsequenced modification
13840 // as side effect (as in "k++ + k") and 2) add a new usage with the
13841 // appropriate usage kind.
13842 //
13843 // We also have to be careful that some operation sequences modification as
13844 // side effect as well (for example: || or ,). To account for this we wrap
13845 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13846 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13847 // which record usages which are modifications as side effect, and then
13848 // downgrade them (or more accurately restore the previous usage which was a
13849 // modification as side effect) when exiting the scope of the sequenced
13850 // subexpression.
13851
13852 void notePreUse(Object O, const Expr *UseExpr) {
13853 UsageInfo &UI = UsageMap[O];
13854 // Uses conflict with other modifications.
13855 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13856 }
13857
13858 void notePostUse(Object O, const Expr *UseExpr) {
13859 UsageInfo &UI = UsageMap[O];
13860 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13861 /*IsModMod=*/false);
13862 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13863 }
13864
13865 void notePreMod(Object O, const Expr *ModExpr) {
13866 UsageInfo &UI = UsageMap[O];
13867 // Modifications conflict with other modifications and with uses.
13868 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13869 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13870 }
13871
13872 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13873 UsageInfo &UI = UsageMap[O];
13874 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13875 /*IsModMod=*/true);
13876 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13877 }
13878
13879public:
13880 SequenceChecker(Sema &S, const Expr *E,
13881 SmallVectorImpl<const Expr *> &WorkList)
13882 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13883 Visit(E);
13884 // Silence a -Wunused-private-field since WorkList is now unused.
13885 // TODO: Evaluate if it can be used, and if not remove it.
13886 (void)this->WorkList;
13887 }
13888
13889 void VisitStmt(const Stmt *S) {
13890 // Skip all statements which aren't expressions for now.
13891 }
13892
13893 void VisitExpr(const Expr *E) {
13894 // By default, just recurse to evaluated subexpressions.
13895 Base::VisitStmt(E);
13896 }
13897
13898 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
13899 for (auto *Sub : CSE->children()) {
13900 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
13901 if (!ChildExpr)
13902 continue;
13903
13904 if (ChildExpr == CSE->getOperand())
13905 // Do not recurse over a CoroutineSuspendExpr's operand.
13906 // The operand is also a subexpression of getCommonExpr(), and
13907 // recursing into it directly could confuse object management
13908 // for the sake of sequence tracking.
13909 continue;
13910
13911 Visit(Sub);
13912 }
13913 }
13914
13915 void VisitCastExpr(const CastExpr *E) {
13916 Object O = Object();
13917 if (E->getCastKind() == CK_LValueToRValue)
13918 O = getObject(E->getSubExpr(), false);
13919
13920 if (O)
13921 notePreUse(O, E);
13922 VisitExpr(E);
13923 if (O)
13924 notePostUse(O, E);
13925 }
13926
13927 void VisitSequencedExpressions(const Expr *SequencedBefore,
13928 const Expr *SequencedAfter) {
13929 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13930 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13931 SequenceTree::Seq OldRegion = Region;
13932
13933 {
13934 SequencedSubexpression SeqBefore(*this);
13935 Region = BeforeRegion;
13936 Visit(SequencedBefore);
13937 }
13938
13939 Region = AfterRegion;
13940 Visit(SequencedAfter);
13941
13942 Region = OldRegion;
13943
13944 Tree.merge(BeforeRegion);
13945 Tree.merge(AfterRegion);
13946 }
13947
13948 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13949 // C++17 [expr.sub]p1:
13950 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13951 // expression E1 is sequenced before the expression E2.
13952 if (SemaRef.getLangOpts().CPlusPlus17)
13953 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13954 else {
13955 Visit(ASE->getLHS());
13956 Visit(ASE->getRHS());
13957 }
13958 }
13959
13960 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13961 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13962 void VisitBinPtrMem(const BinaryOperator *BO) {
13963 // C++17 [expr.mptr.oper]p4:
13964 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13965 // the expression E1 is sequenced before the expression E2.
13966 if (SemaRef.getLangOpts().CPlusPlus17)
13967 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13968 else {
13969 Visit(BO->getLHS());
13970 Visit(BO->getRHS());
13971 }
13972 }
13973
13974 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13975 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13976 void VisitBinShlShr(const BinaryOperator *BO) {
13977 // C++17 [expr.shift]p4:
13978 // The expression E1 is sequenced before the expression E2.
13979 if (SemaRef.getLangOpts().CPlusPlus17)
13980 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13981 else {
13982 Visit(BO->getLHS());
13983 Visit(BO->getRHS());
13984 }
13985 }
13986
13987 void VisitBinComma(const BinaryOperator *BO) {
13988 // C++11 [expr.comma]p1:
13989 // Every value computation and side effect associated with the left
13990 // expression is sequenced before every value computation and side
13991 // effect associated with the right expression.
13992 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13993 }
13994
13995 void VisitBinAssign(const BinaryOperator *BO) {
13996 SequenceTree::Seq RHSRegion;
13997 SequenceTree::Seq LHSRegion;
13998 if (SemaRef.getLangOpts().CPlusPlus17) {
13999 RHSRegion = Tree.allocate(Region);
14000 LHSRegion = Tree.allocate(Region);
14001 } else {
14002 RHSRegion = Region;
14003 LHSRegion = Region;
14004 }
14005 SequenceTree::Seq OldRegion = Region;
14006
14007 // C++11 [expr.ass]p1:
14008 // [...] the assignment is sequenced after the value computation
14009 // of the right and left operands, [...]
14010 //
14011 // so check it before inspecting the operands and update the
14012 // map afterwards.
14013 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14014 if (O)
14015 notePreMod(O, BO);
14016
14017 if (SemaRef.getLangOpts().CPlusPlus17) {
14018 // C++17 [expr.ass]p1:
14019 // [...] The right operand is sequenced before the left operand. [...]
14020 {
14021 SequencedSubexpression SeqBefore(*this);
14022 Region = RHSRegion;
14023 Visit(BO->getRHS());
14024 }
14025
14026 Region = LHSRegion;
14027 Visit(BO->getLHS());
14028
14029 if (O && isa<CompoundAssignOperator>(BO))
14030 notePostUse(O, BO);
14031
14032 } else {
14033 // C++11 does not specify any sequencing between the LHS and RHS.
14034 Region = LHSRegion;
14035 Visit(BO->getLHS());
14036
14037 if (O && isa<CompoundAssignOperator>(BO))
14038 notePostUse(O, BO);
14039
14040 Region = RHSRegion;
14041 Visit(BO->getRHS());
14042 }
14043
14044 // C++11 [expr.ass]p1:
14045 // the assignment is sequenced [...] before the value computation of the
14046 // assignment expression.
14047 // C11 6.5.16/3 has no such rule.
14048 Region = OldRegion;
14049 if (O)
14050 notePostMod(O, BO,
14051 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14052 : UK_ModAsSideEffect);
14053 if (SemaRef.getLangOpts().CPlusPlus17) {
14054 Tree.merge(RHSRegion);
14055 Tree.merge(LHSRegion);
14056 }
14057 }
14058
14059 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14060 VisitBinAssign(CAO);
14061 }
14062
14063 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14064 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14065 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14066 Object O = getObject(UO->getSubExpr(), true);
14067 if (!O)
14068 return VisitExpr(UO);
14069
14070 notePreMod(O, UO);
14071 Visit(UO->getSubExpr());
14072 // C++11 [expr.pre.incr]p1:
14073 // the expression ++x is equivalent to x+=1
14074 notePostMod(O, UO,
14075 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14076 : UK_ModAsSideEffect);
14077 }
14078
14079 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14080 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14081 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14082 Object O = getObject(UO->getSubExpr(), true);
14083 if (!O)
14084 return VisitExpr(UO);
14085
14086 notePreMod(O, UO);
14087 Visit(UO->getSubExpr());
14088 notePostMod(O, UO, UK_ModAsSideEffect);
14089 }
14090
14091 void VisitBinLOr(const BinaryOperator *BO) {
14092 // C++11 [expr.log.or]p2:
14093 // If the second expression is evaluated, every value computation and
14094 // side effect associated with the first expression is sequenced before
14095 // every value computation and side effect associated with the
14096 // second expression.
14097 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14098 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14099 SequenceTree::Seq OldRegion = Region;
14100
14101 EvaluationTracker Eval(*this);
14102 {
14103 SequencedSubexpression Sequenced(*this);
14104 Region = LHSRegion;
14105 Visit(BO->getLHS());
14106 }
14107
14108 // C++11 [expr.log.or]p1:
14109 // [...] the second operand is not evaluated if the first operand
14110 // evaluates to true.
14111 bool EvalResult = false;
14112 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14113 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14114 if (ShouldVisitRHS) {
14115 Region = RHSRegion;
14116 Visit(BO->getRHS());
14117 }
14118
14119 Region = OldRegion;
14120 Tree.merge(LHSRegion);
14121 Tree.merge(RHSRegion);
14122 }
14123
14124 void VisitBinLAnd(const BinaryOperator *BO) {
14125 // C++11 [expr.log.and]p2:
14126 // If the second expression is evaluated, every value computation and
14127 // side effect associated with the first expression is sequenced before
14128 // every value computation and side effect associated with the
14129 // second expression.
14130 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14131 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14132 SequenceTree::Seq OldRegion = Region;
14133
14134 EvaluationTracker Eval(*this);
14135 {
14136 SequencedSubexpression Sequenced(*this);
14137 Region = LHSRegion;
14138 Visit(BO->getLHS());
14139 }
14140
14141 // C++11 [expr.log.and]p1:
14142 // [...] the second operand is not evaluated if the first operand is false.
14143 bool EvalResult = false;
14144 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14145 bool ShouldVisitRHS = !EvalOK || EvalResult;
14146 if (ShouldVisitRHS) {
14147 Region = RHSRegion;
14148 Visit(BO->getRHS());
14149 }
14150
14151 Region = OldRegion;
14152 Tree.merge(LHSRegion);
14153 Tree.merge(RHSRegion);
14154 }
14155
14156 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14157 // C++11 [expr.cond]p1:
14158 // [...] Every value computation and side effect associated with the first
14159 // expression is sequenced before every value computation and side effect
14160 // associated with the second or third expression.
14161 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14162
14163 // No sequencing is specified between the true and false expression.
14164 // However since exactly one of both is going to be evaluated we can
14165 // consider them to be sequenced. This is needed to avoid warning on
14166 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14167 // both the true and false expressions because we can't evaluate x.
14168 // This will still allow us to detect an expression like (pre C++17)
14169 // "(x ? y += 1 : y += 2) = y".
14170 //
14171 // We don't wrap the visitation of the true and false expression with
14172 // SequencedSubexpression because we don't want to downgrade modifications
14173 // as side effect in the true and false expressions after the visition
14174 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14175 // not warn between the two "y++", but we should warn between the "y++"
14176 // and the "y".
14177 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14178 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14179 SequenceTree::Seq OldRegion = Region;
14180
14181 EvaluationTracker Eval(*this);
14182 {
14183 SequencedSubexpression Sequenced(*this);
14184 Region = ConditionRegion;
14185 Visit(CO->getCond());
14186 }
14187
14188 // C++11 [expr.cond]p1:
14189 // [...] The first expression is contextually converted to bool (Clause 4).
14190 // It is evaluated and if it is true, the result of the conditional
14191 // expression is the value of the second expression, otherwise that of the
14192 // third expression. Only one of the second and third expressions is
14193 // evaluated. [...]
14194 bool EvalResult = false;
14195 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14196 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14197 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14198 if (ShouldVisitTrueExpr) {
14199 Region = TrueRegion;
14200 Visit(CO->getTrueExpr());
14201 }
14202 if (ShouldVisitFalseExpr) {
14203 Region = FalseRegion;
14204 Visit(CO->getFalseExpr());
14205 }
14206
14207 Region = OldRegion;
14208 Tree.merge(ConditionRegion);
14209 Tree.merge(TrueRegion);
14210 Tree.merge(FalseRegion);
14211 }
14212
14213 void VisitCallExpr(const CallExpr *CE) {
14214 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14215
14216 if (CE->isUnevaluatedBuiltinCall(Context))
14217 return;
14218
14219 // C++11 [intro.execution]p15:
14220 // When calling a function [...], every value computation and side effect
14221 // associated with any argument expression, or with the postfix expression
14222 // designating the called function, is sequenced before execution of every
14223 // expression or statement in the body of the function [and thus before
14224 // the value computation of its result].
14225 SequencedSubexpression Sequenced(*this);
14226 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14227 // C++17 [expr.call]p5
14228 // The postfix-expression is sequenced before each expression in the
14229 // expression-list and any default argument. [...]
14230 SequenceTree::Seq CalleeRegion;
14231 SequenceTree::Seq OtherRegion;
14232 if (SemaRef.getLangOpts().CPlusPlus17) {
14233 CalleeRegion = Tree.allocate(Region);
14234 OtherRegion = Tree.allocate(Region);
14235 } else {
14236 CalleeRegion = Region;
14237 OtherRegion = Region;
14238 }
14239 SequenceTree::Seq OldRegion = Region;
14240
14241 // Visit the callee expression first.
14242 Region = CalleeRegion;
14243 if (SemaRef.getLangOpts().CPlusPlus17) {
14244 SequencedSubexpression Sequenced(*this);
14245 Visit(CE->getCallee());
14246 } else {
14247 Visit(CE->getCallee());
14248 }
14249
14250 // Then visit the argument expressions.
14251 Region = OtherRegion;
14252 for (const Expr *Argument : CE->arguments())
14253 Visit(Argument);
14254
14255 Region = OldRegion;
14256 if (SemaRef.getLangOpts().CPlusPlus17) {
14257 Tree.merge(CalleeRegion);
14258 Tree.merge(OtherRegion);
14259 }
14260 });
14261 }
14262
14263 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14264 // C++17 [over.match.oper]p2:
14265 // [...] the operator notation is first transformed to the equivalent
14266 // function-call notation as summarized in Table 12 (where @ denotes one
14267 // of the operators covered in the specified subclause). However, the
14268 // operands are sequenced in the order prescribed for the built-in
14269 // operator (Clause 8).
14270 //
14271 // From the above only overloaded binary operators and overloaded call
14272 // operators have sequencing rules in C++17 that we need to handle
14273 // separately.
14274 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14275 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14276 return VisitCallExpr(CXXOCE);
14277
14278 enum {
14279 NoSequencing,
14280 LHSBeforeRHS,
14281 RHSBeforeLHS,
14282 LHSBeforeRest
14283 } SequencingKind;
14284 switch (CXXOCE->getOperator()) {
14285 case OO_Equal:
14286 case OO_PlusEqual:
14287 case OO_MinusEqual:
14288 case OO_StarEqual:
14289 case OO_SlashEqual:
14290 case OO_PercentEqual:
14291 case OO_CaretEqual:
14292 case OO_AmpEqual:
14293 case OO_PipeEqual:
14294 case OO_LessLessEqual:
14295 case OO_GreaterGreaterEqual:
14296 SequencingKind = RHSBeforeLHS;
14297 break;
14298
14299 case OO_LessLess:
14300 case OO_GreaterGreater:
14301 case OO_AmpAmp:
14302 case OO_PipePipe:
14303 case OO_Comma:
14304 case OO_ArrowStar:
14305 case OO_Subscript:
14306 SequencingKind = LHSBeforeRHS;
14307 break;
14308
14309 case OO_Call:
14310 SequencingKind = LHSBeforeRest;
14311 break;
14312
14313 default:
14314 SequencingKind = NoSequencing;
14315 break;
14316 }
14317
14318 if (SequencingKind == NoSequencing)
14319 return VisitCallExpr(CXXOCE);
14320
14321 // This is a call, so all subexpressions are sequenced before the result.
14322 SequencedSubexpression Sequenced(*this);
14323
14324 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14325 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14326 "Should only get there with C++17 and above!");
14327 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14328 "Should only get there with an overloaded binary operator"
14329 " or an overloaded call operator!");
14330
14331 if (SequencingKind == LHSBeforeRest) {
14332 assert(CXXOCE->getOperator() == OO_Call &&
14333 "We should only have an overloaded call operator here!");
14334
14335 // This is very similar to VisitCallExpr, except that we only have the
14336 // C++17 case. The postfix-expression is the first argument of the
14337 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14338 // are in the following arguments.
14339 //
14340 // Note that we intentionally do not visit the callee expression since
14341 // it is just a decayed reference to a function.
14342 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14343 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14344 SequenceTree::Seq OldRegion = Region;
14345
14346 assert(CXXOCE->getNumArgs() >= 1 &&
14347 "An overloaded call operator must have at least one argument"
14348 " for the postfix-expression!");
14349 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14350 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14351 CXXOCE->getNumArgs() - 1);
14352
14353 // Visit the postfix-expression first.
14354 {
14355 Region = PostfixExprRegion;
14356 SequencedSubexpression Sequenced(*this);
14357 Visit(PostfixExpr);
14358 }
14359
14360 // Then visit the argument expressions.
14361 Region = ArgsRegion;
14362 for (const Expr *Arg : Args)
14363 Visit(Arg);
14364
14365 Region = OldRegion;
14366 Tree.merge(PostfixExprRegion);
14367 Tree.merge(ArgsRegion);
14368 } else {
14369 assert(CXXOCE->getNumArgs() == 2 &&
14370 "Should only have two arguments here!");
14371 assert((SequencingKind == LHSBeforeRHS ||
14372 SequencingKind == RHSBeforeLHS) &&
14373 "Unexpected sequencing kind!");
14374
14375 // We do not visit the callee expression since it is just a decayed
14376 // reference to a function.
14377 const Expr *E1 = CXXOCE->getArg(0);
14378 const Expr *E2 = CXXOCE->getArg(1);
14379 if (SequencingKind == RHSBeforeLHS)
14380 std::swap(E1, E2);
14381
14382 return VisitSequencedExpressions(E1, E2);
14383 }
14384 });
14385 }
14386
14387 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14388 // This is a call, so all subexpressions are sequenced before the result.
14389 SequencedSubexpression Sequenced(*this);
14390
14391 if (!CCE->isListInitialization())
14392 return VisitExpr(CCE);
14393
14394 // In C++11, list initializations are sequenced.
14395 SequenceExpressionsInOrder(
14396 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14397 }
14398
14399 void VisitInitListExpr(const InitListExpr *ILE) {
14400 if (!SemaRef.getLangOpts().CPlusPlus11)
14401 return VisitExpr(ILE);
14402
14403 // In C++11, list initializations are sequenced.
14404 SequenceExpressionsInOrder(ILE->inits());
14405 }
14406
14407 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14408 // C++20 parenthesized list initializations are sequenced. See C++20
14409 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14410 SequenceExpressionsInOrder(PLIE->getInitExprs());
14411 }
14412
14413private:
14414 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14416 SequenceTree::Seq Parent = Region;
14417 for (const Expr *E : ExpressionList) {
14418 if (!E)
14419 continue;
14420 Region = Tree.allocate(Parent);
14421 Elts.push_back(Region);
14422 Visit(E);
14423 }
14424
14425 // Forget that the initializers are sequenced.
14426 Region = Parent;
14427 for (unsigned I = 0; I < Elts.size(); ++I)
14428 Tree.merge(Elts[I]);
14429 }
14430};
14431
14432SequenceChecker::UsageInfo::UsageInfo() = default;
14433
14434} // namespace
14435
14436void Sema::CheckUnsequencedOperations(const Expr *E) {
14437 SmallVector<const Expr *, 8> WorkList;
14438 WorkList.push_back(E);
14439 while (!WorkList.empty()) {
14440 const Expr *Item = WorkList.pop_back_val();
14441 SequenceChecker(*this, Item, WorkList);
14442 }
14443}
14444
14445void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14446 bool IsConstexpr) {
14447 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14448 IsConstexpr || isa<ConstantExpr>(E));
14449 CheckImplicitConversions(E, CheckLoc);
14450 if (!E->isInstantiationDependent())
14451 CheckUnsequencedOperations(E);
14452 if (!IsConstexpr && !E->isValueDependent())
14453 CheckForIntOverflow(E);
14454}
14455
14456void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14457 FieldDecl *BitField,
14458 Expr *Init) {
14459 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14460}
14461
14463 SourceLocation Loc) {
14464 if (!PType->isVariablyModifiedType())
14465 return;
14466 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14467 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14468 return;
14469 }
14470 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14471 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14472 return;
14473 }
14474 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14475 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14476 return;
14477 }
14478
14479 const ArrayType *AT = S.Context.getAsArrayType(PType);
14480 if (!AT)
14481 return;
14482
14485 return;
14486 }
14487
14488 S.Diag(Loc, diag::err_array_star_in_function_definition);
14489}
14490
14492 bool CheckParameterNames) {
14493 bool HasInvalidParm = false;
14494 for (ParmVarDecl *Param : Parameters) {
14495 assert(Param && "null in a parameter list");
14496 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14497 // function declarator that is part of a function definition of
14498 // that function shall not have incomplete type.
14499 //
14500 // C++23 [dcl.fct.def.general]/p2
14501 // The type of a parameter [...] for a function definition
14502 // shall not be a (possibly cv-qualified) class type that is incomplete
14503 // or abstract within the function body unless the function is deleted.
14504 if (!Param->isInvalidDecl() &&
14505 (RequireCompleteType(Param->getLocation(), Param->getType(),
14506 diag::err_typecheck_decl_incomplete_type) ||
14507 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14508 diag::err_abstract_type_in_decl,
14510 Param->setInvalidDecl();
14511 HasInvalidParm = true;
14512 }
14513
14514 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14515 // declaration of each parameter shall include an identifier.
14516 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14517 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14518 // Diagnose this as an extension in C17 and earlier.
14519 if (!getLangOpts().C23)
14520 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14521 }
14522
14523 // C99 6.7.5.3p12:
14524 // If the function declarator is not part of a definition of that
14525 // function, parameters may have incomplete type and may use the [*]
14526 // notation in their sequences of declarator specifiers to specify
14527 // variable length array types.
14528 QualType PType = Param->getOriginalType();
14529 // FIXME: This diagnostic should point the '[*]' if source-location
14530 // information is added for it.
14531 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14532
14533 // If the parameter is a c++ class type and it has to be destructed in the
14534 // callee function, declare the destructor so that it can be called by the
14535 // callee function. Do not perform any direct access check on the dtor here.
14536 if (!Param->isInvalidDecl()) {
14537 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14538 if (!ClassDecl->isInvalidDecl() &&
14539 !ClassDecl->hasIrrelevantDestructor() &&
14540 !ClassDecl->isDependentContext() &&
14541 ClassDecl->isParamDestroyedInCallee()) {
14543 MarkFunctionReferenced(Param->getLocation(), Destructor);
14544 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14545 }
14546 }
14547 }
14548
14549 // Parameters with the pass_object_size attribute only need to be marked
14550 // constant at function definitions. Because we lack information about
14551 // whether we're on a declaration or definition when we're instantiating the
14552 // attribute, we need to check for constness here.
14553 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14554 if (!Param->getType().isConstQualified())
14555 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14556 << Attr->getSpelling() << 1;
14557
14558 // Check for parameter names shadowing fields from the class.
14559 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14560 // The owning context for the parameter should be the function, but we
14561 // want to see if this function's declaration context is a record.
14562 DeclContext *DC = Param->getDeclContext();
14563 if (DC && DC->isFunctionOrMethod()) {
14564 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14565 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14566 RD, /*DeclIsField*/ false);
14567 }
14568 }
14569
14570 if (!Param->isInvalidDecl() &&
14571 Param->getOriginalType()->isWebAssemblyTableType()) {
14572 Param->setInvalidDecl();
14573 HasInvalidParm = true;
14574 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14575 }
14576 }
14577
14578 return HasInvalidParm;
14579}
14580
14581std::optional<std::pair<
14583 *E,
14585 &Ctx);
14586
14587/// Compute the alignment and offset of the base class object given the
14588/// derived-to-base cast expression and the alignment and offset of the derived
14589/// class object.
14590static std::pair<CharUnits, CharUnits>
14592 CharUnits BaseAlignment, CharUnits Offset,
14593 ASTContext &Ctx) {
14594 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14595 ++PathI) {
14596 const CXXBaseSpecifier *Base = *PathI;
14597 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14598 if (Base->isVirtual()) {
14599 // The complete object may have a lower alignment than the non-virtual
14600 // alignment of the base, in which case the base may be misaligned. Choose
14601 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14602 // conservative lower bound of the complete object alignment.
14603 CharUnits NonVirtualAlignment =
14605 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14606 Offset = CharUnits::Zero();
14607 } else {
14608 const ASTRecordLayout &RL =
14609 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14610 Offset += RL.getBaseClassOffset(BaseDecl);
14611 }
14612 DerivedType = Base->getType();
14613 }
14614
14615 return std::make_pair(BaseAlignment, Offset);
14616}
14617
14618/// Compute the alignment and offset of a binary additive operator.
14619static std::optional<std::pair<CharUnits, CharUnits>>
14621 bool IsSub, ASTContext &Ctx) {
14622 QualType PointeeType = PtrE->getType()->getPointeeType();
14623
14624 if (!PointeeType->isConstantSizeType())
14625 return std::nullopt;
14626
14627 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14628
14629 if (!P)
14630 return std::nullopt;
14631
14632 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14633 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14634 CharUnits Offset = EltSize * IdxRes->getExtValue();
14635 if (IsSub)
14636 Offset = -Offset;
14637 return std::make_pair(P->first, P->second + Offset);
14638 }
14639
14640 // If the integer expression isn't a constant expression, compute the lower
14641 // bound of the alignment using the alignment and offset of the pointer
14642 // expression and the element size.
14643 return std::make_pair(
14644 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14645 CharUnits::Zero());
14646}
14647
14648/// This helper function takes an lvalue expression and returns the alignment of
14649/// a VarDecl and a constant offset from the VarDecl.
14650std::optional<std::pair<
14651 CharUnits,
14653 ASTContext &Ctx) {
14654 E = E->IgnoreParens();
14655 switch (E->getStmtClass()) {
14656 default:
14657 break;
14658 case Stmt::CStyleCastExprClass:
14659 case Stmt::CXXStaticCastExprClass:
14660 case Stmt::ImplicitCastExprClass: {
14661 auto *CE = cast<CastExpr>(E);
14662 const Expr *From = CE->getSubExpr();
14663 switch (CE->getCastKind()) {
14664 default:
14665 break;
14666 case CK_NoOp:
14667 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14668 case CK_UncheckedDerivedToBase:
14669 case CK_DerivedToBase: {
14670 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14671 if (!P)
14672 break;
14673 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14674 P->second, Ctx);
14675 }
14676 }
14677 break;
14678 }
14679 case Stmt::ArraySubscriptExprClass: {
14680 auto *ASE = cast<ArraySubscriptExpr>(E);
14682 false, Ctx);
14683 }
14684 case Stmt::DeclRefExprClass: {
14685 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14686 // FIXME: If VD is captured by copy or is an escaping __block variable,
14687 // use the alignment of VD's type.
14688 if (!VD->getType()->isReferenceType()) {
14689 // Dependent alignment cannot be resolved -> bail out.
14690 if (VD->hasDependentAlignment())
14691 break;
14692 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14693 }
14694 if (VD->hasInit())
14695 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14696 }
14697 break;
14698 }
14699 case Stmt::MemberExprClass: {
14700 auto *ME = cast<MemberExpr>(E);
14701 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14702 if (!FD || FD->getType()->isReferenceType() ||
14703 FD->getParent()->isInvalidDecl())
14704 break;
14705 std::optional<std::pair<CharUnits, CharUnits>> P;
14706 if (ME->isArrow())
14707 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14708 else
14709 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14710 if (!P)
14711 break;
14712 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14713 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14714 return std::make_pair(P->first,
14715 P->second + CharUnits::fromQuantity(Offset));
14716 }
14717 case Stmt::UnaryOperatorClass: {
14718 auto *UO = cast<UnaryOperator>(E);
14719 switch (UO->getOpcode()) {
14720 default:
14721 break;
14722 case UO_Deref:
14724 }
14725 break;
14726 }
14727 case Stmt::BinaryOperatorClass: {
14728 auto *BO = cast<BinaryOperator>(E);
14729 auto Opcode = BO->getOpcode();
14730 switch (Opcode) {
14731 default:
14732 break;
14733 case BO_Comma:
14735 }
14736 break;
14737 }
14738 }
14739 return std::nullopt;
14740}
14741
14742/// This helper function takes a pointer expression and returns the alignment of
14743/// a VarDecl and a constant offset from the VarDecl.
14744std::optional<std::pair<
14746 *E,
14748 &Ctx) {
14749 E = E->IgnoreParens();
14750 switch (E->getStmtClass()) {
14751 default:
14752 break;
14753 case Stmt::CStyleCastExprClass:
14754 case Stmt::CXXStaticCastExprClass:
14755 case Stmt::ImplicitCastExprClass: {
14756 auto *CE = cast<CastExpr>(E);
14757 const Expr *From = CE->getSubExpr();
14758 switch (CE->getCastKind()) {
14759 default:
14760 break;
14761 case CK_NoOp:
14762 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14763 case CK_ArrayToPointerDecay:
14764 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14765 case CK_UncheckedDerivedToBase:
14766 case CK_DerivedToBase: {
14767 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14768 if (!P)
14769 break;
14771 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14772 }
14773 }
14774 break;
14775 }
14776 case Stmt::CXXThisExprClass: {
14777 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14779 return std::make_pair(Alignment, CharUnits::Zero());
14780 }
14781 case Stmt::UnaryOperatorClass: {
14782 auto *UO = cast<UnaryOperator>(E);
14783 if (UO->getOpcode() == UO_AddrOf)
14785 break;
14786 }
14787 case Stmt::BinaryOperatorClass: {
14788 auto *BO = cast<BinaryOperator>(E);
14789 auto Opcode = BO->getOpcode();
14790 switch (Opcode) {
14791 default:
14792 break;
14793 case BO_Add:
14794 case BO_Sub: {
14795 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14796 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14797 std::swap(LHS, RHS);
14798 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14799 Ctx);
14800 }
14801 case BO_Comma:
14802 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14803 }
14804 break;
14805 }
14806 }
14807 return std::nullopt;
14808}
14809
14811 // See if we can compute the alignment of a VarDecl and an offset from it.
14812 std::optional<std::pair<CharUnits, CharUnits>> P =
14814
14815 if (P)
14816 return P->first.alignmentAtOffset(P->second);
14817
14818 // If that failed, return the type's alignment.
14820}
14821
14823 // This is actually a lot of work to potentially be doing on every
14824 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14825 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14826 return;
14827
14828 // Ignore dependent types.
14829 if (T->isDependentType() || Op->getType()->isDependentType())
14830 return;
14831
14832 // Require that the destination be a pointer type.
14833 const PointerType *DestPtr = T->getAs<PointerType>();
14834 if (!DestPtr) return;
14835
14836 // If the destination has alignment 1, we're done.
14837 QualType DestPointee = DestPtr->getPointeeType();
14838 if (DestPointee->isIncompleteType()) return;
14839 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14840 if (DestAlign.isOne()) return;
14841
14842 // Require that the source be a pointer type.
14843 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14844 if (!SrcPtr) return;
14845 QualType SrcPointee = SrcPtr->getPointeeType();
14846
14847 // Explicitly allow casts from cv void*. We already implicitly
14848 // allowed casts to cv void*, since they have alignment 1.
14849 // Also allow casts involving incomplete types, which implicitly
14850 // includes 'void'.
14851 if (SrcPointee->isIncompleteType()) return;
14852
14853 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14854
14855 if (SrcAlign >= DestAlign) return;
14856
14857 Diag(TRange.getBegin(), diag::warn_cast_align)
14858 << Op->getType() << T
14859 << static_cast<unsigned>(SrcAlign.getQuantity())
14860 << static_cast<unsigned>(DestAlign.getQuantity())
14861 << TRange << Op->getSourceRange();
14862}
14863
14864void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14865 const ArraySubscriptExpr *ASE,
14866 bool AllowOnePastEnd, bool IndexNegated) {
14867 // Already diagnosed by the constant evaluator.
14869 return;
14870
14871 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14872 if (IndexExpr->isValueDependent())
14873 return;
14874
14875 const Type *EffectiveType =
14877 BaseExpr = BaseExpr->IgnoreParenCasts();
14878 const ConstantArrayType *ArrayTy =
14879 Context.getAsConstantArrayType(BaseExpr->getType());
14880
14882 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
14883
14884 const Type *BaseType =
14885 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14886 bool IsUnboundedArray =
14887 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
14888 Context, StrictFlexArraysLevel,
14889 /*IgnoreTemplateOrMacroSubstitution=*/true);
14890 if (EffectiveType->isDependentType() ||
14891 (!IsUnboundedArray && BaseType->isDependentType()))
14892 return;
14893
14895 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14896 return;
14897
14898 llvm::APSInt index = Result.Val.getInt();
14899 if (IndexNegated) {
14900 index.setIsUnsigned(false);
14901 index = -index;
14902 }
14903
14904 if (IsUnboundedArray) {
14905 if (EffectiveType->isFunctionType())
14906 return;
14907 if (index.isUnsigned() || !index.isNegative()) {
14908 const auto &ASTC = getASTContext();
14909 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
14910 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
14911 if (index.getBitWidth() < AddrBits)
14912 index = index.zext(AddrBits);
14913 std::optional<CharUnits> ElemCharUnits =
14914 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14915 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14916 // pointer) bounds-checking isn't meaningful.
14917 if (!ElemCharUnits || ElemCharUnits->isZero())
14918 return;
14919 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14920 // If index has more active bits than address space, we already know
14921 // we have a bounds violation to warn about. Otherwise, compute
14922 // address of (index + 1)th element, and warn about bounds violation
14923 // only if that address exceeds address space.
14924 if (index.getActiveBits() <= AddrBits) {
14925 bool Overflow;
14926 llvm::APInt Product(index);
14927 Product += 1;
14928 Product = Product.umul_ov(ElemBytes, Overflow);
14929 if (!Overflow && Product.getActiveBits() <= AddrBits)
14930 return;
14931 }
14932
14933 // Need to compute max possible elements in address space, since that
14934 // is included in diag message.
14935 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14936 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14937 MaxElems += 1;
14938 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14939 MaxElems = MaxElems.udiv(ElemBytes);
14940
14941 unsigned DiagID =
14942 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14943 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14944
14945 // Diag message shows element size in bits and in "bytes" (platform-
14946 // dependent CharUnits)
14947 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14948 PDiag(DiagID) << index << AddrBits
14949 << (unsigned)ASTC.toBits(*ElemCharUnits)
14950 << ElemBytes << MaxElems
14951 << MaxElems.getZExtValue()
14952 << IndexExpr->getSourceRange());
14953
14954 const NamedDecl *ND = nullptr;
14955 // Try harder to find a NamedDecl to point at in the note.
14956 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14957 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14958 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14959 ND = DRE->getDecl();
14960 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14961 ND = ME->getMemberDecl();
14962
14963 if (ND)
14964 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14965 PDiag(diag::note_array_declared_here) << ND);
14966 }
14967 return;
14968 }
14969
14970 if (index.isUnsigned() || !index.isNegative()) {
14971 // It is possible that the type of the base expression after
14972 // IgnoreParenCasts is incomplete, even though the type of the base
14973 // expression before IgnoreParenCasts is complete (see PR39746 for an
14974 // example). In this case we have no information about whether the array
14975 // access exceeds the array bounds. However we can still diagnose an array
14976 // access which precedes the array bounds.
14977 if (BaseType->isIncompleteType())
14978 return;
14979
14980 llvm::APInt size = ArrayTy->getSize();
14981
14982 if (BaseType != EffectiveType) {
14983 // Make sure we're comparing apples to apples when comparing index to
14984 // size.
14985 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14986 uint64_t array_typesize = Context.getTypeSize(BaseType);
14987
14988 // Handle ptrarith_typesize being zero, such as when casting to void*.
14989 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
14990 if (!ptrarith_typesize)
14991 ptrarith_typesize = Context.getCharWidth();
14992
14993 if (ptrarith_typesize != array_typesize) {
14994 // There's a cast to a different size type involved.
14995 uint64_t ratio = array_typesize / ptrarith_typesize;
14996
14997 // TODO: Be smarter about handling cases where array_typesize is not a
14998 // multiple of ptrarith_typesize.
14999 if (ptrarith_typesize * ratio == array_typesize)
15000 size *= llvm::APInt(size.getBitWidth(), ratio);
15001 }
15002 }
15003
15004 if (size.getBitWidth() > index.getBitWidth())
15005 index = index.zext(size.getBitWidth());
15006 else if (size.getBitWidth() < index.getBitWidth())
15007 size = size.zext(index.getBitWidth());
15008
15009 // For array subscripting the index must be less than size, but for pointer
15010 // arithmetic also allow the index (offset) to be equal to size since
15011 // computing the next address after the end of the array is legal and
15012 // commonly done e.g. in C++ iterators and range-based for loops.
15013 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15014 return;
15015
15016 // Suppress the warning if the subscript expression (as identified by the
15017 // ']' location) and the index expression are both from macro expansions
15018 // within a system header.
15019 if (ASE) {
15020 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15021 ASE->getRBracketLoc());
15022 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15023 SourceLocation IndexLoc =
15024 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15025 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15026 return;
15027 }
15028 }
15029
15030 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15031 : diag::warn_ptr_arith_exceeds_bounds;
15032 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15033 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15034
15035 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15036 PDiag(DiagID)
15037 << index << ArrayTy->desugar() << CastMsg
15038 << CastMsgTy << IndexExpr->getSourceRange());
15039 } else {
15040 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15041 if (!ASE) {
15042 DiagID = diag::warn_ptr_arith_precedes_bounds;
15043 if (index.isNegative()) index = -index;
15044 }
15045
15046 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15047 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15048 }
15049
15050 const NamedDecl *ND = nullptr;
15051 // Try harder to find a NamedDecl to point at in the note.
15052 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15053 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15054 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15055 ND = DRE->getDecl();
15056 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15057 ND = ME->getMemberDecl();
15058
15059 if (ND)
15060 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15061 PDiag(diag::note_array_declared_here) << ND);
15062}
15063
15064void Sema::CheckArrayAccess(const Expr *expr) {
15065 int AllowOnePastEnd = 0;
15066 while (expr) {
15067 expr = expr->IgnoreParenImpCasts();
15068 switch (expr->getStmtClass()) {
15069 case Stmt::ArraySubscriptExprClass: {
15070 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15071 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15072 AllowOnePastEnd > 0);
15073 expr = ASE->getBase();
15074 break;
15075 }
15076 case Stmt::MemberExprClass: {
15077 expr = cast<MemberExpr>(expr)->getBase();
15078 break;
15079 }
15080 case Stmt::ArraySectionExprClass: {
15081 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15082 // FIXME: We should probably be checking all of the elements to the
15083 // 'length' here as well.
15084 if (ASE->getLowerBound())
15085 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15086 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15087 return;
15088 }
15089 case Stmt::UnaryOperatorClass: {
15090 // Only unwrap the * and & unary operators
15091 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15092 expr = UO->getSubExpr();
15093 switch (UO->getOpcode()) {
15094 case UO_AddrOf:
15095 AllowOnePastEnd++;
15096 break;
15097 case UO_Deref:
15098 AllowOnePastEnd--;
15099 break;
15100 default:
15101 return;
15102 }
15103 break;
15104 }
15105 case Stmt::ConditionalOperatorClass: {
15106 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15107 if (const Expr *lhs = cond->getLHS())
15108 CheckArrayAccess(lhs);
15109 if (const Expr *rhs = cond->getRHS())
15110 CheckArrayAccess(rhs);
15111 return;
15112 }
15113 case Stmt::CXXOperatorCallExprClass: {
15114 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15115 for (const auto *Arg : OCE->arguments())
15116 CheckArrayAccess(Arg);
15117 return;
15118 }
15119 default:
15120 return;
15121 }
15122 }
15123}
15124
15126 Expr *RHS, bool isProperty) {
15127 // Check if RHS is an Objective-C object literal, which also can get
15128 // immediately zapped in a weak reference. Note that we explicitly
15129 // allow ObjCStringLiterals, since those are designed to never really die.
15130 RHS = RHS->IgnoreParenImpCasts();
15131
15132 // This enum needs to match with the 'select' in
15133 // warn_objc_arc_literal_assign (off-by-1).
15135 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15136 return false;
15137
15138 S.Diag(Loc, diag::warn_arc_literal_assign)
15139 << (unsigned) Kind
15140 << (isProperty ? 0 : 1)
15141 << RHS->getSourceRange();
15142
15143 return true;
15144}
15145
15148 Expr *RHS, bool isProperty) {
15149 // Strip off any implicit cast added to get to the one ARC-specific.
15150 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15151 if (cast->getCastKind() == CK_ARCConsumeObject) {
15152 S.Diag(Loc, diag::warn_arc_retained_assign)
15154 << (isProperty ? 0 : 1)
15155 << RHS->getSourceRange();
15156 return true;
15157 }
15158 RHS = cast->getSubExpr();
15159 }
15160
15161 if (LT == Qualifiers::OCL_Weak &&
15162 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15163 return true;
15164
15165 return false;
15166}
15167
15169 QualType LHS, Expr *RHS) {
15171
15173 return false;
15174
15175 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15176 return true;
15177
15178 return false;
15179}
15180
15182 Expr *LHS, Expr *RHS) {
15183 QualType LHSType;
15184 // PropertyRef on LHS type need be directly obtained from
15185 // its declaration as it has a PseudoType.
15187 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15188 if (PRE && !PRE->isImplicitProperty()) {
15189 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15190 if (PD)
15191 LHSType = PD->getType();
15192 }
15193
15194 if (LHSType.isNull())
15195 LHSType = LHS->getType();
15196
15198
15199 if (LT == Qualifiers::OCL_Weak) {
15200 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15202 }
15203
15204 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15205 return;
15206
15207 // FIXME. Check for other life times.
15208 if (LT != Qualifiers::OCL_None)
15209 return;
15210
15211 if (PRE) {
15212 if (PRE->isImplicitProperty())
15213 return;
15214 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15215 if (!PD)
15216 return;
15217
15218 unsigned Attributes = PD->getPropertyAttributes();
15219 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15220 // when 'assign' attribute was not explicitly specified
15221 // by user, ignore it and rely on property type itself
15222 // for lifetime info.
15223 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15224 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15225 LHSType->isObjCRetainableType())
15226 return;
15227
15228 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15229 if (cast->getCastKind() == CK_ARCConsumeObject) {
15230 Diag(Loc, diag::warn_arc_retained_property_assign)
15231 << RHS->getSourceRange();
15232 return;
15233 }
15234 RHS = cast->getSubExpr();
15235 }
15236 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15237 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15238 return;
15239 }
15240 }
15241}
15242
15243//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15244
15245static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15246 SourceLocation StmtLoc,
15247 const NullStmt *Body) {
15248 // Do not warn if the body is a macro that expands to nothing, e.g:
15249 //
15250 // #define CALL(x)
15251 // if (condition)
15252 // CALL(0);
15253 if (Body->hasLeadingEmptyMacro())
15254 return false;
15255
15256 // Get line numbers of statement and body.
15257 bool StmtLineInvalid;
15258 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15259 &StmtLineInvalid);
15260 if (StmtLineInvalid)
15261 return false;
15262
15263 bool BodyLineInvalid;
15264 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15265 &BodyLineInvalid);
15266 if (BodyLineInvalid)
15267 return false;
15268
15269 // Warn if null statement and body are on the same line.
15270 if (StmtLine != BodyLine)
15271 return false;
15272
15273 return true;
15274}
15275
15277 const Stmt *Body,
15278 unsigned DiagID) {
15279 // Since this is a syntactic check, don't emit diagnostic for template
15280 // instantiations, this just adds noise.
15282 return;
15283
15284 // The body should be a null statement.
15285 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15286 if (!NBody)
15287 return;
15288
15289 // Do the usual checks.
15290 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15291 return;
15292
15293 Diag(NBody->getSemiLoc(), DiagID);
15294 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15295}
15296
15298 const Stmt *PossibleBody) {
15299 assert(!CurrentInstantiationScope); // Ensured by caller
15300
15301 SourceLocation StmtLoc;
15302 const Stmt *Body;
15303 unsigned DiagID;
15304 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15305 StmtLoc = FS->getRParenLoc();
15306 Body = FS->getBody();
15307 DiagID = diag::warn_empty_for_body;
15308 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15309 StmtLoc = WS->getRParenLoc();
15310 Body = WS->getBody();
15311 DiagID = diag::warn_empty_while_body;
15312 } else
15313 return; // Neither `for' nor `while'.
15314
15315 // The body should be a null statement.
15316 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15317 if (!NBody)
15318 return;
15319
15320 // Skip expensive checks if diagnostic is disabled.
15321 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15322 return;
15323
15324 // Do the usual checks.
15325 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15326 return;
15327
15328 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15329 // noise level low, emit diagnostics only if for/while is followed by a
15330 // CompoundStmt, e.g.:
15331 // for (int i = 0; i < n; i++);
15332 // {
15333 // a(i);
15334 // }
15335 // or if for/while is followed by a statement with more indentation
15336 // than for/while itself:
15337 // for (int i = 0; i < n; i++);
15338 // a(i);
15339 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15340 if (!ProbableTypo) {
15341 bool BodyColInvalid;
15342 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15343 PossibleBody->getBeginLoc(), &BodyColInvalid);
15344 if (BodyColInvalid)
15345 return;
15346
15347 bool StmtColInvalid;
15348 unsigned StmtCol =
15349 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15350 if (StmtColInvalid)
15351 return;
15352
15353 if (BodyCol > StmtCol)
15354 ProbableTypo = true;
15355 }
15356
15357 if (ProbableTypo) {
15358 Diag(NBody->getSemiLoc(), DiagID);
15359 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15360 }
15361}
15362
15363//===--- CHECK: Warn on self move with std::move. -------------------------===//
15364
15365void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15366 SourceLocation OpLoc) {
15367 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15368 return;
15369
15371 return;
15372
15373 // Strip parens and casts away.
15374 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15375 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15376
15377 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15378 // which we can treat as an inlined std::move
15379 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15380 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15381 RHSExpr = CE->getArg(0);
15382 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15383 CXXSCE && CXXSCE->isXValue())
15384 RHSExpr = CXXSCE->getSubExpr();
15385 else
15386 return;
15387
15388 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15389 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15390
15391 // Two DeclRefExpr's, check that the decls are the same.
15392 if (LHSDeclRef && RHSDeclRef) {
15393 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15394 return;
15395 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15396 RHSDeclRef->getDecl()->getCanonicalDecl())
15397 return;
15398
15399 auto D = Diag(OpLoc, diag::warn_self_move)
15400 << LHSExpr->getType() << LHSExpr->getSourceRange()
15401 << RHSExpr->getSourceRange();
15402 if (const FieldDecl *F =
15404 D << 1 << F
15405 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15406 else
15407 D << 0;
15408 return;
15409 }
15410
15411 // Member variables require a different approach to check for self moves.
15412 // MemberExpr's are the same if every nested MemberExpr refers to the same
15413 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15414 // the base Expr's are CXXThisExpr's.
15415 const Expr *LHSBase = LHSExpr;
15416 const Expr *RHSBase = RHSExpr;
15417 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15418 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15419 if (!LHSME || !RHSME)
15420 return;
15421
15422 while (LHSME && RHSME) {
15423 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15424 RHSME->getMemberDecl()->getCanonicalDecl())
15425 return;
15426
15427 LHSBase = LHSME->getBase();
15428 RHSBase = RHSME->getBase();
15429 LHSME = dyn_cast<MemberExpr>(LHSBase);
15430 RHSME = dyn_cast<MemberExpr>(RHSBase);
15431 }
15432
15433 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15434 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15435 if (LHSDeclRef && RHSDeclRef) {
15436 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15437 return;
15438 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15439 RHSDeclRef->getDecl()->getCanonicalDecl())
15440 return;
15441
15442 Diag(OpLoc, diag::warn_self_move)
15443 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15444 << RHSExpr->getSourceRange();
15445 return;
15446 }
15447
15448 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15449 Diag(OpLoc, diag::warn_self_move)
15450 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15451 << RHSExpr->getSourceRange();
15452}
15453
15454//===--- Layout compatibility ----------------------------------------------//
15455
15456static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15457
15458/// Check if two enumeration types are layout-compatible.
15459static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15460 const EnumDecl *ED2) {
15461 // C++11 [dcl.enum] p8:
15462 // Two enumeration types are layout-compatible if they have the same
15463 // underlying type.
15464 return ED1->isComplete() && ED2->isComplete() &&
15465 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15466}
15467
15468/// Check if two fields are layout-compatible.
15469/// Can be used on union members, which are exempt from alignment requirement
15470/// of common initial sequence.
15471static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15472 const FieldDecl *Field2,
15473 bool AreUnionMembers = false) {
15474#ifndef NDEBUG
15475 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15476 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15477 assert(((Field1Parent->isStructureOrClassType() &&
15478 Field2Parent->isStructureOrClassType()) ||
15479 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15480 "Can't evaluate layout compatibility between a struct field and a "
15481 "union field.");
15482 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15483 (AreUnionMembers && Field1Parent->isUnionType())) &&
15484 "AreUnionMembers should be 'true' for union fields (only).");
15485#endif
15486
15487 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15488 return false;
15489
15490 if (Field1->isBitField() != Field2->isBitField())
15491 return false;
15492
15493 if (Field1->isBitField()) {
15494 // Make sure that the bit-fields are the same length.
15495 unsigned Bits1 = Field1->getBitWidthValue();
15496 unsigned Bits2 = Field2->getBitWidthValue();
15497
15498 if (Bits1 != Bits2)
15499 return false;
15500 }
15501
15502 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15503 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15504 return false;
15505
15506 if (!AreUnionMembers &&
15507 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15508 return false;
15509
15510 return true;
15511}
15512
15513/// Check if two standard-layout structs are layout-compatible.
15514/// (C++11 [class.mem] p17)
15515static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15516 const RecordDecl *RD2) {
15517 // Get to the class where the fields are declared
15518 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15519 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15520
15521 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15522 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15523
15524 // Check the fields.
15525 return llvm::equal(RD1->fields(), RD2->fields(),
15526 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15527 return isLayoutCompatible(C, F1, F2);
15528 });
15529}
15530
15531/// Check if two standard-layout unions are layout-compatible.
15532/// (C++11 [class.mem] p18)
15533static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15534 const RecordDecl *RD2) {
15535 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15536 RD2->fields());
15537
15538 for (auto *Field1 : RD1->fields()) {
15539 auto I = UnmatchedFields.begin();
15540 auto E = UnmatchedFields.end();
15541
15542 for ( ; I != E; ++I) {
15543 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15544 bool Result = UnmatchedFields.erase(*I);
15545 (void) Result;
15546 assert(Result);
15547 break;
15548 }
15549 }
15550 if (I == E)
15551 return false;
15552 }
15553
15554 return UnmatchedFields.empty();
15555}
15556
15557static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15558 const RecordDecl *RD2) {
15559 if (RD1->isUnion() != RD2->isUnion())
15560 return false;
15561
15562 if (RD1->isUnion())
15563 return isLayoutCompatibleUnion(C, RD1, RD2);
15564 else
15565 return isLayoutCompatibleStruct(C, RD1, RD2);
15566}
15567
15568/// Check if two types are layout-compatible in C++11 sense.
15569static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15570 if (T1.isNull() || T2.isNull())
15571 return false;
15572
15573 // C++20 [basic.types] p11:
15574 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15575 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15576 // or layout-compatible standard-layout class types (11.4).
15579
15580 if (C.hasSameType(T1, T2))
15581 return true;
15582
15583 const Type::TypeClass TC1 = T1->getTypeClass();
15584 const Type::TypeClass TC2 = T2->getTypeClass();
15585
15586 if (TC1 != TC2)
15587 return false;
15588
15589 if (TC1 == Type::Enum)
15590 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15591 if (TC1 == Type::Record) {
15592 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15593 return false;
15594
15596 T2->castAsRecordDecl());
15597 }
15598
15599 return false;
15600}
15601
15603 return isLayoutCompatible(getASTContext(), T1, T2);
15604}
15605
15606//===-------------- Pointer interconvertibility ----------------------------//
15607
15609 const TypeSourceInfo *Derived) {
15610 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15611 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15612
15613 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15614 getASTContext().hasSameType(BaseT, DerivedT))
15615 return true;
15616
15617 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15618 return false;
15619
15620 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15621 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15622 return true;
15623
15624 return false;
15625}
15626
15627//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15628
15629/// Given a type tag expression find the type tag itself.
15630///
15631/// \param TypeExpr Type tag expression, as it appears in user's code.
15632///
15633/// \param VD Declaration of an identifier that appears in a type tag.
15634///
15635/// \param MagicValue Type tag magic value.
15636///
15637/// \param isConstantEvaluated whether the evalaution should be performed in
15638
15639/// constant context.
15640static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15641 const ValueDecl **VD, uint64_t *MagicValue,
15642 bool isConstantEvaluated) {
15643 while(true) {
15644 if (!TypeExpr)
15645 return false;
15646
15647 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15648
15649 switch (TypeExpr->getStmtClass()) {
15650 case Stmt::UnaryOperatorClass: {
15651 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15652 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15653 TypeExpr = UO->getSubExpr();
15654 continue;
15655 }
15656 return false;
15657 }
15658
15659 case Stmt::DeclRefExprClass: {
15660 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15661 *VD = DRE->getDecl();
15662 return true;
15663 }
15664
15665 case Stmt::IntegerLiteralClass: {
15666 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15667 llvm::APInt MagicValueAPInt = IL->getValue();
15668 if (MagicValueAPInt.getActiveBits() <= 64) {
15669 *MagicValue = MagicValueAPInt.getZExtValue();
15670 return true;
15671 } else
15672 return false;
15673 }
15674
15675 case Stmt::BinaryConditionalOperatorClass:
15676 case Stmt::ConditionalOperatorClass: {
15677 const AbstractConditionalOperator *ACO =
15679 bool Result;
15680 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15681 isConstantEvaluated)) {
15682 if (Result)
15683 TypeExpr = ACO->getTrueExpr();
15684 else
15685 TypeExpr = ACO->getFalseExpr();
15686 continue;
15687 }
15688 return false;
15689 }
15690
15691 case Stmt::BinaryOperatorClass: {
15692 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15693 if (BO->getOpcode() == BO_Comma) {
15694 TypeExpr = BO->getRHS();
15695 continue;
15696 }
15697 return false;
15698 }
15699
15700 default:
15701 return false;
15702 }
15703 }
15704}
15705
15706/// Retrieve the C type corresponding to type tag TypeExpr.
15707///
15708/// \param TypeExpr Expression that specifies a type tag.
15709///
15710/// \param MagicValues Registered magic values.
15711///
15712/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15713/// kind.
15714///
15715/// \param TypeInfo Information about the corresponding C type.
15716///
15717/// \param isConstantEvaluated whether the evalaution should be performed in
15718/// constant context.
15719///
15720/// \returns true if the corresponding C type was found.
15722 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15723 const ASTContext &Ctx,
15724 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15725 *MagicValues,
15726 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15727 bool isConstantEvaluated) {
15728 FoundWrongKind = false;
15729
15730 // Variable declaration that has type_tag_for_datatype attribute.
15731 const ValueDecl *VD = nullptr;
15732
15733 uint64_t MagicValue;
15734
15735 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15736 return false;
15737
15738 if (VD) {
15739 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15740 if (I->getArgumentKind() != ArgumentKind) {
15741 FoundWrongKind = true;
15742 return false;
15743 }
15744 TypeInfo.Type = I->getMatchingCType();
15745 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15746 TypeInfo.MustBeNull = I->getMustBeNull();
15747 return true;
15748 }
15749 return false;
15750 }
15751
15752 if (!MagicValues)
15753 return false;
15754
15755 llvm::DenseMap<Sema::TypeTagMagicValue,
15757 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15758 if (I == MagicValues->end())
15759 return false;
15760
15761 TypeInfo = I->second;
15762 return true;
15763}
15764
15766 uint64_t MagicValue, QualType Type,
15767 bool LayoutCompatible,
15768 bool MustBeNull) {
15769 if (!TypeTagForDatatypeMagicValues)
15770 TypeTagForDatatypeMagicValues.reset(
15771 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15772
15773 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15774 (*TypeTagForDatatypeMagicValues)[Magic] =
15775 TypeTagData(Type, LayoutCompatible, MustBeNull);
15776}
15777
15778static bool IsSameCharType(QualType T1, QualType T2) {
15779 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15780 if (!BT1)
15781 return false;
15782
15783 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15784 if (!BT2)
15785 return false;
15786
15787 BuiltinType::Kind T1Kind = BT1->getKind();
15788 BuiltinType::Kind T2Kind = BT2->getKind();
15789
15790 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15791 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15792 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15793 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15794}
15795
15796void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15797 const ArrayRef<const Expr *> ExprArgs,
15798 SourceLocation CallSiteLoc) {
15799 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15800 bool IsPointerAttr = Attr->getIsPointer();
15801
15802 // Retrieve the argument representing the 'type_tag'.
15803 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15804 if (TypeTagIdxAST >= ExprArgs.size()) {
15805 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15806 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15807 return;
15808 }
15809 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15810 bool FoundWrongKind;
15811 TypeTagData TypeInfo;
15812 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15813 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15814 TypeInfo, isConstantEvaluatedContext())) {
15815 if (FoundWrongKind)
15816 Diag(TypeTagExpr->getExprLoc(),
15817 diag::warn_type_tag_for_datatype_wrong_kind)
15818 << TypeTagExpr->getSourceRange();
15819 return;
15820 }
15821
15822 // Retrieve the argument representing the 'arg_idx'.
15823 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15824 if (ArgumentIdxAST >= ExprArgs.size()) {
15825 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15826 << 1 << Attr->getArgumentIdx().getSourceIndex();
15827 return;
15828 }
15829 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15830 if (IsPointerAttr) {
15831 // Skip implicit cast of pointer to `void *' (as a function argument).
15832 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15833 if (ICE->getType()->isVoidPointerType() &&
15834 ICE->getCastKind() == CK_BitCast)
15835 ArgumentExpr = ICE->getSubExpr();
15836 }
15837 QualType ArgumentType = ArgumentExpr->getType();
15838
15839 // Passing a `void*' pointer shouldn't trigger a warning.
15840 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15841 return;
15842
15843 if (TypeInfo.MustBeNull) {
15844 // Type tag with matching void type requires a null pointer.
15845 if (!ArgumentExpr->isNullPointerConstant(Context,
15847 Diag(ArgumentExpr->getExprLoc(),
15848 diag::warn_type_safety_null_pointer_required)
15849 << ArgumentKind->getName()
15850 << ArgumentExpr->getSourceRange()
15851 << TypeTagExpr->getSourceRange();
15852 }
15853 return;
15854 }
15855
15856 QualType RequiredType = TypeInfo.Type;
15857 if (IsPointerAttr)
15858 RequiredType = Context.getPointerType(RequiredType);
15859
15860 bool mismatch = false;
15861 if (!TypeInfo.LayoutCompatible) {
15862 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15863
15864 // C++11 [basic.fundamental] p1:
15865 // Plain char, signed char, and unsigned char are three distinct types.
15866 //
15867 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15868 // char' depending on the current char signedness mode.
15869 if (mismatch)
15870 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15871 RequiredType->getPointeeType())) ||
15872 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15873 mismatch = false;
15874 } else
15875 if (IsPointerAttr)
15876 mismatch = !isLayoutCompatible(Context,
15877 ArgumentType->getPointeeType(),
15878 RequiredType->getPointeeType());
15879 else
15880 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15881
15882 if (mismatch)
15883 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15884 << ArgumentType << ArgumentKind
15885 << TypeInfo.LayoutCompatible << RequiredType
15886 << ArgumentExpr->getSourceRange()
15887 << TypeTagExpr->getSourceRange();
15888}
15889
15890void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15891 CharUnits Alignment) {
15892 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
15893 Alignment);
15894}
15895
15897 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
15898 const NamedDecl *ND = m.RD;
15899 if (ND->getName().empty()) {
15900 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15901 ND = TD;
15902 }
15903 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15904 << m.MD << ND << m.E->getSourceRange();
15905 }
15907}
15908
15910 E = E->IgnoreParens();
15911 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
15912 return;
15913 if (isa<UnaryOperator>(E) &&
15914 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15915 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15916 if (isa<MemberExpr>(Op)) {
15917 auto &MisalignedMembersForExpr =
15919 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
15920 if (MA != MisalignedMembersForExpr.end() &&
15921 (T->isDependentType() || T->isIntegerType() ||
15922 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15923 Context.getTypeAlignInChars(
15924 T->getPointeeType()) <= MA->Alignment))))
15925 MisalignedMembersForExpr.erase(MA);
15926 }
15927 }
15928}
15929
15931 Expr *E,
15932 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15933 Action) {
15934 const auto *ME = dyn_cast<MemberExpr>(E);
15935 if (!ME)
15936 return;
15937
15938 // No need to check expressions with an __unaligned-qualified type.
15939 if (E->getType().getQualifiers().hasUnaligned())
15940 return;
15941
15942 // For a chain of MemberExpr like "a.b.c.d" this list
15943 // will keep FieldDecl's like [d, c, b].
15944 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15945 const MemberExpr *TopME = nullptr;
15946 bool AnyIsPacked = false;
15947 do {
15948 QualType BaseType = ME->getBase()->getType();
15949 if (BaseType->isDependentType())
15950 return;
15951 if (ME->isArrow())
15952 BaseType = BaseType->getPointeeType();
15953 auto *RD = BaseType->castAsRecordDecl();
15954 if (RD->isInvalidDecl())
15955 return;
15956
15957 ValueDecl *MD = ME->getMemberDecl();
15958 auto *FD = dyn_cast<FieldDecl>(MD);
15959 // We do not care about non-data members.
15960 if (!FD || FD->isInvalidDecl())
15961 return;
15962
15963 AnyIsPacked =
15964 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15965 ReverseMemberChain.push_back(FD);
15966
15967 TopME = ME;
15968 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15969 } while (ME);
15970 assert(TopME && "We did not compute a topmost MemberExpr!");
15971
15972 // Not the scope of this diagnostic.
15973 if (!AnyIsPacked)
15974 return;
15975
15976 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15977 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15978 // TODO: The innermost base of the member expression may be too complicated.
15979 // For now, just disregard these cases. This is left for future
15980 // improvement.
15981 if (!DRE && !isa<CXXThisExpr>(TopBase))
15982 return;
15983
15984 // Alignment expected by the whole expression.
15985 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15986
15987 // No need to do anything else with this case.
15988 if (ExpectedAlignment.isOne())
15989 return;
15990
15991 // Synthesize offset of the whole access.
15992 CharUnits Offset;
15993 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
15994 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
15995
15996 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15997 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15998 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
15999
16000 // The base expression of the innermost MemberExpr may give
16001 // stronger guarantees than the class containing the member.
16002 if (DRE && !TopME->isArrow()) {
16003 const ValueDecl *VD = DRE->getDecl();
16004 if (!VD->getType()->isReferenceType())
16005 CompleteObjectAlignment =
16006 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16007 }
16008
16009 // Check if the synthesized offset fulfills the alignment.
16010 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16011 // It may fulfill the offset it but the effective alignment may still be
16012 // lower than the expected expression alignment.
16013 CompleteObjectAlignment < ExpectedAlignment) {
16014 // If this happens, we want to determine a sensible culprit of this.
16015 // Intuitively, watching the chain of member expressions from right to
16016 // left, we start with the required alignment (as required by the field
16017 // type) but some packed attribute in that chain has reduced the alignment.
16018 // It may happen that another packed structure increases it again. But if
16019 // we are here such increase has not been enough. So pointing the first
16020 // FieldDecl that either is packed or else its RecordDecl is,
16021 // seems reasonable.
16022 FieldDecl *FD = nullptr;
16023 CharUnits Alignment;
16024 for (FieldDecl *FDI : ReverseMemberChain) {
16025 if (FDI->hasAttr<PackedAttr>() ||
16026 FDI->getParent()->hasAttr<PackedAttr>()) {
16027 FD = FDI;
16028 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16029 Context.getTypeAlignInChars(
16030 Context.getCanonicalTagType(FD->getParent())));
16031 break;
16032 }
16033 }
16034 assert(FD && "We did not find a packed FieldDecl!");
16035 Action(E, FD->getParent(), FD, Alignment);
16036 }
16037}
16038
16039void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16040 using namespace std::placeholders;
16041
16043 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16044 _2, _3, _4));
16045}
16046
16048 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16049 if (checkArgCount(TheCall, 1))
16050 return true;
16051
16052 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16053 if (A.isInvalid())
16054 return true;
16055
16056 TheCall->setArg(0, A.get());
16057 QualType TyA = A.get()->getType();
16058
16059 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16060 ArgTyRestr, 1))
16061 return true;
16062
16063 TheCall->setType(TyA);
16064 return false;
16065}
16066
16067bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16068 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16069 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16070 TheCall->setType(*Res);
16071 return false;
16072 }
16073 return true;
16074}
16075
16077 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16078 if (!Res)
16079 return true;
16080
16081 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16082 TheCall->setType(VecTy0->getElementType());
16083 else
16084 TheCall->setType(*Res);
16085
16086 return false;
16087}
16088
16090 SourceLocation Loc) {
16092 R = RHS->getEnumCoercedType(S.Context);
16093 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16095 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16096 << LHS->getSourceRange() << RHS->getSourceRange()
16097 << /*Arithmetic Between*/ 0 << L << R;
16098 }
16099 return false;
16100}
16101
16102/// Check if all arguments have the same type. If the types don't match, emit an
16103/// error message and return true. Otherwise return false.
16104///
16105/// For scalars we directly compare their unqualified types. But even if we
16106/// compare unqualified vector types, a difference in qualifiers in the element
16107/// types can make the vector types be considered not equal. For example,
16108/// vector of 4 'const float' values vs vector of 4 'float' values.
16109/// So we compare unqualified types of their elements and number of elements.
16111 ArrayRef<Expr *> Args) {
16112 assert(!Args.empty() && "Should have at least one argument.");
16113
16114 Expr *Arg0 = Args.front();
16115 QualType Ty0 = Arg0->getType();
16116
16117 auto EmitError = [&](Expr *ArgI) {
16118 SemaRef.Diag(Arg0->getBeginLoc(),
16119 diag::err_typecheck_call_different_arg_types)
16120 << Arg0->getType() << ArgI->getType();
16121 };
16122
16123 // Compare scalar types.
16124 if (!Ty0->isVectorType()) {
16125 for (Expr *ArgI : Args.drop_front())
16126 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16127 EmitError(ArgI);
16128 return true;
16129 }
16130
16131 return false;
16132 }
16133
16134 // Compare vector types.
16135 const auto *Vec0 = Ty0->castAs<VectorType>();
16136 for (Expr *ArgI : Args.drop_front()) {
16137 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16138 if (!VecI ||
16139 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16140 VecI->getElementType()) ||
16141 Vec0->getNumElements() != VecI->getNumElements()) {
16142 EmitError(ArgI);
16143 return true;
16144 }
16145 }
16146
16147 return false;
16148}
16149
16150std::optional<QualType>
16152 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16153 if (checkArgCount(TheCall, 2))
16154 return std::nullopt;
16155
16157 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16158 return std::nullopt;
16159
16160 Expr *Args[2];
16161 for (int I = 0; I < 2; ++I) {
16162 ExprResult Converted =
16163 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16164 if (Converted.isInvalid())
16165 return std::nullopt;
16166 Args[I] = Converted.get();
16167 }
16168
16169 SourceLocation LocA = Args[0]->getBeginLoc();
16170 QualType TyA = Args[0]->getType();
16171
16172 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16173 return std::nullopt;
16174
16175 if (checkBuiltinVectorMathArgTypes(*this, Args))
16176 return std::nullopt;
16177
16178 TheCall->setArg(0, Args[0]);
16179 TheCall->setArg(1, Args[1]);
16180 return TyA;
16181}
16182
16184 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16185 if (checkArgCount(TheCall, 3))
16186 return true;
16187
16188 SourceLocation Loc = TheCall->getExprLoc();
16189 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16190 TheCall->getArg(1), Loc) ||
16191 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16192 TheCall->getArg(2), Loc))
16193 return true;
16194
16195 Expr *Args[3];
16196 for (int I = 0; I < 3; ++I) {
16197 ExprResult Converted =
16198 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16199 if (Converted.isInvalid())
16200 return true;
16201 Args[I] = Converted.get();
16202 }
16203
16204 int ArgOrdinal = 1;
16205 for (Expr *Arg : Args) {
16206 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16207 ArgTyRestr, ArgOrdinal++))
16208 return true;
16209 }
16210
16211 if (checkBuiltinVectorMathArgTypes(*this, Args))
16212 return true;
16213
16214 for (int I = 0; I < 3; ++I)
16215 TheCall->setArg(I, Args[I]);
16216
16217 TheCall->setType(Args[0]->getType());
16218 return false;
16219}
16220
16221bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16222 if (checkArgCount(TheCall, 1))
16223 return true;
16224
16225 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16226 if (A.isInvalid())
16227 return true;
16228
16229 TheCall->setArg(0, A.get());
16230 return false;
16231}
16232
16233bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16234 if (checkArgCount(TheCall, 1))
16235 return true;
16236
16237 ExprResult Arg = TheCall->getArg(0);
16238 QualType TyArg = Arg.get()->getType();
16239
16240 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16241 return Diag(TheCall->getArg(0)->getBeginLoc(),
16242 diag::err_builtin_invalid_arg_type)
16243 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16244
16245 TheCall->setType(TyArg);
16246 return false;
16247}
16248
16249ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16250 ExprResult CallResult) {
16251 if (checkArgCount(TheCall, 1))
16252 return ExprError();
16253
16254 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16255 if (MatrixArg.isInvalid())
16256 return MatrixArg;
16257 Expr *Matrix = MatrixArg.get();
16258
16259 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16260 if (!MType) {
16261 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16262 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16263 << Matrix->getType();
16264 return ExprError();
16265 }
16266
16267 // Create returned matrix type by swapping rows and columns of the argument
16268 // matrix type.
16269 QualType ResultType = Context.getConstantMatrixType(
16270 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16271
16272 // Change the return type to the type of the returned matrix.
16273 TheCall->setType(ResultType);
16274
16275 // Update call argument to use the possibly converted matrix argument.
16276 TheCall->setArg(0, Matrix);
16277 return CallResult;
16278}
16279
16280// Get and verify the matrix dimensions.
16281static std::optional<unsigned>
16283 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16284 if (!Value) {
16285 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16286 << Name;
16287 return {};
16288 }
16289 uint64_t Dim = Value->getZExtValue();
16290 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16291 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16292 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16293 return {};
16294 }
16295 return Dim;
16296}
16297
16298ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16299 ExprResult CallResult) {
16300 if (!getLangOpts().MatrixTypes) {
16301 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16302 return ExprError();
16303 }
16304
16305 if (checkArgCount(TheCall, 4))
16306 return ExprError();
16307
16308 unsigned PtrArgIdx = 0;
16309 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16310 Expr *RowsExpr = TheCall->getArg(1);
16311 Expr *ColumnsExpr = TheCall->getArg(2);
16312 Expr *StrideExpr = TheCall->getArg(3);
16313
16314 bool ArgError = false;
16315
16316 // Check pointer argument.
16317 {
16319 if (PtrConv.isInvalid())
16320 return PtrConv;
16321 PtrExpr = PtrConv.get();
16322 TheCall->setArg(0, PtrExpr);
16323 if (PtrExpr->isTypeDependent()) {
16324 TheCall->setType(Context.DependentTy);
16325 return TheCall;
16326 }
16327 }
16328
16329 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16330 QualType ElementTy;
16331 if (!PtrTy) {
16332 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16333 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16334 << PtrExpr->getType();
16335 ArgError = true;
16336 } else {
16337 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16338
16340 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16341 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16342 << /* no fp */ 0 << PtrExpr->getType();
16343 ArgError = true;
16344 }
16345 }
16346
16347 // Apply default Lvalue conversions and convert the expression to size_t.
16348 auto ApplyArgumentConversions = [this](Expr *E) {
16350 if (Conv.isInvalid())
16351 return Conv;
16352
16353 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16354 };
16355
16356 // Apply conversion to row and column expressions.
16357 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16358 if (!RowsConv.isInvalid()) {
16359 RowsExpr = RowsConv.get();
16360 TheCall->setArg(1, RowsExpr);
16361 } else
16362 RowsExpr = nullptr;
16363
16364 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16365 if (!ColumnsConv.isInvalid()) {
16366 ColumnsExpr = ColumnsConv.get();
16367 TheCall->setArg(2, ColumnsExpr);
16368 } else
16369 ColumnsExpr = nullptr;
16370
16371 // If any part of the result matrix type is still pending, just use
16372 // Context.DependentTy, until all parts are resolved.
16373 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16374 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16375 TheCall->setType(Context.DependentTy);
16376 return CallResult;
16377 }
16378
16379 // Check row and column dimensions.
16380 std::optional<unsigned> MaybeRows;
16381 if (RowsExpr)
16382 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16383
16384 std::optional<unsigned> MaybeColumns;
16385 if (ColumnsExpr)
16386 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16387
16388 // Check stride argument.
16389 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16390 if (StrideConv.isInvalid())
16391 return ExprError();
16392 StrideExpr = StrideConv.get();
16393 TheCall->setArg(3, StrideExpr);
16394
16395 if (MaybeRows) {
16396 if (std::optional<llvm::APSInt> Value =
16397 StrideExpr->getIntegerConstantExpr(Context)) {
16398 uint64_t Stride = Value->getZExtValue();
16399 if (Stride < *MaybeRows) {
16400 Diag(StrideExpr->getBeginLoc(),
16401 diag::err_builtin_matrix_stride_too_small);
16402 ArgError = true;
16403 }
16404 }
16405 }
16406
16407 if (ArgError || !MaybeRows || !MaybeColumns)
16408 return ExprError();
16409
16410 TheCall->setType(
16411 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16412 return CallResult;
16413}
16414
16415ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16416 ExprResult CallResult) {
16417 if (checkArgCount(TheCall, 3))
16418 return ExprError();
16419
16420 unsigned PtrArgIdx = 1;
16421 Expr *MatrixExpr = TheCall->getArg(0);
16422 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16423 Expr *StrideExpr = TheCall->getArg(2);
16424
16425 bool ArgError = false;
16426
16427 {
16428 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16429 if (MatrixConv.isInvalid())
16430 return MatrixConv;
16431 MatrixExpr = MatrixConv.get();
16432 TheCall->setArg(0, MatrixExpr);
16433 }
16434 if (MatrixExpr->isTypeDependent()) {
16435 TheCall->setType(Context.DependentTy);
16436 return TheCall;
16437 }
16438
16439 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16440 if (!MatrixTy) {
16441 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16442 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16443 ArgError = true;
16444 }
16445
16446 {
16448 if (PtrConv.isInvalid())
16449 return PtrConv;
16450 PtrExpr = PtrConv.get();
16451 TheCall->setArg(1, PtrExpr);
16452 if (PtrExpr->isTypeDependent()) {
16453 TheCall->setType(Context.DependentTy);
16454 return TheCall;
16455 }
16456 }
16457
16458 // Check pointer argument.
16459 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16460 if (!PtrTy) {
16461 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16462 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16463 << PtrExpr->getType();
16464 ArgError = true;
16465 } else {
16466 QualType ElementTy = PtrTy->getPointeeType();
16467 if (ElementTy.isConstQualified()) {
16468 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16469 ArgError = true;
16470 }
16471 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16472 if (MatrixTy &&
16473 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16474 Diag(PtrExpr->getBeginLoc(),
16475 diag::err_builtin_matrix_pointer_arg_mismatch)
16476 << ElementTy << MatrixTy->getElementType();
16477 ArgError = true;
16478 }
16479 }
16480
16481 // Apply default Lvalue conversions and convert the stride expression to
16482 // size_t.
16483 {
16484 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16485 if (StrideConv.isInvalid())
16486 return StrideConv;
16487
16488 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16489 if (StrideConv.isInvalid())
16490 return StrideConv;
16491 StrideExpr = StrideConv.get();
16492 TheCall->setArg(2, StrideExpr);
16493 }
16494
16495 // Check stride argument.
16496 if (MatrixTy) {
16497 if (std::optional<llvm::APSInt> Value =
16498 StrideExpr->getIntegerConstantExpr(Context)) {
16499 uint64_t Stride = Value->getZExtValue();
16500 if (Stride < MatrixTy->getNumRows()) {
16501 Diag(StrideExpr->getBeginLoc(),
16502 diag::err_builtin_matrix_stride_too_small);
16503 ArgError = true;
16504 }
16505 }
16506 }
16507
16508 if (ArgError)
16509 return ExprError();
16510
16511 return CallResult;
16512}
16513
16515 const NamedDecl *Callee) {
16516 // This warning does not make sense in code that has no runtime behavior.
16518 return;
16519
16520 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16521
16522 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16523 return;
16524
16525 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16526 // all TCBs the callee is a part of.
16527 llvm::StringSet<> CalleeTCBs;
16528 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16529 CalleeTCBs.insert(A->getTCBName());
16530 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16531 CalleeTCBs.insert(A->getTCBName());
16532
16533 // Go through the TCBs the caller is a part of and emit warnings if Caller
16534 // is in a TCB that the Callee is not.
16535 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16536 StringRef CallerTCB = A->getTCBName();
16537 if (CalleeTCBs.count(CallerTCB) == 0) {
16538 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16539 << Callee << CallerTCB;
16540 }
16541 }
16542}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers=false)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
MathCheck
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
__device__ __2f16 float __ockl_bool s
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * toString() const
const char * getStart() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isComplexInt() const
Definition APValue.h:470
bool isFloat() const
Definition APValue.h:468
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isInt() const
Definition APValue.h:467
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
bool isAddrLabelDiff() const
Definition APValue.h:478
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:772
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedLongLongTy
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4287
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4465
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4471
SourceLocation getQuestionLoc() const
Definition Expr.h:4314
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4477
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Expr * getBase()
Get base of the array section.
Definition Expr.h:7183
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7187
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getRBracketLoc() const
Definition Expr.h:2769
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
QualType getElementType() const
Definition TypeBase.h:3734
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:6963
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:6945
Attr - This represents one attribute.
Definition Attr.h:45
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
SourceLocation getExprLoc() const
Definition Expr.h:4013
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2128
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
BinaryOperatorKind Opcode
Definition Expr.h:3977
Pointer to a block type.
Definition TypeBase.h:3542
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
bool isInteger() const
Definition TypeBase.h:3225
bool isFloatingPoint() const
Definition TypeBase.h:3237
bool isSignedInteger() const
Definition TypeBase.h:3229
bool isUnsignedInteger() const
Definition TypeBase.h:3233
Kind getKind() const
Definition TypeBase.h:3212
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:375
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:3903
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1631
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:154
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5143
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5183
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3094
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1588
arg_iterator arg_begin()
Definition Expr.h:3134
arg_iterator arg_end()
Definition Expr.h:3137
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
bool isCallToStdMove() const
Definition Expr.cpp:3619
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3170
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
arg_range arguments()
Definition Expr.h:3129
SourceLocation getEndLoc() const
Definition Expr.h:3230
SourceLocation getRParenLoc() const
Definition Expr.h:3208
Decl * getCalleeDecl()
Definition Expr.h:3054
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition Expr.cpp:1593
void setCallee(Expr *F)
Definition Expr.h:3026
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3113
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
Expr * getSubExpr()
Definition Expr.h:3660
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getLHS() const
Definition Expr.h:4359
Expr * getRHS() const
Definition Expr.h:4360
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
QualType desugar() const
Definition TypeBase.h:3861
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
static ConvertVectorExpr * Create(const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5552
Expr * getOperand() const
Definition ExprCXX.h:5326
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:484
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
T * getAttr() const
Definition DeclBase.h:573
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1988
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4007
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4230
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:671
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3073
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:202
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4203
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
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:3665
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3065
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4042
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:262
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:222
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:133
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4741
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2868
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4542
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3751
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3854
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3122
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4318
bool isStatic() const
Definition Decl.h:2929
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4133
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4119
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3815
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
unsigned getNumParams() const
Definition TypeBase.h:5532
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5653
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4759
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4755
QualType getReturnType() const
Definition TypeBase.h:4790
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
Describes an C or C++ initializer list.
Definition Expr.h:5233
ArrayRef< Expr * > inits()
Definition Expr.h:5283
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1020
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1056
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:498
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1103
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:848
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1683
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1697
SourceLocation getSemiLoc() const
Definition Stmt.h:1694
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:616
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:705
bool isImplicitProperty() const
Definition ExprObjC.h:702
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:52
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:298
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6690
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5071
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2866
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8318
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
void removeLocalVolatile()
Definition TypeBase.h:8394
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8386
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8399
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8324
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4312
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4398
field_range fields() const
Definition Decl.h:4515
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4390
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1025
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1108
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:95
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:262
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:283
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:526
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
SemaAMDGPU & AMDGPU()
Definition Sema.h:1416
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13000
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2643
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9297
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9305
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9342
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
bool FormatStringHasSArg(const StringLiteral *FExpr)
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6896
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2045
SemaHexagon & Hexagon()
Definition Sema.h:1456
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1651
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:833
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1546
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ASTContext & Context
Definition Sema.h:1283
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
SemaObjC & ObjC()
Definition Sema.h:1486
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:754
ASTContext & getASTContext() const
Definition Sema.h:925
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2585
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
AtomicArgumentOrder
Definition Sema.h:2692
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:918
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
SemaBPF & BPF()
Definition Sema.h:1431
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
SemaDirectX & DirectX()
Definition Sema.h:1446
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition Sema.h:1281
static const uint64_t MaximumAlignment
Definition Sema.h:1214
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:952
SemaHLSL & HLSL()
Definition Sema.h:1451
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1471
SemaRISCV & RISCV()
Definition Sema.h:1516
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2758
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6929
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1663
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1314
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2665
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15318
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:2298
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:639
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1414
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
SemaOpenCL & OpenCL()
Definition Sema.h:1496
FormatArgumentPassingKind
Definition Sema.h:2595
@ FAPK_Elsewhere
Definition Sema.h:2599
@ FAPK_Fixed
Definition Sema.h:2596
@ FAPK_Variadic
Definition Sema.h:2597
@ FAPK_VAList
Definition Sema.h:2598
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8136
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13879
SourceManager & getSourceManager() const
Definition Sema.h:923
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
Definition Sema.h:2587
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::FloatTy)
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
SemaPPC & PPC()
Definition Sema.h:1506
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1246
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FormatStringI...
SemaSystemZ & SystemZ()
Definition Sema.h:1536
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
SourceManager & SourceMgr
Definition Sema.h:1286
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:783
DiagnosticsEngine & Diags
Definition Sema.h:1285
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
SemaNVPTX & NVPTX()
Definition Sema.h:1481
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:625
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
@ AbstractParamType
Definition Sema.h:6201
SemaSPIRV & SPIRV()
Definition Sema.h:1521
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
SemaLoongArch & LoongArch()
Definition Sema.h:1461
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6389
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
SemaWasm & Wasm()
Definition Sema.h:1541
SemaARM & ARM()
Definition Sema.h:1421
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4577
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition Stmt.cpp:299
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
bool isUTF8() const
Definition Expr.h:1918
bool isWide() const
Definition Expr.h:1917
bool isPascal() const
Definition Expr.h:1922
unsigned getLength() const
Definition Expr.h:1909
StringLiteralKind getKind() const
Definition Expr.h:1912
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition Expr.cpp:1322
bool isUTF32() const
Definition Expr.h:1920
unsigned getByteLength() const
Definition Expr.h:1908
StringRef getString() const
Definition Expr.h:1867
bool isUTF16() const
Definition Expr.h:1919
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1974
bool isOrdinary() const
Definition Expr.h:1916
unsigned getCharByteWidth() const
Definition Expr.h:1910
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3832
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isUnion() const
Definition Decl.h:3922
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:385
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6165
A container of type source information.
Definition TypeBase.h:8249
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8260
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9051
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9031
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2066
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2425
bool isArrayType() const
Definition TypeBase.h:8614
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isPointerType() const
Definition TypeBase.h:8515
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isScalarType() const
Definition TypeBase.h:8973
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1909
bool isVariableArrayType() const
Definition TypeBase.h:8626
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isExtVectorType() const
Definition TypeBase.h:8658
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2646
bool isBitIntType() const
Definition TypeBase.h:8780
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8840
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8638
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2243
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2557
bool isAtomicType() const
Definition TypeBase.h:8697
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3074
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isUnscopedEnumerationType() const
Definition Type.cpp:2125
bool isObjCObjectType() const
Definition TypeBase.h:8688
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9144
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2312
bool isStructureOrClassType() const
Definition Type.cpp:706
bool isVectorType() const
Definition TypeBase.h:8654
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
bool isAnyPointerType() const
Definition TypeBase.h:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isObjCRetainableType() const
Definition Type.cpp:5283
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2569
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2634
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2362
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5501
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2677
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:216
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1257
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1242
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1235
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1249
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2485
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1203
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1264
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:511
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:661
@ Comparison
A comparison.
Definition Sema.h:665
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:34
@ Success
Annotation was successful.
Definition Parser.h:65
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
PointerAuthDiscArgKind
Definition Sema.h:592
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:545
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:497
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:519
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:137
StringLiteralKind
Definition Expr.h:1763
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Win64
Definition Specifiers.h:285
@ CC_X86_64SysV
Definition Specifiers.h:286
@ Generic
not a target-specific vector type
Definition TypeBase.h:4136
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5874
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
Extra information about a function prototype.
Definition TypeBase.h:5339
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned Indentation
The number of spaces to use to indent each line.
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13171
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13197
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13187
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13146
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6790
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2607
#define log2(__x)
Definition tgmath.h:970