clang 22.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
80#include "clang/Sema/SemaWasm.h"
81#include "clang/Sema/SemaX86.h"
82#include "llvm/ADT/APFloat.h"
83#include "llvm/ADT/APInt.h"
84#include "llvm/ADT/APSInt.h"
85#include "llvm/ADT/ArrayRef.h"
86#include "llvm/ADT/DenseMap.h"
87#include "llvm/ADT/FoldingSet.h"
88#include "llvm/ADT/STLExtras.h"
89#include "llvm/ADT/STLForwardCompat.h"
90#include "llvm/ADT/SmallBitVector.h"
91#include "llvm/ADT/SmallPtrSet.h"
92#include "llvm/ADT/SmallString.h"
93#include "llvm/ADT/SmallVector.h"
94#include "llvm/ADT/StringExtras.h"
95#include "llvm/ADT/StringRef.h"
96#include "llvm/ADT/StringSet.h"
97#include "llvm/ADT/StringSwitch.h"
98#include "llvm/Support/AtomicOrdering.h"
99#include "llvm/Support/Compiler.h"
100#include "llvm/Support/ConvertUTF.h"
101#include "llvm/Support/ErrorHandling.h"
102#include "llvm/Support/Format.h"
103#include "llvm/Support/Locale.h"
104#include "llvm/Support/MathExtras.h"
105#include "llvm/Support/SaveAndRestore.h"
106#include "llvm/Support/raw_ostream.h"
107#include "llvm/TargetParser/RISCVTargetParser.h"
108#include "llvm/TargetParser/Triple.h"
109#include <algorithm>
110#include <cassert>
111#include <cctype>
112#include <cstddef>
113#include <cstdint>
114#include <functional>
115#include <limits>
116#include <optional>
117#include <string>
118#include <tuple>
119#include <utility>
120
121using namespace clang;
122using namespace sema;
123
125 unsigned ByteNo) const {
126 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
127 Context.getTargetInfo());
128}
129
130static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
132 return (A << 8) | B;
133}
134
135bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
136 unsigned ArgCount = Call->getNumArgs();
137 if (ArgCount >= MinArgCount)
138 return false;
139
140 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
141 << 0 /*function call*/ << MinArgCount << ArgCount
142 << /*is non object*/ 0 << Call->getSourceRange();
143}
144
145bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
146 unsigned ArgCount = Call->getNumArgs();
147 if (ArgCount <= MaxArgCount)
148 return false;
149 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
150 << 0 /*function call*/ << MaxArgCount << ArgCount
151 << /*is non object*/ 0 << Call->getSourceRange();
152}
153
154bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
155 unsigned MaxArgCount) {
156 return checkArgCountAtLeast(Call, MinArgCount) ||
157 checkArgCountAtMost(Call, MaxArgCount);
158}
159
160bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
161 unsigned ArgCount = Call->getNumArgs();
162 if (ArgCount == DesiredArgCount)
163 return false;
164
165 if (checkArgCountAtLeast(Call, DesiredArgCount))
166 return true;
167 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
168
169 // Highlight all the excess arguments.
170 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
171 Call->getArg(ArgCount - 1)->getEndLoc());
172
173 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
174 << 0 /*function call*/ << DesiredArgCount << ArgCount
175 << /*is non object*/ 0 << Range;
176}
177
179 bool HasError = false;
180
181 for (const Expr *Arg : Call->arguments()) {
182 if (Arg->isValueDependent())
183 continue;
184
185 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
186 int DiagMsgKind = -1;
187 // Arguments must be pointers to constant strings and cannot use '$'.
188 if (!ArgString.has_value())
189 DiagMsgKind = 0;
190 else if (ArgString->find('$') != std::string::npos)
191 DiagMsgKind = 1;
192
193 if (DiagMsgKind >= 0) {
194 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
195 << DiagMsgKind << Arg->getSourceRange();
196 HasError = true;
197 }
198 }
199
200 return !HasError;
201}
202
204 if (Value->isTypeDependent())
205 return false;
206
207 InitializedEntity Entity =
209 ExprResult Result =
211 if (Result.isInvalid())
212 return true;
213 Value = Result.get();
214 return false;
215}
216
217/// Check that the first argument to __builtin_annotation is an integer
218/// and the second argument is a non-wide string literal.
219static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
220 if (S.checkArgCount(TheCall, 2))
221 return true;
222
223 // First argument should be an integer.
224 Expr *ValArg = TheCall->getArg(0);
225 QualType Ty = ValArg->getType();
226 if (!Ty->isIntegerType()) {
227 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
228 << ValArg->getSourceRange();
229 return true;
230 }
231
232 // Second argument should be a constant string.
233 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
234 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
235 if (!Literal || !Literal->isOrdinary()) {
236 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
237 << StrArg->getSourceRange();
238 return true;
239 }
240
241 TheCall->setType(Ty);
242 return false;
243}
244
245static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
246 // We need at least one argument.
247 if (TheCall->getNumArgs() < 1) {
248 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
249 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
250 << TheCall->getCallee()->getSourceRange();
251 return true;
252 }
253
254 // All arguments should be wide string literals.
255 for (Expr *Arg : TheCall->arguments()) {
256 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
257 if (!Literal || !Literal->isWide()) {
258 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
259 << Arg->getSourceRange();
260 return true;
261 }
262 }
263
264 return false;
265}
266
267/// Check that the argument to __builtin_addressof is a glvalue, and set the
268/// result type to the corresponding pointer type.
269static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
270 if (S.checkArgCount(TheCall, 1))
271 return true;
272
273 ExprResult Arg(TheCall->getArg(0));
274 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
275 if (ResultType.isNull())
276 return true;
277
278 TheCall->setArg(0, Arg.get());
279 TheCall->setType(ResultType);
280 return false;
281}
282
283/// Check that the argument to __builtin_function_start is a function.
284static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
285 if (S.checkArgCount(TheCall, 1))
286 return true;
287
288 if (TheCall->getArg(0)->containsErrors())
289 return true;
290
292 if (Arg.isInvalid())
293 return true;
294
295 TheCall->setArg(0, Arg.get());
296 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
298
299 if (!FD) {
300 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
301 << TheCall->getSourceRange();
302 return true;
303 }
304
305 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
306 TheCall->getBeginLoc());
307}
308
309/// Check the number of arguments and set the result type to
310/// the argument type.
311static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
312 if (S.checkArgCount(TheCall, 1))
313 return true;
314
315 TheCall->setType(TheCall->getArg(0)->getType());
316 return false;
317}
318
319/// Check that the value argument for __builtin_is_aligned(value, alignment) and
320/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
321/// type (but not a function pointer) and that the alignment is a power-of-two.
322static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
323 if (S.checkArgCount(TheCall, 2))
324 return true;
325
326 clang::Expr *Source = TheCall->getArg(0);
327 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
328
329 auto IsValidIntegerType = [](QualType Ty) {
330 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
331 };
332 QualType SrcTy = Source->getType();
333 // We should also be able to use it with arrays (but not functions!).
334 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
335 SrcTy = S.Context.getDecayedType(SrcTy);
336 }
337 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
338 SrcTy->isFunctionPointerType()) {
339 // FIXME: this is not quite the right error message since we don't allow
340 // floating point types, or member pointers.
341 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
342 << SrcTy;
343 return true;
344 }
345
346 clang::Expr *AlignOp = TheCall->getArg(1);
347 if (!IsValidIntegerType(AlignOp->getType())) {
348 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
349 << AlignOp->getType();
350 return true;
351 }
352 Expr::EvalResult AlignResult;
353 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
354 // We can't check validity of alignment if it is value dependent.
355 if (!AlignOp->isValueDependent() &&
356 AlignOp->EvaluateAsInt(AlignResult, S.Context,
358 llvm::APSInt AlignValue = AlignResult.Val.getInt();
359 llvm::APSInt MaxValue(
360 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
361 if (AlignValue < 1) {
362 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
363 return true;
364 }
365 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
366 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
367 << toString(MaxValue, 10);
368 return true;
369 }
370 if (!AlignValue.isPowerOf2()) {
371 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
372 return true;
373 }
374 if (AlignValue == 1) {
375 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
376 << IsBooleanAlignBuiltin;
377 }
378 }
379
382 SourceLocation(), Source);
383 if (SrcArg.isInvalid())
384 return true;
385 TheCall->setArg(0, SrcArg.get());
386 ExprResult AlignArg =
388 S.Context, AlignOp->getType(), false),
389 SourceLocation(), AlignOp);
390 if (AlignArg.isInvalid())
391 return true;
392 TheCall->setArg(1, AlignArg.get());
393 // For align_up/align_down, the return type is the same as the (potentially
394 // decayed) argument type including qualifiers. For is_aligned(), the result
395 // is always bool.
396 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
397 return false;
398}
399
400static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
401 if (S.checkArgCount(TheCall, 3))
402 return true;
403
404 std::pair<unsigned, const char *> Builtins[] = {
405 { Builtin::BI__builtin_add_overflow, "ckd_add" },
406 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
407 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
408 };
409
410 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
411 const char *> &P) {
412 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
414 S.getSourceManager(), S.getLangOpts()) == P.second;
415 });
416
417 auto ValidCkdIntType = [](QualType QT) {
418 // A valid checked integer type is an integer type other than a plain char,
419 // bool, a bit-precise type, or an enumeration type.
420 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
421 return (BT->getKind() >= BuiltinType::Short &&
422 BT->getKind() <= BuiltinType::Int128) || (
423 BT->getKind() >= BuiltinType::UShort &&
424 BT->getKind() <= BuiltinType::UInt128) ||
425 BT->getKind() == BuiltinType::UChar ||
426 BT->getKind() == BuiltinType::SChar;
427 return false;
428 };
429
430 // First two arguments should be integers.
431 for (unsigned I = 0; I < 2; ++I) {
433 if (Arg.isInvalid()) return true;
434 TheCall->setArg(I, Arg.get());
435
436 QualType Ty = Arg.get()->getType();
437 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
438 if (!IsValid) {
439 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
440 << CkdOperation << Ty << Arg.get()->getSourceRange();
441 return true;
442 }
443 }
444
445 // Third argument should be a pointer to a non-const integer.
446 // IRGen correctly handles volatile, restrict, and address spaces, and
447 // the other qualifiers aren't possible.
448 {
450 if (Arg.isInvalid()) return true;
451 TheCall->setArg(2, Arg.get());
452
453 QualType Ty = Arg.get()->getType();
454 const auto *PtrTy = Ty->getAs<PointerType>();
455 if (!PtrTy ||
456 !PtrTy->getPointeeType()->isIntegerType() ||
457 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
458 PtrTy->getPointeeType().isConstQualified()) {
459 S.Diag(Arg.get()->getBeginLoc(),
460 diag::err_overflow_builtin_must_be_ptr_int)
461 << CkdOperation << Ty << Arg.get()->getSourceRange();
462 return true;
463 }
464 }
465
466 // Disallow signed bit-precise integer args larger than 128 bits to mul
467 // function until we improve backend support.
468 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
469 for (unsigned I = 0; I < 3; ++I) {
470 const auto Arg = TheCall->getArg(I);
471 // Third argument will be a pointer.
472 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
473 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
474 S.getASTContext().getIntWidth(Ty) > 128)
475 return S.Diag(Arg->getBeginLoc(),
476 diag::err_overflow_builtin_bit_int_max_size)
477 << 128;
478 }
479 }
480
481 return false;
482}
483
484namespace {
485struct BuiltinDumpStructGenerator {
486 Sema &S;
487 CallExpr *TheCall;
488 SourceLocation Loc = TheCall->getBeginLoc();
489 SmallVector<Expr *, 32> Actions;
490 DiagnosticErrorTrap ErrorTracker;
491 PrintingPolicy Policy;
492
493 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
494 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
495 Policy(S.Context.getPrintingPolicy()) {
496 Policy.AnonymousTagLocations = false;
497 }
498
499 Expr *makeOpaqueValueExpr(Expr *Inner) {
500 auto *OVE = new (S.Context)
501 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
502 Inner->getObjectKind(), Inner);
503 Actions.push_back(OVE);
504 return OVE;
505 }
506
507 Expr *getStringLiteral(llvm::StringRef Str) {
509 // Wrap the literal in parentheses to attach a source location.
510 return new (S.Context) ParenExpr(Loc, Loc, Lit);
511 }
512
513 bool callPrintFunction(llvm::StringRef Format,
514 llvm::ArrayRef<Expr *> Exprs = {}) {
515 SmallVector<Expr *, 8> Args;
516 assert(TheCall->getNumArgs() >= 2);
517 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
518 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
519 Args.push_back(getStringLiteral(Format));
520 llvm::append_range(Args, Exprs);
521
522 // Register a note to explain why we're performing the call.
523 Sema::CodeSynthesisContext Ctx;
525 Ctx.PointOfInstantiation = Loc;
526 Ctx.CallArgs = Args.data();
527 Ctx.NumCallArgs = Args.size();
529
530 ExprResult RealCall =
531 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
532 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
533
535 if (!RealCall.isInvalid())
536 Actions.push_back(RealCall.get());
537 // Bail out if we've hit any errors, even if we managed to build the
538 // call. We don't want to produce more than one error.
539 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
540 }
541
542 Expr *getIndentString(unsigned Depth) {
543 if (!Depth)
544 return nullptr;
545
546 llvm::SmallString<32> Indent;
547 Indent.resize(Depth * Policy.Indentation, ' ');
548 return getStringLiteral(Indent);
549 }
550
551 Expr *getTypeString(QualType T) {
552 return getStringLiteral(T.getAsString(Policy));
553 }
554
555 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
556 llvm::raw_svector_ostream OS(Str);
557
558 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
559 // than trying to print a single character.
560 if (auto *BT = T->getAs<BuiltinType>()) {
561 switch (BT->getKind()) {
562 case BuiltinType::Bool:
563 OS << "%d";
564 return true;
565 case BuiltinType::Char_U:
566 case BuiltinType::UChar:
567 OS << "%hhu";
568 return true;
569 case BuiltinType::Char_S:
570 case BuiltinType::SChar:
571 OS << "%hhd";
572 return true;
573 default:
574 break;
575 }
576 }
577
578 analyze_printf::PrintfSpecifier Specifier;
579 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
580 // We were able to guess how to format this.
581 if (Specifier.getConversionSpecifier().getKind() ==
582 analyze_printf::PrintfConversionSpecifier::sArg) {
583 // Wrap double-quotes around a '%s' specifier and limit its maximum
584 // length. Ideally we'd also somehow escape special characters in the
585 // contents but printf doesn't support that.
586 // FIXME: '%s' formatting is not safe in general.
587 OS << '"';
588 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
589 Specifier.toString(OS);
590 OS << '"';
591 // FIXME: It would be nice to include a '...' if the string doesn't fit
592 // in the length limit.
593 } else {
594 Specifier.toString(OS);
595 }
596 return true;
597 }
598
599 if (T->isPointerType()) {
600 // Format all pointers with '%p'.
601 OS << "%p";
602 return true;
603 }
604
605 return false;
606 }
607
608 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
609 Expr *IndentLit = getIndentString(Depth);
610 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
611 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
612 : callPrintFunction("%s", {TypeLit}))
613 return true;
614
615 return dumpRecordValue(RD, E, IndentLit, Depth);
616 }
617
618 // Dump a record value. E should be a pointer or lvalue referring to an RD.
619 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
620 unsigned Depth) {
621 // FIXME: Decide what to do if RD is a union. At least we should probably
622 // turn off printing `const char*` members with `%s`, because that is very
623 // likely to crash if that's not the active member. Whatever we decide, we
624 // should document it.
625
626 // Build an OpaqueValueExpr so we can refer to E more than once without
627 // triggering re-evaluation.
628 Expr *RecordArg = makeOpaqueValueExpr(E);
629 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
630
631 if (callPrintFunction(" {\n"))
632 return true;
633
634 // Dump each base class, regardless of whether they're aggregates.
635 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
636 for (const auto &Base : CXXRD->bases()) {
637 QualType BaseType =
638 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
639 : S.Context.getLValueReferenceType(Base.getType());
641 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
642 RecordArg);
643 if (BasePtr.isInvalid() ||
644 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
645 Depth + 1))
646 return true;
647 }
648 }
649
650 Expr *FieldIndentArg = getIndentString(Depth + 1);
651
652 // Dump each field.
653 for (auto *D : RD->decls()) {
654 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
655 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
656 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
657 continue;
658
659 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
660 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
661 getTypeString(FD->getType()),
662 getStringLiteral(FD->getName())};
663
664 if (FD->isBitField()) {
665 Format += ": %zu ";
666 QualType SizeT = S.Context.getSizeType();
667 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
668 FD->getBitWidthValue());
669 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
670 }
671
672 Format += "=";
673
676 CXXScopeSpec(), Loc, IFD,
677 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
679 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
681 DeclarationNameInfo(FD->getDeclName(), Loc));
682 if (Field.isInvalid())
683 return true;
684
685 auto *InnerRD = FD->getType()->getAsRecordDecl();
686 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
687 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
688 // Recursively print the values of members of aggregate record type.
689 if (callPrintFunction(Format, Args) ||
690 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
691 return true;
692 } else {
693 Format += " ";
694 if (appendFormatSpecifier(FD->getType(), Format)) {
695 // We know how to print this field.
696 Args.push_back(Field.get());
697 } else {
698 // We don't know how to print this field. Print out its address
699 // with a format specifier that a smart tool will be able to
700 // recognize and treat specially.
701 Format += "*%p";
702 ExprResult FieldAddr =
703 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
704 if (FieldAddr.isInvalid())
705 return true;
706 Args.push_back(FieldAddr.get());
707 }
708 Format += "\n";
709 if (callPrintFunction(Format, Args))
710 return true;
711 }
712 }
713
714 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
715 : callPrintFunction("}\n");
716 }
717
718 Expr *buildWrapper() {
719 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
721 TheCall->setType(Wrapper->getType());
722 TheCall->setValueKind(Wrapper->getValueKind());
723 return Wrapper;
724 }
725};
726} // namespace
727
729 if (S.checkArgCountAtLeast(TheCall, 2))
730 return ExprError();
731
732 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
733 if (PtrArgResult.isInvalid())
734 return ExprError();
735 TheCall->setArg(0, PtrArgResult.get());
736
737 // First argument should be a pointer to a struct.
738 QualType PtrArgType = PtrArgResult.get()->getType();
739 if (!PtrArgType->isPointerType() ||
740 !PtrArgType->getPointeeType()->isRecordType()) {
741 S.Diag(PtrArgResult.get()->getBeginLoc(),
742 diag::err_expected_struct_pointer_argument)
743 << 1 << TheCall->getDirectCallee() << PtrArgType;
744 return ExprError();
745 }
746 QualType Pointee = PtrArgType->getPointeeType();
747 const RecordDecl *RD = Pointee->getAsRecordDecl();
748 // Try to instantiate the class template as appropriate; otherwise, access to
749 // its data() may lead to a crash.
750 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
751 diag::err_incomplete_type))
752 return ExprError();
753 // Second argument is a callable, but we can't fully validate it until we try
754 // calling it.
755 QualType FnArgType = TheCall->getArg(1)->getType();
756 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
757 !FnArgType->isBlockPointerType() &&
758 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
759 auto *BT = FnArgType->getAs<BuiltinType>();
760 switch (BT ? BT->getKind() : BuiltinType::Void) {
761 case BuiltinType::Dependent:
762 case BuiltinType::Overload:
763 case BuiltinType::BoundMember:
764 case BuiltinType::PseudoObject:
765 case BuiltinType::UnknownAny:
766 case BuiltinType::BuiltinFn:
767 // This might be a callable.
768 break;
769
770 default:
771 S.Diag(TheCall->getArg(1)->getBeginLoc(),
772 diag::err_expected_callable_argument)
773 << 2 << TheCall->getDirectCallee() << FnArgType;
774 return ExprError();
775 }
776 }
777
778 BuiltinDumpStructGenerator Generator(S, TheCall);
779
780 // Wrap parentheses around the given pointer. This is not necessary for
781 // correct code generation, but it means that when we pretty-print the call
782 // arguments in our diagnostics we will produce '(&s)->n' instead of the
783 // incorrect '&s->n'.
784 Expr *PtrArg = PtrArgResult.get();
785 PtrArg = new (S.Context)
786 ParenExpr(PtrArg->getBeginLoc(),
787 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
788 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
789 return ExprError();
790
791 return Generator.buildWrapper();
792}
793
794static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
795 if (S.checkArgCount(BuiltinCall, 2))
796 return true;
797
798 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
799 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
800 Expr *Call = BuiltinCall->getArg(0);
801 Expr *Chain = BuiltinCall->getArg(1);
802
803 if (Call->getStmtClass() != Stmt::CallExprClass) {
804 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
805 << Call->getSourceRange();
806 return true;
807 }
808
809 auto CE = cast<CallExpr>(Call);
810 if (CE->getCallee()->getType()->isBlockPointerType()) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 const Decl *TargetDecl = CE->getCalleeDecl();
817 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
818 if (FD->getBuiltinID()) {
819 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
820 << Call->getSourceRange();
821 return true;
822 }
823
824 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
825 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
826 << Call->getSourceRange();
827 return true;
828 }
829
830 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
831 if (ChainResult.isInvalid())
832 return true;
833 if (!ChainResult.get()->getType()->isPointerType()) {
834 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
835 << Chain->getSourceRange();
836 return true;
837 }
838
839 QualType ReturnTy = CE->getCallReturnType(S.Context);
840 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
841 QualType BuiltinTy = S.Context.getFunctionType(
842 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
843 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
844
845 Builtin =
846 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
847
848 BuiltinCall->setType(CE->getType());
849 BuiltinCall->setValueKind(CE->getValueKind());
850 BuiltinCall->setObjectKind(CE->getObjectKind());
851 BuiltinCall->setCallee(Builtin);
852 BuiltinCall->setArg(1, ChainResult.get());
853
854 return false;
855}
856
857namespace {
858
859class ScanfDiagnosticFormatHandler
861 // Accepts the argument index (relative to the first destination index) of the
862 // argument whose size we want.
863 using ComputeSizeFunction =
864 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
865
866 // Accepts the argument index (relative to the first destination index), the
867 // destination size, and the source size).
868 using DiagnoseFunction =
869 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
870
871 ComputeSizeFunction ComputeSizeArgument;
872 DiagnoseFunction Diagnose;
873
874public:
875 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
876 DiagnoseFunction Diagnose)
877 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
878
879 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
880 const char *StartSpecifier,
881 unsigned specifierLen) override {
882 if (!FS.consumesDataArgument())
883 return true;
884
885 unsigned NulByte = 0;
886 switch ((FS.getConversionSpecifier().getKind())) {
887 default:
888 return true;
891 NulByte = 1;
892 break;
894 break;
895 }
896
897 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
898 if (FW.getHowSpecified() !=
899 analyze_format_string::OptionalAmount::HowSpecified::Constant)
900 return true;
901
902 unsigned SourceSize = FW.getConstantAmount() + NulByte;
903
904 std::optional<llvm::APSInt> DestSizeAPS =
905 ComputeSizeArgument(FS.getArgIndex());
906 if (!DestSizeAPS)
907 return true;
908
909 unsigned DestSize = DestSizeAPS->getZExtValue();
910
911 if (DestSize < SourceSize)
912 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
913
914 return true;
915 }
916};
917
918class EstimateSizeFormatHandler
920 size_t Size;
921 /// Whether the format string contains Linux kernel's format specifier
922 /// extension.
923 bool IsKernelCompatible = true;
924
925public:
926 EstimateSizeFormatHandler(StringRef Format)
927 : Size(std::min(Format.find(0), Format.size()) +
928 1 /* null byte always written by sprintf */) {}
929
930 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
931 const char *, unsigned SpecifierLen,
932 const TargetInfo &) override {
933
934 const size_t FieldWidth = computeFieldWidth(FS);
935 const size_t Precision = computePrecision(FS);
936
937 // The actual format.
938 switch (FS.getConversionSpecifier().getKind()) {
939 // Just a char.
942 Size += std::max(FieldWidth, (size_t)1);
943 break;
944 // Just an integer.
954 Size += std::max(FieldWidth, Precision);
955 break;
956
957 // %g style conversion switches between %f or %e style dynamically.
958 // %g removes trailing zeros, and does not print decimal point if there are
959 // no digits that follow it. Thus %g can print a single digit.
960 // FIXME: If it is alternative form:
961 // For g and G conversions, trailing zeros are not removed from the result.
964 Size += 1;
965 break;
966
967 // Floating point number in the form '[+]ddd.ddd'.
970 Size += std::max(FieldWidth, 1 /* integer part */ +
971 (Precision ? 1 + Precision
972 : 0) /* period + decimal */);
973 break;
974
975 // Floating point number in the form '[-]d.ddde[+-]dd'.
978 Size +=
979 std::max(FieldWidth,
980 1 /* integer part */ +
981 (Precision ? 1 + Precision : 0) /* period + decimal */ +
982 1 /* e or E letter */ + 2 /* exponent */);
983 break;
984
985 // Floating point number in the form '[-]0xh.hhhhp±dd'.
988 Size +=
989 std::max(FieldWidth,
990 2 /* 0x */ + 1 /* integer part */ +
991 (Precision ? 1 + Precision : 0) /* period + decimal */ +
992 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
993 break;
994
995 // Just a string.
998 Size += FieldWidth;
999 break;
1000
1001 // Just a pointer in the form '0xddd'.
1003 // Linux kernel has its own extesion for `%p` specifier.
1004 // Kernel Document:
1005 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1006 IsKernelCompatible = false;
1007 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1008 break;
1009
1010 // A plain percent.
1012 Size += 1;
1013 break;
1014
1015 default:
1016 break;
1017 }
1018
1019 // If field width is specified, the sign/space is already accounted for
1020 // within the field width, so no additional size is needed.
1021 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1022 Size += 1;
1023
1024 if (FS.hasAlternativeForm()) {
1025 switch (FS.getConversionSpecifier().getKind()) {
1026 // For o conversion, it increases the precision, if and only if necessary,
1027 // to force the first digit of the result to be a zero
1028 // (if the value and precision are both 0, a single 0 is printed)
1030 // For b conversion, a nonzero result has 0b prefixed to it.
1032 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1033 // it.
1036 // Note: even when the prefix is added, if
1037 // (prefix_width <= FieldWidth - formatted_length) holds,
1038 // the prefix does not increase the format
1039 // size. e.g.(("%#3x", 0xf) is "0xf")
1040
1041 // If the result is zero, o, b, x, X adds nothing.
1042 break;
1043 // For a, A, e, E, f, F, g, and G conversions,
1044 // the result of converting a floating-point number always contains a
1045 // decimal-point
1054 Size += (Precision ? 0 : 1);
1055 break;
1056 // For other conversions, the behavior is undefined.
1057 default:
1058 break;
1059 }
1060 }
1061 assert(SpecifierLen <= Size && "no underflow");
1062 Size -= SpecifierLen;
1063 return true;
1064 }
1065
1066 size_t getSizeLowerBound() const { return Size; }
1067 bool isKernelCompatible() const { return IsKernelCompatible; }
1068
1069private:
1070 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1071 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1072 size_t FieldWidth = 0;
1074 FieldWidth = FW.getConstantAmount();
1075 return FieldWidth;
1076 }
1077
1078 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1079 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1080 size_t Precision = 0;
1081
1082 // See man 3 printf for default precision value based on the specifier.
1083 switch (FW.getHowSpecified()) {
1085 switch (FS.getConversionSpecifier().getKind()) {
1086 default:
1087 break;
1091 Precision = 1;
1092 break;
1099 Precision = 1;
1100 break;
1107 Precision = 6;
1108 break;
1110 Precision = 1;
1111 break;
1112 }
1113 break;
1115 Precision = FW.getConstantAmount();
1116 break;
1117 default:
1118 break;
1119 }
1120 return Precision;
1121 }
1122};
1123
1124} // namespace
1125
1126static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1127 StringRef &FormatStrRef, size_t &StrLen,
1128 ASTContext &Context) {
1129 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1130 Format && (Format->isOrdinary() || Format->isUTF8())) {
1131 FormatStrRef = Format->getString();
1132 const ConstantArrayType *T =
1133 Context.getAsConstantArrayType(Format->getType());
1134 assert(T && "String literal not of constant array type!");
1135 size_t TypeSize = T->getZExtSize();
1136 // In case there's a null byte somewhere.
1137 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1138 return true;
1139 }
1140 return false;
1141}
1142
1143void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1144 CallExpr *TheCall) {
1145 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1147 return;
1148
1149 bool UseDABAttr = false;
1150 const FunctionDecl *UseDecl = FD;
1151
1152 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1153 if (DABAttr) {
1154 UseDecl = DABAttr->getFunction();
1155 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1156 UseDABAttr = true;
1157 }
1158
1159 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1160
1161 if (!BuiltinID)
1162 return;
1163
1164 const TargetInfo &TI = getASTContext().getTargetInfo();
1165 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1166
1167 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1168 // If we refer to a diagnose_as_builtin attribute, we need to change the
1169 // argument index to refer to the arguments of the called function. Unless
1170 // the index is out of bounds, which presumably means it's a variadic
1171 // function.
1172 if (!UseDABAttr)
1173 return Index;
1174 unsigned DABIndices = DABAttr->argIndices_size();
1175 unsigned NewIndex = Index < DABIndices
1176 ? DABAttr->argIndices_begin()[Index]
1177 : Index - DABIndices + FD->getNumParams();
1178 if (NewIndex >= TheCall->getNumArgs())
1179 return std::nullopt;
1180 return NewIndex;
1181 };
1182
1183 auto ComputeExplicitObjectSizeArgument =
1184 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1185 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1186 if (!IndexOptional)
1187 return std::nullopt;
1188 unsigned NewIndex = *IndexOptional;
1189 Expr::EvalResult Result;
1190 Expr *SizeArg = TheCall->getArg(NewIndex);
1191 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1192 return std::nullopt;
1193 llvm::APSInt Integer = Result.Val.getInt();
1194 Integer.setIsUnsigned(true);
1195 return Integer;
1196 };
1197
1198 auto ComputeSizeArgument =
1199 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1200 // If the parameter has a pass_object_size attribute, then we should use its
1201 // (potentially) more strict checking mode. Otherwise, conservatively assume
1202 // type 0.
1203 int BOSType = 0;
1204 // This check can fail for variadic functions.
1205 if (Index < FD->getNumParams()) {
1206 if (const auto *POS =
1207 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1208 BOSType = POS->getType();
1209 }
1210
1211 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1212 if (!IndexOptional)
1213 return std::nullopt;
1214 unsigned NewIndex = *IndexOptional;
1215
1216 if (NewIndex >= TheCall->getNumArgs())
1217 return std::nullopt;
1218
1219 const Expr *ObjArg = TheCall->getArg(NewIndex);
1221 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1222 return std::nullopt;
1223
1224 // Get the object size in the target's size_t width.
1225 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1226 };
1227
1228 auto ComputeStrLenArgument =
1229 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1230 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1231 if (!IndexOptional)
1232 return std::nullopt;
1233 unsigned NewIndex = *IndexOptional;
1234
1235 const Expr *ObjArg = TheCall->getArg(NewIndex);
1237 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1238 return std::nullopt;
1239 // Add 1 for null byte.
1240 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1241 };
1242
1243 std::optional<llvm::APSInt> SourceSize;
1244 std::optional<llvm::APSInt> DestinationSize;
1245 unsigned DiagID = 0;
1246 bool IsChkVariant = false;
1247
1248 auto GetFunctionName = [&]() {
1249 std::string FunctionNameStr =
1250 getASTContext().BuiltinInfo.getName(BuiltinID);
1251 llvm::StringRef FunctionName = FunctionNameStr;
1252 // Skim off the details of whichever builtin was called to produce a better
1253 // diagnostic, as it's unlikely that the user wrote the __builtin
1254 // explicitly.
1255 if (IsChkVariant) {
1256 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1257 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1258 } else {
1259 FunctionName.consume_front("__builtin_");
1260 }
1261 return FunctionName.str();
1262 };
1263
1264 switch (BuiltinID) {
1265 default:
1266 return;
1267 case Builtin::BI__builtin_strcat:
1268 case Builtin::BIstrcat:
1269 case Builtin::BI__builtin_stpcpy:
1270 case Builtin::BIstpcpy:
1271 case Builtin::BI__builtin_strcpy:
1272 case Builtin::BIstrcpy: {
1273 DiagID = diag::warn_fortify_strlen_overflow;
1274 SourceSize = ComputeStrLenArgument(1);
1275 DestinationSize = ComputeSizeArgument(0);
1276 break;
1277 }
1278
1279 case Builtin::BI__builtin___strcat_chk:
1280 case Builtin::BI__builtin___stpcpy_chk:
1281 case Builtin::BI__builtin___strcpy_chk: {
1282 DiagID = diag::warn_fortify_strlen_overflow;
1283 SourceSize = ComputeStrLenArgument(1);
1284 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1285 IsChkVariant = true;
1286 break;
1287 }
1288
1289 case Builtin::BIscanf:
1290 case Builtin::BIfscanf:
1291 case Builtin::BIsscanf: {
1292 unsigned FormatIndex = 1;
1293 unsigned DataIndex = 2;
1294 if (BuiltinID == Builtin::BIscanf) {
1295 FormatIndex = 0;
1296 DataIndex = 1;
1297 }
1298
1299 const auto *FormatExpr =
1300 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1301
1302 StringRef FormatStrRef;
1303 size_t StrLen;
1304 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1305 return;
1306
1307 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1308 unsigned SourceSize) {
1309 DiagID = diag::warn_fortify_scanf_overflow;
1310 unsigned Index = ArgIndex + DataIndex;
1311 std::string FunctionName = GetFunctionName();
1312 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1313 PDiag(DiagID) << FunctionName << (Index + 1)
1314 << DestSize << SourceSize);
1315 };
1316
1317 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1318 return ComputeSizeArgument(Index + DataIndex);
1319 };
1320 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1321 const char *FormatBytes = FormatStrRef.data();
1323 FormatBytes + StrLen, getLangOpts(),
1324 Context.getTargetInfo());
1325
1326 // Unlike the other cases, in this one we have already issued the diagnostic
1327 // here, so no need to continue (because unlike the other cases, here the
1328 // diagnostic refers to the argument number).
1329 return;
1330 }
1331
1332 case Builtin::BIsprintf:
1333 case Builtin::BI__builtin___sprintf_chk: {
1334 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1335 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1336
1337 StringRef FormatStrRef;
1338 size_t StrLen;
1339 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1340 EstimateSizeFormatHandler H(FormatStrRef);
1341 const char *FormatBytes = FormatStrRef.data();
1343 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1344 Context.getTargetInfo(), false)) {
1345 DiagID = H.isKernelCompatible()
1346 ? diag::warn_format_overflow
1347 : diag::warn_format_overflow_non_kprintf;
1348 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1349 .extOrTrunc(SizeTypeWidth);
1350 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1351 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1352 IsChkVariant = true;
1353 } else {
1354 DestinationSize = ComputeSizeArgument(0);
1355 }
1356 break;
1357 }
1358 }
1359 return;
1360 }
1361 case Builtin::BI__builtin___memcpy_chk:
1362 case Builtin::BI__builtin___memmove_chk:
1363 case Builtin::BI__builtin___memset_chk:
1364 case Builtin::BI__builtin___strlcat_chk:
1365 case Builtin::BI__builtin___strlcpy_chk:
1366 case Builtin::BI__builtin___strncat_chk:
1367 case Builtin::BI__builtin___strncpy_chk:
1368 case Builtin::BI__builtin___stpncpy_chk:
1369 case Builtin::BI__builtin___memccpy_chk:
1370 case Builtin::BI__builtin___mempcpy_chk: {
1371 DiagID = diag::warn_builtin_chk_overflow;
1372 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1373 DestinationSize =
1374 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1375 IsChkVariant = true;
1376 break;
1377 }
1378
1379 case Builtin::BI__builtin___snprintf_chk:
1380 case Builtin::BI__builtin___vsnprintf_chk: {
1381 DiagID = diag::warn_builtin_chk_overflow;
1382 SourceSize = ComputeExplicitObjectSizeArgument(1);
1383 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1384 IsChkVariant = true;
1385 break;
1386 }
1387
1388 case Builtin::BIstrncat:
1389 case Builtin::BI__builtin_strncat:
1390 case Builtin::BIstrncpy:
1391 case Builtin::BI__builtin_strncpy:
1392 case Builtin::BIstpncpy:
1393 case Builtin::BI__builtin_stpncpy: {
1394 // Whether these functions overflow depends on the runtime strlen of the
1395 // string, not just the buffer size, so emitting the "always overflow"
1396 // diagnostic isn't quite right. We should still diagnose passing a buffer
1397 // size larger than the destination buffer though; this is a runtime abort
1398 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1399 DiagID = diag::warn_fortify_source_size_mismatch;
1400 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1401 DestinationSize = ComputeSizeArgument(0);
1402 break;
1403 }
1404
1405 case Builtin::BImemcpy:
1406 case Builtin::BI__builtin_memcpy:
1407 case Builtin::BImemmove:
1408 case Builtin::BI__builtin_memmove:
1409 case Builtin::BImemset:
1410 case Builtin::BI__builtin_memset:
1411 case Builtin::BImempcpy:
1412 case Builtin::BI__builtin_mempcpy: {
1413 DiagID = diag::warn_fortify_source_overflow;
1414 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1415 DestinationSize = ComputeSizeArgument(0);
1416 break;
1417 }
1418 case Builtin::BIsnprintf:
1419 case Builtin::BI__builtin_snprintf:
1420 case Builtin::BIvsnprintf:
1421 case Builtin::BI__builtin_vsnprintf: {
1422 DiagID = diag::warn_fortify_source_size_mismatch;
1423 SourceSize = ComputeExplicitObjectSizeArgument(1);
1424 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1425 StringRef FormatStrRef;
1426 size_t StrLen;
1427 if (SourceSize &&
1428 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1429 EstimateSizeFormatHandler H(FormatStrRef);
1430 const char *FormatBytes = FormatStrRef.data();
1432 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1433 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1434 llvm::APSInt FormatSize =
1435 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1436 .extOrTrunc(SizeTypeWidth);
1437 if (FormatSize > *SourceSize && *SourceSize != 0) {
1438 unsigned TruncationDiagID =
1439 H.isKernelCompatible() ? diag::warn_format_truncation
1440 : diag::warn_format_truncation_non_kprintf;
1441 SmallString<16> SpecifiedSizeStr;
1442 SmallString<16> FormatSizeStr;
1443 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1444 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1445 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1446 PDiag(TruncationDiagID)
1447 << GetFunctionName() << SpecifiedSizeStr
1448 << FormatSizeStr);
1449 }
1450 }
1451 }
1452 DestinationSize = ComputeSizeArgument(0);
1453 }
1454 }
1455
1456 if (!SourceSize || !DestinationSize ||
1457 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1458 return;
1459
1460 std::string FunctionName = GetFunctionName();
1461
1462 SmallString<16> DestinationStr;
1463 SmallString<16> SourceStr;
1464 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1465 SourceSize->toString(SourceStr, /*Radix=*/10);
1466 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1467 PDiag(DiagID)
1468 << FunctionName << DestinationStr << SourceStr);
1469}
1470
1471static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1472 Scope::ScopeFlags NeededScopeFlags,
1473 unsigned DiagID) {
1474 // Scopes aren't available during instantiation. Fortunately, builtin
1475 // functions cannot be template args so they cannot be formed through template
1476 // instantiation. Therefore checking once during the parse is sufficient.
1477 if (SemaRef.inTemplateInstantiation())
1478 return false;
1479
1480 Scope *S = SemaRef.getCurScope();
1481 while (S && !S->isSEHExceptScope())
1482 S = S->getParent();
1483 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1484 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1485 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1486 << DRE->getDecl()->getIdentifier();
1487 return true;
1488 }
1489
1490 return false;
1491}
1492
1493// In OpenCL, __builtin_alloca_* should return a pointer to address space
1494// that corresponds to the stack address space i.e private address space.
1495static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1496 QualType RT = TheCall->getType();
1497 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1498 "__builtin_alloca has invalid address space");
1499
1500 RT = RT->getPointeeType();
1502 TheCall->setType(S.Context.getPointerType(RT));
1503}
1504
1505static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1506 if (S.checkArgCountAtLeast(TheCall, 1))
1507 return true;
1508
1509 for (Expr *Arg : TheCall->arguments()) {
1510 // If argument is dependent on a template parameter, we can't resolve now.
1511 if (Arg->isTypeDependent() || Arg->isValueDependent())
1512 continue;
1513 // Reject void types.
1514 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1515 if (ArgTy->isVoidType())
1516 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1517 }
1518
1519 TheCall->setType(S.Context.getSizeType());
1520 return false;
1521}
1522
1523namespace {
1524enum PointerAuthOpKind {
1525 PAO_Strip,
1526 PAO_Sign,
1527 PAO_Auth,
1528 PAO_SignGeneric,
1529 PAO_Discriminator,
1530 PAO_BlendPointer,
1531 PAO_BlendInteger
1532};
1533}
1534
1536 if (getLangOpts().PointerAuthIntrinsics)
1537 return false;
1538
1539 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1540 return true;
1541}
1542
1543static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1545}
1546
1547static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1548 // Convert it to type 'int'.
1549 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1550 return true;
1551
1552 // Value-dependent expressions are okay; wait for template instantiation.
1553 if (Arg->isValueDependent())
1554 return false;
1555
1556 unsigned KeyValue;
1557 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1558}
1559
1561 // Attempt to constant-evaluate the expression.
1562 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1563 if (!KeyValue) {
1564 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1565 << 0 << Arg->getSourceRange();
1566 return true;
1567 }
1568
1569 // Ask the target to validate the key parameter.
1570 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1572 {
1573 llvm::raw_svector_ostream Str(Value);
1574 Str << *KeyValue;
1575 }
1576
1577 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1578 << Value << Arg->getSourceRange();
1579 return true;
1580 }
1581
1582 Result = KeyValue->getZExtValue();
1583 return false;
1584}
1585
1588 unsigned &IntVal) {
1589 if (!Arg) {
1590 IntVal = 0;
1591 return true;
1592 }
1593
1594 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1595 if (!Result) {
1596 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1597 return false;
1598 }
1599
1600 unsigned Max;
1601 bool IsAddrDiscArg = false;
1602
1603 switch (Kind) {
1605 Max = 1;
1606 IsAddrDiscArg = true;
1607 break;
1610 break;
1611 };
1612
1614 if (IsAddrDiscArg)
1615 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1616 << Result->getExtValue();
1617 else
1618 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1619 << Result->getExtValue() << Max;
1620
1621 return false;
1622 };
1623
1624 IntVal = Result->getZExtValue();
1625 return true;
1626}
1627
1628static std::pair<const ValueDecl *, CharUnits>
1630 // Must evaluate as a pointer.
1631 Expr::EvalResult Result;
1632 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1633 return {nullptr, CharUnits()};
1634
1635 const auto *BaseDecl =
1636 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1637 if (!BaseDecl)
1638 return {nullptr, CharUnits()};
1639
1640 return {BaseDecl, Result.Val.getLValueOffset()};
1641}
1642
1643static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1644 bool RequireConstant = false) {
1645 if (Arg->hasPlaceholderType()) {
1647 if (R.isInvalid())
1648 return true;
1649 Arg = R.get();
1650 }
1651
1652 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1653 return OpKind != PAO_BlendInteger;
1654 };
1655 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1656 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1657 OpKind == PAO_SignGeneric;
1658 };
1659
1660 // Require the value to have the right range of type.
1661 QualType ExpectedTy;
1662 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1663 ExpectedTy = Arg->getType().getUnqualifiedType();
1664 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1665 ExpectedTy = S.Context.VoidPtrTy;
1666 } else if (AllowsInteger(OpKind) &&
1668 ExpectedTy = S.Context.getUIntPtrType();
1669
1670 } else {
1671 // Diagnose the failures.
1672 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1673 << unsigned(OpKind == PAO_Discriminator ? 1
1674 : OpKind == PAO_BlendPointer ? 2
1675 : OpKind == PAO_BlendInteger ? 3
1676 : 0)
1677 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1678 << Arg->getType() << Arg->getSourceRange();
1679 return true;
1680 }
1681
1682 // Convert to that type. This should just be an lvalue-to-rvalue
1683 // conversion.
1684 if (convertArgumentToType(S, Arg, ExpectedTy))
1685 return true;
1686
1687 if (!RequireConstant) {
1688 // Warn about null pointers for non-generic sign and auth operations.
1689 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1691 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1692 ? diag::warn_ptrauth_sign_null_pointer
1693 : diag::warn_ptrauth_auth_null_pointer)
1694 << Arg->getSourceRange();
1695 }
1696
1697 return false;
1698 }
1699
1700 // Perform special checking on the arguments to ptrauth_sign_constant.
1701
1702 // The main argument.
1703 if (OpKind == PAO_Sign) {
1704 // Require the value we're signing to have a special form.
1705 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1706 bool Invalid;
1707
1708 // Must be rooted in a declaration reference.
1709 if (!BaseDecl)
1710 Invalid = true;
1711
1712 // If it's a function declaration, we can't have an offset.
1713 else if (isa<FunctionDecl>(BaseDecl))
1714 Invalid = !Offset.isZero();
1715
1716 // Otherwise we're fine.
1717 else
1718 Invalid = false;
1719
1720 if (Invalid)
1721 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1722 return Invalid;
1723 }
1724
1725 // The discriminator argument.
1726 assert(OpKind == PAO_Discriminator);
1727
1728 // Must be a pointer or integer or blend thereof.
1729 Expr *Pointer = nullptr;
1730 Expr *Integer = nullptr;
1731 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1732 if (Call->getBuiltinCallee() ==
1733 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1734 Pointer = Call->getArg(0);
1735 Integer = Call->getArg(1);
1736 }
1737 }
1738 if (!Pointer && !Integer) {
1739 if (Arg->getType()->isPointerType())
1740 Pointer = Arg;
1741 else
1742 Integer = Arg;
1743 }
1744
1745 // Check the pointer.
1746 bool Invalid = false;
1747 if (Pointer) {
1748 assert(Pointer->getType()->isPointerType());
1749
1750 // TODO: if we're initializing a global, check that the address is
1751 // somehow related to what we're initializing. This probably will
1752 // never really be feasible and we'll have to catch it at link-time.
1753 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1754 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1755 Invalid = true;
1756 }
1757
1758 // Check the integer.
1759 if (Integer) {
1760 assert(Integer->getType()->isIntegerType());
1761 if (!Integer->isEvaluatable(S.Context))
1762 Invalid = true;
1763 }
1764
1765 if (Invalid)
1766 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1767 return Invalid;
1768}
1769
1771 if (S.checkArgCount(Call, 2))
1772 return ExprError();
1774 return ExprError();
1775 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1776 checkPointerAuthKey(S, Call->getArgs()[1]))
1777 return ExprError();
1778
1779 Call->setType(Call->getArgs()[0]->getType());
1780 return Call;
1781}
1782
1784 if (S.checkArgCount(Call, 2))
1785 return ExprError();
1787 return ExprError();
1788 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1789 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1790 return ExprError();
1791
1792 Call->setType(S.Context.getUIntPtrType());
1793 return Call;
1794}
1795
1797 if (S.checkArgCount(Call, 2))
1798 return ExprError();
1800 return ExprError();
1801 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1802 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1803 return ExprError();
1804
1805 Call->setType(S.Context.getUIntPtrType());
1806 return Call;
1807}
1808
1810 PointerAuthOpKind OpKind,
1811 bool RequireConstant) {
1812 if (S.checkArgCount(Call, 3))
1813 return ExprError();
1815 return ExprError();
1816 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1817 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1818 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1819 RequireConstant))
1820 return ExprError();
1821
1822 Call->setType(Call->getArgs()[0]->getType());
1823 return Call;
1824}
1825
1827 if (S.checkArgCount(Call, 5))
1828 return ExprError();
1830 return ExprError();
1831 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1832 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1833 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1834 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1835 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1836 return ExprError();
1837
1838 Call->setType(Call->getArgs()[0]->getType());
1839 return Call;
1840}
1841
1844 return ExprError();
1845
1846 // We've already performed normal call type-checking.
1847 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1848
1849 // Operand must be an ordinary or UTF-8 string literal.
1850 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1851 if (!Literal || Literal->getCharByteWidth() != 1) {
1852 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1853 << (Literal ? 1 : 0) << Arg->getSourceRange();
1854 return ExprError();
1855 }
1856
1857 return Call;
1858}
1859
1861 if (S.checkArgCount(Call, 1))
1862 return ExprError();
1863 Expr *FirstArg = Call->getArg(0);
1864 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1865 if (FirstValue.isInvalid())
1866 return ExprError();
1867 Call->setArg(0, FirstValue.get());
1868 QualType FirstArgType = FirstArg->getType();
1869 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1870 FirstArgType = S.Context.getDecayedType(FirstArgType);
1871
1872 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1873 if (!FirstArgRecord) {
1874 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1875 << /*isPolymorphic=*/0 << FirstArgType;
1876 return ExprError();
1877 }
1878 if (S.RequireCompleteType(
1879 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1880 diag::err_get_vtable_pointer_requires_complete_type)) {
1881 return ExprError();
1882 }
1883
1884 if (!FirstArgRecord->isPolymorphic()) {
1885 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1886 << /*isPolymorphic=*/1 << FirstArgRecord;
1887 return ExprError();
1888 }
1890 Call->setType(ReturnType);
1891 return Call;
1892}
1893
1895 if (S.checkArgCount(TheCall, 1))
1896 return ExprError();
1897
1898 // Compute __builtin_launder's parameter type from the argument.
1899 // The parameter type is:
1900 // * The type of the argument if it's not an array or function type,
1901 // Otherwise,
1902 // * The decayed argument type.
1903 QualType ParamTy = [&]() {
1904 QualType ArgTy = TheCall->getArg(0)->getType();
1905 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1906 return S.Context.getPointerType(Ty->getElementType());
1907 if (ArgTy->isFunctionType()) {
1908 return S.Context.getPointerType(ArgTy);
1909 }
1910 return ArgTy;
1911 }();
1912
1913 TheCall->setType(ParamTy);
1914
1915 auto DiagSelect = [&]() -> std::optional<unsigned> {
1916 if (!ParamTy->isPointerType())
1917 return 0;
1918 if (ParamTy->isFunctionPointerType())
1919 return 1;
1920 if (ParamTy->isVoidPointerType())
1921 return 2;
1922 return std::optional<unsigned>{};
1923 }();
1924 if (DiagSelect) {
1925 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1926 << *DiagSelect << TheCall->getSourceRange();
1927 return ExprError();
1928 }
1929
1930 // We either have an incomplete class type, or we have a class template
1931 // whose instantiation has not been forced. Example:
1932 //
1933 // template <class T> struct Foo { T value; };
1934 // Foo<int> *p = nullptr;
1935 // auto *d = __builtin_launder(p);
1936 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1937 diag::err_incomplete_type))
1938 return ExprError();
1939
1940 assert(ParamTy->getPointeeType()->isObjectType() &&
1941 "Unhandled non-object pointer case");
1942
1943 InitializedEntity Entity =
1945 ExprResult Arg =
1946 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1947 if (Arg.isInvalid())
1948 return ExprError();
1949 TheCall->setArg(0, Arg.get());
1950
1951 return TheCall;
1952}
1953
1955 if (S.checkArgCount(TheCall, 1))
1956 return ExprError();
1957
1959 if (Arg.isInvalid())
1960 return ExprError();
1961 QualType ParamTy = Arg.get()->getType();
1962 TheCall->setArg(0, Arg.get());
1963 TheCall->setType(S.Context.BoolTy);
1964
1965 // Only accept pointers to objects as arguments, which should have object
1966 // pointer or void pointer types.
1967 if (const auto *PT = ParamTy->getAs<PointerType>()) {
1968 // LWG4138: Function pointer types not allowed
1969 if (PT->getPointeeType()->isFunctionType()) {
1970 S.Diag(TheCall->getArg(0)->getExprLoc(),
1971 diag::err_builtin_is_within_lifetime_invalid_arg)
1972 << 1;
1973 return ExprError();
1974 }
1975 // Disallow VLAs too since those shouldn't be able to
1976 // be a template parameter for `std::is_within_lifetime`
1977 if (PT->getPointeeType()->isVariableArrayType()) {
1978 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
1979 << 1 << "__builtin_is_within_lifetime";
1980 return ExprError();
1981 }
1982 } else {
1983 S.Diag(TheCall->getArg(0)->getExprLoc(),
1984 diag::err_builtin_is_within_lifetime_invalid_arg)
1985 << 0;
1986 return ExprError();
1987 }
1988 return TheCall;
1989}
1990
1992 if (S.checkArgCount(TheCall, 3))
1993 return ExprError();
1994
1995 QualType Dest = TheCall->getArg(0)->getType();
1996 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
1997 S.Diag(TheCall->getArg(0)->getExprLoc(),
1998 diag::err_builtin_trivially_relocate_invalid_arg_type)
1999 << /*a pointer*/ 0;
2000 return ExprError();
2001 }
2002
2003 QualType T = Dest->getPointeeType();
2004 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2005 diag::err_incomplete_type))
2006 return ExprError();
2007
2008 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2009 T->isIncompleteArrayType()) {
2010 S.Diag(TheCall->getArg(0)->getExprLoc(),
2011 diag::err_builtin_trivially_relocate_invalid_arg_type)
2012 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2013 return ExprError();
2014 }
2015
2016 TheCall->setType(Dest);
2017
2018 QualType Src = TheCall->getArg(1)->getType();
2019 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2020 S.Diag(TheCall->getArg(1)->getExprLoc(),
2021 diag::err_builtin_trivially_relocate_invalid_arg_type)
2022 << /*the same*/ 3;
2023 return ExprError();
2024 }
2025
2026 Expr *SizeExpr = TheCall->getArg(2);
2027 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2028 if (Size.isInvalid())
2029 return ExprError();
2030
2031 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2032 if (Size.isInvalid())
2033 return ExprError();
2034 SizeExpr = Size.get();
2035 TheCall->setArg(2, SizeExpr);
2036
2037 return TheCall;
2038}
2039
2040// Emit an error and return true if the current object format type is in the
2041// list of unsupported types.
2043 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2044 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2045 llvm::Triple::ObjectFormatType CurObjFormat =
2046 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2047 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2048 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2049 << TheCall->getSourceRange();
2050 return true;
2051 }
2052 return false;
2053}
2054
2055// Emit an error and return true if the current architecture is not in the list
2056// of supported architectures.
2057static bool
2059 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2060 llvm::Triple::ArchType CurArch =
2061 S.getASTContext().getTargetInfo().getTriple().getArch();
2062 if (llvm::is_contained(SupportedArchs, CurArch))
2063 return false;
2064 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2065 << TheCall->getSourceRange();
2066 return true;
2067}
2068
2069static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2070 SourceLocation CallSiteLoc);
2071
2072bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2073 CallExpr *TheCall) {
2074 switch (TI.getTriple().getArch()) {
2075 default:
2076 // Some builtins don't require additional checking, so just consider these
2077 // acceptable.
2078 return false;
2079 case llvm::Triple::arm:
2080 case llvm::Triple::armeb:
2081 case llvm::Triple::thumb:
2082 case llvm::Triple::thumbeb:
2083 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2084 case llvm::Triple::aarch64:
2085 case llvm::Triple::aarch64_32:
2086 case llvm::Triple::aarch64_be:
2087 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2088 case llvm::Triple::bpfeb:
2089 case llvm::Triple::bpfel:
2090 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2091 case llvm::Triple::dxil:
2092 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2093 case llvm::Triple::hexagon:
2094 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2095 case llvm::Triple::mips:
2096 case llvm::Triple::mipsel:
2097 case llvm::Triple::mips64:
2098 case llvm::Triple::mips64el:
2099 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2100 case llvm::Triple::spirv:
2101 case llvm::Triple::spirv32:
2102 case llvm::Triple::spirv64:
2103 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2104 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2105 return false;
2106 case llvm::Triple::systemz:
2107 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2108 case llvm::Triple::x86:
2109 case llvm::Triple::x86_64:
2110 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2111 case llvm::Triple::ppc:
2112 case llvm::Triple::ppcle:
2113 case llvm::Triple::ppc64:
2114 case llvm::Triple::ppc64le:
2115 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2116 case llvm::Triple::amdgcn:
2117 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2118 case llvm::Triple::riscv32:
2119 case llvm::Triple::riscv64:
2120 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2121 case llvm::Triple::loongarch32:
2122 case llvm::Triple::loongarch64:
2123 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2124 TheCall);
2125 case llvm::Triple::wasm32:
2126 case llvm::Triple::wasm64:
2127 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2128 case llvm::Triple::nvptx:
2129 case llvm::Triple::nvptx64:
2130 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2131 }
2132}
2133
2135 return T->isDependentType() ||
2136 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2137}
2138
2139// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2140// not a valid type, emit an error message and return true. Otherwise return
2141// false.
2142static bool
2145 int ArgOrdinal) {
2146 QualType EltTy = ArgTy;
2147 if (auto *VecTy = EltTy->getAs<VectorType>())
2148 EltTy = VecTy->getElementType();
2149
2150 switch (ArgTyRestr) {
2152 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2153 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2154 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2155 << ArgTy;
2156 }
2157 break;
2159 if (!EltTy->isRealFloatingType()) {
2160 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2161 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2162 << /* floating-point */ 1 << ArgTy;
2163 }
2164 break;
2166 if (!EltTy->isIntegerType()) {
2167 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2168 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2169 << /* no fp */ 0 << ArgTy;
2170 }
2171 break;
2173 if (EltTy->isUnsignedIntegerType()) {
2174 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2175 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2176 << /* or fp */ 1 << ArgTy;
2177 }
2178 break;
2179 }
2180
2181 return false;
2182}
2183
2184/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2185/// This checks that the target supports the builtin and that the string
2186/// argument is constant and valid.
2187static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2188 const TargetInfo *AuxTI, unsigned BuiltinID) {
2189 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2190 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2191 "Expecting __builtin_cpu_...");
2192
2193 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2194 const TargetInfo *TheTI = &TI;
2195 auto SupportsBI = [=](const TargetInfo *TInfo) {
2196 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2197 (!IsCPUSupports && TInfo->supportsCpuIs()));
2198 };
2199 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2200 TheTI = AuxTI;
2201
2202 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2203 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2204 return S.Diag(TheCall->getBeginLoc(),
2205 TI.getTriple().isOSAIX()
2206 ? diag::err_builtin_aix_os_unsupported
2207 : diag::err_builtin_target_unsupported)
2208 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2209
2210 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2211 // Check if the argument is a string literal.
2212 if (!isa<StringLiteral>(Arg))
2213 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2214 << Arg->getSourceRange();
2215
2216 // Check the contents of the string.
2217 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2218 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2219 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2220 << Arg->getSourceRange();
2221 return false;
2222 }
2223 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2224 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2225 << Arg->getSourceRange();
2226 return false;
2227}
2228
2229/// Checks that __builtin_bswapg was called with a single argument, which is an
2230/// unsigned integer, and overrides the return value type to the integer type.
2231static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2232 if (S.checkArgCount(TheCall, 1))
2233 return true;
2234 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2235 if (ArgRes.isInvalid())
2236 return true;
2237
2238 Expr *Arg = ArgRes.get();
2239 TheCall->setArg(0, Arg);
2240 if (Arg->isTypeDependent())
2241 return false;
2242
2243 QualType ArgTy = Arg->getType();
2244
2245 if (!ArgTy->isIntegerType()) {
2246 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2247 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2248 << ArgTy;
2249 return true;
2250 }
2251 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2252 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8) {
2253 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2254 << ArgTy << BT->getNumBits();
2255 return true;
2256 }
2257 }
2258 TheCall->setType(ArgTy);
2259 return false;
2260}
2261
2262/// Checks that __builtin_popcountg was called with a single argument, which is
2263/// an unsigned integer.
2264static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2265 if (S.checkArgCount(TheCall, 1))
2266 return true;
2267
2268 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2269 if (ArgRes.isInvalid())
2270 return true;
2271
2272 Expr *Arg = ArgRes.get();
2273 TheCall->setArg(0, Arg);
2274
2275 QualType ArgTy = Arg->getType();
2276
2277 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2278 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2279 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2280 << ArgTy;
2281 return true;
2282 }
2283 return false;
2284}
2285
2286/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2287/// an unsigned integer, and an optional second argument, which is promoted to
2288/// an 'int'.
2289static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2290 if (S.checkArgCountRange(TheCall, 1, 2))
2291 return true;
2292
2293 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2294 if (Arg0Res.isInvalid())
2295 return true;
2296
2297 Expr *Arg0 = Arg0Res.get();
2298 TheCall->setArg(0, Arg0);
2299
2300 QualType Arg0Ty = Arg0->getType();
2301
2302 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2303 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2304 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2305 << Arg0Ty;
2306 return true;
2307 }
2308
2309 if (TheCall->getNumArgs() > 1) {
2310 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2311 if (Arg1Res.isInvalid())
2312 return true;
2313
2314 Expr *Arg1 = Arg1Res.get();
2315 TheCall->setArg(1, Arg1);
2316
2317 QualType Arg1Ty = Arg1->getType();
2318
2319 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2320 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2321 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2322 return true;
2323 }
2324 }
2325
2326 return false;
2327}
2328
2329static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2330 unsigned Pos, bool AllowConst,
2331 bool AllowAS) {
2332 QualType MaskTy = MaskArg->getType();
2333 if (!MaskTy->isExtVectorBoolType())
2334 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2335 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2336 << MaskTy;
2337
2338 QualType PtrTy = PtrArg->getType();
2339 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2340 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2341 << Pos << "scalar pointer";
2342
2343 QualType PointeeTy = PtrTy->getPointeeType();
2344 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2345 (!AllowConst && PointeeTy.isConstQualified()) ||
2346 (!AllowAS && PointeeTy.hasAddressSpace())) {
2349 return S.Diag(PtrArg->getExprLoc(),
2350 diag::err_typecheck_convert_incompatible)
2351 << PtrTy << Target << /*different qualifiers=*/5
2352 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2353 << PtrTy << Target;
2354 }
2355 return false;
2356}
2357
2358static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2359 bool TypeDependent = false;
2360 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2361 ExprResult Converted =
2363 if (Converted.isInvalid())
2364 return true;
2365 TheCall->setArg(Arg, Converted.get());
2366 TypeDependent |= Converted.get()->isTypeDependent();
2367 }
2368
2369 if (TypeDependent)
2370 TheCall->setType(S.Context.DependentTy);
2371 return false;
2372}
2373
2375 if (S.checkArgCountRange(TheCall, 2, 3))
2376 return ExprError();
2377
2378 if (ConvertMaskedBuiltinArgs(S, TheCall))
2379 return ExprError();
2380
2381 Expr *MaskArg = TheCall->getArg(0);
2382 Expr *PtrArg = TheCall->getArg(1);
2383 if (TheCall->isTypeDependent())
2384 return TheCall;
2385
2386 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2387 TheCall->getBuiltinCallee() ==
2388 Builtin::BI__builtin_masked_load))
2389 return ExprError();
2390
2391 QualType MaskTy = MaskArg->getType();
2392 QualType PtrTy = PtrArg->getType();
2393 QualType PointeeTy = PtrTy->getPointeeType();
2394 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2395
2397 MaskVecTy->getNumElements());
2398 if (TheCall->getNumArgs() == 3) {
2399 Expr *PassThruArg = TheCall->getArg(2);
2400 QualType PassThruTy = PassThruArg->getType();
2401 if (!S.Context.hasSameType(PassThruTy, RetTy))
2402 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2403 << /* third argument */ 3 << RetTy;
2404 }
2405
2406 TheCall->setType(RetTy);
2407 return TheCall;
2408}
2409
2411 if (S.checkArgCount(TheCall, 3))
2412 return ExprError();
2413
2414 if (ConvertMaskedBuiltinArgs(S, TheCall))
2415 return ExprError();
2416
2417 Expr *MaskArg = TheCall->getArg(0);
2418 Expr *ValArg = TheCall->getArg(1);
2419 Expr *PtrArg = TheCall->getArg(2);
2420 if (TheCall->isTypeDependent())
2421 return TheCall;
2422
2423 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2424 TheCall->getBuiltinCallee() ==
2425 Builtin::BI__builtin_masked_store))
2426 return ExprError();
2427
2428 QualType MaskTy = MaskArg->getType();
2429 QualType PtrTy = PtrArg->getType();
2430 QualType ValTy = ValArg->getType();
2431 if (!ValTy->isVectorType())
2432 return ExprError(
2433 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2434 << 2 << "vector");
2435
2436 QualType PointeeTy = PtrTy->getPointeeType();
2437 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2438 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2439 MaskVecTy->getNumElements());
2440 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2441 MemoryTy.getUnqualifiedType()))
2442 return ExprError(S.Diag(TheCall->getBeginLoc(),
2443 diag::err_vec_builtin_incompatible_vector)
2444 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2445 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2446 TheCall->getArg(1)->getEndLoc()));
2447
2448 TheCall->setType(S.Context.VoidTy);
2449 return TheCall;
2450}
2451
2453 if (S.checkArgCountRange(TheCall, 3, 4))
2454 return ExprError();
2455
2456 if (ConvertMaskedBuiltinArgs(S, TheCall))
2457 return ExprError();
2458
2459 Expr *MaskArg = TheCall->getArg(0);
2460 Expr *IdxArg = TheCall->getArg(1);
2461 Expr *PtrArg = TheCall->getArg(2);
2462 if (TheCall->isTypeDependent())
2463 return TheCall;
2464
2465 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2466 /*AllowAS=*/true))
2467 return ExprError();
2468
2469 QualType IdxTy = IdxArg->getType();
2470 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2471 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2472 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2473 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2474 << IdxTy;
2475
2476 QualType MaskTy = MaskArg->getType();
2477 QualType PtrTy = PtrArg->getType();
2478 QualType PointeeTy = PtrTy->getPointeeType();
2479 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2480 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2481 return ExprError(
2482 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2484 TheCall->getBuiltinCallee())
2485 << MaskTy << IdxTy);
2486
2488 MaskVecTy->getNumElements());
2489 if (TheCall->getNumArgs() == 4) {
2490 Expr *PassThruArg = TheCall->getArg(3);
2491 QualType PassThruTy = PassThruArg->getType();
2492 if (!S.Context.hasSameType(PassThruTy, RetTy))
2493 return S.Diag(PassThruArg->getExprLoc(),
2494 diag::err_vec_masked_load_store_ptr)
2495 << /* fourth argument */ 4 << RetTy;
2496 }
2497
2498 TheCall->setType(RetTy);
2499 return TheCall;
2500}
2501
2503 if (S.checkArgCount(TheCall, 4))
2504 return ExprError();
2505
2506 if (ConvertMaskedBuiltinArgs(S, TheCall))
2507 return ExprError();
2508
2509 Expr *MaskArg = TheCall->getArg(0);
2510 Expr *IdxArg = TheCall->getArg(1);
2511 Expr *ValArg = TheCall->getArg(2);
2512 Expr *PtrArg = TheCall->getArg(3);
2513 if (TheCall->isTypeDependent())
2514 return TheCall;
2515
2516 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2517 /*AllowAS=*/true))
2518 return ExprError();
2519
2520 QualType IdxTy = IdxArg->getType();
2521 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2522 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2523 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2524 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2525 << IdxTy;
2526
2527 QualType ValTy = ValArg->getType();
2528 QualType MaskTy = MaskArg->getType();
2529 QualType PtrTy = PtrArg->getType();
2530 QualType PointeeTy = PtrTy->getPointeeType();
2531
2532 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2533 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2534 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2535 return ExprError(
2536 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2538 TheCall->getBuiltinCallee())
2539 << MaskTy << IdxTy);
2540 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2541 return ExprError(
2542 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2544 TheCall->getBuiltinCallee())
2545 << MaskTy << ValTy);
2546
2548 MaskVecTy->getNumElements());
2549 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2550 return ExprError(S.Diag(TheCall->getBeginLoc(),
2551 diag::err_vec_builtin_incompatible_vector)
2552 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2553 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2554 TheCall->getArg(1)->getEndLoc()));
2555
2556 TheCall->setType(S.Context.VoidTy);
2557 return TheCall;
2558}
2559
2561 SourceLocation Loc = TheCall->getBeginLoc();
2562 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2563 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2564
2565 if (Args.size() == 0) {
2566 S.Diag(TheCall->getBeginLoc(),
2567 diag::err_typecheck_call_too_few_args_at_least)
2568 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2569 << /*is_non_object=*/0 << TheCall->getSourceRange();
2570 return ExprError();
2571 }
2572
2573 QualType FuncT = Args[0]->getType();
2574
2575 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2576 if (Args.size() < 2) {
2577 S.Diag(TheCall->getBeginLoc(),
2578 diag::err_typecheck_call_too_few_args_at_least)
2579 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2580 << /*is_non_object=*/0 << TheCall->getSourceRange();
2581 return ExprError();
2582 }
2583
2584 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2585 QualType ObjectT = Args[1]->getType();
2586
2587 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2588 return ExprError();
2589
2590 ExprResult ObjectArg = [&]() -> ExprResult {
2591 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2592 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2593 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2594 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2595 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2596 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2597 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2598 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2599 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2600 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2601 return Args[1];
2602 }
2603
2604 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2605 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2606 // reference_wrapper;
2607 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2608 if (RD->isInStdNamespace() &&
2609 RD->getDeclName().getAsString() == "reference_wrapper") {
2610 CXXScopeSpec SS;
2611 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2612 UnqualifiedId GetID;
2613 GetID.setIdentifier(GetName, Loc);
2614
2616 S.getCurScope(), Args[1], Loc, tok::period, SS,
2617 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2618
2619 if (MemExpr.isInvalid())
2620 return ExprError();
2621
2622 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2623 }
2624 }
2625
2626 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2627 // class T and t1 does not satisfy the previous two items;
2628
2629 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2630 }();
2631
2632 if (ObjectArg.isInvalid())
2633 return ExprError();
2634
2635 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2636 tok::periodstar, ObjectArg.get(), Args[0]);
2637 if (BinOp.isInvalid())
2638 return ExprError();
2639
2640 if (MPT->isMemberDataPointer())
2641 return BinOp;
2642
2643 auto *MemCall = new (S.Context)
2645
2646 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2647 Args.drop_front(2), TheCall->getRParenLoc());
2648 }
2649 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2650 Args.drop_front(), TheCall->getRParenLoc());
2651}
2652
2653// Performs a similar job to Sema::UsualUnaryConversions, but without any
2654// implicit promotion of integral/enumeration types.
2656 // First, convert to an r-value.
2658 if (Res.isInvalid())
2659 return ExprError();
2660
2661 // Promote floating-point types.
2662 return S.UsualUnaryFPConversions(Res.get());
2663}
2664
2666Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2667 CallExpr *TheCall) {
2668 ExprResult TheCallResult(TheCall);
2669
2670 // Find out if any arguments are required to be integer constant expressions.
2671 unsigned ICEArguments = 0;
2673 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2675 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2676
2677 // If any arguments are required to be ICE's, check and diagnose.
2678 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2679 // Skip arguments not required to be ICE's.
2680 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2681
2682 llvm::APSInt Result;
2683 // If we don't have enough arguments, continue so we can issue better
2684 // diagnostic in checkArgCount(...)
2685 if (ArgNo < TheCall->getNumArgs() &&
2686 BuiltinConstantArg(TheCall, ArgNo, Result))
2687 return true;
2688 ICEArguments &= ~(1 << ArgNo);
2689 }
2690
2691 FPOptions FPO;
2692 switch (BuiltinID) {
2693 case Builtin::BI__builtin_cpu_supports:
2694 case Builtin::BI__builtin_cpu_is:
2695 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2696 Context.getAuxTargetInfo(), BuiltinID))
2697 return ExprError();
2698 break;
2699 case Builtin::BI__builtin_cpu_init:
2700 if (!Context.getTargetInfo().supportsCpuInit()) {
2701 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2702 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2703 return ExprError();
2704 }
2705 break;
2706 case Builtin::BI__builtin___CFStringMakeConstantString:
2707 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2708 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2710 *this, BuiltinID, TheCall,
2711 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2712 return ExprError();
2713 assert(TheCall->getNumArgs() == 1 &&
2714 "Wrong # arguments to builtin CFStringMakeConstantString");
2715 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2716 return ExprError();
2717 break;
2718 case Builtin::BI__builtin_ms_va_start:
2719 case Builtin::BI__builtin_stdarg_start:
2720 case Builtin::BI__builtin_va_start:
2721 case Builtin::BI__builtin_c23_va_start:
2722 if (BuiltinVAStart(BuiltinID, TheCall))
2723 return ExprError();
2724 break;
2725 case Builtin::BI__va_start: {
2726 switch (Context.getTargetInfo().getTriple().getArch()) {
2727 case llvm::Triple::aarch64:
2728 case llvm::Triple::arm:
2729 case llvm::Triple::thumb:
2730 if (BuiltinVAStartARMMicrosoft(TheCall))
2731 return ExprError();
2732 break;
2733 default:
2734 if (BuiltinVAStart(BuiltinID, TheCall))
2735 return ExprError();
2736 break;
2737 }
2738 break;
2739 }
2740
2741 // The acquire, release, and no fence variants are ARM and AArch64 only.
2742 case Builtin::BI_interlockedbittestandset_acq:
2743 case Builtin::BI_interlockedbittestandset_rel:
2744 case Builtin::BI_interlockedbittestandset_nf:
2745 case Builtin::BI_interlockedbittestandreset_acq:
2746 case Builtin::BI_interlockedbittestandreset_rel:
2747 case Builtin::BI_interlockedbittestandreset_nf:
2749 *this, TheCall,
2750 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2751 return ExprError();
2752 break;
2753
2754 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2755 case Builtin::BI_bittest64:
2756 case Builtin::BI_bittestandcomplement64:
2757 case Builtin::BI_bittestandreset64:
2758 case Builtin::BI_bittestandset64:
2759 case Builtin::BI_interlockedbittestandreset64:
2760 case Builtin::BI_interlockedbittestandset64:
2762 *this, TheCall,
2763 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2764 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2765 return ExprError();
2766 break;
2767
2768 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2769 case Builtin::BI_interlockedbittestandreset64_acq:
2770 case Builtin::BI_interlockedbittestandreset64_rel:
2771 case Builtin::BI_interlockedbittestandreset64_nf:
2772 case Builtin::BI_interlockedbittestandset64_acq:
2773 case Builtin::BI_interlockedbittestandset64_rel:
2774 case Builtin::BI_interlockedbittestandset64_nf:
2775 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2776 return ExprError();
2777 break;
2778
2779 case Builtin::BI__builtin_set_flt_rounds:
2781 *this, TheCall,
2782 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2783 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2784 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2785 llvm::Triple::ppc64le}))
2786 return ExprError();
2787 break;
2788
2789 case Builtin::BI__builtin_isgreater:
2790 case Builtin::BI__builtin_isgreaterequal:
2791 case Builtin::BI__builtin_isless:
2792 case Builtin::BI__builtin_islessequal:
2793 case Builtin::BI__builtin_islessgreater:
2794 case Builtin::BI__builtin_isunordered:
2795 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2796 return ExprError();
2797 break;
2798 case Builtin::BI__builtin_fpclassify:
2799 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2800 return ExprError();
2801 break;
2802 case Builtin::BI__builtin_isfpclass:
2803 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2804 return ExprError();
2805 break;
2806 case Builtin::BI__builtin_isfinite:
2807 case Builtin::BI__builtin_isinf:
2808 case Builtin::BI__builtin_isinf_sign:
2809 case Builtin::BI__builtin_isnan:
2810 case Builtin::BI__builtin_issignaling:
2811 case Builtin::BI__builtin_isnormal:
2812 case Builtin::BI__builtin_issubnormal:
2813 case Builtin::BI__builtin_iszero:
2814 case Builtin::BI__builtin_signbit:
2815 case Builtin::BI__builtin_signbitf:
2816 case Builtin::BI__builtin_signbitl:
2817 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2818 return ExprError();
2819 break;
2820 case Builtin::BI__builtin_shufflevector:
2821 return BuiltinShuffleVector(TheCall);
2822 // TheCall will be freed by the smart pointer here, but that's fine, since
2823 // BuiltinShuffleVector guts it, but then doesn't release it.
2824 case Builtin::BI__builtin_masked_load:
2825 case Builtin::BI__builtin_masked_expand_load:
2826 return BuiltinMaskedLoad(*this, TheCall);
2827 case Builtin::BI__builtin_masked_store:
2828 case Builtin::BI__builtin_masked_compress_store:
2829 return BuiltinMaskedStore(*this, TheCall);
2830 case Builtin::BI__builtin_masked_gather:
2831 return BuiltinMaskedGather(*this, TheCall);
2832 case Builtin::BI__builtin_masked_scatter:
2833 return BuiltinMaskedScatter(*this, TheCall);
2834 case Builtin::BI__builtin_invoke:
2835 return BuiltinInvoke(*this, TheCall);
2836 case Builtin::BI__builtin_prefetch:
2837 if (BuiltinPrefetch(TheCall))
2838 return ExprError();
2839 break;
2840 case Builtin::BI__builtin_alloca_with_align:
2841 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2842 if (BuiltinAllocaWithAlign(TheCall))
2843 return ExprError();
2844 [[fallthrough]];
2845 case Builtin::BI__builtin_alloca:
2846 case Builtin::BI__builtin_alloca_uninitialized:
2847 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2848 << TheCall->getDirectCallee();
2849 if (getLangOpts().OpenCL) {
2850 builtinAllocaAddrSpace(*this, TheCall);
2851 }
2852 break;
2853 case Builtin::BI__builtin_infer_alloc_token:
2854 if (checkBuiltinInferAllocToken(*this, TheCall))
2855 return ExprError();
2856 break;
2857 case Builtin::BI__arithmetic_fence:
2858 if (BuiltinArithmeticFence(TheCall))
2859 return ExprError();
2860 break;
2861 case Builtin::BI__assume:
2862 case Builtin::BI__builtin_assume:
2863 if (BuiltinAssume(TheCall))
2864 return ExprError();
2865 break;
2866 case Builtin::BI__builtin_assume_aligned:
2867 if (BuiltinAssumeAligned(TheCall))
2868 return ExprError();
2869 break;
2870 case Builtin::BI__builtin_dynamic_object_size:
2871 case Builtin::BI__builtin_object_size:
2872 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2873 return ExprError();
2874 break;
2875 case Builtin::BI__builtin_longjmp:
2876 if (BuiltinLongjmp(TheCall))
2877 return ExprError();
2878 break;
2879 case Builtin::BI__builtin_setjmp:
2880 if (BuiltinSetjmp(TheCall))
2881 return ExprError();
2882 break;
2883 case Builtin::BI__builtin_classify_type:
2884 if (checkArgCount(TheCall, 1))
2885 return true;
2886 TheCall->setType(Context.IntTy);
2887 break;
2888 case Builtin::BI__builtin_complex:
2889 if (BuiltinComplex(TheCall))
2890 return ExprError();
2891 break;
2892 case Builtin::BI__builtin_constant_p: {
2893 if (checkArgCount(TheCall, 1))
2894 return true;
2896 if (Arg.isInvalid()) return true;
2897 TheCall->setArg(0, Arg.get());
2898 TheCall->setType(Context.IntTy);
2899 break;
2900 }
2901 case Builtin::BI__builtin_launder:
2902 return BuiltinLaunder(*this, TheCall);
2903 case Builtin::BI__builtin_is_within_lifetime:
2904 return BuiltinIsWithinLifetime(*this, TheCall);
2905 case Builtin::BI__builtin_trivially_relocate:
2906 return BuiltinTriviallyRelocate(*this, TheCall);
2907
2908 case Builtin::BI__sync_fetch_and_add:
2909 case Builtin::BI__sync_fetch_and_add_1:
2910 case Builtin::BI__sync_fetch_and_add_2:
2911 case Builtin::BI__sync_fetch_and_add_4:
2912 case Builtin::BI__sync_fetch_and_add_8:
2913 case Builtin::BI__sync_fetch_and_add_16:
2914 case Builtin::BI__sync_fetch_and_sub:
2915 case Builtin::BI__sync_fetch_and_sub_1:
2916 case Builtin::BI__sync_fetch_and_sub_2:
2917 case Builtin::BI__sync_fetch_and_sub_4:
2918 case Builtin::BI__sync_fetch_and_sub_8:
2919 case Builtin::BI__sync_fetch_and_sub_16:
2920 case Builtin::BI__sync_fetch_and_or:
2921 case Builtin::BI__sync_fetch_and_or_1:
2922 case Builtin::BI__sync_fetch_and_or_2:
2923 case Builtin::BI__sync_fetch_and_or_4:
2924 case Builtin::BI__sync_fetch_and_or_8:
2925 case Builtin::BI__sync_fetch_and_or_16:
2926 case Builtin::BI__sync_fetch_and_and:
2927 case Builtin::BI__sync_fetch_and_and_1:
2928 case Builtin::BI__sync_fetch_and_and_2:
2929 case Builtin::BI__sync_fetch_and_and_4:
2930 case Builtin::BI__sync_fetch_and_and_8:
2931 case Builtin::BI__sync_fetch_and_and_16:
2932 case Builtin::BI__sync_fetch_and_xor:
2933 case Builtin::BI__sync_fetch_and_xor_1:
2934 case Builtin::BI__sync_fetch_and_xor_2:
2935 case Builtin::BI__sync_fetch_and_xor_4:
2936 case Builtin::BI__sync_fetch_and_xor_8:
2937 case Builtin::BI__sync_fetch_and_xor_16:
2938 case Builtin::BI__sync_fetch_and_nand:
2939 case Builtin::BI__sync_fetch_and_nand_1:
2940 case Builtin::BI__sync_fetch_and_nand_2:
2941 case Builtin::BI__sync_fetch_and_nand_4:
2942 case Builtin::BI__sync_fetch_and_nand_8:
2943 case Builtin::BI__sync_fetch_and_nand_16:
2944 case Builtin::BI__sync_add_and_fetch:
2945 case Builtin::BI__sync_add_and_fetch_1:
2946 case Builtin::BI__sync_add_and_fetch_2:
2947 case Builtin::BI__sync_add_and_fetch_4:
2948 case Builtin::BI__sync_add_and_fetch_8:
2949 case Builtin::BI__sync_add_and_fetch_16:
2950 case Builtin::BI__sync_sub_and_fetch:
2951 case Builtin::BI__sync_sub_and_fetch_1:
2952 case Builtin::BI__sync_sub_and_fetch_2:
2953 case Builtin::BI__sync_sub_and_fetch_4:
2954 case Builtin::BI__sync_sub_and_fetch_8:
2955 case Builtin::BI__sync_sub_and_fetch_16:
2956 case Builtin::BI__sync_and_and_fetch:
2957 case Builtin::BI__sync_and_and_fetch_1:
2958 case Builtin::BI__sync_and_and_fetch_2:
2959 case Builtin::BI__sync_and_and_fetch_4:
2960 case Builtin::BI__sync_and_and_fetch_8:
2961 case Builtin::BI__sync_and_and_fetch_16:
2962 case Builtin::BI__sync_or_and_fetch:
2963 case Builtin::BI__sync_or_and_fetch_1:
2964 case Builtin::BI__sync_or_and_fetch_2:
2965 case Builtin::BI__sync_or_and_fetch_4:
2966 case Builtin::BI__sync_or_and_fetch_8:
2967 case Builtin::BI__sync_or_and_fetch_16:
2968 case Builtin::BI__sync_xor_and_fetch:
2969 case Builtin::BI__sync_xor_and_fetch_1:
2970 case Builtin::BI__sync_xor_and_fetch_2:
2971 case Builtin::BI__sync_xor_and_fetch_4:
2972 case Builtin::BI__sync_xor_and_fetch_8:
2973 case Builtin::BI__sync_xor_and_fetch_16:
2974 case Builtin::BI__sync_nand_and_fetch:
2975 case Builtin::BI__sync_nand_and_fetch_1:
2976 case Builtin::BI__sync_nand_and_fetch_2:
2977 case Builtin::BI__sync_nand_and_fetch_4:
2978 case Builtin::BI__sync_nand_and_fetch_8:
2979 case Builtin::BI__sync_nand_and_fetch_16:
2980 case Builtin::BI__sync_val_compare_and_swap:
2981 case Builtin::BI__sync_val_compare_and_swap_1:
2982 case Builtin::BI__sync_val_compare_and_swap_2:
2983 case Builtin::BI__sync_val_compare_and_swap_4:
2984 case Builtin::BI__sync_val_compare_and_swap_8:
2985 case Builtin::BI__sync_val_compare_and_swap_16:
2986 case Builtin::BI__sync_bool_compare_and_swap:
2987 case Builtin::BI__sync_bool_compare_and_swap_1:
2988 case Builtin::BI__sync_bool_compare_and_swap_2:
2989 case Builtin::BI__sync_bool_compare_and_swap_4:
2990 case Builtin::BI__sync_bool_compare_and_swap_8:
2991 case Builtin::BI__sync_bool_compare_and_swap_16:
2992 case Builtin::BI__sync_lock_test_and_set:
2993 case Builtin::BI__sync_lock_test_and_set_1:
2994 case Builtin::BI__sync_lock_test_and_set_2:
2995 case Builtin::BI__sync_lock_test_and_set_4:
2996 case Builtin::BI__sync_lock_test_and_set_8:
2997 case Builtin::BI__sync_lock_test_and_set_16:
2998 case Builtin::BI__sync_lock_release:
2999 case Builtin::BI__sync_lock_release_1:
3000 case Builtin::BI__sync_lock_release_2:
3001 case Builtin::BI__sync_lock_release_4:
3002 case Builtin::BI__sync_lock_release_8:
3003 case Builtin::BI__sync_lock_release_16:
3004 case Builtin::BI__sync_swap:
3005 case Builtin::BI__sync_swap_1:
3006 case Builtin::BI__sync_swap_2:
3007 case Builtin::BI__sync_swap_4:
3008 case Builtin::BI__sync_swap_8:
3009 case Builtin::BI__sync_swap_16:
3010 return BuiltinAtomicOverloaded(TheCallResult);
3011 case Builtin::BI__sync_synchronize:
3012 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3013 << TheCall->getCallee()->getSourceRange();
3014 break;
3015 case Builtin::BI__builtin_nontemporal_load:
3016 case Builtin::BI__builtin_nontemporal_store:
3017 return BuiltinNontemporalOverloaded(TheCallResult);
3018 case Builtin::BI__builtin_memcpy_inline: {
3019 clang::Expr *SizeOp = TheCall->getArg(2);
3020 // We warn about copying to or from `nullptr` pointers when `size` is
3021 // greater than 0. When `size` is value dependent we cannot evaluate its
3022 // value so we bail out.
3023 if (SizeOp->isValueDependent())
3024 break;
3025 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3026 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3027 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3028 }
3029 break;
3030 }
3031 case Builtin::BI__builtin_memset_inline: {
3032 clang::Expr *SizeOp = TheCall->getArg(2);
3033 // We warn about filling to `nullptr` pointers when `size` is greater than
3034 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3035 // out.
3036 if (SizeOp->isValueDependent())
3037 break;
3038 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3039 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3040 break;
3041 }
3042#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3043 case Builtin::BI##ID: \
3044 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3045#include "clang/Basic/Builtins.inc"
3046 case Builtin::BI__annotation:
3047 if (BuiltinMSVCAnnotation(*this, TheCall))
3048 return ExprError();
3049 break;
3050 case Builtin::BI__builtin_annotation:
3051 if (BuiltinAnnotation(*this, TheCall))
3052 return ExprError();
3053 break;
3054 case Builtin::BI__builtin_addressof:
3055 if (BuiltinAddressof(*this, TheCall))
3056 return ExprError();
3057 break;
3058 case Builtin::BI__builtin_function_start:
3059 if (BuiltinFunctionStart(*this, TheCall))
3060 return ExprError();
3061 break;
3062 case Builtin::BI__builtin_is_aligned:
3063 case Builtin::BI__builtin_align_up:
3064 case Builtin::BI__builtin_align_down:
3065 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3066 return ExprError();
3067 break;
3068 case Builtin::BI__builtin_add_overflow:
3069 case Builtin::BI__builtin_sub_overflow:
3070 case Builtin::BI__builtin_mul_overflow:
3071 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3072 return ExprError();
3073 break;
3074 case Builtin::BI__builtin_operator_new:
3075 case Builtin::BI__builtin_operator_delete: {
3076 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3077 ExprResult Res =
3078 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3079 return Res;
3080 }
3081 case Builtin::BI__builtin_dump_struct:
3082 return BuiltinDumpStruct(*this, TheCall);
3083 case Builtin::BI__builtin_expect_with_probability: {
3084 // We first want to ensure we are called with 3 arguments
3085 if (checkArgCount(TheCall, 3))
3086 return ExprError();
3087 // then check probability is constant float in range [0.0, 1.0]
3088 const Expr *ProbArg = TheCall->getArg(2);
3089 SmallVector<PartialDiagnosticAt, 8> Notes;
3090 Expr::EvalResult Eval;
3091 Eval.Diag = &Notes;
3092 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3093 !Eval.Val.isFloat()) {
3094 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3095 << ProbArg->getSourceRange();
3096 for (const PartialDiagnosticAt &PDiag : Notes)
3097 Diag(PDiag.first, PDiag.second);
3098 return ExprError();
3099 }
3100 llvm::APFloat Probability = Eval.Val.getFloat();
3101 bool LoseInfo = false;
3102 Probability.convert(llvm::APFloat::IEEEdouble(),
3103 llvm::RoundingMode::Dynamic, &LoseInfo);
3104 if (!(Probability >= llvm::APFloat(0.0) &&
3105 Probability <= llvm::APFloat(1.0))) {
3106 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3107 << ProbArg->getSourceRange();
3108 return ExprError();
3109 }
3110 break;
3111 }
3112 case Builtin::BI__builtin_preserve_access_index:
3113 if (BuiltinPreserveAI(*this, TheCall))
3114 return ExprError();
3115 break;
3116 case Builtin::BI__builtin_call_with_static_chain:
3117 if (BuiltinCallWithStaticChain(*this, TheCall))
3118 return ExprError();
3119 break;
3120 case Builtin::BI__exception_code:
3121 case Builtin::BI_exception_code:
3122 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3123 diag::err_seh___except_block))
3124 return ExprError();
3125 break;
3126 case Builtin::BI__exception_info:
3127 case Builtin::BI_exception_info:
3128 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3129 diag::err_seh___except_filter))
3130 return ExprError();
3131 break;
3132 case Builtin::BI__GetExceptionInfo:
3133 if (checkArgCount(TheCall, 1))
3134 return ExprError();
3135
3137 TheCall->getBeginLoc(),
3138 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3139 TheCall))
3140 return ExprError();
3141
3142 TheCall->setType(Context.VoidPtrTy);
3143 break;
3144 case Builtin::BIaddressof:
3145 case Builtin::BI__addressof:
3146 case Builtin::BIforward:
3147 case Builtin::BIforward_like:
3148 case Builtin::BImove:
3149 case Builtin::BImove_if_noexcept:
3150 case Builtin::BIas_const: {
3151 // These are all expected to be of the form
3152 // T &/&&/* f(U &/&&)
3153 // where T and U only differ in qualification.
3154 if (checkArgCount(TheCall, 1))
3155 return ExprError();
3156 QualType Param = FDecl->getParamDecl(0)->getType();
3157 QualType Result = FDecl->getReturnType();
3158 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3159 BuiltinID == Builtin::BI__addressof;
3160 if (!(Param->isReferenceType() &&
3161 (ReturnsPointer ? Result->isAnyPointerType()
3162 : Result->isReferenceType()) &&
3163 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3164 Result->getPointeeType()))) {
3165 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3166 << FDecl;
3167 return ExprError();
3168 }
3169 break;
3170 }
3171 case Builtin::BI__builtin_ptrauth_strip:
3172 return PointerAuthStrip(*this, TheCall);
3173 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3174 return PointerAuthBlendDiscriminator(*this, TheCall);
3175 case Builtin::BI__builtin_ptrauth_sign_constant:
3176 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3177 /*RequireConstant=*/true);
3178 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3179 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3180 /*RequireConstant=*/false);
3181 case Builtin::BI__builtin_ptrauth_auth:
3182 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3183 /*RequireConstant=*/false);
3184 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3185 return PointerAuthSignGenericData(*this, TheCall);
3186 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3187 return PointerAuthAuthAndResign(*this, TheCall);
3188 case Builtin::BI__builtin_ptrauth_string_discriminator:
3189 return PointerAuthStringDiscriminator(*this, TheCall);
3190
3191 case Builtin::BI__builtin_get_vtable_pointer:
3192 return GetVTablePointer(*this, TheCall);
3193
3194 // OpenCL v2.0, s6.13.16 - Pipe functions
3195 case Builtin::BIread_pipe:
3196 case Builtin::BIwrite_pipe:
3197 // Since those two functions are declared with var args, we need a semantic
3198 // check for the argument.
3199 if (OpenCL().checkBuiltinRWPipe(TheCall))
3200 return ExprError();
3201 break;
3202 case Builtin::BIreserve_read_pipe:
3203 case Builtin::BIreserve_write_pipe:
3204 case Builtin::BIwork_group_reserve_read_pipe:
3205 case Builtin::BIwork_group_reserve_write_pipe:
3206 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3207 return ExprError();
3208 break;
3209 case Builtin::BIsub_group_reserve_read_pipe:
3210 case Builtin::BIsub_group_reserve_write_pipe:
3211 if (OpenCL().checkSubgroupExt(TheCall) ||
3212 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3213 return ExprError();
3214 break;
3215 case Builtin::BIcommit_read_pipe:
3216 case Builtin::BIcommit_write_pipe:
3217 case Builtin::BIwork_group_commit_read_pipe:
3218 case Builtin::BIwork_group_commit_write_pipe:
3219 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3220 return ExprError();
3221 break;
3222 case Builtin::BIsub_group_commit_read_pipe:
3223 case Builtin::BIsub_group_commit_write_pipe:
3224 if (OpenCL().checkSubgroupExt(TheCall) ||
3225 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3226 return ExprError();
3227 break;
3228 case Builtin::BIget_pipe_num_packets:
3229 case Builtin::BIget_pipe_max_packets:
3230 if (OpenCL().checkBuiltinPipePackets(TheCall))
3231 return ExprError();
3232 break;
3233 case Builtin::BIto_global:
3234 case Builtin::BIto_local:
3235 case Builtin::BIto_private:
3236 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3237 return ExprError();
3238 break;
3239 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3240 case Builtin::BIenqueue_kernel:
3241 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3242 return ExprError();
3243 break;
3244 case Builtin::BIget_kernel_work_group_size:
3245 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3246 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3247 return ExprError();
3248 break;
3249 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3250 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3251 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3252 return ExprError();
3253 break;
3254 case Builtin::BI__builtin_os_log_format:
3255 Cleanup.setExprNeedsCleanups(true);
3256 [[fallthrough]];
3257 case Builtin::BI__builtin_os_log_format_buffer_size:
3258 if (BuiltinOSLogFormat(TheCall))
3259 return ExprError();
3260 break;
3261 case Builtin::BI__builtin_frame_address:
3262 case Builtin::BI__builtin_return_address: {
3263 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3264 return ExprError();
3265
3266 // -Wframe-address warning if non-zero passed to builtin
3267 // return/frame address.
3268 Expr::EvalResult Result;
3269 if (!TheCall->getArg(0)->isValueDependent() &&
3270 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3271 Result.Val.getInt() != 0)
3272 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3273 << ((BuiltinID == Builtin::BI__builtin_return_address)
3274 ? "__builtin_return_address"
3275 : "__builtin_frame_address")
3276 << TheCall->getSourceRange();
3277 break;
3278 }
3279
3280 case Builtin::BI__builtin_nondeterministic_value: {
3281 if (BuiltinNonDeterministicValue(TheCall))
3282 return ExprError();
3283 break;
3284 }
3285
3286 // __builtin_elementwise_abs restricts the element type to signed integers or
3287 // floating point types only.
3288 case Builtin::BI__builtin_elementwise_abs:
3291 return ExprError();
3292 break;
3293
3294 // These builtins restrict the element type to floating point
3295 // types only.
3296 case Builtin::BI__builtin_elementwise_acos:
3297 case Builtin::BI__builtin_elementwise_asin:
3298 case Builtin::BI__builtin_elementwise_atan:
3299 case Builtin::BI__builtin_elementwise_ceil:
3300 case Builtin::BI__builtin_elementwise_cos:
3301 case Builtin::BI__builtin_elementwise_cosh:
3302 case Builtin::BI__builtin_elementwise_exp:
3303 case Builtin::BI__builtin_elementwise_exp2:
3304 case Builtin::BI__builtin_elementwise_exp10:
3305 case Builtin::BI__builtin_elementwise_floor:
3306 case Builtin::BI__builtin_elementwise_log:
3307 case Builtin::BI__builtin_elementwise_log2:
3308 case Builtin::BI__builtin_elementwise_log10:
3309 case Builtin::BI__builtin_elementwise_roundeven:
3310 case Builtin::BI__builtin_elementwise_round:
3311 case Builtin::BI__builtin_elementwise_rint:
3312 case Builtin::BI__builtin_elementwise_nearbyint:
3313 case Builtin::BI__builtin_elementwise_sin:
3314 case Builtin::BI__builtin_elementwise_sinh:
3315 case Builtin::BI__builtin_elementwise_sqrt:
3316 case Builtin::BI__builtin_elementwise_tan:
3317 case Builtin::BI__builtin_elementwise_tanh:
3318 case Builtin::BI__builtin_elementwise_trunc:
3319 case Builtin::BI__builtin_elementwise_canonicalize:
3322 return ExprError();
3323 break;
3324 case Builtin::BI__builtin_elementwise_fma:
3325 if (BuiltinElementwiseTernaryMath(TheCall))
3326 return ExprError();
3327 break;
3328
3329 case Builtin::BI__builtin_elementwise_ldexp: {
3330 if (checkArgCount(TheCall, 2))
3331 return ExprError();
3332
3333 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3334 if (A.isInvalid())
3335 return ExprError();
3336 QualType TyA = A.get()->getType();
3337 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3339 return ExprError();
3340
3341 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3342 if (Exp.isInvalid())
3343 return ExprError();
3344 QualType TyExp = Exp.get()->getType();
3345 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3347 2))
3348 return ExprError();
3349
3350 // Check the two arguments are either scalars or vectors of equal length.
3351 const auto *Vec0 = TyA->getAs<VectorType>();
3352 const auto *Vec1 = TyExp->getAs<VectorType>();
3353 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3354 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3355 if (Arg0Length != Arg1Length) {
3356 Diag(Exp.get()->getBeginLoc(),
3357 diag::err_typecheck_vector_lengths_not_equal)
3358 << TyA << TyExp << A.get()->getSourceRange()
3359 << Exp.get()->getSourceRange();
3360 return ExprError();
3361 }
3362
3363 TheCall->setArg(0, A.get());
3364 TheCall->setArg(1, Exp.get());
3365 TheCall->setType(TyA);
3366 break;
3367 }
3368
3369 // These builtins restrict the element type to floating point
3370 // types only, and take in two arguments.
3371 case Builtin::BI__builtin_elementwise_minnum:
3372 case Builtin::BI__builtin_elementwise_maxnum:
3373 case Builtin::BI__builtin_elementwise_minimum:
3374 case Builtin::BI__builtin_elementwise_maximum:
3375 case Builtin::BI__builtin_elementwise_minimumnum:
3376 case Builtin::BI__builtin_elementwise_maximumnum:
3377 case Builtin::BI__builtin_elementwise_atan2:
3378 case Builtin::BI__builtin_elementwise_fmod:
3379 case Builtin::BI__builtin_elementwise_pow:
3380 if (BuiltinElementwiseMath(TheCall,
3382 return ExprError();
3383 break;
3384 // These builtins restrict the element type to integer
3385 // types only.
3386 case Builtin::BI__builtin_elementwise_add_sat:
3387 case Builtin::BI__builtin_elementwise_sub_sat:
3388 if (BuiltinElementwiseMath(TheCall,
3390 return ExprError();
3391 break;
3392 case Builtin::BI__builtin_elementwise_fshl:
3393 case Builtin::BI__builtin_elementwise_fshr:
3396 return ExprError();
3397 break;
3398 case Builtin::BI__builtin_elementwise_min:
3399 case Builtin::BI__builtin_elementwise_max:
3400 if (BuiltinElementwiseMath(TheCall))
3401 return ExprError();
3402 break;
3403 case Builtin::BI__builtin_elementwise_popcount:
3404 case Builtin::BI__builtin_elementwise_bitreverse:
3407 return ExprError();
3408 break;
3409 case Builtin::BI__builtin_elementwise_copysign: {
3410 if (checkArgCount(TheCall, 2))
3411 return ExprError();
3412
3413 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3414 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3415 if (Magnitude.isInvalid() || Sign.isInvalid())
3416 return ExprError();
3417
3418 QualType MagnitudeTy = Magnitude.get()->getType();
3419 QualType SignTy = Sign.get()->getType();
3421 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3424 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3426 return ExprError();
3427 }
3428
3429 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3430 return Diag(Sign.get()->getBeginLoc(),
3431 diag::err_typecheck_call_different_arg_types)
3432 << MagnitudeTy << SignTy;
3433 }
3434
3435 TheCall->setArg(0, Magnitude.get());
3436 TheCall->setArg(1, Sign.get());
3437 TheCall->setType(Magnitude.get()->getType());
3438 break;
3439 }
3440 case Builtin::BI__builtin_elementwise_clzg:
3441 case Builtin::BI__builtin_elementwise_ctzg:
3442 // These builtins can be unary or binary. Note for empty calls we call the
3443 // unary checker in order to not emit an error that says the function
3444 // expects 2 arguments, which would be misleading.
3445 if (TheCall->getNumArgs() <= 1) {
3448 return ExprError();
3449 } else if (BuiltinElementwiseMath(
3451 return ExprError();
3452 break;
3453 case Builtin::BI__builtin_reduce_max:
3454 case Builtin::BI__builtin_reduce_min: {
3455 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3456 return ExprError();
3457
3458 const Expr *Arg = TheCall->getArg(0);
3459 const auto *TyA = Arg->getType()->getAs<VectorType>();
3460
3461 QualType ElTy;
3462 if (TyA)
3463 ElTy = TyA->getElementType();
3464 else if (Arg->getType()->isSizelessVectorType())
3466
3467 if (ElTy.isNull()) {
3468 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3469 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3470 << Arg->getType();
3471 return ExprError();
3472 }
3473
3474 TheCall->setType(ElTy);
3475 break;
3476 }
3477 case Builtin::BI__builtin_reduce_maximum:
3478 case Builtin::BI__builtin_reduce_minimum: {
3479 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3480 return ExprError();
3481
3482 const Expr *Arg = TheCall->getArg(0);
3483 const auto *TyA = Arg->getType()->getAs<VectorType>();
3484
3485 QualType ElTy;
3486 if (TyA)
3487 ElTy = TyA->getElementType();
3488 else if (Arg->getType()->isSizelessVectorType())
3490
3491 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3492 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3493 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3494 << Arg->getType();
3495 return ExprError();
3496 }
3497
3498 TheCall->setType(ElTy);
3499 break;
3500 }
3501
3502 // These builtins support vectors of integers only.
3503 // TODO: ADD/MUL should support floating-point types.
3504 case Builtin::BI__builtin_reduce_add:
3505 case Builtin::BI__builtin_reduce_mul:
3506 case Builtin::BI__builtin_reduce_xor:
3507 case Builtin::BI__builtin_reduce_or:
3508 case Builtin::BI__builtin_reduce_and: {
3509 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3510 return ExprError();
3511
3512 const Expr *Arg = TheCall->getArg(0);
3513 const auto *TyA = Arg->getType()->getAs<VectorType>();
3514
3515 QualType ElTy;
3516 if (TyA)
3517 ElTy = TyA->getElementType();
3518 else if (Arg->getType()->isSizelessVectorType())
3520
3521 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3522 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3523 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3524 << Arg->getType();
3525 return ExprError();
3526 }
3527
3528 TheCall->setType(ElTy);
3529 break;
3530 }
3531
3532 case Builtin::BI__builtin_matrix_transpose:
3533 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3534
3535 case Builtin::BI__builtin_matrix_column_major_load:
3536 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3537
3538 case Builtin::BI__builtin_matrix_column_major_store:
3539 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3540
3541 case Builtin::BI__builtin_verbose_trap:
3542 if (!checkBuiltinVerboseTrap(TheCall, *this))
3543 return ExprError();
3544 break;
3545
3546 case Builtin::BI__builtin_get_device_side_mangled_name: {
3547 auto Check = [](CallExpr *TheCall) {
3548 if (TheCall->getNumArgs() != 1)
3549 return false;
3550 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3551 if (!DRE)
3552 return false;
3553 auto *D = DRE->getDecl();
3554 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3555 return false;
3556 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3557 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3558 };
3559 if (!Check(TheCall)) {
3560 Diag(TheCall->getBeginLoc(),
3561 diag::err_hip_invalid_args_builtin_mangled_name);
3562 return ExprError();
3563 }
3564 break;
3565 }
3566 case Builtin::BI__builtin_bswapg:
3567 if (BuiltinBswapg(*this, TheCall))
3568 return ExprError();
3569 break;
3570 case Builtin::BI__builtin_popcountg:
3571 if (BuiltinPopcountg(*this, TheCall))
3572 return ExprError();
3573 break;
3574 case Builtin::BI__builtin_clzg:
3575 case Builtin::BI__builtin_ctzg:
3576 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3577 return ExprError();
3578 break;
3579
3580 case Builtin::BI__builtin_allow_runtime_check: {
3581 Expr *Arg = TheCall->getArg(0);
3582 // Check if the argument is a string literal.
3584 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3585 << Arg->getSourceRange();
3586 return ExprError();
3587 }
3588 break;
3589 }
3590
3591 case Builtin::BI__builtin_allow_sanitize_check: {
3592 Expr *Arg = TheCall->getArg(0);
3593 // Check if the argument is a string literal.
3594 const StringLiteral *SanitizerName =
3595 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
3596 if (!SanitizerName) {
3597 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3598 << Arg->getSourceRange();
3599 return ExprError();
3600 }
3601 // Validate the sanitizer name.
3602 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3603 .Cases({"address", "thread", "memory", "hwaddress",
3604 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3605 true)
3606 .Default(false)) {
3607 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
3608 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3609 << Arg->getSourceRange();
3610 return ExprError();
3611 }
3612 break;
3613 }
3614 case Builtin::BI__builtin_counted_by_ref:
3615 if (BuiltinCountedByRef(TheCall))
3616 return ExprError();
3617 break;
3618 }
3619
3620 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3621 return ExprError();
3622
3623 // Since the target specific builtins for each arch overlap, only check those
3624 // of the arch we are compiling for.
3625 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3626 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3627 assert(Context.getAuxTargetInfo() &&
3628 "Aux Target Builtin, but not an aux target?");
3629
3630 if (CheckTSBuiltinFunctionCall(
3631 *Context.getAuxTargetInfo(),
3632 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3633 return ExprError();
3634 } else {
3635 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3636 TheCall))
3637 return ExprError();
3638 }
3639 }
3640
3641 return TheCallResult;
3642}
3643
3644bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3645 llvm::APSInt Result;
3646 // We can't check the value of a dependent argument.
3647 Expr *Arg = TheCall->getArg(ArgNum);
3648 if (Arg->isTypeDependent() || Arg->isValueDependent())
3649 return false;
3650
3651 // Check constant-ness first.
3652 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3653 return true;
3654
3655 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3656 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3657 return false;
3658
3659 return Diag(TheCall->getBeginLoc(),
3660 diag::err_argument_not_contiguous_bit_field)
3661 << ArgNum << Arg->getSourceRange();
3662}
3663
3664bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3665 unsigned FirstArg, FormatStringInfo *FSI) {
3666 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3667 bool IsVariadic = false;
3668 if (const FunctionType *FnTy = D->getFunctionType())
3669 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3670 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3671 IsVariadic = BD->isVariadic();
3672 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3673 IsVariadic = OMD->isVariadic();
3674
3675 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3676 IsVariadic, FSI);
3677}
3678
3679bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3680 bool HasImplicitThisParam, bool IsVariadic,
3681 FormatStringInfo *FSI) {
3682 if (FirstArg == 0)
3684 else if (IsVariadic)
3686 else
3688 FSI->FormatIdx = FormatIdx - 1;
3689 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3690
3691 // The way the format attribute works in GCC, the implicit this argument
3692 // of member functions is counted. However, it doesn't appear in our own
3693 // lists, so decrement format_idx in that case.
3694 if (HasImplicitThisParam) {
3695 if(FSI->FormatIdx == 0)
3696 return false;
3697 --FSI->FormatIdx;
3698 if (FSI->FirstDataArg != 0)
3699 --FSI->FirstDataArg;
3700 }
3701 return true;
3702}
3703
3704/// Checks if a the given expression evaluates to null.
3705///
3706/// Returns true if the value evaluates to null.
3707static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3708 // Treat (smart) pointers constructed from nullptr as null, whether we can
3709 // const-evaluate them or not.
3710 // This must happen first: the smart pointer expr might have _Nonnull type!
3714 return true;
3715
3716 // If the expression has non-null type, it doesn't evaluate to null.
3717 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3718 if (*nullability == NullabilityKind::NonNull)
3719 return false;
3720 }
3721
3722 // As a special case, transparent unions initialized with zero are
3723 // considered null for the purposes of the nonnull attribute.
3724 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3725 UT &&
3726 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3727 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3728 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3729 Expr = ILE->getInit(0);
3730 }
3731
3732 bool Result;
3733 return (!Expr->isValueDependent() &&
3735 !Result);
3736}
3737
3739 const Expr *ArgExpr,
3740 SourceLocation CallSiteLoc) {
3741 if (CheckNonNullExpr(S, ArgExpr))
3742 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3743 S.PDiag(diag::warn_null_arg)
3744 << ArgExpr->getSourceRange());
3745}
3746
3747/// Determine whether the given type has a non-null nullability annotation.
3749 if (auto nullability = type->getNullability())
3750 return *nullability == NullabilityKind::NonNull;
3751
3752 return false;
3753}
3754
3756 const NamedDecl *FDecl,
3757 const FunctionProtoType *Proto,
3759 SourceLocation CallSiteLoc) {
3760 assert((FDecl || Proto) && "Need a function declaration or prototype");
3761
3762 // Already checked by constant evaluator.
3764 return;
3765 // Check the attributes attached to the method/function itself.
3766 llvm::SmallBitVector NonNullArgs;
3767 if (FDecl) {
3768 // Handle the nonnull attribute on the function/method declaration itself.
3769 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3770 if (!NonNull->args_size()) {
3771 // Easy case: all pointer arguments are nonnull.
3772 for (const auto *Arg : Args)
3773 if (S.isValidPointerAttrType(Arg->getType()))
3774 CheckNonNullArgument(S, Arg, CallSiteLoc);
3775 return;
3776 }
3777
3778 for (const ParamIdx &Idx : NonNull->args()) {
3779 unsigned IdxAST = Idx.getASTIndex();
3780 if (IdxAST >= Args.size())
3781 continue;
3782 if (NonNullArgs.empty())
3783 NonNullArgs.resize(Args.size());
3784 NonNullArgs.set(IdxAST);
3785 }
3786 }
3787 }
3788
3789 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3790 // Handle the nonnull attribute on the parameters of the
3791 // function/method.
3793 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3794 parms = FD->parameters();
3795 else
3796 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3797
3798 unsigned ParamIndex = 0;
3799 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3800 I != E; ++I, ++ParamIndex) {
3801 const ParmVarDecl *PVD = *I;
3802 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3803 if (NonNullArgs.empty())
3804 NonNullArgs.resize(Args.size());
3805
3806 NonNullArgs.set(ParamIndex);
3807 }
3808 }
3809 } else {
3810 // If we have a non-function, non-method declaration but no
3811 // function prototype, try to dig out the function prototype.
3812 if (!Proto) {
3813 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3814 QualType type = VD->getType().getNonReferenceType();
3815 if (auto pointerType = type->getAs<PointerType>())
3816 type = pointerType->getPointeeType();
3817 else if (auto blockType = type->getAs<BlockPointerType>())
3818 type = blockType->getPointeeType();
3819 // FIXME: data member pointers?
3820
3821 // Dig out the function prototype, if there is one.
3822 Proto = type->getAs<FunctionProtoType>();
3823 }
3824 }
3825
3826 // Fill in non-null argument information from the nullability
3827 // information on the parameter types (if we have them).
3828 if (Proto) {
3829 unsigned Index = 0;
3830 for (auto paramType : Proto->getParamTypes()) {
3831 if (isNonNullType(paramType)) {
3832 if (NonNullArgs.empty())
3833 NonNullArgs.resize(Args.size());
3834
3835 NonNullArgs.set(Index);
3836 }
3837
3838 ++Index;
3839 }
3840 }
3841 }
3842
3843 // Check for non-null arguments.
3844 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3845 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3846 if (NonNullArgs[ArgIndex])
3847 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3848 }
3849}
3850
3851void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3852 StringRef ParamName, QualType ArgTy,
3853 QualType ParamTy) {
3854
3855 // If a function accepts a pointer or reference type
3856 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3857 return;
3858
3859 // If the parameter is a pointer type, get the pointee type for the
3860 // argument too. If the parameter is a reference type, don't try to get
3861 // the pointee type for the argument.
3862 if (ParamTy->isPointerType())
3863 ArgTy = ArgTy->getPointeeType();
3864
3865 // Remove reference or pointer
3866 ParamTy = ParamTy->getPointeeType();
3867
3868 // Find expected alignment, and the actual alignment of the passed object.
3869 // getTypeAlignInChars requires complete types
3870 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3871 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3872 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3873 return;
3874
3875 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3876 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3877
3878 // If the argument is less aligned than the parameter, there is a
3879 // potential alignment issue.
3880 if (ArgAlign < ParamAlign)
3881 Diag(Loc, diag::warn_param_mismatched_alignment)
3882 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3883 << ParamName << (FDecl != nullptr) << FDecl;
3884}
3885
3886void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3887 const Expr *ThisArg,
3889 if (!FD || Args.empty())
3890 return;
3891 auto GetArgAt = [&](int Idx) -> const Expr * {
3892 if (Idx == LifetimeCaptureByAttr::Global ||
3893 Idx == LifetimeCaptureByAttr::Unknown)
3894 return nullptr;
3895 if (IsMemberFunction && Idx == 0)
3896 return ThisArg;
3897 return Args[Idx - IsMemberFunction];
3898 };
3899 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3900 unsigned ArgIdx) {
3901 if (!Attr)
3902 return;
3903
3904 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3905 for (int CapturingParamIdx : Attr->params()) {
3906 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3907 // initialization codepath.
3908 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3910 continue;
3911 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3912 CapturingEntity CE{Capturing};
3913 // Ensure that 'Captured' outlives the 'Capturing' entity.
3914 checkCaptureByLifetime(*this, CE, Captured);
3915 }
3916 };
3917 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3918 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3919 I + IsMemberFunction);
3920 // Check when the implicit object param is captured.
3921 if (IsMemberFunction) {
3922 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3923 if (!TSI)
3924 return;
3926 for (TypeLoc TL = TSI->getTypeLoc();
3927 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3928 TL = ATL.getModifiedLoc())
3929 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3930 }
3931}
3932
3934 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3935 bool IsMemberFunction, SourceLocation Loc,
3936 SourceRange Range, VariadicCallType CallType) {
3937 // FIXME: We should check as much as we can in the template definition.
3938 if (CurContext->isDependentContext())
3939 return;
3940
3941 // Printf and scanf checking.
3942 llvm::SmallBitVector CheckedVarArgs;
3943 if (FDecl) {
3944 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3945 // Only create vector if there are format attributes.
3946 CheckedVarArgs.resize(Args.size());
3947 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3948 CheckedVarArgs);
3949 }
3950
3951 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3952 CheckedVarArgs.resize(Args.size());
3953 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3954 CheckedVarArgs);
3955 }
3956 }
3957
3958 // Refuse POD arguments that weren't caught by the format string
3959 // checks above.
3960 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3961 if (CallType != VariadicCallType::DoesNotApply &&
3962 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3963 unsigned NumParams = Proto ? Proto->getNumParams()
3964 : isa_and_nonnull<FunctionDecl>(FDecl)
3965 ? cast<FunctionDecl>(FDecl)->getNumParams()
3966 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3967 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3968 : 0;
3969
3970 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3971 // Args[ArgIdx] can be null in malformed code.
3972 if (const Expr *Arg = Args[ArgIdx]) {
3973 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3974 checkVariadicArgument(Arg, CallType);
3975 }
3976 }
3977 }
3978 if (FD)
3979 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3980 if (FDecl || Proto) {
3981 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3982
3983 // Type safety checking.
3984 if (FDecl) {
3985 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3986 CheckArgumentWithTypeTag(I, Args, Loc);
3987 }
3988 }
3989
3990 // Check that passed arguments match the alignment of original arguments.
3991 // Try to get the missing prototype from the declaration.
3992 if (!Proto && FDecl) {
3993 const auto *FT = FDecl->getFunctionType();
3994 if (isa_and_nonnull<FunctionProtoType>(FT))
3995 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3996 }
3997 if (Proto) {
3998 // For variadic functions, we may have more args than parameters.
3999 // For some K&R functions, we may have less args than parameters.
4000 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4001 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4002 bool IsScalableArg = false;
4003 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4004 // Args[ArgIdx] can be null in malformed code.
4005 if (const Expr *Arg = Args[ArgIdx]) {
4006 if (Arg->containsErrors())
4007 continue;
4008
4009 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4010 FDecl->hasLinkage() &&
4011 FDecl->getFormalLinkage() != Linkage::Internal &&
4013 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4014
4015 QualType ParamTy = Proto->getParamType(ArgIdx);
4016 if (ParamTy->isSizelessVectorType())
4017 IsScalableArg = true;
4018 QualType ArgTy = Arg->getType();
4019 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4020 ArgTy, ParamTy);
4021 }
4022 }
4023
4024 // If the callee has an AArch64 SME attribute to indicate that it is an
4025 // __arm_streaming function, then the caller requires SME to be available.
4028 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4029 llvm::StringMap<bool> CallerFeatureMap;
4030 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4031 if (!CallerFeatureMap.contains("sme"))
4032 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4033 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4034 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4035 }
4036 }
4037
4038 // If the call requires a streaming-mode change and has scalable vector
4039 // arguments or return values, then warn the user that the streaming and
4040 // non-streaming vector lengths may be different.
4041 // When both streaming and non-streaming vector lengths are defined and
4042 // mismatched, produce an error.
4043 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4044 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4045 (IsScalableArg || IsScalableRet)) {
4046 bool IsCalleeStreaming =
4048 bool IsCalleeStreamingCompatible =
4049 ExtInfo.AArch64SMEAttributes &
4051 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4052 if (!IsCalleeStreamingCompatible &&
4053 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4054 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4055 const LangOptions &LO = getLangOpts();
4056 unsigned VL = LO.VScaleMin * 128;
4057 unsigned SVL = LO.VScaleStreamingMin * 128;
4058 bool IsVLMismatch = VL && SVL && VL != SVL;
4059
4060 auto EmitDiag = [&](bool IsArg) {
4061 if (IsVLMismatch) {
4062 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4063 // Emit warning for streaming-compatible callers
4064 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4065 << IsArg << IsCalleeStreaming << SVL << VL;
4066 else
4067 // Emit error otherwise
4068 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4069 << IsArg << SVL << VL;
4070 } else
4071 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4072 << IsArg;
4073 };
4074
4075 if (IsScalableArg)
4076 EmitDiag(true);
4077 if (IsScalableRet)
4078 EmitDiag(false);
4079 }
4080 }
4081
4082 FunctionType::ArmStateValue CalleeArmZAState =
4084 FunctionType::ArmStateValue CalleeArmZT0State =
4086 if (CalleeArmZAState != FunctionType::ARM_None ||
4087 CalleeArmZT0State != FunctionType::ARM_None) {
4088 bool CallerHasZAState = false;
4089 bool CallerHasZT0State = false;
4090 if (CallerFD) {
4091 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4092 if (Attr && Attr->isNewZA())
4093 CallerHasZAState = true;
4094 if (Attr && Attr->isNewZT0())
4095 CallerHasZT0State = true;
4096 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4097 CallerHasZAState |=
4099 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4101 CallerHasZT0State |=
4103 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4105 }
4106 }
4107
4108 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4109 Diag(Loc, diag::err_sme_za_call_no_za_state);
4110
4111 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4112 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4113
4114 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4115 CalleeArmZT0State != FunctionType::ARM_None) {
4116 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4117 Diag(Loc, diag::note_sme_use_preserves_za);
4118 }
4119 }
4120 }
4121
4122 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4123 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4124 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4125 if (!Arg->isValueDependent()) {
4126 Expr::EvalResult Align;
4127 if (Arg->EvaluateAsInt(Align, Context)) {
4128 const llvm::APSInt &I = Align.Val.getInt();
4129 if (!I.isPowerOf2())
4130 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4131 << Arg->getSourceRange();
4132
4133 if (I > Sema::MaximumAlignment)
4134 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4135 << Arg->getSourceRange() << Sema::MaximumAlignment;
4136 }
4137 }
4138 }
4139
4140 if (FD)
4141 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4142}
4143
4144void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4145 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4146 DiagnoseUseOfDecl(Decl, Loc);
4147 }
4148}
4149
4150void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4152 const FunctionProtoType *Proto,
4153 SourceLocation Loc) {
4154 VariadicCallType CallType = Proto->isVariadic()
4157
4158 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4159 CheckArgAlignment(
4160 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4161 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4162
4163 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4164 Loc, SourceRange(), CallType);
4165}
4166
4168 const FunctionProtoType *Proto) {
4169 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4170 isa<CXXMethodDecl>(FDecl);
4171 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4172 IsMemberOperatorCall;
4173 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4174 TheCall->getCallee());
4175 Expr** Args = TheCall->getArgs();
4176 unsigned NumArgs = TheCall->getNumArgs();
4177
4178 Expr *ImplicitThis = nullptr;
4179 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4180 // If this is a call to a member operator, hide the first
4181 // argument from checkCall.
4182 // FIXME: Our choice of AST representation here is less than ideal.
4183 ImplicitThis = Args[0];
4184 ++Args;
4185 --NumArgs;
4186 } else if (IsMemberFunction && !FDecl->isStatic() &&
4188 ImplicitThis =
4189 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4190
4191 if (ImplicitThis) {
4192 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4193 // used.
4194 QualType ThisType = ImplicitThis->getType();
4195 if (!ThisType->isPointerType()) {
4196 assert(!ThisType->isReferenceType());
4197 ThisType = Context.getPointerType(ThisType);
4198 }
4199
4200 QualType ThisTypeFromDecl = Context.getPointerType(
4201 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4202
4203 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4204 ThisTypeFromDecl);
4205 }
4206
4207 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4208 IsMemberFunction, TheCall->getRParenLoc(),
4209 TheCall->getCallee()->getSourceRange(), CallType);
4210
4211 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4212 // None of the checks below are needed for functions that don't have
4213 // simple names (e.g., C++ conversion functions).
4214 if (!FnInfo)
4215 return false;
4216
4217 // Enforce TCB except for builtin calls, which are always allowed.
4218 if (FDecl->getBuiltinID() == 0)
4219 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4220
4221 CheckAbsoluteValueFunction(TheCall, FDecl);
4222 CheckMaxUnsignedZero(TheCall, FDecl);
4223 CheckInfNaNFunction(TheCall, FDecl);
4224
4225 if (getLangOpts().ObjC)
4226 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4227
4228 unsigned CMId = FDecl->getMemoryFunctionKind();
4229
4230 // Handle memory setting and copying functions.
4231 switch (CMId) {
4232 case 0:
4233 return false;
4234 case Builtin::BIstrlcpy: // fallthrough
4235 case Builtin::BIstrlcat:
4236 CheckStrlcpycatArguments(TheCall, FnInfo);
4237 break;
4238 case Builtin::BIstrncat:
4239 CheckStrncatArguments(TheCall, FnInfo);
4240 break;
4241 case Builtin::BIfree:
4242 CheckFreeArguments(TheCall);
4243 break;
4244 default:
4245 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4246 }
4247
4248 return false;
4249}
4250
4251bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4252 const FunctionProtoType *Proto) {
4253 QualType Ty;
4254 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4255 Ty = V->getType().getNonReferenceType();
4256 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4257 Ty = F->getType().getNonReferenceType();
4258 else
4259 return false;
4260
4261 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4262 !Ty->isFunctionProtoType())
4263 return false;
4264
4265 VariadicCallType CallType;
4266 if (!Proto || !Proto->isVariadic()) {
4268 } else if (Ty->isBlockPointerType()) {
4269 CallType = VariadicCallType::Block;
4270 } else { // Ty->isFunctionPointerType()
4271 CallType = VariadicCallType::Function;
4272 }
4273
4274 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4275 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4276 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4277 TheCall->getCallee()->getSourceRange(), CallType);
4278
4279 return false;
4280}
4281
4282bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4283 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4284 TheCall->getCallee());
4285 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4286 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4287 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4288 TheCall->getCallee()->getSourceRange(), CallType);
4289
4290 return false;
4291}
4292
4293static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4294 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4295 return false;
4296
4297 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4298 switch (Op) {
4299 case AtomicExpr::AO__c11_atomic_init:
4300 case AtomicExpr::AO__opencl_atomic_init:
4301 llvm_unreachable("There is no ordering argument for an init");
4302
4303 case AtomicExpr::AO__c11_atomic_load:
4304 case AtomicExpr::AO__opencl_atomic_load:
4305 case AtomicExpr::AO__hip_atomic_load:
4306 case AtomicExpr::AO__atomic_load_n:
4307 case AtomicExpr::AO__atomic_load:
4308 case AtomicExpr::AO__scoped_atomic_load_n:
4309 case AtomicExpr::AO__scoped_atomic_load:
4310 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4311 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4312
4313 case AtomicExpr::AO__c11_atomic_store:
4314 case AtomicExpr::AO__opencl_atomic_store:
4315 case AtomicExpr::AO__hip_atomic_store:
4316 case AtomicExpr::AO__atomic_store:
4317 case AtomicExpr::AO__atomic_store_n:
4318 case AtomicExpr::AO__scoped_atomic_store:
4319 case AtomicExpr::AO__scoped_atomic_store_n:
4320 case AtomicExpr::AO__atomic_clear:
4321 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4322 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4323 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4324
4325 default:
4326 return true;
4327 }
4328}
4329
4330ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4332 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4333 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4334 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4335 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4336 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4337 Op);
4338}
4339
4341 SourceLocation RParenLoc, MultiExprArg Args,
4343 AtomicArgumentOrder ArgOrder) {
4344 // All the non-OpenCL operations take one of the following forms.
4345 // The OpenCL operations take the __c11 forms with one extra argument for
4346 // synchronization scope.
4347 enum {
4348 // C __c11_atomic_init(A *, C)
4349 Init,
4350
4351 // C __c11_atomic_load(A *, int)
4352 Load,
4353
4354 // void __atomic_load(A *, CP, int)
4355 LoadCopy,
4356
4357 // void __atomic_store(A *, CP, int)
4358 Copy,
4359
4360 // C __c11_atomic_add(A *, M, int)
4361 Arithmetic,
4362
4363 // C __atomic_exchange_n(A *, CP, int)
4364 Xchg,
4365
4366 // void __atomic_exchange(A *, C *, CP, int)
4367 GNUXchg,
4368
4369 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4370 C11CmpXchg,
4371
4372 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4373 GNUCmpXchg,
4374
4375 // bool __atomic_test_and_set(A *, int)
4376 TestAndSetByte,
4377
4378 // void __atomic_clear(A *, int)
4379 ClearByte,
4380 } Form = Init;
4381
4382 const unsigned NumForm = ClearByte + 1;
4383 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4384 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4385 // where:
4386 // C is an appropriate type,
4387 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4388 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4389 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4390 // the int parameters are for orderings.
4391
4392 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4393 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4394 "need to update code for modified forms");
4395 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4396 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4397 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4398 "need to update code for modified C11 atomics");
4399 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4400 Op <= AtomicExpr::AO__opencl_atomic_store;
4401 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4402 Op <= AtomicExpr::AO__hip_atomic_store;
4403 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4404 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4405 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4406 Op <= AtomicExpr::AO__c11_atomic_store) ||
4407 IsOpenCL;
4408 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4409 Op == AtomicExpr::AO__atomic_store_n ||
4410 Op == AtomicExpr::AO__atomic_exchange_n ||
4411 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4412 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4413 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4414 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4415 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4416 // Bit mask for extra allowed value types other than integers for atomic
4417 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4418 // allow floating point.
4419 enum ArithOpExtraValueType {
4420 AOEVT_None = 0,
4421 AOEVT_Pointer = 1,
4422 AOEVT_FP = 2,
4423 };
4424 unsigned ArithAllows = AOEVT_None;
4425
4426 switch (Op) {
4427 case AtomicExpr::AO__c11_atomic_init:
4428 case AtomicExpr::AO__opencl_atomic_init:
4429 Form = Init;
4430 break;
4431
4432 case AtomicExpr::AO__c11_atomic_load:
4433 case AtomicExpr::AO__opencl_atomic_load:
4434 case AtomicExpr::AO__hip_atomic_load:
4435 case AtomicExpr::AO__atomic_load_n:
4436 case AtomicExpr::AO__scoped_atomic_load_n:
4437 Form = Load;
4438 break;
4439
4440 case AtomicExpr::AO__atomic_load:
4441 case AtomicExpr::AO__scoped_atomic_load:
4442 Form = LoadCopy;
4443 break;
4444
4445 case AtomicExpr::AO__c11_atomic_store:
4446 case AtomicExpr::AO__opencl_atomic_store:
4447 case AtomicExpr::AO__hip_atomic_store:
4448 case AtomicExpr::AO__atomic_store:
4449 case AtomicExpr::AO__atomic_store_n:
4450 case AtomicExpr::AO__scoped_atomic_store:
4451 case AtomicExpr::AO__scoped_atomic_store_n:
4452 Form = Copy;
4453 break;
4454 case AtomicExpr::AO__atomic_fetch_add:
4455 case AtomicExpr::AO__atomic_fetch_sub:
4456 case AtomicExpr::AO__atomic_add_fetch:
4457 case AtomicExpr::AO__atomic_sub_fetch:
4458 case AtomicExpr::AO__scoped_atomic_fetch_add:
4459 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4460 case AtomicExpr::AO__scoped_atomic_add_fetch:
4461 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4462 case AtomicExpr::AO__c11_atomic_fetch_add:
4463 case AtomicExpr::AO__c11_atomic_fetch_sub:
4464 case AtomicExpr::AO__opencl_atomic_fetch_add:
4465 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4466 case AtomicExpr::AO__hip_atomic_fetch_add:
4467 case AtomicExpr::AO__hip_atomic_fetch_sub:
4468 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4469 Form = Arithmetic;
4470 break;
4471 case AtomicExpr::AO__atomic_fetch_max:
4472 case AtomicExpr::AO__atomic_fetch_min:
4473 case AtomicExpr::AO__atomic_max_fetch:
4474 case AtomicExpr::AO__atomic_min_fetch:
4475 case AtomicExpr::AO__scoped_atomic_fetch_max:
4476 case AtomicExpr::AO__scoped_atomic_fetch_min:
4477 case AtomicExpr::AO__scoped_atomic_max_fetch:
4478 case AtomicExpr::AO__scoped_atomic_min_fetch:
4479 case AtomicExpr::AO__c11_atomic_fetch_max:
4480 case AtomicExpr::AO__c11_atomic_fetch_min:
4481 case AtomicExpr::AO__opencl_atomic_fetch_max:
4482 case AtomicExpr::AO__opencl_atomic_fetch_min:
4483 case AtomicExpr::AO__hip_atomic_fetch_max:
4484 case AtomicExpr::AO__hip_atomic_fetch_min:
4485 ArithAllows = AOEVT_FP;
4486 Form = Arithmetic;
4487 break;
4488 case AtomicExpr::AO__c11_atomic_fetch_and:
4489 case AtomicExpr::AO__c11_atomic_fetch_or:
4490 case AtomicExpr::AO__c11_atomic_fetch_xor:
4491 case AtomicExpr::AO__hip_atomic_fetch_and:
4492 case AtomicExpr::AO__hip_atomic_fetch_or:
4493 case AtomicExpr::AO__hip_atomic_fetch_xor:
4494 case AtomicExpr::AO__c11_atomic_fetch_nand:
4495 case AtomicExpr::AO__opencl_atomic_fetch_and:
4496 case AtomicExpr::AO__opencl_atomic_fetch_or:
4497 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4498 case AtomicExpr::AO__atomic_fetch_and:
4499 case AtomicExpr::AO__atomic_fetch_or:
4500 case AtomicExpr::AO__atomic_fetch_xor:
4501 case AtomicExpr::AO__atomic_fetch_nand:
4502 case AtomicExpr::AO__atomic_and_fetch:
4503 case AtomicExpr::AO__atomic_or_fetch:
4504 case AtomicExpr::AO__atomic_xor_fetch:
4505 case AtomicExpr::AO__atomic_nand_fetch:
4506 case AtomicExpr::AO__scoped_atomic_fetch_and:
4507 case AtomicExpr::AO__scoped_atomic_fetch_or:
4508 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4509 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4510 case AtomicExpr::AO__scoped_atomic_and_fetch:
4511 case AtomicExpr::AO__scoped_atomic_or_fetch:
4512 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4513 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4514 case AtomicExpr::AO__scoped_atomic_uinc_wrap:
4515 case AtomicExpr::AO__scoped_atomic_udec_wrap:
4516 Form = Arithmetic;
4517 break;
4518
4519 case AtomicExpr::AO__c11_atomic_exchange:
4520 case AtomicExpr::AO__hip_atomic_exchange:
4521 case AtomicExpr::AO__opencl_atomic_exchange:
4522 case AtomicExpr::AO__atomic_exchange_n:
4523 case AtomicExpr::AO__scoped_atomic_exchange_n:
4524 Form = Xchg;
4525 break;
4526
4527 case AtomicExpr::AO__atomic_exchange:
4528 case AtomicExpr::AO__scoped_atomic_exchange:
4529 Form = GNUXchg;
4530 break;
4531
4532 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4533 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4534 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4535 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4536 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4537 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4538 Form = C11CmpXchg;
4539 break;
4540
4541 case AtomicExpr::AO__atomic_compare_exchange:
4542 case AtomicExpr::AO__atomic_compare_exchange_n:
4543 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4544 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4545 Form = GNUCmpXchg;
4546 break;
4547
4548 case AtomicExpr::AO__atomic_test_and_set:
4549 Form = TestAndSetByte;
4550 break;
4551
4552 case AtomicExpr::AO__atomic_clear:
4553 Form = ClearByte;
4554 break;
4555 }
4556
4557 unsigned AdjustedNumArgs = NumArgs[Form];
4558 if ((IsOpenCL || IsHIP || IsScoped) &&
4559 Op != AtomicExpr::AO__opencl_atomic_init)
4560 ++AdjustedNumArgs;
4561 // Check we have the right number of arguments.
4562 if (Args.size() < AdjustedNumArgs) {
4563 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4564 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4565 << /*is non object*/ 0 << ExprRange;
4566 return ExprError();
4567 } else if (Args.size() > AdjustedNumArgs) {
4568 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4569 diag::err_typecheck_call_too_many_args)
4570 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4571 << /*is non object*/ 0 << ExprRange;
4572 return ExprError();
4573 }
4574
4575 // Inspect the first argument of the atomic operation.
4576 Expr *Ptr = Args[0];
4578 if (ConvertedPtr.isInvalid())
4579 return ExprError();
4580
4581 Ptr = ConvertedPtr.get();
4582 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4583 if (!pointerType) {
4584 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4585 << Ptr->getType() << 0 << Ptr->getSourceRange();
4586 return ExprError();
4587 }
4588
4589 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4590 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4591 QualType ValType = AtomTy; // 'C'
4592 if (IsC11) {
4593 if (!AtomTy->isAtomicType()) {
4594 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4595 << Ptr->getType() << Ptr->getSourceRange();
4596 return ExprError();
4597 }
4598 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4600 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4601 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4602 << Ptr->getSourceRange();
4603 return ExprError();
4604 }
4605 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4606 } else if (Form != Load && Form != LoadCopy) {
4607 if (ValType.isConstQualified()) {
4608 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4609 << Ptr->getType() << Ptr->getSourceRange();
4610 return ExprError();
4611 }
4612 }
4613
4614 if (Form != TestAndSetByte && Form != ClearByte) {
4615 // Pointer to object of size zero is not allowed.
4616 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4617 diag::err_incomplete_type))
4618 return ExprError();
4619
4620 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4621 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4622 << Ptr->getType() << 1 << Ptr->getSourceRange();
4623 return ExprError();
4624 }
4625 } else {
4626 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4627 // non-const pointer type, including void* and pointers to incomplete
4628 // structs, but only access the first byte.
4629 AtomTy = Context.CharTy;
4630 AtomTy = AtomTy.withCVRQualifiers(
4631 pointerType->getPointeeType().getCVRQualifiers());
4632 QualType PointerQT = Context.getPointerType(AtomTy);
4633 pointerType = PointerQT->getAs<PointerType>();
4634 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4635 ValType = AtomTy;
4636 }
4637
4638 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4639 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4640 Diag(ExprRange.getBegin(),
4641 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4642 << 0 << Ptr->getType() << Ptr->getSourceRange();
4643 return ExprError();
4644 }
4645
4646 // For an arithmetic operation, the implied arithmetic must be well-formed.
4647 if (Form == Arithmetic) {
4648 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4649 // trivial type errors.
4650 auto IsAllowedValueType = [&](QualType ValType,
4651 unsigned AllowedType) -> bool {
4652 if (ValType->isIntegerType())
4653 return true;
4654 if (ValType->isPointerType())
4655 return AllowedType & AOEVT_Pointer;
4656 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4657 return false;
4658 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4659 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4660 &Context.getTargetInfo().getLongDoubleFormat() ==
4661 &llvm::APFloat::x87DoubleExtended())
4662 return false;
4663 return true;
4664 };
4665 if (!IsAllowedValueType(ValType, ArithAllows)) {
4666 auto DID = ArithAllows & AOEVT_FP
4667 ? (ArithAllows & AOEVT_Pointer
4668 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4669 : diag::err_atomic_op_needs_atomic_int_or_fp)
4670 : diag::err_atomic_op_needs_atomic_int;
4671 Diag(ExprRange.getBegin(), DID)
4672 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4673 return ExprError();
4674 }
4675 if (IsC11 && ValType->isPointerType() &&
4677 diag::err_incomplete_type)) {
4678 return ExprError();
4679 }
4680 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4681 // For __atomic_*_n operations, the value type must be a scalar integral or
4682 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4683 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4684 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4685 return ExprError();
4686 }
4687
4688 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4689 !AtomTy->isScalarType()) {
4690 // For GNU atomics, require a trivially-copyable type. This is not part of
4691 // the GNU atomics specification but we enforce it for consistency with
4692 // other atomics which generally all require a trivially-copyable type. This
4693 // is because atomics just copy bits.
4694 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4695 << Ptr->getType() << Ptr->getSourceRange();
4696 return ExprError();
4697 }
4698
4699 switch (ValType.getObjCLifetime()) {
4702 // okay
4703 break;
4704
4708 // FIXME: Can this happen? By this point, ValType should be known
4709 // to be trivially copyable.
4710 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4711 << ValType << Ptr->getSourceRange();
4712 return ExprError();
4713 }
4714
4715 // All atomic operations have an overload which takes a pointer to a volatile
4716 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4717 // into the result or the other operands. Similarly atomic_load takes a
4718 // pointer to a const 'A'.
4719 ValType.removeLocalVolatile();
4720 ValType.removeLocalConst();
4721 QualType ResultType = ValType;
4722 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4723 Form == ClearByte)
4724 ResultType = Context.VoidTy;
4725 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4726 ResultType = Context.BoolTy;
4727
4728 // The type of a parameter passed 'by value'. In the GNU atomics, such
4729 // arguments are actually passed as pointers.
4730 QualType ByValType = ValType; // 'CP'
4731 bool IsPassedByAddress = false;
4732 if (!IsC11 && !IsHIP && !IsN) {
4733 ByValType = Ptr->getType();
4734 IsPassedByAddress = true;
4735 }
4736
4737 SmallVector<Expr *, 5> APIOrderedArgs;
4738 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4739 APIOrderedArgs.push_back(Args[0]);
4740 switch (Form) {
4741 case Init:
4742 case Load:
4743 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4744 break;
4745 case LoadCopy:
4746 case Copy:
4747 case Arithmetic:
4748 case Xchg:
4749 APIOrderedArgs.push_back(Args[2]); // Val1
4750 APIOrderedArgs.push_back(Args[1]); // Order
4751 break;
4752 case GNUXchg:
4753 APIOrderedArgs.push_back(Args[2]); // Val1
4754 APIOrderedArgs.push_back(Args[3]); // Val2
4755 APIOrderedArgs.push_back(Args[1]); // Order
4756 break;
4757 case C11CmpXchg:
4758 APIOrderedArgs.push_back(Args[2]); // Val1
4759 APIOrderedArgs.push_back(Args[4]); // Val2
4760 APIOrderedArgs.push_back(Args[1]); // Order
4761 APIOrderedArgs.push_back(Args[3]); // OrderFail
4762 break;
4763 case GNUCmpXchg:
4764 APIOrderedArgs.push_back(Args[2]); // Val1
4765 APIOrderedArgs.push_back(Args[4]); // Val2
4766 APIOrderedArgs.push_back(Args[5]); // Weak
4767 APIOrderedArgs.push_back(Args[1]); // Order
4768 APIOrderedArgs.push_back(Args[3]); // OrderFail
4769 break;
4770 case TestAndSetByte:
4771 case ClearByte:
4772 APIOrderedArgs.push_back(Args[1]); // Order
4773 break;
4774 }
4775 } else
4776 APIOrderedArgs.append(Args.begin(), Args.end());
4777
4778 // The first argument's non-CV pointer type is used to deduce the type of
4779 // subsequent arguments, except for:
4780 // - weak flag (always converted to bool)
4781 // - memory order (always converted to int)
4782 // - scope (always converted to int)
4783 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4784 QualType Ty;
4785 if (i < NumVals[Form] + 1) {
4786 switch (i) {
4787 case 0:
4788 // The first argument is always a pointer. It has a fixed type.
4789 // It is always dereferenced, a nullptr is undefined.
4790 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4791 // Nothing else to do: we already know all we want about this pointer.
4792 continue;
4793 case 1:
4794 // The second argument is the non-atomic operand. For arithmetic, this
4795 // is always passed by value, and for a compare_exchange it is always
4796 // passed by address. For the rest, GNU uses by-address and C11 uses
4797 // by-value.
4798 assert(Form != Load);
4799 if (Form == Arithmetic && ValType->isPointerType())
4800 Ty = Context.getPointerDiffType();
4801 else if (Form == Init || Form == Arithmetic)
4802 Ty = ValType;
4803 else if (Form == Copy || Form == Xchg) {
4804 if (IsPassedByAddress) {
4805 // The value pointer is always dereferenced, a nullptr is undefined.
4806 CheckNonNullArgument(*this, APIOrderedArgs[i],
4807 ExprRange.getBegin());
4808 }
4809 Ty = ByValType;
4810 } else {
4811 Expr *ValArg = APIOrderedArgs[i];
4812 // The value pointer is always dereferenced, a nullptr is undefined.
4813 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4815 // Keep address space of non-atomic pointer type.
4816 if (const PointerType *PtrTy =
4817 ValArg->getType()->getAs<PointerType>()) {
4818 AS = PtrTy->getPointeeType().getAddressSpace();
4819 }
4820 Ty = Context.getPointerType(
4821 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4822 }
4823 break;
4824 case 2:
4825 // The third argument to compare_exchange / GNU exchange is the desired
4826 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4827 if (IsPassedByAddress)
4828 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4829 Ty = ByValType;
4830 break;
4831 case 3:
4832 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4833 Ty = Context.BoolTy;
4834 break;
4835 }
4836 } else {
4837 // The order(s) and scope are always converted to int.
4838 Ty = Context.IntTy;
4839 }
4840
4841 InitializedEntity Entity =
4843 ExprResult Arg = APIOrderedArgs[i];
4844 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4845 if (Arg.isInvalid())
4846 return true;
4847 APIOrderedArgs[i] = Arg.get();
4848 }
4849
4850 // Permute the arguments into a 'consistent' order.
4851 SmallVector<Expr*, 5> SubExprs;
4852 SubExprs.push_back(Ptr);
4853 switch (Form) {
4854 case Init:
4855 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4856 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4857 break;
4858 case Load:
4859 case TestAndSetByte:
4860 case ClearByte:
4861 SubExprs.push_back(APIOrderedArgs[1]); // Order
4862 break;
4863 case LoadCopy:
4864 case Copy:
4865 case Arithmetic:
4866 case Xchg:
4867 SubExprs.push_back(APIOrderedArgs[2]); // Order
4868 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4869 break;
4870 case GNUXchg:
4871 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4872 SubExprs.push_back(APIOrderedArgs[3]); // Order
4873 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4874 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4875 break;
4876 case C11CmpXchg:
4877 SubExprs.push_back(APIOrderedArgs[3]); // Order
4878 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4879 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4880 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4881 break;
4882 case GNUCmpXchg:
4883 SubExprs.push_back(APIOrderedArgs[4]); // Order
4884 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4885 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4886 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4887 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4888 break;
4889 }
4890
4891 // If the memory orders are constants, check they are valid.
4892 if (SubExprs.size() >= 2 && Form != Init) {
4893 std::optional<llvm::APSInt> Success =
4894 SubExprs[1]->getIntegerConstantExpr(Context);
4895 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4896 Diag(SubExprs[1]->getBeginLoc(),
4897 diag::warn_atomic_op_has_invalid_memory_order)
4898 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4899 << SubExprs[1]->getSourceRange();
4900 }
4901 if (SubExprs.size() >= 5) {
4902 if (std::optional<llvm::APSInt> Failure =
4903 SubExprs[3]->getIntegerConstantExpr(Context)) {
4904 if (!llvm::is_contained(
4905 {llvm::AtomicOrderingCABI::relaxed,
4906 llvm::AtomicOrderingCABI::consume,
4907 llvm::AtomicOrderingCABI::acquire,
4908 llvm::AtomicOrderingCABI::seq_cst},
4909 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4910 Diag(SubExprs[3]->getBeginLoc(),
4911 diag::warn_atomic_op_has_invalid_memory_order)
4912 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4913 }
4914 }
4915 }
4916 }
4917
4918 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4919 auto *Scope = Args[Args.size() - 1];
4920 if (std::optional<llvm::APSInt> Result =
4921 Scope->getIntegerConstantExpr(Context)) {
4922 if (!ScopeModel->isValid(Result->getZExtValue()))
4923 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4924 << Scope->getSourceRange();
4925 }
4926 SubExprs.push_back(Scope);
4927 }
4928
4929 AtomicExpr *AE = new (Context)
4930 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4931
4932 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4933 Op == AtomicExpr::AO__c11_atomic_store ||
4934 Op == AtomicExpr::AO__opencl_atomic_load ||
4935 Op == AtomicExpr::AO__hip_atomic_load ||
4936 Op == AtomicExpr::AO__opencl_atomic_store ||
4937 Op == AtomicExpr::AO__hip_atomic_store) &&
4938 Context.AtomicUsesUnsupportedLibcall(AE))
4939 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4940 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4941 Op == AtomicExpr::AO__opencl_atomic_load ||
4942 Op == AtomicExpr::AO__hip_atomic_load)
4943 ? 0
4944 : 1);
4945
4946 if (ValType->isBitIntType()) {
4947 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4948 return ExprError();
4949 }
4950
4951 return AE;
4952}
4953
4954/// checkBuiltinArgument - Given a call to a builtin function, perform
4955/// normal type-checking on the given argument, updating the call in
4956/// place. This is useful when a builtin function requires custom
4957/// type-checking for some of its arguments but not necessarily all of
4958/// them.
4959///
4960/// Returns true on error.
4961static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4962 FunctionDecl *Fn = E->getDirectCallee();
4963 assert(Fn && "builtin call without direct callee!");
4964
4965 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4966 InitializedEntity Entity =
4968
4969 ExprResult Arg = E->getArg(ArgIndex);
4970 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4971 if (Arg.isInvalid())
4972 return true;
4973
4974 E->setArg(ArgIndex, Arg.get());
4975 return false;
4976}
4977
4978ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4979 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4980 Expr *Callee = TheCall->getCallee();
4981 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4982 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4983
4984 // Ensure that we have at least one argument to do type inference from.
4985 if (TheCall->getNumArgs() < 1) {
4986 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4987 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4988 << Callee->getSourceRange();
4989 return ExprError();
4990 }
4991
4992 // Inspect the first argument of the atomic builtin. This should always be
4993 // a pointer type, whose element is an integral scalar or pointer type.
4994 // Because it is a pointer type, we don't have to worry about any implicit
4995 // casts here.
4996 // FIXME: We don't allow floating point scalars as input.
4997 Expr *FirstArg = TheCall->getArg(0);
4998 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4999 if (FirstArgResult.isInvalid())
5000 return ExprError();
5001 FirstArg = FirstArgResult.get();
5002 TheCall->setArg(0, FirstArg);
5003
5004 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5005 if (!pointerType) {
5006 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5007 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5008 return ExprError();
5009 }
5010
5011 QualType ValType = pointerType->getPointeeType();
5012 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5013 !ValType->isBlockPointerType()) {
5014 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5015 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5016 return ExprError();
5017 }
5018 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5019 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5020 Diag(FirstArg->getBeginLoc(),
5021 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5022 << 1 << ValType << FirstArg->getSourceRange();
5023 return ExprError();
5024 }
5025
5026 if (ValType.isConstQualified()) {
5027 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5028 << FirstArg->getType() << FirstArg->getSourceRange();
5029 return ExprError();
5030 }
5031
5032 switch (ValType.getObjCLifetime()) {
5035 // okay
5036 break;
5037
5041 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5042 << ValType << FirstArg->getSourceRange();
5043 return ExprError();
5044 }
5045
5046 // Strip any qualifiers off ValType.
5047 ValType = ValType.getUnqualifiedType();
5048
5049 // The majority of builtins return a value, but a few have special return
5050 // types, so allow them to override appropriately below.
5051 QualType ResultType = ValType;
5052
5053 // We need to figure out which concrete builtin this maps onto. For example,
5054 // __sync_fetch_and_add with a 2 byte object turns into
5055 // __sync_fetch_and_add_2.
5056#define BUILTIN_ROW(x) \
5057 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5058 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5059
5060 static const unsigned BuiltinIndices[][5] = {
5061 BUILTIN_ROW(__sync_fetch_and_add),
5062 BUILTIN_ROW(__sync_fetch_and_sub),
5063 BUILTIN_ROW(__sync_fetch_and_or),
5064 BUILTIN_ROW(__sync_fetch_and_and),
5065 BUILTIN_ROW(__sync_fetch_and_xor),
5066 BUILTIN_ROW(__sync_fetch_and_nand),
5067
5068 BUILTIN_ROW(__sync_add_and_fetch),
5069 BUILTIN_ROW(__sync_sub_and_fetch),
5070 BUILTIN_ROW(__sync_and_and_fetch),
5071 BUILTIN_ROW(__sync_or_and_fetch),
5072 BUILTIN_ROW(__sync_xor_and_fetch),
5073 BUILTIN_ROW(__sync_nand_and_fetch),
5074
5075 BUILTIN_ROW(__sync_val_compare_and_swap),
5076 BUILTIN_ROW(__sync_bool_compare_and_swap),
5077 BUILTIN_ROW(__sync_lock_test_and_set),
5078 BUILTIN_ROW(__sync_lock_release),
5079 BUILTIN_ROW(__sync_swap)
5080 };
5081#undef BUILTIN_ROW
5082
5083 // Determine the index of the size.
5084 unsigned SizeIndex;
5085 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5086 case 1: SizeIndex = 0; break;
5087 case 2: SizeIndex = 1; break;
5088 case 4: SizeIndex = 2; break;
5089 case 8: SizeIndex = 3; break;
5090 case 16: SizeIndex = 4; break;
5091 default:
5092 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5093 << FirstArg->getType() << FirstArg->getSourceRange();
5094 return ExprError();
5095 }
5096
5097 // Each of these builtins has one pointer argument, followed by some number of
5098 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5099 // that we ignore. Find out which row of BuiltinIndices to read from as well
5100 // as the number of fixed args.
5101 unsigned BuiltinID = FDecl->getBuiltinID();
5102 unsigned BuiltinIndex, NumFixed = 1;
5103 bool WarnAboutSemanticsChange = false;
5104 switch (BuiltinID) {
5105 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5106 case Builtin::BI__sync_fetch_and_add:
5107 case Builtin::BI__sync_fetch_and_add_1:
5108 case Builtin::BI__sync_fetch_and_add_2:
5109 case Builtin::BI__sync_fetch_and_add_4:
5110 case Builtin::BI__sync_fetch_and_add_8:
5111 case Builtin::BI__sync_fetch_and_add_16:
5112 BuiltinIndex = 0;
5113 break;
5114
5115 case Builtin::BI__sync_fetch_and_sub:
5116 case Builtin::BI__sync_fetch_and_sub_1:
5117 case Builtin::BI__sync_fetch_and_sub_2:
5118 case Builtin::BI__sync_fetch_and_sub_4:
5119 case Builtin::BI__sync_fetch_and_sub_8:
5120 case Builtin::BI__sync_fetch_and_sub_16:
5121 BuiltinIndex = 1;
5122 break;
5123
5124 case Builtin::BI__sync_fetch_and_or:
5125 case Builtin::BI__sync_fetch_and_or_1:
5126 case Builtin::BI__sync_fetch_and_or_2:
5127 case Builtin::BI__sync_fetch_and_or_4:
5128 case Builtin::BI__sync_fetch_and_or_8:
5129 case Builtin::BI__sync_fetch_and_or_16:
5130 BuiltinIndex = 2;
5131 break;
5132
5133 case Builtin::BI__sync_fetch_and_and:
5134 case Builtin::BI__sync_fetch_and_and_1:
5135 case Builtin::BI__sync_fetch_and_and_2:
5136 case Builtin::BI__sync_fetch_and_and_4:
5137 case Builtin::BI__sync_fetch_and_and_8:
5138 case Builtin::BI__sync_fetch_and_and_16:
5139 BuiltinIndex = 3;
5140 break;
5141
5142 case Builtin::BI__sync_fetch_and_xor:
5143 case Builtin::BI__sync_fetch_and_xor_1:
5144 case Builtin::BI__sync_fetch_and_xor_2:
5145 case Builtin::BI__sync_fetch_and_xor_4:
5146 case Builtin::BI__sync_fetch_and_xor_8:
5147 case Builtin::BI__sync_fetch_and_xor_16:
5148 BuiltinIndex = 4;
5149 break;
5150
5151 case Builtin::BI__sync_fetch_and_nand:
5152 case Builtin::BI__sync_fetch_and_nand_1:
5153 case Builtin::BI__sync_fetch_and_nand_2:
5154 case Builtin::BI__sync_fetch_and_nand_4:
5155 case Builtin::BI__sync_fetch_and_nand_8:
5156 case Builtin::BI__sync_fetch_and_nand_16:
5157 BuiltinIndex = 5;
5158 WarnAboutSemanticsChange = true;
5159 break;
5160
5161 case Builtin::BI__sync_add_and_fetch:
5162 case Builtin::BI__sync_add_and_fetch_1:
5163 case Builtin::BI__sync_add_and_fetch_2:
5164 case Builtin::BI__sync_add_and_fetch_4:
5165 case Builtin::BI__sync_add_and_fetch_8:
5166 case Builtin::BI__sync_add_and_fetch_16:
5167 BuiltinIndex = 6;
5168 break;
5169
5170 case Builtin::BI__sync_sub_and_fetch:
5171 case Builtin::BI__sync_sub_and_fetch_1:
5172 case Builtin::BI__sync_sub_and_fetch_2:
5173 case Builtin::BI__sync_sub_and_fetch_4:
5174 case Builtin::BI__sync_sub_and_fetch_8:
5175 case Builtin::BI__sync_sub_and_fetch_16:
5176 BuiltinIndex = 7;
5177 break;
5178
5179 case Builtin::BI__sync_and_and_fetch:
5180 case Builtin::BI__sync_and_and_fetch_1:
5181 case Builtin::BI__sync_and_and_fetch_2:
5182 case Builtin::BI__sync_and_and_fetch_4:
5183 case Builtin::BI__sync_and_and_fetch_8:
5184 case Builtin::BI__sync_and_and_fetch_16:
5185 BuiltinIndex = 8;
5186 break;
5187
5188 case Builtin::BI__sync_or_and_fetch:
5189 case Builtin::BI__sync_or_and_fetch_1:
5190 case Builtin::BI__sync_or_and_fetch_2:
5191 case Builtin::BI__sync_or_and_fetch_4:
5192 case Builtin::BI__sync_or_and_fetch_8:
5193 case Builtin::BI__sync_or_and_fetch_16:
5194 BuiltinIndex = 9;
5195 break;
5196
5197 case Builtin::BI__sync_xor_and_fetch:
5198 case Builtin::BI__sync_xor_and_fetch_1:
5199 case Builtin::BI__sync_xor_and_fetch_2:
5200 case Builtin::BI__sync_xor_and_fetch_4:
5201 case Builtin::BI__sync_xor_and_fetch_8:
5202 case Builtin::BI__sync_xor_and_fetch_16:
5203 BuiltinIndex = 10;
5204 break;
5205
5206 case Builtin::BI__sync_nand_and_fetch:
5207 case Builtin::BI__sync_nand_and_fetch_1:
5208 case Builtin::BI__sync_nand_and_fetch_2:
5209 case Builtin::BI__sync_nand_and_fetch_4:
5210 case Builtin::BI__sync_nand_and_fetch_8:
5211 case Builtin::BI__sync_nand_and_fetch_16:
5212 BuiltinIndex = 11;
5213 WarnAboutSemanticsChange = true;
5214 break;
5215
5216 case Builtin::BI__sync_val_compare_and_swap:
5217 case Builtin::BI__sync_val_compare_and_swap_1:
5218 case Builtin::BI__sync_val_compare_and_swap_2:
5219 case Builtin::BI__sync_val_compare_and_swap_4:
5220 case Builtin::BI__sync_val_compare_and_swap_8:
5221 case Builtin::BI__sync_val_compare_and_swap_16:
5222 BuiltinIndex = 12;
5223 NumFixed = 2;
5224 break;
5225
5226 case Builtin::BI__sync_bool_compare_and_swap:
5227 case Builtin::BI__sync_bool_compare_and_swap_1:
5228 case Builtin::BI__sync_bool_compare_and_swap_2:
5229 case Builtin::BI__sync_bool_compare_and_swap_4:
5230 case Builtin::BI__sync_bool_compare_and_swap_8:
5231 case Builtin::BI__sync_bool_compare_and_swap_16:
5232 BuiltinIndex = 13;
5233 NumFixed = 2;
5234 ResultType = Context.BoolTy;
5235 break;
5236
5237 case Builtin::BI__sync_lock_test_and_set:
5238 case Builtin::BI__sync_lock_test_and_set_1:
5239 case Builtin::BI__sync_lock_test_and_set_2:
5240 case Builtin::BI__sync_lock_test_and_set_4:
5241 case Builtin::BI__sync_lock_test_and_set_8:
5242 case Builtin::BI__sync_lock_test_and_set_16:
5243 BuiltinIndex = 14;
5244 break;
5245
5246 case Builtin::BI__sync_lock_release:
5247 case Builtin::BI__sync_lock_release_1:
5248 case Builtin::BI__sync_lock_release_2:
5249 case Builtin::BI__sync_lock_release_4:
5250 case Builtin::BI__sync_lock_release_8:
5251 case Builtin::BI__sync_lock_release_16:
5252 BuiltinIndex = 15;
5253 NumFixed = 0;
5254 ResultType = Context.VoidTy;
5255 break;
5256
5257 case Builtin::BI__sync_swap:
5258 case Builtin::BI__sync_swap_1:
5259 case Builtin::BI__sync_swap_2:
5260 case Builtin::BI__sync_swap_4:
5261 case Builtin::BI__sync_swap_8:
5262 case Builtin::BI__sync_swap_16:
5263 BuiltinIndex = 16;
5264 break;
5265 }
5266
5267 // Now that we know how many fixed arguments we expect, first check that we
5268 // have at least that many.
5269 if (TheCall->getNumArgs() < 1+NumFixed) {
5270 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5271 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5272 << Callee->getSourceRange();
5273 return ExprError();
5274 }
5275
5276 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5277 << Callee->getSourceRange();
5278
5279 if (WarnAboutSemanticsChange) {
5280 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5281 << Callee->getSourceRange();
5282 }
5283
5284 // Get the decl for the concrete builtin from this, we can tell what the
5285 // concrete integer type we should convert to is.
5286 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5287 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5288 FunctionDecl *NewBuiltinDecl;
5289 if (NewBuiltinID == BuiltinID)
5290 NewBuiltinDecl = FDecl;
5291 else {
5292 // Perform builtin lookup to avoid redeclaring it.
5293 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5294 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5295 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5296 assert(Res.getFoundDecl());
5297 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5298 if (!NewBuiltinDecl)
5299 return ExprError();
5300 }
5301
5302 // The first argument --- the pointer --- has a fixed type; we
5303 // deduce the types of the rest of the arguments accordingly. Walk
5304 // the remaining arguments, converting them to the deduced value type.
5305 for (unsigned i = 0; i != NumFixed; ++i) {
5306 ExprResult Arg = TheCall->getArg(i+1);
5307
5308 // GCC does an implicit conversion to the pointer or integer ValType. This
5309 // can fail in some cases (1i -> int**), check for this error case now.
5310 // Initialize the argument.
5311 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5312 ValType, /*consume*/ false);
5313 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5314 if (Arg.isInvalid())
5315 return ExprError();
5316
5317 // Okay, we have something that *can* be converted to the right type. Check
5318 // to see if there is a potentially weird extension going on here. This can
5319 // happen when you do an atomic operation on something like an char* and
5320 // pass in 42. The 42 gets converted to char. This is even more strange
5321 // for things like 45.123 -> char, etc.
5322 // FIXME: Do this check.
5323 TheCall->setArg(i+1, Arg.get());
5324 }
5325
5326 // Create a new DeclRefExpr to refer to the new decl.
5327 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5328 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5329 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5330 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5331
5332 // Set the callee in the CallExpr.
5333 // FIXME: This loses syntactic information.
5334 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5335 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5336 CK_BuiltinFnToFnPtr);
5337 TheCall->setCallee(PromotedCall.get());
5338
5339 // Change the result type of the call to match the original value type. This
5340 // is arbitrary, but the codegen for these builtins ins design to handle it
5341 // gracefully.
5342 TheCall->setType(ResultType);
5343
5344 // Prohibit problematic uses of bit-precise integer types with atomic
5345 // builtins. The arguments would have already been converted to the first
5346 // argument's type, so only need to check the first argument.
5347 const auto *BitIntValType = ValType->getAs<BitIntType>();
5348 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5349 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5350 return ExprError();
5351 }
5352
5353 return TheCallResult;
5354}
5355
5356ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5357 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5358 DeclRefExpr *DRE =
5360 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5361 unsigned BuiltinID = FDecl->getBuiltinID();
5362 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5363 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5364 "Unexpected nontemporal load/store builtin!");
5365 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5366 unsigned numArgs = isStore ? 2 : 1;
5367
5368 // Ensure that we have the proper number of arguments.
5369 if (checkArgCount(TheCall, numArgs))
5370 return ExprError();
5371
5372 // Inspect the last argument of the nontemporal builtin. This should always
5373 // be a pointer type, from which we imply the type of the memory access.
5374 // Because it is a pointer type, we don't have to worry about any implicit
5375 // casts here.
5376 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5377 ExprResult PointerArgResult =
5379
5380 if (PointerArgResult.isInvalid())
5381 return ExprError();
5382 PointerArg = PointerArgResult.get();
5383 TheCall->setArg(numArgs - 1, PointerArg);
5384
5385 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5386 if (!pointerType) {
5387 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5388 << PointerArg->getType() << PointerArg->getSourceRange();
5389 return ExprError();
5390 }
5391
5392 QualType ValType = pointerType->getPointeeType();
5393
5394 // Strip any qualifiers off ValType.
5395 ValType = ValType.getUnqualifiedType();
5396 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5397 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5398 !ValType->isVectorType()) {
5399 Diag(DRE->getBeginLoc(),
5400 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5401 << PointerArg->getType() << PointerArg->getSourceRange();
5402 return ExprError();
5403 }
5404
5405 if (!isStore) {
5406 TheCall->setType(ValType);
5407 return TheCallResult;
5408 }
5409
5410 ExprResult ValArg = TheCall->getArg(0);
5411 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5412 Context, ValType, /*consume*/ false);
5413 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5414 if (ValArg.isInvalid())
5415 return ExprError();
5416
5417 TheCall->setArg(0, ValArg.get());
5418 TheCall->setType(Context.VoidTy);
5419 return TheCallResult;
5420}
5421
5422/// CheckObjCString - Checks that the format string argument to the os_log()
5423/// and os_trace() functions is correct, and converts it to const char *.
5424ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5425 Arg = Arg->IgnoreParenCasts();
5426 auto *Literal = dyn_cast<StringLiteral>(Arg);
5427 if (!Literal) {
5428 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5429 Literal = ObjcLiteral->getString();
5430 }
5431 }
5432
5433 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5434 return ExprError(
5435 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5436 << Arg->getSourceRange());
5437 }
5438
5439 ExprResult Result(Literal);
5440 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5441 InitializedEntity Entity =
5443 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5444 return Result;
5445}
5446
5447/// Check that the user is calling the appropriate va_start builtin for the
5448/// target and calling convention.
5449static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5450 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5451 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5452 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5453 TT.getArch() == llvm::Triple::aarch64_32);
5454 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5455 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5456 if (IsX64 || IsAArch64) {
5457 CallingConv CC = CC_C;
5458 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5459 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5460 if (IsMSVAStart) {
5461 // Don't allow this in System V ABI functions.
5462 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5463 return S.Diag(Fn->getBeginLoc(),
5464 diag::err_ms_va_start_used_in_sysv_function);
5465 } else {
5466 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5467 // On x64 Windows, don't allow this in System V ABI functions.
5468 // (Yes, that means there's no corresponding way to support variadic
5469 // System V ABI functions on Windows.)
5470 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5471 (!IsWindowsOrUEFI && CC == CC_Win64))
5472 return S.Diag(Fn->getBeginLoc(),
5473 diag::err_va_start_used_in_wrong_abi_function)
5474 << !IsWindowsOrUEFI;
5475 }
5476 return false;
5477 }
5478
5479 if (IsMSVAStart)
5480 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5481 return false;
5482}
5483
5485 ParmVarDecl **LastParam = nullptr) {
5486 // Determine whether the current function, block, or obj-c method is variadic
5487 // and get its parameter list.
5488 bool IsVariadic = false;
5490 DeclContext *Caller = S.CurContext;
5491 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5492 IsVariadic = Block->isVariadic();
5493 Params = Block->parameters();
5494 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5495 IsVariadic = FD->isVariadic();
5496 Params = FD->parameters();
5497 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5498 IsVariadic = MD->isVariadic();
5499 // FIXME: This isn't correct for methods (results in bogus warning).
5500 Params = MD->parameters();
5501 } else if (isa<CapturedDecl>(Caller)) {
5502 // We don't support va_start in a CapturedDecl.
5503 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5504 return true;
5505 } else {
5506 // This must be some other declcontext that parses exprs.
5507 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5508 return true;
5509 }
5510
5511 if (!IsVariadic) {
5512 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5513 return true;
5514 }
5515
5516 if (LastParam)
5517 *LastParam = Params.empty() ? nullptr : Params.back();
5518
5519 return false;
5520}
5521
5522bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5523 Expr *Fn = TheCall->getCallee();
5524 if (checkVAStartABI(*this, BuiltinID, Fn))
5525 return true;
5526
5527 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5528 // This builtin requires one argument (the va_list), allows two arguments,
5529 // but diagnoses more than two arguments. e.g.,
5530 // __builtin_c23_va_start(); // error
5531 // __builtin_c23_va_start(list); // ok
5532 // __builtin_c23_va_start(list, param); // ok
5533 // __builtin_c23_va_start(list, anything, anything); // error
5534 // This differs from the GCC behavior in that they accept the last case
5535 // with a warning, but it doesn't seem like a useful behavior to allow.
5536 if (checkArgCountRange(TheCall, 1, 2))
5537 return true;
5538 } else {
5539 // In C23 mode, va_start only needs one argument. However, the builtin still
5540 // requires two arguments (which matches the behavior of the GCC builtin),
5541 // <stdarg.h> passes `0` as the second argument in C23 mode.
5542 if (checkArgCount(TheCall, 2))
5543 return true;
5544 }
5545
5546 // Type-check the first argument normally.
5547 if (checkBuiltinArgument(*this, TheCall, 0))
5548 return true;
5549
5550 // Check that the current function is variadic, and get its last parameter.
5551 ParmVarDecl *LastParam;
5552 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5553 return true;
5554
5555 // Verify that the second argument to the builtin is the last non-variadic
5556 // argument of the current function or method. In C23 mode, if the call is
5557 // not to __builtin_c23_va_start, and the second argument is an integer
5558 // constant expression with value 0, then we don't bother with this check.
5559 // For __builtin_c23_va_start, we only perform the check for the second
5560 // argument being the last argument to the current function if there is a
5561 // second argument present.
5562 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5563 TheCall->getNumArgs() < 2) {
5564 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5565 return false;
5566 }
5567
5568 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5569 if (std::optional<llvm::APSInt> Val =
5571 Val && LangOpts.C23 && *Val == 0 &&
5572 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5573 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5574 return false;
5575 }
5576
5577 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5578 // next block.
5579 QualType Type;
5580 SourceLocation ParamLoc;
5581 bool IsCRegister = false;
5582 bool SecondArgIsLastNonVariadicArgument = false;
5583 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5584 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5585 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5586
5587 Type = PV->getType();
5588 ParamLoc = PV->getLocation();
5589 IsCRegister =
5590 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5591 }
5592 }
5593
5594 if (!SecondArgIsLastNonVariadicArgument)
5595 Diag(TheCall->getArg(1)->getBeginLoc(),
5596 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5597 else if (IsCRegister || Type->isReferenceType() ||
5598 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5599 // Promotable integers are UB, but enumerations need a bit of
5600 // extra checking to see what their promotable type actually is.
5601 if (!Context.isPromotableIntegerType(Type))
5602 return false;
5603 const auto *ED = Type->getAsEnumDecl();
5604 if (!ED)
5605 return true;
5606 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5607 }()) {
5608 unsigned Reason = 0;
5609 if (Type->isReferenceType()) Reason = 1;
5610 else if (IsCRegister) Reason = 2;
5611 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5612 Diag(ParamLoc, diag::note_parameter_type) << Type;
5613 }
5614
5615 return false;
5616}
5617
5618bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5619 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5620 const LangOptions &LO = getLangOpts();
5621
5622 if (LO.CPlusPlus)
5623 return Arg->getType()
5625 .getTypePtr()
5626 ->getPointeeType()
5628
5629 // In C, allow aliasing through `char *`, this is required for AArch64 at
5630 // least.
5631 return true;
5632 };
5633
5634 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5635 // const char *named_addr);
5636
5637 Expr *Func = Call->getCallee();
5638
5639 if (Call->getNumArgs() < 3)
5640 return Diag(Call->getEndLoc(),
5641 diag::err_typecheck_call_too_few_args_at_least)
5642 << 0 /*function call*/ << 3 << Call->getNumArgs()
5643 << /*is non object*/ 0;
5644
5645 // Type-check the first argument normally.
5646 if (checkBuiltinArgument(*this, Call, 0))
5647 return true;
5648
5649 // Check that the current function is variadic.
5651 return true;
5652
5653 // __va_start on Windows does not validate the parameter qualifiers
5654
5655 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5656 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5657
5658 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5659 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5660
5661 const QualType &ConstCharPtrTy =
5662 Context.getPointerType(Context.CharTy.withConst());
5663 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5664 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5665 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5666 << 0 /* qualifier difference */
5667 << 3 /* parameter mismatch */
5668 << 2 << Arg1->getType() << ConstCharPtrTy;
5669
5670 const QualType SizeTy = Context.getSizeType();
5671 if (!Context.hasSameType(
5673 SizeTy))
5674 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5675 << Arg2->getType() << SizeTy << 1 /* different class */
5676 << 0 /* qualifier difference */
5677 << 3 /* parameter mismatch */
5678 << 3 << Arg2->getType() << SizeTy;
5679
5680 return false;
5681}
5682
5683bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5684 if (checkArgCount(TheCall, 2))
5685 return true;
5686
5687 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5688 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5689 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5690 << 1 << 0 << TheCall->getSourceRange();
5691
5692 ExprResult OrigArg0 = TheCall->getArg(0);
5693 ExprResult OrigArg1 = TheCall->getArg(1);
5694
5695 // Do standard promotions between the two arguments, returning their common
5696 // type.
5697 QualType Res = UsualArithmeticConversions(
5698 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5699 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5700 return true;
5701
5702 // Make sure any conversions are pushed back into the call; this is
5703 // type safe since unordered compare builtins are declared as "_Bool
5704 // foo(...)".
5705 TheCall->setArg(0, OrigArg0.get());
5706 TheCall->setArg(1, OrigArg1.get());
5707
5708 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5709 return false;
5710
5711 // If the common type isn't a real floating type, then the arguments were
5712 // invalid for this operation.
5713 if (Res.isNull() || !Res->isRealFloatingType())
5714 return Diag(OrigArg0.get()->getBeginLoc(),
5715 diag::err_typecheck_call_invalid_ordered_compare)
5716 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5717 << SourceRange(OrigArg0.get()->getBeginLoc(),
5718 OrigArg1.get()->getEndLoc());
5719
5720 return false;
5721}
5722
5723bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5724 unsigned BuiltinID) {
5725 if (checkArgCount(TheCall, NumArgs))
5726 return true;
5727
5728 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5729 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5730 BuiltinID == Builtin::BI__builtin_isinf ||
5731 BuiltinID == Builtin::BI__builtin_isinf_sign))
5732 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5733 << 0 << 0 << TheCall->getSourceRange();
5734
5735 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5736 BuiltinID == Builtin::BI__builtin_isunordered))
5737 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5738 << 1 << 0 << TheCall->getSourceRange();
5739
5740 bool IsFPClass = NumArgs == 2;
5741
5742 // Find out position of floating-point argument.
5743 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5744
5745 // We can count on all parameters preceding the floating-point just being int.
5746 // Try all of those.
5747 for (unsigned i = 0; i < FPArgNo; ++i) {
5748 Expr *Arg = TheCall->getArg(i);
5749
5750 if (Arg->isTypeDependent())
5751 return false;
5752
5755
5756 if (Res.isInvalid())
5757 return true;
5758 TheCall->setArg(i, Res.get());
5759 }
5760
5761 Expr *OrigArg = TheCall->getArg(FPArgNo);
5762
5763 if (OrigArg->isTypeDependent())
5764 return false;
5765
5766 // Usual Unary Conversions will convert half to float, which we want for
5767 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5768 // type how it is, but do normal L->Rvalue conversions.
5769 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5770 ExprResult Res = UsualUnaryConversions(OrigArg);
5771
5772 if (!Res.isUsable())
5773 return true;
5774 OrigArg = Res.get();
5775 } else {
5777
5778 if (!Res.isUsable())
5779 return true;
5780 OrigArg = Res.get();
5781 }
5782 TheCall->setArg(FPArgNo, OrigArg);
5783
5784 QualType VectorResultTy;
5785 QualType ElementTy = OrigArg->getType();
5786 // TODO: When all classification function are implemented with is_fpclass,
5787 // vector argument can be supported in all of them.
5788 if (ElementTy->isVectorType() && IsFPClass) {
5789 VectorResultTy = GetSignedVectorType(ElementTy);
5790 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5791 }
5792
5793 // This operation requires a non-_Complex floating-point number.
5794 if (!ElementTy->isRealFloatingType())
5795 return Diag(OrigArg->getBeginLoc(),
5796 diag::err_typecheck_call_invalid_unary_fp)
5797 << OrigArg->getType() << OrigArg->getSourceRange();
5798
5799 // __builtin_isfpclass has integer parameter that specify test mask. It is
5800 // passed in (...), so it should be analyzed completely here.
5801 if (IsFPClass)
5802 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5803 return true;
5804
5805 // TODO: enable this code to all classification functions.
5806 if (IsFPClass) {
5807 QualType ResultTy;
5808 if (!VectorResultTy.isNull())
5809 ResultTy = VectorResultTy;
5810 else
5811 ResultTy = Context.IntTy;
5812 TheCall->setType(ResultTy);
5813 }
5814
5815 return false;
5816}
5817
5818bool Sema::BuiltinComplex(CallExpr *TheCall) {
5819 if (checkArgCount(TheCall, 2))
5820 return true;
5821
5822 bool Dependent = false;
5823 for (unsigned I = 0; I != 2; ++I) {
5824 Expr *Arg = TheCall->getArg(I);
5825 QualType T = Arg->getType();
5826 if (T->isDependentType()) {
5827 Dependent = true;
5828 continue;
5829 }
5830
5831 // Despite supporting _Complex int, GCC requires a real floating point type
5832 // for the operands of __builtin_complex.
5833 if (!T->isRealFloatingType()) {
5834 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5835 << Arg->getType() << Arg->getSourceRange();
5836 }
5837
5838 ExprResult Converted = DefaultLvalueConversion(Arg);
5839 if (Converted.isInvalid())
5840 return true;
5841 TheCall->setArg(I, Converted.get());
5842 }
5843
5844 if (Dependent) {
5845 TheCall->setType(Context.DependentTy);
5846 return false;
5847 }
5848
5849 Expr *Real = TheCall->getArg(0);
5850 Expr *Imag = TheCall->getArg(1);
5851 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5852 return Diag(Real->getBeginLoc(),
5853 diag::err_typecheck_call_different_arg_types)
5854 << Real->getType() << Imag->getType()
5855 << Real->getSourceRange() << Imag->getSourceRange();
5856 }
5857
5858 TheCall->setType(Context.getComplexType(Real->getType()));
5859 return false;
5860}
5861
5862/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5863// This is declared to take (...), so we have to check everything.
5865 unsigned NumArgs = TheCall->getNumArgs();
5866 if (NumArgs < 2)
5867 return ExprError(Diag(TheCall->getEndLoc(),
5868 diag::err_typecheck_call_too_few_args_at_least)
5869 << 0 /*function call*/ << 2 << NumArgs
5870 << /*is non object*/ 0 << TheCall->getSourceRange());
5871
5872 // Determine which of the following types of shufflevector we're checking:
5873 // 1) unary, vector mask: (lhs, mask)
5874 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5875 QualType ResType = TheCall->getArg(0)->getType();
5876 unsigned NumElements = 0;
5877
5878 if (!TheCall->getArg(0)->isTypeDependent() &&
5879 !TheCall->getArg(1)->isTypeDependent()) {
5880 QualType LHSType = TheCall->getArg(0)->getType();
5881 QualType RHSType = TheCall->getArg(1)->getType();
5882
5883 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5884 return ExprError(
5885 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5886 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5887 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5888 TheCall->getArg(1)->getEndLoc()));
5889
5890 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5891 unsigned NumResElements = NumArgs - 2;
5892
5893 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5894 // with mask. If so, verify that RHS is an integer vector type with the
5895 // same number of elts as lhs.
5896 if (NumArgs == 2) {
5897 if (!RHSType->hasIntegerRepresentation() ||
5898 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5899 return ExprError(Diag(TheCall->getBeginLoc(),
5900 diag::err_vec_builtin_incompatible_vector)
5901 << TheCall->getDirectCallee()
5902 << /*isMoreThanTwoArgs*/ false
5903 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5904 TheCall->getArg(1)->getEndLoc()));
5905 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5906 return ExprError(Diag(TheCall->getBeginLoc(),
5907 diag::err_vec_builtin_incompatible_vector)
5908 << TheCall->getDirectCallee()
5909 << /*isMoreThanTwoArgs*/ false
5910 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5911 TheCall->getArg(1)->getEndLoc()));
5912 } else if (NumElements != NumResElements) {
5913 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5914 ResType = ResType->isExtVectorType()
5915 ? Context.getExtVectorType(EltType, NumResElements)
5916 : Context.getVectorType(EltType, NumResElements,
5918 }
5919 }
5920
5921 for (unsigned I = 2; I != NumArgs; ++I) {
5922 Expr *Arg = TheCall->getArg(I);
5923 if (Arg->isTypeDependent() || Arg->isValueDependent())
5924 continue;
5925
5926 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5927 if (!Result)
5928 return ExprError(Diag(TheCall->getBeginLoc(),
5929 diag::err_shufflevector_nonconstant_argument)
5930 << Arg->getSourceRange());
5931
5932 // Allow -1 which will be translated to undef in the IR.
5933 if (Result->isSigned() && Result->isAllOnes())
5934 ;
5935 else if (Result->getActiveBits() > 64 ||
5936 Result->getZExtValue() >= NumElements * 2)
5937 return ExprError(Diag(TheCall->getBeginLoc(),
5938 diag::err_shufflevector_argument_too_large)
5939 << Arg->getSourceRange());
5940
5941 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5942 }
5943
5944 auto *Result = new (Context) ShuffleVectorExpr(
5945 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5946 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5947
5948 // All moved to Result.
5949 TheCall->shrinkNumArgs(0);
5950 return Result;
5951}
5952
5954 SourceLocation BuiltinLoc,
5955 SourceLocation RParenLoc) {
5958 QualType DstTy = TInfo->getType();
5959 QualType SrcTy = E->getType();
5960
5961 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5962 return ExprError(Diag(BuiltinLoc,
5963 diag::err_convertvector_non_vector)
5964 << E->getSourceRange());
5965 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5966 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5967 << "second"
5968 << "__builtin_convertvector");
5969
5970 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5971 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5972 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5973 if (SrcElts != DstElts)
5974 return ExprError(Diag(BuiltinLoc,
5975 diag::err_convertvector_incompatible_vector)
5976 << E->getSourceRange());
5977 }
5978
5979 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5980 RParenLoc, CurFPFeatureOverrides());
5981}
5982
5983bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5984 unsigned NumArgs = TheCall->getNumArgs();
5985
5986 if (NumArgs > 3)
5987 return Diag(TheCall->getEndLoc(),
5988 diag::err_typecheck_call_too_many_args_at_most)
5989 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5990 << TheCall->getSourceRange();
5991
5992 // Argument 0 is checked for us and the remaining arguments must be
5993 // constant integers.
5994 for (unsigned i = 1; i != NumArgs; ++i)
5995 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5996 return true;
5997
5998 return false;
5999}
6000
6001bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6002 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6003 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6004 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6005 if (checkArgCount(TheCall, 1))
6006 return true;
6007 Expr *Arg = TheCall->getArg(0);
6008 if (Arg->isInstantiationDependent())
6009 return false;
6010
6011 QualType ArgTy = Arg->getType();
6012 if (!ArgTy->hasFloatingRepresentation())
6013 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6014 << ArgTy;
6015 if (Arg->isLValue()) {
6016 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6017 TheCall->setArg(0, FirstArg.get());
6018 }
6019 TheCall->setType(TheCall->getArg(0)->getType());
6020 return false;
6021}
6022
6023bool Sema::BuiltinAssume(CallExpr *TheCall) {
6024 Expr *Arg = TheCall->getArg(0);
6025 if (Arg->isInstantiationDependent()) return false;
6026
6027 if (Arg->HasSideEffects(Context))
6028 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6029 << Arg->getSourceRange()
6030 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6031
6032 return false;
6033}
6034
6035bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6036 // The alignment must be a constant integer.
6037 Expr *Arg = TheCall->getArg(1);
6038
6039 // We can't check the value of a dependent argument.
6040 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6041 if (const auto *UE =
6042 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6043 if (UE->getKind() == UETT_AlignOf ||
6044 UE->getKind() == UETT_PreferredAlignOf)
6045 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6046 << Arg->getSourceRange();
6047
6048 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6049
6050 if (!Result.isPowerOf2())
6051 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6052 << Arg->getSourceRange();
6053
6054 if (Result < Context.getCharWidth())
6055 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6056 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6057
6058 if (Result > std::numeric_limits<int32_t>::max())
6059 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6060 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6061 }
6062
6063 return false;
6064}
6065
6066bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6067 if (checkArgCountRange(TheCall, 2, 3))
6068 return true;
6069
6070 unsigned NumArgs = TheCall->getNumArgs();
6071 Expr *FirstArg = TheCall->getArg(0);
6072
6073 {
6074 ExprResult FirstArgResult =
6076 if (!FirstArgResult.get()->getType()->isPointerType()) {
6077 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6078 << TheCall->getSourceRange();
6079 return true;
6080 }
6081 TheCall->setArg(0, FirstArgResult.get());
6082 }
6083
6084 // The alignment must be a constant integer.
6085 Expr *SecondArg = TheCall->getArg(1);
6086
6087 // We can't check the value of a dependent argument.
6088 if (!SecondArg->isValueDependent()) {
6089 llvm::APSInt Result;
6090 if (BuiltinConstantArg(TheCall, 1, Result))
6091 return true;
6092
6093 if (!Result.isPowerOf2())
6094 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6095 << SecondArg->getSourceRange();
6096
6098 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6099 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6100
6101 TheCall->setArg(1,
6103 }
6104
6105 if (NumArgs > 2) {
6106 Expr *ThirdArg = TheCall->getArg(2);
6107 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6108 return true;
6109 TheCall->setArg(2, ThirdArg);
6110 }
6111
6112 return false;
6113}
6114
6115bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6116 unsigned BuiltinID =
6117 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6118 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6119
6120 unsigned NumArgs = TheCall->getNumArgs();
6121 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6122 if (NumArgs < NumRequiredArgs) {
6123 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6124 << 0 /* function call */ << NumRequiredArgs << NumArgs
6125 << /*is non object*/ 0 << TheCall->getSourceRange();
6126 }
6127 if (NumArgs >= NumRequiredArgs + 0x100) {
6128 return Diag(TheCall->getEndLoc(),
6129 diag::err_typecheck_call_too_many_args_at_most)
6130 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6131 << /*is non object*/ 0 << TheCall->getSourceRange();
6132 }
6133 unsigned i = 0;
6134
6135 // For formatting call, check buffer arg.
6136 if (!IsSizeCall) {
6137 ExprResult Arg(TheCall->getArg(i));
6138 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6139 Context, Context.VoidPtrTy, false);
6140 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6141 if (Arg.isInvalid())
6142 return true;
6143 TheCall->setArg(i, Arg.get());
6144 i++;
6145 }
6146
6147 // Check string literal arg.
6148 unsigned FormatIdx = i;
6149 {
6150 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6151 if (Arg.isInvalid())
6152 return true;
6153 TheCall->setArg(i, Arg.get());
6154 i++;
6155 }
6156
6157 // Make sure variadic args are scalar.
6158 unsigned FirstDataArg = i;
6159 while (i < NumArgs) {
6161 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6162 if (Arg.isInvalid())
6163 return true;
6164 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6165 if (ArgSize.getQuantity() >= 0x100) {
6166 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6167 << i << (int)ArgSize.getQuantity() << 0xff
6168 << TheCall->getSourceRange();
6169 }
6170 TheCall->setArg(i, Arg.get());
6171 i++;
6172 }
6173
6174 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6175 // call to avoid duplicate diagnostics.
6176 if (!IsSizeCall) {
6177 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6178 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6179 bool Success = CheckFormatArguments(
6180 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6182 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6183 if (!Success)
6184 return true;
6185 }
6186
6187 if (IsSizeCall) {
6188 TheCall->setType(Context.getSizeType());
6189 } else {
6190 TheCall->setType(Context.VoidPtrTy);
6191 }
6192 return false;
6193}
6194
6195bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6196 llvm::APSInt &Result) {
6197 Expr *Arg = TheCall->getArg(ArgNum);
6198
6199 if (Arg->isTypeDependent() || Arg->isValueDependent())
6200 return false;
6201
6202 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6203 if (!R) {
6204 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6205 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6206 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6207 << FDecl->getDeclName() << Arg->getSourceRange();
6208 }
6209 Result = *R;
6210
6211 return false;
6212}
6213
6214bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6215 int High, bool RangeIsError) {
6217 return false;
6218 llvm::APSInt Result;
6219
6220 // We can't check the value of a dependent argument.
6221 Expr *Arg = TheCall->getArg(ArgNum);
6222 if (Arg->isTypeDependent() || Arg->isValueDependent())
6223 return false;
6224
6225 // Check constant-ness first.
6226 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6227 return true;
6228
6229 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6230 if (RangeIsError)
6231 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6232 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6233 else
6234 // Defer the warning until we know if the code will be emitted so that
6235 // dead code can ignore this.
6236 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6237 PDiag(diag::warn_argument_invalid_range)
6238 << toString(Result, 10) << Low << High
6239 << Arg->getSourceRange());
6240 }
6241
6242 return false;
6243}
6244
6245bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6246 unsigned Num) {
6247 llvm::APSInt Result;
6248
6249 // We can't check the value of a dependent argument.
6250 Expr *Arg = TheCall->getArg(ArgNum);
6251 if (Arg->isTypeDependent() || Arg->isValueDependent())
6252 return false;
6253
6254 // Check constant-ness first.
6255 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6256 return true;
6257
6258 if (Result.getSExtValue() % Num != 0)
6259 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6260 << Num << Arg->getSourceRange();
6261
6262 return false;
6263}
6264
6265bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6266 llvm::APSInt Result;
6267
6268 // We can't check the value of a dependent argument.
6269 Expr *Arg = TheCall->getArg(ArgNum);
6270 if (Arg->isTypeDependent() || Arg->isValueDependent())
6271 return false;
6272
6273 // Check constant-ness first.
6274 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6275 return true;
6276
6277 if (Result.isPowerOf2())
6278 return false;
6279
6280 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6281 << Arg->getSourceRange();
6282}
6283
6284static bool IsShiftedByte(llvm::APSInt Value) {
6285 if (Value.isNegative())
6286 return false;
6287
6288 // Check if it's a shifted byte, by shifting it down
6289 while (true) {
6290 // If the value fits in the bottom byte, the check passes.
6291 if (Value < 0x100)
6292 return true;
6293
6294 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6295 // fails.
6296 if ((Value & 0xFF) != 0)
6297 return false;
6298
6299 // If the bottom 8 bits are all 0, but something above that is nonzero,
6300 // then shifting the value right by 8 bits won't affect whether it's a
6301 // shifted byte or not. So do that, and go round again.
6302 Value >>= 8;
6303 }
6304}
6305
6306bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6307 unsigned ArgBits) {
6308 llvm::APSInt Result;
6309
6310 // We can't check the value of a dependent argument.
6311 Expr *Arg = TheCall->getArg(ArgNum);
6312 if (Arg->isTypeDependent() || Arg->isValueDependent())
6313 return false;
6314
6315 // Check constant-ness first.
6316 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6317 return true;
6318
6319 // Truncate to the given size.
6320 Result = Result.getLoBits(ArgBits);
6321 Result.setIsUnsigned(true);
6322
6323 if (IsShiftedByte(Result))
6324 return false;
6325
6326 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6327 << Arg->getSourceRange();
6328}
6329
6331 unsigned ArgNum,
6332 unsigned ArgBits) {
6333 llvm::APSInt Result;
6334
6335 // We can't check the value of a dependent argument.
6336 Expr *Arg = TheCall->getArg(ArgNum);
6337 if (Arg->isTypeDependent() || Arg->isValueDependent())
6338 return false;
6339
6340 // Check constant-ness first.
6341 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6342 return true;
6343
6344 // Truncate to the given size.
6345 Result = Result.getLoBits(ArgBits);
6346 Result.setIsUnsigned(true);
6347
6348 // Check to see if it's in either of the required forms.
6349 if (IsShiftedByte(Result) ||
6350 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6351 return false;
6352
6353 return Diag(TheCall->getBeginLoc(),
6354 diag::err_argument_not_shifted_byte_or_xxff)
6355 << Arg->getSourceRange();
6356}
6357
6358bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6359 if (!Context.getTargetInfo().hasSjLjLowering())
6360 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6361 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6362
6363 Expr *Arg = TheCall->getArg(1);
6364 llvm::APSInt Result;
6365
6366 // TODO: This is less than ideal. Overload this to take a value.
6367 if (BuiltinConstantArg(TheCall, 1, Result))
6368 return true;
6369
6370 if (Result != 1)
6371 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6372 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6373
6374 return false;
6375}
6376
6377bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6378 if (!Context.getTargetInfo().hasSjLjLowering())
6379 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6380 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6381 return false;
6382}
6383
6384bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6385 if (checkArgCount(TheCall, 1))
6386 return true;
6387
6388 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6389 if (ArgRes.isInvalid())
6390 return true;
6391
6392 // For simplicity, we support only limited expressions for the argument.
6393 // Specifically a flexible array member or a pointer with counted_by:
6394 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6395 // complex casting, which really shouldn't be a huge problem.
6396 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6397 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6398 return Diag(Arg->getBeginLoc(),
6399 diag::err_builtin_counted_by_ref_invalid_arg)
6400 << Arg->getSourceRange();
6401
6402 if (Arg->HasSideEffects(Context))
6403 return Diag(Arg->getBeginLoc(),
6404 diag::err_builtin_counted_by_ref_has_side_effects)
6405 << Arg->getSourceRange();
6406
6407 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6408 const auto *CATy =
6409 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6410
6411 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6412 // Member has counted_by attribute - return pointer to count field
6413 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6414 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6415 TheCall->setType(Context.getPointerType(CountFD->getType()));
6416 return false;
6417 }
6418 }
6419
6420 // FAMs and pointers without counted_by return void*
6421 QualType MemberTy = ME->getMemberDecl()->getType();
6422 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6423 return Diag(Arg->getBeginLoc(),
6424 diag::err_builtin_counted_by_ref_invalid_arg)
6425 << Arg->getSourceRange();
6426 } else {
6427 return Diag(Arg->getBeginLoc(),
6428 diag::err_builtin_counted_by_ref_invalid_arg)
6429 << Arg->getSourceRange();
6430 }
6431
6432 TheCall->setType(Context.getPointerType(Context.VoidTy));
6433 return false;
6434}
6435
6436/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6437/// It allows leaking and modification of bounds safety information.
6438bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6440 const CallExpr *CE =
6441 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6442 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6443 return false;
6444
6445 switch (K) {
6448 Diag(E->getExprLoc(),
6449 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6450 << 0 << E->getSourceRange();
6451 break;
6453 Diag(E->getExprLoc(),
6454 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6455 << 1 << E->getSourceRange();
6456 break;
6458 Diag(E->getExprLoc(),
6459 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6460 << 2 << E->getSourceRange();
6461 break;
6463 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6464 << 0 << E->getSourceRange();
6465 break;
6467 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6468 << 1 << E->getSourceRange();
6469 break;
6470 }
6471
6472 return true;
6473}
6474
6475namespace {
6476
6477class UncoveredArgHandler {
6478 enum { Unknown = -1, AllCovered = -2 };
6479
6480 signed FirstUncoveredArg = Unknown;
6481 SmallVector<const Expr *, 4> DiagnosticExprs;
6482
6483public:
6484 UncoveredArgHandler() = default;
6485
6486 bool hasUncoveredArg() const {
6487 return (FirstUncoveredArg >= 0);
6488 }
6489
6490 unsigned getUncoveredArg() const {
6491 assert(hasUncoveredArg() && "no uncovered argument");
6492 return FirstUncoveredArg;
6493 }
6494
6495 void setAllCovered() {
6496 // A string has been found with all arguments covered, so clear out
6497 // the diagnostics.
6498 DiagnosticExprs.clear();
6499 FirstUncoveredArg = AllCovered;
6500 }
6501
6502 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6503 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6504
6505 // Don't update if a previous string covers all arguments.
6506 if (FirstUncoveredArg == AllCovered)
6507 return;
6508
6509 // UncoveredArgHandler tracks the highest uncovered argument index
6510 // and with it all the strings that match this index.
6511 if (NewFirstUncoveredArg == FirstUncoveredArg)
6512 DiagnosticExprs.push_back(StrExpr);
6513 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6514 DiagnosticExprs.clear();
6515 DiagnosticExprs.push_back(StrExpr);
6516 FirstUncoveredArg = NewFirstUncoveredArg;
6517 }
6518 }
6519
6520 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6521};
6522
6523enum StringLiteralCheckType {
6524 SLCT_NotALiteral,
6525 SLCT_UncheckedLiteral,
6526 SLCT_CheckedLiteral
6527};
6528
6529} // namespace
6530
6531static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6532 BinaryOperatorKind BinOpKind,
6533 bool AddendIsRight) {
6534 unsigned BitWidth = Offset.getBitWidth();
6535 unsigned AddendBitWidth = Addend.getBitWidth();
6536 // There might be negative interim results.
6537 if (Addend.isUnsigned()) {
6538 Addend = Addend.zext(++AddendBitWidth);
6539 Addend.setIsSigned(true);
6540 }
6541 // Adjust the bit width of the APSInts.
6542 if (AddendBitWidth > BitWidth) {
6543 Offset = Offset.sext(AddendBitWidth);
6544 BitWidth = AddendBitWidth;
6545 } else if (BitWidth > AddendBitWidth) {
6546 Addend = Addend.sext(BitWidth);
6547 }
6548
6549 bool Ov = false;
6550 llvm::APSInt ResOffset = Offset;
6551 if (BinOpKind == BO_Add)
6552 ResOffset = Offset.sadd_ov(Addend, Ov);
6553 else {
6554 assert(AddendIsRight && BinOpKind == BO_Sub &&
6555 "operator must be add or sub with addend on the right");
6556 ResOffset = Offset.ssub_ov(Addend, Ov);
6557 }
6558
6559 // We add an offset to a pointer here so we should support an offset as big as
6560 // possible.
6561 if (Ov) {
6562 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6563 "index (intermediate) result too big");
6564 Offset = Offset.sext(2 * BitWidth);
6565 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6566 return;
6567 }
6568
6569 Offset = ResOffset;
6570}
6571
6572namespace {
6573
6574// This is a wrapper class around StringLiteral to support offsetted string
6575// literals as format strings. It takes the offset into account when returning
6576// the string and its length or the source locations to display notes correctly.
6577class FormatStringLiteral {
6578 const StringLiteral *FExpr;
6579 int64_t Offset;
6580
6581public:
6582 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6583 : FExpr(fexpr), Offset(Offset) {}
6584
6585 const StringLiteral *getFormatString() const { return FExpr; }
6586
6587 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6588
6589 unsigned getByteLength() const {
6590 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6591 }
6592
6593 unsigned getLength() const { return FExpr->getLength() - Offset; }
6594 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6595
6596 StringLiteralKind getKind() const { return FExpr->getKind(); }
6597
6598 QualType getType() const { return FExpr->getType(); }
6599
6600 bool isAscii() const { return FExpr->isOrdinary(); }
6601 bool isWide() const { return FExpr->isWide(); }
6602 bool isUTF8() const { return FExpr->isUTF8(); }
6603 bool isUTF16() const { return FExpr->isUTF16(); }
6604 bool isUTF32() const { return FExpr->isUTF32(); }
6605 bool isPascal() const { return FExpr->isPascal(); }
6606
6607 SourceLocation getLocationOfByte(
6608 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6609 const TargetInfo &Target, unsigned *StartToken = nullptr,
6610 unsigned *StartTokenByteOffset = nullptr) const {
6611 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6612 StartToken, StartTokenByteOffset);
6613 }
6614
6615 SourceLocation getBeginLoc() const LLVM_READONLY {
6616 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6617 }
6618
6619 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6620};
6621
6622} // namespace
6623
6624static void CheckFormatString(
6625 Sema &S, const FormatStringLiteral *FExpr,
6626 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6628 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6629 bool inFunctionCall, VariadicCallType CallType,
6630 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6631 bool IgnoreStringsWithoutSpecifiers);
6632
6633static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6634 const Expr *E);
6635
6636// Determine if an expression is a string literal or constant string.
6637// If this function returns false on the arguments to a function expecting a
6638// format string, we will usually need to emit a warning.
6639// True string literals are then checked by CheckFormatString.
6640static StringLiteralCheckType
6641checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6642 const Expr *E, ArrayRef<const Expr *> Args,
6643 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6644 unsigned firstDataArg, FormatStringType Type,
6645 VariadicCallType CallType, bool InFunctionCall,
6646 llvm::SmallBitVector &CheckedVarArgs,
6647 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6648 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6649 bool IgnoreStringsWithoutSpecifiers = false) {
6651 return SLCT_NotALiteral;
6652tryAgain:
6653 assert(Offset.isSigned() && "invalid offset");
6654
6655 if (E->isTypeDependent() || E->isValueDependent())
6656 return SLCT_NotALiteral;
6657
6658 E = E->IgnoreParenCasts();
6659
6661 // Technically -Wformat-nonliteral does not warn about this case.
6662 // The behavior of printf and friends in this case is implementation
6663 // dependent. Ideally if the format string cannot be null then
6664 // it should have a 'nonnull' attribute in the function prototype.
6665 return SLCT_UncheckedLiteral;
6666
6667 switch (E->getStmtClass()) {
6668 case Stmt::InitListExprClass:
6669 // Handle expressions like {"foobar"}.
6670 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6671 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6672 format_idx, firstDataArg, Type, CallType,
6673 /*InFunctionCall*/ false, CheckedVarArgs,
6674 UncoveredArg, Offset, CallerFormatParamIdx,
6675 IgnoreStringsWithoutSpecifiers);
6676 }
6677 return SLCT_NotALiteral;
6678 case Stmt::BinaryConditionalOperatorClass:
6679 case Stmt::ConditionalOperatorClass: {
6680 // The expression is a literal if both sub-expressions were, and it was
6681 // completely checked only if both sub-expressions were checked.
6684
6685 // Determine whether it is necessary to check both sub-expressions, for
6686 // example, because the condition expression is a constant that can be
6687 // evaluated at compile time.
6688 bool CheckLeft = true, CheckRight = true;
6689
6690 bool Cond;
6691 if (C->getCond()->EvaluateAsBooleanCondition(
6693 if (Cond)
6694 CheckRight = false;
6695 else
6696 CheckLeft = false;
6697 }
6698
6699 // We need to maintain the offsets for the right and the left hand side
6700 // separately to check if every possible indexed expression is a valid
6701 // string literal. They might have different offsets for different string
6702 // literals in the end.
6703 StringLiteralCheckType Left;
6704 if (!CheckLeft)
6705 Left = SLCT_UncheckedLiteral;
6706 else {
6707 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
6708 Args, APK, format_idx, firstDataArg, Type,
6709 CallType, InFunctionCall, CheckedVarArgs,
6710 UncoveredArg, Offset, CallerFormatParamIdx,
6711 IgnoreStringsWithoutSpecifiers);
6712 if (Left == SLCT_NotALiteral || !CheckRight) {
6713 return Left;
6714 }
6715 }
6716
6717 StringLiteralCheckType Right = checkFormatStringExpr(
6718 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6719 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6720 UncoveredArg, Offset, CallerFormatParamIdx,
6721 IgnoreStringsWithoutSpecifiers);
6722
6723 return (CheckLeft && Left < Right) ? Left : Right;
6724 }
6725
6726 case Stmt::ImplicitCastExprClass:
6727 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6728 goto tryAgain;
6729
6730 case Stmt::OpaqueValueExprClass:
6731 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6732 E = src;
6733 goto tryAgain;
6734 }
6735 return SLCT_NotALiteral;
6736
6737 case Stmt::PredefinedExprClass:
6738 // While __func__, etc., are technically not string literals, they
6739 // cannot contain format specifiers and thus are not a security
6740 // liability.
6741 return SLCT_UncheckedLiteral;
6742
6743 case Stmt::DeclRefExprClass: {
6744 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6745
6746 // As an exception, do not flag errors for variables binding to
6747 // const string literals.
6748 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6749 bool isConstant = false;
6750 QualType T = DR->getType();
6751
6752 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6753 isConstant = AT->getElementType().isConstant(S.Context);
6754 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6755 isConstant = T.isConstant(S.Context) &&
6756 PT->getPointeeType().isConstant(S.Context);
6757 } else if (T->isObjCObjectPointerType()) {
6758 // In ObjC, there is usually no "const ObjectPointer" type,
6759 // so don't check if the pointee type is constant.
6760 isConstant = T.isConstant(S.Context);
6761 }
6762
6763 if (isConstant) {
6764 if (const Expr *Init = VD->getAnyInitializer()) {
6765 // Look through initializers like const char c[] = { "foo" }
6766 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6767 if (InitList->isStringLiteralInit())
6768 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6769 }
6770 return checkFormatStringExpr(
6771 S, ReferenceFormatString, Init, Args, APK, format_idx,
6772 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
6773 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
6774 }
6775 }
6776
6777 // When the format argument is an argument of this function, and this
6778 // function also has the format attribute, there are several interactions
6779 // for which there shouldn't be a warning. For instance, when calling
6780 // v*printf from a function that has the printf format attribute, we
6781 // should not emit a warning about using `fmt`, even though it's not
6782 // constant, because the arguments have already been checked for the
6783 // caller of `logmessage`:
6784 //
6785 // __attribute__((format(printf, 1, 2)))
6786 // void logmessage(char const *fmt, ...) {
6787 // va_list ap;
6788 // va_start(ap, fmt);
6789 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6790 // ...
6791 // }
6792 //
6793 // Another interaction that we need to support is using a format string
6794 // specified by the format_matches attribute:
6795 //
6796 // __attribute__((format_matches(printf, 1, "%s %d")))
6797 // void logmessage(char const *fmt, const char *a, int b) {
6798 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6799 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6800 // ...
6801 // }
6802 //
6803 // Yet another interaction that we need to support is calling a variadic
6804 // format function from a format function that has fixed arguments. For
6805 // instance:
6806 //
6807 // __attribute__((format(printf, 1, 2)))
6808 // void logstring(char const *fmt, char const *str) {
6809 // printf(fmt, str); /* do not emit a warning about "fmt" */
6810 // }
6811 //
6812 // Same (and perhaps more relatably) for the variadic template case:
6813 //
6814 // template<typename... Args>
6815 // __attribute__((format(printf, 1, 2)))
6816 // void log(const char *fmt, Args&&... args) {
6817 // printf(fmt, forward<Args>(args)...);
6818 // /* do not emit a warning about "fmt" */
6819 // }
6820 //
6821 // Due to implementation difficulty, we only check the format, not the
6822 // format arguments, in all cases.
6823 //
6824 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6825 if (CallerFormatParamIdx)
6826 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
6827 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6828 for (const auto *PVFormatMatches :
6829 D->specific_attrs<FormatMatchesAttr>()) {
6830 Sema::FormatStringInfo CalleeFSI;
6831 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6832 0, &CalleeFSI))
6833 continue;
6834 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6835 // If using the wrong type of format string, emit a diagnostic
6836 // here and stop checking to avoid irrelevant diagnostics.
6837 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6838 S.Diag(Args[format_idx]->getBeginLoc(),
6839 diag::warn_format_string_type_incompatible)
6840 << PVFormatMatches->getType()->getName()
6842 if (!InFunctionCall) {
6843 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6844 diag::note_format_string_defined);
6845 }
6846 return SLCT_UncheckedLiteral;
6847 }
6848 return checkFormatStringExpr(
6849 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6850 Args, APK, format_idx, firstDataArg, Type, CallType,
6851 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6852 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6853 }
6854 }
6855
6856 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6857 Sema::FormatStringInfo CallerFSI;
6858 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6859 PVFormat->getFirstArg(), &CallerFSI))
6860 continue;
6861 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6862 // We also check if the formats are compatible.
6863 // We can't pass a 'scanf' string to a 'printf' function.
6864 if (Type != S.GetFormatStringType(PVFormat)) {
6865 S.Diag(Args[format_idx]->getBeginLoc(),
6866 diag::warn_format_string_type_incompatible)
6867 << PVFormat->getType()->getName()
6869 if (!InFunctionCall) {
6870 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6871 }
6872 return SLCT_UncheckedLiteral;
6873 }
6874 // Lastly, check that argument passing kinds transition in a
6875 // way that makes sense:
6876 // from a caller with FAPK_VAList, allow FAPK_VAList
6877 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6878 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6879 // from a caller with FAPK_Variadic, allow FAPK_VAList
6880 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6885 return SLCT_UncheckedLiteral;
6886 }
6887 }
6888 }
6889 }
6890 }
6891 }
6892
6893 return SLCT_NotALiteral;
6894 }
6895
6896 case Stmt::CallExprClass:
6897 case Stmt::CXXMemberCallExprClass: {
6898 const CallExpr *CE = cast<CallExpr>(E);
6899 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6900 bool IsFirst = true;
6901 StringLiteralCheckType CommonResult;
6902 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6903 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6904 StringLiteralCheckType Result = checkFormatStringExpr(
6905 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6906 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6907 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6908 if (IsFirst) {
6909 CommonResult = Result;
6910 IsFirst = false;
6911 }
6912 }
6913 if (!IsFirst)
6914 return CommonResult;
6915
6916 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6917 unsigned BuiltinID = FD->getBuiltinID();
6918 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6919 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6920 const Expr *Arg = CE->getArg(0);
6921 return checkFormatStringExpr(
6922 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6923 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6924 UncoveredArg, Offset, CallerFormatParamIdx,
6925 IgnoreStringsWithoutSpecifiers);
6926 }
6927 }
6928 }
6929 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6930 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6931 format_idx, firstDataArg, Type, CallType,
6932 /*InFunctionCall*/ false, CheckedVarArgs,
6933 UncoveredArg, Offset, CallerFormatParamIdx,
6934 IgnoreStringsWithoutSpecifiers);
6935 return SLCT_NotALiteral;
6936 }
6937 case Stmt::ObjCMessageExprClass: {
6938 const auto *ME = cast<ObjCMessageExpr>(E);
6939 if (const auto *MD = ME->getMethodDecl()) {
6940 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6941 // As a special case heuristic, if we're using the method -[NSBundle
6942 // localizedStringForKey:value:table:], ignore any key strings that lack
6943 // format specifiers. The idea is that if the key doesn't have any
6944 // format specifiers then its probably just a key to map to the
6945 // localized strings. If it does have format specifiers though, then its
6946 // likely that the text of the key is the format string in the
6947 // programmer's language, and should be checked.
6948 const ObjCInterfaceDecl *IFace;
6949 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6950 IFace->getIdentifier()->isStr("NSBundle") &&
6951 MD->getSelector().isKeywordSelector(
6952 {"localizedStringForKey", "value", "table"})) {
6953 IgnoreStringsWithoutSpecifiers = true;
6954 }
6955
6956 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6957 return checkFormatStringExpr(
6958 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6959 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6960 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6961 }
6962 }
6963
6964 return SLCT_NotALiteral;
6965 }
6966 case Stmt::ObjCStringLiteralClass:
6967 case Stmt::StringLiteralClass: {
6968 const StringLiteral *StrE = nullptr;
6969
6970 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6971 StrE = ObjCFExpr->getString();
6972 else
6973 StrE = cast<StringLiteral>(E);
6974
6975 if (StrE) {
6976 if (Offset.isNegative() || Offset > StrE->getLength()) {
6977 // TODO: It would be better to have an explicit warning for out of
6978 // bounds literals.
6979 return SLCT_NotALiteral;
6980 }
6981 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6982 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6983 format_idx, firstDataArg, Type, InFunctionCall,
6984 CallType, CheckedVarArgs, UncoveredArg,
6985 IgnoreStringsWithoutSpecifiers);
6986 return SLCT_CheckedLiteral;
6987 }
6988
6989 return SLCT_NotALiteral;
6990 }
6991 case Stmt::BinaryOperatorClass: {
6992 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6993
6994 // A string literal + an int offset is still a string literal.
6995 if (BinOp->isAdditiveOp()) {
6996 Expr::EvalResult LResult, RResult;
6997
6998 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6999 LResult, S.Context, Expr::SE_NoSideEffects,
7001 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7002 RResult, S.Context, Expr::SE_NoSideEffects,
7004
7005 if (LIsInt != RIsInt) {
7006 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7007
7008 if (LIsInt) {
7009 if (BinOpKind == BO_Add) {
7010 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7011 E = BinOp->getRHS();
7012 goto tryAgain;
7013 }
7014 } else {
7015 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7016 E = BinOp->getLHS();
7017 goto tryAgain;
7018 }
7019 }
7020 }
7021
7022 return SLCT_NotALiteral;
7023 }
7024 case Stmt::UnaryOperatorClass: {
7025 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7026 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7027 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7028 Expr::EvalResult IndexResult;
7029 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7032 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7033 /*RHS is int*/ true);
7034 E = ASE->getBase();
7035 goto tryAgain;
7036 }
7037 }
7038
7039 return SLCT_NotALiteral;
7040 }
7041
7042 default:
7043 return SLCT_NotALiteral;
7044 }
7045}
7046
7047// If this expression can be evaluated at compile-time,
7048// check if the result is a StringLiteral and return it
7049// otherwise return nullptr
7051 const Expr *E) {
7052 Expr::EvalResult Result;
7053 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7054 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7055 if (isa_and_nonnull<StringLiteral>(LVE))
7056 return LVE;
7057 }
7058 return nullptr;
7059}
7060
7062 switch (FST) {
7064 return "scanf";
7066 return "printf";
7068 return "NSString";
7070 return "strftime";
7072 return "strfmon";
7074 return "kprintf";
7076 return "freebsd_kprintf";
7078 return "os_log";
7079 default:
7080 return "<unknown>";
7081 }
7082}
7083
7085 return llvm::StringSwitch<FormatStringType>(Flavor)
7086 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7087 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7089 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7090 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7091 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7092 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7094 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7095 .Case("os_trace", FormatStringType::OSLog)
7096 .Case("os_log", FormatStringType::OSLog)
7097 .Default(FormatStringType::Unknown);
7098}
7099
7101 return GetFormatStringType(Format->getType()->getName());
7102}
7103
7104FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7105 return GetFormatStringType(Format->getType()->getName());
7106}
7107
7108bool Sema::CheckFormatArguments(const FormatAttr *Format,
7109 ArrayRef<const Expr *> Args, bool IsCXXMember,
7110 VariadicCallType CallType, SourceLocation Loc,
7111 SourceRange Range,
7112 llvm::SmallBitVector &CheckedVarArgs) {
7113 FormatStringInfo FSI;
7114 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7115 IsCXXMember,
7116 CallType != VariadicCallType::DoesNotApply, &FSI))
7117 return CheckFormatArguments(
7118 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7119 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7120 return false;
7121}
7122
7123bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7124 ArrayRef<const Expr *> Args, bool IsCXXMember,
7125 VariadicCallType CallType, SourceLocation Loc,
7126 SourceRange Range,
7127 llvm::SmallBitVector &CheckedVarArgs) {
7128 FormatStringInfo FSI;
7129 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7130 &FSI)) {
7131 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7132 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7133 Format->getFormatString(), FSI.FormatIdx,
7134 FSI.FirstDataArg, GetFormatStringType(Format),
7135 CallType, Loc, Range, CheckedVarArgs);
7136 }
7137 return false;
7138}
7139
7142 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7143 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7144 SourceLocation Loc) {
7145 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7146 return false;
7147
7148 DeclContext *DC = S->CurContext;
7149 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7150 return false;
7151 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7152
7153 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7154
7155 // Find the offset to convert between attribute and parameter indexes.
7156 unsigned CallerArgumentIndexOffset =
7157 hasImplicitObjectParameter(Caller) ? 2 : 1;
7158
7159 unsigned FirstArgumentIndex = -1;
7160 switch (APK) {
7163 // As an extension, clang allows the format attribute on non-variadic
7164 // functions.
7165 // Caller must have fixed arguments to pass them to a fixed or variadic
7166 // function. Try to match caller and callee arguments. If successful, then
7167 // emit a diag with the caller idx, otherwise we can't determine the callee
7168 // arguments.
7169 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7170 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7171 // There aren't enough arguments in the caller to pass to callee.
7172 return false;
7173 }
7174 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7175 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7176 const auto *Arg =
7177 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7178 if (!Arg)
7179 return false;
7180 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7181 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7182 return false;
7183 }
7184 FirstArgumentIndex =
7185 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7186 break;
7187 }
7189 // Caller arguments are either variadic or a va_list.
7190 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7191 ? (NumCallerParams + CallerArgumentIndexOffset)
7192 : 0;
7193 break;
7195 // The callee has a format_matches attribute. We will emit that instead.
7196 if (!ReferenceFormatString)
7197 return false;
7198 break;
7199 }
7200
7201 // Emit the diagnostic and fixit.
7202 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7203 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7204 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7205 do {
7206 std::string Attr, Fixit;
7207 llvm::raw_string_ostream AttrOS(Attr);
7209 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7210 << FirstArgumentIndex << ")";
7211 } else {
7212 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7213 << ", \"";
7214 AttrOS.write_escaped(ReferenceFormatString->getString());
7215 AttrOS << "\")";
7216 }
7217 AttrOS.flush();
7218 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7219 if (ND)
7220 DB << ND;
7221 else
7222 DB << "block";
7223
7224 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7225 if (isa<BlockDecl>(Caller))
7226 break;
7227
7228 SourceLocation SL;
7229 llvm::raw_string_ostream IS(Fixit);
7230 // The attribute goes at the start of the declaration in C/C++ functions
7231 // and methods, but after the declaration for Objective-C methods.
7232 if (isa<ObjCMethodDecl>(Caller)) {
7233 IS << ' ';
7234 SL = Caller->getEndLoc();
7235 }
7236 const LangOptions &LO = S->getLangOpts();
7237 if (LO.C23 || LO.CPlusPlus11)
7238 IS << "[[gnu::" << Attr << "]]";
7239 else if (LO.ObjC || LO.GNUMode)
7240 IS << "__attribute__((" << Attr << "))";
7241 else
7242 break;
7243 if (!isa<ObjCMethodDecl>(Caller)) {
7244 IS << ' ';
7245 SL = Caller->getBeginLoc();
7246 }
7247 IS.flush();
7248
7249 DB << FixItHint::CreateInsertion(SL, Fixit);
7250 } while (false);
7251
7252 // Add implicit format or format_matches attribute.
7254 Caller->addAttr(FormatAttr::CreateImplicit(
7255 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7256 FormatStringIndex, FirstArgumentIndex));
7257 } else {
7258 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7259 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7260 FormatStringIndex, ReferenceFormatString));
7261 }
7262
7263 {
7264 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7265 if (ND)
7266 DB << ND;
7267 else
7268 DB << "block";
7269 }
7270 return true;
7271}
7272
7273bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7275 StringLiteral *ReferenceFormatString,
7276 unsigned format_idx, unsigned firstDataArg,
7278 VariadicCallType CallType, SourceLocation Loc,
7279 SourceRange Range,
7280 llvm::SmallBitVector &CheckedVarArgs) {
7281 // CHECK: printf/scanf-like function is called with no format string.
7282 if (format_idx >= Args.size()) {
7283 Diag(Loc, diag::warn_missing_format_string) << Range;
7284 return false;
7285 }
7286
7287 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7288
7289 // CHECK: format string is not a string literal.
7290 //
7291 // Dynamically generated format strings are difficult to
7292 // automatically vet at compile time. Requiring that format strings
7293 // are string literals: (1) permits the checking of format strings by
7294 // the compiler and thereby (2) can practically remove the source of
7295 // many format string exploits.
7296
7297 // Format string can be either ObjC string (e.g. @"%d") or
7298 // C string (e.g. "%d")
7299 // ObjC string uses the same format specifiers as C string, so we can use
7300 // the same format string checking logic for both ObjC and C strings.
7301 UncoveredArgHandler UncoveredArg;
7302 std::optional<unsigned> CallerParamIdx;
7303 StringLiteralCheckType CT = checkFormatStringExpr(
7304 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7305 firstDataArg, Type, CallType,
7306 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7307 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7308
7309 // Generate a diagnostic where an uncovered argument is detected.
7310 if (UncoveredArg.hasUncoveredArg()) {
7311 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7312 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7313 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7314 }
7315
7316 if (CT != SLCT_NotALiteral)
7317 // Literal format string found, check done!
7318 return CT == SLCT_CheckedLiteral;
7319
7320 // Do not emit diag when the string param is a macro expansion and the
7321 // format is either NSString or CFString. This is a hack to prevent
7322 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7323 // which are usually used in place of NS and CF string literals.
7324 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7326 SourceMgr.isInSystemMacro(FormatLoc))
7327 return false;
7328
7329 if (CallerParamIdx && CheckMissingFormatAttribute(
7330 this, Args, APK, ReferenceFormatString, format_idx,
7331 firstDataArg, Type, *CallerParamIdx, Loc))
7332 return false;
7333
7334 // Strftime is particular as it always uses a single 'time' argument,
7335 // so it is safe to pass a non-literal string.
7337 return false;
7338
7339 // If there are no arguments specified, warn with -Wformat-security, otherwise
7340 // warn only with -Wformat-nonliteral.
7341 if (Args.size() == firstDataArg) {
7342 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7343 << OrigFormatExpr->getSourceRange();
7344 switch (Type) {
7345 default:
7346 break;
7350 Diag(FormatLoc, diag::note_format_security_fixit)
7351 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7352 break;
7354 Diag(FormatLoc, diag::note_format_security_fixit)
7355 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7356 break;
7357 }
7358 } else {
7359 Diag(FormatLoc, diag::warn_format_nonliteral)
7360 << OrigFormatExpr->getSourceRange();
7361 }
7362 return false;
7363}
7364
7365namespace {
7366
7367class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7368protected:
7369 Sema &S;
7370 const FormatStringLiteral *FExpr;
7371 const Expr *OrigFormatExpr;
7372 const FormatStringType FSType;
7373 const unsigned FirstDataArg;
7374 const unsigned NumDataArgs;
7375 const char *Beg; // Start of format string.
7376 const Sema::FormatArgumentPassingKind ArgPassingKind;
7377 ArrayRef<const Expr *> Args;
7378 unsigned FormatIdx;
7379 llvm::SmallBitVector CoveredArgs;
7380 bool usesPositionalArgs = false;
7381 bool atFirstArg = true;
7382 bool inFunctionCall;
7383 VariadicCallType CallType;
7384 llvm::SmallBitVector &CheckedVarArgs;
7385 UncoveredArgHandler &UncoveredArg;
7386
7387public:
7388 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7389 const Expr *origFormatExpr, const FormatStringType type,
7390 unsigned firstDataArg, unsigned numDataArgs,
7391 const char *beg, Sema::FormatArgumentPassingKind APK,
7392 ArrayRef<const Expr *> Args, unsigned formatIdx,
7393 bool inFunctionCall, VariadicCallType callType,
7394 llvm::SmallBitVector &CheckedVarArgs,
7395 UncoveredArgHandler &UncoveredArg)
7396 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7397 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7398 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7399 inFunctionCall(inFunctionCall), CallType(callType),
7400 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7401 CoveredArgs.resize(numDataArgs);
7402 CoveredArgs.reset();
7403 }
7404
7405 bool HasFormatArguments() const {
7406 return ArgPassingKind == Sema::FAPK_Fixed ||
7407 ArgPassingKind == Sema::FAPK_Variadic;
7408 }
7409
7410 void DoneProcessing();
7411
7412 void HandleIncompleteSpecifier(const char *startSpecifier,
7413 unsigned specifierLen) override;
7414
7415 void HandleInvalidLengthModifier(
7416 const analyze_format_string::FormatSpecifier &FS,
7417 const analyze_format_string::ConversionSpecifier &CS,
7418 const char *startSpecifier, unsigned specifierLen,
7419 unsigned DiagID);
7420
7421 void HandleNonStandardLengthModifier(
7422 const analyze_format_string::FormatSpecifier &FS,
7423 const char *startSpecifier, unsigned specifierLen);
7424
7425 void HandleNonStandardConversionSpecifier(
7426 const analyze_format_string::ConversionSpecifier &CS,
7427 const char *startSpecifier, unsigned specifierLen);
7428
7429 void HandlePosition(const char *startPos, unsigned posLen) override;
7430
7431 void HandleInvalidPosition(const char *startSpecifier,
7432 unsigned specifierLen,
7434
7435 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7436
7437 void HandleNullChar(const char *nullCharacter) override;
7438
7439 template <typename Range>
7440 static void
7441 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7442 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7443 bool IsStringLocation, Range StringRange,
7444 ArrayRef<FixItHint> Fixit = {});
7445
7446protected:
7447 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7448 const char *startSpec,
7449 unsigned specifierLen,
7450 const char *csStart, unsigned csLen);
7451
7452 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7453 const char *startSpec,
7454 unsigned specifierLen);
7455
7456 SourceRange getFormatStringRange();
7457 CharSourceRange getSpecifierRange(const char *startSpecifier,
7458 unsigned specifierLen);
7459 SourceLocation getLocationOfByte(const char *x);
7460
7461 const Expr *getDataArg(unsigned i) const;
7462
7463 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7464 const analyze_format_string::ConversionSpecifier &CS,
7465 const char *startSpecifier, unsigned specifierLen,
7466 unsigned argIndex);
7467
7468 template <typename Range>
7469 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7470 bool IsStringLocation, Range StringRange,
7471 ArrayRef<FixItHint> Fixit = {});
7472};
7473
7474} // namespace
7475
7476SourceRange CheckFormatHandler::getFormatStringRange() {
7477 return OrigFormatExpr->getSourceRange();
7478}
7479
7480CharSourceRange CheckFormatHandler::
7481getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7482 SourceLocation Start = getLocationOfByte(startSpecifier);
7483 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7484
7485 // Advance the end SourceLocation by one due to half-open ranges.
7486 End = End.getLocWithOffset(1);
7487
7488 return CharSourceRange::getCharRange(Start, End);
7489}
7490
7491SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7492 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7494}
7495
7496void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7497 unsigned specifierLen){
7498 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7499 getLocationOfByte(startSpecifier),
7500 /*IsStringLocation*/true,
7501 getSpecifierRange(startSpecifier, specifierLen));
7502}
7503
7504void CheckFormatHandler::HandleInvalidLengthModifier(
7507 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7508 using namespace analyze_format_string;
7509
7510 const LengthModifier &LM = FS.getLengthModifier();
7511 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7512
7513 // See if we know how to fix this length modifier.
7514 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7515 if (FixedLM) {
7516 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7517 getLocationOfByte(LM.getStart()),
7518 /*IsStringLocation*/true,
7519 getSpecifierRange(startSpecifier, specifierLen));
7520
7521 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7522 << FixedLM->toString()
7523 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7524
7525 } else {
7526 FixItHint Hint;
7527 if (DiagID == diag::warn_format_nonsensical_length)
7528 Hint = FixItHint::CreateRemoval(LMRange);
7529
7530 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7531 getLocationOfByte(LM.getStart()),
7532 /*IsStringLocation*/true,
7533 getSpecifierRange(startSpecifier, specifierLen),
7534 Hint);
7535 }
7536}
7537
7538void CheckFormatHandler::HandleNonStandardLengthModifier(
7540 const char *startSpecifier, unsigned specifierLen) {
7541 using namespace analyze_format_string;
7542
7543 const LengthModifier &LM = FS.getLengthModifier();
7544 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7545
7546 // See if we know how to fix this length modifier.
7547 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7548 if (FixedLM) {
7549 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7550 << LM.toString() << 0,
7551 getLocationOfByte(LM.getStart()),
7552 /*IsStringLocation*/true,
7553 getSpecifierRange(startSpecifier, specifierLen));
7554
7555 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7556 << FixedLM->toString()
7557 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7558
7559 } else {
7560 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7561 << LM.toString() << 0,
7562 getLocationOfByte(LM.getStart()),
7563 /*IsStringLocation*/true,
7564 getSpecifierRange(startSpecifier, specifierLen));
7565 }
7566}
7567
7568void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7570 const char *startSpecifier, unsigned specifierLen) {
7571 using namespace analyze_format_string;
7572
7573 // See if we know how to fix this conversion specifier.
7574 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7575 if (FixedCS) {
7576 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7577 << CS.toString() << /*conversion specifier*/1,
7578 getLocationOfByte(CS.getStart()),
7579 /*IsStringLocation*/true,
7580 getSpecifierRange(startSpecifier, specifierLen));
7581
7582 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7583 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7584 << FixedCS->toString()
7585 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7586 } else {
7587 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7588 << CS.toString() << /*conversion specifier*/1,
7589 getLocationOfByte(CS.getStart()),
7590 /*IsStringLocation*/true,
7591 getSpecifierRange(startSpecifier, specifierLen));
7592 }
7593}
7594
7595void CheckFormatHandler::HandlePosition(const char *startPos,
7596 unsigned posLen) {
7597 if (!S.getDiagnostics().isIgnored(
7598 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7599 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7600 getLocationOfByte(startPos),
7601 /*IsStringLocation*/ true,
7602 getSpecifierRange(startPos, posLen));
7603}
7604
7605void CheckFormatHandler::HandleInvalidPosition(
7606 const char *startSpecifier, unsigned specifierLen,
7608 if (!S.getDiagnostics().isIgnored(
7609 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7610 EmitFormatDiagnostic(
7611 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7612 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7613 getSpecifierRange(startSpecifier, specifierLen));
7614}
7615
7616void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7617 unsigned posLen) {
7618 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7619 SourceLocation()))
7620 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7621 getLocationOfByte(startPos),
7622 /*IsStringLocation*/ true,
7623 getSpecifierRange(startPos, posLen));
7624}
7625
7626void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7627 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7628 // The presence of a null character is likely an error.
7629 EmitFormatDiagnostic(
7630 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7631 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7632 getFormatStringRange());
7633 }
7634}
7635
7636// Note that this may return NULL if there was an error parsing or building
7637// one of the argument expressions.
7638const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7639 return Args[FirstDataArg + i];
7640}
7641
7642void CheckFormatHandler::DoneProcessing() {
7643 // Does the number of data arguments exceed the number of
7644 // format conversions in the format string?
7645 if (HasFormatArguments()) {
7646 // Find any arguments that weren't covered.
7647 CoveredArgs.flip();
7648 signed notCoveredArg = CoveredArgs.find_first();
7649 if (notCoveredArg >= 0) {
7650 assert((unsigned)notCoveredArg < NumDataArgs);
7651 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7652 } else {
7653 UncoveredArg.setAllCovered();
7654 }
7655 }
7656}
7657
7658void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7659 const Expr *ArgExpr) {
7660 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7661 "Invalid state");
7662
7663 if (!ArgExpr)
7664 return;
7665
7666 SourceLocation Loc = ArgExpr->getBeginLoc();
7667
7668 if (S.getSourceManager().isInSystemMacro(Loc))
7669 return;
7670
7671 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7672 for (auto E : DiagnosticExprs)
7673 PDiag << E->getSourceRange();
7674
7675 CheckFormatHandler::EmitFormatDiagnostic(
7676 S, IsFunctionCall, DiagnosticExprs[0],
7677 PDiag, Loc, /*IsStringLocation*/false,
7678 DiagnosticExprs[0]->getSourceRange());
7679}
7680
7681bool
7682CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7683 SourceLocation Loc,
7684 const char *startSpec,
7685 unsigned specifierLen,
7686 const char *csStart,
7687 unsigned csLen) {
7688 bool keepGoing = true;
7689 if (argIndex < NumDataArgs) {
7690 // Consider the argument coverered, even though the specifier doesn't
7691 // make sense.
7692 CoveredArgs.set(argIndex);
7693 }
7694 else {
7695 // If argIndex exceeds the number of data arguments we
7696 // don't issue a warning because that is just a cascade of warnings (and
7697 // they may have intended '%%' anyway). We don't want to continue processing
7698 // the format string after this point, however, as we will like just get
7699 // gibberish when trying to match arguments.
7700 keepGoing = false;
7701 }
7702
7703 StringRef Specifier(csStart, csLen);
7704
7705 // If the specifier in non-printable, it could be the first byte of a UTF-8
7706 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7707 // hex value.
7708 std::string CodePointStr;
7709 if (!llvm::sys::locale::isPrint(*csStart)) {
7710 llvm::UTF32 CodePoint;
7711 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7712 const llvm::UTF8 *E =
7713 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7714 llvm::ConversionResult Result =
7715 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7716
7717 if (Result != llvm::conversionOK) {
7718 unsigned char FirstChar = *csStart;
7719 CodePoint = (llvm::UTF32)FirstChar;
7720 }
7721
7722 llvm::raw_string_ostream OS(CodePointStr);
7723 if (CodePoint < 256)
7724 OS << "\\x" << llvm::format("%02x", CodePoint);
7725 else if (CodePoint <= 0xFFFF)
7726 OS << "\\u" << llvm::format("%04x", CodePoint);
7727 else
7728 OS << "\\U" << llvm::format("%08x", CodePoint);
7729 Specifier = CodePointStr;
7730 }
7731
7732 EmitFormatDiagnostic(
7733 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7734 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7735
7736 return keepGoing;
7737}
7738
7739void
7740CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7741 const char *startSpec,
7742 unsigned specifierLen) {
7743 EmitFormatDiagnostic(
7744 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7745 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7746}
7747
7748bool
7749CheckFormatHandler::CheckNumArgs(
7752 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7753
7754 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7756 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7757 << (argIndex+1) << NumDataArgs)
7758 : S.PDiag(diag::warn_printf_insufficient_data_args);
7759 EmitFormatDiagnostic(
7760 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7761 getSpecifierRange(startSpecifier, specifierLen));
7762
7763 // Since more arguments than conversion tokens are given, by extension
7764 // all arguments are covered, so mark this as so.
7765 UncoveredArg.setAllCovered();
7766 return false;
7767 }
7768 return true;
7769}
7770
7771template<typename Range>
7772void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7773 SourceLocation Loc,
7774 bool IsStringLocation,
7775 Range StringRange,
7776 ArrayRef<FixItHint> FixIt) {
7777 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7778 Loc, IsStringLocation, StringRange, FixIt);
7779}
7780
7781/// If the format string is not within the function call, emit a note
7782/// so that the function call and string are in diagnostic messages.
7783///
7784/// \param InFunctionCall if true, the format string is within the function
7785/// call and only one diagnostic message will be produced. Otherwise, an
7786/// extra note will be emitted pointing to location of the format string.
7787///
7788/// \param ArgumentExpr the expression that is passed as the format string
7789/// argument in the function call. Used for getting locations when two
7790/// diagnostics are emitted.
7791///
7792/// \param PDiag the callee should already have provided any strings for the
7793/// diagnostic message. This function only adds locations and fixits
7794/// to diagnostics.
7795///
7796/// \param Loc primary location for diagnostic. If two diagnostics are
7797/// required, one will be at Loc and a new SourceLocation will be created for
7798/// the other one.
7799///
7800/// \param IsStringLocation if true, Loc points to the format string should be
7801/// used for the note. Otherwise, Loc points to the argument list and will
7802/// be used with PDiag.
7803///
7804/// \param StringRange some or all of the string to highlight. This is
7805/// templated so it can accept either a CharSourceRange or a SourceRange.
7806///
7807/// \param FixIt optional fix it hint for the format string.
7808template <typename Range>
7809void CheckFormatHandler::EmitFormatDiagnostic(
7810 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7811 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7812 Range StringRange, ArrayRef<FixItHint> FixIt) {
7813 if (InFunctionCall) {
7814 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7815 D << StringRange;
7816 D << FixIt;
7817 } else {
7818 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7819 << ArgumentExpr->getSourceRange();
7820
7822 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7823 diag::note_format_string_defined);
7824
7825 Note << StringRange;
7826 Note << FixIt;
7827 }
7828}
7829
7830//===--- CHECK: Printf format string checking -----------------------------===//
7831
7832namespace {
7833
7834class CheckPrintfHandler : public CheckFormatHandler {
7835public:
7836 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7837 const Expr *origFormatExpr, const FormatStringType type,
7838 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7839 const char *beg, Sema::FormatArgumentPassingKind APK,
7840 ArrayRef<const Expr *> Args, unsigned formatIdx,
7841 bool inFunctionCall, VariadicCallType CallType,
7842 llvm::SmallBitVector &CheckedVarArgs,
7843 UncoveredArgHandler &UncoveredArg)
7844 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7845 numDataArgs, beg, APK, Args, formatIdx,
7846 inFunctionCall, CallType, CheckedVarArgs,
7847 UncoveredArg) {}
7848
7849 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7850
7851 /// Returns true if '%@' specifiers are allowed in the format string.
7852 bool allowsObjCArg() const {
7853 return FSType == FormatStringType::NSString ||
7854 FSType == FormatStringType::OSLog ||
7855 FSType == FormatStringType::OSTrace;
7856 }
7857
7858 bool HandleInvalidPrintfConversionSpecifier(
7859 const analyze_printf::PrintfSpecifier &FS,
7860 const char *startSpecifier,
7861 unsigned specifierLen) override;
7862
7863 void handleInvalidMaskType(StringRef MaskType) override;
7864
7865 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7866 const char *startSpecifier, unsigned specifierLen,
7867 const TargetInfo &Target) override;
7868 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7869 const char *StartSpecifier,
7870 unsigned SpecifierLen,
7871 const Expr *E);
7872
7873 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7874 const char *startSpecifier, unsigned specifierLen);
7875 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7876 const analyze_printf::OptionalAmount &Amt,
7877 unsigned type,
7878 const char *startSpecifier, unsigned specifierLen);
7879 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7880 const analyze_printf::OptionalFlag &flag,
7881 const char *startSpecifier, unsigned specifierLen);
7882 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7883 const analyze_printf::OptionalFlag &ignoredFlag,
7884 const analyze_printf::OptionalFlag &flag,
7885 const char *startSpecifier, unsigned specifierLen);
7886 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7887 const Expr *E);
7888
7889 void HandleEmptyObjCModifierFlag(const char *startFlag,
7890 unsigned flagLen) override;
7891
7892 void HandleInvalidObjCModifierFlag(const char *startFlag,
7893 unsigned flagLen) override;
7894
7895 void
7896 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7897 const char *flagsEnd,
7898 const char *conversionPosition) override;
7899};
7900
7901/// Keeps around the information needed to verify that two specifiers are
7902/// compatible.
7903class EquatableFormatArgument {
7904public:
7905 enum SpecifierSensitivity : unsigned {
7906 SS_None,
7907 SS_Private,
7908 SS_Public,
7909 SS_Sensitive
7910 };
7911
7912 enum FormatArgumentRole : unsigned {
7913 FAR_Data,
7914 FAR_FieldWidth,
7915 FAR_Precision,
7916 FAR_Auxiliary, // FreeBSD kernel %b and %D
7917 };
7918
7919private:
7920 analyze_format_string::ArgType ArgType;
7922 StringRef SpecifierLetter;
7923 CharSourceRange Range;
7924 SourceLocation ElementLoc;
7925 FormatArgumentRole Role : 2;
7926 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7927 unsigned Position : 14;
7928 unsigned ModifierFor : 14; // not set for FAR_Data
7929
7930 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7931 bool InFunctionCall) const;
7932
7933public:
7934 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7936 StringRef SpecifierLetter,
7937 analyze_format_string::ArgType ArgType,
7938 FormatArgumentRole Role,
7939 SpecifierSensitivity Sensitivity, unsigned Position,
7940 unsigned ModifierFor)
7941 : ArgType(ArgType), LengthMod(LengthMod),
7942 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7943 Role(Role), Sensitivity(Sensitivity), Position(Position),
7944 ModifierFor(ModifierFor) {}
7945
7946 unsigned getPosition() const { return Position; }
7947 SourceLocation getSourceLocation() const { return ElementLoc; }
7948 CharSourceRange getSourceRange() const { return Range; }
7949 analyze_format_string::LengthModifier getLengthModifier() const {
7950 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7951 }
7952 void setModifierFor(unsigned V) { ModifierFor = V; }
7953
7954 std::string buildFormatSpecifier() const {
7955 std::string result;
7956 llvm::raw_string_ostream(result)
7957 << getLengthModifier().toString() << SpecifierLetter;
7958 return result;
7959 }
7960
7961 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7962 const Expr *FmtExpr, bool InFunctionCall) const;
7963};
7964
7965/// Turns format strings into lists of EquatableSpecifier objects.
7966class DecomposePrintfHandler : public CheckPrintfHandler {
7967 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7968 bool HadError;
7969
7970 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7971 const Expr *origFormatExpr,
7972 const FormatStringType type, unsigned firstDataArg,
7973 unsigned numDataArgs, bool isObjC, const char *beg,
7975 ArrayRef<const Expr *> Args, unsigned formatIdx,
7976 bool inFunctionCall, VariadicCallType CallType,
7977 llvm::SmallBitVector &CheckedVarArgs,
7978 UncoveredArgHandler &UncoveredArg,
7979 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7980 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7981 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7982 inFunctionCall, CallType, CheckedVarArgs,
7983 UncoveredArg),
7984 Specs(Specs), HadError(false) {}
7985
7986public:
7987 static bool
7988 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7989 FormatStringType type, bool IsObjC, bool InFunctionCall,
7990 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7991
7992 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7993 const char *startSpecifier,
7994 unsigned specifierLen,
7995 const TargetInfo &Target) override;
7996};
7997
7998} // namespace
7999
8000bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8001 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8002 unsigned specifierLen) {
8005
8006 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8007 getLocationOfByte(CS.getStart()),
8008 startSpecifier, specifierLen,
8009 CS.getStart(), CS.getLength());
8010}
8011
8012void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8013 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8014}
8015
8016// Error out if struct or complex type argments are passed to os_log.
8018 QualType T) {
8019 if (FSType != FormatStringType::OSLog)
8020 return false;
8021 return T->isRecordType() || T->isComplexType();
8022}
8023
8024bool CheckPrintfHandler::HandleAmount(
8025 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8026 const char *startSpecifier, unsigned specifierLen) {
8027 if (Amt.hasDataArgument()) {
8028 if (HasFormatArguments()) {
8029 unsigned argIndex = Amt.getArgIndex();
8030 if (argIndex >= NumDataArgs) {
8031 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8032 << k,
8033 getLocationOfByte(Amt.getStart()),
8034 /*IsStringLocation*/ true,
8035 getSpecifierRange(startSpecifier, specifierLen));
8036 // Don't do any more checking. We will just emit
8037 // spurious errors.
8038 return false;
8039 }
8040
8041 // Type check the data argument. It should be an 'int'.
8042 // Although not in conformance with C99, we also allow the argument to be
8043 // an 'unsigned int' as that is a reasonably safe case. GCC also
8044 // doesn't emit a warning for that case.
8045 CoveredArgs.set(argIndex);
8046 const Expr *Arg = getDataArg(argIndex);
8047 if (!Arg)
8048 return false;
8049
8050 QualType T = Arg->getType();
8051
8052 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8053 assert(AT.isValid());
8054
8055 if (!AT.matchesType(S.Context, T)) {
8056 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8057 ? diag::err_printf_asterisk_wrong_type
8058 : diag::warn_printf_asterisk_wrong_type;
8059 EmitFormatDiagnostic(S.PDiag(DiagID)
8061 << T << Arg->getSourceRange(),
8062 getLocationOfByte(Amt.getStart()),
8063 /*IsStringLocation*/ true,
8064 getSpecifierRange(startSpecifier, specifierLen));
8065 // Don't do any more checking. We will just emit
8066 // spurious errors.
8067 return false;
8068 }
8069 }
8070 }
8071 return true;
8072}
8073
8074void CheckPrintfHandler::HandleInvalidAmount(
8077 unsigned type,
8078 const char *startSpecifier,
8079 unsigned specifierLen) {
8082
8083 FixItHint fixit =
8085 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8086 Amt.getConstantLength()))
8087 : FixItHint();
8088
8089 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8090 << type << CS.toString(),
8091 getLocationOfByte(Amt.getStart()),
8092 /*IsStringLocation*/true,
8093 getSpecifierRange(startSpecifier, specifierLen),
8094 fixit);
8095}
8096
8097void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8098 const analyze_printf::OptionalFlag &flag,
8099 const char *startSpecifier,
8100 unsigned specifierLen) {
8101 // Warn about pointless flag with a fixit removal.
8104 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8105 << flag.toString() << CS.toString(),
8106 getLocationOfByte(flag.getPosition()),
8107 /*IsStringLocation*/true,
8108 getSpecifierRange(startSpecifier, specifierLen),
8110 getSpecifierRange(flag.getPosition(), 1)));
8111}
8112
8113void CheckPrintfHandler::HandleIgnoredFlag(
8115 const analyze_printf::OptionalFlag &ignoredFlag,
8116 const analyze_printf::OptionalFlag &flag,
8117 const char *startSpecifier,
8118 unsigned specifierLen) {
8119 // Warn about ignored flag with a fixit removal.
8120 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8121 << ignoredFlag.toString() << flag.toString(),
8122 getLocationOfByte(ignoredFlag.getPosition()),
8123 /*IsStringLocation*/true,
8124 getSpecifierRange(startSpecifier, specifierLen),
8126 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8127}
8128
8129void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8130 unsigned flagLen) {
8131 // Warn about an empty flag.
8132 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8133 getLocationOfByte(startFlag),
8134 /*IsStringLocation*/true,
8135 getSpecifierRange(startFlag, flagLen));
8136}
8137
8138void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8139 unsigned flagLen) {
8140 // Warn about an invalid flag.
8141 auto Range = getSpecifierRange(startFlag, flagLen);
8142 StringRef flag(startFlag, flagLen);
8143 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8144 getLocationOfByte(startFlag),
8145 /*IsStringLocation*/true,
8146 Range, FixItHint::CreateRemoval(Range));
8147}
8148
8149void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8150 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8151 // Warn about using '[...]' without a '@' conversion.
8152 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8153 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8154 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8155 getLocationOfByte(conversionPosition),
8156 /*IsStringLocation*/ true, Range,
8158}
8159
8160void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8161 const Expr *FmtExpr,
8162 bool InFunctionCall) const {
8163 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8164 ElementLoc, true, Range);
8165}
8166
8167bool EquatableFormatArgument::VerifyCompatible(
8168 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8169 bool InFunctionCall) const {
8171 if (Role != Other.Role) {
8172 // diagnose and stop
8173 EmitDiagnostic(
8174 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8175 FmtExpr, InFunctionCall);
8176 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8177 return false;
8178 }
8179
8180 if (Role != FAR_Data) {
8181 if (ModifierFor != Other.ModifierFor) {
8182 // diagnose and stop
8183 EmitDiagnostic(S,
8184 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8185 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8186 FmtExpr, InFunctionCall);
8187 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8188 return false;
8189 }
8190 return true;
8191 }
8192
8193 bool HadError = false;
8194 if (Sensitivity != Other.Sensitivity) {
8195 // diagnose and continue
8196 EmitDiagnostic(S,
8197 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8198 << Sensitivity << Other.Sensitivity,
8199 FmtExpr, InFunctionCall);
8200 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8201 << 0 << Other.Range;
8202 }
8203
8204 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8205 case MK::Match:
8206 break;
8207
8208 case MK::MatchPromotion:
8209 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8210 // MatchPromotion is treated as a failure by format_matches.
8211 case MK::NoMatch:
8212 case MK::NoMatchTypeConfusion:
8213 case MK::NoMatchPromotionTypeConfusion:
8214 EmitDiagnostic(S,
8215 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8216 << buildFormatSpecifier()
8217 << Other.buildFormatSpecifier(),
8218 FmtExpr, InFunctionCall);
8219 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8220 << 0 << Other.Range;
8221 break;
8222
8223 case MK::NoMatchPedantic:
8224 EmitDiagnostic(S,
8225 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8226 << buildFormatSpecifier()
8227 << Other.buildFormatSpecifier(),
8228 FmtExpr, InFunctionCall);
8229 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8230 << 0 << Other.Range;
8231 break;
8232
8233 case MK::NoMatchSignedness:
8234 EmitDiagnostic(S,
8235 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8236 << buildFormatSpecifier()
8237 << Other.buildFormatSpecifier(),
8238 FmtExpr, InFunctionCall);
8239 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8240 << 0 << Other.Range;
8241 break;
8242 }
8243 return !HadError;
8244}
8245
8246bool DecomposePrintfHandler::GetSpecifiers(
8247 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8248 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8250 StringRef Data = FSL->getString();
8251 const char *Str = Data.data();
8252 llvm::SmallBitVector BV;
8253 UncoveredArgHandler UA;
8254 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8255 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8256 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8257 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8258 UA, Args);
8259
8261 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8263 H.DoneProcessing();
8264 if (H.HadError)
8265 return false;
8266
8267 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8268 const EquatableFormatArgument &B) {
8269 return A.getPosition() < B.getPosition();
8270 });
8271 return true;
8272}
8273
8274bool DecomposePrintfHandler::HandlePrintfSpecifier(
8275 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8276 unsigned specifierLen, const TargetInfo &Target) {
8277 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8278 specifierLen, Target)) {
8279 HadError = true;
8280 return false;
8281 }
8282
8283 // Do not add any specifiers to the list for %%. This is possibly incorrect
8284 // if using a precision/width with a data argument, but that combination is
8285 // meaningless and we wouldn't know which format to attach the
8286 // precision/width to.
8287 const auto &CS = FS.getConversionSpecifier();
8289 return true;
8290
8291 // have to patch these to have the right ModifierFor if they are used
8292 const unsigned Unset = ~0;
8293 unsigned FieldWidthIndex = Unset;
8294 unsigned PrecisionIndex = Unset;
8295
8296 // field width?
8297 const auto &FieldWidth = FS.getFieldWidth();
8298 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8299 FieldWidthIndex = Specs.size();
8300 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8301 getLocationOfByte(FieldWidth.getStart()),
8303 FieldWidth.getArgType(S.Context),
8304 EquatableFormatArgument::FAR_FieldWidth,
8305 EquatableFormatArgument::SS_None,
8306 FieldWidth.usesPositionalArg()
8307 ? FieldWidth.getPositionalArgIndex() - 1
8308 : FieldWidthIndex,
8309 0);
8310 }
8311 // precision?
8312 const auto &Precision = FS.getPrecision();
8313 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8314 PrecisionIndex = Specs.size();
8315 Specs.emplace_back(
8316 getSpecifierRange(startSpecifier, specifierLen),
8317 getLocationOfByte(Precision.getStart()),
8319 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8320 EquatableFormatArgument::SS_None,
8321 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8322 : PrecisionIndex,
8323 0);
8324 }
8325
8326 // this specifier
8327 unsigned SpecIndex =
8328 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8329 if (FieldWidthIndex != Unset)
8330 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8331 if (PrecisionIndex != Unset)
8332 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8333
8334 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8335 if (FS.isPrivate())
8336 Sensitivity = EquatableFormatArgument::SS_Private;
8337 else if (FS.isPublic())
8338 Sensitivity = EquatableFormatArgument::SS_Public;
8339 else if (FS.isSensitive())
8340 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8341 else
8342 Sensitivity = EquatableFormatArgument::SS_None;
8343
8344 Specs.emplace_back(
8345 getSpecifierRange(startSpecifier, specifierLen),
8346 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8347 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8348 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8349
8350 // auxiliary argument?
8353 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8354 getLocationOfByte(CS.getStart()),
8356 CS.getCharacters(),
8358 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8359 SpecIndex + 1, SpecIndex);
8360 }
8361 return true;
8362}
8363
8364// Determines if the specified is a C++ class or struct containing
8365// a member with the specified name and kind (e.g. a CXXMethodDecl named
8366// "c_str()").
8367template<typename MemberKind>
8369CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8370 auto *RD = Ty->getAsCXXRecordDecl();
8372
8373 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8374 return Results;
8375
8376 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8379
8380 // We just need to include all members of the right kind turned up by the
8381 // filter, at this point.
8382 if (S.LookupQualifiedName(R, RD))
8383 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8384 NamedDecl *decl = (*I)->getUnderlyingDecl();
8385 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8386 Results.insert(FK);
8387 }
8388 return Results;
8389}
8390
8391/// Check if we could call '.c_str()' on an object.
8392///
8393/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8394/// allow the call, or if it would be ambiguous).
8396 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8397
8398 MethodSet Results =
8399 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8400 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8401 MI != ME; ++MI)
8402 if ((*MI)->getMinRequiredArguments() == 0)
8403 return true;
8404 return false;
8405}
8406
8407// Check if a (w)string was passed when a (w)char* was needed, and offer a
8408// better diagnostic if so. AT is assumed to be valid.
8409// Returns true when a c_str() conversion method is found.
8410bool CheckPrintfHandler::checkForCStrMembers(
8411 const analyze_printf::ArgType &AT, const Expr *E) {
8412 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8413
8414 MethodSet Results =
8416
8417 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8418 MI != ME; ++MI) {
8419 const CXXMethodDecl *Method = *MI;
8420 if (Method->getMinRequiredArguments() == 0 &&
8421 AT.matchesType(S.Context, Method->getReturnType())) {
8422 // FIXME: Suggest parens if the expression needs them.
8424 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8425 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8426 return true;
8427 }
8428 }
8429
8430 return false;
8431}
8432
8433bool CheckPrintfHandler::HandlePrintfSpecifier(
8434 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8435 unsigned specifierLen, const TargetInfo &Target) {
8436 using namespace analyze_format_string;
8437 using namespace analyze_printf;
8438
8439 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8440
8441 if (FS.consumesDataArgument()) {
8442 if (atFirstArg) {
8443 atFirstArg = false;
8444 usesPositionalArgs = FS.usesPositionalArg();
8445 }
8446 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8447 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8448 startSpecifier, specifierLen);
8449 return false;
8450 }
8451 }
8452
8453 // First check if the field width, precision, and conversion specifier
8454 // have matching data arguments.
8455 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8456 startSpecifier, specifierLen)) {
8457 return false;
8458 }
8459
8460 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8461 startSpecifier, specifierLen)) {
8462 return false;
8463 }
8464
8465 if (!CS.consumesDataArgument()) {
8466 // FIXME: Technically specifying a precision or field width here
8467 // makes no sense. Worth issuing a warning at some point.
8468 return true;
8469 }
8470
8471 // Consume the argument.
8472 unsigned argIndex = FS.getArgIndex();
8473 if (argIndex < NumDataArgs) {
8474 // The check to see if the argIndex is valid will come later.
8475 // We set the bit here because we may exit early from this
8476 // function if we encounter some other error.
8477 CoveredArgs.set(argIndex);
8478 }
8479
8480 // FreeBSD kernel extensions.
8481 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8482 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8483 // We need at least two arguments.
8484 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8485 return false;
8486
8487 if (HasFormatArguments()) {
8488 // Claim the second argument.
8489 CoveredArgs.set(argIndex + 1);
8490
8491 // Type check the first argument (int for %b, pointer for %D)
8492 const Expr *Ex = getDataArg(argIndex);
8493 const analyze_printf::ArgType &AT =
8494 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8495 ? ArgType(S.Context.IntTy)
8496 : ArgType::CPointerTy;
8497 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8498 EmitFormatDiagnostic(
8499 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8500 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8501 << false << Ex->getSourceRange(),
8502 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8503 getSpecifierRange(startSpecifier, specifierLen));
8504
8505 // Type check the second argument (char * for both %b and %D)
8506 Ex = getDataArg(argIndex + 1);
8508 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8509 EmitFormatDiagnostic(
8510 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8511 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8512 << false << Ex->getSourceRange(),
8513 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8514 getSpecifierRange(startSpecifier, specifierLen));
8515 }
8516 return true;
8517 }
8518
8519 // Check for using an Objective-C specific conversion specifier
8520 // in a non-ObjC literal.
8521 if (!allowsObjCArg() && CS.isObjCArg()) {
8522 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8523 specifierLen);
8524 }
8525
8526 // %P can only be used with os_log.
8527 if (FSType != FormatStringType::OSLog &&
8528 CS.getKind() == ConversionSpecifier::PArg) {
8529 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8530 specifierLen);
8531 }
8532
8533 // %n is not allowed with os_log.
8534 if (FSType == FormatStringType::OSLog &&
8535 CS.getKind() == ConversionSpecifier::nArg) {
8536 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8537 getLocationOfByte(CS.getStart()),
8538 /*IsStringLocation*/ false,
8539 getSpecifierRange(startSpecifier, specifierLen));
8540
8541 return true;
8542 }
8543
8544 // Only scalars are allowed for os_trace.
8545 if (FSType == FormatStringType::OSTrace &&
8546 (CS.getKind() == ConversionSpecifier::PArg ||
8547 CS.getKind() == ConversionSpecifier::sArg ||
8548 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8549 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8550 specifierLen);
8551 }
8552
8553 // Check for use of public/private annotation outside of os_log().
8554 if (FSType != FormatStringType::OSLog) {
8555 if (FS.isPublic().isSet()) {
8556 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8557 << "public",
8558 getLocationOfByte(FS.isPublic().getPosition()),
8559 /*IsStringLocation*/ false,
8560 getSpecifierRange(startSpecifier, specifierLen));
8561 }
8562 if (FS.isPrivate().isSet()) {
8563 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8564 << "private",
8565 getLocationOfByte(FS.isPrivate().getPosition()),
8566 /*IsStringLocation*/ false,
8567 getSpecifierRange(startSpecifier, specifierLen));
8568 }
8569 }
8570
8571 const llvm::Triple &Triple = Target.getTriple();
8572 if (CS.getKind() == ConversionSpecifier::nArg &&
8573 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8574 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8575 getLocationOfByte(CS.getStart()),
8576 /*IsStringLocation*/ false,
8577 getSpecifierRange(startSpecifier, specifierLen));
8578 }
8579
8580 // Check for invalid use of field width
8581 if (!FS.hasValidFieldWidth()) {
8582 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8583 startSpecifier, specifierLen);
8584 }
8585
8586 // Check for invalid use of precision
8587 if (!FS.hasValidPrecision()) {
8588 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8589 startSpecifier, specifierLen);
8590 }
8591
8592 // Precision is mandatory for %P specifier.
8593 if (CS.getKind() == ConversionSpecifier::PArg &&
8595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8596 getLocationOfByte(startSpecifier),
8597 /*IsStringLocation*/ false,
8598 getSpecifierRange(startSpecifier, specifierLen));
8599 }
8600
8601 // Check each flag does not conflict with any other component.
8603 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8604 if (!FS.hasValidLeadingZeros())
8605 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8606 if (!FS.hasValidPlusPrefix())
8607 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8608 if (!FS.hasValidSpacePrefix())
8609 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8610 if (!FS.hasValidAlternativeForm())
8611 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8612 if (!FS.hasValidLeftJustified())
8613 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8614
8615 // Check that flags are not ignored by another flag
8616 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8617 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8618 startSpecifier, specifierLen);
8619 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8620 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8621 startSpecifier, specifierLen);
8622
8623 // Check the length modifier is valid with the given conversion specifier.
8625 S.getLangOpts()))
8626 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8627 diag::warn_format_nonsensical_length);
8628 else if (!FS.hasStandardLengthModifier())
8629 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8631 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8632 diag::warn_format_non_standard_conversion_spec);
8633
8635 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8636
8637 // The remaining checks depend on the data arguments.
8638 if (!HasFormatArguments())
8639 return true;
8640
8641 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8642 return false;
8643
8644 const Expr *Arg = getDataArg(argIndex);
8645 if (!Arg)
8646 return true;
8647
8648 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8649}
8650
8651static bool requiresParensToAddCast(const Expr *E) {
8652 // FIXME: We should have a general way to reason about operator
8653 // precedence and whether parens are actually needed here.
8654 // Take care of a few common cases where they aren't.
8655 const Expr *Inside = E->IgnoreImpCasts();
8656 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8657 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8658
8659 switch (Inside->getStmtClass()) {
8660 case Stmt::ArraySubscriptExprClass:
8661 case Stmt::CallExprClass:
8662 case Stmt::CharacterLiteralClass:
8663 case Stmt::CXXBoolLiteralExprClass:
8664 case Stmt::DeclRefExprClass:
8665 case Stmt::FloatingLiteralClass:
8666 case Stmt::IntegerLiteralClass:
8667 case Stmt::MemberExprClass:
8668 case Stmt::ObjCArrayLiteralClass:
8669 case Stmt::ObjCBoolLiteralExprClass:
8670 case Stmt::ObjCBoxedExprClass:
8671 case Stmt::ObjCDictionaryLiteralClass:
8672 case Stmt::ObjCEncodeExprClass:
8673 case Stmt::ObjCIvarRefExprClass:
8674 case Stmt::ObjCMessageExprClass:
8675 case Stmt::ObjCPropertyRefExprClass:
8676 case Stmt::ObjCStringLiteralClass:
8677 case Stmt::ObjCSubscriptRefExprClass:
8678 case Stmt::ParenExprClass:
8679 case Stmt::StringLiteralClass:
8680 case Stmt::UnaryOperatorClass:
8681 return false;
8682 default:
8683 return true;
8684 }
8685}
8686
8687static std::pair<QualType, StringRef>
8689 QualType IntendedTy,
8690 const Expr *E) {
8691 // Use a 'while' to peel off layers of typedefs.
8692 QualType TyTy = IntendedTy;
8693 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8694 StringRef Name = UserTy->getDecl()->getName();
8695 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8696 .Case("CFIndex", Context.getNSIntegerType())
8697 .Case("NSInteger", Context.getNSIntegerType())
8698 .Case("NSUInteger", Context.getNSUIntegerType())
8699 .Case("SInt32", Context.IntTy)
8700 .Case("UInt32", Context.UnsignedIntTy)
8701 .Default(QualType());
8702
8703 if (!CastTy.isNull())
8704 return std::make_pair(CastTy, Name);
8705
8706 TyTy = UserTy->desugar();
8707 }
8708
8709 // Strip parens if necessary.
8710 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8711 return shouldNotPrintDirectly(Context,
8712 PE->getSubExpr()->getType(),
8713 PE->getSubExpr());
8714
8715 // If this is a conditional expression, then its result type is constructed
8716 // via usual arithmetic conversions and thus there might be no necessary
8717 // typedef sugar there. Recurse to operands to check for NSInteger &
8718 // Co. usage condition.
8719 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8720 QualType TrueTy, FalseTy;
8721 StringRef TrueName, FalseName;
8722
8723 std::tie(TrueTy, TrueName) =
8724 shouldNotPrintDirectly(Context,
8725 CO->getTrueExpr()->getType(),
8726 CO->getTrueExpr());
8727 std::tie(FalseTy, FalseName) =
8728 shouldNotPrintDirectly(Context,
8729 CO->getFalseExpr()->getType(),
8730 CO->getFalseExpr());
8731
8732 if (TrueTy == FalseTy)
8733 return std::make_pair(TrueTy, TrueName);
8734 else if (TrueTy.isNull())
8735 return std::make_pair(FalseTy, FalseName);
8736 else if (FalseTy.isNull())
8737 return std::make_pair(TrueTy, TrueName);
8738 }
8739
8740 return std::make_pair(QualType(), StringRef());
8741}
8742
8743/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8744/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8745/// type do not count.
8746static bool
8748 QualType From = ICE->getSubExpr()->getType();
8749 QualType To = ICE->getType();
8750 // It's an integer promotion if the destination type is the promoted
8751 // source type.
8752 if (ICE->getCastKind() == CK_IntegralCast &&
8754 S.Context.getPromotedIntegerType(From) == To)
8755 return true;
8756 // Look through vector types, since we do default argument promotion for
8757 // those in OpenCL.
8758 if (const auto *VecTy = From->getAs<ExtVectorType>())
8759 From = VecTy->getElementType();
8760 if (const auto *VecTy = To->getAs<ExtVectorType>())
8761 To = VecTy->getElementType();
8762 // It's a floating promotion if the source type is a lower rank.
8763 return ICE->getCastKind() == CK_FloatingCast &&
8764 S.Context.getFloatingTypeOrder(From, To) < 0;
8765}
8766
8769 DiagnosticsEngine &Diags, SourceLocation Loc) {
8771 if (Diags.isIgnored(
8772 diag::warn_format_conversion_argument_type_mismatch_signedness,
8773 Loc) ||
8774 Diags.isIgnored(
8775 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8776 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8778 }
8779 }
8780 return Match;
8781}
8782
8783bool
8784CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8785 const char *StartSpecifier,
8786 unsigned SpecifierLen,
8787 const Expr *E) {
8788 using namespace analyze_format_string;
8789 using namespace analyze_printf;
8790
8791 // Now type check the data expression that matches the
8792 // format specifier.
8793 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8794 if (!AT.isValid())
8795 return true;
8796
8797 QualType ExprTy = E->getType();
8798 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8799 ExprTy = TET->getUnderlyingExpr()->getType();
8800 }
8801
8802 // When using the format attribute in C++, you can receive a function or an
8803 // array that will necessarily decay to a pointer when passed to the final
8804 // format consumer. Apply decay before type comparison.
8805 if (ExprTy->canDecayToPointerType())
8806 ExprTy = S.Context.getDecayedType(ExprTy);
8807
8808 // Diagnose attempts to print a boolean value as a character. Unlike other
8809 // -Wformat diagnostics, this is fine from a type perspective, but it still
8810 // doesn't make sense.
8813 const CharSourceRange &CSR =
8814 getSpecifierRange(StartSpecifier, SpecifierLen);
8815 SmallString<4> FSString;
8816 llvm::raw_svector_ostream os(FSString);
8817 FS.toString(os);
8818 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8819 << FSString,
8820 E->getExprLoc(), false, CSR);
8821 return true;
8822 }
8823
8824 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8825 // dumping raw class data (like is-a pointer), not actual data.
8827 ExprTy->isObjCObjectPointerType()) {
8828 const CharSourceRange &CSR =
8829 getSpecifierRange(StartSpecifier, SpecifierLen);
8830 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8831 E->getExprLoc(), false, CSR);
8832 return true;
8833 }
8834
8835 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8837 ArgType::MatchKind OrigMatch = Match;
8838
8840 if (Match == ArgType::Match)
8841 return true;
8842
8843 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8844 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8845
8846 // Look through argument promotions for our error message's reported type.
8847 // This includes the integral and floating promotions, but excludes array
8848 // and function pointer decay (seeing that an argument intended to be a
8849 // string has type 'char [6]' is probably more confusing than 'char *') and
8850 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8851 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8852 if (isArithmeticArgumentPromotion(S, ICE)) {
8853 E = ICE->getSubExpr();
8854 ExprTy = E->getType();
8855
8856 // Check if we didn't match because of an implicit cast from a 'char'
8857 // or 'short' to an 'int'. This is done because printf is a varargs
8858 // function.
8859 if (ICE->getType() == S.Context.IntTy ||
8860 ICE->getType() == S.Context.UnsignedIntTy) {
8861 // All further checking is done on the subexpression
8862 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8863 if (OrigMatch == ArgType::NoMatchSignedness &&
8864 ImplicitMatch != ArgType::NoMatchSignedness)
8865 // If the original match was a signedness match this match on the
8866 // implicit cast type also need to be signedness match otherwise we
8867 // might introduce new unexpected warnings from -Wformat-signedness.
8868 return true;
8869 ImplicitMatch = handleFormatSignedness(
8870 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8871 if (ImplicitMatch == ArgType::Match)
8872 return true;
8873 }
8874 }
8875 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8876 // Special case for 'a', which has type 'int' in C.
8877 // Note, however, that we do /not/ want to treat multibyte constants like
8878 // 'MooV' as characters! This form is deprecated but still exists. In
8879 // addition, don't treat expressions as of type 'char' if one byte length
8880 // modifier is provided.
8881 if (ExprTy == S.Context.IntTy &&
8883 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8884 ExprTy = S.Context.CharTy;
8885 // To improve check results, we consider a character literal in C
8886 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8887 // more likely a type confusion situation, so we will suggest to
8888 // use '%hhd' instead by discarding the MatchPromotion.
8889 if (Match == ArgType::MatchPromotion)
8891 }
8892 }
8893 if (Match == ArgType::MatchPromotion) {
8894 // WG14 N2562 only clarified promotions in *printf
8895 // For NSLog in ObjC, just preserve -Wformat behavior
8896 if (!S.getLangOpts().ObjC &&
8897 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8898 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8899 return true;
8901 }
8902 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8903 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8904 Match = ImplicitMatch;
8905 assert(Match != ArgType::MatchPromotion);
8906
8907 // Look through unscoped enums to their underlying type.
8908 bool IsEnum = false;
8909 bool IsScopedEnum = false;
8910 QualType IntendedTy = ExprTy;
8911 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8912 IntendedTy = ED->getIntegerType();
8913 if (!ED->isScoped()) {
8914 ExprTy = IntendedTy;
8915 // This controls whether we're talking about the underlying type or not,
8916 // which we only want to do when it's an unscoped enum.
8917 IsEnum = true;
8918 } else {
8919 IsScopedEnum = true;
8920 }
8921 }
8922
8923 // %C in an Objective-C context prints a unichar, not a wchar_t.
8924 // If the argument is an integer of some kind, believe the %C and suggest
8925 // a cast instead of changing the conversion specifier.
8926 if (isObjCContext() &&
8929 !ExprTy->isCharType()) {
8930 // 'unichar' is defined as a typedef of unsigned short, but we should
8931 // prefer using the typedef if it is visible.
8932 IntendedTy = S.Context.UnsignedShortTy;
8933
8934 // While we are here, check if the value is an IntegerLiteral that happens
8935 // to be within the valid range.
8936 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8937 const llvm::APInt &V = IL->getValue();
8938 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8939 return true;
8940 }
8941
8942 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8944 if (S.LookupName(Result, S.getCurScope())) {
8945 NamedDecl *ND = Result.getFoundDecl();
8946 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8947 if (TD->getUnderlyingType() == IntendedTy)
8948 IntendedTy =
8950 /*Qualifier=*/std::nullopt, TD);
8951 }
8952 }
8953 }
8954
8955 // Special-case some of Darwin's platform-independence types by suggesting
8956 // casts to primitive types that are known to be large enough.
8957 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8958 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8959 QualType CastTy;
8960 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8961 if (!CastTy.isNull()) {
8962 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8963 // (long in ASTContext). Only complain to pedants or when they're the
8964 // underlying type of a scoped enum (which always needs a cast).
8965 if (!IsScopedEnum &&
8966 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8967 (AT.isSizeT() || AT.isPtrdiffT()) &&
8968 AT.matchesType(S.Context, CastTy))
8970 IntendedTy = CastTy;
8971 ShouldNotPrintDirectly = true;
8972 }
8973 }
8974
8975 // We may be able to offer a FixItHint if it is a supported type.
8976 PrintfSpecifier fixedFS = FS;
8977 bool Success =
8978 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8979
8980 if (Success) {
8981 // Get the fix string from the fixed format specifier
8982 SmallString<16> buf;
8983 llvm::raw_svector_ostream os(buf);
8984 fixedFS.toString(os);
8985
8986 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8987
8988 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8989 unsigned Diag;
8990 switch (Match) {
8991 case ArgType::Match:
8994 llvm_unreachable("expected non-matching");
8996 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8997 break;
8999 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9000 break;
9002 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9003 break;
9004 case ArgType::NoMatch:
9005 Diag = diag::warn_format_conversion_argument_type_mismatch;
9006 break;
9007 }
9008
9009 // In this case, the specifier is wrong and should be changed to match
9010 // the argument.
9011 EmitFormatDiagnostic(S.PDiag(Diag)
9013 << IntendedTy << IsEnum << E->getSourceRange(),
9014 E->getBeginLoc(),
9015 /*IsStringLocation*/ false, SpecRange,
9016 FixItHint::CreateReplacement(SpecRange, os.str()));
9017 } else {
9018 // The canonical type for formatting this value is different from the
9019 // actual type of the expression. (This occurs, for example, with Darwin's
9020 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9021 // should be printed as 'long' for 64-bit compatibility.)
9022 // Rather than emitting a normal format/argument mismatch, we want to
9023 // add a cast to the recommended type (and correct the format string
9024 // if necessary). We should also do so for scoped enumerations.
9025 SmallString<16> CastBuf;
9026 llvm::raw_svector_ostream CastFix(CastBuf);
9027 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9028 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9029 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9030
9032 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9033 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9034 E->getExprLoc());
9035 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9036 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9037
9038 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9039 // If there's already a cast present, just replace it.
9040 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9041 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9042
9043 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9044 // If the expression has high enough precedence,
9045 // just write the C-style cast.
9046 Hints.push_back(
9047 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9048 } else {
9049 // Otherwise, add parens around the expression as well as the cast.
9050 CastFix << "(";
9051 Hints.push_back(
9052 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9053
9054 // We don't use getLocForEndOfToken because it returns invalid source
9055 // locations for macro expansions (by design).
9059 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9060 }
9061
9062 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9063 // The expression has a type that should not be printed directly.
9064 // We extract the name from the typedef because we don't want to show
9065 // the underlying type in the diagnostic.
9066 StringRef Name;
9067 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9068 Name = TypedefTy->getDecl()->getName();
9069 else
9070 Name = CastTyName;
9071 unsigned Diag = Match == ArgType::NoMatchPedantic
9072 ? diag::warn_format_argument_needs_cast_pedantic
9073 : diag::warn_format_argument_needs_cast;
9074 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9075 << E->getSourceRange(),
9076 E->getBeginLoc(), /*IsStringLocation=*/false,
9077 SpecRange, Hints);
9078 } else {
9079 // In this case, the expression could be printed using a different
9080 // specifier, but we've decided that the specifier is probably correct
9081 // and we should cast instead. Just use the normal warning message.
9082
9083 unsigned Diag =
9084 IsScopedEnum
9085 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9086 : diag::warn_format_conversion_argument_type_mismatch;
9087
9088 EmitFormatDiagnostic(
9089 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9090 << IsEnum << E->getSourceRange(),
9091 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9092 }
9093 }
9094 } else {
9095 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9096 SpecifierLen);
9097 // Since the warning for passing non-POD types to variadic functions
9098 // was deferred until now, we emit a warning for non-POD
9099 // arguments here.
9100 bool EmitTypeMismatch = false;
9101 switch (S.isValidVarArgType(ExprTy)) {
9102 case VarArgKind::Valid:
9104 unsigned Diag;
9105 switch (Match) {
9106 case ArgType::Match:
9109 llvm_unreachable("expected non-matching");
9111 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9112 break;
9114 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9115 break;
9117 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9118 break;
9119 case ArgType::NoMatch:
9120 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9121 ? diag::err_format_conversion_argument_type_mismatch
9122 : diag::warn_format_conversion_argument_type_mismatch;
9123 break;
9124 }
9125
9126 EmitFormatDiagnostic(
9127 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9128 << IsEnum << CSR << E->getSourceRange(),
9129 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9130 break;
9131 }
9134 if (CallType == VariadicCallType::DoesNotApply) {
9135 EmitTypeMismatch = true;
9136 } else {
9137 EmitFormatDiagnostic(
9138 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9139 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9140 << AT.getRepresentativeTypeName(S.Context) << CSR
9141 << E->getSourceRange(),
9142 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9143 checkForCStrMembers(AT, E);
9144 }
9145 break;
9146
9148 if (CallType == VariadicCallType::DoesNotApply)
9149 EmitTypeMismatch = true;
9150 else if (ExprTy->isObjCObjectType())
9151 EmitFormatDiagnostic(
9152 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9153 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9154 << AT.getRepresentativeTypeName(S.Context) << CSR
9155 << E->getSourceRange(),
9156 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9157 else
9158 // FIXME: If this is an initializer list, suggest removing the braces
9159 // or inserting a cast to the target type.
9160 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9161 << isa<InitListExpr>(E) << ExprTy << CallType
9163 break;
9164 }
9165
9166 if (EmitTypeMismatch) {
9167 // The function is not variadic, so we do not generate warnings about
9168 // being allowed to pass that object as a variadic argument. Instead,
9169 // since there are inherently no printf specifiers for types which cannot
9170 // be passed as variadic arguments, emit a plain old specifier mismatch
9171 // argument.
9172 EmitFormatDiagnostic(
9173 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9174 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9175 << E->getSourceRange(),
9176 E->getBeginLoc(), false, CSR);
9177 }
9178
9179 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9180 "format string specifier index out of range");
9181 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9182 }
9183
9184 return true;
9185}
9186
9187//===--- CHECK: Scanf format string checking ------------------------------===//
9188
9189namespace {
9190
9191class CheckScanfHandler : public CheckFormatHandler {
9192public:
9193 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9194 const Expr *origFormatExpr, FormatStringType type,
9195 unsigned firstDataArg, unsigned numDataArgs,
9196 const char *beg, Sema::FormatArgumentPassingKind APK,
9197 ArrayRef<const Expr *> Args, unsigned formatIdx,
9198 bool inFunctionCall, VariadicCallType CallType,
9199 llvm::SmallBitVector &CheckedVarArgs,
9200 UncoveredArgHandler &UncoveredArg)
9201 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9202 numDataArgs, beg, APK, Args, formatIdx,
9203 inFunctionCall, CallType, CheckedVarArgs,
9204 UncoveredArg) {}
9205
9206 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9207 const char *startSpecifier,
9208 unsigned specifierLen) override;
9209
9210 bool HandleInvalidScanfConversionSpecifier(
9211 const analyze_scanf::ScanfSpecifier &FS,
9212 const char *startSpecifier,
9213 unsigned specifierLen) override;
9214
9215 void HandleIncompleteScanList(const char *start, const char *end) override;
9216};
9217
9218} // namespace
9219
9220void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9221 const char *end) {
9222 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9223 getLocationOfByte(end), /*IsStringLocation*/true,
9224 getSpecifierRange(start, end - start));
9225}
9226
9227bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9229 const char *startSpecifier,
9230 unsigned specifierLen) {
9233
9234 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9235 getLocationOfByte(CS.getStart()),
9236 startSpecifier, specifierLen,
9237 CS.getStart(), CS.getLength());
9238}
9239
9240bool CheckScanfHandler::HandleScanfSpecifier(
9242 const char *startSpecifier,
9243 unsigned specifierLen) {
9244 using namespace analyze_scanf;
9245 using namespace analyze_format_string;
9246
9247 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9248
9249 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9250 // be used to decide if we are using positional arguments consistently.
9251 if (FS.consumesDataArgument()) {
9252 if (atFirstArg) {
9253 atFirstArg = false;
9254 usesPositionalArgs = FS.usesPositionalArg();
9255 }
9256 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9257 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9258 startSpecifier, specifierLen);
9259 return false;
9260 }
9261 }
9262
9263 // Check if the field with is non-zero.
9264 const OptionalAmount &Amt = FS.getFieldWidth();
9266 if (Amt.getConstantAmount() == 0) {
9267 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9268 Amt.getConstantLength());
9269 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9270 getLocationOfByte(Amt.getStart()),
9271 /*IsStringLocation*/true, R,
9273 }
9274 }
9275
9276 if (!FS.consumesDataArgument()) {
9277 // FIXME: Technically specifying a precision or field width here
9278 // makes no sense. Worth issuing a warning at some point.
9279 return true;
9280 }
9281
9282 // Consume the argument.
9283 unsigned argIndex = FS.getArgIndex();
9284 if (argIndex < NumDataArgs) {
9285 // The check to see if the argIndex is valid will come later.
9286 // We set the bit here because we may exit early from this
9287 // function if we encounter some other error.
9288 CoveredArgs.set(argIndex);
9289 }
9290
9291 // Check the length modifier is valid with the given conversion specifier.
9293 S.getLangOpts()))
9294 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9295 diag::warn_format_nonsensical_length);
9296 else if (!FS.hasStandardLengthModifier())
9297 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9299 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9300 diag::warn_format_non_standard_conversion_spec);
9301
9303 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9304
9305 // The remaining checks depend on the data arguments.
9306 if (!HasFormatArguments())
9307 return true;
9308
9309 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9310 return false;
9311
9312 // Check that the argument type matches the format specifier.
9313 const Expr *Ex = getDataArg(argIndex);
9314 if (!Ex)
9315 return true;
9316
9318
9319 if (!AT.isValid()) {
9320 return true;
9321 }
9322
9324 AT.matchesType(S.Context, Ex->getType());
9327 return true;
9330
9331 ScanfSpecifier fixedFS = FS;
9332 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9333 S.getLangOpts(), S.Context);
9334
9335 unsigned Diag =
9336 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9337 : Signedness
9338 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9339 : diag::warn_format_conversion_argument_type_mismatch;
9340
9341 if (Success) {
9342 // Get the fix string from the fixed format specifier.
9343 SmallString<128> buf;
9344 llvm::raw_svector_ostream os(buf);
9345 fixedFS.toString(os);
9346
9347 EmitFormatDiagnostic(
9349 << Ex->getType() << false << Ex->getSourceRange(),
9350 Ex->getBeginLoc(),
9351 /*IsStringLocation*/ false,
9352 getSpecifierRange(startSpecifier, specifierLen),
9354 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9355 } else {
9356 EmitFormatDiagnostic(S.PDiag(Diag)
9358 << Ex->getType() << false << Ex->getSourceRange(),
9359 Ex->getBeginLoc(),
9360 /*IsStringLocation*/ false,
9361 getSpecifierRange(startSpecifier, specifierLen));
9362 }
9363
9364 return true;
9365}
9366
9367static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9369 const StringLiteral *Fmt,
9371 const Expr *FmtExpr, bool InFunctionCall) {
9372 bool HadError = false;
9373 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9374 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9375 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9376 // In positional-style format strings, the same specifier can appear
9377 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9378 // are sorted by getPosition(), and we process each range of equal
9379 // getPosition() values as one group.
9380 // RefArgs are taken from a string literal that was given to
9381 // attribute(format_matches), and if we got this far, we have already
9382 // verified that if it has positional specifiers that appear in multiple
9383 // locations, then they are all mutually compatible. What's left for us to
9384 // do is verify that all specifiers with the same position in FmtArgs are
9385 // compatible with the RefArgs specifiers. We check each specifier from
9386 // FmtArgs against the first member of the RefArgs group.
9387 for (; FmtIter < FmtEnd; ++FmtIter) {
9388 // Clang does not diagnose missing format specifiers in positional-style
9389 // strings (TODO: which it probably should do, as it is UB to skip over a
9390 // format argument). Skip specifiers if needed.
9391 if (FmtIter->getPosition() < RefIter->getPosition())
9392 continue;
9393
9394 // Delimits a new getPosition() value.
9395 if (FmtIter->getPosition() > RefIter->getPosition())
9396 break;
9397
9398 HadError |=
9399 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9400 }
9401
9402 // Jump RefIter to the start of the next group.
9403 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9404 return Arg.getPosition() != RefIter->getPosition();
9405 });
9406 }
9407
9408 if (FmtIter < FmtEnd) {
9409 CheckFormatHandler::EmitFormatDiagnostic(
9410 S, InFunctionCall, FmtExpr,
9411 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9412 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9413 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9414 } else if (RefIter < RefEnd) {
9415 CheckFormatHandler::EmitFormatDiagnostic(
9416 S, InFunctionCall, FmtExpr,
9417 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9418 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9419 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9420 << 1 << RefIter->getSourceRange();
9421 }
9422 return !HadError;
9423}
9424
9426 Sema &S, const FormatStringLiteral *FExpr,
9427 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9429 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9430 bool inFunctionCall, VariadicCallType CallType,
9431 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9432 bool IgnoreStringsWithoutSpecifiers) {
9433 // CHECK: is the format string a wide literal?
9434 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9435 CheckFormatHandler::EmitFormatDiagnostic(
9436 S, inFunctionCall, Args[format_idx],
9437 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9438 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9439 return;
9440 }
9441
9442 // Str - The format string. NOTE: this is NOT null-terminated!
9443 StringRef StrRef = FExpr->getString();
9444 const char *Str = StrRef.data();
9445 // Account for cases where the string literal is truncated in a declaration.
9446 const ConstantArrayType *T =
9447 S.Context.getAsConstantArrayType(FExpr->getType());
9448 assert(T && "String literal not of constant array type!");
9449 size_t TypeSize = T->getZExtSize();
9450 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9451 const unsigned numDataArgs = Args.size() - firstDataArg;
9452
9453 if (IgnoreStringsWithoutSpecifiers &&
9455 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9456 return;
9457
9458 // Emit a warning if the string literal is truncated and does not contain an
9459 // embedded null character.
9460 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9461 CheckFormatHandler::EmitFormatDiagnostic(
9462 S, inFunctionCall, Args[format_idx],
9463 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9464 FExpr->getBeginLoc(),
9465 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9466 return;
9467 }
9468
9469 // CHECK: empty format string?
9470 if (StrLen == 0 && numDataArgs > 0) {
9471 CheckFormatHandler::EmitFormatDiagnostic(
9472 S, inFunctionCall, Args[format_idx],
9473 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9474 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9475 return;
9476 }
9477
9482 bool IsObjC =
9484 if (ReferenceFormatString == nullptr) {
9485 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9486 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9487 inFunctionCall, CallType, CheckedVarArgs,
9488 UncoveredArg);
9489
9491 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9494 H.DoneProcessing();
9495 } else {
9497 Type, ReferenceFormatString, FExpr->getFormatString(),
9498 inFunctionCall ? nullptr : Args[format_idx]);
9499 }
9500 } else if (Type == FormatStringType::Scanf) {
9501 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9502 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9503 CallType, CheckedVarArgs, UncoveredArg);
9504
9506 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9507 H.DoneProcessing();
9508 } // TODO: handle other formats
9509}
9510
9512 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9513 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9518 return true;
9519
9520 bool IsObjC =
9523 FormatStringLiteral RefLit = AuthoritativeFormatString;
9524 FormatStringLiteral TestLit = TestedFormatString;
9525 const Expr *Arg;
9526 bool DiagAtStringLiteral;
9527 if (FunctionCallArg) {
9528 Arg = FunctionCallArg;
9529 DiagAtStringLiteral = false;
9530 } else {
9531 Arg = TestedFormatString;
9532 DiagAtStringLiteral = true;
9533 }
9534 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9535 AuthoritativeFormatString, Type,
9536 IsObjC, true, RefArgs) &&
9537 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9538 DiagAtStringLiteral, FmtArgs)) {
9539 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9540 TestedFormatString, FmtArgs, Arg,
9541 DiagAtStringLiteral);
9542 }
9543 return false;
9544}
9545
9547 const StringLiteral *Str) {
9552 return true;
9553
9554 FormatStringLiteral RefLit = Str;
9556 bool IsObjC =
9558 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9559 true, Args))
9560 return false;
9561
9562 // Group arguments by getPosition() value, and check that each member of the
9563 // group is compatible with the first member. This verifies that when
9564 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9565 // are mutually compatible. As an optimization, don't test the first member
9566 // against itself.
9567 bool HadError = false;
9568 auto Iter = Args.begin();
9569 auto End = Args.end();
9570 while (Iter != End) {
9571 const auto &FirstInGroup = *Iter;
9572 for (++Iter;
9573 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9574 ++Iter) {
9575 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9576 }
9577 }
9578 return !HadError;
9579}
9580
9582 // Str - The format string. NOTE: this is NOT null-terminated!
9583 StringRef StrRef = FExpr->getString();
9584 const char *Str = StrRef.data();
9585 // Account for cases where the string literal is truncated in a declaration.
9586 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9587 assert(T && "String literal not of constant array type!");
9588 size_t TypeSize = T->getZExtSize();
9589 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9590 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9591 getLangOpts(),
9592 Context.getTargetInfo());
9593}
9594
9595//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9596
9597// Returns the related absolute value function that is larger, of 0 if one
9598// does not exist.
9599static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9600 switch (AbsFunction) {
9601 default:
9602 return 0;
9603
9604 case Builtin::BI__builtin_abs:
9605 return Builtin::BI__builtin_labs;
9606 case Builtin::BI__builtin_labs:
9607 return Builtin::BI__builtin_llabs;
9608 case Builtin::BI__builtin_llabs:
9609 return 0;
9610
9611 case Builtin::BI__builtin_fabsf:
9612 return Builtin::BI__builtin_fabs;
9613 case Builtin::BI__builtin_fabs:
9614 return Builtin::BI__builtin_fabsl;
9615 case Builtin::BI__builtin_fabsl:
9616 return 0;
9617
9618 case Builtin::BI__builtin_cabsf:
9619 return Builtin::BI__builtin_cabs;
9620 case Builtin::BI__builtin_cabs:
9621 return Builtin::BI__builtin_cabsl;
9622 case Builtin::BI__builtin_cabsl:
9623 return 0;
9624
9625 case Builtin::BIabs:
9626 return Builtin::BIlabs;
9627 case Builtin::BIlabs:
9628 return Builtin::BIllabs;
9629 case Builtin::BIllabs:
9630 return 0;
9631
9632 case Builtin::BIfabsf:
9633 return Builtin::BIfabs;
9634 case Builtin::BIfabs:
9635 return Builtin::BIfabsl;
9636 case Builtin::BIfabsl:
9637 return 0;
9638
9639 case Builtin::BIcabsf:
9640 return Builtin::BIcabs;
9641 case Builtin::BIcabs:
9642 return Builtin::BIcabsl;
9643 case Builtin::BIcabsl:
9644 return 0;
9645 }
9646}
9647
9648// Returns the argument type of the absolute value function.
9650 unsigned AbsType) {
9651 if (AbsType == 0)
9652 return QualType();
9653
9655 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9657 return QualType();
9658
9660 if (!FT)
9661 return QualType();
9662
9663 if (FT->getNumParams() != 1)
9664 return QualType();
9665
9666 return FT->getParamType(0);
9667}
9668
9669// Returns the best absolute value function, or zero, based on type and
9670// current absolute value function.
9671static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9672 unsigned AbsFunctionKind) {
9673 unsigned BestKind = 0;
9674 uint64_t ArgSize = Context.getTypeSize(ArgType);
9675 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9676 Kind = getLargerAbsoluteValueFunction(Kind)) {
9677 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9678 if (Context.getTypeSize(ParamType) >= ArgSize) {
9679 if (BestKind == 0)
9680 BestKind = Kind;
9681 else if (Context.hasSameType(ParamType, ArgType)) {
9682 BestKind = Kind;
9683 break;
9684 }
9685 }
9686 }
9687 return BestKind;
9688}
9689
9695
9697 if (T->isIntegralOrEnumerationType())
9698 return AVK_Integer;
9699 if (T->isRealFloatingType())
9700 return AVK_Floating;
9701 if (T->isAnyComplexType())
9702 return AVK_Complex;
9703
9704 llvm_unreachable("Type not integer, floating, or complex");
9705}
9706
9707// Changes the absolute value function to a different type. Preserves whether
9708// the function is a builtin.
9709static unsigned changeAbsFunction(unsigned AbsKind,
9710 AbsoluteValueKind ValueKind) {
9711 switch (ValueKind) {
9712 case AVK_Integer:
9713 switch (AbsKind) {
9714 default:
9715 return 0;
9716 case Builtin::BI__builtin_fabsf:
9717 case Builtin::BI__builtin_fabs:
9718 case Builtin::BI__builtin_fabsl:
9719 case Builtin::BI__builtin_cabsf:
9720 case Builtin::BI__builtin_cabs:
9721 case Builtin::BI__builtin_cabsl:
9722 return Builtin::BI__builtin_abs;
9723 case Builtin::BIfabsf:
9724 case Builtin::BIfabs:
9725 case Builtin::BIfabsl:
9726 case Builtin::BIcabsf:
9727 case Builtin::BIcabs:
9728 case Builtin::BIcabsl:
9729 return Builtin::BIabs;
9730 }
9731 case AVK_Floating:
9732 switch (AbsKind) {
9733 default:
9734 return 0;
9735 case Builtin::BI__builtin_abs:
9736 case Builtin::BI__builtin_labs:
9737 case Builtin::BI__builtin_llabs:
9738 case Builtin::BI__builtin_cabsf:
9739 case Builtin::BI__builtin_cabs:
9740 case Builtin::BI__builtin_cabsl:
9741 return Builtin::BI__builtin_fabsf;
9742 case Builtin::BIabs:
9743 case Builtin::BIlabs:
9744 case Builtin::BIllabs:
9745 case Builtin::BIcabsf:
9746 case Builtin::BIcabs:
9747 case Builtin::BIcabsl:
9748 return Builtin::BIfabsf;
9749 }
9750 case AVK_Complex:
9751 switch (AbsKind) {
9752 default:
9753 return 0;
9754 case Builtin::BI__builtin_abs:
9755 case Builtin::BI__builtin_labs:
9756 case Builtin::BI__builtin_llabs:
9757 case Builtin::BI__builtin_fabsf:
9758 case Builtin::BI__builtin_fabs:
9759 case Builtin::BI__builtin_fabsl:
9760 return Builtin::BI__builtin_cabsf;
9761 case Builtin::BIabs:
9762 case Builtin::BIlabs:
9763 case Builtin::BIllabs:
9764 case Builtin::BIfabsf:
9765 case Builtin::BIfabs:
9766 case Builtin::BIfabsl:
9767 return Builtin::BIcabsf;
9768 }
9769 }
9770 llvm_unreachable("Unable to convert function");
9771}
9772
9773static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9774 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9775 if (!FnInfo)
9776 return 0;
9777
9778 switch (FDecl->getBuiltinID()) {
9779 default:
9780 return 0;
9781 case Builtin::BI__builtin_abs:
9782 case Builtin::BI__builtin_fabs:
9783 case Builtin::BI__builtin_fabsf:
9784 case Builtin::BI__builtin_fabsl:
9785 case Builtin::BI__builtin_labs:
9786 case Builtin::BI__builtin_llabs:
9787 case Builtin::BI__builtin_cabs:
9788 case Builtin::BI__builtin_cabsf:
9789 case Builtin::BI__builtin_cabsl:
9790 case Builtin::BIabs:
9791 case Builtin::BIlabs:
9792 case Builtin::BIllabs:
9793 case Builtin::BIfabs:
9794 case Builtin::BIfabsf:
9795 case Builtin::BIfabsl:
9796 case Builtin::BIcabs:
9797 case Builtin::BIcabsf:
9798 case Builtin::BIcabsl:
9799 return FDecl->getBuiltinID();
9800 }
9801 llvm_unreachable("Unknown Builtin type");
9802}
9803
9804// If the replacement is valid, emit a note with replacement function.
9805// Additionally, suggest including the proper header if not already included.
9807 unsigned AbsKind, QualType ArgType) {
9808 bool EmitHeaderHint = true;
9809 const char *HeaderName = nullptr;
9810 std::string FunctionName;
9811 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9812 FunctionName = "std::abs";
9813 if (ArgType->isIntegralOrEnumerationType()) {
9814 HeaderName = "cstdlib";
9815 } else if (ArgType->isRealFloatingType()) {
9816 HeaderName = "cmath";
9817 } else {
9818 llvm_unreachable("Invalid Type");
9819 }
9820
9821 // Lookup all std::abs
9822 if (NamespaceDecl *Std = S.getStdNamespace()) {
9823 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9825 S.LookupQualifiedName(R, Std);
9826
9827 for (const auto *I : R) {
9828 const FunctionDecl *FDecl = nullptr;
9829 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9830 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9831 } else {
9832 FDecl = dyn_cast<FunctionDecl>(I);
9833 }
9834 if (!FDecl)
9835 continue;
9836
9837 // Found std::abs(), check that they are the right ones.
9838 if (FDecl->getNumParams() != 1)
9839 continue;
9840
9841 // Check that the parameter type can handle the argument.
9842 QualType ParamType = FDecl->getParamDecl(0)->getType();
9843 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9844 S.Context.getTypeSize(ArgType) <=
9845 S.Context.getTypeSize(ParamType)) {
9846 // Found a function, don't need the header hint.
9847 EmitHeaderHint = false;
9848 break;
9849 }
9850 }
9851 }
9852 } else {
9853 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9854 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9855
9856 if (HeaderName) {
9857 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9858 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9860 S.LookupName(R, S.getCurScope());
9861
9862 if (R.isSingleResult()) {
9863 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9864 if (FD && FD->getBuiltinID() == AbsKind) {
9865 EmitHeaderHint = false;
9866 } else {
9867 return;
9868 }
9869 } else if (!R.empty()) {
9870 return;
9871 }
9872 }
9873 }
9874
9875 S.Diag(Loc, diag::note_replace_abs_function)
9876 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9877
9878 if (!HeaderName)
9879 return;
9880
9881 if (!EmitHeaderHint)
9882 return;
9883
9884 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9885 << FunctionName;
9886}
9887
9888template <std::size_t StrLen>
9889static bool IsStdFunction(const FunctionDecl *FDecl,
9890 const char (&Str)[StrLen]) {
9891 if (!FDecl)
9892 return false;
9893 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9894 return false;
9895 if (!FDecl->isInStdNamespace())
9896 return false;
9897
9898 return true;
9899}
9900
9901enum class MathCheck { NaN, Inf };
9902static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9903 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9904 return llvm::is_contained(names, calleeName);
9905 };
9906
9907 switch (Check) {
9908 case MathCheck::NaN:
9909 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9910 "__builtin_nanf16", "__builtin_nanf128"});
9911 case MathCheck::Inf:
9912 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9913 "__builtin_inff16", "__builtin_inff128"});
9914 }
9915 llvm_unreachable("unknown MathCheck");
9916}
9917
9918static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9919 if (FDecl->getName() != "infinity")
9920 return false;
9921
9922 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9923 const CXXRecordDecl *RDecl = MDecl->getParent();
9924 if (RDecl->getName() != "numeric_limits")
9925 return false;
9926
9927 if (const NamespaceDecl *NSDecl =
9928 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9929 return NSDecl->isStdNamespace();
9930 }
9931
9932 return false;
9933}
9934
9935void Sema::CheckInfNaNFunction(const CallExpr *Call,
9936 const FunctionDecl *FDecl) {
9937 if (!FDecl->getIdentifier())
9938 return;
9939
9940 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9941 if (FPO.getNoHonorNaNs() &&
9942 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9944 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9945 << 1 << 0 << Call->getSourceRange();
9946 return;
9947 }
9948
9949 if (FPO.getNoHonorInfs() &&
9950 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9951 IsInfinityFunction(FDecl) ||
9953 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9954 << 0 << 0 << Call->getSourceRange();
9955 }
9956}
9957
9958void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9959 const FunctionDecl *FDecl) {
9960 if (Call->getNumArgs() != 1)
9961 return;
9962
9963 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9964 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9965 if (AbsKind == 0 && !IsStdAbs)
9966 return;
9967
9968 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9969 QualType ParamType = Call->getArg(0)->getType();
9970
9971 // Unsigned types cannot be negative. Suggest removing the absolute value
9972 // function call.
9973 if (ArgType->isUnsignedIntegerType()) {
9974 std::string FunctionName =
9975 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9976 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9977 Diag(Call->getExprLoc(), diag::note_remove_abs)
9978 << FunctionName
9979 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9980 return;
9981 }
9982
9983 // Taking the absolute value of a pointer is very suspicious, they probably
9984 // wanted to index into an array, dereference a pointer, call a function, etc.
9985 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9986 unsigned DiagType = 0;
9987 if (ArgType->isFunctionType())
9988 DiagType = 1;
9989 else if (ArgType->isArrayType())
9990 DiagType = 2;
9991
9992 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9993 return;
9994 }
9995
9996 // std::abs has overloads which prevent most of the absolute value problems
9997 // from occurring.
9998 if (IsStdAbs)
9999 return;
10000
10001 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10002 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10003
10004 // The argument and parameter are the same kind. Check if they are the right
10005 // size.
10006 if (ArgValueKind == ParamValueKind) {
10007 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10008 return;
10009
10010 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10011 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10012 << FDecl << ArgType << ParamType;
10013
10014 if (NewAbsKind == 0)
10015 return;
10016
10017 emitReplacement(*this, Call->getExprLoc(),
10018 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10019 return;
10020 }
10021
10022 // ArgValueKind != ParamValueKind
10023 // The wrong type of absolute value function was used. Attempt to find the
10024 // proper one.
10025 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10026 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10027 if (NewAbsKind == 0)
10028 return;
10029
10030 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10031 << FDecl << ParamValueKind << ArgValueKind;
10032
10033 emitReplacement(*this, Call->getExprLoc(),
10034 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10035}
10036
10037//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10038void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10039 const FunctionDecl *FDecl) {
10040 if (!Call || !FDecl) return;
10041
10042 // Ignore template specializations and macros.
10043 if (inTemplateInstantiation()) return;
10044 if (Call->getExprLoc().isMacroID()) return;
10045
10046 // Only care about the one template argument, two function parameter std::max
10047 if (Call->getNumArgs() != 2) return;
10048 if (!IsStdFunction(FDecl, "max")) return;
10049 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10050 if (!ArgList) return;
10051 if (ArgList->size() != 1) return;
10052
10053 // Check that template type argument is unsigned integer.
10054 const auto& TA = ArgList->get(0);
10055 if (TA.getKind() != TemplateArgument::Type) return;
10056 QualType ArgType = TA.getAsType();
10057 if (!ArgType->isUnsignedIntegerType()) return;
10058
10059 // See if either argument is a literal zero.
10060 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10061 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10062 if (!MTE) return false;
10063 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10064 if (!Num) return false;
10065 if (Num->getValue() != 0) return false;
10066 return true;
10067 };
10068
10069 const Expr *FirstArg = Call->getArg(0);
10070 const Expr *SecondArg = Call->getArg(1);
10071 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10072 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10073
10074 // Only warn when exactly one argument is zero.
10075 if (IsFirstArgZero == IsSecondArgZero) return;
10076
10077 SourceRange FirstRange = FirstArg->getSourceRange();
10078 SourceRange SecondRange = SecondArg->getSourceRange();
10079
10080 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10081
10082 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10083 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10084
10085 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10086 SourceRange RemovalRange;
10087 if (IsFirstArgZero) {
10088 RemovalRange = SourceRange(FirstRange.getBegin(),
10089 SecondRange.getBegin().getLocWithOffset(-1));
10090 } else {
10091 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10092 SecondRange.getEnd());
10093 }
10094
10095 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10096 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10097 << FixItHint::CreateRemoval(RemovalRange);
10098}
10099
10100//===--- CHECK: Standard memory functions ---------------------------------===//
10101
10102/// Takes the expression passed to the size_t parameter of functions
10103/// such as memcmp, strncat, etc and warns if it's a comparison.
10104///
10105/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10107 const IdentifierInfo *FnName,
10108 SourceLocation FnLoc,
10109 SourceLocation RParenLoc) {
10110 const auto *Size = dyn_cast<BinaryOperator>(E);
10111 if (!Size)
10112 return false;
10113
10114 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10115 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10116 return false;
10117
10118 SourceRange SizeRange = Size->getSourceRange();
10119 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10120 << SizeRange << FnName;
10121 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10122 << FnName
10124 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10125 << FixItHint::CreateRemoval(RParenLoc);
10126 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10127 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10129 ")");
10130
10131 return true;
10132}
10133
10134/// Determine whether the given type is or contains a dynamic class type
10135/// (e.g., whether it has a vtable).
10137 bool &IsContained) {
10138 // Look through array types while ignoring qualifiers.
10139 const Type *Ty = T->getBaseElementTypeUnsafe();
10140 IsContained = false;
10141
10142 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10143 RD = RD ? RD->getDefinition() : nullptr;
10144 if (!RD || RD->isInvalidDecl())
10145 return nullptr;
10146
10147 if (RD->isDynamicClass())
10148 return RD;
10149
10150 // Check all the fields. If any bases were dynamic, the class is dynamic.
10151 // It's impossible for a class to transitively contain itself by value, so
10152 // infinite recursion is impossible.
10153 for (auto *FD : RD->fields()) {
10154 bool SubContained;
10155 if (const CXXRecordDecl *ContainedRD =
10156 getContainedDynamicClass(FD->getType(), SubContained)) {
10157 IsContained = true;
10158 return ContainedRD;
10159 }
10160 }
10161
10162 return nullptr;
10163}
10164
10166 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10167 if (Unary->getKind() == UETT_SizeOf)
10168 return Unary;
10169 return nullptr;
10170}
10171
10172/// If E is a sizeof expression, returns its argument expression,
10173/// otherwise returns NULL.
10174static const Expr *getSizeOfExprArg(const Expr *E) {
10176 if (!SizeOf->isArgumentType())
10177 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10178 return nullptr;
10179}
10180
10181/// If E is a sizeof expression, returns its argument type.
10184 return SizeOf->getTypeOfArgument();
10185 return QualType();
10186}
10187
10188namespace {
10189
10190struct SearchNonTrivialToInitializeField
10191 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10192 using Super =
10193 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10194
10195 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10196
10197 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10198 SourceLocation SL) {
10199 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10200 asDerived().visitArray(PDIK, AT, SL);
10201 return;
10202 }
10203
10204 Super::visitWithKind(PDIK, FT, SL);
10205 }
10206
10207 void visitARCStrong(QualType FT, SourceLocation SL) {
10208 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10209 }
10210 void visitARCWeak(QualType FT, SourceLocation SL) {
10211 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10212 }
10213 void visitStruct(QualType FT, SourceLocation SL) {
10214 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10215 visit(FD->getType(), FD->getLocation());
10216 }
10217 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10218 const ArrayType *AT, SourceLocation SL) {
10219 visit(getContext().getBaseElementType(AT), SL);
10220 }
10221 void visitTrivial(QualType FT, SourceLocation SL) {}
10222
10223 static void diag(QualType RT, const Expr *E, Sema &S) {
10224 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10225 }
10226
10227 ASTContext &getContext() { return S.getASTContext(); }
10228
10229 const Expr *E;
10230 Sema &S;
10231};
10232
10233struct SearchNonTrivialToCopyField
10234 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10235 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10236
10237 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10238
10239 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10240 SourceLocation SL) {
10241 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10242 asDerived().visitArray(PCK, AT, SL);
10243 return;
10244 }
10245
10246 Super::visitWithKind(PCK, FT, SL);
10247 }
10248
10249 void visitARCStrong(QualType FT, SourceLocation SL) {
10250 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10251 }
10252 void visitARCWeak(QualType FT, SourceLocation SL) {
10253 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10254 }
10255 void visitPtrAuth(QualType FT, SourceLocation SL) {
10256 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10257 }
10258 void visitStruct(QualType FT, SourceLocation SL) {
10259 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10260 visit(FD->getType(), FD->getLocation());
10261 }
10262 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10263 SourceLocation SL) {
10264 visit(getContext().getBaseElementType(AT), SL);
10265 }
10266 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10267 SourceLocation SL) {}
10268 void visitTrivial(QualType FT, SourceLocation SL) {}
10269 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10270
10271 static void diag(QualType RT, const Expr *E, Sema &S) {
10272 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10273 }
10274
10275 ASTContext &getContext() { return S.getASTContext(); }
10276
10277 const Expr *E;
10278 Sema &S;
10279};
10280
10281}
10282
10283/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10284static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10285 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10286
10287 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10288 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10289 return false;
10290
10291 return doesExprLikelyComputeSize(BO->getLHS()) ||
10292 doesExprLikelyComputeSize(BO->getRHS());
10293 }
10294
10295 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10296}
10297
10298/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10299///
10300/// \code
10301/// #define MACRO 0
10302/// foo(MACRO);
10303/// foo(0);
10304/// \endcode
10305///
10306/// This should return true for the first call to foo, but not for the second
10307/// (regardless of whether foo is a macro or function).
10309 SourceLocation CallLoc,
10310 SourceLocation ArgLoc) {
10311 if (!CallLoc.isMacroID())
10312 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10313
10314 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10315 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10316}
10317
10318/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10319/// last two arguments transposed.
10320static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10321 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10322 return;
10323
10324 const Expr *SizeArg =
10325 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10326
10327 auto isLiteralZero = [](const Expr *E) {
10328 return (isa<IntegerLiteral>(E) &&
10329 cast<IntegerLiteral>(E)->getValue() == 0) ||
10331 cast<CharacterLiteral>(E)->getValue() == 0);
10332 };
10333
10334 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10335 SourceLocation CallLoc = Call->getRParenLoc();
10337 if (isLiteralZero(SizeArg) &&
10338 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10339
10340 SourceLocation DiagLoc = SizeArg->getExprLoc();
10341
10342 // Some platforms #define bzero to __builtin_memset. See if this is the
10343 // case, and if so, emit a better diagnostic.
10344 if (BId == Builtin::BIbzero ||
10346 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10347 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10348 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10349 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10350 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10351 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10352 }
10353 return;
10354 }
10355
10356 // If the second argument to a memset is a sizeof expression and the third
10357 // isn't, this is also likely an error. This should catch
10358 // 'memset(buf, sizeof(buf), 0xff)'.
10359 if (BId == Builtin::BImemset &&
10360 doesExprLikelyComputeSize(Call->getArg(1)) &&
10361 !doesExprLikelyComputeSize(Call->getArg(2))) {
10362 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10363 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10364 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10365 return;
10366 }
10367}
10368
10369void Sema::CheckMemaccessArguments(const CallExpr *Call,
10370 unsigned BId,
10371 IdentifierInfo *FnName) {
10372 assert(BId != 0);
10373
10374 // It is possible to have a non-standard definition of memset. Validate
10375 // we have enough arguments, and if not, abort further checking.
10376 unsigned ExpectedNumArgs =
10377 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10378 if (Call->getNumArgs() < ExpectedNumArgs)
10379 return;
10380
10381 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10382 BId == Builtin::BIstrndup ? 1 : 2);
10383 unsigned LenArg =
10384 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10385 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10386
10387 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10388 Call->getBeginLoc(), Call->getRParenLoc()))
10389 return;
10390
10391 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10392 CheckMemaccessSize(*this, BId, Call);
10393
10394 // We have special checking when the length is a sizeof expression.
10395 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10396 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10397 llvm::FoldingSetNodeID SizeOfArgID;
10398
10399 // Although widely used, 'bzero' is not a standard function. Be more strict
10400 // with the argument types before allowing diagnostics and only allow the
10401 // form bzero(ptr, sizeof(...)).
10402 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10403 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10404 return;
10405
10406 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10407 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10408 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10409
10410 QualType DestTy = Dest->getType();
10411 QualType PointeeTy;
10412 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10413 PointeeTy = DestPtrTy->getPointeeType();
10414
10415 // Never warn about void type pointers. This can be used to suppress
10416 // false positives.
10417 if (PointeeTy->isVoidType())
10418 continue;
10419
10420 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10421 // actually comparing the expressions for equality. Because computing the
10422 // expression IDs can be expensive, we only do this if the diagnostic is
10423 // enabled.
10424 if (SizeOfArg &&
10425 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10426 SizeOfArg->getExprLoc())) {
10427 // We only compute IDs for expressions if the warning is enabled, and
10428 // cache the sizeof arg's ID.
10429 if (SizeOfArgID == llvm::FoldingSetNodeID())
10430 SizeOfArg->Profile(SizeOfArgID, Context, true);
10431 llvm::FoldingSetNodeID DestID;
10432 Dest->Profile(DestID, Context, true);
10433 if (DestID == SizeOfArgID) {
10434 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10435 // over sizeof(src) as well.
10436 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10437 StringRef ReadableName = FnName->getName();
10438
10439 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10440 if (UnaryOp->getOpcode() == UO_AddrOf)
10441 ActionIdx = 1; // If its an address-of operator, just remove it.
10442 if (!PointeeTy->isIncompleteType() &&
10443 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10444 ActionIdx = 2; // If the pointee's size is sizeof(char),
10445 // suggest an explicit length.
10446
10447 // If the function is defined as a builtin macro, do not show macro
10448 // expansion.
10449 SourceLocation SL = SizeOfArg->getExprLoc();
10450 SourceRange DSR = Dest->getSourceRange();
10451 SourceRange SSR = SizeOfArg->getSourceRange();
10452 SourceManager &SM = getSourceManager();
10453
10454 if (SM.isMacroArgExpansion(SL)) {
10455 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10456 SL = SM.getSpellingLoc(SL);
10457 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10458 SM.getSpellingLoc(DSR.getEnd()));
10459 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10460 SM.getSpellingLoc(SSR.getEnd()));
10461 }
10462
10463 DiagRuntimeBehavior(SL, SizeOfArg,
10464 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10465 << ReadableName
10466 << PointeeTy
10467 << DestTy
10468 << DSR
10469 << SSR);
10470 DiagRuntimeBehavior(SL, SizeOfArg,
10471 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10472 << ActionIdx
10473 << SSR);
10474
10475 break;
10476 }
10477 }
10478
10479 // Also check for cases where the sizeof argument is the exact same
10480 // type as the memory argument, and where it points to a user-defined
10481 // record type.
10482 if (SizeOfArgTy != QualType()) {
10483 if (PointeeTy->isRecordType() &&
10484 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10485 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10486 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10487 << FnName << SizeOfArgTy << ArgIdx
10488 << PointeeTy << Dest->getSourceRange()
10489 << LenExpr->getSourceRange());
10490 break;
10491 }
10492 }
10493 } else if (DestTy->isArrayType()) {
10494 PointeeTy = DestTy;
10495 }
10496
10497 if (PointeeTy == QualType())
10498 continue;
10499
10500 // Always complain about dynamic classes.
10501 bool IsContained;
10502 if (const CXXRecordDecl *ContainedRD =
10503 getContainedDynamicClass(PointeeTy, IsContained)) {
10504
10505 unsigned OperationType = 0;
10506 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10507 // "overwritten" if we're warning about the destination for any call
10508 // but memcmp; otherwise a verb appropriate to the call.
10509 if (ArgIdx != 0 || IsCmp) {
10510 if (BId == Builtin::BImemcpy)
10511 OperationType = 1;
10512 else if(BId == Builtin::BImemmove)
10513 OperationType = 2;
10514 else if (IsCmp)
10515 OperationType = 3;
10516 }
10517
10518 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10519 PDiag(diag::warn_dyn_class_memaccess)
10520 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10521 << IsContained << ContainedRD << OperationType
10522 << Call->getCallee()->getSourceRange());
10523 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10524 BId != Builtin::BImemset)
10526 Dest->getExprLoc(), Dest,
10527 PDiag(diag::warn_arc_object_memaccess)
10528 << ArgIdx << FnName << PointeeTy
10529 << Call->getCallee()->getSourceRange());
10530 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10531
10532 // FIXME: Do not consider incomplete types even though they may be
10533 // completed later. GCC does not diagnose such code, but we may want to
10534 // consider diagnosing it in the future, perhaps under a different, but
10535 // related, diagnostic group.
10536 bool NonTriviallyCopyableCXXRecord =
10537 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10538 !PointeeTy.isTriviallyCopyableType(Context);
10539
10540 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10542 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10543 PDiag(diag::warn_cstruct_memaccess)
10544 << ArgIdx << FnName << PointeeTy << 0);
10545 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10546 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10547 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10548 // FIXME: Limiting this warning to dest argument until we decide
10549 // whether it's valid for source argument too.
10550 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10551 PDiag(diag::warn_cxxstruct_memaccess)
10552 << FnName << PointeeTy);
10553 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10555 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10556 PDiag(diag::warn_cstruct_memaccess)
10557 << ArgIdx << FnName << PointeeTy << 1);
10558 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10559 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10560 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10561 // FIXME: Limiting this warning to dest argument until we decide
10562 // whether it's valid for source argument too.
10563 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10564 PDiag(diag::warn_cxxstruct_memaccess)
10565 << FnName << PointeeTy);
10566 } else {
10567 continue;
10568 }
10569 } else
10570 continue;
10571
10573 Dest->getExprLoc(), Dest,
10574 PDiag(diag::note_bad_memaccess_silence)
10575 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10576 break;
10577 }
10578}
10579
10580// A little helper routine: ignore addition and subtraction of integer literals.
10581// This intentionally does not ignore all integer constant expressions because
10582// we don't want to remove sizeof().
10583static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10584 Ex = Ex->IgnoreParenCasts();
10585
10586 while (true) {
10587 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10588 if (!BO || !BO->isAdditiveOp())
10589 break;
10590
10591 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10592 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10593
10594 if (isa<IntegerLiteral>(RHS))
10595 Ex = LHS;
10596 else if (isa<IntegerLiteral>(LHS))
10597 Ex = RHS;
10598 else
10599 break;
10600 }
10601
10602 return Ex;
10603}
10604
10606 ASTContext &Context) {
10607 // Only handle constant-sized or VLAs, but not flexible members.
10608 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10609 // Only issue the FIXIT for arrays of size > 1.
10610 if (CAT->getZExtSize() <= 1)
10611 return false;
10612 } else if (!Ty->isVariableArrayType()) {
10613 return false;
10614 }
10615 return true;
10616}
10617
10618void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10619 IdentifierInfo *FnName) {
10620
10621 // Don't crash if the user has the wrong number of arguments
10622 unsigned NumArgs = Call->getNumArgs();
10623 if ((NumArgs != 3) && (NumArgs != 4))
10624 return;
10625
10626 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10627 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10628 const Expr *CompareWithSrc = nullptr;
10629
10630 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10631 Call->getBeginLoc(), Call->getRParenLoc()))
10632 return;
10633
10634 // Look for 'strlcpy(dst, x, sizeof(x))'
10635 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10636 CompareWithSrc = Ex;
10637 else {
10638 // Look for 'strlcpy(dst, x, strlen(x))'
10639 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10640 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10641 SizeCall->getNumArgs() == 1)
10642 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10643 }
10644 }
10645
10646 if (!CompareWithSrc)
10647 return;
10648
10649 // Determine if the argument to sizeof/strlen is equal to the source
10650 // argument. In principle there's all kinds of things you could do
10651 // here, for instance creating an == expression and evaluating it with
10652 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10653 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10654 if (!SrcArgDRE)
10655 return;
10656
10657 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10658 if (!CompareWithSrcDRE ||
10659 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10660 return;
10661
10662 const Expr *OriginalSizeArg = Call->getArg(2);
10663 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10664 << OriginalSizeArg->getSourceRange() << FnName;
10665
10666 // Output a FIXIT hint if the destination is an array (rather than a
10667 // pointer to an array). This could be enhanced to handle some
10668 // pointers if we know the actual size, like if DstArg is 'array+2'
10669 // we could say 'sizeof(array)-2'.
10670 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10672 return;
10673
10674 SmallString<128> sizeString;
10675 llvm::raw_svector_ostream OS(sizeString);
10676 OS << "sizeof(";
10677 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10678 OS << ")";
10679
10680 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10681 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10682 OS.str());
10683}
10684
10685/// Check if two expressions refer to the same declaration.
10686static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10687 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10688 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10689 return D1->getDecl() == D2->getDecl();
10690 return false;
10691}
10692
10693static const Expr *getStrlenExprArg(const Expr *E) {
10694 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10695 const FunctionDecl *FD = CE->getDirectCallee();
10696 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10697 return nullptr;
10698 return CE->getArg(0)->IgnoreParenCasts();
10699 }
10700 return nullptr;
10701}
10702
10703void Sema::CheckStrncatArguments(const CallExpr *CE,
10704 const IdentifierInfo *FnName) {
10705 // Don't crash if the user has the wrong number of arguments.
10706 if (CE->getNumArgs() < 3)
10707 return;
10708 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10709 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10710 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10711
10712 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10713 CE->getRParenLoc()))
10714 return;
10715
10716 // Identify common expressions, which are wrongly used as the size argument
10717 // to strncat and may lead to buffer overflows.
10718 unsigned PatternType = 0;
10719 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10720 // - sizeof(dst)
10721 if (referToTheSameDecl(SizeOfArg, DstArg))
10722 PatternType = 1;
10723 // - sizeof(src)
10724 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10725 PatternType = 2;
10726 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10727 if (BE->getOpcode() == BO_Sub) {
10728 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10729 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10730 // - sizeof(dst) - strlen(dst)
10731 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10733 PatternType = 1;
10734 // - sizeof(src) - (anything)
10735 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10736 PatternType = 2;
10737 }
10738 }
10739
10740 if (PatternType == 0)
10741 return;
10742
10743 // Generate the diagnostic.
10744 SourceLocation SL = LenArg->getBeginLoc();
10745 SourceRange SR = LenArg->getSourceRange();
10746 SourceManager &SM = getSourceManager();
10747
10748 // If the function is defined as a builtin macro, do not show macro expansion.
10749 if (SM.isMacroArgExpansion(SL)) {
10750 SL = SM.getSpellingLoc(SL);
10751 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10752 SM.getSpellingLoc(SR.getEnd()));
10753 }
10754
10755 // Check if the destination is an array (rather than a pointer to an array).
10756 QualType DstTy = DstArg->getType();
10757 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10758 Context);
10759 if (!isKnownSizeArray) {
10760 if (PatternType == 1)
10761 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10762 else
10763 Diag(SL, diag::warn_strncat_src_size) << SR;
10764 return;
10765 }
10766
10767 if (PatternType == 1)
10768 Diag(SL, diag::warn_strncat_large_size) << SR;
10769 else
10770 Diag(SL, diag::warn_strncat_src_size) << SR;
10771
10772 SmallString<128> sizeString;
10773 llvm::raw_svector_ostream OS(sizeString);
10774 OS << "sizeof(";
10775 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10776 OS << ") - ";
10777 OS << "strlen(";
10778 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10779 OS << ") - 1";
10780
10781 Diag(SL, diag::note_strncat_wrong_size)
10782 << FixItHint::CreateReplacement(SR, OS.str());
10783}
10784
10785namespace {
10786void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10787 const UnaryOperator *UnaryExpr, const Decl *D) {
10789 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10790 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10791 return;
10792 }
10793}
10794
10795void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10796 const UnaryOperator *UnaryExpr) {
10797 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10798 const Decl *D = Lvalue->getDecl();
10799 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10800 if (!DD->getType()->isReferenceType())
10801 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10802 }
10803 }
10804
10805 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10806 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10807 Lvalue->getMemberDecl());
10808}
10809
10810void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10811 const UnaryOperator *UnaryExpr) {
10812 const auto *Lambda = dyn_cast<LambdaExpr>(
10814 if (!Lambda)
10815 return;
10816
10817 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10818 << CalleeName << 2 /*object: lambda expression*/;
10819}
10820
10821void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10822 const DeclRefExpr *Lvalue) {
10823 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10824 if (Var == nullptr)
10825 return;
10826
10827 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10828 << CalleeName << 0 /*object: */ << Var;
10829}
10830
10831void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10832 const CastExpr *Cast) {
10833 SmallString<128> SizeString;
10834 llvm::raw_svector_ostream OS(SizeString);
10835
10836 clang::CastKind Kind = Cast->getCastKind();
10837 if (Kind == clang::CK_BitCast &&
10838 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10839 return;
10840 if (Kind == clang::CK_IntegralToPointer &&
10842 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10843 return;
10844
10845 switch (Cast->getCastKind()) {
10846 case clang::CK_BitCast:
10847 case clang::CK_IntegralToPointer:
10848 case clang::CK_FunctionToPointerDecay:
10849 OS << '\'';
10850 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10851 OS << '\'';
10852 break;
10853 default:
10854 return;
10855 }
10856
10857 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10858 << CalleeName << 0 /*object: */ << OS.str();
10859}
10860} // namespace
10861
10862void Sema::CheckFreeArguments(const CallExpr *E) {
10863 const std::string CalleeName =
10864 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10865
10866 { // Prefer something that doesn't involve a cast to make things simpler.
10867 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10868 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10869 switch (UnaryExpr->getOpcode()) {
10870 case UnaryOperator::Opcode::UO_AddrOf:
10871 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10872 case UnaryOperator::Opcode::UO_Plus:
10873 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10874 default:
10875 break;
10876 }
10877
10878 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10879 if (Lvalue->getType()->isArrayType())
10880 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10881
10882 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10883 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10884 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10885 return;
10886 }
10887
10888 if (isa<BlockExpr>(Arg)) {
10889 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10890 << CalleeName << 1 /*object: block*/;
10891 return;
10892 }
10893 }
10894 // Maybe the cast was important, check after the other cases.
10895 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10896 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10897}
10898
10899void
10900Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10901 SourceLocation ReturnLoc,
10902 bool isObjCMethod,
10903 const AttrVec *Attrs,
10904 const FunctionDecl *FD) {
10905 // Check if the return value is null but should not be.
10906 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10907 (!isObjCMethod && isNonNullType(lhsType))) &&
10908 CheckNonNullExpr(*this, RetValExp))
10909 Diag(ReturnLoc, diag::warn_null_ret)
10910 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10911
10912 // C++11 [basic.stc.dynamic.allocation]p4:
10913 // If an allocation function declared with a non-throwing
10914 // exception-specification fails to allocate storage, it shall return
10915 // a null pointer. Any other allocation function that fails to allocate
10916 // storage shall indicate failure only by throwing an exception [...]
10917 if (FD) {
10919 if (Op == OO_New || Op == OO_Array_New) {
10920 const FunctionProtoType *Proto
10921 = FD->getType()->castAs<FunctionProtoType>();
10922 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10923 CheckNonNullExpr(*this, RetValExp))
10924 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10925 << FD << getLangOpts().CPlusPlus11;
10926 }
10927 }
10928
10929 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10930 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10931 }
10932
10933 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10934 // here prevent the user from using a PPC MMA type as trailing return type.
10935 if (Context.getTargetInfo().getTriple().isPPC64())
10936 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10937}
10938
10940 const Expr *RHS, BinaryOperatorKind Opcode) {
10941 if (!BinaryOperator::isEqualityOp(Opcode))
10942 return;
10943
10944 // Match and capture subexpressions such as "(float) X == 0.1".
10945 const FloatingLiteral *FPLiteral;
10946 const CastExpr *FPCast;
10947 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10948 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10949 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10950 return FPLiteral && FPCast;
10951 };
10952
10953 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10954 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10955 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10956 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10957 TargetTy->isFloatingPoint()) {
10958 bool Lossy;
10959 llvm::APFloat TargetC = FPLiteral->getValue();
10960 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10961 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10962 if (Lossy) {
10963 // If the literal cannot be represented in the source type, then a
10964 // check for == is always false and check for != is always true.
10965 Diag(Loc, diag::warn_float_compare_literal)
10966 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10967 << LHS->getSourceRange() << RHS->getSourceRange();
10968 return;
10969 }
10970 }
10971 }
10972
10973 // Match a more general floating-point equality comparison (-Wfloat-equal).
10974 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10975 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10976
10977 // Special case: check for x == x (which is OK).
10978 // Do not emit warnings for such cases.
10979 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10980 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10981 if (DRL->getDecl() == DRR->getDecl())
10982 return;
10983
10984 // Special case: check for comparisons against literals that can be exactly
10985 // represented by APFloat. In such cases, do not emit a warning. This
10986 // is a heuristic: often comparison against such literals are used to
10987 // detect if a value in a variable has not changed. This clearly can
10988 // lead to false negatives.
10989 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10990 if (FLL->isExact())
10991 return;
10992 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10993 if (FLR->isExact())
10994 return;
10995
10996 // Check for comparisons with builtin types.
10997 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10998 CL && CL->getBuiltinCallee())
10999 return;
11000
11001 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11002 CR && CR->getBuiltinCallee())
11003 return;
11004
11005 // Emit the diagnostic.
11006 Diag(Loc, diag::warn_floatingpoint_eq)
11007 << LHS->getSourceRange() << RHS->getSourceRange();
11008}
11009
11010//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11011//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11012
11013namespace {
11014
11015/// Structure recording the 'active' range of an integer-valued
11016/// expression.
11017struct IntRange {
11018 /// The number of bits active in the int. Note that this includes exactly one
11019 /// sign bit if !NonNegative.
11020 unsigned Width;
11021
11022 /// True if the int is known not to have negative values. If so, all leading
11023 /// bits before Width are known zero, otherwise they are known to be the
11024 /// same as the MSB within Width.
11025 bool NonNegative;
11026
11027 IntRange(unsigned Width, bool NonNegative)
11028 : Width(Width), NonNegative(NonNegative) {}
11029
11030 /// Number of bits excluding the sign bit.
11031 unsigned valueBits() const {
11032 return NonNegative ? Width : Width - 1;
11033 }
11034
11035 /// Returns the range of the bool type.
11036 static IntRange forBoolType() {
11037 return IntRange(1, true);
11038 }
11039
11040 /// Returns the range of an opaque value of the given integral type.
11041 static IntRange forValueOfType(ASTContext &C, QualType T) {
11042 return forValueOfCanonicalType(C,
11044 }
11045
11046 /// Returns the range of an opaque value of a canonical integral type.
11047 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11048 assert(T->isCanonicalUnqualified());
11049
11050 if (const auto *VT = dyn_cast<VectorType>(T))
11051 T = VT->getElementType().getTypePtr();
11052 if (const auto *CT = dyn_cast<ComplexType>(T))
11053 T = CT->getElementType().getTypePtr();
11054 if (const auto *AT = dyn_cast<AtomicType>(T))
11055 T = AT->getValueType().getTypePtr();
11056
11057 if (!C.getLangOpts().CPlusPlus) {
11058 // For enum types in C code, use the underlying datatype.
11059 if (const auto *ED = T->getAsEnumDecl())
11060 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11061 } else if (auto *Enum = T->getAsEnumDecl()) {
11062 // For enum types in C++, use the known bit width of the enumerators.
11063 // In C++11, enums can have a fixed underlying type. Use this type to
11064 // compute the range.
11065 if (Enum->isFixed()) {
11066 return IntRange(C.getIntWidth(QualType(T, 0)),
11067 !Enum->getIntegerType()->isSignedIntegerType());
11068 }
11069
11070 unsigned NumPositive = Enum->getNumPositiveBits();
11071 unsigned NumNegative = Enum->getNumNegativeBits();
11072
11073 if (NumNegative == 0)
11074 return IntRange(NumPositive, true/*NonNegative*/);
11075 else
11076 return IntRange(std::max(NumPositive + 1, NumNegative),
11077 false/*NonNegative*/);
11078 }
11079
11080 if (const auto *EIT = dyn_cast<BitIntType>(T))
11081 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11082
11083 const BuiltinType *BT = cast<BuiltinType>(T);
11084 assert(BT->isInteger());
11085
11086 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11087 }
11088
11089 /// Returns the "target" range of a canonical integral type, i.e.
11090 /// the range of values expressible in the type.
11091 ///
11092 /// This matches forValueOfCanonicalType except that enums have the
11093 /// full range of their type, not the range of their enumerators.
11094 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11095 assert(T->isCanonicalUnqualified());
11096
11097 if (const VectorType *VT = dyn_cast<VectorType>(T))
11098 T = VT->getElementType().getTypePtr();
11099 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11100 T = CT->getElementType().getTypePtr();
11101 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11102 T = AT->getValueType().getTypePtr();
11103 if (const auto *ED = T->getAsEnumDecl())
11104 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11105
11106 if (const auto *EIT = dyn_cast<BitIntType>(T))
11107 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11108
11109 const BuiltinType *BT = cast<BuiltinType>(T);
11110 assert(BT->isInteger());
11111
11112 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11113 }
11114
11115 /// Returns the supremum of two ranges: i.e. their conservative merge.
11116 static IntRange join(IntRange L, IntRange R) {
11117 bool Unsigned = L.NonNegative && R.NonNegative;
11118 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11119 L.NonNegative && R.NonNegative);
11120 }
11121
11122 /// Return the range of a bitwise-AND of the two ranges.
11123 static IntRange bit_and(IntRange L, IntRange R) {
11124 unsigned Bits = std::max(L.Width, R.Width);
11125 bool NonNegative = false;
11126 if (L.NonNegative) {
11127 Bits = std::min(Bits, L.Width);
11128 NonNegative = true;
11129 }
11130 if (R.NonNegative) {
11131 Bits = std::min(Bits, R.Width);
11132 NonNegative = true;
11133 }
11134 return IntRange(Bits, NonNegative);
11135 }
11136
11137 /// Return the range of a sum of the two ranges.
11138 static IntRange sum(IntRange L, IntRange R) {
11139 bool Unsigned = L.NonNegative && R.NonNegative;
11140 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11141 Unsigned);
11142 }
11143
11144 /// Return the range of a difference of the two ranges.
11145 static IntRange difference(IntRange L, IntRange R) {
11146 // We need a 1-bit-wider range if:
11147 // 1) LHS can be negative: least value can be reduced.
11148 // 2) RHS can be negative: greatest value can be increased.
11149 bool CanWiden = !L.NonNegative || !R.NonNegative;
11150 bool Unsigned = L.NonNegative && R.Width == 0;
11151 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11152 !Unsigned,
11153 Unsigned);
11154 }
11155
11156 /// Return the range of a product of the two ranges.
11157 static IntRange product(IntRange L, IntRange R) {
11158 // If both LHS and RHS can be negative, we can form
11159 // -2^L * -2^R = 2^(L + R)
11160 // which requires L + R + 1 value bits to represent.
11161 bool CanWiden = !L.NonNegative && !R.NonNegative;
11162 bool Unsigned = L.NonNegative && R.NonNegative;
11163 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11164 Unsigned);
11165 }
11166
11167 /// Return the range of a remainder operation between the two ranges.
11168 static IntRange rem(IntRange L, IntRange R) {
11169 // The result of a remainder can't be larger than the result of
11170 // either side. The sign of the result is the sign of the LHS.
11171 bool Unsigned = L.NonNegative;
11172 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11173 Unsigned);
11174 }
11175};
11176
11177} // namespace
11178
11179static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11180 if (value.isSigned() && value.isNegative())
11181 return IntRange(value.getSignificantBits(), false);
11182
11183 if (value.getBitWidth() > MaxWidth)
11184 value = value.trunc(MaxWidth);
11185
11186 // isNonNegative() just checks the sign bit without considering
11187 // signedness.
11188 return IntRange(value.getActiveBits(), true);
11189}
11190
11191static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11192 if (result.isInt())
11193 return GetValueRange(result.getInt(), MaxWidth);
11194
11195 if (result.isVector()) {
11196 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11197 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11198 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11199 R = IntRange::join(R, El);
11200 }
11201 return R;
11202 }
11203
11204 if (result.isComplexInt()) {
11205 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11206 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11207 return IntRange::join(R, I);
11208 }
11209
11210 // This can happen with lossless casts to intptr_t of "based" lvalues.
11211 // Assume it might use arbitrary bits.
11212 // FIXME: The only reason we need to pass the type in here is to get
11213 // the sign right on this one case. It would be nice if APValue
11214 // preserved this.
11215 assert(result.isLValue() || result.isAddrLabelDiff());
11216 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11217}
11218
11219static QualType GetExprType(const Expr *E) {
11220 QualType Ty = E->getType();
11221 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11222 Ty = AtomicRHS->getValueType();
11223 return Ty;
11224}
11225
11226/// Attempts to estimate an approximate range for the given integer expression.
11227/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11228/// reliable estimation cannot be determined.
11229///
11230/// \param MaxWidth The width to which the value will be truncated.
11231/// \param InConstantContext If \c true, interpret the expression within a
11232/// constant context.
11233/// \param Approximate If \c true, provide a likely range of values by assuming
11234/// that arithmetic on narrower types remains within those types.
11235/// If \c false, return a range that includes all possible values
11236/// resulting from the expression.
11237/// \returns A range of values that the expression might take, or
11238/// std::nullopt if a reliable estimation cannot be determined.
11239static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11240 unsigned MaxWidth,
11241 bool InConstantContext,
11242 bool Approximate) {
11243 E = E->IgnoreParens();
11244
11245 // Try a full evaluation first.
11246 Expr::EvalResult result;
11247 if (E->EvaluateAsRValue(result, C, InConstantContext))
11248 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11249
11250 // I think we only want to look through implicit casts here; if the
11251 // user has an explicit widening cast, we should treat the value as
11252 // being of the new, wider type.
11253 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11254 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11255 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11256 Approximate);
11257
11258 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11259
11260 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11261 CE->getCastKind() == CK_BooleanToSignedIntegral;
11262
11263 // Assume that non-integer casts can span the full range of the type.
11264 if (!isIntegerCast)
11265 return OutputTypeRange;
11266
11267 std::optional<IntRange> SubRange = TryGetExprRange(
11268 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11269 InConstantContext, Approximate);
11270 if (!SubRange)
11271 return std::nullopt;
11272
11273 // Bail out if the subexpr's range is as wide as the cast type.
11274 if (SubRange->Width >= OutputTypeRange.Width)
11275 return OutputTypeRange;
11276
11277 // Otherwise, we take the smaller width, and we're non-negative if
11278 // either the output type or the subexpr is.
11279 return IntRange(SubRange->Width,
11280 SubRange->NonNegative || OutputTypeRange.NonNegative);
11281 }
11282
11283 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11284 // If we can fold the condition, just take that operand.
11285 bool CondResult;
11286 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11287 return TryGetExprRange(
11288 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11289 InConstantContext, Approximate);
11290
11291 // Otherwise, conservatively merge.
11292 // TryGetExprRange requires an integer expression, but a throw expression
11293 // results in a void type.
11294 Expr *TrueExpr = CO->getTrueExpr();
11295 if (TrueExpr->getType()->isVoidType())
11296 return std::nullopt;
11297
11298 std::optional<IntRange> L =
11299 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11300 if (!L)
11301 return std::nullopt;
11302
11303 Expr *FalseExpr = CO->getFalseExpr();
11304 if (FalseExpr->getType()->isVoidType())
11305 return std::nullopt;
11306
11307 std::optional<IntRange> R =
11308 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11309 if (!R)
11310 return std::nullopt;
11311
11312 return IntRange::join(*L, *R);
11313 }
11314
11315 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11316 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11317
11318 switch (BO->getOpcode()) {
11319 case BO_Cmp:
11320 llvm_unreachable("builtin <=> should have class type");
11321
11322 // Boolean-valued operations are single-bit and positive.
11323 case BO_LAnd:
11324 case BO_LOr:
11325 case BO_LT:
11326 case BO_GT:
11327 case BO_LE:
11328 case BO_GE:
11329 case BO_EQ:
11330 case BO_NE:
11331 return IntRange::forBoolType();
11332
11333 // The type of the assignments is the type of the LHS, so the RHS
11334 // is not necessarily the same type.
11335 case BO_MulAssign:
11336 case BO_DivAssign:
11337 case BO_RemAssign:
11338 case BO_AddAssign:
11339 case BO_SubAssign:
11340 case BO_XorAssign:
11341 case BO_OrAssign:
11342 // TODO: bitfields?
11343 return IntRange::forValueOfType(C, GetExprType(E));
11344
11345 // Simple assignments just pass through the RHS, which will have
11346 // been coerced to the LHS type.
11347 case BO_Assign:
11348 // TODO: bitfields?
11349 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11350 Approximate);
11351
11352 // Operations with opaque sources are black-listed.
11353 case BO_PtrMemD:
11354 case BO_PtrMemI:
11355 return IntRange::forValueOfType(C, GetExprType(E));
11356
11357 // Bitwise-and uses the *infinum* of the two source ranges.
11358 case BO_And:
11359 case BO_AndAssign:
11360 Combine = IntRange::bit_and;
11361 break;
11362
11363 // Left shift gets black-listed based on a judgement call.
11364 case BO_Shl:
11365 // ...except that we want to treat '1 << (blah)' as logically
11366 // positive. It's an important idiom.
11367 if (IntegerLiteral *I
11368 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11369 if (I->getValue() == 1) {
11370 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11371 return IntRange(R.Width, /*NonNegative*/ true);
11372 }
11373 }
11374 [[fallthrough]];
11375
11376 case BO_ShlAssign:
11377 return IntRange::forValueOfType(C, GetExprType(E));
11378
11379 // Right shift by a constant can narrow its left argument.
11380 case BO_Shr:
11381 case BO_ShrAssign: {
11382 std::optional<IntRange> L = TryGetExprRange(
11383 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11384 if (!L)
11385 return std::nullopt;
11386
11387 // If the shift amount is a positive constant, drop the width by
11388 // that much.
11389 if (std::optional<llvm::APSInt> shift =
11390 BO->getRHS()->getIntegerConstantExpr(C)) {
11391 if (shift->isNonNegative()) {
11392 if (shift->uge(L->Width))
11393 L->Width = (L->NonNegative ? 0 : 1);
11394 else
11395 L->Width -= shift->getZExtValue();
11396 }
11397 }
11398
11399 return L;
11400 }
11401
11402 // Comma acts as its right operand.
11403 case BO_Comma:
11404 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11405 Approximate);
11406
11407 case BO_Add:
11408 if (!Approximate)
11409 Combine = IntRange::sum;
11410 break;
11411
11412 case BO_Sub:
11413 if (BO->getLHS()->getType()->isPointerType())
11414 return IntRange::forValueOfType(C, GetExprType(E));
11415 if (!Approximate)
11416 Combine = IntRange::difference;
11417 break;
11418
11419 case BO_Mul:
11420 if (!Approximate)
11421 Combine = IntRange::product;
11422 break;
11423
11424 // The width of a division result is mostly determined by the size
11425 // of the LHS.
11426 case BO_Div: {
11427 // Don't 'pre-truncate' the operands.
11428 unsigned opWidth = C.getIntWidth(GetExprType(E));
11429 std::optional<IntRange> L = TryGetExprRange(
11430 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11431 if (!L)
11432 return std::nullopt;
11433
11434 // If the divisor is constant, use that.
11435 if (std::optional<llvm::APSInt> divisor =
11436 BO->getRHS()->getIntegerConstantExpr(C)) {
11437 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11438 if (log2 >= L->Width)
11439 L->Width = (L->NonNegative ? 0 : 1);
11440 else
11441 L->Width = std::min(L->Width - log2, MaxWidth);
11442 return L;
11443 }
11444
11445 // Otherwise, just use the LHS's width.
11446 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11447 // could be -1.
11448 std::optional<IntRange> R = TryGetExprRange(
11449 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11450 if (!R)
11451 return std::nullopt;
11452
11453 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11454 }
11455
11456 case BO_Rem:
11457 Combine = IntRange::rem;
11458 break;
11459
11460 // The default behavior is okay for these.
11461 case BO_Xor:
11462 case BO_Or:
11463 break;
11464 }
11465
11466 // Combine the two ranges, but limit the result to the type in which we
11467 // performed the computation.
11468 QualType T = GetExprType(E);
11469 unsigned opWidth = C.getIntWidth(T);
11470 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11471 InConstantContext, Approximate);
11472 if (!L)
11473 return std::nullopt;
11474
11475 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11476 InConstantContext, Approximate);
11477 if (!R)
11478 return std::nullopt;
11479
11480 IntRange C = Combine(*L, *R);
11481 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11482 C.Width = std::min(C.Width, MaxWidth);
11483 return C;
11484 }
11485
11486 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11487 switch (UO->getOpcode()) {
11488 // Boolean-valued operations are white-listed.
11489 case UO_LNot:
11490 return IntRange::forBoolType();
11491
11492 // Operations with opaque sources are black-listed.
11493 case UO_Deref:
11494 case UO_AddrOf: // should be impossible
11495 return IntRange::forValueOfType(C, GetExprType(E));
11496
11497 case UO_Minus: {
11498 if (E->getType()->isUnsignedIntegerType()) {
11499 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11500 Approximate);
11501 }
11502
11503 std::optional<IntRange> SubRange = TryGetExprRange(
11504 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11505
11506 if (!SubRange)
11507 return std::nullopt;
11508
11509 // If the range was previously non-negative, we need an extra bit for the
11510 // sign bit. Otherwise, we need an extra bit because the negation of the
11511 // most-negative value is one bit wider than that value.
11512 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11513 }
11514
11515 case UO_Not: {
11516 if (E->getType()->isUnsignedIntegerType()) {
11517 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11518 Approximate);
11519 }
11520
11521 std::optional<IntRange> SubRange = TryGetExprRange(
11522 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11523
11524 if (!SubRange)
11525 return std::nullopt;
11526
11527 // The width increments by 1 if the sub-expression cannot be negative
11528 // since it now can be.
11529 return IntRange(
11530 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11531 false);
11532 }
11533
11534 default:
11535 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11536 Approximate);
11537 }
11538 }
11539
11540 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11541 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11542 Approximate);
11543
11544 if (const auto *BitField = E->getSourceBitField())
11545 return IntRange(BitField->getBitWidthValue(),
11546 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11547
11548 if (GetExprType(E)->isVoidType())
11549 return std::nullopt;
11550
11551 return IntRange::forValueOfType(C, GetExprType(E));
11552}
11553
11554static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11555 bool InConstantContext,
11556 bool Approximate) {
11557 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11558 Approximate);
11559}
11560
11561/// Checks whether the given value, which currently has the given
11562/// source semantics, has the same value when coerced through the
11563/// target semantics.
11564static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11565 const llvm::fltSemantics &Src,
11566 const llvm::fltSemantics &Tgt) {
11567 llvm::APFloat truncated = value;
11568
11569 bool ignored;
11570 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11571 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11572
11573 return truncated.bitwiseIsEqual(value);
11574}
11575
11576/// Checks whether the given value, which currently has the given
11577/// source semantics, has the same value when coerced through the
11578/// target semantics.
11579///
11580/// The value might be a vector of floats (or a complex number).
11581static bool IsSameFloatAfterCast(const APValue &value,
11582 const llvm::fltSemantics &Src,
11583 const llvm::fltSemantics &Tgt) {
11584 if (value.isFloat())
11585 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11586
11587 if (value.isVector()) {
11588 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11589 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11590 return false;
11591 return true;
11592 }
11593
11594 assert(value.isComplexFloat());
11595 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11596 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11597}
11598
11599static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11600 bool IsListInit = false);
11601
11602static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11603 // Suppress cases where we are comparing against an enum constant.
11604 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11605 if (isa<EnumConstantDecl>(DR->getDecl()))
11606 return true;
11607
11608 // Suppress cases where the value is expanded from a macro, unless that macro
11609 // is how a language represents a boolean literal. This is the case in both C
11610 // and Objective-C.
11611 SourceLocation BeginLoc = E->getBeginLoc();
11612 if (BeginLoc.isMacroID()) {
11613 StringRef MacroName = Lexer::getImmediateMacroName(
11614 BeginLoc, S.getSourceManager(), S.getLangOpts());
11615 return MacroName != "YES" && MacroName != "NO" &&
11616 MacroName != "true" && MacroName != "false";
11617 }
11618
11619 return false;
11620}
11621
11622static bool isKnownToHaveUnsignedValue(const Expr *E) {
11623 return E->getType()->isIntegerType() &&
11624 (!E->getType()->isSignedIntegerType() ||
11626}
11627
11628namespace {
11629/// The promoted range of values of a type. In general this has the
11630/// following structure:
11631///
11632/// |-----------| . . . |-----------|
11633/// ^ ^ ^ ^
11634/// Min HoleMin HoleMax Max
11635///
11636/// ... where there is only a hole if a signed type is promoted to unsigned
11637/// (in which case Min and Max are the smallest and largest representable
11638/// values).
11639struct PromotedRange {
11640 // Min, or HoleMax if there is a hole.
11641 llvm::APSInt PromotedMin;
11642 // Max, or HoleMin if there is a hole.
11643 llvm::APSInt PromotedMax;
11644
11645 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11646 if (R.Width == 0)
11647 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11648 else if (R.Width >= BitWidth && !Unsigned) {
11649 // Promotion made the type *narrower*. This happens when promoting
11650 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11651 // Treat all values of 'signed int' as being in range for now.
11652 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11653 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11654 } else {
11655 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11656 .extOrTrunc(BitWidth);
11657 PromotedMin.setIsUnsigned(Unsigned);
11658
11659 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11660 .extOrTrunc(BitWidth);
11661 PromotedMax.setIsUnsigned(Unsigned);
11662 }
11663 }
11664
11665 // Determine whether this range is contiguous (has no hole).
11666 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11667
11668 // Where a constant value is within the range.
11669 enum ComparisonResult {
11670 LT = 0x1,
11671 LE = 0x2,
11672 GT = 0x4,
11673 GE = 0x8,
11674 EQ = 0x10,
11675 NE = 0x20,
11676 InRangeFlag = 0x40,
11677
11678 Less = LE | LT | NE,
11679 Min = LE | InRangeFlag,
11680 InRange = InRangeFlag,
11681 Max = GE | InRangeFlag,
11682 Greater = GE | GT | NE,
11683
11684 OnlyValue = LE | GE | EQ | InRangeFlag,
11685 InHole = NE
11686 };
11687
11688 ComparisonResult compare(const llvm::APSInt &Value) const {
11689 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11690 Value.isUnsigned() == PromotedMin.isUnsigned());
11691 if (!isContiguous()) {
11692 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11693 if (Value.isMinValue()) return Min;
11694 if (Value.isMaxValue()) return Max;
11695 if (Value >= PromotedMin) return InRange;
11696 if (Value <= PromotedMax) return InRange;
11697 return InHole;
11698 }
11699
11700 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11701 case -1: return Less;
11702 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11703 case 1:
11704 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11705 case -1: return InRange;
11706 case 0: return Max;
11707 case 1: return Greater;
11708 }
11709 }
11710
11711 llvm_unreachable("impossible compare result");
11712 }
11713
11714 static std::optional<StringRef>
11715 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11716 if (Op == BO_Cmp) {
11717 ComparisonResult LTFlag = LT, GTFlag = GT;
11718 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11719
11720 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11721 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11722 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11723 return std::nullopt;
11724 }
11725
11726 ComparisonResult TrueFlag, FalseFlag;
11727 if (Op == BO_EQ) {
11728 TrueFlag = EQ;
11729 FalseFlag = NE;
11730 } else if (Op == BO_NE) {
11731 TrueFlag = NE;
11732 FalseFlag = EQ;
11733 } else {
11734 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11735 TrueFlag = LT;
11736 FalseFlag = GE;
11737 } else {
11738 TrueFlag = GT;
11739 FalseFlag = LE;
11740 }
11741 if (Op == BO_GE || Op == BO_LE)
11742 std::swap(TrueFlag, FalseFlag);
11743 }
11744 if (R & TrueFlag)
11745 return StringRef("true");
11746 if (R & FalseFlag)
11747 return StringRef("false");
11748 return std::nullopt;
11749 }
11750};
11751}
11752
11753static bool HasEnumType(const Expr *E) {
11754 // Strip off implicit integral promotions.
11755 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11756 if (ICE->getCastKind() != CK_IntegralCast &&
11757 ICE->getCastKind() != CK_NoOp)
11758 break;
11759 E = ICE->getSubExpr();
11760 }
11761
11762 return E->getType()->isEnumeralType();
11763}
11764
11765static int classifyConstantValue(Expr *Constant) {
11766 // The values of this enumeration are used in the diagnostics
11767 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11768 enum ConstantValueKind {
11769 Miscellaneous = 0,
11770 LiteralTrue,
11771 LiteralFalse
11772 };
11773 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11774 return BL->getValue() ? ConstantValueKind::LiteralTrue
11775 : ConstantValueKind::LiteralFalse;
11776 return ConstantValueKind::Miscellaneous;
11777}
11778
11780 Expr *Constant, Expr *Other,
11781 const llvm::APSInt &Value,
11782 bool RhsConstant) {
11784 return false;
11785
11786 Expr *OriginalOther = Other;
11787
11788 Constant = Constant->IgnoreParenImpCasts();
11789 Other = Other->IgnoreParenImpCasts();
11790
11791 // Suppress warnings on tautological comparisons between values of the same
11792 // enumeration type. There are only two ways we could warn on this:
11793 // - If the constant is outside the range of representable values of
11794 // the enumeration. In such a case, we should warn about the cast
11795 // to enumeration type, not about the comparison.
11796 // - If the constant is the maximum / minimum in-range value. For an
11797 // enumeratin type, such comparisons can be meaningful and useful.
11798 if (Constant->getType()->isEnumeralType() &&
11799 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11800 return false;
11801
11802 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11803 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11804 if (!OtherValueRange)
11805 return false;
11806
11807 QualType OtherT = Other->getType();
11808 if (const auto *AT = OtherT->getAs<AtomicType>())
11809 OtherT = AT->getValueType();
11810 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11811
11812 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11813 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11814 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11815 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11816 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11817
11818 // Whether we're treating Other as being a bool because of the form of
11819 // expression despite it having another type (typically 'int' in C).
11820 bool OtherIsBooleanDespiteType =
11821 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11822 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11823 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11824
11825 // Check if all values in the range of possible values of this expression
11826 // lead to the same comparison outcome.
11827 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11828 Value.isUnsigned());
11829 auto Cmp = OtherPromotedValueRange.compare(Value);
11830 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11831 if (!Result)
11832 return false;
11833
11834 // Also consider the range determined by the type alone. This allows us to
11835 // classify the warning under the proper diagnostic group.
11836 bool TautologicalTypeCompare = false;
11837 {
11838 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11839 Value.isUnsigned());
11840 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11841 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11842 RhsConstant)) {
11843 TautologicalTypeCompare = true;
11844 Cmp = TypeCmp;
11845 Result = TypeResult;
11846 }
11847 }
11848
11849 // Don't warn if the non-constant operand actually always evaluates to the
11850 // same value.
11851 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11852 return false;
11853
11854 // Suppress the diagnostic for an in-range comparison if the constant comes
11855 // from a macro or enumerator. We don't want to diagnose
11856 //
11857 // some_long_value <= INT_MAX
11858 //
11859 // when sizeof(int) == sizeof(long).
11860 bool InRange = Cmp & PromotedRange::InRangeFlag;
11861 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11862 return false;
11863
11864 // A comparison of an unsigned bit-field against 0 is really a type problem,
11865 // even though at the type level the bit-field might promote to 'signed int'.
11866 if (Other->refersToBitField() && InRange && Value == 0 &&
11867 Other->getType()->isUnsignedIntegerOrEnumerationType())
11868 TautologicalTypeCompare = true;
11869
11870 // If this is a comparison to an enum constant, include that
11871 // constant in the diagnostic.
11872 const EnumConstantDecl *ED = nullptr;
11873 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11874 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11875
11876 // Should be enough for uint128 (39 decimal digits)
11877 SmallString<64> PrettySourceValue;
11878 llvm::raw_svector_ostream OS(PrettySourceValue);
11879 if (ED) {
11880 OS << '\'' << *ED << "' (" << Value << ")";
11881 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11882 Constant->IgnoreParenImpCasts())) {
11883 OS << (BL->getValue() ? "YES" : "NO");
11884 } else {
11885 OS << Value;
11886 }
11887
11888 if (!TautologicalTypeCompare) {
11889 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11890 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11891 << E->getOpcodeStr() << OS.str() << *Result
11892 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11893 return true;
11894 }
11895
11896 if (IsObjCSignedCharBool) {
11898 S.PDiag(diag::warn_tautological_compare_objc_bool)
11899 << OS.str() << *Result);
11900 return true;
11901 }
11902
11903 // FIXME: We use a somewhat different formatting for the in-range cases and
11904 // cases involving boolean values for historical reasons. We should pick a
11905 // consistent way of presenting these diagnostics.
11906 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11907
11909 E->getOperatorLoc(), E,
11910 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11911 : diag::warn_tautological_bool_compare)
11912 << OS.str() << classifyConstantValue(Constant) << OtherT
11913 << OtherIsBooleanDespiteType << *Result
11914 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11915 } else {
11916 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11917 unsigned Diag =
11918 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11919 ? (HasEnumType(OriginalOther)
11920 ? diag::warn_unsigned_enum_always_true_comparison
11921 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11922 : diag::warn_unsigned_always_true_comparison)
11923 : diag::warn_tautological_constant_compare;
11924
11925 S.Diag(E->getOperatorLoc(), Diag)
11926 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11927 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11928 }
11929
11930 return true;
11931}
11932
11933/// Analyze the operands of the given comparison. Implements the
11934/// fallback case from AnalyzeComparison.
11939
11940/// Implements -Wsign-compare.
11941///
11942/// \param E the binary operator to check for warnings
11944 // The type the comparison is being performed in.
11945 QualType T = E->getLHS()->getType();
11946
11947 // Only analyze comparison operators where both sides have been converted to
11948 // the same type.
11950 return AnalyzeImpConvsInComparison(S, E);
11951
11952 // Don't analyze value-dependent comparisons directly.
11953 if (E->isValueDependent())
11954 return AnalyzeImpConvsInComparison(S, E);
11955
11956 Expr *LHS = E->getLHS();
11957 Expr *RHS = E->getRHS();
11958
11959 if (T->isIntegralType(S.Context)) {
11960 std::optional<llvm::APSInt> RHSValue =
11962 std::optional<llvm::APSInt> LHSValue =
11964
11965 // We don't care about expressions whose result is a constant.
11966 if (RHSValue && LHSValue)
11967 return AnalyzeImpConvsInComparison(S, E);
11968
11969 // We only care about expressions where just one side is literal
11970 if ((bool)RHSValue ^ (bool)LHSValue) {
11971 // Is the constant on the RHS or LHS?
11972 const bool RhsConstant = (bool)RHSValue;
11973 Expr *Const = RhsConstant ? RHS : LHS;
11974 Expr *Other = RhsConstant ? LHS : RHS;
11975 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11976
11977 // Check whether an integer constant comparison results in a value
11978 // of 'true' or 'false'.
11979 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11980 return AnalyzeImpConvsInComparison(S, E);
11981 }
11982 }
11983
11984 if (!T->hasUnsignedIntegerRepresentation()) {
11985 // We don't do anything special if this isn't an unsigned integral
11986 // comparison: we're only interested in integral comparisons, and
11987 // signed comparisons only happen in cases we don't care to warn about.
11988 return AnalyzeImpConvsInComparison(S, E);
11989 }
11990
11991 LHS = LHS->IgnoreParenImpCasts();
11992 RHS = RHS->IgnoreParenImpCasts();
11993
11994 if (!S.getLangOpts().CPlusPlus) {
11995 // Avoid warning about comparison of integers with different signs when
11996 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11997 // the type of `E`.
11998 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11999 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12000 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12001 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12002 }
12003
12004 // Check to see if one of the (unmodified) operands is of different
12005 // signedness.
12006 Expr *signedOperand, *unsignedOperand;
12008 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12009 "unsigned comparison between two signed integer expressions?");
12010 signedOperand = LHS;
12011 unsignedOperand = RHS;
12012 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12013 signedOperand = RHS;
12014 unsignedOperand = LHS;
12015 } else {
12016 return AnalyzeImpConvsInComparison(S, E);
12017 }
12018
12019 // Otherwise, calculate the effective range of the signed operand.
12020 std::optional<IntRange> signedRange =
12022 /*Approximate=*/true);
12023 if (!signedRange)
12024 return;
12025
12026 // Go ahead and analyze implicit conversions in the operands. Note
12027 // that we skip the implicit conversions on both sides.
12030
12031 // If the signed range is non-negative, -Wsign-compare won't fire.
12032 if (signedRange->NonNegative)
12033 return;
12034
12035 // For (in)equality comparisons, if the unsigned operand is a
12036 // constant which cannot collide with a overflowed signed operand,
12037 // then reinterpreting the signed operand as unsigned will not
12038 // change the result of the comparison.
12039 if (E->isEqualityOp()) {
12040 unsigned comparisonWidth = S.Context.getIntWidth(T);
12041 std::optional<IntRange> unsignedRange = TryGetExprRange(
12042 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12043 /*Approximate=*/true);
12044 if (!unsignedRange)
12045 return;
12046
12047 // We should never be unable to prove that the unsigned operand is
12048 // non-negative.
12049 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12050
12051 if (unsignedRange->Width < comparisonWidth)
12052 return;
12053 }
12054
12056 S.PDiag(diag::warn_mixed_sign_comparison)
12057 << LHS->getType() << RHS->getType()
12058 << LHS->getSourceRange() << RHS->getSourceRange());
12059}
12060
12061/// Analyzes an attempt to assign the given value to a bitfield.
12062///
12063/// Returns true if there was something fishy about the attempt.
12065 SourceLocation InitLoc) {
12066 assert(Bitfield->isBitField());
12067 if (Bitfield->isInvalidDecl())
12068 return false;
12069
12070 // White-list bool bitfields.
12071 QualType BitfieldType = Bitfield->getType();
12072 if (BitfieldType->isBooleanType())
12073 return false;
12074
12075 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12076 // If the underlying enum type was not explicitly specified as an unsigned
12077 // type and the enum contain only positive values, MSVC++ will cause an
12078 // inconsistency by storing this as a signed type.
12079 if (S.getLangOpts().CPlusPlus11 &&
12080 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12081 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12082 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12083 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12084 << BitfieldEnumDecl;
12085 }
12086 }
12087
12088 // Ignore value- or type-dependent expressions.
12089 if (Bitfield->getBitWidth()->isValueDependent() ||
12090 Bitfield->getBitWidth()->isTypeDependent() ||
12091 Init->isValueDependent() ||
12092 Init->isTypeDependent())
12093 return false;
12094
12095 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12096 unsigned FieldWidth = Bitfield->getBitWidthValue();
12097
12098 Expr::EvalResult Result;
12099 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12101 // The RHS is not constant. If the RHS has an enum type, make sure the
12102 // bitfield is wide enough to hold all the values of the enum without
12103 // truncation.
12104 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12105 const PreferredTypeAttr *PTAttr = nullptr;
12106 if (!ED) {
12107 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12108 if (PTAttr)
12109 ED = PTAttr->getType()->getAsEnumDecl();
12110 }
12111 if (ED) {
12112 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12113
12114 // Enum types are implicitly signed on Windows, so check if there are any
12115 // negative enumerators to see if the enum was intended to be signed or
12116 // not.
12117 bool SignedEnum = ED->getNumNegativeBits() > 0;
12118
12119 // Check for surprising sign changes when assigning enum values to a
12120 // bitfield of different signedness. If the bitfield is signed and we
12121 // have exactly the right number of bits to store this unsigned enum,
12122 // suggest changing the enum to an unsigned type. This typically happens
12123 // on Windows where unfixed enums always use an underlying type of 'int'.
12124 unsigned DiagID = 0;
12125 if (SignedEnum && !SignedBitfield) {
12126 DiagID =
12127 PTAttr == nullptr
12128 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12129 : diag::
12130 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12131 } else if (SignedBitfield && !SignedEnum &&
12132 ED->getNumPositiveBits() == FieldWidth) {
12133 DiagID =
12134 PTAttr == nullptr
12135 ? diag::warn_signed_bitfield_enum_conversion
12136 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12137 }
12138 if (DiagID) {
12139 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12140 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12141 SourceRange TypeRange =
12142 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12143 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12144 << SignedEnum << TypeRange;
12145 if (PTAttr)
12146 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12147 << ED;
12148 }
12149
12150 // Compute the required bitwidth. If the enum has negative values, we need
12151 // one more bit than the normal number of positive bits to represent the
12152 // sign bit.
12153 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12154 ED->getNumNegativeBits())
12155 : ED->getNumPositiveBits();
12156
12157 // Check the bitwidth.
12158 if (BitsNeeded > FieldWidth) {
12159 Expr *WidthExpr = Bitfield->getBitWidth();
12160 auto DiagID =
12161 PTAttr == nullptr
12162 ? diag::warn_bitfield_too_small_for_enum
12163 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12164 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12165 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12166 << BitsNeeded << ED << WidthExpr->getSourceRange();
12167 if (PTAttr)
12168 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12169 << ED;
12170 }
12171 }
12172
12173 return false;
12174 }
12175
12176 llvm::APSInt Value = Result.Val.getInt();
12177
12178 unsigned OriginalWidth = Value.getBitWidth();
12179
12180 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12181 // false positives where the user is demonstrating they intend to use the
12182 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12183 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12184 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12185 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12186 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12187 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12188 S.findMacroSpelling(MaybeMacroLoc, "true"))
12189 return false;
12190 }
12191
12192 if (!Value.isSigned() || Value.isNegative())
12193 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12194 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12195 OriginalWidth = Value.getSignificantBits();
12196
12197 if (OriginalWidth <= FieldWidth)
12198 return false;
12199
12200 // Compute the value which the bitfield will contain.
12201 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12202 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12203
12204 // Check whether the stored value is equal to the original value.
12205 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12206 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12207 return false;
12208
12209 std::string PrettyValue = toString(Value, 10);
12210 std::string PrettyTrunc = toString(TruncatedValue, 10);
12211
12212 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12213 ? diag::warn_impcast_single_bit_bitield_precision_constant
12214 : diag::warn_impcast_bitfield_precision_constant)
12215 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12216 << Init->getSourceRange();
12217
12218 return true;
12219}
12220
12221/// Analyze the given simple or compound assignment for warning-worthy
12222/// operations.
12224 // Just recurse on the LHS.
12226
12227 // We want to recurse on the RHS as normal unless we're assigning to
12228 // a bitfield.
12229 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12230 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12231 E->getOperatorLoc())) {
12232 // Recurse, ignoring any implicit conversions on the RHS.
12234 E->getOperatorLoc());
12235 }
12236 }
12237
12239
12240 // Diagnose implicitly sequentially-consistent atomic assignment.
12241 if (E->getLHS()->getType()->isAtomicType())
12242 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12243}
12244
12245/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12246static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12247 QualType T, SourceLocation CContext, unsigned diag,
12248 bool PruneControlFlow = false) {
12249 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12250 // address space annotations isn't really useful. The warnings aren't because
12251 // you're converting a `private int` to `unsigned int`, it is because you're
12252 // conerting `int` to `unsigned int`.
12253 if (SourceType.hasAddressSpace())
12254 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12255 if (T.hasAddressSpace())
12257 if (PruneControlFlow) {
12259 S.PDiag(diag)
12260 << SourceType << T << E->getSourceRange()
12261 << SourceRange(CContext));
12262 return;
12263 }
12264 S.Diag(E->getExprLoc(), diag)
12265 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12266}
12267
12268/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12269static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12270 SourceLocation CContext, unsigned diag,
12271 bool PruneControlFlow = false) {
12272 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12273}
12274
12275/// Diagnose an implicit cast from a floating point value to an integer value.
12276static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12277 SourceLocation CContext) {
12278 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12279 bool PruneWarnings = S.inTemplateInstantiation();
12280
12281 const Expr *InnerE = E->IgnoreParenImpCasts();
12282 // We also want to warn on, e.g., "int i = -1.234"
12283 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12284 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12285 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12286
12287 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12288
12289 llvm::APFloat Value(0.0);
12290 bool IsConstant =
12292 if (!IsConstant) {
12293 if (S.ObjC().isSignedCharBool(T)) {
12295 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12296 << E->getType());
12297 }
12298
12299 return DiagnoseImpCast(S, E, T, CContext,
12300 diag::warn_impcast_float_integer, PruneWarnings);
12301 }
12302
12303 bool isExact = false;
12304
12305 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12306 T->hasUnsignedIntegerRepresentation());
12307 llvm::APFloat::opStatus Result = Value.convertToInteger(
12308 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12309
12310 // FIXME: Force the precision of the source value down so we don't print
12311 // digits which are usually useless (we don't really care here if we
12312 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12313 // would automatically print the shortest representation, but it's a bit
12314 // tricky to implement.
12315 SmallString<16> PrettySourceValue;
12316 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12317 precision = (precision * 59 + 195) / 196;
12318 Value.toString(PrettySourceValue, precision);
12319
12320 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12322 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12323 << PrettySourceValue);
12324 }
12325
12326 if (Result == llvm::APFloat::opOK && isExact) {
12327 if (IsLiteral) return;
12328 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12329 PruneWarnings);
12330 }
12331
12332 // Conversion of a floating-point value to a non-bool integer where the
12333 // integral part cannot be represented by the integer type is undefined.
12334 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12335 return DiagnoseImpCast(
12336 S, E, T, CContext,
12337 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12338 : diag::warn_impcast_float_to_integer_out_of_range,
12339 PruneWarnings);
12340
12341 unsigned DiagID = 0;
12342 if (IsLiteral) {
12343 // Warn on floating point literal to integer.
12344 DiagID = diag::warn_impcast_literal_float_to_integer;
12345 } else if (IntegerValue == 0) {
12346 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12347 return DiagnoseImpCast(S, E, T, CContext,
12348 diag::warn_impcast_float_integer, PruneWarnings);
12349 }
12350 // Warn on non-zero to zero conversion.
12351 DiagID = diag::warn_impcast_float_to_integer_zero;
12352 } else {
12353 if (IntegerValue.isUnsigned()) {
12354 if (!IntegerValue.isMaxValue()) {
12355 return DiagnoseImpCast(S, E, T, CContext,
12356 diag::warn_impcast_float_integer, PruneWarnings);
12357 }
12358 } else { // IntegerValue.isSigned()
12359 if (!IntegerValue.isMaxSignedValue() &&
12360 !IntegerValue.isMinSignedValue()) {
12361 return DiagnoseImpCast(S, E, T, CContext,
12362 diag::warn_impcast_float_integer, PruneWarnings);
12363 }
12364 }
12365 // Warn on evaluatable floating point expression to integer conversion.
12366 DiagID = diag::warn_impcast_float_to_integer;
12367 }
12368
12369 SmallString<16> PrettyTargetValue;
12370 if (IsBool)
12371 PrettyTargetValue = Value.isZero() ? "false" : "true";
12372 else
12373 IntegerValue.toString(PrettyTargetValue);
12374
12375 if (PruneWarnings) {
12377 S.PDiag(DiagID)
12378 << E->getType() << T.getUnqualifiedType()
12379 << PrettySourceValue << PrettyTargetValue
12380 << E->getSourceRange() << SourceRange(CContext));
12381 } else {
12382 S.Diag(E->getExprLoc(), DiagID)
12383 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12384 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12385 }
12386}
12387
12388/// Analyze the given compound assignment for the possible losing of
12389/// floating-point precision.
12391 assert(isa<CompoundAssignOperator>(E) &&
12392 "Must be compound assignment operation");
12393 // Recurse on the LHS and RHS in here
12396
12397 if (E->getLHS()->getType()->isAtomicType())
12398 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12399
12400 // Now check the outermost expression
12401 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12402 const auto *RBT = cast<CompoundAssignOperator>(E)
12403 ->getComputationResultType()
12404 ->getAs<BuiltinType>();
12405
12406 // The below checks assume source is floating point.
12407 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12408
12409 // If source is floating point but target is an integer.
12410 if (ResultBT->isInteger())
12411 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12412 E->getExprLoc(), diag::warn_impcast_float_integer);
12413
12414 if (!ResultBT->isFloatingPoint())
12415 return;
12416
12417 // If both source and target are floating points, warn about losing precision.
12419 QualType(ResultBT, 0), QualType(RBT, 0));
12420 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12421 // warn about dropping FP rank.
12422 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12423 diag::warn_impcast_float_result_precision);
12424}
12425
12426static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12427 IntRange Range) {
12428 if (!Range.Width) return "0";
12429
12430 llvm::APSInt ValueInRange = Value;
12431 ValueInRange.setIsSigned(!Range.NonNegative);
12432 ValueInRange = ValueInRange.trunc(Range.Width);
12433 return toString(ValueInRange, 10);
12434}
12435
12436static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12437 bool ToBool) {
12438 if (!isa<ImplicitCastExpr>(Ex))
12439 return false;
12440
12441 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12443 const Type *Source =
12445 if (Target->isDependentType())
12446 return false;
12447
12448 const auto *FloatCandidateBT =
12449 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12450 const Type *BoolCandidateType = ToBool ? Target : Source;
12451
12452 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12453 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12454}
12455
12456static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12457 SourceLocation CC) {
12458 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12459 const Expr *CurrA = TheCall->getArg(I);
12460 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12461 continue;
12462
12463 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12464 S, TheCall->getArg(I - 1), false));
12465 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12466 S, TheCall->getArg(I + 1), false));
12467 if (IsSwapped) {
12468 // Warn on this floating-point to bool conversion.
12470 CurrA->getType(), CC,
12471 diag::warn_impcast_floating_point_to_bool);
12472 }
12473 }
12474}
12475
12477 SourceLocation CC) {
12478 // Don't warn on functions which have return type nullptr_t.
12479 if (isa<CallExpr>(E))
12480 return;
12481
12482 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12483 const Expr *NewE = E->IgnoreParenImpCasts();
12484 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12485 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12486 if (!IsGNUNullExpr && !HasNullPtrType)
12487 return;
12488
12489 // Return if target type is a safe conversion.
12490 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12491 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12492 return;
12493
12494 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12495 E->getExprLoc()))
12496 return;
12497
12499
12500 // Venture through the macro stacks to get to the source of macro arguments.
12501 // The new location is a better location than the complete location that was
12502 // passed in.
12503 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12505
12506 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12507 if (IsGNUNullExpr && Loc.isMacroID()) {
12508 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12509 Loc, S.SourceMgr, S.getLangOpts());
12510 if (MacroName == "NULL")
12512 }
12513
12514 // Only warn if the null and context location are in the same macro expansion.
12515 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12516 return;
12517
12518 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12519 << HasNullPtrType << T << SourceRange(CC)
12522}
12523
12524// Helper function to filter out cases for constant width constant conversion.
12525// Don't warn on char array initialization or for non-decimal values.
12527 SourceLocation CC) {
12528 // If initializing from a constant, and the constant starts with '0',
12529 // then it is a binary, octal, or hexadecimal. Allow these constants
12530 // to fill all the bits, even if there is a sign change.
12531 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12532 const char FirstLiteralCharacter =
12533 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12534 if (FirstLiteralCharacter == '0')
12535 return false;
12536 }
12537
12538 // If the CC location points to a '{', and the type is char, then assume
12539 // assume it is an array initialization.
12540 if (CC.isValid() && T->isCharType()) {
12541 const char FirstContextCharacter =
12543 if (FirstContextCharacter == '{')
12544 return false;
12545 }
12546
12547 return true;
12548}
12549
12551 const auto *IL = dyn_cast<IntegerLiteral>(E);
12552 if (!IL) {
12553 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12554 if (UO->getOpcode() == UO_Minus)
12555 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12556 }
12557 }
12558
12559 return IL;
12560}
12561
12563 E = E->IgnoreParenImpCasts();
12564 SourceLocation ExprLoc = E->getExprLoc();
12565
12566 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12567 BinaryOperator::Opcode Opc = BO->getOpcode();
12568 Expr::EvalResult Result;
12569 // Do not diagnose unsigned shifts.
12570 if (Opc == BO_Shl) {
12571 const auto *LHS = getIntegerLiteral(BO->getLHS());
12572 const auto *RHS = getIntegerLiteral(BO->getRHS());
12573 if (LHS && LHS->getValue() == 0)
12574 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12575 else if (!E->isValueDependent() && LHS && RHS &&
12576 RHS->getValue().isNonNegative() &&
12578 S.Diag(ExprLoc, diag::warn_left_shift_always)
12579 << (Result.Val.getInt() != 0);
12580 else if (E->getType()->isSignedIntegerType())
12581 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12584 ") != 0");
12585 }
12586 }
12587
12588 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12589 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12590 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12591 if (!LHS || !RHS)
12592 return;
12593 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12594 (RHS->getValue() == 0 || RHS->getValue() == 1))
12595 // Do not diagnose common idioms.
12596 return;
12597 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12598 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12599 }
12600}
12601
12603 const Type *Target, Expr *E,
12604 QualType T,
12605 SourceLocation CC) {
12606 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12607 Source != Target);
12608
12609 // Lone surrogates have a distinct representation in UTF-32.
12610 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12611 // so don't warn on such conversion.
12612 if (Source->isChar16Type() && Target->isChar32Type())
12613 return;
12614
12615 Expr::EvalResult Result;
12618 llvm::APSInt Value(32);
12619 Value = Result.Val.getInt();
12620 bool IsASCII = Value <= 0x7F;
12621 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12622 bool ConversionPreservesSemantics =
12623 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12624
12625 if (!ConversionPreservesSemantics) {
12626 auto IsSingleCodeUnitCP = [](const QualType &T,
12627 const llvm::APSInt &Value) {
12628 if (T->isChar8Type())
12629 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12630 if (T->isChar16Type())
12631 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12632 assert(T->isChar32Type());
12633 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12634 };
12635
12636 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12637 << E->getType() << T
12638 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12639 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12640 }
12641 } else {
12642 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12644 DiagnoseImpCast(S, E, T, CC,
12645 LosesPrecision ? diag::warn_impcast_unicode_precision
12646 : diag::warn_impcast_unicode_char_type);
12647 }
12648}
12649
12651 From = Context.getCanonicalType(From);
12652 To = Context.getCanonicalType(To);
12653 QualType MaybePointee = From->getPointeeType();
12654 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12655 From = MaybePointee;
12656 MaybePointee = To->getPointeeType();
12657 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12658 To = MaybePointee;
12659
12660 if (const auto *FromFn = From->getAs<FunctionType>()) {
12661 if (const auto *ToFn = To->getAs<FunctionType>()) {
12662 if (FromFn->getCFIUncheckedCalleeAttr() &&
12663 !ToFn->getCFIUncheckedCalleeAttr())
12664 return true;
12665 }
12666 }
12667 return false;
12668}
12669
12671 bool *ICContext, bool IsListInit) {
12672 if (E->isTypeDependent() || E->isValueDependent()) return;
12673
12674 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12675 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12676 if (Source == Target) return;
12677 if (Target->isDependentType()) return;
12678
12679 // If the conversion context location is invalid don't complain. We also
12680 // don't want to emit a warning if the issue occurs from the expansion of
12681 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12682 // delay this check as long as possible. Once we detect we are in that
12683 // scenario, we just return.
12684 if (CC.isInvalid())
12685 return;
12686
12687 if (Source->isAtomicType())
12688 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12689
12690 // Diagnose implicit casts to bool.
12691 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12692 if (isa<StringLiteral>(E))
12693 // Warn on string literal to bool. Checks for string literals in logical
12694 // and expressions, for instance, assert(0 && "error here"), are
12695 // prevented by a check in AnalyzeImplicitConversions().
12696 return DiagnoseImpCast(*this, E, T, CC,
12697 diag::warn_impcast_string_literal_to_bool);
12700 // This covers the literal expressions that evaluate to Objective-C
12701 // objects.
12702 return DiagnoseImpCast(*this, E, T, CC,
12703 diag::warn_impcast_objective_c_literal_to_bool);
12704 }
12705 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12706 // Warn on pointer to bool conversion that is always true.
12708 SourceRange(CC));
12709 }
12710 }
12711
12712 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12713 // is a typedef for signed char (macOS), then that constant value has to be 1
12714 // or 0.
12715 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12718 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12720 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12721 << toString(Result.Val.getInt(), 10));
12722 }
12723 return;
12724 }
12725 }
12726
12727 // Check implicit casts from Objective-C collection literals to specialized
12728 // collection types, e.g., NSArray<NSString *> *.
12729 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12730 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12731 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12732 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12733
12734 // Strip vector types.
12735 if (isa<VectorType>(Source)) {
12736 if (Target->isSveVLSBuiltinType() &&
12737 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12738 QualType(Source, 0)) ||
12739 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12740 QualType(Source, 0))))
12741 return;
12742
12743 if (Target->isRVVVLSBuiltinType() &&
12744 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12745 QualType(Source, 0)) ||
12746 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12747 QualType(Source, 0))))
12748 return;
12749
12750 if (!isa<VectorType>(Target)) {
12751 if (SourceMgr.isInSystemMacro(CC))
12752 return;
12753 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12754 }
12755 if (getLangOpts().HLSL &&
12756 Target->castAs<VectorType>()->getNumElements() <
12757 Source->castAs<VectorType>()->getNumElements()) {
12758 // Diagnose vector truncation but don't return. We may also want to
12759 // diagnose an element conversion.
12760 DiagnoseImpCast(*this, E, T, CC,
12761 diag::warn_hlsl_impcast_vector_truncation);
12762 }
12763
12764 // If the vector cast is cast between two vectors of the same size, it is
12765 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12766 if (!getLangOpts().HLSL &&
12767 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12768 return;
12769
12770 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12771 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12772 }
12773 if (const auto *VecTy = dyn_cast<VectorType>(Target))
12774 Target = VecTy->getElementType().getTypePtr();
12775
12776 if (isa<ConstantMatrixType>(Source)) {
12777 if (Target->isScalarType())
12778 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
12779
12780 if (getLangOpts().HLSL &&
12782 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
12783 // Diagnose Matrix truncation but don't return. We may also want to
12784 // diagnose an element conversion.
12785 DiagnoseImpCast(*this, E, T, CC,
12786 diag::warn_hlsl_impcast_matrix_truncation);
12787 }
12788 }
12789 // Strip complex types.
12790 if (isa<ComplexType>(Source)) {
12791 if (!isa<ComplexType>(Target)) {
12792 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12793 return;
12794
12795 return DiagnoseImpCast(*this, E, T, CC,
12797 ? diag::err_impcast_complex_scalar
12798 : diag::warn_impcast_complex_scalar);
12799 }
12800
12801 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12802 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12803 }
12804
12805 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12806 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12807
12808 // Strip SVE vector types
12809 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12810 // Need the original target type for vector type checks
12811 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12812 // Handle conversion from scalable to fixed when msve-vector-bits is
12813 // specified
12814 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12815 QualType(Source, 0)) ||
12816 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12817 QualType(Source, 0)))
12818 return;
12819
12820 // If the vector cast is cast between two vectors of the same size, it is
12821 // a bitcast, not a conversion.
12822 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12823 return;
12824
12825 Source = SourceBT->getSveEltType(Context).getTypePtr();
12826 }
12827
12828 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12829 Target = TargetBT->getSveEltType(Context).getTypePtr();
12830
12831 // If the source is floating point...
12832 if (SourceBT && SourceBT->isFloatingPoint()) {
12833 // ...and the target is floating point...
12834 if (TargetBT && TargetBT->isFloatingPoint()) {
12835 // ...then warn if we're dropping FP rank.
12836
12838 QualType(SourceBT, 0), QualType(TargetBT, 0));
12839 if (Order > 0) {
12840 // Don't warn about float constants that are precisely
12841 // representable in the target type.
12842 Expr::EvalResult result;
12843 if (E->EvaluateAsRValue(result, Context)) {
12844 // Value might be a float, a float vector, or a float complex.
12846 result.Val,
12847 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12848 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12849 return;
12850 }
12851
12852 if (SourceMgr.isInSystemMacro(CC))
12853 return;
12854
12855 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12856 }
12857 // ... or possibly if we're increasing rank, too
12858 else if (Order < 0) {
12859 if (SourceMgr.isInSystemMacro(CC))
12860 return;
12861
12862 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12863 }
12864 return;
12865 }
12866
12867 // If the target is integral, always warn.
12868 if (TargetBT && TargetBT->isInteger()) {
12869 if (SourceMgr.isInSystemMacro(CC))
12870 return;
12871
12872 DiagnoseFloatingImpCast(*this, E, T, CC);
12873 }
12874
12875 // Detect the case where a call result is converted from floating-point to
12876 // to bool, and the final argument to the call is converted from bool, to
12877 // discover this typo:
12878 //
12879 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12880 //
12881 // FIXME: This is an incredibly special case; is there some more general
12882 // way to detect this class of misplaced-parentheses bug?
12883 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12884 // Check last argument of function call to see if it is an
12885 // implicit cast from a type matching the type the result
12886 // is being cast to.
12887 CallExpr *CEx = cast<CallExpr>(E);
12888 if (unsigned NumArgs = CEx->getNumArgs()) {
12889 Expr *LastA = CEx->getArg(NumArgs - 1);
12890 Expr *InnerE = LastA->IgnoreParenImpCasts();
12891 if (isa<ImplicitCastExpr>(LastA) &&
12892 InnerE->getType()->isBooleanType()) {
12893 // Warn on this floating-point to bool conversion
12894 DiagnoseImpCast(*this, E, T, CC,
12895 diag::warn_impcast_floating_point_to_bool);
12896 }
12897 }
12898 }
12899 return;
12900 }
12901
12902 // Valid casts involving fixed point types should be accounted for here.
12903 if (Source->isFixedPointType()) {
12904 if (Target->isUnsaturatedFixedPointType()) {
12908 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12909 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12910 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12911 if (Value > MaxVal || Value < MinVal) {
12913 PDiag(diag::warn_impcast_fixed_point_range)
12914 << Value.toString() << T
12915 << E->getSourceRange()
12916 << clang::SourceRange(CC));
12917 return;
12918 }
12919 }
12920 } else if (Target->isIntegerType()) {
12924 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12925
12926 bool Overflowed;
12927 llvm::APSInt IntResult = FXResult.convertToInt(
12928 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12929 &Overflowed);
12930
12931 if (Overflowed) {
12933 PDiag(diag::warn_impcast_fixed_point_range)
12934 << FXResult.toString() << T
12935 << E->getSourceRange()
12936 << clang::SourceRange(CC));
12937 return;
12938 }
12939 }
12940 }
12941 } else if (Target->isUnsaturatedFixedPointType()) {
12942 if (Source->isIntegerType()) {
12946 llvm::APSInt Value = Result.Val.getInt();
12947
12948 bool Overflowed;
12949 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12950 Value, Context.getFixedPointSemantics(T), &Overflowed);
12951
12952 if (Overflowed) {
12954 PDiag(diag::warn_impcast_fixed_point_range)
12955 << toString(Value, /*Radix=*/10) << T
12956 << E->getSourceRange()
12957 << clang::SourceRange(CC));
12958 return;
12959 }
12960 }
12961 }
12962 }
12963
12964 // If we are casting an integer type to a floating point type without
12965 // initialization-list syntax, we might lose accuracy if the floating
12966 // point type has a narrower significand than the integer type.
12967 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12968 TargetBT->isFloatingType() && !IsListInit) {
12969 // Determine the number of precision bits in the source integer type.
12970 std::optional<IntRange> SourceRange =
12972 /*Approximate=*/true);
12973 if (!SourceRange)
12974 return;
12975 unsigned int SourcePrecision = SourceRange->Width;
12976
12977 // Determine the number of precision bits in the
12978 // target floating point type.
12979 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12980 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12981
12982 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12983 SourcePrecision > TargetPrecision) {
12984
12985 if (std::optional<llvm::APSInt> SourceInt =
12987 // If the source integer is a constant, convert it to the target
12988 // floating point type. Issue a warning if the value changes
12989 // during the whole conversion.
12990 llvm::APFloat TargetFloatValue(
12991 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12992 llvm::APFloat::opStatus ConversionStatus =
12993 TargetFloatValue.convertFromAPInt(
12994 *SourceInt, SourceBT->isSignedInteger(),
12995 llvm::APFloat::rmNearestTiesToEven);
12996
12997 if (ConversionStatus != llvm::APFloat::opOK) {
12998 SmallString<32> PrettySourceValue;
12999 SourceInt->toString(PrettySourceValue, 10);
13000 SmallString<32> PrettyTargetValue;
13001 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13002
13004 E->getExprLoc(), E,
13005 PDiag(diag::warn_impcast_integer_float_precision_constant)
13006 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13007 << E->getSourceRange() << clang::SourceRange(CC));
13008 }
13009 } else {
13010 // Otherwise, the implicit conversion may lose precision.
13011 DiagnoseImpCast(*this, E, T, CC,
13012 diag::warn_impcast_integer_float_precision);
13013 }
13014 }
13015 }
13016
13017 DiagnoseNullConversion(*this, E, T, CC);
13018
13020
13021 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13022 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13023 return;
13024 }
13025
13026 if (Target->isBooleanType())
13027 DiagnoseIntInBoolContext(*this, E);
13028
13030 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13031 << QualType(Source, 0) << QualType(Target, 0);
13032 }
13033
13034 if (!Source->isIntegerType() || !Target->isIntegerType())
13035 return;
13036
13037 // TODO: remove this early return once the false positives for constant->bool
13038 // in templates, macros, etc, are reduced or removed.
13039 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13040 return;
13041
13042 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13043 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13045 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13046 << E->getType());
13047 }
13048 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13049 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13050 if (!LikelySourceRange)
13051 return;
13052
13053 IntRange SourceTypeRange =
13054 IntRange::forTargetOfCanonicalType(Context, Source);
13055 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13056
13057 if (LikelySourceRange->Width > TargetRange.Width) {
13058 // If the source is a constant, use a default-on diagnostic.
13059 // TODO: this should happen for bitfield stores, too.
13063 llvm::APSInt Value(32);
13064 Value = Result.Val.getInt();
13065
13066 if (SourceMgr.isInSystemMacro(CC))
13067 return;
13068
13069 std::string PrettySourceValue = toString(Value, 10);
13070 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13071
13073 PDiag(diag::warn_impcast_integer_precision_constant)
13074 << PrettySourceValue << PrettyTargetValue
13075 << E->getType() << T << E->getSourceRange()
13076 << SourceRange(CC));
13077 return;
13078 }
13079
13080 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13081 if (SourceMgr.isInSystemMacro(CC))
13082 return;
13083
13084 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13085 if (UO->getOpcode() == UO_Minus)
13086 return DiagnoseImpCast(
13087 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13088 }
13089
13090 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13091 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13092 /* pruneControlFlow */ true);
13093 return DiagnoseImpCast(*this, E, T, CC,
13094 diag::warn_impcast_integer_precision);
13095 }
13096
13097 if (TargetRange.Width > SourceTypeRange.Width) {
13098 if (auto *UO = dyn_cast<UnaryOperator>(E))
13099 if (UO->getOpcode() == UO_Minus)
13100 if (Source->isUnsignedIntegerType()) {
13101 if (Target->isUnsignedIntegerType())
13102 return DiagnoseImpCast(*this, E, T, CC,
13103 diag::warn_impcast_high_order_zero_bits);
13104 if (Target->isSignedIntegerType())
13105 return DiagnoseImpCast(*this, E, T, CC,
13106 diag::warn_impcast_nonnegative_result);
13107 }
13108 }
13109
13110 if (TargetRange.Width == LikelySourceRange->Width &&
13111 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13112 Source->isSignedIntegerType()) {
13113 // Warn when doing a signed to signed conversion, warn if the positive
13114 // source value is exactly the width of the target type, which will
13115 // cause a negative value to be stored.
13116
13119 !SourceMgr.isInSystemMacro(CC)) {
13120 llvm::APSInt Value = Result.Val.getInt();
13121 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13122 std::string PrettySourceValue = toString(Value, 10);
13123 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13124
13125 Diag(E->getExprLoc(),
13126 PDiag(diag::warn_impcast_integer_precision_constant)
13127 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13128 << E->getSourceRange() << SourceRange(CC));
13129 return;
13130 }
13131 }
13132
13133 // Fall through for non-constants to give a sign conversion warning.
13134 }
13135
13136 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13137 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13138 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13139 LikelySourceRange->Width == TargetRange.Width))) {
13140 if (SourceMgr.isInSystemMacro(CC))
13141 return;
13142
13143 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13144 TargetBT->isInteger() &&
13145 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13146 return;
13147 }
13148
13149 unsigned DiagID = diag::warn_impcast_integer_sign;
13150
13151 // Traditionally, gcc has warned about this under -Wsign-compare.
13152 // We also want to warn about it in -Wconversion.
13153 // So if -Wconversion is off, use a completely identical diagnostic
13154 // in the sign-compare group.
13155 // The conditional-checking code will
13156 if (ICContext) {
13157 DiagID = diag::warn_impcast_integer_sign_conditional;
13158 *ICContext = true;
13159 }
13160
13161 DiagnoseImpCast(*this, E, T, CC, DiagID);
13162 }
13163
13164 // If we're implicitly converting from an integer into an enumeration, that
13165 // is valid in C but invalid in C++.
13166 QualType SourceType = E->getEnumCoercedType(Context);
13167 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13168 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13169 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13170
13171 // Diagnose conversions between different enumeration types.
13172 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13173 // type, to give us better diagnostics.
13174 Source = Context.getCanonicalType(SourceType).getTypePtr();
13175
13176 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13177 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13178 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13179 TargetEnum->getDecl()->hasNameForLinkage() &&
13180 SourceEnum != TargetEnum) {
13181 if (SourceMgr.isInSystemMacro(CC))
13182 return;
13183
13184 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13185 diag::warn_impcast_different_enum_types);
13186 }
13187}
13188
13191
13193 SourceLocation CC, bool &ICContext) {
13194 E = E->IgnoreParenImpCasts();
13195 // Diagnose incomplete type for second or third operand in C.
13196 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13197 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13198
13199 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13200 return CheckConditionalOperator(S, CO, CC, T);
13201
13203 if (E->getType() != T)
13204 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13205}
13206
13210
13211 Expr *TrueExpr = E->getTrueExpr();
13212 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13213 TrueExpr = BCO->getCommon();
13214
13215 bool Suspicious = false;
13216 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13217 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13218
13219 if (T->isBooleanType())
13221
13222 // If -Wconversion would have warned about either of the candidates
13223 // for a signedness conversion to the context type...
13224 if (!Suspicious) return;
13225
13226 // ...but it's currently ignored...
13227 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13228 return;
13229
13230 // ...then check whether it would have warned about either of the
13231 // candidates for a signedness conversion to the condition type.
13232 if (E->getType() == T) return;
13233
13234 Suspicious = false;
13235 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13236 &Suspicious);
13237 if (!Suspicious)
13239 E->getType(), CC, &Suspicious);
13240}
13241
13242/// Check conversion of given expression to boolean.
13243/// Input argument E is a logical expression.
13245 // Run the bool-like conversion checks only for C since there bools are
13246 // still not used as the return type from "boolean" operators or as the input
13247 // type for conditional operators.
13248 if (S.getLangOpts().CPlusPlus)
13249 return;
13251 return;
13253}
13254
13255namespace {
13256struct AnalyzeImplicitConversionsWorkItem {
13257 Expr *E;
13258 SourceLocation CC;
13259 bool IsListInit;
13260};
13261}
13262
13264 Sema &S, Expr *E, QualType T, SourceLocation CC,
13265 bool ExtraCheckForImplicitConversion,
13267 E = E->IgnoreParenImpCasts();
13268 WorkList.push_back({E, CC, false});
13269
13270 if (ExtraCheckForImplicitConversion && E->getType() != T)
13271 S.CheckImplicitConversion(E, T, CC);
13272}
13273
13274/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13275/// that should be visited are added to WorkList.
13277 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13279 Expr *OrigE = Item.E;
13280 SourceLocation CC = Item.CC;
13281
13282 QualType T = OrigE->getType();
13283 Expr *E = OrigE->IgnoreParenImpCasts();
13284
13285 // Propagate whether we are in a C++ list initialization expression.
13286 // If so, we do not issue warnings for implicit int-float conversion
13287 // precision loss, because C++11 narrowing already handles it.
13288 //
13289 // HLSL's initialization lists are special, so they shouldn't observe the C++
13290 // behavior here.
13291 bool IsListInit =
13292 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13293 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13294
13295 if (E->isTypeDependent() || E->isValueDependent())
13296 return;
13297
13298 Expr *SourceExpr = E;
13299 // Examine, but don't traverse into the source expression of an
13300 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13301 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13302 // evaluate it in the context of checking the specific conversion to T though.
13303 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13304 if (auto *Src = OVE->getSourceExpr())
13305 SourceExpr = Src;
13306
13307 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13308 if (UO->getOpcode() == UO_Not &&
13309 UO->getSubExpr()->isKnownToHaveBooleanValue())
13310 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13311 << OrigE->getSourceRange() << T->isBooleanType()
13312 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13313
13314 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13315 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13316 BO->getLHS()->isKnownToHaveBooleanValue() &&
13317 BO->getRHS()->isKnownToHaveBooleanValue() &&
13318 BO->getLHS()->HasSideEffects(S.Context) &&
13319 BO->getRHS()->HasSideEffects(S.Context)) {
13321 const LangOptions &LO = S.getLangOpts();
13322 SourceLocation BLoc = BO->getOperatorLoc();
13323 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13324 StringRef SR = clang::Lexer::getSourceText(
13325 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13326 // To reduce false positives, only issue the diagnostic if the operator
13327 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13328 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13329 // in C, along with other macro spellings the user might invent.
13330 if (SR.str() == "&" || SR.str() == "|") {
13331
13332 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13333 << (BO->getOpcode() == BO_And ? "&" : "|")
13334 << OrigE->getSourceRange()
13336 BO->getOperatorLoc(),
13337 (BO->getOpcode() == BO_And ? "&&" : "||"));
13338 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13339 }
13340 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13341 /// Analyze the given comma operator. The basic idea behind the analysis
13342 /// is to analyze the left and right operands slightly differently. The
13343 /// left operand needs to check whether the operand itself has an implicit
13344 /// conversion, but not whether the left operand induces an implicit
13345 /// conversion for the entire comma expression itself. This is similar to
13346 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13347 /// were directly used for the implicit conversion check.
13348 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13349 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13350 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13351 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13352 return;
13353 }
13354 }
13355
13356 // For conditional operators, we analyze the arguments as if they
13357 // were being fed directly into the output.
13358 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13359 CheckConditionalOperator(S, CO, CC, T);
13360 return;
13361 }
13362
13363 // Check implicit argument conversions for function calls.
13364 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13366
13367 // Go ahead and check any implicit conversions we might have skipped.
13368 // The non-canonical typecheck is just an optimization;
13369 // CheckImplicitConversion will filter out dead implicit conversions.
13370 if (SourceExpr->getType() != T)
13371 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13372
13373 // Now continue drilling into this expression.
13374
13375 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13376 // The bound subexpressions in a PseudoObjectExpr are not reachable
13377 // as transitive children.
13378 // FIXME: Use a more uniform representation for this.
13379 for (auto *SE : POE->semantics())
13380 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13381 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13382 }
13383
13384 // Skip past explicit casts.
13385 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13386 E = CE->getSubExpr();
13387 // In the special case of a C++ function-style cast with braces,
13388 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13389 // initializer. This InitListExpr basically belongs to the cast itself, so
13390 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13392 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13393 if (InitListE->getNumInits() == 1) {
13394 E = InitListE->getInit(0);
13395 }
13396 }
13397 }
13398 E = E->IgnoreParenImpCasts();
13399 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13400 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13401 WorkList.push_back({E, CC, IsListInit});
13402 return;
13403 }
13404
13405 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13406 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13407 // The base expression is only used to initialize the parameter for
13408 // arguments to `inout` parameters, so we only traverse down the base
13409 // expression for `inout` cases.
13410 if (OutArgE->isInOut())
13411 WorkList.push_back(
13412 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13413 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13414 return;
13415 }
13416
13417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13418 // Do a somewhat different check with comparison operators.
13419 if (BO->isComparisonOp())
13420 return AnalyzeComparison(S, BO);
13421
13422 // And with simple assignments.
13423 if (BO->getOpcode() == BO_Assign)
13424 return AnalyzeAssignment(S, BO);
13425 // And with compound assignments.
13426 if (BO->isAssignmentOp())
13427 return AnalyzeCompoundAssignment(S, BO);
13428 }
13429
13430 // These break the otherwise-useful invariant below. Fortunately,
13431 // we don't really need to recurse into them, because any internal
13432 // expressions should have been analyzed already when they were
13433 // built into statements.
13434 if (isa<StmtExpr>(E)) return;
13435
13436 // Don't descend into unevaluated contexts.
13437 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13438
13439 // Now just recurse over the expression's children.
13440 CC = E->getExprLoc();
13441 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13442 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13443 for (Stmt *SubStmt : E->children()) {
13444 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13445 if (!ChildExpr)
13446 continue;
13447
13448 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13449 if (ChildExpr == CSE->getOperand())
13450 // Do not recurse over a CoroutineSuspendExpr's operand.
13451 // The operand is also a subexpression of getCommonExpr(), and
13452 // recursing into it directly would produce duplicate diagnostics.
13453 continue;
13454
13455 if (IsLogicalAndOperator &&
13457 // Ignore checking string literals that are in logical and operators.
13458 // This is a common pattern for asserts.
13459 continue;
13460 WorkList.push_back({ChildExpr, CC, IsListInit});
13461 }
13462
13463 if (BO && BO->isLogicalOp()) {
13464 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13465 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13466 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13467
13468 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13469 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13470 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13471 }
13472
13473 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13474 if (U->getOpcode() == UO_LNot) {
13475 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13476 } else if (U->getOpcode() != UO_AddrOf) {
13477 if (U->getSubExpr()->getType()->isAtomicType())
13478 S.Diag(U->getSubExpr()->getBeginLoc(),
13479 diag::warn_atomic_implicit_seq_cst);
13480 }
13481 }
13482}
13483
13484/// AnalyzeImplicitConversions - Find and report any interesting
13485/// implicit conversions in the given expression. There are a couple
13486/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13488 bool IsListInit/*= false*/) {
13490 WorkList.push_back({OrigE, CC, IsListInit});
13491 while (!WorkList.empty())
13492 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13493}
13494
13495// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13496// Returns true when emitting a warning about taking the address of a reference.
13497static bool CheckForReference(Sema &SemaRef, const Expr *E,
13498 const PartialDiagnostic &PD) {
13499 E = E->IgnoreParenImpCasts();
13500
13501 const FunctionDecl *FD = nullptr;
13502
13503 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13504 if (!DRE->getDecl()->getType()->isReferenceType())
13505 return false;
13506 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13507 if (!M->getMemberDecl()->getType()->isReferenceType())
13508 return false;
13509 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13510 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13511 return false;
13512 FD = Call->getDirectCallee();
13513 } else {
13514 return false;
13515 }
13516
13517 SemaRef.Diag(E->getExprLoc(), PD);
13518
13519 // If possible, point to location of function.
13520 if (FD) {
13521 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13522 }
13523
13524 return true;
13525}
13526
13527// Returns true if the SourceLocation is expanded from any macro body.
13528// Returns false if the SourceLocation is invalid, is from not in a macro
13529// expansion, or is from expanded from a top-level macro argument.
13531 if (Loc.isInvalid())
13532 return false;
13533
13534 while (Loc.isMacroID()) {
13535 if (SM.isMacroBodyExpansion(Loc))
13536 return true;
13537 Loc = SM.getImmediateMacroCallerLoc(Loc);
13538 }
13539
13540 return false;
13541}
13542
13545 bool IsEqual, SourceRange Range) {
13546 if (!E)
13547 return;
13548
13549 // Don't warn inside macros.
13550 if (E->getExprLoc().isMacroID()) {
13552 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13553 IsInAnyMacroBody(SM, Range.getBegin()))
13554 return;
13555 }
13556 E = E->IgnoreImpCasts();
13557
13558 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13559
13560 if (isa<CXXThisExpr>(E)) {
13561 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13562 : diag::warn_this_bool_conversion;
13563 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13564 return;
13565 }
13566
13567 bool IsAddressOf = false;
13568
13569 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13570 if (UO->getOpcode() != UO_AddrOf)
13571 return;
13572 IsAddressOf = true;
13573 E = UO->getSubExpr();
13574 }
13575
13576 if (IsAddressOf) {
13577 unsigned DiagID = IsCompare
13578 ? diag::warn_address_of_reference_null_compare
13579 : diag::warn_address_of_reference_bool_conversion;
13580 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13581 << IsEqual;
13582 if (CheckForReference(*this, E, PD)) {
13583 return;
13584 }
13585 }
13586
13587 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13588 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13589 std::string Str;
13590 llvm::raw_string_ostream S(Str);
13591 E->printPretty(S, nullptr, getPrintingPolicy());
13592 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13593 : diag::warn_cast_nonnull_to_bool;
13594 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13595 << E->getSourceRange() << Range << IsEqual;
13596 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13597 };
13598
13599 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13600 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13601 if (auto *Callee = Call->getDirectCallee()) {
13602 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13603 ComplainAboutNonnullParamOrCall(A);
13604 return;
13605 }
13606 }
13607 }
13608
13609 // Complain if we are converting a lambda expression to a boolean value
13610 // outside of instantiation.
13611 if (!inTemplateInstantiation()) {
13612 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13613 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13614 MRecordDecl && MRecordDecl->isLambda()) {
13615 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13616 << /*LambdaPointerConversionOperatorType=*/3
13617 << MRecordDecl->getSourceRange() << Range << IsEqual;
13618 return;
13619 }
13620 }
13621 }
13622
13623 // Expect to find a single Decl. Skip anything more complicated.
13624 ValueDecl *D = nullptr;
13625 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13626 D = R->getDecl();
13627 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13628 D = M->getMemberDecl();
13629 }
13630
13631 // Weak Decls can be null.
13632 if (!D || D->isWeak())
13633 return;
13634
13635 // Check for parameter decl with nonnull attribute
13636 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13637 if (getCurFunction() &&
13638 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13639 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13640 ComplainAboutNonnullParamOrCall(A);
13641 return;
13642 }
13643
13644 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13645 // Skip function template not specialized yet.
13647 return;
13648 auto ParamIter = llvm::find(FD->parameters(), PV);
13649 assert(ParamIter != FD->param_end());
13650 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13651
13652 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13653 if (!NonNull->args_size()) {
13654 ComplainAboutNonnullParamOrCall(NonNull);
13655 return;
13656 }
13657
13658 for (const ParamIdx &ArgNo : NonNull->args()) {
13659 if (ArgNo.getASTIndex() == ParamNo) {
13660 ComplainAboutNonnullParamOrCall(NonNull);
13661 return;
13662 }
13663 }
13664 }
13665 }
13666 }
13667 }
13668
13669 QualType T = D->getType();
13670 const bool IsArray = T->isArrayType();
13671 const bool IsFunction = T->isFunctionType();
13672
13673 // Address of function is used to silence the function warning.
13674 if (IsAddressOf && IsFunction) {
13675 return;
13676 }
13677
13678 // Found nothing.
13679 if (!IsAddressOf && !IsFunction && !IsArray)
13680 return;
13681
13682 // Pretty print the expression for the diagnostic.
13683 std::string Str;
13684 llvm::raw_string_ostream S(Str);
13685 E->printPretty(S, nullptr, getPrintingPolicy());
13686
13687 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13688 : diag::warn_impcast_pointer_to_bool;
13689 enum {
13690 AddressOf,
13691 FunctionPointer,
13692 ArrayPointer
13693 } DiagType;
13694 if (IsAddressOf)
13695 DiagType = AddressOf;
13696 else if (IsFunction)
13697 DiagType = FunctionPointer;
13698 else if (IsArray)
13699 DiagType = ArrayPointer;
13700 else
13701 llvm_unreachable("Could not determine diagnostic.");
13702 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13703 << Range << IsEqual;
13704
13705 if (!IsFunction)
13706 return;
13707
13708 // Suggest '&' to silence the function warning.
13709 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13711
13712 // Check to see if '()' fixit should be emitted.
13713 QualType ReturnType;
13714 UnresolvedSet<4> NonTemplateOverloads;
13715 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13716 if (ReturnType.isNull())
13717 return;
13718
13719 if (IsCompare) {
13720 // There are two cases here. If there is null constant, the only suggest
13721 // for a pointer return type. If the null is 0, then suggest if the return
13722 // type is a pointer or an integer type.
13723 if (!ReturnType->isPointerType()) {
13724 if (NullKind == Expr::NPCK_ZeroExpression ||
13725 NullKind == Expr::NPCK_ZeroLiteral) {
13726 if (!ReturnType->isIntegerType())
13727 return;
13728 } else {
13729 return;
13730 }
13731 }
13732 } else { // !IsCompare
13733 // For function to bool, only suggest if the function pointer has bool
13734 // return type.
13735 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13736 return;
13737 }
13738 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13740}
13741
13742void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13743 // Don't diagnose in unevaluated contexts.
13745 return;
13746
13747 // Don't diagnose for value- or type-dependent expressions.
13748 if (E->isTypeDependent() || E->isValueDependent())
13749 return;
13750
13751 // Check for array bounds violations in cases where the check isn't triggered
13752 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13753 // ArraySubscriptExpr is on the RHS of a variable initialization.
13754 CheckArrayAccess(E);
13755
13756 // This is not the right CC for (e.g.) a variable initialization.
13757 AnalyzeImplicitConversions(*this, E, CC);
13758}
13759
13760void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13761 ::CheckBoolLikeConversion(*this, E, CC);
13762}
13763
13764void Sema::CheckForIntOverflow (const Expr *E) {
13765 // Use a work list to deal with nested struct initializers.
13766 SmallVector<const Expr *, 2> Exprs(1, E);
13767
13768 do {
13769 const Expr *OriginalE = Exprs.pop_back_val();
13770 const Expr *E = OriginalE->IgnoreParenCasts();
13771
13774 continue;
13775 }
13776
13777 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13778 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13779 else if (isa<ObjCBoxedExpr>(OriginalE))
13781 else if (const auto *Call = dyn_cast<CallExpr>(E))
13782 Exprs.append(Call->arg_begin(), Call->arg_end());
13783 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13784 Exprs.append(Message->arg_begin(), Message->arg_end());
13785 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13786 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13787 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13788 Exprs.push_back(Temporary->getSubExpr());
13789 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13790 Exprs.push_back(Array->getIdx());
13791 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13792 Exprs.push_back(Compound->getInitializer());
13793 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13794 New && New->isArray()) {
13795 if (auto ArraySize = New->getArraySize())
13796 Exprs.push_back(*ArraySize);
13797 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13798 Exprs.push_back(MTE->getSubExpr());
13799 } while (!Exprs.empty());
13800}
13801
13802namespace {
13803
13804/// Visitor for expressions which looks for unsequenced operations on the
13805/// same object.
13806class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13807 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13808
13809 /// A tree of sequenced regions within an expression. Two regions are
13810 /// unsequenced if one is an ancestor or a descendent of the other. When we
13811 /// finish processing an expression with sequencing, such as a comma
13812 /// expression, we fold its tree nodes into its parent, since they are
13813 /// unsequenced with respect to nodes we will visit later.
13814 class SequenceTree {
13815 struct Value {
13816 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13817 unsigned Parent : 31;
13818 LLVM_PREFERRED_TYPE(bool)
13819 unsigned Merged : 1;
13820 };
13821 SmallVector<Value, 8> Values;
13822
13823 public:
13824 /// A region within an expression which may be sequenced with respect
13825 /// to some other region.
13826 class Seq {
13827 friend class SequenceTree;
13828
13829 unsigned Index;
13830
13831 explicit Seq(unsigned N) : Index(N) {}
13832
13833 public:
13834 Seq() : Index(0) {}
13835 };
13836
13837 SequenceTree() { Values.push_back(Value(0)); }
13838 Seq root() const { return Seq(0); }
13839
13840 /// Create a new sequence of operations, which is an unsequenced
13841 /// subset of \p Parent. This sequence of operations is sequenced with
13842 /// respect to other children of \p Parent.
13843 Seq allocate(Seq Parent) {
13844 Values.push_back(Value(Parent.Index));
13845 return Seq(Values.size() - 1);
13846 }
13847
13848 /// Merge a sequence of operations into its parent.
13849 void merge(Seq S) {
13850 Values[S.Index].Merged = true;
13851 }
13852
13853 /// Determine whether two operations are unsequenced. This operation
13854 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13855 /// should have been merged into its parent as appropriate.
13856 bool isUnsequenced(Seq Cur, Seq Old) {
13857 unsigned C = representative(Cur.Index);
13858 unsigned Target = representative(Old.Index);
13859 while (C >= Target) {
13860 if (C == Target)
13861 return true;
13862 C = Values[C].Parent;
13863 }
13864 return false;
13865 }
13866
13867 private:
13868 /// Pick a representative for a sequence.
13869 unsigned representative(unsigned K) {
13870 if (Values[K].Merged)
13871 // Perform path compression as we go.
13872 return Values[K].Parent = representative(Values[K].Parent);
13873 return K;
13874 }
13875 };
13876
13877 /// An object for which we can track unsequenced uses.
13878 using Object = const NamedDecl *;
13879
13880 /// Different flavors of object usage which we track. We only track the
13881 /// least-sequenced usage of each kind.
13882 enum UsageKind {
13883 /// A read of an object. Multiple unsequenced reads are OK.
13884 UK_Use,
13885
13886 /// A modification of an object which is sequenced before the value
13887 /// computation of the expression, such as ++n in C++.
13888 UK_ModAsValue,
13889
13890 /// A modification of an object which is not sequenced before the value
13891 /// computation of the expression, such as n++.
13892 UK_ModAsSideEffect,
13893
13894 UK_Count = UK_ModAsSideEffect + 1
13895 };
13896
13897 /// Bundle together a sequencing region and the expression corresponding
13898 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13899 struct Usage {
13900 const Expr *UsageExpr = nullptr;
13901 SequenceTree::Seq Seq;
13902
13903 Usage() = default;
13904 };
13905
13906 struct UsageInfo {
13907 Usage Uses[UK_Count];
13908
13909 /// Have we issued a diagnostic for this object already?
13910 bool Diagnosed = false;
13911
13912 UsageInfo();
13913 };
13914 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13915
13916 Sema &SemaRef;
13917
13918 /// Sequenced regions within the expression.
13919 SequenceTree Tree;
13920
13921 /// Declaration modifications and references which we have seen.
13922 UsageInfoMap UsageMap;
13923
13924 /// The region we are currently within.
13925 SequenceTree::Seq Region;
13926
13927 /// Filled in with declarations which were modified as a side-effect
13928 /// (that is, post-increment operations).
13929 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13930
13931 /// Expressions to check later. We defer checking these to reduce
13932 /// stack usage.
13933 SmallVectorImpl<const Expr *> &WorkList;
13934
13935 /// RAII object wrapping the visitation of a sequenced subexpression of an
13936 /// expression. At the end of this process, the side-effects of the evaluation
13937 /// become sequenced with respect to the value computation of the result, so
13938 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13939 /// UK_ModAsValue.
13940 struct SequencedSubexpression {
13941 SequencedSubexpression(SequenceChecker &Self)
13942 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13943 Self.ModAsSideEffect = &ModAsSideEffect;
13944 }
13945
13946 ~SequencedSubexpression() {
13947 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13948 // Add a new usage with usage kind UK_ModAsValue, and then restore
13949 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13950 // the previous one was empty).
13951 UsageInfo &UI = Self.UsageMap[M.first];
13952 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13953 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13954 SideEffectUsage = M.second;
13955 }
13956 Self.ModAsSideEffect = OldModAsSideEffect;
13957 }
13958
13959 SequenceChecker &Self;
13960 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13961 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13962 };
13963
13964 /// RAII object wrapping the visitation of a subexpression which we might
13965 /// choose to evaluate as a constant. If any subexpression is evaluated and
13966 /// found to be non-constant, this allows us to suppress the evaluation of
13967 /// the outer expression.
13968 class EvaluationTracker {
13969 public:
13970 EvaluationTracker(SequenceChecker &Self)
13971 : Self(Self), Prev(Self.EvalTracker) {
13972 Self.EvalTracker = this;
13973 }
13974
13975 ~EvaluationTracker() {
13976 Self.EvalTracker = Prev;
13977 if (Prev)
13978 Prev->EvalOK &= EvalOK;
13979 }
13980
13981 bool evaluate(const Expr *E, bool &Result) {
13982 if (!EvalOK || E->isValueDependent())
13983 return false;
13984 EvalOK = E->EvaluateAsBooleanCondition(
13985 Result, Self.SemaRef.Context,
13986 Self.SemaRef.isConstantEvaluatedContext());
13987 return EvalOK;
13988 }
13989
13990 private:
13991 SequenceChecker &Self;
13992 EvaluationTracker *Prev;
13993 bool EvalOK = true;
13994 } *EvalTracker = nullptr;
13995
13996 /// Find the object which is produced by the specified expression,
13997 /// if any.
13998 Object getObject(const Expr *E, bool Mod) const {
13999 E = E->IgnoreParenCasts();
14000 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14001 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14002 return getObject(UO->getSubExpr(), Mod);
14003 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14004 if (BO->getOpcode() == BO_Comma)
14005 return getObject(BO->getRHS(), Mod);
14006 if (Mod && BO->isAssignmentOp())
14007 return getObject(BO->getLHS(), Mod);
14008 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14009 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14010 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14011 return ME->getMemberDecl();
14012 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14013 // FIXME: If this is a reference, map through to its value.
14014 return DRE->getDecl();
14015 return nullptr;
14016 }
14017
14018 /// Note that an object \p O was modified or used by an expression
14019 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14020 /// the object \p O as obtained via the \p UsageMap.
14021 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14022 // Get the old usage for the given object and usage kind.
14023 Usage &U = UI.Uses[UK];
14024 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14025 // If we have a modification as side effect and are in a sequenced
14026 // subexpression, save the old Usage so that we can restore it later
14027 // in SequencedSubexpression::~SequencedSubexpression.
14028 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14029 ModAsSideEffect->push_back(std::make_pair(O, U));
14030 // Then record the new usage with the current sequencing region.
14031 U.UsageExpr = UsageExpr;
14032 U.Seq = Region;
14033 }
14034 }
14035
14036 /// Check whether a modification or use of an object \p O in an expression
14037 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14038 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14039 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14040 /// usage and false we are checking for a mod-use unsequenced usage.
14041 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14042 UsageKind OtherKind, bool IsModMod) {
14043 if (UI.Diagnosed)
14044 return;
14045
14046 const Usage &U = UI.Uses[OtherKind];
14047 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14048 return;
14049
14050 const Expr *Mod = U.UsageExpr;
14051 const Expr *ModOrUse = UsageExpr;
14052 if (OtherKind == UK_Use)
14053 std::swap(Mod, ModOrUse);
14054
14055 SemaRef.DiagRuntimeBehavior(
14056 Mod->getExprLoc(), {Mod, ModOrUse},
14057 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14058 : diag::warn_unsequenced_mod_use)
14059 << O << SourceRange(ModOrUse->getExprLoc()));
14060 UI.Diagnosed = true;
14061 }
14062
14063 // A note on note{Pre, Post}{Use, Mod}:
14064 //
14065 // (It helps to follow the algorithm with an expression such as
14066 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14067 // operations before C++17 and both are well-defined in C++17).
14068 //
14069 // When visiting a node which uses/modify an object we first call notePreUse
14070 // or notePreMod before visiting its sub-expression(s). At this point the
14071 // children of the current node have not yet been visited and so the eventual
14072 // uses/modifications resulting from the children of the current node have not
14073 // been recorded yet.
14074 //
14075 // We then visit the children of the current node. After that notePostUse or
14076 // notePostMod is called. These will 1) detect an unsequenced modification
14077 // as side effect (as in "k++ + k") and 2) add a new usage with the
14078 // appropriate usage kind.
14079 //
14080 // We also have to be careful that some operation sequences modification as
14081 // side effect as well (for example: || or ,). To account for this we wrap
14082 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14083 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14084 // which record usages which are modifications as side effect, and then
14085 // downgrade them (or more accurately restore the previous usage which was a
14086 // modification as side effect) when exiting the scope of the sequenced
14087 // subexpression.
14088
14089 void notePreUse(Object O, const Expr *UseExpr) {
14090 UsageInfo &UI = UsageMap[O];
14091 // Uses conflict with other modifications.
14092 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14093 }
14094
14095 void notePostUse(Object O, const Expr *UseExpr) {
14096 UsageInfo &UI = UsageMap[O];
14097 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14098 /*IsModMod=*/false);
14099 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14100 }
14101
14102 void notePreMod(Object O, const Expr *ModExpr) {
14103 UsageInfo &UI = UsageMap[O];
14104 // Modifications conflict with other modifications and with uses.
14105 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14106 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14107 }
14108
14109 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14110 UsageInfo &UI = UsageMap[O];
14111 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14112 /*IsModMod=*/true);
14113 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14114 }
14115
14116public:
14117 SequenceChecker(Sema &S, const Expr *E,
14118 SmallVectorImpl<const Expr *> &WorkList)
14119 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14120 Visit(E);
14121 // Silence a -Wunused-private-field since WorkList is now unused.
14122 // TODO: Evaluate if it can be used, and if not remove it.
14123 (void)this->WorkList;
14124 }
14125
14126 void VisitStmt(const Stmt *S) {
14127 // Skip all statements which aren't expressions for now.
14128 }
14129
14130 void VisitExpr(const Expr *E) {
14131 // By default, just recurse to evaluated subexpressions.
14132 Base::VisitStmt(E);
14133 }
14134
14135 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14136 for (auto *Sub : CSE->children()) {
14137 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14138 if (!ChildExpr)
14139 continue;
14140
14141 if (ChildExpr == CSE->getOperand())
14142 // Do not recurse over a CoroutineSuspendExpr's operand.
14143 // The operand is also a subexpression of getCommonExpr(), and
14144 // recursing into it directly could confuse object management
14145 // for the sake of sequence tracking.
14146 continue;
14147
14148 Visit(Sub);
14149 }
14150 }
14151
14152 void VisitCastExpr(const CastExpr *E) {
14153 Object O = Object();
14154 if (E->getCastKind() == CK_LValueToRValue)
14155 O = getObject(E->getSubExpr(), false);
14156
14157 if (O)
14158 notePreUse(O, E);
14159 VisitExpr(E);
14160 if (O)
14161 notePostUse(O, E);
14162 }
14163
14164 void VisitSequencedExpressions(const Expr *SequencedBefore,
14165 const Expr *SequencedAfter) {
14166 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14167 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14168 SequenceTree::Seq OldRegion = Region;
14169
14170 {
14171 SequencedSubexpression SeqBefore(*this);
14172 Region = BeforeRegion;
14173 Visit(SequencedBefore);
14174 }
14175
14176 Region = AfterRegion;
14177 Visit(SequencedAfter);
14178
14179 Region = OldRegion;
14180
14181 Tree.merge(BeforeRegion);
14182 Tree.merge(AfterRegion);
14183 }
14184
14185 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14186 // C++17 [expr.sub]p1:
14187 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14188 // expression E1 is sequenced before the expression E2.
14189 if (SemaRef.getLangOpts().CPlusPlus17)
14190 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14191 else {
14192 Visit(ASE->getLHS());
14193 Visit(ASE->getRHS());
14194 }
14195 }
14196
14197 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14198 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14199 void VisitBinPtrMem(const BinaryOperator *BO) {
14200 // C++17 [expr.mptr.oper]p4:
14201 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14202 // the expression E1 is sequenced before the expression E2.
14203 if (SemaRef.getLangOpts().CPlusPlus17)
14204 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14205 else {
14206 Visit(BO->getLHS());
14207 Visit(BO->getRHS());
14208 }
14209 }
14210
14211 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14212 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14213 void VisitBinShlShr(const BinaryOperator *BO) {
14214 // C++17 [expr.shift]p4:
14215 // The expression E1 is sequenced before the expression E2.
14216 if (SemaRef.getLangOpts().CPlusPlus17)
14217 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14218 else {
14219 Visit(BO->getLHS());
14220 Visit(BO->getRHS());
14221 }
14222 }
14223
14224 void VisitBinComma(const BinaryOperator *BO) {
14225 // C++11 [expr.comma]p1:
14226 // Every value computation and side effect associated with the left
14227 // expression is sequenced before every value computation and side
14228 // effect associated with the right expression.
14229 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14230 }
14231
14232 void VisitBinAssign(const BinaryOperator *BO) {
14233 SequenceTree::Seq RHSRegion;
14234 SequenceTree::Seq LHSRegion;
14235 if (SemaRef.getLangOpts().CPlusPlus17) {
14236 RHSRegion = Tree.allocate(Region);
14237 LHSRegion = Tree.allocate(Region);
14238 } else {
14239 RHSRegion = Region;
14240 LHSRegion = Region;
14241 }
14242 SequenceTree::Seq OldRegion = Region;
14243
14244 // C++11 [expr.ass]p1:
14245 // [...] the assignment is sequenced after the value computation
14246 // of the right and left operands, [...]
14247 //
14248 // so check it before inspecting the operands and update the
14249 // map afterwards.
14250 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14251 if (O)
14252 notePreMod(O, BO);
14253
14254 if (SemaRef.getLangOpts().CPlusPlus17) {
14255 // C++17 [expr.ass]p1:
14256 // [...] The right operand is sequenced before the left operand. [...]
14257 {
14258 SequencedSubexpression SeqBefore(*this);
14259 Region = RHSRegion;
14260 Visit(BO->getRHS());
14261 }
14262
14263 Region = LHSRegion;
14264 Visit(BO->getLHS());
14265
14266 if (O && isa<CompoundAssignOperator>(BO))
14267 notePostUse(O, BO);
14268
14269 } else {
14270 // C++11 does not specify any sequencing between the LHS and RHS.
14271 Region = LHSRegion;
14272 Visit(BO->getLHS());
14273
14274 if (O && isa<CompoundAssignOperator>(BO))
14275 notePostUse(O, BO);
14276
14277 Region = RHSRegion;
14278 Visit(BO->getRHS());
14279 }
14280
14281 // C++11 [expr.ass]p1:
14282 // the assignment is sequenced [...] before the value computation of the
14283 // assignment expression.
14284 // C11 6.5.16/3 has no such rule.
14285 Region = OldRegion;
14286 if (O)
14287 notePostMod(O, BO,
14288 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14289 : UK_ModAsSideEffect);
14290 if (SemaRef.getLangOpts().CPlusPlus17) {
14291 Tree.merge(RHSRegion);
14292 Tree.merge(LHSRegion);
14293 }
14294 }
14295
14296 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14297 VisitBinAssign(CAO);
14298 }
14299
14300 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14301 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14302 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14303 Object O = getObject(UO->getSubExpr(), true);
14304 if (!O)
14305 return VisitExpr(UO);
14306
14307 notePreMod(O, UO);
14308 Visit(UO->getSubExpr());
14309 // C++11 [expr.pre.incr]p1:
14310 // the expression ++x is equivalent to x+=1
14311 notePostMod(O, UO,
14312 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14313 : UK_ModAsSideEffect);
14314 }
14315
14316 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14317 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14318 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14319 Object O = getObject(UO->getSubExpr(), true);
14320 if (!O)
14321 return VisitExpr(UO);
14322
14323 notePreMod(O, UO);
14324 Visit(UO->getSubExpr());
14325 notePostMod(O, UO, UK_ModAsSideEffect);
14326 }
14327
14328 void VisitBinLOr(const BinaryOperator *BO) {
14329 // C++11 [expr.log.or]p2:
14330 // If the second expression is evaluated, every value computation and
14331 // side effect associated with the first expression is sequenced before
14332 // every value computation and side effect associated with the
14333 // second expression.
14334 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14335 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14336 SequenceTree::Seq OldRegion = Region;
14337
14338 EvaluationTracker Eval(*this);
14339 {
14340 SequencedSubexpression Sequenced(*this);
14341 Region = LHSRegion;
14342 Visit(BO->getLHS());
14343 }
14344
14345 // C++11 [expr.log.or]p1:
14346 // [...] the second operand is not evaluated if the first operand
14347 // evaluates to true.
14348 bool EvalResult = false;
14349 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14350 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14351 if (ShouldVisitRHS) {
14352 Region = RHSRegion;
14353 Visit(BO->getRHS());
14354 }
14355
14356 Region = OldRegion;
14357 Tree.merge(LHSRegion);
14358 Tree.merge(RHSRegion);
14359 }
14360
14361 void VisitBinLAnd(const BinaryOperator *BO) {
14362 // C++11 [expr.log.and]p2:
14363 // If the second expression is evaluated, every value computation and
14364 // side effect associated with the first expression is sequenced before
14365 // every value computation and side effect associated with the
14366 // second expression.
14367 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14368 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14369 SequenceTree::Seq OldRegion = Region;
14370
14371 EvaluationTracker Eval(*this);
14372 {
14373 SequencedSubexpression Sequenced(*this);
14374 Region = LHSRegion;
14375 Visit(BO->getLHS());
14376 }
14377
14378 // C++11 [expr.log.and]p1:
14379 // [...] the second operand is not evaluated if the first operand is false.
14380 bool EvalResult = false;
14381 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14382 bool ShouldVisitRHS = !EvalOK || EvalResult;
14383 if (ShouldVisitRHS) {
14384 Region = RHSRegion;
14385 Visit(BO->getRHS());
14386 }
14387
14388 Region = OldRegion;
14389 Tree.merge(LHSRegion);
14390 Tree.merge(RHSRegion);
14391 }
14392
14393 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14394 // C++11 [expr.cond]p1:
14395 // [...] Every value computation and side effect associated with the first
14396 // expression is sequenced before every value computation and side effect
14397 // associated with the second or third expression.
14398 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14399
14400 // No sequencing is specified between the true and false expression.
14401 // However since exactly one of both is going to be evaluated we can
14402 // consider them to be sequenced. This is needed to avoid warning on
14403 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14404 // both the true and false expressions because we can't evaluate x.
14405 // This will still allow us to detect an expression like (pre C++17)
14406 // "(x ? y += 1 : y += 2) = y".
14407 //
14408 // We don't wrap the visitation of the true and false expression with
14409 // SequencedSubexpression because we don't want to downgrade modifications
14410 // as side effect in the true and false expressions after the visition
14411 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14412 // not warn between the two "y++", but we should warn between the "y++"
14413 // and the "y".
14414 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14415 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14416 SequenceTree::Seq OldRegion = Region;
14417
14418 EvaluationTracker Eval(*this);
14419 {
14420 SequencedSubexpression Sequenced(*this);
14421 Region = ConditionRegion;
14422 Visit(CO->getCond());
14423 }
14424
14425 // C++11 [expr.cond]p1:
14426 // [...] The first expression is contextually converted to bool (Clause 4).
14427 // It is evaluated and if it is true, the result of the conditional
14428 // expression is the value of the second expression, otherwise that of the
14429 // third expression. Only one of the second and third expressions is
14430 // evaluated. [...]
14431 bool EvalResult = false;
14432 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14433 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14434 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14435 if (ShouldVisitTrueExpr) {
14436 Region = TrueRegion;
14437 Visit(CO->getTrueExpr());
14438 }
14439 if (ShouldVisitFalseExpr) {
14440 Region = FalseRegion;
14441 Visit(CO->getFalseExpr());
14442 }
14443
14444 Region = OldRegion;
14445 Tree.merge(ConditionRegion);
14446 Tree.merge(TrueRegion);
14447 Tree.merge(FalseRegion);
14448 }
14449
14450 void VisitCallExpr(const CallExpr *CE) {
14451 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14452
14453 if (CE->isUnevaluatedBuiltinCall(Context))
14454 return;
14455
14456 // C++11 [intro.execution]p15:
14457 // When calling a function [...], every value computation and side effect
14458 // associated with any argument expression, or with the postfix expression
14459 // designating the called function, is sequenced before execution of every
14460 // expression or statement in the body of the function [and thus before
14461 // the value computation of its result].
14462 SequencedSubexpression Sequenced(*this);
14463 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14464 // C++17 [expr.call]p5
14465 // The postfix-expression is sequenced before each expression in the
14466 // expression-list and any default argument. [...]
14467 SequenceTree::Seq CalleeRegion;
14468 SequenceTree::Seq OtherRegion;
14469 if (SemaRef.getLangOpts().CPlusPlus17) {
14470 CalleeRegion = Tree.allocate(Region);
14471 OtherRegion = Tree.allocate(Region);
14472 } else {
14473 CalleeRegion = Region;
14474 OtherRegion = Region;
14475 }
14476 SequenceTree::Seq OldRegion = Region;
14477
14478 // Visit the callee expression first.
14479 Region = CalleeRegion;
14480 if (SemaRef.getLangOpts().CPlusPlus17) {
14481 SequencedSubexpression Sequenced(*this);
14482 Visit(CE->getCallee());
14483 } else {
14484 Visit(CE->getCallee());
14485 }
14486
14487 // Then visit the argument expressions.
14488 Region = OtherRegion;
14489 for (const Expr *Argument : CE->arguments())
14490 Visit(Argument);
14491
14492 Region = OldRegion;
14493 if (SemaRef.getLangOpts().CPlusPlus17) {
14494 Tree.merge(CalleeRegion);
14495 Tree.merge(OtherRegion);
14496 }
14497 });
14498 }
14499
14500 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14501 // C++17 [over.match.oper]p2:
14502 // [...] the operator notation is first transformed to the equivalent
14503 // function-call notation as summarized in Table 12 (where @ denotes one
14504 // of the operators covered in the specified subclause). However, the
14505 // operands are sequenced in the order prescribed for the built-in
14506 // operator (Clause 8).
14507 //
14508 // From the above only overloaded binary operators and overloaded call
14509 // operators have sequencing rules in C++17 that we need to handle
14510 // separately.
14511 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14512 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14513 return VisitCallExpr(CXXOCE);
14514
14515 enum {
14516 NoSequencing,
14517 LHSBeforeRHS,
14518 RHSBeforeLHS,
14519 LHSBeforeRest
14520 } SequencingKind;
14521 switch (CXXOCE->getOperator()) {
14522 case OO_Equal:
14523 case OO_PlusEqual:
14524 case OO_MinusEqual:
14525 case OO_StarEqual:
14526 case OO_SlashEqual:
14527 case OO_PercentEqual:
14528 case OO_CaretEqual:
14529 case OO_AmpEqual:
14530 case OO_PipeEqual:
14531 case OO_LessLessEqual:
14532 case OO_GreaterGreaterEqual:
14533 SequencingKind = RHSBeforeLHS;
14534 break;
14535
14536 case OO_LessLess:
14537 case OO_GreaterGreater:
14538 case OO_AmpAmp:
14539 case OO_PipePipe:
14540 case OO_Comma:
14541 case OO_ArrowStar:
14542 case OO_Subscript:
14543 SequencingKind = LHSBeforeRHS;
14544 break;
14545
14546 case OO_Call:
14547 SequencingKind = LHSBeforeRest;
14548 break;
14549
14550 default:
14551 SequencingKind = NoSequencing;
14552 break;
14553 }
14554
14555 if (SequencingKind == NoSequencing)
14556 return VisitCallExpr(CXXOCE);
14557
14558 // This is a call, so all subexpressions are sequenced before the result.
14559 SequencedSubexpression Sequenced(*this);
14560
14561 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14562 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14563 "Should only get there with C++17 and above!");
14564 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14565 "Should only get there with an overloaded binary operator"
14566 " or an overloaded call operator!");
14567
14568 if (SequencingKind == LHSBeforeRest) {
14569 assert(CXXOCE->getOperator() == OO_Call &&
14570 "We should only have an overloaded call operator here!");
14571
14572 // This is very similar to VisitCallExpr, except that we only have the
14573 // C++17 case. The postfix-expression is the first argument of the
14574 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14575 // are in the following arguments.
14576 //
14577 // Note that we intentionally do not visit the callee expression since
14578 // it is just a decayed reference to a function.
14579 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14580 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14581 SequenceTree::Seq OldRegion = Region;
14582
14583 assert(CXXOCE->getNumArgs() >= 1 &&
14584 "An overloaded call operator must have at least one argument"
14585 " for the postfix-expression!");
14586 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14587 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14588 CXXOCE->getNumArgs() - 1);
14589
14590 // Visit the postfix-expression first.
14591 {
14592 Region = PostfixExprRegion;
14593 SequencedSubexpression Sequenced(*this);
14594 Visit(PostfixExpr);
14595 }
14596
14597 // Then visit the argument expressions.
14598 Region = ArgsRegion;
14599 for (const Expr *Arg : Args)
14600 Visit(Arg);
14601
14602 Region = OldRegion;
14603 Tree.merge(PostfixExprRegion);
14604 Tree.merge(ArgsRegion);
14605 } else {
14606 assert(CXXOCE->getNumArgs() == 2 &&
14607 "Should only have two arguments here!");
14608 assert((SequencingKind == LHSBeforeRHS ||
14609 SequencingKind == RHSBeforeLHS) &&
14610 "Unexpected sequencing kind!");
14611
14612 // We do not visit the callee expression since it is just a decayed
14613 // reference to a function.
14614 const Expr *E1 = CXXOCE->getArg(0);
14615 const Expr *E2 = CXXOCE->getArg(1);
14616 if (SequencingKind == RHSBeforeLHS)
14617 std::swap(E1, E2);
14618
14619 return VisitSequencedExpressions(E1, E2);
14620 }
14621 });
14622 }
14623
14624 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14625 // This is a call, so all subexpressions are sequenced before the result.
14626 SequencedSubexpression Sequenced(*this);
14627
14628 if (!CCE->isListInitialization())
14629 return VisitExpr(CCE);
14630
14631 // In C++11, list initializations are sequenced.
14632 SequenceExpressionsInOrder(
14633 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14634 }
14635
14636 void VisitInitListExpr(const InitListExpr *ILE) {
14637 if (!SemaRef.getLangOpts().CPlusPlus11)
14638 return VisitExpr(ILE);
14639
14640 // In C++11, list initializations are sequenced.
14641 SequenceExpressionsInOrder(ILE->inits());
14642 }
14643
14644 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14645 // C++20 parenthesized list initializations are sequenced. See C++20
14646 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14647 SequenceExpressionsInOrder(PLIE->getInitExprs());
14648 }
14649
14650private:
14651 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14653 SequenceTree::Seq Parent = Region;
14654 for (const Expr *E : ExpressionList) {
14655 if (!E)
14656 continue;
14657 Region = Tree.allocate(Parent);
14658 Elts.push_back(Region);
14659 Visit(E);
14660 }
14661
14662 // Forget that the initializers are sequenced.
14663 Region = Parent;
14664 for (unsigned I = 0; I < Elts.size(); ++I)
14665 Tree.merge(Elts[I]);
14666 }
14667};
14668
14669SequenceChecker::UsageInfo::UsageInfo() = default;
14670
14671} // namespace
14672
14673void Sema::CheckUnsequencedOperations(const Expr *E) {
14674 SmallVector<const Expr *, 8> WorkList;
14675 WorkList.push_back(E);
14676 while (!WorkList.empty()) {
14677 const Expr *Item = WorkList.pop_back_val();
14678 SequenceChecker(*this, Item, WorkList);
14679 }
14680}
14681
14682void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14683 bool IsConstexpr) {
14684 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14685 IsConstexpr || isa<ConstantExpr>(E));
14686 CheckImplicitConversions(E, CheckLoc);
14687 if (!E->isInstantiationDependent())
14688 CheckUnsequencedOperations(E);
14689 if (!IsConstexpr && !E->isValueDependent())
14690 CheckForIntOverflow(E);
14691}
14692
14693void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14694 FieldDecl *BitField,
14695 Expr *Init) {
14696 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14697}
14698
14700 SourceLocation Loc) {
14701 if (!PType->isVariablyModifiedType())
14702 return;
14703 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14704 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14705 return;
14706 }
14707 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14708 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14709 return;
14710 }
14711 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14712 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14713 return;
14714 }
14715
14716 const ArrayType *AT = S.Context.getAsArrayType(PType);
14717 if (!AT)
14718 return;
14719
14722 return;
14723 }
14724
14725 S.Diag(Loc, diag::err_array_star_in_function_definition);
14726}
14727
14729 bool CheckParameterNames) {
14730 bool HasInvalidParm = false;
14731 for (ParmVarDecl *Param : Parameters) {
14732 assert(Param && "null in a parameter list");
14733 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14734 // function declarator that is part of a function definition of
14735 // that function shall not have incomplete type.
14736 //
14737 // C++23 [dcl.fct.def.general]/p2
14738 // The type of a parameter [...] for a function definition
14739 // shall not be a (possibly cv-qualified) class type that is incomplete
14740 // or abstract within the function body unless the function is deleted.
14741 if (!Param->isInvalidDecl() &&
14742 (RequireCompleteType(Param->getLocation(), Param->getType(),
14743 diag::err_typecheck_decl_incomplete_type) ||
14744 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14745 diag::err_abstract_type_in_decl,
14747 Param->setInvalidDecl();
14748 HasInvalidParm = true;
14749 }
14750
14751 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14752 // declaration of each parameter shall include an identifier.
14753 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14754 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14755 // Diagnose this as an extension in C17 and earlier.
14756 if (!getLangOpts().C23)
14757 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14758 }
14759
14760 // C99 6.7.5.3p12:
14761 // If the function declarator is not part of a definition of that
14762 // function, parameters may have incomplete type and may use the [*]
14763 // notation in their sequences of declarator specifiers to specify
14764 // variable length array types.
14765 QualType PType = Param->getOriginalType();
14766 // FIXME: This diagnostic should point the '[*]' if source-location
14767 // information is added for it.
14768 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14769
14770 // If the parameter is a c++ class type and it has to be destructed in the
14771 // callee function, declare the destructor so that it can be called by the
14772 // callee function. Do not perform any direct access check on the dtor here.
14773 if (!Param->isInvalidDecl()) {
14774 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14775 if (!ClassDecl->isInvalidDecl() &&
14776 !ClassDecl->hasIrrelevantDestructor() &&
14777 !ClassDecl->isDependentContext() &&
14778 ClassDecl->isParamDestroyedInCallee()) {
14780 MarkFunctionReferenced(Param->getLocation(), Destructor);
14781 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14782 }
14783 }
14784 }
14785
14786 // Parameters with the pass_object_size attribute only need to be marked
14787 // constant at function definitions. Because we lack information about
14788 // whether we're on a declaration or definition when we're instantiating the
14789 // attribute, we need to check for constness here.
14790 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14791 if (!Param->getType().isConstQualified())
14792 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14793 << Attr->getSpelling() << 1;
14794
14795 // Check for parameter names shadowing fields from the class.
14796 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14797 // The owning context for the parameter should be the function, but we
14798 // want to see if this function's declaration context is a record.
14799 DeclContext *DC = Param->getDeclContext();
14800 if (DC && DC->isFunctionOrMethod()) {
14801 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14802 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14803 RD, /*DeclIsField*/ false);
14804 }
14805 }
14806
14807 if (!Param->isInvalidDecl() &&
14808 Param->getOriginalType()->isWebAssemblyTableType()) {
14809 Param->setInvalidDecl();
14810 HasInvalidParm = true;
14811 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14812 }
14813 }
14814
14815 return HasInvalidParm;
14816}
14817
14818std::optional<std::pair<
14820 *E,
14822 &Ctx);
14823
14824/// Compute the alignment and offset of the base class object given the
14825/// derived-to-base cast expression and the alignment and offset of the derived
14826/// class object.
14827static std::pair<CharUnits, CharUnits>
14829 CharUnits BaseAlignment, CharUnits Offset,
14830 ASTContext &Ctx) {
14831 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14832 ++PathI) {
14833 const CXXBaseSpecifier *Base = *PathI;
14834 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14835 if (Base->isVirtual()) {
14836 // The complete object may have a lower alignment than the non-virtual
14837 // alignment of the base, in which case the base may be misaligned. Choose
14838 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14839 // conservative lower bound of the complete object alignment.
14840 CharUnits NonVirtualAlignment =
14842 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14843 Offset = CharUnits::Zero();
14844 } else {
14845 const ASTRecordLayout &RL =
14846 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14847 Offset += RL.getBaseClassOffset(BaseDecl);
14848 }
14849 DerivedType = Base->getType();
14850 }
14851
14852 return std::make_pair(BaseAlignment, Offset);
14853}
14854
14855/// Compute the alignment and offset of a binary additive operator.
14856static std::optional<std::pair<CharUnits, CharUnits>>
14858 bool IsSub, ASTContext &Ctx) {
14859 QualType PointeeType = PtrE->getType()->getPointeeType();
14860
14861 if (!PointeeType->isConstantSizeType())
14862 return std::nullopt;
14863
14864 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14865
14866 if (!P)
14867 return std::nullopt;
14868
14869 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14870 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14871 CharUnits Offset = EltSize * IdxRes->getExtValue();
14872 if (IsSub)
14873 Offset = -Offset;
14874 return std::make_pair(P->first, P->second + Offset);
14875 }
14876
14877 // If the integer expression isn't a constant expression, compute the lower
14878 // bound of the alignment using the alignment and offset of the pointer
14879 // expression and the element size.
14880 return std::make_pair(
14881 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14882 CharUnits::Zero());
14883}
14884
14885/// This helper function takes an lvalue expression and returns the alignment of
14886/// a VarDecl and a constant offset from the VarDecl.
14887std::optional<std::pair<
14888 CharUnits,
14890 ASTContext &Ctx) {
14891 E = E->IgnoreParens();
14892 switch (E->getStmtClass()) {
14893 default:
14894 break;
14895 case Stmt::CStyleCastExprClass:
14896 case Stmt::CXXStaticCastExprClass:
14897 case Stmt::ImplicitCastExprClass: {
14898 auto *CE = cast<CastExpr>(E);
14899 const Expr *From = CE->getSubExpr();
14900 switch (CE->getCastKind()) {
14901 default:
14902 break;
14903 case CK_NoOp:
14904 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14905 case CK_UncheckedDerivedToBase:
14906 case CK_DerivedToBase: {
14907 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14908 if (!P)
14909 break;
14910 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14911 P->second, Ctx);
14912 }
14913 }
14914 break;
14915 }
14916 case Stmt::ArraySubscriptExprClass: {
14917 auto *ASE = cast<ArraySubscriptExpr>(E);
14919 false, Ctx);
14920 }
14921 case Stmt::DeclRefExprClass: {
14922 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14923 // FIXME: If VD is captured by copy or is an escaping __block variable,
14924 // use the alignment of VD's type.
14925 if (!VD->getType()->isReferenceType()) {
14926 // Dependent alignment cannot be resolved -> bail out.
14927 if (VD->hasDependentAlignment())
14928 break;
14929 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14930 }
14931 if (VD->hasInit())
14932 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14933 }
14934 break;
14935 }
14936 case Stmt::MemberExprClass: {
14937 auto *ME = cast<MemberExpr>(E);
14938 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14939 if (!FD || FD->getType()->isReferenceType() ||
14940 FD->getParent()->isInvalidDecl())
14941 break;
14942 std::optional<std::pair<CharUnits, CharUnits>> P;
14943 if (ME->isArrow())
14944 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14945 else
14946 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14947 if (!P)
14948 break;
14949 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14950 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14951 return std::make_pair(P->first,
14952 P->second + CharUnits::fromQuantity(Offset));
14953 }
14954 case Stmt::UnaryOperatorClass: {
14955 auto *UO = cast<UnaryOperator>(E);
14956 switch (UO->getOpcode()) {
14957 default:
14958 break;
14959 case UO_Deref:
14961 }
14962 break;
14963 }
14964 case Stmt::BinaryOperatorClass: {
14965 auto *BO = cast<BinaryOperator>(E);
14966 auto Opcode = BO->getOpcode();
14967 switch (Opcode) {
14968 default:
14969 break;
14970 case BO_Comma:
14972 }
14973 break;
14974 }
14975 }
14976 return std::nullopt;
14977}
14978
14979/// This helper function takes a pointer expression and returns the alignment of
14980/// a VarDecl and a constant offset from the VarDecl.
14981std::optional<std::pair<
14983 *E,
14985 &Ctx) {
14986 E = E->IgnoreParens();
14987 switch (E->getStmtClass()) {
14988 default:
14989 break;
14990 case Stmt::CStyleCastExprClass:
14991 case Stmt::CXXStaticCastExprClass:
14992 case Stmt::ImplicitCastExprClass: {
14993 auto *CE = cast<CastExpr>(E);
14994 const Expr *From = CE->getSubExpr();
14995 switch (CE->getCastKind()) {
14996 default:
14997 break;
14998 case CK_NoOp:
14999 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15000 case CK_ArrayToPointerDecay:
15001 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15002 case CK_UncheckedDerivedToBase:
15003 case CK_DerivedToBase: {
15004 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15005 if (!P)
15006 break;
15008 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15009 }
15010 }
15011 break;
15012 }
15013 case Stmt::CXXThisExprClass: {
15014 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15016 return std::make_pair(Alignment, CharUnits::Zero());
15017 }
15018 case Stmt::UnaryOperatorClass: {
15019 auto *UO = cast<UnaryOperator>(E);
15020 if (UO->getOpcode() == UO_AddrOf)
15022 break;
15023 }
15024 case Stmt::BinaryOperatorClass: {
15025 auto *BO = cast<BinaryOperator>(E);
15026 auto Opcode = BO->getOpcode();
15027 switch (Opcode) {
15028 default:
15029 break;
15030 case BO_Add:
15031 case BO_Sub: {
15032 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15033 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15034 std::swap(LHS, RHS);
15035 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15036 Ctx);
15037 }
15038 case BO_Comma:
15039 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15040 }
15041 break;
15042 }
15043 }
15044 return std::nullopt;
15045}
15046
15048 // See if we can compute the alignment of a VarDecl and an offset from it.
15049 std::optional<std::pair<CharUnits, CharUnits>> P =
15051
15052 if (P)
15053 return P->first.alignmentAtOffset(P->second);
15054
15055 // If that failed, return the type's alignment.
15057}
15058
15060 // This is actually a lot of work to potentially be doing on every
15061 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15062 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15063 return;
15064
15065 // Ignore dependent types.
15066 if (T->isDependentType() || Op->getType()->isDependentType())
15067 return;
15068
15069 // Require that the destination be a pointer type.
15070 const PointerType *DestPtr = T->getAs<PointerType>();
15071 if (!DestPtr) return;
15072
15073 // If the destination has alignment 1, we're done.
15074 QualType DestPointee = DestPtr->getPointeeType();
15075 if (DestPointee->isIncompleteType()) return;
15076 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15077 if (DestAlign.isOne()) return;
15078
15079 // Require that the source be a pointer type.
15080 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15081 if (!SrcPtr) return;
15082 QualType SrcPointee = SrcPtr->getPointeeType();
15083
15084 // Explicitly allow casts from cv void*. We already implicitly
15085 // allowed casts to cv void*, since they have alignment 1.
15086 // Also allow casts involving incomplete types, which implicitly
15087 // includes 'void'.
15088 if (SrcPointee->isIncompleteType()) return;
15089
15090 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15091
15092 if (SrcAlign >= DestAlign) return;
15093
15094 Diag(TRange.getBegin(), diag::warn_cast_align)
15095 << Op->getType() << T
15096 << static_cast<unsigned>(SrcAlign.getQuantity())
15097 << static_cast<unsigned>(DestAlign.getQuantity())
15098 << TRange << Op->getSourceRange();
15099}
15100
15101void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15102 const ArraySubscriptExpr *ASE,
15103 bool AllowOnePastEnd, bool IndexNegated) {
15104 // Already diagnosed by the constant evaluator.
15106 return;
15107
15108 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15109 if (IndexExpr->isValueDependent())
15110 return;
15111
15112 const Type *EffectiveType =
15114 BaseExpr = BaseExpr->IgnoreParenCasts();
15115 const ConstantArrayType *ArrayTy =
15116 Context.getAsConstantArrayType(BaseExpr->getType());
15117
15119 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15120
15121 const Type *BaseType =
15122 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15123 bool IsUnboundedArray =
15124 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15125 Context, StrictFlexArraysLevel,
15126 /*IgnoreTemplateOrMacroSubstitution=*/true);
15127 if (EffectiveType->isDependentType() ||
15128 (!IsUnboundedArray && BaseType->isDependentType()))
15129 return;
15130
15132 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15133 return;
15134
15135 llvm::APSInt index = Result.Val.getInt();
15136 if (IndexNegated) {
15137 index.setIsUnsigned(false);
15138 index = -index;
15139 }
15140
15141 if (IsUnboundedArray) {
15142 if (EffectiveType->isFunctionType())
15143 return;
15144 if (index.isUnsigned() || !index.isNegative()) {
15145 const auto &ASTC = getASTContext();
15146 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15147 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15148 if (index.getBitWidth() < AddrBits)
15149 index = index.zext(AddrBits);
15150 std::optional<CharUnits> ElemCharUnits =
15151 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15152 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15153 // pointer) bounds-checking isn't meaningful.
15154 if (!ElemCharUnits || ElemCharUnits->isZero())
15155 return;
15156 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15157 // If index has more active bits than address space, we already know
15158 // we have a bounds violation to warn about. Otherwise, compute
15159 // address of (index + 1)th element, and warn about bounds violation
15160 // only if that address exceeds address space.
15161 if (index.getActiveBits() <= AddrBits) {
15162 bool Overflow;
15163 llvm::APInt Product(index);
15164 Product += 1;
15165 Product = Product.umul_ov(ElemBytes, Overflow);
15166 if (!Overflow && Product.getActiveBits() <= AddrBits)
15167 return;
15168 }
15169
15170 // Need to compute max possible elements in address space, since that
15171 // is included in diag message.
15172 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15173 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15174 MaxElems += 1;
15175 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15176 MaxElems = MaxElems.udiv(ElemBytes);
15177
15178 unsigned DiagID =
15179 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15180 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15181
15182 // Diag message shows element size in bits and in "bytes" (platform-
15183 // dependent CharUnits)
15184 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15185 PDiag(DiagID) << index << AddrBits
15186 << (unsigned)ASTC.toBits(*ElemCharUnits)
15187 << ElemBytes << MaxElems
15188 << MaxElems.getZExtValue()
15189 << IndexExpr->getSourceRange());
15190
15191 const NamedDecl *ND = nullptr;
15192 // Try harder to find a NamedDecl to point at in the note.
15193 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15194 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15195 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15196 ND = DRE->getDecl();
15197 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15198 ND = ME->getMemberDecl();
15199
15200 if (ND)
15201 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15202 PDiag(diag::note_array_declared_here) << ND);
15203 }
15204 return;
15205 }
15206
15207 if (index.isUnsigned() || !index.isNegative()) {
15208 // It is possible that the type of the base expression after
15209 // IgnoreParenCasts is incomplete, even though the type of the base
15210 // expression before IgnoreParenCasts is complete (see PR39746 for an
15211 // example). In this case we have no information about whether the array
15212 // access exceeds the array bounds. However we can still diagnose an array
15213 // access which precedes the array bounds.
15214 if (BaseType->isIncompleteType())
15215 return;
15216
15217 llvm::APInt size = ArrayTy->getSize();
15218
15219 if (BaseType != EffectiveType) {
15220 // Make sure we're comparing apples to apples when comparing index to
15221 // size.
15222 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15223 uint64_t array_typesize = Context.getTypeSize(BaseType);
15224
15225 // Handle ptrarith_typesize being zero, such as when casting to void*.
15226 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15227 if (!ptrarith_typesize)
15228 ptrarith_typesize = Context.getCharWidth();
15229
15230 if (ptrarith_typesize != array_typesize) {
15231 // There's a cast to a different size type involved.
15232 uint64_t ratio = array_typesize / ptrarith_typesize;
15233
15234 // TODO: Be smarter about handling cases where array_typesize is not a
15235 // multiple of ptrarith_typesize.
15236 if (ptrarith_typesize * ratio == array_typesize)
15237 size *= llvm::APInt(size.getBitWidth(), ratio);
15238 }
15239 }
15240
15241 if (size.getBitWidth() > index.getBitWidth())
15242 index = index.zext(size.getBitWidth());
15243 else if (size.getBitWidth() < index.getBitWidth())
15244 size = size.zext(index.getBitWidth());
15245
15246 // For array subscripting the index must be less than size, but for pointer
15247 // arithmetic also allow the index (offset) to be equal to size since
15248 // computing the next address after the end of the array is legal and
15249 // commonly done e.g. in C++ iterators and range-based for loops.
15250 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15251 return;
15252
15253 // Suppress the warning if the subscript expression (as identified by the
15254 // ']' location) and the index expression are both from macro expansions
15255 // within a system header.
15256 if (ASE) {
15257 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15258 ASE->getRBracketLoc());
15259 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15260 SourceLocation IndexLoc =
15261 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15262 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15263 return;
15264 }
15265 }
15266
15267 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15268 : diag::warn_ptr_arith_exceeds_bounds;
15269 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15270 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15271
15272 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15273 PDiag(DiagID)
15274 << index << ArrayTy->desugar() << CastMsg
15275 << CastMsgTy << IndexExpr->getSourceRange());
15276 } else {
15277 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15278 if (!ASE) {
15279 DiagID = diag::warn_ptr_arith_precedes_bounds;
15280 if (index.isNegative()) index = -index;
15281 }
15282
15283 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15284 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15285 }
15286
15287 const NamedDecl *ND = nullptr;
15288 // Try harder to find a NamedDecl to point at in the note.
15289 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15290 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15291 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15292 ND = DRE->getDecl();
15293 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15294 ND = ME->getMemberDecl();
15295
15296 if (ND)
15297 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15298 PDiag(diag::note_array_declared_here) << ND);
15299}
15300
15301void Sema::CheckArrayAccess(const Expr *expr) {
15302 int AllowOnePastEnd = 0;
15303 while (expr) {
15304 expr = expr->IgnoreParenImpCasts();
15305 switch (expr->getStmtClass()) {
15306 case Stmt::ArraySubscriptExprClass: {
15307 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15308 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15309 AllowOnePastEnd > 0);
15310 expr = ASE->getBase();
15311 break;
15312 }
15313 case Stmt::MemberExprClass: {
15314 expr = cast<MemberExpr>(expr)->getBase();
15315 break;
15316 }
15317 case Stmt::ArraySectionExprClass: {
15318 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15319 // FIXME: We should probably be checking all of the elements to the
15320 // 'length' here as well.
15321 if (ASE->getLowerBound())
15322 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15323 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15324 return;
15325 }
15326 case Stmt::UnaryOperatorClass: {
15327 // Only unwrap the * and & unary operators
15328 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15329 expr = UO->getSubExpr();
15330 switch (UO->getOpcode()) {
15331 case UO_AddrOf:
15332 AllowOnePastEnd++;
15333 break;
15334 case UO_Deref:
15335 AllowOnePastEnd--;
15336 break;
15337 default:
15338 return;
15339 }
15340 break;
15341 }
15342 case Stmt::ConditionalOperatorClass: {
15343 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15344 if (const Expr *lhs = cond->getLHS())
15345 CheckArrayAccess(lhs);
15346 if (const Expr *rhs = cond->getRHS())
15347 CheckArrayAccess(rhs);
15348 return;
15349 }
15350 case Stmt::CXXOperatorCallExprClass: {
15351 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15352 for (const auto *Arg : OCE->arguments())
15353 CheckArrayAccess(Arg);
15354 return;
15355 }
15356 default:
15357 return;
15358 }
15359 }
15360}
15361
15363 Expr *RHS, bool isProperty) {
15364 // Check if RHS is an Objective-C object literal, which also can get
15365 // immediately zapped in a weak reference. Note that we explicitly
15366 // allow ObjCStringLiterals, since those are designed to never really die.
15367 RHS = RHS->IgnoreParenImpCasts();
15368
15369 // This enum needs to match with the 'select' in
15370 // warn_objc_arc_literal_assign (off-by-1).
15372 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15373 return false;
15374
15375 S.Diag(Loc, diag::warn_arc_literal_assign)
15376 << (unsigned) Kind
15377 << (isProperty ? 0 : 1)
15378 << RHS->getSourceRange();
15379
15380 return true;
15381}
15382
15385 Expr *RHS, bool isProperty) {
15386 // Strip off any implicit cast added to get to the one ARC-specific.
15387 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15388 if (cast->getCastKind() == CK_ARCConsumeObject) {
15389 S.Diag(Loc, diag::warn_arc_retained_assign)
15391 << (isProperty ? 0 : 1)
15392 << RHS->getSourceRange();
15393 return true;
15394 }
15395 RHS = cast->getSubExpr();
15396 }
15397
15398 if (LT == Qualifiers::OCL_Weak &&
15399 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15400 return true;
15401
15402 return false;
15403}
15404
15406 QualType LHS, Expr *RHS) {
15408
15410 return false;
15411
15412 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15413 return true;
15414
15415 return false;
15416}
15417
15419 Expr *LHS, Expr *RHS) {
15420 QualType LHSType;
15421 // PropertyRef on LHS type need be directly obtained from
15422 // its declaration as it has a PseudoType.
15424 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15425 if (PRE && !PRE->isImplicitProperty()) {
15426 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15427 if (PD)
15428 LHSType = PD->getType();
15429 }
15430
15431 if (LHSType.isNull())
15432 LHSType = LHS->getType();
15433
15435
15436 if (LT == Qualifiers::OCL_Weak) {
15437 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15439 }
15440
15441 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15442 return;
15443
15444 // FIXME. Check for other life times.
15445 if (LT != Qualifiers::OCL_None)
15446 return;
15447
15448 if (PRE) {
15449 if (PRE->isImplicitProperty())
15450 return;
15451 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15452 if (!PD)
15453 return;
15454
15455 unsigned Attributes = PD->getPropertyAttributes();
15456 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15457 // when 'assign' attribute was not explicitly specified
15458 // by user, ignore it and rely on property type itself
15459 // for lifetime info.
15460 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15461 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15462 LHSType->isObjCRetainableType())
15463 return;
15464
15465 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15466 if (cast->getCastKind() == CK_ARCConsumeObject) {
15467 Diag(Loc, diag::warn_arc_retained_property_assign)
15468 << RHS->getSourceRange();
15469 return;
15470 }
15471 RHS = cast->getSubExpr();
15472 }
15473 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15474 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15475 return;
15476 }
15477 }
15478}
15479
15480//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15481
15482static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15483 SourceLocation StmtLoc,
15484 const NullStmt *Body) {
15485 // Do not warn if the body is a macro that expands to nothing, e.g:
15486 //
15487 // #define CALL(x)
15488 // if (condition)
15489 // CALL(0);
15490 if (Body->hasLeadingEmptyMacro())
15491 return false;
15492
15493 // Get line numbers of statement and body.
15494 bool StmtLineInvalid;
15495 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15496 &StmtLineInvalid);
15497 if (StmtLineInvalid)
15498 return false;
15499
15500 bool BodyLineInvalid;
15501 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15502 &BodyLineInvalid);
15503 if (BodyLineInvalid)
15504 return false;
15505
15506 // Warn if null statement and body are on the same line.
15507 if (StmtLine != BodyLine)
15508 return false;
15509
15510 return true;
15511}
15512
15514 const Stmt *Body,
15515 unsigned DiagID) {
15516 // Since this is a syntactic check, don't emit diagnostic for template
15517 // instantiations, this just adds noise.
15519 return;
15520
15521 // The body should be a null statement.
15522 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15523 if (!NBody)
15524 return;
15525
15526 // Do the usual checks.
15527 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15528 return;
15529
15530 Diag(NBody->getSemiLoc(), DiagID);
15531 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15532}
15533
15535 const Stmt *PossibleBody) {
15536 assert(!CurrentInstantiationScope); // Ensured by caller
15537
15538 SourceLocation StmtLoc;
15539 const Stmt *Body;
15540 unsigned DiagID;
15541 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15542 StmtLoc = FS->getRParenLoc();
15543 Body = FS->getBody();
15544 DiagID = diag::warn_empty_for_body;
15545 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15546 StmtLoc = WS->getRParenLoc();
15547 Body = WS->getBody();
15548 DiagID = diag::warn_empty_while_body;
15549 } else
15550 return; // Neither `for' nor `while'.
15551
15552 // The body should be a null statement.
15553 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15554 if (!NBody)
15555 return;
15556
15557 // Skip expensive checks if diagnostic is disabled.
15558 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15559 return;
15560
15561 // Do the usual checks.
15562 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15563 return;
15564
15565 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15566 // noise level low, emit diagnostics only if for/while is followed by a
15567 // CompoundStmt, e.g.:
15568 // for (int i = 0; i < n; i++);
15569 // {
15570 // a(i);
15571 // }
15572 // or if for/while is followed by a statement with more indentation
15573 // than for/while itself:
15574 // for (int i = 0; i < n; i++);
15575 // a(i);
15576 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15577 if (!ProbableTypo) {
15578 bool BodyColInvalid;
15579 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15580 PossibleBody->getBeginLoc(), &BodyColInvalid);
15581 if (BodyColInvalid)
15582 return;
15583
15584 bool StmtColInvalid;
15585 unsigned StmtCol =
15586 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15587 if (StmtColInvalid)
15588 return;
15589
15590 if (BodyCol > StmtCol)
15591 ProbableTypo = true;
15592 }
15593
15594 if (ProbableTypo) {
15595 Diag(NBody->getSemiLoc(), DiagID);
15596 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15597 }
15598}
15599
15600//===--- CHECK: Warn on self move with std::move. -------------------------===//
15601
15602void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15603 SourceLocation OpLoc) {
15604 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15605 return;
15606
15608 return;
15609
15610 // Strip parens and casts away.
15611 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15612 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15613
15614 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15615 // which we can treat as an inlined std::move
15616 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15617 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15618 RHSExpr = CE->getArg(0);
15619 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15620 CXXSCE && CXXSCE->isXValue())
15621 RHSExpr = CXXSCE->getSubExpr();
15622 else
15623 return;
15624
15625 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15626 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15627
15628 // Two DeclRefExpr's, check that the decls are the same.
15629 if (LHSDeclRef && RHSDeclRef) {
15630 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15631 return;
15632 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15633 RHSDeclRef->getDecl()->getCanonicalDecl())
15634 return;
15635
15636 auto D = Diag(OpLoc, diag::warn_self_move)
15637 << LHSExpr->getType() << LHSExpr->getSourceRange()
15638 << RHSExpr->getSourceRange();
15639 if (const FieldDecl *F =
15641 D << 1 << F
15642 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15643 else
15644 D << 0;
15645 return;
15646 }
15647
15648 // Member variables require a different approach to check for self moves.
15649 // MemberExpr's are the same if every nested MemberExpr refers to the same
15650 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15651 // the base Expr's are CXXThisExpr's.
15652 const Expr *LHSBase = LHSExpr;
15653 const Expr *RHSBase = RHSExpr;
15654 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15655 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15656 if (!LHSME || !RHSME)
15657 return;
15658
15659 while (LHSME && RHSME) {
15660 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15661 RHSME->getMemberDecl()->getCanonicalDecl())
15662 return;
15663
15664 LHSBase = LHSME->getBase();
15665 RHSBase = RHSME->getBase();
15666 LHSME = dyn_cast<MemberExpr>(LHSBase);
15667 RHSME = dyn_cast<MemberExpr>(RHSBase);
15668 }
15669
15670 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15671 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15672 if (LHSDeclRef && RHSDeclRef) {
15673 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15674 return;
15675 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15676 RHSDeclRef->getDecl()->getCanonicalDecl())
15677 return;
15678
15679 Diag(OpLoc, diag::warn_self_move)
15680 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15681 << RHSExpr->getSourceRange();
15682 return;
15683 }
15684
15685 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15686 Diag(OpLoc, diag::warn_self_move)
15687 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15688 << RHSExpr->getSourceRange();
15689}
15690
15691//===--- Layout compatibility ----------------------------------------------//
15692
15693static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15694
15695/// Check if two enumeration types are layout-compatible.
15696static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15697 const EnumDecl *ED2) {
15698 // C++11 [dcl.enum] p8:
15699 // Two enumeration types are layout-compatible if they have the same
15700 // underlying type.
15701 return ED1->isComplete() && ED2->isComplete() &&
15702 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15703}
15704
15705/// Check if two fields are layout-compatible.
15706/// Can be used on union members, which are exempt from alignment requirement
15707/// of common initial sequence.
15708static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15709 const FieldDecl *Field2,
15710 bool AreUnionMembers = false) {
15711#ifndef NDEBUG
15712 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15713 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15714 assert(((Field1Parent->isStructureOrClassType() &&
15715 Field2Parent->isStructureOrClassType()) ||
15716 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15717 "Can't evaluate layout compatibility between a struct field and a "
15718 "union field.");
15719 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15720 (AreUnionMembers && Field1Parent->isUnionType())) &&
15721 "AreUnionMembers should be 'true' for union fields (only).");
15722#endif
15723
15724 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15725 return false;
15726
15727 if (Field1->isBitField() != Field2->isBitField())
15728 return false;
15729
15730 if (Field1->isBitField()) {
15731 // Make sure that the bit-fields are the same length.
15732 unsigned Bits1 = Field1->getBitWidthValue();
15733 unsigned Bits2 = Field2->getBitWidthValue();
15734
15735 if (Bits1 != Bits2)
15736 return false;
15737 }
15738
15739 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15740 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15741 return false;
15742
15743 if (!AreUnionMembers &&
15744 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15745 return false;
15746
15747 return true;
15748}
15749
15750/// Check if two standard-layout structs are layout-compatible.
15751/// (C++11 [class.mem] p17)
15752static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15753 const RecordDecl *RD2) {
15754 // Get to the class where the fields are declared
15755 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15756 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15757
15758 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15759 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15760
15761 // Check the fields.
15762 return llvm::equal(RD1->fields(), RD2->fields(),
15763 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15764 return isLayoutCompatible(C, F1, F2);
15765 });
15766}
15767
15768/// Check if two standard-layout unions are layout-compatible.
15769/// (C++11 [class.mem] p18)
15770static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15771 const RecordDecl *RD2) {
15772 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15773 RD2->fields());
15774
15775 for (auto *Field1 : RD1->fields()) {
15776 auto I = UnmatchedFields.begin();
15777 auto E = UnmatchedFields.end();
15778
15779 for ( ; I != E; ++I) {
15780 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15781 bool Result = UnmatchedFields.erase(*I);
15782 (void) Result;
15783 assert(Result);
15784 break;
15785 }
15786 }
15787 if (I == E)
15788 return false;
15789 }
15790
15791 return UnmatchedFields.empty();
15792}
15793
15794static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15795 const RecordDecl *RD2) {
15796 if (RD1->isUnion() != RD2->isUnion())
15797 return false;
15798
15799 if (RD1->isUnion())
15800 return isLayoutCompatibleUnion(C, RD1, RD2);
15801 else
15802 return isLayoutCompatibleStruct(C, RD1, RD2);
15803}
15804
15805/// Check if two types are layout-compatible in C++11 sense.
15806static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15807 if (T1.isNull() || T2.isNull())
15808 return false;
15809
15810 // C++20 [basic.types] p11:
15811 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15812 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15813 // or layout-compatible standard-layout class types (11.4).
15816
15817 if (C.hasSameType(T1, T2))
15818 return true;
15819
15820 const Type::TypeClass TC1 = T1->getTypeClass();
15821 const Type::TypeClass TC2 = T2->getTypeClass();
15822
15823 if (TC1 != TC2)
15824 return false;
15825
15826 if (TC1 == Type::Enum)
15827 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15828 if (TC1 == Type::Record) {
15829 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15830 return false;
15831
15833 T2->castAsRecordDecl());
15834 }
15835
15836 return false;
15837}
15838
15840 return isLayoutCompatible(getASTContext(), T1, T2);
15841}
15842
15843//===-------------- Pointer interconvertibility ----------------------------//
15844
15846 const TypeSourceInfo *Derived) {
15847 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15848 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15849
15850 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15851 getASTContext().hasSameType(BaseT, DerivedT))
15852 return true;
15853
15854 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15855 return false;
15856
15857 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15858 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15859 return true;
15860
15861 return false;
15862}
15863
15864//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15865
15866/// Given a type tag expression find the type tag itself.
15867///
15868/// \param TypeExpr Type tag expression, as it appears in user's code.
15869///
15870/// \param VD Declaration of an identifier that appears in a type tag.
15871///
15872/// \param MagicValue Type tag magic value.
15873///
15874/// \param isConstantEvaluated whether the evalaution should be performed in
15875
15876/// constant context.
15877static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15878 const ValueDecl **VD, uint64_t *MagicValue,
15879 bool isConstantEvaluated) {
15880 while(true) {
15881 if (!TypeExpr)
15882 return false;
15883
15884 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15885
15886 switch (TypeExpr->getStmtClass()) {
15887 case Stmt::UnaryOperatorClass: {
15888 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15889 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15890 TypeExpr = UO->getSubExpr();
15891 continue;
15892 }
15893 return false;
15894 }
15895
15896 case Stmt::DeclRefExprClass: {
15897 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15898 *VD = DRE->getDecl();
15899 return true;
15900 }
15901
15902 case Stmt::IntegerLiteralClass: {
15903 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15904 llvm::APInt MagicValueAPInt = IL->getValue();
15905 if (MagicValueAPInt.getActiveBits() <= 64) {
15906 *MagicValue = MagicValueAPInt.getZExtValue();
15907 return true;
15908 } else
15909 return false;
15910 }
15911
15912 case Stmt::BinaryConditionalOperatorClass:
15913 case Stmt::ConditionalOperatorClass: {
15914 const AbstractConditionalOperator *ACO =
15916 bool Result;
15917 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15918 isConstantEvaluated)) {
15919 if (Result)
15920 TypeExpr = ACO->getTrueExpr();
15921 else
15922 TypeExpr = ACO->getFalseExpr();
15923 continue;
15924 }
15925 return false;
15926 }
15927
15928 case Stmt::BinaryOperatorClass: {
15929 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15930 if (BO->getOpcode() == BO_Comma) {
15931 TypeExpr = BO->getRHS();
15932 continue;
15933 }
15934 return false;
15935 }
15936
15937 default:
15938 return false;
15939 }
15940 }
15941}
15942
15943/// Retrieve the C type corresponding to type tag TypeExpr.
15944///
15945/// \param TypeExpr Expression that specifies a type tag.
15946///
15947/// \param MagicValues Registered magic values.
15948///
15949/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15950/// kind.
15951///
15952/// \param TypeInfo Information about the corresponding C type.
15953///
15954/// \param isConstantEvaluated whether the evalaution should be performed in
15955/// constant context.
15956///
15957/// \returns true if the corresponding C type was found.
15959 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15960 const ASTContext &Ctx,
15961 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15962 *MagicValues,
15963 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15964 bool isConstantEvaluated) {
15965 FoundWrongKind = false;
15966
15967 // Variable declaration that has type_tag_for_datatype attribute.
15968 const ValueDecl *VD = nullptr;
15969
15970 uint64_t MagicValue;
15971
15972 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15973 return false;
15974
15975 if (VD) {
15976 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15977 if (I->getArgumentKind() != ArgumentKind) {
15978 FoundWrongKind = true;
15979 return false;
15980 }
15981 TypeInfo.Type = I->getMatchingCType();
15982 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15983 TypeInfo.MustBeNull = I->getMustBeNull();
15984 return true;
15985 }
15986 return false;
15987 }
15988
15989 if (!MagicValues)
15990 return false;
15991
15992 llvm::DenseMap<Sema::TypeTagMagicValue,
15994 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15995 if (I == MagicValues->end())
15996 return false;
15997
15998 TypeInfo = I->second;
15999 return true;
16000}
16001
16003 uint64_t MagicValue, QualType Type,
16004 bool LayoutCompatible,
16005 bool MustBeNull) {
16006 if (!TypeTagForDatatypeMagicValues)
16007 TypeTagForDatatypeMagicValues.reset(
16008 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16009
16010 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16011 (*TypeTagForDatatypeMagicValues)[Magic] =
16012 TypeTagData(Type, LayoutCompatible, MustBeNull);
16013}
16014
16015static bool IsSameCharType(QualType T1, QualType T2) {
16016 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16017 if (!BT1)
16018 return false;
16019
16020 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16021 if (!BT2)
16022 return false;
16023
16024 BuiltinType::Kind T1Kind = BT1->getKind();
16025 BuiltinType::Kind T2Kind = BT2->getKind();
16026
16027 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16028 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16029 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16030 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16031}
16032
16033void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16034 const ArrayRef<const Expr *> ExprArgs,
16035 SourceLocation CallSiteLoc) {
16036 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16037 bool IsPointerAttr = Attr->getIsPointer();
16038
16039 // Retrieve the argument representing the 'type_tag'.
16040 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16041 if (TypeTagIdxAST >= ExprArgs.size()) {
16042 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16043 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16044 return;
16045 }
16046 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16047 bool FoundWrongKind;
16048 TypeTagData TypeInfo;
16049 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16050 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16051 TypeInfo, isConstantEvaluatedContext())) {
16052 if (FoundWrongKind)
16053 Diag(TypeTagExpr->getExprLoc(),
16054 diag::warn_type_tag_for_datatype_wrong_kind)
16055 << TypeTagExpr->getSourceRange();
16056 return;
16057 }
16058
16059 // Retrieve the argument representing the 'arg_idx'.
16060 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16061 if (ArgumentIdxAST >= ExprArgs.size()) {
16062 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16063 << 1 << Attr->getArgumentIdx().getSourceIndex();
16064 return;
16065 }
16066 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16067 if (IsPointerAttr) {
16068 // Skip implicit cast of pointer to `void *' (as a function argument).
16069 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16070 if (ICE->getType()->isVoidPointerType() &&
16071 ICE->getCastKind() == CK_BitCast)
16072 ArgumentExpr = ICE->getSubExpr();
16073 }
16074 QualType ArgumentType = ArgumentExpr->getType();
16075
16076 // Passing a `void*' pointer shouldn't trigger a warning.
16077 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16078 return;
16079
16080 if (TypeInfo.MustBeNull) {
16081 // Type tag with matching void type requires a null pointer.
16082 if (!ArgumentExpr->isNullPointerConstant(Context,
16084 Diag(ArgumentExpr->getExprLoc(),
16085 diag::warn_type_safety_null_pointer_required)
16086 << ArgumentKind->getName()
16087 << ArgumentExpr->getSourceRange()
16088 << TypeTagExpr->getSourceRange();
16089 }
16090 return;
16091 }
16092
16093 QualType RequiredType = TypeInfo.Type;
16094 if (IsPointerAttr)
16095 RequiredType = Context.getPointerType(RequiredType);
16096
16097 bool mismatch = false;
16098 if (!TypeInfo.LayoutCompatible) {
16099 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16100
16101 // C++11 [basic.fundamental] p1:
16102 // Plain char, signed char, and unsigned char are three distinct types.
16103 //
16104 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16105 // char' depending on the current char signedness mode.
16106 if (mismatch)
16107 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16108 RequiredType->getPointeeType())) ||
16109 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16110 mismatch = false;
16111 } else
16112 if (IsPointerAttr)
16113 mismatch = !isLayoutCompatible(Context,
16114 ArgumentType->getPointeeType(),
16115 RequiredType->getPointeeType());
16116 else
16117 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16118
16119 if (mismatch)
16120 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16121 << ArgumentType << ArgumentKind
16122 << TypeInfo.LayoutCompatible << RequiredType
16123 << ArgumentExpr->getSourceRange()
16124 << TypeTagExpr->getSourceRange();
16125}
16126
16127void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16128 CharUnits Alignment) {
16129 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16130 Alignment);
16131}
16132
16134 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16135 const NamedDecl *ND = m.RD;
16136 if (ND->getName().empty()) {
16137 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16138 ND = TD;
16139 }
16140 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16141 << m.MD << ND << m.E->getSourceRange();
16142 }
16144}
16145
16147 E = E->IgnoreParens();
16148 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16149 return;
16150 if (isa<UnaryOperator>(E) &&
16151 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16152 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16153 if (isa<MemberExpr>(Op)) {
16154 auto &MisalignedMembersForExpr =
16156 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16157 if (MA != MisalignedMembersForExpr.end() &&
16158 (T->isDependentType() || T->isIntegerType() ||
16159 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16160 Context.getTypeAlignInChars(
16161 T->getPointeeType()) <= MA->Alignment))))
16162 MisalignedMembersForExpr.erase(MA);
16163 }
16164 }
16165}
16166
16168 Expr *E,
16169 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16170 Action) {
16171 const auto *ME = dyn_cast<MemberExpr>(E);
16172 if (!ME)
16173 return;
16174
16175 // No need to check expressions with an __unaligned-qualified type.
16176 if (E->getType().getQualifiers().hasUnaligned())
16177 return;
16178
16179 // For a chain of MemberExpr like "a.b.c.d" this list
16180 // will keep FieldDecl's like [d, c, b].
16181 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16182 const MemberExpr *TopME = nullptr;
16183 bool AnyIsPacked = false;
16184 do {
16185 QualType BaseType = ME->getBase()->getType();
16186 if (BaseType->isDependentType())
16187 return;
16188 if (ME->isArrow())
16189 BaseType = BaseType->getPointeeType();
16190 auto *RD = BaseType->castAsRecordDecl();
16191 if (RD->isInvalidDecl())
16192 return;
16193
16194 ValueDecl *MD = ME->getMemberDecl();
16195 auto *FD = dyn_cast<FieldDecl>(MD);
16196 // We do not care about non-data members.
16197 if (!FD || FD->isInvalidDecl())
16198 return;
16199
16200 AnyIsPacked =
16201 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16202 ReverseMemberChain.push_back(FD);
16203
16204 TopME = ME;
16205 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16206 } while (ME);
16207 assert(TopME && "We did not compute a topmost MemberExpr!");
16208
16209 // Not the scope of this diagnostic.
16210 if (!AnyIsPacked)
16211 return;
16212
16213 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16214 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16215 // TODO: The innermost base of the member expression may be too complicated.
16216 // For now, just disregard these cases. This is left for future
16217 // improvement.
16218 if (!DRE && !isa<CXXThisExpr>(TopBase))
16219 return;
16220
16221 // Alignment expected by the whole expression.
16222 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16223
16224 // No need to do anything else with this case.
16225 if (ExpectedAlignment.isOne())
16226 return;
16227
16228 // Synthesize offset of the whole access.
16229 CharUnits Offset;
16230 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16231 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16232
16233 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16234 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16235 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16236
16237 // The base expression of the innermost MemberExpr may give
16238 // stronger guarantees than the class containing the member.
16239 if (DRE && !TopME->isArrow()) {
16240 const ValueDecl *VD = DRE->getDecl();
16241 if (!VD->getType()->isReferenceType())
16242 CompleteObjectAlignment =
16243 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16244 }
16245
16246 // Check if the synthesized offset fulfills the alignment.
16247 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16248 // It may fulfill the offset it but the effective alignment may still be
16249 // lower than the expected expression alignment.
16250 CompleteObjectAlignment < ExpectedAlignment) {
16251 // If this happens, we want to determine a sensible culprit of this.
16252 // Intuitively, watching the chain of member expressions from right to
16253 // left, we start with the required alignment (as required by the field
16254 // type) but some packed attribute in that chain has reduced the alignment.
16255 // It may happen that another packed structure increases it again. But if
16256 // we are here such increase has not been enough. So pointing the first
16257 // FieldDecl that either is packed or else its RecordDecl is,
16258 // seems reasonable.
16259 FieldDecl *FD = nullptr;
16260 CharUnits Alignment;
16261 for (FieldDecl *FDI : ReverseMemberChain) {
16262 if (FDI->hasAttr<PackedAttr>() ||
16263 FDI->getParent()->hasAttr<PackedAttr>()) {
16264 FD = FDI;
16265 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16266 Context.getTypeAlignInChars(
16267 Context.getCanonicalTagType(FD->getParent())));
16268 break;
16269 }
16270 }
16271 assert(FD && "We did not find a packed FieldDecl!");
16272 Action(E, FD->getParent(), FD, Alignment);
16273 }
16274}
16275
16276void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16277 using namespace std::placeholders;
16278
16280 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16281 _2, _3, _4));
16282}
16283
16285 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16286 if (checkArgCount(TheCall, 1))
16287 return true;
16288
16289 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16290 if (A.isInvalid())
16291 return true;
16292
16293 TheCall->setArg(0, A.get());
16294 QualType TyA = A.get()->getType();
16295
16296 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16297 ArgTyRestr, 1))
16298 return true;
16299
16300 TheCall->setType(TyA);
16301 return false;
16302}
16303
16304bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16305 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16306 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16307 TheCall->setType(*Res);
16308 return false;
16309 }
16310 return true;
16311}
16312
16314 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16315 if (!Res)
16316 return true;
16317
16318 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16319 TheCall->setType(VecTy0->getElementType());
16320 else
16321 TheCall->setType(*Res);
16322
16323 return false;
16324}
16325
16327 SourceLocation Loc) {
16329 R = RHS->getEnumCoercedType(S.Context);
16330 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16332 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16333 << LHS->getSourceRange() << RHS->getSourceRange()
16334 << /*Arithmetic Between*/ 0 << L << R;
16335 }
16336 return false;
16337}
16338
16339/// Check if all arguments have the same type. If the types don't match, emit an
16340/// error message and return true. Otherwise return false.
16341///
16342/// For scalars we directly compare their unqualified types. But even if we
16343/// compare unqualified vector types, a difference in qualifiers in the element
16344/// types can make the vector types be considered not equal. For example,
16345/// vector of 4 'const float' values vs vector of 4 'float' values.
16346/// So we compare unqualified types of their elements and number of elements.
16348 ArrayRef<Expr *> Args) {
16349 assert(!Args.empty() && "Should have at least one argument.");
16350
16351 Expr *Arg0 = Args.front();
16352 QualType Ty0 = Arg0->getType();
16353
16354 auto EmitError = [&](Expr *ArgI) {
16355 SemaRef.Diag(Arg0->getBeginLoc(),
16356 diag::err_typecheck_call_different_arg_types)
16357 << Arg0->getType() << ArgI->getType();
16358 };
16359
16360 // Compare scalar types.
16361 if (!Ty0->isVectorType()) {
16362 for (Expr *ArgI : Args.drop_front())
16363 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16364 EmitError(ArgI);
16365 return true;
16366 }
16367
16368 return false;
16369 }
16370
16371 // Compare vector types.
16372 const auto *Vec0 = Ty0->castAs<VectorType>();
16373 for (Expr *ArgI : Args.drop_front()) {
16374 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16375 if (!VecI ||
16376 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16377 VecI->getElementType()) ||
16378 Vec0->getNumElements() != VecI->getNumElements()) {
16379 EmitError(ArgI);
16380 return true;
16381 }
16382 }
16383
16384 return false;
16385}
16386
16387std::optional<QualType>
16389 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16390 if (checkArgCount(TheCall, 2))
16391 return std::nullopt;
16392
16394 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16395 return std::nullopt;
16396
16397 Expr *Args[2];
16398 for (int I = 0; I < 2; ++I) {
16399 ExprResult Converted =
16400 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16401 if (Converted.isInvalid())
16402 return std::nullopt;
16403 Args[I] = Converted.get();
16404 }
16405
16406 SourceLocation LocA = Args[0]->getBeginLoc();
16407 QualType TyA = Args[0]->getType();
16408
16409 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16410 return std::nullopt;
16411
16412 if (checkBuiltinVectorMathArgTypes(*this, Args))
16413 return std::nullopt;
16414
16415 TheCall->setArg(0, Args[0]);
16416 TheCall->setArg(1, Args[1]);
16417 return TyA;
16418}
16419
16421 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16422 if (checkArgCount(TheCall, 3))
16423 return true;
16424
16425 SourceLocation Loc = TheCall->getExprLoc();
16426 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16427 TheCall->getArg(1), Loc) ||
16428 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16429 TheCall->getArg(2), Loc))
16430 return true;
16431
16432 Expr *Args[3];
16433 for (int I = 0; I < 3; ++I) {
16434 ExprResult Converted =
16435 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16436 if (Converted.isInvalid())
16437 return true;
16438 Args[I] = Converted.get();
16439 }
16440
16441 int ArgOrdinal = 1;
16442 for (Expr *Arg : Args) {
16443 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16444 ArgTyRestr, ArgOrdinal++))
16445 return true;
16446 }
16447
16448 if (checkBuiltinVectorMathArgTypes(*this, Args))
16449 return true;
16450
16451 for (int I = 0; I < 3; ++I)
16452 TheCall->setArg(I, Args[I]);
16453
16454 TheCall->setType(Args[0]->getType());
16455 return false;
16456}
16457
16458bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16459 if (checkArgCount(TheCall, 1))
16460 return true;
16461
16462 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16463 if (A.isInvalid())
16464 return true;
16465
16466 TheCall->setArg(0, A.get());
16467 return false;
16468}
16469
16470bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16471 if (checkArgCount(TheCall, 1))
16472 return true;
16473
16474 ExprResult Arg = TheCall->getArg(0);
16475 QualType TyArg = Arg.get()->getType();
16476
16477 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16478 return Diag(TheCall->getArg(0)->getBeginLoc(),
16479 diag::err_builtin_invalid_arg_type)
16480 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16481
16482 TheCall->setType(TyArg);
16483 return false;
16484}
16485
16486ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16487 ExprResult CallResult) {
16488 if (checkArgCount(TheCall, 1))
16489 return ExprError();
16490
16491 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16492 if (MatrixArg.isInvalid())
16493 return MatrixArg;
16494 Expr *Matrix = MatrixArg.get();
16495
16496 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16497 if (!MType) {
16498 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16499 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16500 << Matrix->getType();
16501 return ExprError();
16502 }
16503
16504 // Create returned matrix type by swapping rows and columns of the argument
16505 // matrix type.
16506 QualType ResultType = Context.getConstantMatrixType(
16507 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16508
16509 // Change the return type to the type of the returned matrix.
16510 TheCall->setType(ResultType);
16511
16512 // Update call argument to use the possibly converted matrix argument.
16513 TheCall->setArg(0, Matrix);
16514 return CallResult;
16515}
16516
16517// Get and verify the matrix dimensions.
16518static std::optional<unsigned>
16520 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16521 if (!Value) {
16522 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16523 << Name;
16524 return {};
16525 }
16526 uint64_t Dim = Value->getZExtValue();
16527 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16528 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16529 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16530 return {};
16531 }
16532 return Dim;
16533}
16534
16535ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16536 ExprResult CallResult) {
16537 if (!getLangOpts().MatrixTypes) {
16538 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16539 return ExprError();
16540 }
16541
16542 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16544 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16545 << /*column*/ 1 << /*load*/ 0;
16546 return ExprError();
16547 }
16548
16549 if (checkArgCount(TheCall, 4))
16550 return ExprError();
16551
16552 unsigned PtrArgIdx = 0;
16553 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16554 Expr *RowsExpr = TheCall->getArg(1);
16555 Expr *ColumnsExpr = TheCall->getArg(2);
16556 Expr *StrideExpr = TheCall->getArg(3);
16557
16558 bool ArgError = false;
16559
16560 // Check pointer argument.
16561 {
16563 if (PtrConv.isInvalid())
16564 return PtrConv;
16565 PtrExpr = PtrConv.get();
16566 TheCall->setArg(0, PtrExpr);
16567 if (PtrExpr->isTypeDependent()) {
16568 TheCall->setType(Context.DependentTy);
16569 return TheCall;
16570 }
16571 }
16572
16573 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16574 QualType ElementTy;
16575 if (!PtrTy) {
16576 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16577 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16578 << PtrExpr->getType();
16579 ArgError = true;
16580 } else {
16581 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16582
16584 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16585 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16586 << /* no fp */ 0 << PtrExpr->getType();
16587 ArgError = true;
16588 }
16589 }
16590
16591 // Apply default Lvalue conversions and convert the expression to size_t.
16592 auto ApplyArgumentConversions = [this](Expr *E) {
16594 if (Conv.isInvalid())
16595 return Conv;
16596
16597 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16598 };
16599
16600 // Apply conversion to row and column expressions.
16601 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16602 if (!RowsConv.isInvalid()) {
16603 RowsExpr = RowsConv.get();
16604 TheCall->setArg(1, RowsExpr);
16605 } else
16606 RowsExpr = nullptr;
16607
16608 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16609 if (!ColumnsConv.isInvalid()) {
16610 ColumnsExpr = ColumnsConv.get();
16611 TheCall->setArg(2, ColumnsExpr);
16612 } else
16613 ColumnsExpr = nullptr;
16614
16615 // If any part of the result matrix type is still pending, just use
16616 // Context.DependentTy, until all parts are resolved.
16617 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16618 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16619 TheCall->setType(Context.DependentTy);
16620 return CallResult;
16621 }
16622
16623 // Check row and column dimensions.
16624 std::optional<unsigned> MaybeRows;
16625 if (RowsExpr)
16626 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16627
16628 std::optional<unsigned> MaybeColumns;
16629 if (ColumnsExpr)
16630 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16631
16632 // Check stride argument.
16633 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16634 if (StrideConv.isInvalid())
16635 return ExprError();
16636 StrideExpr = StrideConv.get();
16637 TheCall->setArg(3, StrideExpr);
16638
16639 if (MaybeRows) {
16640 if (std::optional<llvm::APSInt> Value =
16641 StrideExpr->getIntegerConstantExpr(Context)) {
16642 uint64_t Stride = Value->getZExtValue();
16643 if (Stride < *MaybeRows) {
16644 Diag(StrideExpr->getBeginLoc(),
16645 diag::err_builtin_matrix_stride_too_small);
16646 ArgError = true;
16647 }
16648 }
16649 }
16650
16651 if (ArgError || !MaybeRows || !MaybeColumns)
16652 return ExprError();
16653
16654 TheCall->setType(
16655 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16656 return CallResult;
16657}
16658
16659ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16660 ExprResult CallResult) {
16661 if (!getLangOpts().MatrixTypes) {
16662 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16663 return ExprError();
16664 }
16665
16666 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16668 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16669 << /*column*/ 1 << /*store*/ 1;
16670 return ExprError();
16671 }
16672
16673 if (checkArgCount(TheCall, 3))
16674 return ExprError();
16675
16676 unsigned PtrArgIdx = 1;
16677 Expr *MatrixExpr = TheCall->getArg(0);
16678 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16679 Expr *StrideExpr = TheCall->getArg(2);
16680
16681 bool ArgError = false;
16682
16683 {
16684 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16685 if (MatrixConv.isInvalid())
16686 return MatrixConv;
16687 MatrixExpr = MatrixConv.get();
16688 TheCall->setArg(0, MatrixExpr);
16689 }
16690 if (MatrixExpr->isTypeDependent()) {
16691 TheCall->setType(Context.DependentTy);
16692 return TheCall;
16693 }
16694
16695 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16696 if (!MatrixTy) {
16697 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16698 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16699 ArgError = true;
16700 }
16701
16702 {
16704 if (PtrConv.isInvalid())
16705 return PtrConv;
16706 PtrExpr = PtrConv.get();
16707 TheCall->setArg(1, PtrExpr);
16708 if (PtrExpr->isTypeDependent()) {
16709 TheCall->setType(Context.DependentTy);
16710 return TheCall;
16711 }
16712 }
16713
16714 // Check pointer argument.
16715 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16716 if (!PtrTy) {
16717 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16718 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16719 << PtrExpr->getType();
16720 ArgError = true;
16721 } else {
16722 QualType ElementTy = PtrTy->getPointeeType();
16723 if (ElementTy.isConstQualified()) {
16724 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16725 ArgError = true;
16726 }
16727 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16728 if (MatrixTy &&
16729 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16730 Diag(PtrExpr->getBeginLoc(),
16731 diag::err_builtin_matrix_pointer_arg_mismatch)
16732 << ElementTy << MatrixTy->getElementType();
16733 ArgError = true;
16734 }
16735 }
16736
16737 // Apply default Lvalue conversions and convert the stride expression to
16738 // size_t.
16739 {
16740 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16741 if (StrideConv.isInvalid())
16742 return StrideConv;
16743
16744 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16745 if (StrideConv.isInvalid())
16746 return StrideConv;
16747 StrideExpr = StrideConv.get();
16748 TheCall->setArg(2, StrideExpr);
16749 }
16750
16751 // Check stride argument.
16752 if (MatrixTy) {
16753 if (std::optional<llvm::APSInt> Value =
16754 StrideExpr->getIntegerConstantExpr(Context)) {
16755 uint64_t Stride = Value->getZExtValue();
16756 if (Stride < MatrixTy->getNumRows()) {
16757 Diag(StrideExpr->getBeginLoc(),
16758 diag::err_builtin_matrix_stride_too_small);
16759 ArgError = true;
16760 }
16761 }
16762 }
16763
16764 if (ArgError)
16765 return ExprError();
16766
16767 return CallResult;
16768}
16769
16771 const NamedDecl *Callee) {
16772 // This warning does not make sense in code that has no runtime behavior.
16774 return;
16775
16776 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16777
16778 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16779 return;
16780
16781 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16782 // all TCBs the callee is a part of.
16783 llvm::StringSet<> CalleeTCBs;
16784 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16785 CalleeTCBs.insert(A->getTCBName());
16786 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16787 CalleeTCBs.insert(A->getTCBName());
16788
16789 // Go through the TCBs the caller is a part of and emit warnings if Caller
16790 // is in a TCB that the Callee is not.
16791 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16792 StringRef CallerTCB = A->getTCBName();
16793 if (CalleeTCBs.count(CallerTCB) == 0) {
16794 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16795 << Callee << CallerTCB;
16796 }
16797 }
16798}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isValidMathElementType(QualType T)
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
MathCheck
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
__device__ __2f16 float __ockl_bool s
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * toString() const
const char * getStart() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isComplexInt() const
Definition APValue.h:470
bool isFloat() const
Definition APValue.h:468
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isInt() const
Definition APValue.h:467
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
bool isAddrLabelDiff() const
Definition APValue.h:478
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:790
Builtin::Context & BuiltinInfo
Definition ASTContext.h:792
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
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:843
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
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:4353
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4531
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4537
SourceLocation getQuestionLoc() const
Definition Expr.h:4380
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4543
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:7249
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7253
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:3723
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3737
QualType getElementType() const
Definition TypeBase.h:3735
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6880
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7029
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7011
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:4038
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4171
Expr * getLHS() const
Definition Expr.h:4088
SourceLocation getOperatorLoc() const
Definition Expr.h:4080
SourceLocation getExprLoc() const
Definition Expr.h:4079
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
Expr * getRHS() const
Definition Expr.h:4090
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4124
Opcode getOpcode() const
Definition Expr.h:4083
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4135
BinaryOperatorKind Opcode
Definition Expr.h:4043
Pointer to a block type.
Definition TypeBase.h:3543
This class is used for builtin types like 'int'.
Definition TypeBase.h:3165
bool isInteger() const
Definition TypeBase.h:3226
bool isFloatingPoint() const
Definition TypeBase.h:3238
bool isSignedInteger() const
Definition TypeBase.h:3230
bool isUnsignedInteger() const
Definition TypeBase.h:3234
Kind getKind() const
Definition TypeBase.h:3213
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:382
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:3969
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1630
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1688
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:154
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3147
SourceLocation getBeginLoc() const
Definition Expr.h:3277
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3160
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1591
arg_iterator arg_begin()
Definition Expr.h:3200
arg_iterator arg_end()
Definition Expr.h:3203
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3126
bool isCallToStdMove() const
Definition Expr.cpp:3623
Expr * getCallee()
Definition Expr.h:3090
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3134
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3236
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3137
arg_range arguments()
Definition Expr.h:3195
SourceLocation getEndLoc() const
Definition Expr.h:3296
SourceLocation getRParenLoc() const
Definition Expr.h:3274
Decl * getCalleeDecl()
Definition Expr.h:3120
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition Expr.cpp:1596
void setCallee(Expr *F)
Definition Expr.h:3092
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3179
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:3676
path_iterator path_begin()
Definition Expr.h:3746
CastKind getCastKind() const
Definition Expr.h:3720
path_iterator path_end()
Definition Expr.h:3747
Expr * getSubExpr()
Definition Expr.h:3726
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:4391
Expr * getLHS() const
Definition Expr.h:4425
Expr * getRHS() const
Definition Expr.h:4426
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
QualType desugar() const
Definition TypeBase.h:3862
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3817
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4410
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:5559
Expr * getOperand() const
Definition ExprCXX.h:5324
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:487
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1999
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:4010
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4242
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4183
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:671
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:205
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4208
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3669
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3069
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4047
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:265
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:225
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4268
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:4752
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:2879
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4553
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:3762
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3865
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:3133
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4329
bool isStatic() const
Definition Decl.h:2929
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4144
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4130
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3826
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
unsigned getNumParams() const
Definition TypeBase.h:5547
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5668
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5554
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4774
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4770
QualType getReturnType() const
Definition TypeBase.h:4805
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:3853
Describes an C or C++ initializer list.
Definition Expr.h:5299
ArrayRef< Expr * > inits()
Definition Expr.h:5349
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:974
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1020
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1056
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:498
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1103
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:848
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4359
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3364
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
Expr * getBase() const
Definition Expr.h:3441
bool isArrow() const
Definition Expr.h:3548
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
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:1941
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1694
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1708
SourceLocation getSemiLoc() const
Definition Stmt.h:1705
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:614
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:703
bool isImplicitProperty() const
Definition ExprObjC.h:700
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:52
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:273
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6756
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5076
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8376
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2867
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:8292
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8418
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8332
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:8344
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8386
void removeLocalVolatile()
Definition TypeBase.h:8408
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8400
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8365
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8413
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1671
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8338
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:4324
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4410
field_range fields() const
Definition Decl.h:4527
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4402
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1025
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1108
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:97
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:277
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:283
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:535
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:855
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:1418
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:13048
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2640
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9328
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9336
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9373
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:6925
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:2047
SemaHexagon & Hexagon()
Definition Sema.h:1458
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1654
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:833
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1548
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:923
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:1488
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:926
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:2590
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:2697
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:919
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:1433
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:1448
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:1453
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1473
SemaRISCV & RISCV()
Definition Sema.h:1518
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:2763
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6958
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1666
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1316
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:2670
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15395
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2295
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:639
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1416
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:1498
FormatArgumentPassingKind
Definition Sema.h:2600
@ FAPK_Elsewhere
Definition Sema.h:2604
@ FAPK_Fixed
Definition Sema.h:2601
@ FAPK_Variadic
Definition Sema.h:2602
@ FAPK_VAList
Definition Sema.h:2603
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:8174
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:13938
SourceManager & getSourceManager() const
Definition Sema.h:924
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:2592
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:1508
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:1538
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:1483
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:6225
SemaSPIRV & SPIRV()
Definition Sema.h:1523
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:1463
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6413
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:1543
SemaARM & ARM()
Definition Sema.h:1423
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:4643
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:1484
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
bool isUTF8() const
Definition Expr.h:1918
bool isWide() const
Definition Expr.h:1917
bool isPascal() const
Definition Expr.h:1922
unsigned getLength() const
Definition Expr.h:1909
StringLiteralKind getKind() const
Definition Expr.h:1912
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition Expr.cpp:1325
bool isUTF32() const
Definition Expr.h:1920
unsigned getByteLength() const
Definition Expr.h:1908
StringRef getString() const
Definition Expr.h:1867
bool isUTF16() const
Definition Expr.h:1919
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1974
bool isOrdinary() const
Definition Expr.h:1916
unsigned getCharByteWidth() const
Definition Expr.h:1910
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3835
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3815
bool isUnion() const
Definition Decl.h:3925
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:388
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6180
A container of type source information.
Definition TypeBase.h:8263
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:8274
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8549
bool isVoidType() const
Definition TypeBase.h:8891
bool isBooleanType() const
Definition TypeBase.h:9021
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2226
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9071
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:788
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2206
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2274
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2116
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:9051
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:2067
bool isVoidPointerType() const
Definition Type.cpp:713
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8628
bool isCharType() const
Definition Type.cpp:2133
bool isFunctionPointerType() const
Definition TypeBase.h:8596
bool isPointerType() const
Definition TypeBase.h:8529
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8935
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
bool isReferenceType() const
Definition TypeBase.h:8553
bool isEnumeralType() const
Definition TypeBase.h:8660
bool isScalarType() const
Definition TypeBase.h:8993
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:1910
bool isVariableArrayType() const
Definition TypeBase.h:8640
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isExtVectorType() const
Definition TypeBase.h:8672
bool isExtVectorBoolType() const
Definition TypeBase.h:8676
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2647
bool isBitIntType() const
Definition TypeBase.h:8800
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8860
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8652
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
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:2244
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3120
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool isAtomicType() const
Definition TypeBase.h:8717
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3075
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:2801
bool isUnscopedEnumerationType() const
Definition Type.cpp:2126
bool isObjCObjectType() const
Definition TypeBase.h:8708
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9164
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9027
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:2436
bool isFunctionType() const
Definition TypeBase.h:8525
bool isObjCObjectPointerType() const
Definition TypeBase.h:8704
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2313
bool isStructureOrClassType() const
Definition Type.cpp:707
bool isVectorType() const
Definition TypeBase.h:8668
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2321
bool isFloatingType() const
Definition Type.cpp:2305
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:2254
bool isAnyPointerType() const
Definition TypeBase.h:8537
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:9111
bool isNullPtrType() const
Definition TypeBase.h:8928
bool isRecordType() const
Definition TypeBase.h:8656
bool isObjCRetainableType() const
Definition Type.cpp:5284
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5015
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2635
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2362
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3395
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5576
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4176
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2688
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:1290
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1275
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1268
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1282
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2525
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1236
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1297
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:817
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:512
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:662
@ Comparison
A comparison.
Definition Sema.h:666
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:24
@ Success
Annotation was successful.
Definition Parser.h:65
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
PointerAuthDiscArgKind
Definition Sema.h:593
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:545
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:112
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:563
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:498
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:520
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:127
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
StringLiteralKind
Definition Expr.h:1763
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Win64
Definition Specifiers.h:285
@ CC_X86_64SysV
Definition Specifiers.h:286
@ Generic
not a target-specific vector type
Definition TypeBase.h:4137
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5889
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5882
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:5354
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:13222
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13248
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13238
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13197
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6819
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2612
#define log2(__x)
Definition tgmath.h:970