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 case Builtin::BI__builtin_counted_by_ref:
3591 if (BuiltinCountedByRef(TheCall))
3592 return ExprError();
3593 break;
3594 }
3595
3596 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3597 return ExprError();
3598
3599 // Since the target specific builtins for each arch overlap, only check those
3600 // of the arch we are compiling for.
3601 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3602 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3603 assert(Context.getAuxTargetInfo() &&
3604 "Aux Target Builtin, but not an aux target?");
3605
3606 if (CheckTSBuiltinFunctionCall(
3607 *Context.getAuxTargetInfo(),
3608 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3609 return ExprError();
3610 } else {
3611 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3612 TheCall))
3613 return ExprError();
3614 }
3615 }
3616
3617 return TheCallResult;
3618}
3619
3620bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3621 llvm::APSInt Result;
3622 // We can't check the value of a dependent argument.
3623 Expr *Arg = TheCall->getArg(ArgNum);
3624 if (Arg->isTypeDependent() || Arg->isValueDependent())
3625 return false;
3626
3627 // Check constant-ness first.
3628 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3629 return true;
3630
3631 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3632 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3633 return false;
3634
3635 return Diag(TheCall->getBeginLoc(),
3636 diag::err_argument_not_contiguous_bit_field)
3637 << ArgNum << Arg->getSourceRange();
3638}
3639
3640bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3641 unsigned FirstArg, FormatStringInfo *FSI) {
3642 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3643 bool IsVariadic = false;
3644 if (const FunctionType *FnTy = D->getFunctionType())
3645 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3646 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3647 IsVariadic = BD->isVariadic();
3648 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3649 IsVariadic = OMD->isVariadic();
3650
3651 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3652 IsVariadic, FSI);
3653}
3654
3655bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3656 bool HasImplicitThisParam, bool IsVariadic,
3657 FormatStringInfo *FSI) {
3658 if (FirstArg == 0)
3660 else if (IsVariadic)
3662 else
3664 FSI->FormatIdx = FormatIdx - 1;
3665 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3666
3667 // The way the format attribute works in GCC, the implicit this argument
3668 // of member functions is counted. However, it doesn't appear in our own
3669 // lists, so decrement format_idx in that case.
3670 if (HasImplicitThisParam) {
3671 if(FSI->FormatIdx == 0)
3672 return false;
3673 --FSI->FormatIdx;
3674 if (FSI->FirstDataArg != 0)
3675 --FSI->FirstDataArg;
3676 }
3677 return true;
3678}
3679
3680/// Checks if a the given expression evaluates to null.
3681///
3682/// Returns true if the value evaluates to null.
3683static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3684 // Treat (smart) pointers constructed from nullptr as null, whether we can
3685 // const-evaluate them or not.
3686 // This must happen first: the smart pointer expr might have _Nonnull type!
3690 return true;
3691
3692 // If the expression has non-null type, it doesn't evaluate to null.
3693 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3694 if (*nullability == NullabilityKind::NonNull)
3695 return false;
3696 }
3697
3698 // As a special case, transparent unions initialized with zero are
3699 // considered null for the purposes of the nonnull attribute.
3700 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3701 UT &&
3702 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3703 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3704 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3705 Expr = ILE->getInit(0);
3706 }
3707
3708 bool Result;
3709 return (!Expr->isValueDependent() &&
3711 !Result);
3712}
3713
3715 const Expr *ArgExpr,
3716 SourceLocation CallSiteLoc) {
3717 if (CheckNonNullExpr(S, ArgExpr))
3718 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3719 S.PDiag(diag::warn_null_arg)
3720 << ArgExpr->getSourceRange());
3721}
3722
3723/// Determine whether the given type has a non-null nullability annotation.
3725 if (auto nullability = type->getNullability())
3726 return *nullability == NullabilityKind::NonNull;
3727
3728 return false;
3729}
3730
3732 const NamedDecl *FDecl,
3733 const FunctionProtoType *Proto,
3735 SourceLocation CallSiteLoc) {
3736 assert((FDecl || Proto) && "Need a function declaration or prototype");
3737
3738 // Already checked by constant evaluator.
3740 return;
3741 // Check the attributes attached to the method/function itself.
3742 llvm::SmallBitVector NonNullArgs;
3743 if (FDecl) {
3744 // Handle the nonnull attribute on the function/method declaration itself.
3745 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3746 if (!NonNull->args_size()) {
3747 // Easy case: all pointer arguments are nonnull.
3748 for (const auto *Arg : Args)
3749 if (S.isValidPointerAttrType(Arg->getType()))
3750 CheckNonNullArgument(S, Arg, CallSiteLoc);
3751 return;
3752 }
3753
3754 for (const ParamIdx &Idx : NonNull->args()) {
3755 unsigned IdxAST = Idx.getASTIndex();
3756 if (IdxAST >= Args.size())
3757 continue;
3758 if (NonNullArgs.empty())
3759 NonNullArgs.resize(Args.size());
3760 NonNullArgs.set(IdxAST);
3761 }
3762 }
3763 }
3764
3765 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3766 // Handle the nonnull attribute on the parameters of the
3767 // function/method.
3769 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3770 parms = FD->parameters();
3771 else
3772 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3773
3774 unsigned ParamIndex = 0;
3775 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3776 I != E; ++I, ++ParamIndex) {
3777 const ParmVarDecl *PVD = *I;
3778 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3779 if (NonNullArgs.empty())
3780 NonNullArgs.resize(Args.size());
3781
3782 NonNullArgs.set(ParamIndex);
3783 }
3784 }
3785 } else {
3786 // If we have a non-function, non-method declaration but no
3787 // function prototype, try to dig out the function prototype.
3788 if (!Proto) {
3789 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3790 QualType type = VD->getType().getNonReferenceType();
3791 if (auto pointerType = type->getAs<PointerType>())
3792 type = pointerType->getPointeeType();
3793 else if (auto blockType = type->getAs<BlockPointerType>())
3794 type = blockType->getPointeeType();
3795 // FIXME: data member pointers?
3796
3797 // Dig out the function prototype, if there is one.
3798 Proto = type->getAs<FunctionProtoType>();
3799 }
3800 }
3801
3802 // Fill in non-null argument information from the nullability
3803 // information on the parameter types (if we have them).
3804 if (Proto) {
3805 unsigned Index = 0;
3806 for (auto paramType : Proto->getParamTypes()) {
3807 if (isNonNullType(paramType)) {
3808 if (NonNullArgs.empty())
3809 NonNullArgs.resize(Args.size());
3810
3811 NonNullArgs.set(Index);
3812 }
3813
3814 ++Index;
3815 }
3816 }
3817 }
3818
3819 // Check for non-null arguments.
3820 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3821 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3822 if (NonNullArgs[ArgIndex])
3823 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3824 }
3825}
3826
3827void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3828 StringRef ParamName, QualType ArgTy,
3829 QualType ParamTy) {
3830
3831 // If a function accepts a pointer or reference type
3832 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3833 return;
3834
3835 // If the parameter is a pointer type, get the pointee type for the
3836 // argument too. If the parameter is a reference type, don't try to get
3837 // the pointee type for the argument.
3838 if (ParamTy->isPointerType())
3839 ArgTy = ArgTy->getPointeeType();
3840
3841 // Remove reference or pointer
3842 ParamTy = ParamTy->getPointeeType();
3843
3844 // Find expected alignment, and the actual alignment of the passed object.
3845 // getTypeAlignInChars requires complete types
3846 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3847 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3848 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3849 return;
3850
3851 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3852 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3853
3854 // If the argument is less aligned than the parameter, there is a
3855 // potential alignment issue.
3856 if (ArgAlign < ParamAlign)
3857 Diag(Loc, diag::warn_param_mismatched_alignment)
3858 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3859 << ParamName << (FDecl != nullptr) << FDecl;
3860}
3861
3862void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3863 const Expr *ThisArg,
3865 if (!FD || Args.empty())
3866 return;
3867 auto GetArgAt = [&](int Idx) -> const Expr * {
3868 if (Idx == LifetimeCaptureByAttr::Global ||
3869 Idx == LifetimeCaptureByAttr::Unknown)
3870 return nullptr;
3871 if (IsMemberFunction && Idx == 0)
3872 return ThisArg;
3873 return Args[Idx - IsMemberFunction];
3874 };
3875 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3876 unsigned ArgIdx) {
3877 if (!Attr)
3878 return;
3879
3880 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3881 for (int CapturingParamIdx : Attr->params()) {
3882 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3883 // initialization codepath.
3884 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3886 continue;
3887 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3888 CapturingEntity CE{Capturing};
3889 // Ensure that 'Captured' outlives the 'Capturing' entity.
3890 checkCaptureByLifetime(*this, CE, Captured);
3891 }
3892 };
3893 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3894 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3895 I + IsMemberFunction);
3896 // Check when the implicit object param is captured.
3897 if (IsMemberFunction) {
3898 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3899 if (!TSI)
3900 return;
3902 for (TypeLoc TL = TSI->getTypeLoc();
3903 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3904 TL = ATL.getModifiedLoc())
3905 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3906 }
3907}
3908
3910 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3911 bool IsMemberFunction, SourceLocation Loc,
3912 SourceRange Range, VariadicCallType CallType) {
3913 // FIXME: We should check as much as we can in the template definition.
3914 if (CurContext->isDependentContext())
3915 return;
3916
3917 // Printf and scanf checking.
3918 llvm::SmallBitVector CheckedVarArgs;
3919 if (FDecl) {
3920 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3921 // Only create vector if there are format attributes.
3922 CheckedVarArgs.resize(Args.size());
3923 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3924 CheckedVarArgs);
3925 }
3926
3927 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3928 CheckedVarArgs.resize(Args.size());
3929 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3930 CheckedVarArgs);
3931 }
3932 }
3933
3934 // Refuse POD arguments that weren't caught by the format string
3935 // checks above.
3936 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3937 if (CallType != VariadicCallType::DoesNotApply &&
3938 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3939 unsigned NumParams = Proto ? Proto->getNumParams()
3940 : isa_and_nonnull<FunctionDecl>(FDecl)
3941 ? cast<FunctionDecl>(FDecl)->getNumParams()
3942 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3943 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3944 : 0;
3945
3946 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3947 // Args[ArgIdx] can be null in malformed code.
3948 if (const Expr *Arg = Args[ArgIdx]) {
3949 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3950 checkVariadicArgument(Arg, CallType);
3951 }
3952 }
3953 }
3954 if (FD)
3955 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3956 if (FDecl || Proto) {
3957 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3958
3959 // Type safety checking.
3960 if (FDecl) {
3961 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3962 CheckArgumentWithTypeTag(I, Args, Loc);
3963 }
3964 }
3965
3966 // Check that passed arguments match the alignment of original arguments.
3967 // Try to get the missing prototype from the declaration.
3968 if (!Proto && FDecl) {
3969 const auto *FT = FDecl->getFunctionType();
3970 if (isa_and_nonnull<FunctionProtoType>(FT))
3971 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3972 }
3973 if (Proto) {
3974 // For variadic functions, we may have more args than parameters.
3975 // For some K&R functions, we may have less args than parameters.
3976 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3977 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3978 bool IsScalableArg = false;
3979 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3980 // Args[ArgIdx] can be null in malformed code.
3981 if (const Expr *Arg = Args[ArgIdx]) {
3982 if (Arg->containsErrors())
3983 continue;
3984
3985 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3986 FDecl->hasLinkage() &&
3987 FDecl->getFormalLinkage() != Linkage::Internal &&
3989 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3990
3991 QualType ParamTy = Proto->getParamType(ArgIdx);
3992 if (ParamTy->isSizelessVectorType())
3993 IsScalableArg = true;
3994 QualType ArgTy = Arg->getType();
3995 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3996 ArgTy, ParamTy);
3997 }
3998 }
3999
4000 // If the callee has an AArch64 SME attribute to indicate that it is an
4001 // __arm_streaming function, then the caller requires SME to be available.
4004 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4005 llvm::StringMap<bool> CallerFeatureMap;
4006 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4007 if (!CallerFeatureMap.contains("sme"))
4008 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4009 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4010 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4011 }
4012 }
4013
4014 // If the call requires a streaming-mode change and has scalable vector
4015 // arguments or return values, then warn the user that the streaming and
4016 // non-streaming vector lengths may be different.
4017 // When both streaming and non-streaming vector lengths are defined and
4018 // mismatched, produce an error.
4019 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4020 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4021 (IsScalableArg || IsScalableRet)) {
4022 bool IsCalleeStreaming =
4024 bool IsCalleeStreamingCompatible =
4025 ExtInfo.AArch64SMEAttributes &
4027 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4028 if (!IsCalleeStreamingCompatible &&
4029 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4030 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4031 const LangOptions &LO = getLangOpts();
4032 unsigned VL = LO.VScaleMin * 128;
4033 unsigned SVL = LO.VScaleStreamingMin * 128;
4034 bool IsVLMismatch = VL && SVL && VL != SVL;
4035
4036 auto EmitDiag = [&](bool IsArg) {
4037 if (IsVLMismatch) {
4038 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4039 // Emit warning for streaming-compatible callers
4040 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4041 << IsArg << IsCalleeStreaming << SVL << VL;
4042 else
4043 // Emit error otherwise
4044 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4045 << IsArg << SVL << VL;
4046 } else
4047 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4048 << IsArg;
4049 };
4050
4051 if (IsScalableArg)
4052 EmitDiag(true);
4053 if (IsScalableRet)
4054 EmitDiag(false);
4055 }
4056 }
4057
4058 FunctionType::ArmStateValue CalleeArmZAState =
4060 FunctionType::ArmStateValue CalleeArmZT0State =
4062 if (CalleeArmZAState != FunctionType::ARM_None ||
4063 CalleeArmZT0State != FunctionType::ARM_None) {
4064 bool CallerHasZAState = false;
4065 bool CallerHasZT0State = false;
4066 if (CallerFD) {
4067 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4068 if (Attr && Attr->isNewZA())
4069 CallerHasZAState = true;
4070 if (Attr && Attr->isNewZT0())
4071 CallerHasZT0State = true;
4072 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4073 CallerHasZAState |=
4075 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4077 CallerHasZT0State |=
4079 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4081 }
4082 }
4083
4084 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4085 Diag(Loc, diag::err_sme_za_call_no_za_state);
4086
4087 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4088 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4089
4090 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4091 CalleeArmZT0State != FunctionType::ARM_None) {
4092 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4093 Diag(Loc, diag::note_sme_use_preserves_za);
4094 }
4095 }
4096 }
4097
4098 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4099 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4100 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4101 if (!Arg->isValueDependent()) {
4102 Expr::EvalResult Align;
4103 if (Arg->EvaluateAsInt(Align, Context)) {
4104 const llvm::APSInt &I = Align.Val.getInt();
4105 if (!I.isPowerOf2())
4106 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4107 << Arg->getSourceRange();
4108
4109 if (I > Sema::MaximumAlignment)
4110 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4111 << Arg->getSourceRange() << Sema::MaximumAlignment;
4112 }
4113 }
4114 }
4115
4116 if (FD)
4117 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4118}
4119
4120void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4121 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4122 DiagnoseUseOfDecl(Decl, Loc);
4123 }
4124}
4125
4126void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4128 const FunctionProtoType *Proto,
4129 SourceLocation Loc) {
4130 VariadicCallType CallType = Proto->isVariadic()
4133
4134 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4135 CheckArgAlignment(
4136 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4137 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4138
4139 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4140 Loc, SourceRange(), CallType);
4141}
4142
4144 const FunctionProtoType *Proto) {
4145 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4146 isa<CXXMethodDecl>(FDecl);
4147 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4148 IsMemberOperatorCall;
4149 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4150 TheCall->getCallee());
4151 Expr** Args = TheCall->getArgs();
4152 unsigned NumArgs = TheCall->getNumArgs();
4153
4154 Expr *ImplicitThis = nullptr;
4155 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4156 // If this is a call to a member operator, hide the first
4157 // argument from checkCall.
4158 // FIXME: Our choice of AST representation here is less than ideal.
4159 ImplicitThis = Args[0];
4160 ++Args;
4161 --NumArgs;
4162 } else if (IsMemberFunction && !FDecl->isStatic() &&
4164 ImplicitThis =
4165 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4166
4167 if (ImplicitThis) {
4168 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4169 // used.
4170 QualType ThisType = ImplicitThis->getType();
4171 if (!ThisType->isPointerType()) {
4172 assert(!ThisType->isReferenceType());
4173 ThisType = Context.getPointerType(ThisType);
4174 }
4175
4176 QualType ThisTypeFromDecl = Context.getPointerType(
4177 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4178
4179 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4180 ThisTypeFromDecl);
4181 }
4182
4183 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4184 IsMemberFunction, TheCall->getRParenLoc(),
4185 TheCall->getCallee()->getSourceRange(), CallType);
4186
4187 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4188 // None of the checks below are needed for functions that don't have
4189 // simple names (e.g., C++ conversion functions).
4190 if (!FnInfo)
4191 return false;
4192
4193 // Enforce TCB except for builtin calls, which are always allowed.
4194 if (FDecl->getBuiltinID() == 0)
4195 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4196
4197 CheckAbsoluteValueFunction(TheCall, FDecl);
4198 CheckMaxUnsignedZero(TheCall, FDecl);
4199 CheckInfNaNFunction(TheCall, FDecl);
4200
4201 if (getLangOpts().ObjC)
4202 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4203
4204 unsigned CMId = FDecl->getMemoryFunctionKind();
4205
4206 // Handle memory setting and copying functions.
4207 switch (CMId) {
4208 case 0:
4209 return false;
4210 case Builtin::BIstrlcpy: // fallthrough
4211 case Builtin::BIstrlcat:
4212 CheckStrlcpycatArguments(TheCall, FnInfo);
4213 break;
4214 case Builtin::BIstrncat:
4215 CheckStrncatArguments(TheCall, FnInfo);
4216 break;
4217 case Builtin::BIfree:
4218 CheckFreeArguments(TheCall);
4219 break;
4220 default:
4221 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4222 }
4223
4224 return false;
4225}
4226
4227bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4228 const FunctionProtoType *Proto) {
4229 QualType Ty;
4230 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4231 Ty = V->getType().getNonReferenceType();
4232 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4233 Ty = F->getType().getNonReferenceType();
4234 else
4235 return false;
4236
4237 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4238 !Ty->isFunctionProtoType())
4239 return false;
4240
4241 VariadicCallType CallType;
4242 if (!Proto || !Proto->isVariadic()) {
4244 } else if (Ty->isBlockPointerType()) {
4245 CallType = VariadicCallType::Block;
4246 } else { // Ty->isFunctionPointerType()
4247 CallType = VariadicCallType::Function;
4248 }
4249
4250 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4251 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4252 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4253 TheCall->getCallee()->getSourceRange(), CallType);
4254
4255 return false;
4256}
4257
4258bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4259 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4260 TheCall->getCallee());
4261 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4262 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4263 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4264 TheCall->getCallee()->getSourceRange(), CallType);
4265
4266 return false;
4267}
4268
4269static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4270 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4271 return false;
4272
4273 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4274 switch (Op) {
4275 case AtomicExpr::AO__c11_atomic_init:
4276 case AtomicExpr::AO__opencl_atomic_init:
4277 llvm_unreachable("There is no ordering argument for an init");
4278
4279 case AtomicExpr::AO__c11_atomic_load:
4280 case AtomicExpr::AO__opencl_atomic_load:
4281 case AtomicExpr::AO__hip_atomic_load:
4282 case AtomicExpr::AO__atomic_load_n:
4283 case AtomicExpr::AO__atomic_load:
4284 case AtomicExpr::AO__scoped_atomic_load_n:
4285 case AtomicExpr::AO__scoped_atomic_load:
4286 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4287 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4288
4289 case AtomicExpr::AO__c11_atomic_store:
4290 case AtomicExpr::AO__opencl_atomic_store:
4291 case AtomicExpr::AO__hip_atomic_store:
4292 case AtomicExpr::AO__atomic_store:
4293 case AtomicExpr::AO__atomic_store_n:
4294 case AtomicExpr::AO__scoped_atomic_store:
4295 case AtomicExpr::AO__scoped_atomic_store_n:
4296 case AtomicExpr::AO__atomic_clear:
4297 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4298 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4299 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4300
4301 default:
4302 return true;
4303 }
4304}
4305
4306ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4308 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4309 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4310 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4311 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4312 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4313 Op);
4314}
4315
4317 SourceLocation RParenLoc, MultiExprArg Args,
4319 AtomicArgumentOrder ArgOrder) {
4320 // All the non-OpenCL operations take one of the following forms.
4321 // The OpenCL operations take the __c11 forms with one extra argument for
4322 // synchronization scope.
4323 enum {
4324 // C __c11_atomic_init(A *, C)
4325 Init,
4326
4327 // C __c11_atomic_load(A *, int)
4328 Load,
4329
4330 // void __atomic_load(A *, CP, int)
4331 LoadCopy,
4332
4333 // void __atomic_store(A *, CP, int)
4334 Copy,
4335
4336 // C __c11_atomic_add(A *, M, int)
4337 Arithmetic,
4338
4339 // C __atomic_exchange_n(A *, CP, int)
4340 Xchg,
4341
4342 // void __atomic_exchange(A *, C *, CP, int)
4343 GNUXchg,
4344
4345 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4346 C11CmpXchg,
4347
4348 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4349 GNUCmpXchg,
4350
4351 // bool __atomic_test_and_set(A *, int)
4352 TestAndSetByte,
4353
4354 // void __atomic_clear(A *, int)
4355 ClearByte,
4356 } Form = Init;
4357
4358 const unsigned NumForm = ClearByte + 1;
4359 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4360 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4361 // where:
4362 // C is an appropriate type,
4363 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4364 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4365 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4366 // the int parameters are for orderings.
4367
4368 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4369 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4370 "need to update code for modified forms");
4371 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4372 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4373 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4374 "need to update code for modified C11 atomics");
4375 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4376 Op <= AtomicExpr::AO__opencl_atomic_store;
4377 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4378 Op <= AtomicExpr::AO__hip_atomic_store;
4379 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4380 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4381 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4382 Op <= AtomicExpr::AO__c11_atomic_store) ||
4383 IsOpenCL;
4384 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4385 Op == AtomicExpr::AO__atomic_store_n ||
4386 Op == AtomicExpr::AO__atomic_exchange_n ||
4387 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4388 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4389 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4390 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4391 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4392 // Bit mask for extra allowed value types other than integers for atomic
4393 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4394 // allow floating point.
4395 enum ArithOpExtraValueType {
4396 AOEVT_None = 0,
4397 AOEVT_Pointer = 1,
4398 AOEVT_FP = 2,
4399 };
4400 unsigned ArithAllows = AOEVT_None;
4401
4402 switch (Op) {
4403 case AtomicExpr::AO__c11_atomic_init:
4404 case AtomicExpr::AO__opencl_atomic_init:
4405 Form = Init;
4406 break;
4407
4408 case AtomicExpr::AO__c11_atomic_load:
4409 case AtomicExpr::AO__opencl_atomic_load:
4410 case AtomicExpr::AO__hip_atomic_load:
4411 case AtomicExpr::AO__atomic_load_n:
4412 case AtomicExpr::AO__scoped_atomic_load_n:
4413 Form = Load;
4414 break;
4415
4416 case AtomicExpr::AO__atomic_load:
4417 case AtomicExpr::AO__scoped_atomic_load:
4418 Form = LoadCopy;
4419 break;
4420
4421 case AtomicExpr::AO__c11_atomic_store:
4422 case AtomicExpr::AO__opencl_atomic_store:
4423 case AtomicExpr::AO__hip_atomic_store:
4424 case AtomicExpr::AO__atomic_store:
4425 case AtomicExpr::AO__atomic_store_n:
4426 case AtomicExpr::AO__scoped_atomic_store:
4427 case AtomicExpr::AO__scoped_atomic_store_n:
4428 Form = Copy;
4429 break;
4430 case AtomicExpr::AO__atomic_fetch_add:
4431 case AtomicExpr::AO__atomic_fetch_sub:
4432 case AtomicExpr::AO__atomic_add_fetch:
4433 case AtomicExpr::AO__atomic_sub_fetch:
4434 case AtomicExpr::AO__scoped_atomic_fetch_add:
4435 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4436 case AtomicExpr::AO__scoped_atomic_add_fetch:
4437 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4438 case AtomicExpr::AO__c11_atomic_fetch_add:
4439 case AtomicExpr::AO__c11_atomic_fetch_sub:
4440 case AtomicExpr::AO__opencl_atomic_fetch_add:
4441 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4442 case AtomicExpr::AO__hip_atomic_fetch_add:
4443 case AtomicExpr::AO__hip_atomic_fetch_sub:
4444 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4445 Form = Arithmetic;
4446 break;
4447 case AtomicExpr::AO__atomic_fetch_max:
4448 case AtomicExpr::AO__atomic_fetch_min:
4449 case AtomicExpr::AO__atomic_max_fetch:
4450 case AtomicExpr::AO__atomic_min_fetch:
4451 case AtomicExpr::AO__scoped_atomic_fetch_max:
4452 case AtomicExpr::AO__scoped_atomic_fetch_min:
4453 case AtomicExpr::AO__scoped_atomic_max_fetch:
4454 case AtomicExpr::AO__scoped_atomic_min_fetch:
4455 case AtomicExpr::AO__c11_atomic_fetch_max:
4456 case AtomicExpr::AO__c11_atomic_fetch_min:
4457 case AtomicExpr::AO__opencl_atomic_fetch_max:
4458 case AtomicExpr::AO__opencl_atomic_fetch_min:
4459 case AtomicExpr::AO__hip_atomic_fetch_max:
4460 case AtomicExpr::AO__hip_atomic_fetch_min:
4461 ArithAllows = AOEVT_FP;
4462 Form = Arithmetic;
4463 break;
4464 case AtomicExpr::AO__c11_atomic_fetch_and:
4465 case AtomicExpr::AO__c11_atomic_fetch_or:
4466 case AtomicExpr::AO__c11_atomic_fetch_xor:
4467 case AtomicExpr::AO__hip_atomic_fetch_and:
4468 case AtomicExpr::AO__hip_atomic_fetch_or:
4469 case AtomicExpr::AO__hip_atomic_fetch_xor:
4470 case AtomicExpr::AO__c11_atomic_fetch_nand:
4471 case AtomicExpr::AO__opencl_atomic_fetch_and:
4472 case AtomicExpr::AO__opencl_atomic_fetch_or:
4473 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4474 case AtomicExpr::AO__atomic_fetch_and:
4475 case AtomicExpr::AO__atomic_fetch_or:
4476 case AtomicExpr::AO__atomic_fetch_xor:
4477 case AtomicExpr::AO__atomic_fetch_nand:
4478 case AtomicExpr::AO__atomic_and_fetch:
4479 case AtomicExpr::AO__atomic_or_fetch:
4480 case AtomicExpr::AO__atomic_xor_fetch:
4481 case AtomicExpr::AO__atomic_nand_fetch:
4482 case AtomicExpr::AO__scoped_atomic_fetch_and:
4483 case AtomicExpr::AO__scoped_atomic_fetch_or:
4484 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4485 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4486 case AtomicExpr::AO__scoped_atomic_and_fetch:
4487 case AtomicExpr::AO__scoped_atomic_or_fetch:
4488 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4489 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4490 case AtomicExpr::AO__scoped_atomic_uinc_wrap:
4491 case AtomicExpr::AO__scoped_atomic_udec_wrap:
4492 Form = Arithmetic;
4493 break;
4494
4495 case AtomicExpr::AO__c11_atomic_exchange:
4496 case AtomicExpr::AO__hip_atomic_exchange:
4497 case AtomicExpr::AO__opencl_atomic_exchange:
4498 case AtomicExpr::AO__atomic_exchange_n:
4499 case AtomicExpr::AO__scoped_atomic_exchange_n:
4500 Form = Xchg;
4501 break;
4502
4503 case AtomicExpr::AO__atomic_exchange:
4504 case AtomicExpr::AO__scoped_atomic_exchange:
4505 Form = GNUXchg;
4506 break;
4507
4508 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4509 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4510 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4511 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4512 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4513 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4514 Form = C11CmpXchg;
4515 break;
4516
4517 case AtomicExpr::AO__atomic_compare_exchange:
4518 case AtomicExpr::AO__atomic_compare_exchange_n:
4519 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4520 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4521 Form = GNUCmpXchg;
4522 break;
4523
4524 case AtomicExpr::AO__atomic_test_and_set:
4525 Form = TestAndSetByte;
4526 break;
4527
4528 case AtomicExpr::AO__atomic_clear:
4529 Form = ClearByte;
4530 break;
4531 }
4532
4533 unsigned AdjustedNumArgs = NumArgs[Form];
4534 if ((IsOpenCL || IsHIP || IsScoped) &&
4535 Op != AtomicExpr::AO__opencl_atomic_init)
4536 ++AdjustedNumArgs;
4537 // Check we have the right number of arguments.
4538 if (Args.size() < AdjustedNumArgs) {
4539 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4540 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4541 << /*is non object*/ 0 << ExprRange;
4542 return ExprError();
4543 } else if (Args.size() > AdjustedNumArgs) {
4544 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4545 diag::err_typecheck_call_too_many_args)
4546 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4547 << /*is non object*/ 0 << ExprRange;
4548 return ExprError();
4549 }
4550
4551 // Inspect the first argument of the atomic operation.
4552 Expr *Ptr = Args[0];
4554 if (ConvertedPtr.isInvalid())
4555 return ExprError();
4556
4557 Ptr = ConvertedPtr.get();
4558 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4559 if (!pointerType) {
4560 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4561 << Ptr->getType() << 0 << Ptr->getSourceRange();
4562 return ExprError();
4563 }
4564
4565 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4566 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4567 QualType ValType = AtomTy; // 'C'
4568 if (IsC11) {
4569 if (!AtomTy->isAtomicType()) {
4570 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4571 << Ptr->getType() << Ptr->getSourceRange();
4572 return ExprError();
4573 }
4574 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4576 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4577 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4578 << Ptr->getSourceRange();
4579 return ExprError();
4580 }
4581 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4582 } else if (Form != Load && Form != LoadCopy) {
4583 if (ValType.isConstQualified()) {
4584 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4585 << Ptr->getType() << Ptr->getSourceRange();
4586 return ExprError();
4587 }
4588 }
4589
4590 if (Form != TestAndSetByte && Form != ClearByte) {
4591 // Pointer to object of size zero is not allowed.
4592 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4593 diag::err_incomplete_type))
4594 return ExprError();
4595
4596 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4597 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4598 << Ptr->getType() << 1 << Ptr->getSourceRange();
4599 return ExprError();
4600 }
4601 } else {
4602 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4603 // non-const pointer type, including void* and pointers to incomplete
4604 // structs, but only access the first byte.
4605 AtomTy = Context.CharTy;
4606 AtomTy = AtomTy.withCVRQualifiers(
4607 pointerType->getPointeeType().getCVRQualifiers());
4608 QualType PointerQT = Context.getPointerType(AtomTy);
4609 pointerType = PointerQT->getAs<PointerType>();
4610 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4611 ValType = AtomTy;
4612 }
4613
4614 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4615 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4616 Diag(ExprRange.getBegin(),
4617 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4618 << 0 << Ptr->getType() << Ptr->getSourceRange();
4619 return ExprError();
4620 }
4621
4622 // For an arithmetic operation, the implied arithmetic must be well-formed.
4623 if (Form == Arithmetic) {
4624 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4625 // trivial type errors.
4626 auto IsAllowedValueType = [&](QualType ValType,
4627 unsigned AllowedType) -> bool {
4628 if (ValType->isIntegerType())
4629 return true;
4630 if (ValType->isPointerType())
4631 return AllowedType & AOEVT_Pointer;
4632 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4633 return false;
4634 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4635 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4636 &Context.getTargetInfo().getLongDoubleFormat() ==
4637 &llvm::APFloat::x87DoubleExtended())
4638 return false;
4639 return true;
4640 };
4641 if (!IsAllowedValueType(ValType, ArithAllows)) {
4642 auto DID = ArithAllows & AOEVT_FP
4643 ? (ArithAllows & AOEVT_Pointer
4644 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4645 : diag::err_atomic_op_needs_atomic_int_or_fp)
4646 : diag::err_atomic_op_needs_atomic_int;
4647 Diag(ExprRange.getBegin(), DID)
4648 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4649 return ExprError();
4650 }
4651 if (IsC11 && ValType->isPointerType() &&
4653 diag::err_incomplete_type)) {
4654 return ExprError();
4655 }
4656 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4657 // For __atomic_*_n operations, the value type must be a scalar integral or
4658 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4659 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4660 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4661 return ExprError();
4662 }
4663
4664 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4665 !AtomTy->isScalarType()) {
4666 // For GNU atomics, require a trivially-copyable type. This is not part of
4667 // the GNU atomics specification but we enforce it for consistency with
4668 // other atomics which generally all require a trivially-copyable type. This
4669 // is because atomics just copy bits.
4670 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4671 << Ptr->getType() << Ptr->getSourceRange();
4672 return ExprError();
4673 }
4674
4675 switch (ValType.getObjCLifetime()) {
4678 // okay
4679 break;
4680
4684 // FIXME: Can this happen? By this point, ValType should be known
4685 // to be trivially copyable.
4686 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4687 << ValType << Ptr->getSourceRange();
4688 return ExprError();
4689 }
4690
4691 // All atomic operations have an overload which takes a pointer to a volatile
4692 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4693 // into the result or the other operands. Similarly atomic_load takes a
4694 // pointer to a const 'A'.
4695 ValType.removeLocalVolatile();
4696 ValType.removeLocalConst();
4697 QualType ResultType = ValType;
4698 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4699 Form == ClearByte)
4700 ResultType = Context.VoidTy;
4701 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4702 ResultType = Context.BoolTy;
4703
4704 // The type of a parameter passed 'by value'. In the GNU atomics, such
4705 // arguments are actually passed as pointers.
4706 QualType ByValType = ValType; // 'CP'
4707 bool IsPassedByAddress = false;
4708 if (!IsC11 && !IsHIP && !IsN) {
4709 ByValType = Ptr->getType();
4710 IsPassedByAddress = true;
4711 }
4712
4713 SmallVector<Expr *, 5> APIOrderedArgs;
4714 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4715 APIOrderedArgs.push_back(Args[0]);
4716 switch (Form) {
4717 case Init:
4718 case Load:
4719 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4720 break;
4721 case LoadCopy:
4722 case Copy:
4723 case Arithmetic:
4724 case Xchg:
4725 APIOrderedArgs.push_back(Args[2]); // Val1
4726 APIOrderedArgs.push_back(Args[1]); // Order
4727 break;
4728 case GNUXchg:
4729 APIOrderedArgs.push_back(Args[2]); // Val1
4730 APIOrderedArgs.push_back(Args[3]); // Val2
4731 APIOrderedArgs.push_back(Args[1]); // Order
4732 break;
4733 case C11CmpXchg:
4734 APIOrderedArgs.push_back(Args[2]); // Val1
4735 APIOrderedArgs.push_back(Args[4]); // Val2
4736 APIOrderedArgs.push_back(Args[1]); // Order
4737 APIOrderedArgs.push_back(Args[3]); // OrderFail
4738 break;
4739 case GNUCmpXchg:
4740 APIOrderedArgs.push_back(Args[2]); // Val1
4741 APIOrderedArgs.push_back(Args[4]); // Val2
4742 APIOrderedArgs.push_back(Args[5]); // Weak
4743 APIOrderedArgs.push_back(Args[1]); // Order
4744 APIOrderedArgs.push_back(Args[3]); // OrderFail
4745 break;
4746 case TestAndSetByte:
4747 case ClearByte:
4748 APIOrderedArgs.push_back(Args[1]); // Order
4749 break;
4750 }
4751 } else
4752 APIOrderedArgs.append(Args.begin(), Args.end());
4753
4754 // The first argument's non-CV pointer type is used to deduce the type of
4755 // subsequent arguments, except for:
4756 // - weak flag (always converted to bool)
4757 // - memory order (always converted to int)
4758 // - scope (always converted to int)
4759 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4760 QualType Ty;
4761 if (i < NumVals[Form] + 1) {
4762 switch (i) {
4763 case 0:
4764 // The first argument is always a pointer. It has a fixed type.
4765 // It is always dereferenced, a nullptr is undefined.
4766 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4767 // Nothing else to do: we already know all we want about this pointer.
4768 continue;
4769 case 1:
4770 // The second argument is the non-atomic operand. For arithmetic, this
4771 // is always passed by value, and for a compare_exchange it is always
4772 // passed by address. For the rest, GNU uses by-address and C11 uses
4773 // by-value.
4774 assert(Form != Load);
4775 if (Form == Arithmetic && ValType->isPointerType())
4776 Ty = Context.getPointerDiffType();
4777 else if (Form == Init || Form == Arithmetic)
4778 Ty = ValType;
4779 else if (Form == Copy || Form == Xchg) {
4780 if (IsPassedByAddress) {
4781 // The value pointer is always dereferenced, a nullptr is undefined.
4782 CheckNonNullArgument(*this, APIOrderedArgs[i],
4783 ExprRange.getBegin());
4784 }
4785 Ty = ByValType;
4786 } else {
4787 Expr *ValArg = APIOrderedArgs[i];
4788 // The value pointer is always dereferenced, a nullptr is undefined.
4789 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4791 // Keep address space of non-atomic pointer type.
4792 if (const PointerType *PtrTy =
4793 ValArg->getType()->getAs<PointerType>()) {
4794 AS = PtrTy->getPointeeType().getAddressSpace();
4795 }
4796 Ty = Context.getPointerType(
4797 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4798 }
4799 break;
4800 case 2:
4801 // The third argument to compare_exchange / GNU exchange is the desired
4802 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4803 if (IsPassedByAddress)
4804 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4805 Ty = ByValType;
4806 break;
4807 case 3:
4808 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4809 Ty = Context.BoolTy;
4810 break;
4811 }
4812 } else {
4813 // The order(s) and scope are always converted to int.
4814 Ty = Context.IntTy;
4815 }
4816
4817 InitializedEntity Entity =
4819 ExprResult Arg = APIOrderedArgs[i];
4820 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4821 if (Arg.isInvalid())
4822 return true;
4823 APIOrderedArgs[i] = Arg.get();
4824 }
4825
4826 // Permute the arguments into a 'consistent' order.
4827 SmallVector<Expr*, 5> SubExprs;
4828 SubExprs.push_back(Ptr);
4829 switch (Form) {
4830 case Init:
4831 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4832 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4833 break;
4834 case Load:
4835 case TestAndSetByte:
4836 case ClearByte:
4837 SubExprs.push_back(APIOrderedArgs[1]); // Order
4838 break;
4839 case LoadCopy:
4840 case Copy:
4841 case Arithmetic:
4842 case Xchg:
4843 SubExprs.push_back(APIOrderedArgs[2]); // Order
4844 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4845 break;
4846 case GNUXchg:
4847 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4848 SubExprs.push_back(APIOrderedArgs[3]); // Order
4849 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4850 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4851 break;
4852 case C11CmpXchg:
4853 SubExprs.push_back(APIOrderedArgs[3]); // Order
4854 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4855 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4856 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4857 break;
4858 case GNUCmpXchg:
4859 SubExprs.push_back(APIOrderedArgs[4]); // Order
4860 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4861 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4862 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4863 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4864 break;
4865 }
4866
4867 // If the memory orders are constants, check they are valid.
4868 if (SubExprs.size() >= 2 && Form != Init) {
4869 std::optional<llvm::APSInt> Success =
4870 SubExprs[1]->getIntegerConstantExpr(Context);
4871 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4872 Diag(SubExprs[1]->getBeginLoc(),
4873 diag::warn_atomic_op_has_invalid_memory_order)
4874 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4875 << SubExprs[1]->getSourceRange();
4876 }
4877 if (SubExprs.size() >= 5) {
4878 if (std::optional<llvm::APSInt> Failure =
4879 SubExprs[3]->getIntegerConstantExpr(Context)) {
4880 if (!llvm::is_contained(
4881 {llvm::AtomicOrderingCABI::relaxed,
4882 llvm::AtomicOrderingCABI::consume,
4883 llvm::AtomicOrderingCABI::acquire,
4884 llvm::AtomicOrderingCABI::seq_cst},
4885 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4886 Diag(SubExprs[3]->getBeginLoc(),
4887 diag::warn_atomic_op_has_invalid_memory_order)
4888 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4889 }
4890 }
4891 }
4892 }
4893
4894 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4895 auto *Scope = Args[Args.size() - 1];
4896 if (std::optional<llvm::APSInt> Result =
4897 Scope->getIntegerConstantExpr(Context)) {
4898 if (!ScopeModel->isValid(Result->getZExtValue()))
4899 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4900 << Scope->getSourceRange();
4901 }
4902 SubExprs.push_back(Scope);
4903 }
4904
4905 AtomicExpr *AE = new (Context)
4906 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4907
4908 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4909 Op == AtomicExpr::AO__c11_atomic_store ||
4910 Op == AtomicExpr::AO__opencl_atomic_load ||
4911 Op == AtomicExpr::AO__hip_atomic_load ||
4912 Op == AtomicExpr::AO__opencl_atomic_store ||
4913 Op == AtomicExpr::AO__hip_atomic_store) &&
4914 Context.AtomicUsesUnsupportedLibcall(AE))
4915 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4916 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4917 Op == AtomicExpr::AO__opencl_atomic_load ||
4918 Op == AtomicExpr::AO__hip_atomic_load)
4919 ? 0
4920 : 1);
4921
4922 if (ValType->isBitIntType()) {
4923 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4924 return ExprError();
4925 }
4926
4927 return AE;
4928}
4929
4930/// checkBuiltinArgument - Given a call to a builtin function, perform
4931/// normal type-checking on the given argument, updating the call in
4932/// place. This is useful when a builtin function requires custom
4933/// type-checking for some of its arguments but not necessarily all of
4934/// them.
4935///
4936/// Returns true on error.
4937static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4938 FunctionDecl *Fn = E->getDirectCallee();
4939 assert(Fn && "builtin call without direct callee!");
4940
4941 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4942 InitializedEntity Entity =
4944
4945 ExprResult Arg = E->getArg(ArgIndex);
4946 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4947 if (Arg.isInvalid())
4948 return true;
4949
4950 E->setArg(ArgIndex, Arg.get());
4951 return false;
4952}
4953
4954ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4955 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4956 Expr *Callee = TheCall->getCallee();
4957 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4958 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4959
4960 // Ensure that we have at least one argument to do type inference from.
4961 if (TheCall->getNumArgs() < 1) {
4962 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4963 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4964 << Callee->getSourceRange();
4965 return ExprError();
4966 }
4967
4968 // Inspect the first argument of the atomic builtin. This should always be
4969 // a pointer type, whose element is an integral scalar or pointer type.
4970 // Because it is a pointer type, we don't have to worry about any implicit
4971 // casts here.
4972 // FIXME: We don't allow floating point scalars as input.
4973 Expr *FirstArg = TheCall->getArg(0);
4974 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4975 if (FirstArgResult.isInvalid())
4976 return ExprError();
4977 FirstArg = FirstArgResult.get();
4978 TheCall->setArg(0, FirstArg);
4979
4980 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4981 if (!pointerType) {
4982 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4983 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4984 return ExprError();
4985 }
4986
4987 QualType ValType = pointerType->getPointeeType();
4988 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4989 !ValType->isBlockPointerType()) {
4990 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4991 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4992 return ExprError();
4993 }
4994 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4995 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4996 Diag(FirstArg->getBeginLoc(),
4997 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4998 << 1 << ValType << FirstArg->getSourceRange();
4999 return ExprError();
5000 }
5001
5002 if (ValType.isConstQualified()) {
5003 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5004 << FirstArg->getType() << FirstArg->getSourceRange();
5005 return ExprError();
5006 }
5007
5008 switch (ValType.getObjCLifetime()) {
5011 // okay
5012 break;
5013
5017 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5018 << ValType << FirstArg->getSourceRange();
5019 return ExprError();
5020 }
5021
5022 // Strip any qualifiers off ValType.
5023 ValType = ValType.getUnqualifiedType();
5024
5025 // The majority of builtins return a value, but a few have special return
5026 // types, so allow them to override appropriately below.
5027 QualType ResultType = ValType;
5028
5029 // We need to figure out which concrete builtin this maps onto. For example,
5030 // __sync_fetch_and_add with a 2 byte object turns into
5031 // __sync_fetch_and_add_2.
5032#define BUILTIN_ROW(x) \
5033 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5034 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5035
5036 static const unsigned BuiltinIndices[][5] = {
5037 BUILTIN_ROW(__sync_fetch_and_add),
5038 BUILTIN_ROW(__sync_fetch_and_sub),
5039 BUILTIN_ROW(__sync_fetch_and_or),
5040 BUILTIN_ROW(__sync_fetch_and_and),
5041 BUILTIN_ROW(__sync_fetch_and_xor),
5042 BUILTIN_ROW(__sync_fetch_and_nand),
5043
5044 BUILTIN_ROW(__sync_add_and_fetch),
5045 BUILTIN_ROW(__sync_sub_and_fetch),
5046 BUILTIN_ROW(__sync_and_and_fetch),
5047 BUILTIN_ROW(__sync_or_and_fetch),
5048 BUILTIN_ROW(__sync_xor_and_fetch),
5049 BUILTIN_ROW(__sync_nand_and_fetch),
5050
5051 BUILTIN_ROW(__sync_val_compare_and_swap),
5052 BUILTIN_ROW(__sync_bool_compare_and_swap),
5053 BUILTIN_ROW(__sync_lock_test_and_set),
5054 BUILTIN_ROW(__sync_lock_release),
5055 BUILTIN_ROW(__sync_swap)
5056 };
5057#undef BUILTIN_ROW
5058
5059 // Determine the index of the size.
5060 unsigned SizeIndex;
5061 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5062 case 1: SizeIndex = 0; break;
5063 case 2: SizeIndex = 1; break;
5064 case 4: SizeIndex = 2; break;
5065 case 8: SizeIndex = 3; break;
5066 case 16: SizeIndex = 4; break;
5067 default:
5068 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5069 << FirstArg->getType() << FirstArg->getSourceRange();
5070 return ExprError();
5071 }
5072
5073 // Each of these builtins has one pointer argument, followed by some number of
5074 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5075 // that we ignore. Find out which row of BuiltinIndices to read from as well
5076 // as the number of fixed args.
5077 unsigned BuiltinID = FDecl->getBuiltinID();
5078 unsigned BuiltinIndex, NumFixed = 1;
5079 bool WarnAboutSemanticsChange = false;
5080 switch (BuiltinID) {
5081 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5082 case Builtin::BI__sync_fetch_and_add:
5083 case Builtin::BI__sync_fetch_and_add_1:
5084 case Builtin::BI__sync_fetch_and_add_2:
5085 case Builtin::BI__sync_fetch_and_add_4:
5086 case Builtin::BI__sync_fetch_and_add_8:
5087 case Builtin::BI__sync_fetch_and_add_16:
5088 BuiltinIndex = 0;
5089 break;
5090
5091 case Builtin::BI__sync_fetch_and_sub:
5092 case Builtin::BI__sync_fetch_and_sub_1:
5093 case Builtin::BI__sync_fetch_and_sub_2:
5094 case Builtin::BI__sync_fetch_and_sub_4:
5095 case Builtin::BI__sync_fetch_and_sub_8:
5096 case Builtin::BI__sync_fetch_and_sub_16:
5097 BuiltinIndex = 1;
5098 break;
5099
5100 case Builtin::BI__sync_fetch_and_or:
5101 case Builtin::BI__sync_fetch_and_or_1:
5102 case Builtin::BI__sync_fetch_and_or_2:
5103 case Builtin::BI__sync_fetch_and_or_4:
5104 case Builtin::BI__sync_fetch_and_or_8:
5105 case Builtin::BI__sync_fetch_and_or_16:
5106 BuiltinIndex = 2;
5107 break;
5108
5109 case Builtin::BI__sync_fetch_and_and:
5110 case Builtin::BI__sync_fetch_and_and_1:
5111 case Builtin::BI__sync_fetch_and_and_2:
5112 case Builtin::BI__sync_fetch_and_and_4:
5113 case Builtin::BI__sync_fetch_and_and_8:
5114 case Builtin::BI__sync_fetch_and_and_16:
5115 BuiltinIndex = 3;
5116 break;
5117
5118 case Builtin::BI__sync_fetch_and_xor:
5119 case Builtin::BI__sync_fetch_and_xor_1:
5120 case Builtin::BI__sync_fetch_and_xor_2:
5121 case Builtin::BI__sync_fetch_and_xor_4:
5122 case Builtin::BI__sync_fetch_and_xor_8:
5123 case Builtin::BI__sync_fetch_and_xor_16:
5124 BuiltinIndex = 4;
5125 break;
5126
5127 case Builtin::BI__sync_fetch_and_nand:
5128 case Builtin::BI__sync_fetch_and_nand_1:
5129 case Builtin::BI__sync_fetch_and_nand_2:
5130 case Builtin::BI__sync_fetch_and_nand_4:
5131 case Builtin::BI__sync_fetch_and_nand_8:
5132 case Builtin::BI__sync_fetch_and_nand_16:
5133 BuiltinIndex = 5;
5134 WarnAboutSemanticsChange = true;
5135 break;
5136
5137 case Builtin::BI__sync_add_and_fetch:
5138 case Builtin::BI__sync_add_and_fetch_1:
5139 case Builtin::BI__sync_add_and_fetch_2:
5140 case Builtin::BI__sync_add_and_fetch_4:
5141 case Builtin::BI__sync_add_and_fetch_8:
5142 case Builtin::BI__sync_add_and_fetch_16:
5143 BuiltinIndex = 6;
5144 break;
5145
5146 case Builtin::BI__sync_sub_and_fetch:
5147 case Builtin::BI__sync_sub_and_fetch_1:
5148 case Builtin::BI__sync_sub_and_fetch_2:
5149 case Builtin::BI__sync_sub_and_fetch_4:
5150 case Builtin::BI__sync_sub_and_fetch_8:
5151 case Builtin::BI__sync_sub_and_fetch_16:
5152 BuiltinIndex = 7;
5153 break;
5154
5155 case Builtin::BI__sync_and_and_fetch:
5156 case Builtin::BI__sync_and_and_fetch_1:
5157 case Builtin::BI__sync_and_and_fetch_2:
5158 case Builtin::BI__sync_and_and_fetch_4:
5159 case Builtin::BI__sync_and_and_fetch_8:
5160 case Builtin::BI__sync_and_and_fetch_16:
5161 BuiltinIndex = 8;
5162 break;
5163
5164 case Builtin::BI__sync_or_and_fetch:
5165 case Builtin::BI__sync_or_and_fetch_1:
5166 case Builtin::BI__sync_or_and_fetch_2:
5167 case Builtin::BI__sync_or_and_fetch_4:
5168 case Builtin::BI__sync_or_and_fetch_8:
5169 case Builtin::BI__sync_or_and_fetch_16:
5170 BuiltinIndex = 9;
5171 break;
5172
5173 case Builtin::BI__sync_xor_and_fetch:
5174 case Builtin::BI__sync_xor_and_fetch_1:
5175 case Builtin::BI__sync_xor_and_fetch_2:
5176 case Builtin::BI__sync_xor_and_fetch_4:
5177 case Builtin::BI__sync_xor_and_fetch_8:
5178 case Builtin::BI__sync_xor_and_fetch_16:
5179 BuiltinIndex = 10;
5180 break;
5181
5182 case Builtin::BI__sync_nand_and_fetch:
5183 case Builtin::BI__sync_nand_and_fetch_1:
5184 case Builtin::BI__sync_nand_and_fetch_2:
5185 case Builtin::BI__sync_nand_and_fetch_4:
5186 case Builtin::BI__sync_nand_and_fetch_8:
5187 case Builtin::BI__sync_nand_and_fetch_16:
5188 BuiltinIndex = 11;
5189 WarnAboutSemanticsChange = true;
5190 break;
5191
5192 case Builtin::BI__sync_val_compare_and_swap:
5193 case Builtin::BI__sync_val_compare_and_swap_1:
5194 case Builtin::BI__sync_val_compare_and_swap_2:
5195 case Builtin::BI__sync_val_compare_and_swap_4:
5196 case Builtin::BI__sync_val_compare_and_swap_8:
5197 case Builtin::BI__sync_val_compare_and_swap_16:
5198 BuiltinIndex = 12;
5199 NumFixed = 2;
5200 break;
5201
5202 case Builtin::BI__sync_bool_compare_and_swap:
5203 case Builtin::BI__sync_bool_compare_and_swap_1:
5204 case Builtin::BI__sync_bool_compare_and_swap_2:
5205 case Builtin::BI__sync_bool_compare_and_swap_4:
5206 case Builtin::BI__sync_bool_compare_and_swap_8:
5207 case Builtin::BI__sync_bool_compare_and_swap_16:
5208 BuiltinIndex = 13;
5209 NumFixed = 2;
5210 ResultType = Context.BoolTy;
5211 break;
5212
5213 case Builtin::BI__sync_lock_test_and_set:
5214 case Builtin::BI__sync_lock_test_and_set_1:
5215 case Builtin::BI__sync_lock_test_and_set_2:
5216 case Builtin::BI__sync_lock_test_and_set_4:
5217 case Builtin::BI__sync_lock_test_and_set_8:
5218 case Builtin::BI__sync_lock_test_and_set_16:
5219 BuiltinIndex = 14;
5220 break;
5221
5222 case Builtin::BI__sync_lock_release:
5223 case Builtin::BI__sync_lock_release_1:
5224 case Builtin::BI__sync_lock_release_2:
5225 case Builtin::BI__sync_lock_release_4:
5226 case Builtin::BI__sync_lock_release_8:
5227 case Builtin::BI__sync_lock_release_16:
5228 BuiltinIndex = 15;
5229 NumFixed = 0;
5230 ResultType = Context.VoidTy;
5231 break;
5232
5233 case Builtin::BI__sync_swap:
5234 case Builtin::BI__sync_swap_1:
5235 case Builtin::BI__sync_swap_2:
5236 case Builtin::BI__sync_swap_4:
5237 case Builtin::BI__sync_swap_8:
5238 case Builtin::BI__sync_swap_16:
5239 BuiltinIndex = 16;
5240 break;
5241 }
5242
5243 // Now that we know how many fixed arguments we expect, first check that we
5244 // have at least that many.
5245 if (TheCall->getNumArgs() < 1+NumFixed) {
5246 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5247 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5248 << Callee->getSourceRange();
5249 return ExprError();
5250 }
5251
5252 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5253 << Callee->getSourceRange();
5254
5255 if (WarnAboutSemanticsChange) {
5256 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5257 << Callee->getSourceRange();
5258 }
5259
5260 // Get the decl for the concrete builtin from this, we can tell what the
5261 // concrete integer type we should convert to is.
5262 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5263 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5264 FunctionDecl *NewBuiltinDecl;
5265 if (NewBuiltinID == BuiltinID)
5266 NewBuiltinDecl = FDecl;
5267 else {
5268 // Perform builtin lookup to avoid redeclaring it.
5269 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5270 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5271 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5272 assert(Res.getFoundDecl());
5273 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5274 if (!NewBuiltinDecl)
5275 return ExprError();
5276 }
5277
5278 // The first argument --- the pointer --- has a fixed type; we
5279 // deduce the types of the rest of the arguments accordingly. Walk
5280 // the remaining arguments, converting them to the deduced value type.
5281 for (unsigned i = 0; i != NumFixed; ++i) {
5282 ExprResult Arg = TheCall->getArg(i+1);
5283
5284 // GCC does an implicit conversion to the pointer or integer ValType. This
5285 // can fail in some cases (1i -> int**), check for this error case now.
5286 // Initialize the argument.
5287 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5288 ValType, /*consume*/ false);
5289 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5290 if (Arg.isInvalid())
5291 return ExprError();
5292
5293 // Okay, we have something that *can* be converted to the right type. Check
5294 // to see if there is a potentially weird extension going on here. This can
5295 // happen when you do an atomic operation on something like an char* and
5296 // pass in 42. The 42 gets converted to char. This is even more strange
5297 // for things like 45.123 -> char, etc.
5298 // FIXME: Do this check.
5299 TheCall->setArg(i+1, Arg.get());
5300 }
5301
5302 // Create a new DeclRefExpr to refer to the new decl.
5303 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5304 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5305 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5306 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5307
5308 // Set the callee in the CallExpr.
5309 // FIXME: This loses syntactic information.
5310 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5311 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5312 CK_BuiltinFnToFnPtr);
5313 TheCall->setCallee(PromotedCall.get());
5314
5315 // Change the result type of the call to match the original value type. This
5316 // is arbitrary, but the codegen for these builtins ins design to handle it
5317 // gracefully.
5318 TheCall->setType(ResultType);
5319
5320 // Prohibit problematic uses of bit-precise integer types with atomic
5321 // builtins. The arguments would have already been converted to the first
5322 // argument's type, so only need to check the first argument.
5323 const auto *BitIntValType = ValType->getAs<BitIntType>();
5324 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5325 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5326 return ExprError();
5327 }
5328
5329 return TheCallResult;
5330}
5331
5332ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5333 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5334 DeclRefExpr *DRE =
5336 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5337 unsigned BuiltinID = FDecl->getBuiltinID();
5338 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5339 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5340 "Unexpected nontemporal load/store builtin!");
5341 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5342 unsigned numArgs = isStore ? 2 : 1;
5343
5344 // Ensure that we have the proper number of arguments.
5345 if (checkArgCount(TheCall, numArgs))
5346 return ExprError();
5347
5348 // Inspect the last argument of the nontemporal builtin. This should always
5349 // be a pointer type, from which we imply the type of the memory access.
5350 // Because it is a pointer type, we don't have to worry about any implicit
5351 // casts here.
5352 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5353 ExprResult PointerArgResult =
5355
5356 if (PointerArgResult.isInvalid())
5357 return ExprError();
5358 PointerArg = PointerArgResult.get();
5359 TheCall->setArg(numArgs - 1, PointerArg);
5360
5361 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5362 if (!pointerType) {
5363 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5364 << PointerArg->getType() << PointerArg->getSourceRange();
5365 return ExprError();
5366 }
5367
5368 QualType ValType = pointerType->getPointeeType();
5369
5370 // Strip any qualifiers off ValType.
5371 ValType = ValType.getUnqualifiedType();
5372 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5373 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5374 !ValType->isVectorType()) {
5375 Diag(DRE->getBeginLoc(),
5376 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5377 << PointerArg->getType() << PointerArg->getSourceRange();
5378 return ExprError();
5379 }
5380
5381 if (!isStore) {
5382 TheCall->setType(ValType);
5383 return TheCallResult;
5384 }
5385
5386 ExprResult ValArg = TheCall->getArg(0);
5387 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5388 Context, ValType, /*consume*/ false);
5389 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5390 if (ValArg.isInvalid())
5391 return ExprError();
5392
5393 TheCall->setArg(0, ValArg.get());
5394 TheCall->setType(Context.VoidTy);
5395 return TheCallResult;
5396}
5397
5398/// CheckObjCString - Checks that the format string argument to the os_log()
5399/// and os_trace() functions is correct, and converts it to const char *.
5400ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5401 Arg = Arg->IgnoreParenCasts();
5402 auto *Literal = dyn_cast<StringLiteral>(Arg);
5403 if (!Literal) {
5404 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5405 Literal = ObjcLiteral->getString();
5406 }
5407 }
5408
5409 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5410 return ExprError(
5411 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5412 << Arg->getSourceRange());
5413 }
5414
5415 ExprResult Result(Literal);
5416 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5417 InitializedEntity Entity =
5419 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5420 return Result;
5421}
5422
5423/// Check that the user is calling the appropriate va_start builtin for the
5424/// target and calling convention.
5425static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5426 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5427 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5428 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5429 TT.getArch() == llvm::Triple::aarch64_32);
5430 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5431 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5432 if (IsX64 || IsAArch64) {
5433 CallingConv CC = CC_C;
5434 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5435 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5436 if (IsMSVAStart) {
5437 // Don't allow this in System V ABI functions.
5438 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5439 return S.Diag(Fn->getBeginLoc(),
5440 diag::err_ms_va_start_used_in_sysv_function);
5441 } else {
5442 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5443 // On x64 Windows, don't allow this in System V ABI functions.
5444 // (Yes, that means there's no corresponding way to support variadic
5445 // System V ABI functions on Windows.)
5446 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5447 (!IsWindowsOrUEFI && CC == CC_Win64))
5448 return S.Diag(Fn->getBeginLoc(),
5449 diag::err_va_start_used_in_wrong_abi_function)
5450 << !IsWindowsOrUEFI;
5451 }
5452 return false;
5453 }
5454
5455 if (IsMSVAStart)
5456 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5457 return false;
5458}
5459
5461 ParmVarDecl **LastParam = nullptr) {
5462 // Determine whether the current function, block, or obj-c method is variadic
5463 // and get its parameter list.
5464 bool IsVariadic = false;
5466 DeclContext *Caller = S.CurContext;
5467 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5468 IsVariadic = Block->isVariadic();
5469 Params = Block->parameters();
5470 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5471 IsVariadic = FD->isVariadic();
5472 Params = FD->parameters();
5473 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5474 IsVariadic = MD->isVariadic();
5475 // FIXME: This isn't correct for methods (results in bogus warning).
5476 Params = MD->parameters();
5477 } else if (isa<CapturedDecl>(Caller)) {
5478 // We don't support va_start in a CapturedDecl.
5479 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5480 return true;
5481 } else {
5482 // This must be some other declcontext that parses exprs.
5483 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5484 return true;
5485 }
5486
5487 if (!IsVariadic) {
5488 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5489 return true;
5490 }
5491
5492 if (LastParam)
5493 *LastParam = Params.empty() ? nullptr : Params.back();
5494
5495 return false;
5496}
5497
5498bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5499 Expr *Fn = TheCall->getCallee();
5500 if (checkVAStartABI(*this, BuiltinID, Fn))
5501 return true;
5502
5503 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5504 // This builtin requires one argument (the va_list), allows two arguments,
5505 // but diagnoses more than two arguments. e.g.,
5506 // __builtin_c23_va_start(); // error
5507 // __builtin_c23_va_start(list); // ok
5508 // __builtin_c23_va_start(list, param); // ok
5509 // __builtin_c23_va_start(list, anything, anything); // error
5510 // This differs from the GCC behavior in that they accept the last case
5511 // with a warning, but it doesn't seem like a useful behavior to allow.
5512 if (checkArgCountRange(TheCall, 1, 2))
5513 return true;
5514 } else {
5515 // In C23 mode, va_start only needs one argument. However, the builtin still
5516 // requires two arguments (which matches the behavior of the GCC builtin),
5517 // <stdarg.h> passes `0` as the second argument in C23 mode.
5518 if (checkArgCount(TheCall, 2))
5519 return true;
5520 }
5521
5522 // Type-check the first argument normally.
5523 if (checkBuiltinArgument(*this, TheCall, 0))
5524 return true;
5525
5526 // Check that the current function is variadic, and get its last parameter.
5527 ParmVarDecl *LastParam;
5528 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5529 return true;
5530
5531 // Verify that the second argument to the builtin is the last non-variadic
5532 // argument of the current function or method. In C23 mode, if the call is
5533 // not to __builtin_c23_va_start, and the second argument is an integer
5534 // constant expression with value 0, then we don't bother with this check.
5535 // For __builtin_c23_va_start, we only perform the check for the second
5536 // argument being the last argument to the current function if there is a
5537 // second argument present.
5538 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5539 TheCall->getNumArgs() < 2) {
5540 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5541 return false;
5542 }
5543
5544 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5545 if (std::optional<llvm::APSInt> Val =
5547 Val && LangOpts.C23 && *Val == 0 &&
5548 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5549 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5550 return false;
5551 }
5552
5553 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5554 // next block.
5555 QualType Type;
5556 SourceLocation ParamLoc;
5557 bool IsCRegister = false;
5558 bool SecondArgIsLastNonVariadicArgument = false;
5559 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5560 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5561 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5562
5563 Type = PV->getType();
5564 ParamLoc = PV->getLocation();
5565 IsCRegister =
5566 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5567 }
5568 }
5569
5570 if (!SecondArgIsLastNonVariadicArgument)
5571 Diag(TheCall->getArg(1)->getBeginLoc(),
5572 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5573 else if (IsCRegister || Type->isReferenceType() ||
5574 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5575 // Promotable integers are UB, but enumerations need a bit of
5576 // extra checking to see what their promotable type actually is.
5577 if (!Context.isPromotableIntegerType(Type))
5578 return false;
5579 const auto *ED = Type->getAsEnumDecl();
5580 if (!ED)
5581 return true;
5582 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5583 }()) {
5584 unsigned Reason = 0;
5585 if (Type->isReferenceType()) Reason = 1;
5586 else if (IsCRegister) Reason = 2;
5587 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5588 Diag(ParamLoc, diag::note_parameter_type) << Type;
5589 }
5590
5591 return false;
5592}
5593
5594bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5595 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5596 const LangOptions &LO = getLangOpts();
5597
5598 if (LO.CPlusPlus)
5599 return Arg->getType()
5601 .getTypePtr()
5602 ->getPointeeType()
5604
5605 // In C, allow aliasing through `char *`, this is required for AArch64 at
5606 // least.
5607 return true;
5608 };
5609
5610 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5611 // const char *named_addr);
5612
5613 Expr *Func = Call->getCallee();
5614
5615 if (Call->getNumArgs() < 3)
5616 return Diag(Call->getEndLoc(),
5617 diag::err_typecheck_call_too_few_args_at_least)
5618 << 0 /*function call*/ << 3 << Call->getNumArgs()
5619 << /*is non object*/ 0;
5620
5621 // Type-check the first argument normally.
5622 if (checkBuiltinArgument(*this, Call, 0))
5623 return true;
5624
5625 // Check that the current function is variadic.
5627 return true;
5628
5629 // __va_start on Windows does not validate the parameter qualifiers
5630
5631 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5632 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5633
5634 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5635 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5636
5637 const QualType &ConstCharPtrTy =
5638 Context.getPointerType(Context.CharTy.withConst());
5639 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5640 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5641 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5642 << 0 /* qualifier difference */
5643 << 3 /* parameter mismatch */
5644 << 2 << Arg1->getType() << ConstCharPtrTy;
5645
5646 const QualType SizeTy = Context.getSizeType();
5647 if (!Context.hasSameType(
5649 SizeTy))
5650 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5651 << Arg2->getType() << SizeTy << 1 /* different class */
5652 << 0 /* qualifier difference */
5653 << 3 /* parameter mismatch */
5654 << 3 << Arg2->getType() << SizeTy;
5655
5656 return false;
5657}
5658
5659bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5660 if (checkArgCount(TheCall, 2))
5661 return true;
5662
5663 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5664 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5665 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5666 << 1 << 0 << TheCall->getSourceRange();
5667
5668 ExprResult OrigArg0 = TheCall->getArg(0);
5669 ExprResult OrigArg1 = TheCall->getArg(1);
5670
5671 // Do standard promotions between the two arguments, returning their common
5672 // type.
5673 QualType Res = UsualArithmeticConversions(
5674 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5675 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5676 return true;
5677
5678 // Make sure any conversions are pushed back into the call; this is
5679 // type safe since unordered compare builtins are declared as "_Bool
5680 // foo(...)".
5681 TheCall->setArg(0, OrigArg0.get());
5682 TheCall->setArg(1, OrigArg1.get());
5683
5684 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5685 return false;
5686
5687 // If the common type isn't a real floating type, then the arguments were
5688 // invalid for this operation.
5689 if (Res.isNull() || !Res->isRealFloatingType())
5690 return Diag(OrigArg0.get()->getBeginLoc(),
5691 diag::err_typecheck_call_invalid_ordered_compare)
5692 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5693 << SourceRange(OrigArg0.get()->getBeginLoc(),
5694 OrigArg1.get()->getEndLoc());
5695
5696 return false;
5697}
5698
5699bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5700 unsigned BuiltinID) {
5701 if (checkArgCount(TheCall, NumArgs))
5702 return true;
5703
5704 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5705 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5706 BuiltinID == Builtin::BI__builtin_isinf ||
5707 BuiltinID == Builtin::BI__builtin_isinf_sign))
5708 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5709 << 0 << 0 << TheCall->getSourceRange();
5710
5711 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5712 BuiltinID == Builtin::BI__builtin_isunordered))
5713 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5714 << 1 << 0 << TheCall->getSourceRange();
5715
5716 bool IsFPClass = NumArgs == 2;
5717
5718 // Find out position of floating-point argument.
5719 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5720
5721 // We can count on all parameters preceding the floating-point just being int.
5722 // Try all of those.
5723 for (unsigned i = 0; i < FPArgNo; ++i) {
5724 Expr *Arg = TheCall->getArg(i);
5725
5726 if (Arg->isTypeDependent())
5727 return false;
5728
5731
5732 if (Res.isInvalid())
5733 return true;
5734 TheCall->setArg(i, Res.get());
5735 }
5736
5737 Expr *OrigArg = TheCall->getArg(FPArgNo);
5738
5739 if (OrigArg->isTypeDependent())
5740 return false;
5741
5742 // Usual Unary Conversions will convert half to float, which we want for
5743 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5744 // type how it is, but do normal L->Rvalue conversions.
5745 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5746 ExprResult Res = UsualUnaryConversions(OrigArg);
5747
5748 if (!Res.isUsable())
5749 return true;
5750 OrigArg = Res.get();
5751 } else {
5753
5754 if (!Res.isUsable())
5755 return true;
5756 OrigArg = Res.get();
5757 }
5758 TheCall->setArg(FPArgNo, OrigArg);
5759
5760 QualType VectorResultTy;
5761 QualType ElementTy = OrigArg->getType();
5762 // TODO: When all classification function are implemented with is_fpclass,
5763 // vector argument can be supported in all of them.
5764 if (ElementTy->isVectorType() && IsFPClass) {
5765 VectorResultTy = GetSignedVectorType(ElementTy);
5766 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5767 }
5768
5769 // This operation requires a non-_Complex floating-point number.
5770 if (!ElementTy->isRealFloatingType())
5771 return Diag(OrigArg->getBeginLoc(),
5772 diag::err_typecheck_call_invalid_unary_fp)
5773 << OrigArg->getType() << OrigArg->getSourceRange();
5774
5775 // __builtin_isfpclass has integer parameter that specify test mask. It is
5776 // passed in (...), so it should be analyzed completely here.
5777 if (IsFPClass)
5778 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5779 return true;
5780
5781 // TODO: enable this code to all classification functions.
5782 if (IsFPClass) {
5783 QualType ResultTy;
5784 if (!VectorResultTy.isNull())
5785 ResultTy = VectorResultTy;
5786 else
5787 ResultTy = Context.IntTy;
5788 TheCall->setType(ResultTy);
5789 }
5790
5791 return false;
5792}
5793
5794bool Sema::BuiltinComplex(CallExpr *TheCall) {
5795 if (checkArgCount(TheCall, 2))
5796 return true;
5797
5798 bool Dependent = false;
5799 for (unsigned I = 0; I != 2; ++I) {
5800 Expr *Arg = TheCall->getArg(I);
5801 QualType T = Arg->getType();
5802 if (T->isDependentType()) {
5803 Dependent = true;
5804 continue;
5805 }
5806
5807 // Despite supporting _Complex int, GCC requires a real floating point type
5808 // for the operands of __builtin_complex.
5809 if (!T->isRealFloatingType()) {
5810 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5811 << Arg->getType() << Arg->getSourceRange();
5812 }
5813
5814 ExprResult Converted = DefaultLvalueConversion(Arg);
5815 if (Converted.isInvalid())
5816 return true;
5817 TheCall->setArg(I, Converted.get());
5818 }
5819
5820 if (Dependent) {
5821 TheCall->setType(Context.DependentTy);
5822 return false;
5823 }
5824
5825 Expr *Real = TheCall->getArg(0);
5826 Expr *Imag = TheCall->getArg(1);
5827 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5828 return Diag(Real->getBeginLoc(),
5829 diag::err_typecheck_call_different_arg_types)
5830 << Real->getType() << Imag->getType()
5831 << Real->getSourceRange() << Imag->getSourceRange();
5832 }
5833
5834 TheCall->setType(Context.getComplexType(Real->getType()));
5835 return false;
5836}
5837
5838/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5839// This is declared to take (...), so we have to check everything.
5841 unsigned NumArgs = TheCall->getNumArgs();
5842 if (NumArgs < 2)
5843 return ExprError(Diag(TheCall->getEndLoc(),
5844 diag::err_typecheck_call_too_few_args_at_least)
5845 << 0 /*function call*/ << 2 << NumArgs
5846 << /*is non object*/ 0 << TheCall->getSourceRange());
5847
5848 // Determine which of the following types of shufflevector we're checking:
5849 // 1) unary, vector mask: (lhs, mask)
5850 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5851 QualType ResType = TheCall->getArg(0)->getType();
5852 unsigned NumElements = 0;
5853
5854 if (!TheCall->getArg(0)->isTypeDependent() &&
5855 !TheCall->getArg(1)->isTypeDependent()) {
5856 QualType LHSType = TheCall->getArg(0)->getType();
5857 QualType RHSType = TheCall->getArg(1)->getType();
5858
5859 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5860 return ExprError(
5861 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5862 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5863 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5864 TheCall->getArg(1)->getEndLoc()));
5865
5866 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5867 unsigned NumResElements = NumArgs - 2;
5868
5869 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5870 // with mask. If so, verify that RHS is an integer vector type with the
5871 // same number of elts as lhs.
5872 if (NumArgs == 2) {
5873 if (!RHSType->hasIntegerRepresentation() ||
5874 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5875 return ExprError(Diag(TheCall->getBeginLoc(),
5876 diag::err_vec_builtin_incompatible_vector)
5877 << TheCall->getDirectCallee()
5878 << /*isMoreThanTwoArgs*/ false
5879 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5880 TheCall->getArg(1)->getEndLoc()));
5881 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5882 return ExprError(Diag(TheCall->getBeginLoc(),
5883 diag::err_vec_builtin_incompatible_vector)
5884 << TheCall->getDirectCallee()
5885 << /*isMoreThanTwoArgs*/ false
5886 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5887 TheCall->getArg(1)->getEndLoc()));
5888 } else if (NumElements != NumResElements) {
5889 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5890 ResType = ResType->isExtVectorType()
5891 ? Context.getExtVectorType(EltType, NumResElements)
5892 : Context.getVectorType(EltType, NumResElements,
5894 }
5895 }
5896
5897 for (unsigned I = 2; I != NumArgs; ++I) {
5898 Expr *Arg = TheCall->getArg(I);
5899 if (Arg->isTypeDependent() || Arg->isValueDependent())
5900 continue;
5901
5902 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5903 if (!Result)
5904 return ExprError(Diag(TheCall->getBeginLoc(),
5905 diag::err_shufflevector_nonconstant_argument)
5906 << Arg->getSourceRange());
5907
5908 // Allow -1 which will be translated to undef in the IR.
5909 if (Result->isSigned() && Result->isAllOnes())
5910 ;
5911 else if (Result->getActiveBits() > 64 ||
5912 Result->getZExtValue() >= NumElements * 2)
5913 return ExprError(Diag(TheCall->getBeginLoc(),
5914 diag::err_shufflevector_argument_too_large)
5915 << Arg->getSourceRange());
5916
5917 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5918 }
5919
5920 auto *Result = new (Context) ShuffleVectorExpr(
5921 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5922 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5923
5924 // All moved to Result.
5925 TheCall->shrinkNumArgs(0);
5926 return Result;
5927}
5928
5930 SourceLocation BuiltinLoc,
5931 SourceLocation RParenLoc) {
5934 QualType DstTy = TInfo->getType();
5935 QualType SrcTy = E->getType();
5936
5937 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5938 return ExprError(Diag(BuiltinLoc,
5939 diag::err_convertvector_non_vector)
5940 << E->getSourceRange());
5941 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5942 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5943 << "second"
5944 << "__builtin_convertvector");
5945
5946 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5947 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5948 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5949 if (SrcElts != DstElts)
5950 return ExprError(Diag(BuiltinLoc,
5951 diag::err_convertvector_incompatible_vector)
5952 << E->getSourceRange());
5953 }
5954
5955 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5956 RParenLoc, CurFPFeatureOverrides());
5957}
5958
5959bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5960 unsigned NumArgs = TheCall->getNumArgs();
5961
5962 if (NumArgs > 3)
5963 return Diag(TheCall->getEndLoc(),
5964 diag::err_typecheck_call_too_many_args_at_most)
5965 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5966 << TheCall->getSourceRange();
5967
5968 // Argument 0 is checked for us and the remaining arguments must be
5969 // constant integers.
5970 for (unsigned i = 1; i != NumArgs; ++i)
5971 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5972 return true;
5973
5974 return false;
5975}
5976
5977bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5978 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
5979 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5980 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5981 if (checkArgCount(TheCall, 1))
5982 return true;
5983 Expr *Arg = TheCall->getArg(0);
5984 if (Arg->isInstantiationDependent())
5985 return false;
5986
5987 QualType ArgTy = Arg->getType();
5988 if (!ArgTy->hasFloatingRepresentation())
5989 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5990 << ArgTy;
5991 if (Arg->isLValue()) {
5992 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5993 TheCall->setArg(0, FirstArg.get());
5994 }
5995 TheCall->setType(TheCall->getArg(0)->getType());
5996 return false;
5997}
5998
5999bool Sema::BuiltinAssume(CallExpr *TheCall) {
6000 Expr *Arg = TheCall->getArg(0);
6001 if (Arg->isInstantiationDependent()) return false;
6002
6003 if (Arg->HasSideEffects(Context))
6004 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6005 << Arg->getSourceRange()
6006 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6007
6008 return false;
6009}
6010
6011bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6012 // The alignment must be a constant integer.
6013 Expr *Arg = TheCall->getArg(1);
6014
6015 // We can't check the value of a dependent argument.
6016 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6017 if (const auto *UE =
6018 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6019 if (UE->getKind() == UETT_AlignOf ||
6020 UE->getKind() == UETT_PreferredAlignOf)
6021 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6022 << Arg->getSourceRange();
6023
6024 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6025
6026 if (!Result.isPowerOf2())
6027 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6028 << Arg->getSourceRange();
6029
6030 if (Result < Context.getCharWidth())
6031 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6032 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6033
6034 if (Result > std::numeric_limits<int32_t>::max())
6035 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6036 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6037 }
6038
6039 return false;
6040}
6041
6042bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6043 if (checkArgCountRange(TheCall, 2, 3))
6044 return true;
6045
6046 unsigned NumArgs = TheCall->getNumArgs();
6047 Expr *FirstArg = TheCall->getArg(0);
6048
6049 {
6050 ExprResult FirstArgResult =
6052 if (!FirstArgResult.get()->getType()->isPointerType()) {
6053 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6054 << TheCall->getSourceRange();
6055 return true;
6056 }
6057 TheCall->setArg(0, FirstArgResult.get());
6058 }
6059
6060 // The alignment must be a constant integer.
6061 Expr *SecondArg = TheCall->getArg(1);
6062
6063 // We can't check the value of a dependent argument.
6064 if (!SecondArg->isValueDependent()) {
6065 llvm::APSInt Result;
6066 if (BuiltinConstantArg(TheCall, 1, Result))
6067 return true;
6068
6069 if (!Result.isPowerOf2())
6070 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6071 << SecondArg->getSourceRange();
6072
6074 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6075 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6076
6077 TheCall->setArg(1,
6079 }
6080
6081 if (NumArgs > 2) {
6082 Expr *ThirdArg = TheCall->getArg(2);
6083 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6084 return true;
6085 TheCall->setArg(2, ThirdArg);
6086 }
6087
6088 return false;
6089}
6090
6091bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6092 unsigned BuiltinID =
6093 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6094 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6095
6096 unsigned NumArgs = TheCall->getNumArgs();
6097 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6098 if (NumArgs < NumRequiredArgs) {
6099 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6100 << 0 /* function call */ << NumRequiredArgs << NumArgs
6101 << /*is non object*/ 0 << TheCall->getSourceRange();
6102 }
6103 if (NumArgs >= NumRequiredArgs + 0x100) {
6104 return Diag(TheCall->getEndLoc(),
6105 diag::err_typecheck_call_too_many_args_at_most)
6106 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6107 << /*is non object*/ 0 << TheCall->getSourceRange();
6108 }
6109 unsigned i = 0;
6110
6111 // For formatting call, check buffer arg.
6112 if (!IsSizeCall) {
6113 ExprResult Arg(TheCall->getArg(i));
6114 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6115 Context, Context.VoidPtrTy, false);
6116 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6117 if (Arg.isInvalid())
6118 return true;
6119 TheCall->setArg(i, Arg.get());
6120 i++;
6121 }
6122
6123 // Check string literal arg.
6124 unsigned FormatIdx = i;
6125 {
6126 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6127 if (Arg.isInvalid())
6128 return true;
6129 TheCall->setArg(i, Arg.get());
6130 i++;
6131 }
6132
6133 // Make sure variadic args are scalar.
6134 unsigned FirstDataArg = i;
6135 while (i < NumArgs) {
6137 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6138 if (Arg.isInvalid())
6139 return true;
6140 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6141 if (ArgSize.getQuantity() >= 0x100) {
6142 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6143 << i << (int)ArgSize.getQuantity() << 0xff
6144 << TheCall->getSourceRange();
6145 }
6146 TheCall->setArg(i, Arg.get());
6147 i++;
6148 }
6149
6150 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6151 // call to avoid duplicate diagnostics.
6152 if (!IsSizeCall) {
6153 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6154 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6155 bool Success = CheckFormatArguments(
6156 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6158 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6159 if (!Success)
6160 return true;
6161 }
6162
6163 if (IsSizeCall) {
6164 TheCall->setType(Context.getSizeType());
6165 } else {
6166 TheCall->setType(Context.VoidPtrTy);
6167 }
6168 return false;
6169}
6170
6171bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6172 llvm::APSInt &Result) {
6173 Expr *Arg = TheCall->getArg(ArgNum);
6174
6175 if (Arg->isTypeDependent() || Arg->isValueDependent())
6176 return false;
6177
6178 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6179 if (!R) {
6180 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6181 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6182 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6183 << FDecl->getDeclName() << Arg->getSourceRange();
6184 }
6185 Result = *R;
6186
6187 return false;
6188}
6189
6190bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6191 int High, bool RangeIsError) {
6193 return false;
6194 llvm::APSInt Result;
6195
6196 // We can't check the value of a dependent argument.
6197 Expr *Arg = TheCall->getArg(ArgNum);
6198 if (Arg->isTypeDependent() || Arg->isValueDependent())
6199 return false;
6200
6201 // Check constant-ness first.
6202 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6203 return true;
6204
6205 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6206 if (RangeIsError)
6207 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6208 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6209 else
6210 // Defer the warning until we know if the code will be emitted so that
6211 // dead code can ignore this.
6212 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6213 PDiag(diag::warn_argument_invalid_range)
6214 << toString(Result, 10) << Low << High
6215 << Arg->getSourceRange());
6216 }
6217
6218 return false;
6219}
6220
6221bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6222 unsigned Num) {
6223 llvm::APSInt Result;
6224
6225 // We can't check the value of a dependent argument.
6226 Expr *Arg = TheCall->getArg(ArgNum);
6227 if (Arg->isTypeDependent() || Arg->isValueDependent())
6228 return false;
6229
6230 // Check constant-ness first.
6231 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6232 return true;
6233
6234 if (Result.getSExtValue() % Num != 0)
6235 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6236 << Num << Arg->getSourceRange();
6237
6238 return false;
6239}
6240
6241bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6242 llvm::APSInt Result;
6243
6244 // We can't check the value of a dependent argument.
6245 Expr *Arg = TheCall->getArg(ArgNum);
6246 if (Arg->isTypeDependent() || Arg->isValueDependent())
6247 return false;
6248
6249 // Check constant-ness first.
6250 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6251 return true;
6252
6253 if (Result.isPowerOf2())
6254 return false;
6255
6256 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6257 << Arg->getSourceRange();
6258}
6259
6260static bool IsShiftedByte(llvm::APSInt Value) {
6261 if (Value.isNegative())
6262 return false;
6263
6264 // Check if it's a shifted byte, by shifting it down
6265 while (true) {
6266 // If the value fits in the bottom byte, the check passes.
6267 if (Value < 0x100)
6268 return true;
6269
6270 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6271 // fails.
6272 if ((Value & 0xFF) != 0)
6273 return false;
6274
6275 // If the bottom 8 bits are all 0, but something above that is nonzero,
6276 // then shifting the value right by 8 bits won't affect whether it's a
6277 // shifted byte or not. So do that, and go round again.
6278 Value >>= 8;
6279 }
6280}
6281
6282bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6283 unsigned ArgBits) {
6284 llvm::APSInt Result;
6285
6286 // We can't check the value of a dependent argument.
6287 Expr *Arg = TheCall->getArg(ArgNum);
6288 if (Arg->isTypeDependent() || Arg->isValueDependent())
6289 return false;
6290
6291 // Check constant-ness first.
6292 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6293 return true;
6294
6295 // Truncate to the given size.
6296 Result = Result.getLoBits(ArgBits);
6297 Result.setIsUnsigned(true);
6298
6299 if (IsShiftedByte(Result))
6300 return false;
6301
6302 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6303 << Arg->getSourceRange();
6304}
6305
6307 unsigned ArgNum,
6308 unsigned ArgBits) {
6309 llvm::APSInt Result;
6310
6311 // We can't check the value of a dependent argument.
6312 Expr *Arg = TheCall->getArg(ArgNum);
6313 if (Arg->isTypeDependent() || Arg->isValueDependent())
6314 return false;
6315
6316 // Check constant-ness first.
6317 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6318 return true;
6319
6320 // Truncate to the given size.
6321 Result = Result.getLoBits(ArgBits);
6322 Result.setIsUnsigned(true);
6323
6324 // Check to see if it's in either of the required forms.
6325 if (IsShiftedByte(Result) ||
6326 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6327 return false;
6328
6329 return Diag(TheCall->getBeginLoc(),
6330 diag::err_argument_not_shifted_byte_or_xxff)
6331 << Arg->getSourceRange();
6332}
6333
6334bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6335 if (!Context.getTargetInfo().hasSjLjLowering())
6336 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6337 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6338
6339 Expr *Arg = TheCall->getArg(1);
6340 llvm::APSInt Result;
6341
6342 // TODO: This is less than ideal. Overload this to take a value.
6343 if (BuiltinConstantArg(TheCall, 1, Result))
6344 return true;
6345
6346 if (Result != 1)
6347 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6348 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6349
6350 return false;
6351}
6352
6353bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6354 if (!Context.getTargetInfo().hasSjLjLowering())
6355 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6356 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6357 return false;
6358}
6359
6360bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6361 if (checkArgCount(TheCall, 1))
6362 return true;
6363
6364 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6365 if (ArgRes.isInvalid())
6366 return true;
6367
6368 // For simplicity, we support only limited expressions for the argument.
6369 // Specifically a flexible array member or a pointer with counted_by:
6370 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6371 // complex casting, which really shouldn't be a huge problem.
6372 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6373 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6374 return Diag(Arg->getBeginLoc(),
6375 diag::err_builtin_counted_by_ref_invalid_arg)
6376 << Arg->getSourceRange();
6377
6378 if (Arg->HasSideEffects(Context))
6379 return Diag(Arg->getBeginLoc(),
6380 diag::err_builtin_counted_by_ref_has_side_effects)
6381 << Arg->getSourceRange();
6382
6383 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6384 const auto *CATy =
6385 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6386
6387 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6388 // Member has counted_by attribute - return pointer to count field
6389 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6390 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6391 TheCall->setType(Context.getPointerType(CountFD->getType()));
6392 return false;
6393 }
6394 }
6395
6396 // FAMs and pointers without counted_by return void*
6397 QualType MemberTy = ME->getMemberDecl()->getType();
6398 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6399 return Diag(Arg->getBeginLoc(),
6400 diag::err_builtin_counted_by_ref_invalid_arg)
6401 << Arg->getSourceRange();
6402 } else {
6403 return Diag(Arg->getBeginLoc(),
6404 diag::err_builtin_counted_by_ref_invalid_arg)
6405 << Arg->getSourceRange();
6406 }
6407
6408 TheCall->setType(Context.getPointerType(Context.VoidTy));
6409 return false;
6410}
6411
6412/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6413/// It allows leaking and modification of bounds safety information.
6414bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6416 const CallExpr *CE =
6417 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6418 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6419 return false;
6420
6421 switch (K) {
6424 Diag(E->getExprLoc(),
6425 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6426 << 0 << E->getSourceRange();
6427 break;
6429 Diag(E->getExprLoc(),
6430 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6431 << 1 << E->getSourceRange();
6432 break;
6434 Diag(E->getExprLoc(),
6435 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6436 << 2 << E->getSourceRange();
6437 break;
6439 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6440 << 0 << E->getSourceRange();
6441 break;
6443 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6444 << 1 << E->getSourceRange();
6445 break;
6446 }
6447
6448 return true;
6449}
6450
6451namespace {
6452
6453class UncoveredArgHandler {
6454 enum { Unknown = -1, AllCovered = -2 };
6455
6456 signed FirstUncoveredArg = Unknown;
6457 SmallVector<const Expr *, 4> DiagnosticExprs;
6458
6459public:
6460 UncoveredArgHandler() = default;
6461
6462 bool hasUncoveredArg() const {
6463 return (FirstUncoveredArg >= 0);
6464 }
6465
6466 unsigned getUncoveredArg() const {
6467 assert(hasUncoveredArg() && "no uncovered argument");
6468 return FirstUncoveredArg;
6469 }
6470
6471 void setAllCovered() {
6472 // A string has been found with all arguments covered, so clear out
6473 // the diagnostics.
6474 DiagnosticExprs.clear();
6475 FirstUncoveredArg = AllCovered;
6476 }
6477
6478 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6479 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6480
6481 // Don't update if a previous string covers all arguments.
6482 if (FirstUncoveredArg == AllCovered)
6483 return;
6484
6485 // UncoveredArgHandler tracks the highest uncovered argument index
6486 // and with it all the strings that match this index.
6487 if (NewFirstUncoveredArg == FirstUncoveredArg)
6488 DiagnosticExprs.push_back(StrExpr);
6489 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6490 DiagnosticExprs.clear();
6491 DiagnosticExprs.push_back(StrExpr);
6492 FirstUncoveredArg = NewFirstUncoveredArg;
6493 }
6494 }
6495
6496 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6497};
6498
6499enum StringLiteralCheckType {
6500 SLCT_NotALiteral,
6501 SLCT_UncheckedLiteral,
6502 SLCT_CheckedLiteral
6503};
6504
6505} // namespace
6506
6507static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6508 BinaryOperatorKind BinOpKind,
6509 bool AddendIsRight) {
6510 unsigned BitWidth = Offset.getBitWidth();
6511 unsigned AddendBitWidth = Addend.getBitWidth();
6512 // There might be negative interim results.
6513 if (Addend.isUnsigned()) {
6514 Addend = Addend.zext(++AddendBitWidth);
6515 Addend.setIsSigned(true);
6516 }
6517 // Adjust the bit width of the APSInts.
6518 if (AddendBitWidth > BitWidth) {
6519 Offset = Offset.sext(AddendBitWidth);
6520 BitWidth = AddendBitWidth;
6521 } else if (BitWidth > AddendBitWidth) {
6522 Addend = Addend.sext(BitWidth);
6523 }
6524
6525 bool Ov = false;
6526 llvm::APSInt ResOffset = Offset;
6527 if (BinOpKind == BO_Add)
6528 ResOffset = Offset.sadd_ov(Addend, Ov);
6529 else {
6530 assert(AddendIsRight && BinOpKind == BO_Sub &&
6531 "operator must be add or sub with addend on the right");
6532 ResOffset = Offset.ssub_ov(Addend, Ov);
6533 }
6534
6535 // We add an offset to a pointer here so we should support an offset as big as
6536 // possible.
6537 if (Ov) {
6538 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6539 "index (intermediate) result too big");
6540 Offset = Offset.sext(2 * BitWidth);
6541 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6542 return;
6543 }
6544
6545 Offset = ResOffset;
6546}
6547
6548namespace {
6549
6550// This is a wrapper class around StringLiteral to support offsetted string
6551// literals as format strings. It takes the offset into account when returning
6552// the string and its length or the source locations to display notes correctly.
6553class FormatStringLiteral {
6554 const StringLiteral *FExpr;
6555 int64_t Offset;
6556
6557public:
6558 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6559 : FExpr(fexpr), Offset(Offset) {}
6560
6561 const StringLiteral *getFormatString() const { return FExpr; }
6562
6563 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6564
6565 unsigned getByteLength() const {
6566 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6567 }
6568
6569 unsigned getLength() const { return FExpr->getLength() - Offset; }
6570 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6571
6572 StringLiteralKind getKind() const { return FExpr->getKind(); }
6573
6574 QualType getType() const { return FExpr->getType(); }
6575
6576 bool isAscii() const { return FExpr->isOrdinary(); }
6577 bool isWide() const { return FExpr->isWide(); }
6578 bool isUTF8() const { return FExpr->isUTF8(); }
6579 bool isUTF16() const { return FExpr->isUTF16(); }
6580 bool isUTF32() const { return FExpr->isUTF32(); }
6581 bool isPascal() const { return FExpr->isPascal(); }
6582
6583 SourceLocation getLocationOfByte(
6584 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6585 const TargetInfo &Target, unsigned *StartToken = nullptr,
6586 unsigned *StartTokenByteOffset = nullptr) const {
6587 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6588 StartToken, StartTokenByteOffset);
6589 }
6590
6591 SourceLocation getBeginLoc() const LLVM_READONLY {
6592 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6593 }
6594
6595 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6596};
6597
6598} // namespace
6599
6600static void CheckFormatString(
6601 Sema &S, const FormatStringLiteral *FExpr,
6602 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6604 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6605 bool inFunctionCall, VariadicCallType CallType,
6606 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6607 bool IgnoreStringsWithoutSpecifiers);
6608
6609static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6610 const Expr *E);
6611
6612// Determine if an expression is a string literal or constant string.
6613// If this function returns false on the arguments to a function expecting a
6614// format string, we will usually need to emit a warning.
6615// True string literals are then checked by CheckFormatString.
6616static StringLiteralCheckType
6617checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6618 const Expr *E, ArrayRef<const Expr *> Args,
6619 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6620 unsigned firstDataArg, FormatStringType Type,
6621 VariadicCallType CallType, bool InFunctionCall,
6622 llvm::SmallBitVector &CheckedVarArgs,
6623 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6624 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6625 bool IgnoreStringsWithoutSpecifiers = false) {
6627 return SLCT_NotALiteral;
6628tryAgain:
6629 assert(Offset.isSigned() && "invalid offset");
6630
6631 if (E->isTypeDependent() || E->isValueDependent())
6632 return SLCT_NotALiteral;
6633
6634 E = E->IgnoreParenCasts();
6635
6637 // Technically -Wformat-nonliteral does not warn about this case.
6638 // The behavior of printf and friends in this case is implementation
6639 // dependent. Ideally if the format string cannot be null then
6640 // it should have a 'nonnull' attribute in the function prototype.
6641 return SLCT_UncheckedLiteral;
6642
6643 switch (E->getStmtClass()) {
6644 case Stmt::InitListExprClass:
6645 // Handle expressions like {"foobar"}.
6646 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6647 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6648 format_idx, firstDataArg, Type, CallType,
6649 /*InFunctionCall*/ false, CheckedVarArgs,
6650 UncoveredArg, Offset, CallerFormatParamIdx,
6651 IgnoreStringsWithoutSpecifiers);
6652 }
6653 return SLCT_NotALiteral;
6654 case Stmt::BinaryConditionalOperatorClass:
6655 case Stmt::ConditionalOperatorClass: {
6656 // The expression is a literal if both sub-expressions were, and it was
6657 // completely checked only if both sub-expressions were checked.
6660
6661 // Determine whether it is necessary to check both sub-expressions, for
6662 // example, because the condition expression is a constant that can be
6663 // evaluated at compile time.
6664 bool CheckLeft = true, CheckRight = true;
6665
6666 bool Cond;
6667 if (C->getCond()->EvaluateAsBooleanCondition(
6669 if (Cond)
6670 CheckRight = false;
6671 else
6672 CheckLeft = false;
6673 }
6674
6675 // We need to maintain the offsets for the right and the left hand side
6676 // separately to check if every possible indexed expression is a valid
6677 // string literal. They might have different offsets for different string
6678 // literals in the end.
6679 StringLiteralCheckType Left;
6680 if (!CheckLeft)
6681 Left = SLCT_UncheckedLiteral;
6682 else {
6683 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
6684 Args, APK, format_idx, firstDataArg, Type,
6685 CallType, InFunctionCall, CheckedVarArgs,
6686 UncoveredArg, Offset, CallerFormatParamIdx,
6687 IgnoreStringsWithoutSpecifiers);
6688 if (Left == SLCT_NotALiteral || !CheckRight) {
6689 return Left;
6690 }
6691 }
6692
6693 StringLiteralCheckType Right = checkFormatStringExpr(
6694 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6695 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6696 UncoveredArg, Offset, CallerFormatParamIdx,
6697 IgnoreStringsWithoutSpecifiers);
6698
6699 return (CheckLeft && Left < Right) ? Left : Right;
6700 }
6701
6702 case Stmt::ImplicitCastExprClass:
6703 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6704 goto tryAgain;
6705
6706 case Stmt::OpaqueValueExprClass:
6707 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6708 E = src;
6709 goto tryAgain;
6710 }
6711 return SLCT_NotALiteral;
6712
6713 case Stmt::PredefinedExprClass:
6714 // While __func__, etc., are technically not string literals, they
6715 // cannot contain format specifiers and thus are not a security
6716 // liability.
6717 return SLCT_UncheckedLiteral;
6718
6719 case Stmt::DeclRefExprClass: {
6720 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6721
6722 // As an exception, do not flag errors for variables binding to
6723 // const string literals.
6724 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6725 bool isConstant = false;
6726 QualType T = DR->getType();
6727
6728 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6729 isConstant = AT->getElementType().isConstant(S.Context);
6730 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6731 isConstant = T.isConstant(S.Context) &&
6732 PT->getPointeeType().isConstant(S.Context);
6733 } else if (T->isObjCObjectPointerType()) {
6734 // In ObjC, there is usually no "const ObjectPointer" type,
6735 // so don't check if the pointee type is constant.
6736 isConstant = T.isConstant(S.Context);
6737 }
6738
6739 if (isConstant) {
6740 if (const Expr *Init = VD->getAnyInitializer()) {
6741 // Look through initializers like const char c[] = { "foo" }
6742 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6743 if (InitList->isStringLiteralInit())
6744 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6745 }
6746 return checkFormatStringExpr(
6747 S, ReferenceFormatString, Init, Args, APK, format_idx,
6748 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
6749 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
6750 }
6751 }
6752
6753 // When the format argument is an argument of this function, and this
6754 // function also has the format attribute, there are several interactions
6755 // for which there shouldn't be a warning. For instance, when calling
6756 // v*printf from a function that has the printf format attribute, we
6757 // should not emit a warning about using `fmt`, even though it's not
6758 // constant, because the arguments have already been checked for the
6759 // caller of `logmessage`:
6760 //
6761 // __attribute__((format(printf, 1, 2)))
6762 // void logmessage(char const *fmt, ...) {
6763 // va_list ap;
6764 // va_start(ap, fmt);
6765 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6766 // ...
6767 // }
6768 //
6769 // Another interaction that we need to support is using a format string
6770 // specified by the format_matches attribute:
6771 //
6772 // __attribute__((format_matches(printf, 1, "%s %d")))
6773 // void logmessage(char const *fmt, const char *a, int b) {
6774 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6775 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6776 // ...
6777 // }
6778 //
6779 // Yet another interaction that we need to support is calling a variadic
6780 // format function from a format function that has fixed arguments. For
6781 // instance:
6782 //
6783 // __attribute__((format(printf, 1, 2)))
6784 // void logstring(char const *fmt, char const *str) {
6785 // printf(fmt, str); /* do not emit a warning about "fmt" */
6786 // }
6787 //
6788 // Same (and perhaps more relatably) for the variadic template case:
6789 //
6790 // template<typename... Args>
6791 // __attribute__((format(printf, 1, 2)))
6792 // void log(const char *fmt, Args&&... args) {
6793 // printf(fmt, forward<Args>(args)...);
6794 // /* do not emit a warning about "fmt" */
6795 // }
6796 //
6797 // Due to implementation difficulty, we only check the format, not the
6798 // format arguments, in all cases.
6799 //
6800 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6801 if (CallerFormatParamIdx)
6802 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
6803 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6804 for (const auto *PVFormatMatches :
6805 D->specific_attrs<FormatMatchesAttr>()) {
6806 Sema::FormatStringInfo CalleeFSI;
6807 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6808 0, &CalleeFSI))
6809 continue;
6810 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6811 // If using the wrong type of format string, emit a diagnostic
6812 // here and stop checking to avoid irrelevant diagnostics.
6813 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6814 S.Diag(Args[format_idx]->getBeginLoc(),
6815 diag::warn_format_string_type_incompatible)
6816 << PVFormatMatches->getType()->getName()
6818 if (!InFunctionCall) {
6819 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6820 diag::note_format_string_defined);
6821 }
6822 return SLCT_UncheckedLiteral;
6823 }
6824 return checkFormatStringExpr(
6825 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6826 Args, APK, format_idx, firstDataArg, Type, CallType,
6827 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6828 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6829 }
6830 }
6831
6832 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6833 Sema::FormatStringInfo CallerFSI;
6834 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6835 PVFormat->getFirstArg(), &CallerFSI))
6836 continue;
6837 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6838 // We also check if the formats are compatible.
6839 // We can't pass a 'scanf' string to a 'printf' function.
6840 if (Type != S.GetFormatStringType(PVFormat)) {
6841 S.Diag(Args[format_idx]->getBeginLoc(),
6842 diag::warn_format_string_type_incompatible)
6843 << PVFormat->getType()->getName()
6845 if (!InFunctionCall) {
6846 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6847 }
6848 return SLCT_UncheckedLiteral;
6849 }
6850 // Lastly, check that argument passing kinds transition in a
6851 // way that makes sense:
6852 // from a caller with FAPK_VAList, allow FAPK_VAList
6853 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6854 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6855 // from a caller with FAPK_Variadic, allow FAPK_VAList
6856 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6861 return SLCT_UncheckedLiteral;
6862 }
6863 }
6864 }
6865 }
6866 }
6867 }
6868
6869 return SLCT_NotALiteral;
6870 }
6871
6872 case Stmt::CallExprClass:
6873 case Stmt::CXXMemberCallExprClass: {
6874 const CallExpr *CE = cast<CallExpr>(E);
6875 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6876 bool IsFirst = true;
6877 StringLiteralCheckType CommonResult;
6878 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6879 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6880 StringLiteralCheckType Result = checkFormatStringExpr(
6881 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6882 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6883 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6884 if (IsFirst) {
6885 CommonResult = Result;
6886 IsFirst = false;
6887 }
6888 }
6889 if (!IsFirst)
6890 return CommonResult;
6891
6892 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6893 unsigned BuiltinID = FD->getBuiltinID();
6894 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6895 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6896 const Expr *Arg = CE->getArg(0);
6897 return checkFormatStringExpr(
6898 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6899 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6900 UncoveredArg, Offset, CallerFormatParamIdx,
6901 IgnoreStringsWithoutSpecifiers);
6902 }
6903 }
6904 }
6905 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6906 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6907 format_idx, firstDataArg, Type, CallType,
6908 /*InFunctionCall*/ false, CheckedVarArgs,
6909 UncoveredArg, Offset, CallerFormatParamIdx,
6910 IgnoreStringsWithoutSpecifiers);
6911 return SLCT_NotALiteral;
6912 }
6913 case Stmt::ObjCMessageExprClass: {
6914 const auto *ME = cast<ObjCMessageExpr>(E);
6915 if (const auto *MD = ME->getMethodDecl()) {
6916 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6917 // As a special case heuristic, if we're using the method -[NSBundle
6918 // localizedStringForKey:value:table:], ignore any key strings that lack
6919 // format specifiers. The idea is that if the key doesn't have any
6920 // format specifiers then its probably just a key to map to the
6921 // localized strings. If it does have format specifiers though, then its
6922 // likely that the text of the key is the format string in the
6923 // programmer's language, and should be checked.
6924 const ObjCInterfaceDecl *IFace;
6925 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6926 IFace->getIdentifier()->isStr("NSBundle") &&
6927 MD->getSelector().isKeywordSelector(
6928 {"localizedStringForKey", "value", "table"})) {
6929 IgnoreStringsWithoutSpecifiers = true;
6930 }
6931
6932 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6933 return checkFormatStringExpr(
6934 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6935 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6936 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6937 }
6938 }
6939
6940 return SLCT_NotALiteral;
6941 }
6942 case Stmt::ObjCStringLiteralClass:
6943 case Stmt::StringLiteralClass: {
6944 const StringLiteral *StrE = nullptr;
6945
6946 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6947 StrE = ObjCFExpr->getString();
6948 else
6949 StrE = cast<StringLiteral>(E);
6950
6951 if (StrE) {
6952 if (Offset.isNegative() || Offset > StrE->getLength()) {
6953 // TODO: It would be better to have an explicit warning for out of
6954 // bounds literals.
6955 return SLCT_NotALiteral;
6956 }
6957 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6958 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6959 format_idx, firstDataArg, Type, InFunctionCall,
6960 CallType, CheckedVarArgs, UncoveredArg,
6961 IgnoreStringsWithoutSpecifiers);
6962 return SLCT_CheckedLiteral;
6963 }
6964
6965 return SLCT_NotALiteral;
6966 }
6967 case Stmt::BinaryOperatorClass: {
6968 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6969
6970 // A string literal + an int offset is still a string literal.
6971 if (BinOp->isAdditiveOp()) {
6972 Expr::EvalResult LResult, RResult;
6973
6974 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6975 LResult, S.Context, Expr::SE_NoSideEffects,
6977 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6978 RResult, S.Context, Expr::SE_NoSideEffects,
6980
6981 if (LIsInt != RIsInt) {
6982 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6983
6984 if (LIsInt) {
6985 if (BinOpKind == BO_Add) {
6986 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6987 E = BinOp->getRHS();
6988 goto tryAgain;
6989 }
6990 } else {
6991 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6992 E = BinOp->getLHS();
6993 goto tryAgain;
6994 }
6995 }
6996 }
6997
6998 return SLCT_NotALiteral;
6999 }
7000 case Stmt::UnaryOperatorClass: {
7001 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7002 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7003 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7004 Expr::EvalResult IndexResult;
7005 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7008 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7009 /*RHS is int*/ true);
7010 E = ASE->getBase();
7011 goto tryAgain;
7012 }
7013 }
7014
7015 return SLCT_NotALiteral;
7016 }
7017
7018 default:
7019 return SLCT_NotALiteral;
7020 }
7021}
7022
7023// If this expression can be evaluated at compile-time,
7024// check if the result is a StringLiteral and return it
7025// otherwise return nullptr
7027 const Expr *E) {
7028 Expr::EvalResult Result;
7029 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7030 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7031 if (isa_and_nonnull<StringLiteral>(LVE))
7032 return LVE;
7033 }
7034 return nullptr;
7035}
7036
7038 switch (FST) {
7040 return "scanf";
7042 return "printf";
7044 return "NSString";
7046 return "strftime";
7048 return "strfmon";
7050 return "kprintf";
7052 return "freebsd_kprintf";
7054 return "os_log";
7055 default:
7056 return "<unknown>";
7057 }
7058}
7059
7061 return llvm::StringSwitch<FormatStringType>(Flavor)
7062 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7063 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7065 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7066 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7067 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7068 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7070 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7071 .Case("os_trace", FormatStringType::OSLog)
7072 .Case("os_log", FormatStringType::OSLog)
7073 .Default(FormatStringType::Unknown);
7074}
7075
7077 return GetFormatStringType(Format->getType()->getName());
7078}
7079
7080FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7081 return GetFormatStringType(Format->getType()->getName());
7082}
7083
7084bool Sema::CheckFormatArguments(const FormatAttr *Format,
7085 ArrayRef<const Expr *> Args, bool IsCXXMember,
7086 VariadicCallType CallType, SourceLocation Loc,
7087 SourceRange Range,
7088 llvm::SmallBitVector &CheckedVarArgs) {
7089 FormatStringInfo FSI;
7090 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7091 IsCXXMember,
7092 CallType != VariadicCallType::DoesNotApply, &FSI))
7093 return CheckFormatArguments(
7094 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7095 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7096 return false;
7097}
7098
7099bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7100 ArrayRef<const Expr *> Args, bool IsCXXMember,
7101 VariadicCallType CallType, SourceLocation Loc,
7102 SourceRange Range,
7103 llvm::SmallBitVector &CheckedVarArgs) {
7104 FormatStringInfo FSI;
7105 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7106 &FSI)) {
7107 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7108 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7109 Format->getFormatString(), FSI.FormatIdx,
7110 FSI.FirstDataArg, GetFormatStringType(Format),
7111 CallType, Loc, Range, CheckedVarArgs);
7112 }
7113 return false;
7114}
7115
7118 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7119 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7120 SourceLocation Loc) {
7121 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7122 return false;
7123
7124 DeclContext *DC = S->CurContext;
7125 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7126 return false;
7127 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7128
7129 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7130
7131 // Find the offset to convert between attribute and parameter indexes.
7132 unsigned CallerArgumentIndexOffset =
7133 hasImplicitObjectParameter(Caller) ? 2 : 1;
7134
7135 unsigned FirstArgumentIndex = -1;
7136 switch (APK) {
7139 // As an extension, clang allows the format attribute on non-variadic
7140 // functions.
7141 // Caller must have fixed arguments to pass them to a fixed or variadic
7142 // function. Try to match caller and callee arguments. If successful, then
7143 // emit a diag with the caller idx, otherwise we can't determine the callee
7144 // arguments.
7145 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7146 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7147 // There aren't enough arguments in the caller to pass to callee.
7148 return false;
7149 }
7150 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7151 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7152 const auto *Arg =
7153 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7154 if (!Arg)
7155 return false;
7156 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7157 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7158 return false;
7159 }
7160 FirstArgumentIndex =
7161 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7162 break;
7163 }
7165 // Caller arguments are either variadic or a va_list.
7166 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7167 ? (NumCallerParams + CallerArgumentIndexOffset)
7168 : 0;
7169 break;
7171 // The callee has a format_matches attribute. We will emit that instead.
7172 if (!ReferenceFormatString)
7173 return false;
7174 break;
7175 }
7176
7177 // Emit the diagnostic and fixit.
7178 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7179 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7180 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7181 do {
7182 std::string Attr, Fixit;
7183 llvm::raw_string_ostream AttrOS(Attr);
7185 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7186 << FirstArgumentIndex << ")";
7187 } else {
7188 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7189 << ", \"";
7190 AttrOS.write_escaped(ReferenceFormatString->getString());
7191 AttrOS << "\")";
7192 }
7193 AttrOS.flush();
7194 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7195 if (ND)
7196 DB << ND;
7197 else
7198 DB << "block";
7199
7200 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7201 if (isa<BlockDecl>(Caller))
7202 break;
7203
7204 SourceLocation SL;
7205 llvm::raw_string_ostream IS(Fixit);
7206 // The attribute goes at the start of the declaration in C/C++ functions
7207 // and methods, but after the declaration for Objective-C methods.
7208 if (isa<ObjCMethodDecl>(Caller)) {
7209 IS << ' ';
7210 SL = Caller->getEndLoc();
7211 }
7212 const LangOptions &LO = S->getLangOpts();
7213 if (LO.C23 || LO.CPlusPlus11)
7214 IS << "[[gnu::" << Attr << "]]";
7215 else if (LO.ObjC || LO.GNUMode)
7216 IS << "__attribute__((" << Attr << "))";
7217 else
7218 break;
7219 if (!isa<ObjCMethodDecl>(Caller)) {
7220 IS << ' ';
7221 SL = Caller->getBeginLoc();
7222 }
7223 IS.flush();
7224
7225 DB << FixItHint::CreateInsertion(SL, Fixit);
7226 } while (false);
7227
7228 // Add implicit format or format_matches attribute.
7230 Caller->addAttr(FormatAttr::CreateImplicit(
7231 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7232 FormatStringIndex, FirstArgumentIndex));
7233 } else {
7234 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7235 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7236 FormatStringIndex, ReferenceFormatString));
7237 }
7238
7239 {
7240 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7241 if (ND)
7242 DB << ND;
7243 else
7244 DB << "block";
7245 }
7246 return true;
7247}
7248
7249bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7251 StringLiteral *ReferenceFormatString,
7252 unsigned format_idx, unsigned firstDataArg,
7254 VariadicCallType CallType, SourceLocation Loc,
7255 SourceRange Range,
7256 llvm::SmallBitVector &CheckedVarArgs) {
7257 // CHECK: printf/scanf-like function is called with no format string.
7258 if (format_idx >= Args.size()) {
7259 Diag(Loc, diag::warn_missing_format_string) << Range;
7260 return false;
7261 }
7262
7263 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7264
7265 // CHECK: format string is not a string literal.
7266 //
7267 // Dynamically generated format strings are difficult to
7268 // automatically vet at compile time. Requiring that format strings
7269 // are string literals: (1) permits the checking of format strings by
7270 // the compiler and thereby (2) can practically remove the source of
7271 // many format string exploits.
7272
7273 // Format string can be either ObjC string (e.g. @"%d") or
7274 // C string (e.g. "%d")
7275 // ObjC string uses the same format specifiers as C string, so we can use
7276 // the same format string checking logic for both ObjC and C strings.
7277 UncoveredArgHandler UncoveredArg;
7278 std::optional<unsigned> CallerParamIdx;
7279 StringLiteralCheckType CT = checkFormatStringExpr(
7280 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7281 firstDataArg, Type, CallType,
7282 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7283 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7284
7285 // Generate a diagnostic where an uncovered argument is detected.
7286 if (UncoveredArg.hasUncoveredArg()) {
7287 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7288 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7289 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7290 }
7291
7292 if (CT != SLCT_NotALiteral)
7293 // Literal format string found, check done!
7294 return CT == SLCT_CheckedLiteral;
7295
7296 // Do not emit diag when the string param is a macro expansion and the
7297 // format is either NSString or CFString. This is a hack to prevent
7298 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7299 // which are usually used in place of NS and CF string literals.
7300 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7302 SourceMgr.isInSystemMacro(FormatLoc))
7303 return false;
7304
7305 if (CallerParamIdx && CheckMissingFormatAttribute(
7306 this, Args, APK, ReferenceFormatString, format_idx,
7307 firstDataArg, Type, *CallerParamIdx, Loc))
7308 return false;
7309
7310 // Strftime is particular as it always uses a single 'time' argument,
7311 // so it is safe to pass a non-literal string.
7313 return false;
7314
7315 // If there are no arguments specified, warn with -Wformat-security, otherwise
7316 // warn only with -Wformat-nonliteral.
7317 if (Args.size() == firstDataArg) {
7318 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7319 << OrigFormatExpr->getSourceRange();
7320 switch (Type) {
7321 default:
7322 break;
7326 Diag(FormatLoc, diag::note_format_security_fixit)
7327 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7328 break;
7330 Diag(FormatLoc, diag::note_format_security_fixit)
7331 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7332 break;
7333 }
7334 } else {
7335 Diag(FormatLoc, diag::warn_format_nonliteral)
7336 << OrigFormatExpr->getSourceRange();
7337 }
7338 return false;
7339}
7340
7341namespace {
7342
7343class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7344protected:
7345 Sema &S;
7346 const FormatStringLiteral *FExpr;
7347 const Expr *OrigFormatExpr;
7348 const FormatStringType FSType;
7349 const unsigned FirstDataArg;
7350 const unsigned NumDataArgs;
7351 const char *Beg; // Start of format string.
7352 const Sema::FormatArgumentPassingKind ArgPassingKind;
7353 ArrayRef<const Expr *> Args;
7354 unsigned FormatIdx;
7355 llvm::SmallBitVector CoveredArgs;
7356 bool usesPositionalArgs = false;
7357 bool atFirstArg = true;
7358 bool inFunctionCall;
7359 VariadicCallType CallType;
7360 llvm::SmallBitVector &CheckedVarArgs;
7361 UncoveredArgHandler &UncoveredArg;
7362
7363public:
7364 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7365 const Expr *origFormatExpr, const FormatStringType type,
7366 unsigned firstDataArg, unsigned numDataArgs,
7367 const char *beg, Sema::FormatArgumentPassingKind APK,
7368 ArrayRef<const Expr *> Args, unsigned formatIdx,
7369 bool inFunctionCall, VariadicCallType callType,
7370 llvm::SmallBitVector &CheckedVarArgs,
7371 UncoveredArgHandler &UncoveredArg)
7372 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7373 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7374 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7375 inFunctionCall(inFunctionCall), CallType(callType),
7376 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7377 CoveredArgs.resize(numDataArgs);
7378 CoveredArgs.reset();
7379 }
7380
7381 bool HasFormatArguments() const {
7382 return ArgPassingKind == Sema::FAPK_Fixed ||
7383 ArgPassingKind == Sema::FAPK_Variadic;
7384 }
7385
7386 void DoneProcessing();
7387
7388 void HandleIncompleteSpecifier(const char *startSpecifier,
7389 unsigned specifierLen) override;
7390
7391 void HandleInvalidLengthModifier(
7392 const analyze_format_string::FormatSpecifier &FS,
7393 const analyze_format_string::ConversionSpecifier &CS,
7394 const char *startSpecifier, unsigned specifierLen,
7395 unsigned DiagID);
7396
7397 void HandleNonStandardLengthModifier(
7398 const analyze_format_string::FormatSpecifier &FS,
7399 const char *startSpecifier, unsigned specifierLen);
7400
7401 void HandleNonStandardConversionSpecifier(
7402 const analyze_format_string::ConversionSpecifier &CS,
7403 const char *startSpecifier, unsigned specifierLen);
7404
7405 void HandlePosition(const char *startPos, unsigned posLen) override;
7406
7407 void HandleInvalidPosition(const char *startSpecifier,
7408 unsigned specifierLen,
7410
7411 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7412
7413 void HandleNullChar(const char *nullCharacter) override;
7414
7415 template <typename Range>
7416 static void
7417 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7418 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7419 bool IsStringLocation, Range StringRange,
7420 ArrayRef<FixItHint> Fixit = {});
7421
7422protected:
7423 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7424 const char *startSpec,
7425 unsigned specifierLen,
7426 const char *csStart, unsigned csLen);
7427
7428 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7429 const char *startSpec,
7430 unsigned specifierLen);
7431
7432 SourceRange getFormatStringRange();
7433 CharSourceRange getSpecifierRange(const char *startSpecifier,
7434 unsigned specifierLen);
7435 SourceLocation getLocationOfByte(const char *x);
7436
7437 const Expr *getDataArg(unsigned i) const;
7438
7439 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7440 const analyze_format_string::ConversionSpecifier &CS,
7441 const char *startSpecifier, unsigned specifierLen,
7442 unsigned argIndex);
7443
7444 template <typename Range>
7445 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7446 bool IsStringLocation, Range StringRange,
7447 ArrayRef<FixItHint> Fixit = {});
7448};
7449
7450} // namespace
7451
7452SourceRange CheckFormatHandler::getFormatStringRange() {
7453 return OrigFormatExpr->getSourceRange();
7454}
7455
7456CharSourceRange CheckFormatHandler::
7457getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7458 SourceLocation Start = getLocationOfByte(startSpecifier);
7459 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7460
7461 // Advance the end SourceLocation by one due to half-open ranges.
7462 End = End.getLocWithOffset(1);
7463
7464 return CharSourceRange::getCharRange(Start, End);
7465}
7466
7467SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7468 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7470}
7471
7472void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7473 unsigned specifierLen){
7474 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7475 getLocationOfByte(startSpecifier),
7476 /*IsStringLocation*/true,
7477 getSpecifierRange(startSpecifier, specifierLen));
7478}
7479
7480void CheckFormatHandler::HandleInvalidLengthModifier(
7483 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7484 using namespace analyze_format_string;
7485
7486 const LengthModifier &LM = FS.getLengthModifier();
7487 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7488
7489 // See if we know how to fix this length modifier.
7490 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7491 if (FixedLM) {
7492 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7493 getLocationOfByte(LM.getStart()),
7494 /*IsStringLocation*/true,
7495 getSpecifierRange(startSpecifier, specifierLen));
7496
7497 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7498 << FixedLM->toString()
7499 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7500
7501 } else {
7502 FixItHint Hint;
7503 if (DiagID == diag::warn_format_nonsensical_length)
7504 Hint = FixItHint::CreateRemoval(LMRange);
7505
7506 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7507 getLocationOfByte(LM.getStart()),
7508 /*IsStringLocation*/true,
7509 getSpecifierRange(startSpecifier, specifierLen),
7510 Hint);
7511 }
7512}
7513
7514void CheckFormatHandler::HandleNonStandardLengthModifier(
7516 const char *startSpecifier, unsigned specifierLen) {
7517 using namespace analyze_format_string;
7518
7519 const LengthModifier &LM = FS.getLengthModifier();
7520 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7521
7522 // See if we know how to fix this length modifier.
7523 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7524 if (FixedLM) {
7525 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7526 << LM.toString() << 0,
7527 getLocationOfByte(LM.getStart()),
7528 /*IsStringLocation*/true,
7529 getSpecifierRange(startSpecifier, specifierLen));
7530
7531 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7532 << FixedLM->toString()
7533 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7534
7535 } else {
7536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7537 << LM.toString() << 0,
7538 getLocationOfByte(LM.getStart()),
7539 /*IsStringLocation*/true,
7540 getSpecifierRange(startSpecifier, specifierLen));
7541 }
7542}
7543
7544void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7546 const char *startSpecifier, unsigned specifierLen) {
7547 using namespace analyze_format_string;
7548
7549 // See if we know how to fix this conversion specifier.
7550 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7551 if (FixedCS) {
7552 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7553 << CS.toString() << /*conversion specifier*/1,
7554 getLocationOfByte(CS.getStart()),
7555 /*IsStringLocation*/true,
7556 getSpecifierRange(startSpecifier, specifierLen));
7557
7558 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7559 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7560 << FixedCS->toString()
7561 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7562 } else {
7563 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7564 << CS.toString() << /*conversion specifier*/1,
7565 getLocationOfByte(CS.getStart()),
7566 /*IsStringLocation*/true,
7567 getSpecifierRange(startSpecifier, specifierLen));
7568 }
7569}
7570
7571void CheckFormatHandler::HandlePosition(const char *startPos,
7572 unsigned posLen) {
7573 if (!S.getDiagnostics().isIgnored(
7574 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7575 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7576 getLocationOfByte(startPos),
7577 /*IsStringLocation*/ true,
7578 getSpecifierRange(startPos, posLen));
7579}
7580
7581void CheckFormatHandler::HandleInvalidPosition(
7582 const char *startSpecifier, unsigned specifierLen,
7584 if (!S.getDiagnostics().isIgnored(
7585 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7586 EmitFormatDiagnostic(
7587 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7588 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7589 getSpecifierRange(startSpecifier, specifierLen));
7590}
7591
7592void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7593 unsigned posLen) {
7594 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7595 SourceLocation()))
7596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7597 getLocationOfByte(startPos),
7598 /*IsStringLocation*/ true,
7599 getSpecifierRange(startPos, posLen));
7600}
7601
7602void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7603 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7604 // The presence of a null character is likely an error.
7605 EmitFormatDiagnostic(
7606 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7607 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7608 getFormatStringRange());
7609 }
7610}
7611
7612// Note that this may return NULL if there was an error parsing or building
7613// one of the argument expressions.
7614const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7615 return Args[FirstDataArg + i];
7616}
7617
7618void CheckFormatHandler::DoneProcessing() {
7619 // Does the number of data arguments exceed the number of
7620 // format conversions in the format string?
7621 if (HasFormatArguments()) {
7622 // Find any arguments that weren't covered.
7623 CoveredArgs.flip();
7624 signed notCoveredArg = CoveredArgs.find_first();
7625 if (notCoveredArg >= 0) {
7626 assert((unsigned)notCoveredArg < NumDataArgs);
7627 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7628 } else {
7629 UncoveredArg.setAllCovered();
7630 }
7631 }
7632}
7633
7634void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7635 const Expr *ArgExpr) {
7636 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7637 "Invalid state");
7638
7639 if (!ArgExpr)
7640 return;
7641
7642 SourceLocation Loc = ArgExpr->getBeginLoc();
7643
7644 if (S.getSourceManager().isInSystemMacro(Loc))
7645 return;
7646
7647 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7648 for (auto E : DiagnosticExprs)
7649 PDiag << E->getSourceRange();
7650
7651 CheckFormatHandler::EmitFormatDiagnostic(
7652 S, IsFunctionCall, DiagnosticExprs[0],
7653 PDiag, Loc, /*IsStringLocation*/false,
7654 DiagnosticExprs[0]->getSourceRange());
7655}
7656
7657bool
7658CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7659 SourceLocation Loc,
7660 const char *startSpec,
7661 unsigned specifierLen,
7662 const char *csStart,
7663 unsigned csLen) {
7664 bool keepGoing = true;
7665 if (argIndex < NumDataArgs) {
7666 // Consider the argument coverered, even though the specifier doesn't
7667 // make sense.
7668 CoveredArgs.set(argIndex);
7669 }
7670 else {
7671 // If argIndex exceeds the number of data arguments we
7672 // don't issue a warning because that is just a cascade of warnings (and
7673 // they may have intended '%%' anyway). We don't want to continue processing
7674 // the format string after this point, however, as we will like just get
7675 // gibberish when trying to match arguments.
7676 keepGoing = false;
7677 }
7678
7679 StringRef Specifier(csStart, csLen);
7680
7681 // If the specifier in non-printable, it could be the first byte of a UTF-8
7682 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7683 // hex value.
7684 std::string CodePointStr;
7685 if (!llvm::sys::locale::isPrint(*csStart)) {
7686 llvm::UTF32 CodePoint;
7687 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7688 const llvm::UTF8 *E =
7689 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7690 llvm::ConversionResult Result =
7691 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7692
7693 if (Result != llvm::conversionOK) {
7694 unsigned char FirstChar = *csStart;
7695 CodePoint = (llvm::UTF32)FirstChar;
7696 }
7697
7698 llvm::raw_string_ostream OS(CodePointStr);
7699 if (CodePoint < 256)
7700 OS << "\\x" << llvm::format("%02x", CodePoint);
7701 else if (CodePoint <= 0xFFFF)
7702 OS << "\\u" << llvm::format("%04x", CodePoint);
7703 else
7704 OS << "\\U" << llvm::format("%08x", CodePoint);
7705 Specifier = CodePointStr;
7706 }
7707
7708 EmitFormatDiagnostic(
7709 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7710 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7711
7712 return keepGoing;
7713}
7714
7715void
7716CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7717 const char *startSpec,
7718 unsigned specifierLen) {
7719 EmitFormatDiagnostic(
7720 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7721 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7722}
7723
7724bool
7725CheckFormatHandler::CheckNumArgs(
7728 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7729
7730 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7732 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7733 << (argIndex+1) << NumDataArgs)
7734 : S.PDiag(diag::warn_printf_insufficient_data_args);
7735 EmitFormatDiagnostic(
7736 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7737 getSpecifierRange(startSpecifier, specifierLen));
7738
7739 // Since more arguments than conversion tokens are given, by extension
7740 // all arguments are covered, so mark this as so.
7741 UncoveredArg.setAllCovered();
7742 return false;
7743 }
7744 return true;
7745}
7746
7747template<typename Range>
7748void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7749 SourceLocation Loc,
7750 bool IsStringLocation,
7751 Range StringRange,
7752 ArrayRef<FixItHint> FixIt) {
7753 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7754 Loc, IsStringLocation, StringRange, FixIt);
7755}
7756
7757/// If the format string is not within the function call, emit a note
7758/// so that the function call and string are in diagnostic messages.
7759///
7760/// \param InFunctionCall if true, the format string is within the function
7761/// call and only one diagnostic message will be produced. Otherwise, an
7762/// extra note will be emitted pointing to location of the format string.
7763///
7764/// \param ArgumentExpr the expression that is passed as the format string
7765/// argument in the function call. Used for getting locations when two
7766/// diagnostics are emitted.
7767///
7768/// \param PDiag the callee should already have provided any strings for the
7769/// diagnostic message. This function only adds locations and fixits
7770/// to diagnostics.
7771///
7772/// \param Loc primary location for diagnostic. If two diagnostics are
7773/// required, one will be at Loc and a new SourceLocation will be created for
7774/// the other one.
7775///
7776/// \param IsStringLocation if true, Loc points to the format string should be
7777/// used for the note. Otherwise, Loc points to the argument list and will
7778/// be used with PDiag.
7779///
7780/// \param StringRange some or all of the string to highlight. This is
7781/// templated so it can accept either a CharSourceRange or a SourceRange.
7782///
7783/// \param FixIt optional fix it hint for the format string.
7784template <typename Range>
7785void CheckFormatHandler::EmitFormatDiagnostic(
7786 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7787 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7788 Range StringRange, ArrayRef<FixItHint> FixIt) {
7789 if (InFunctionCall) {
7790 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7791 D << StringRange;
7792 D << FixIt;
7793 } else {
7794 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7795 << ArgumentExpr->getSourceRange();
7796
7798 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7799 diag::note_format_string_defined);
7800
7801 Note << StringRange;
7802 Note << FixIt;
7803 }
7804}
7805
7806//===--- CHECK: Printf format string checking -----------------------------===//
7807
7808namespace {
7809
7810class CheckPrintfHandler : public CheckFormatHandler {
7811public:
7812 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7813 const Expr *origFormatExpr, const FormatStringType type,
7814 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7815 const char *beg, Sema::FormatArgumentPassingKind APK,
7816 ArrayRef<const Expr *> Args, unsigned formatIdx,
7817 bool inFunctionCall, VariadicCallType CallType,
7818 llvm::SmallBitVector &CheckedVarArgs,
7819 UncoveredArgHandler &UncoveredArg)
7820 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7821 numDataArgs, beg, APK, Args, formatIdx,
7822 inFunctionCall, CallType, CheckedVarArgs,
7823 UncoveredArg) {}
7824
7825 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7826
7827 /// Returns true if '%@' specifiers are allowed in the format string.
7828 bool allowsObjCArg() const {
7829 return FSType == FormatStringType::NSString ||
7830 FSType == FormatStringType::OSLog ||
7831 FSType == FormatStringType::OSTrace;
7832 }
7833
7834 bool HandleInvalidPrintfConversionSpecifier(
7835 const analyze_printf::PrintfSpecifier &FS,
7836 const char *startSpecifier,
7837 unsigned specifierLen) override;
7838
7839 void handleInvalidMaskType(StringRef MaskType) override;
7840
7841 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7842 const char *startSpecifier, unsigned specifierLen,
7843 const TargetInfo &Target) override;
7844 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7845 const char *StartSpecifier,
7846 unsigned SpecifierLen,
7847 const Expr *E);
7848
7849 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7850 const char *startSpecifier, unsigned specifierLen);
7851 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7852 const analyze_printf::OptionalAmount &Amt,
7853 unsigned type,
7854 const char *startSpecifier, unsigned specifierLen);
7855 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7856 const analyze_printf::OptionalFlag &flag,
7857 const char *startSpecifier, unsigned specifierLen);
7858 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7859 const analyze_printf::OptionalFlag &ignoredFlag,
7860 const analyze_printf::OptionalFlag &flag,
7861 const char *startSpecifier, unsigned specifierLen);
7862 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7863 const Expr *E);
7864
7865 void HandleEmptyObjCModifierFlag(const char *startFlag,
7866 unsigned flagLen) override;
7867
7868 void HandleInvalidObjCModifierFlag(const char *startFlag,
7869 unsigned flagLen) override;
7870
7871 void
7872 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7873 const char *flagsEnd,
7874 const char *conversionPosition) override;
7875};
7876
7877/// Keeps around the information needed to verify that two specifiers are
7878/// compatible.
7879class EquatableFormatArgument {
7880public:
7881 enum SpecifierSensitivity : unsigned {
7882 SS_None,
7883 SS_Private,
7884 SS_Public,
7885 SS_Sensitive
7886 };
7887
7888 enum FormatArgumentRole : unsigned {
7889 FAR_Data,
7890 FAR_FieldWidth,
7891 FAR_Precision,
7892 FAR_Auxiliary, // FreeBSD kernel %b and %D
7893 };
7894
7895private:
7896 analyze_format_string::ArgType ArgType;
7898 StringRef SpecifierLetter;
7899 CharSourceRange Range;
7900 SourceLocation ElementLoc;
7901 FormatArgumentRole Role : 2;
7902 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7903 unsigned Position : 14;
7904 unsigned ModifierFor : 14; // not set for FAR_Data
7905
7906 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7907 bool InFunctionCall) const;
7908
7909public:
7910 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7912 StringRef SpecifierLetter,
7913 analyze_format_string::ArgType ArgType,
7914 FormatArgumentRole Role,
7915 SpecifierSensitivity Sensitivity, unsigned Position,
7916 unsigned ModifierFor)
7917 : ArgType(ArgType), LengthMod(LengthMod),
7918 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7919 Role(Role), Sensitivity(Sensitivity), Position(Position),
7920 ModifierFor(ModifierFor) {}
7921
7922 unsigned getPosition() const { return Position; }
7923 SourceLocation getSourceLocation() const { return ElementLoc; }
7924 CharSourceRange getSourceRange() const { return Range; }
7925 analyze_format_string::LengthModifier getLengthModifier() const {
7926 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7927 }
7928 void setModifierFor(unsigned V) { ModifierFor = V; }
7929
7930 std::string buildFormatSpecifier() const {
7931 std::string result;
7932 llvm::raw_string_ostream(result)
7933 << getLengthModifier().toString() << SpecifierLetter;
7934 return result;
7935 }
7936
7937 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7938 const Expr *FmtExpr, bool InFunctionCall) const;
7939};
7940
7941/// Turns format strings into lists of EquatableSpecifier objects.
7942class DecomposePrintfHandler : public CheckPrintfHandler {
7943 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7944 bool HadError;
7945
7946 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7947 const Expr *origFormatExpr,
7948 const FormatStringType type, unsigned firstDataArg,
7949 unsigned numDataArgs, bool isObjC, const char *beg,
7951 ArrayRef<const Expr *> Args, unsigned formatIdx,
7952 bool inFunctionCall, VariadicCallType CallType,
7953 llvm::SmallBitVector &CheckedVarArgs,
7954 UncoveredArgHandler &UncoveredArg,
7955 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7956 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7957 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7958 inFunctionCall, CallType, CheckedVarArgs,
7959 UncoveredArg),
7960 Specs(Specs), HadError(false) {}
7961
7962public:
7963 static bool
7964 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7965 FormatStringType type, bool IsObjC, bool InFunctionCall,
7966 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7967
7968 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7969 const char *startSpecifier,
7970 unsigned specifierLen,
7971 const TargetInfo &Target) override;
7972};
7973
7974} // namespace
7975
7976bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7977 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7978 unsigned specifierLen) {
7981
7982 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7983 getLocationOfByte(CS.getStart()),
7984 startSpecifier, specifierLen,
7985 CS.getStart(), CS.getLength());
7986}
7987
7988void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7989 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7990}
7991
7992// Error out if struct or complex type argments are passed to os_log.
7994 QualType T) {
7995 if (FSType != FormatStringType::OSLog)
7996 return false;
7997 return T->isRecordType() || T->isComplexType();
7998}
7999
8000bool CheckPrintfHandler::HandleAmount(
8001 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8002 const char *startSpecifier, unsigned specifierLen) {
8003 if (Amt.hasDataArgument()) {
8004 if (HasFormatArguments()) {
8005 unsigned argIndex = Amt.getArgIndex();
8006 if (argIndex >= NumDataArgs) {
8007 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8008 << k,
8009 getLocationOfByte(Amt.getStart()),
8010 /*IsStringLocation*/ true,
8011 getSpecifierRange(startSpecifier, specifierLen));
8012 // Don't do any more checking. We will just emit
8013 // spurious errors.
8014 return false;
8015 }
8016
8017 // Type check the data argument. It should be an 'int'.
8018 // Although not in conformance with C99, we also allow the argument to be
8019 // an 'unsigned int' as that is a reasonably safe case. GCC also
8020 // doesn't emit a warning for that case.
8021 CoveredArgs.set(argIndex);
8022 const Expr *Arg = getDataArg(argIndex);
8023 if (!Arg)
8024 return false;
8025
8026 QualType T = Arg->getType();
8027
8028 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8029 assert(AT.isValid());
8030
8031 if (!AT.matchesType(S.Context, T)) {
8032 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8033 ? diag::err_printf_asterisk_wrong_type
8034 : diag::warn_printf_asterisk_wrong_type;
8035 EmitFormatDiagnostic(S.PDiag(DiagID)
8037 << T << Arg->getSourceRange(),
8038 getLocationOfByte(Amt.getStart()),
8039 /*IsStringLocation*/ true,
8040 getSpecifierRange(startSpecifier, specifierLen));
8041 // Don't do any more checking. We will just emit
8042 // spurious errors.
8043 return false;
8044 }
8045 }
8046 }
8047 return true;
8048}
8049
8050void CheckPrintfHandler::HandleInvalidAmount(
8053 unsigned type,
8054 const char *startSpecifier,
8055 unsigned specifierLen) {
8058
8059 FixItHint fixit =
8061 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8062 Amt.getConstantLength()))
8063 : FixItHint();
8064
8065 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8066 << type << CS.toString(),
8067 getLocationOfByte(Amt.getStart()),
8068 /*IsStringLocation*/true,
8069 getSpecifierRange(startSpecifier, specifierLen),
8070 fixit);
8071}
8072
8073void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8074 const analyze_printf::OptionalFlag &flag,
8075 const char *startSpecifier,
8076 unsigned specifierLen) {
8077 // Warn about pointless flag with a fixit removal.
8080 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8081 << flag.toString() << CS.toString(),
8082 getLocationOfByte(flag.getPosition()),
8083 /*IsStringLocation*/true,
8084 getSpecifierRange(startSpecifier, specifierLen),
8086 getSpecifierRange(flag.getPosition(), 1)));
8087}
8088
8089void CheckPrintfHandler::HandleIgnoredFlag(
8091 const analyze_printf::OptionalFlag &ignoredFlag,
8092 const analyze_printf::OptionalFlag &flag,
8093 const char *startSpecifier,
8094 unsigned specifierLen) {
8095 // Warn about ignored flag with a fixit removal.
8096 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8097 << ignoredFlag.toString() << flag.toString(),
8098 getLocationOfByte(ignoredFlag.getPosition()),
8099 /*IsStringLocation*/true,
8100 getSpecifierRange(startSpecifier, specifierLen),
8102 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8103}
8104
8105void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8106 unsigned flagLen) {
8107 // Warn about an empty flag.
8108 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8109 getLocationOfByte(startFlag),
8110 /*IsStringLocation*/true,
8111 getSpecifierRange(startFlag, flagLen));
8112}
8113
8114void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8115 unsigned flagLen) {
8116 // Warn about an invalid flag.
8117 auto Range = getSpecifierRange(startFlag, flagLen);
8118 StringRef flag(startFlag, flagLen);
8119 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8120 getLocationOfByte(startFlag),
8121 /*IsStringLocation*/true,
8122 Range, FixItHint::CreateRemoval(Range));
8123}
8124
8125void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8126 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8127 // Warn about using '[...]' without a '@' conversion.
8128 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8129 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8130 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8131 getLocationOfByte(conversionPosition),
8132 /*IsStringLocation*/ true, Range,
8134}
8135
8136void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8137 const Expr *FmtExpr,
8138 bool InFunctionCall) const {
8139 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8140 ElementLoc, true, Range);
8141}
8142
8143bool EquatableFormatArgument::VerifyCompatible(
8144 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8145 bool InFunctionCall) const {
8147 if (Role != Other.Role) {
8148 // diagnose and stop
8149 EmitDiagnostic(
8150 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8151 FmtExpr, InFunctionCall);
8152 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8153 return false;
8154 }
8155
8156 if (Role != FAR_Data) {
8157 if (ModifierFor != Other.ModifierFor) {
8158 // diagnose and stop
8159 EmitDiagnostic(S,
8160 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8161 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8162 FmtExpr, InFunctionCall);
8163 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8164 return false;
8165 }
8166 return true;
8167 }
8168
8169 bool HadError = false;
8170 if (Sensitivity != Other.Sensitivity) {
8171 // diagnose and continue
8172 EmitDiagnostic(S,
8173 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8174 << Sensitivity << Other.Sensitivity,
8175 FmtExpr, InFunctionCall);
8176 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8177 << 0 << Other.Range;
8178 }
8179
8180 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8181 case MK::Match:
8182 break;
8183
8184 case MK::MatchPromotion:
8185 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8186 // MatchPromotion is treated as a failure by format_matches.
8187 case MK::NoMatch:
8188 case MK::NoMatchTypeConfusion:
8189 case MK::NoMatchPromotionTypeConfusion:
8190 EmitDiagnostic(S,
8191 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8192 << buildFormatSpecifier()
8193 << Other.buildFormatSpecifier(),
8194 FmtExpr, InFunctionCall);
8195 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8196 << 0 << Other.Range;
8197 break;
8198
8199 case MK::NoMatchPedantic:
8200 EmitDiagnostic(S,
8201 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8202 << buildFormatSpecifier()
8203 << Other.buildFormatSpecifier(),
8204 FmtExpr, InFunctionCall);
8205 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8206 << 0 << Other.Range;
8207 break;
8208
8209 case MK::NoMatchSignedness:
8210 EmitDiagnostic(S,
8211 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8212 << buildFormatSpecifier()
8213 << Other.buildFormatSpecifier(),
8214 FmtExpr, InFunctionCall);
8215 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8216 << 0 << Other.Range;
8217 break;
8218 }
8219 return !HadError;
8220}
8221
8222bool DecomposePrintfHandler::GetSpecifiers(
8223 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8224 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8226 StringRef Data = FSL->getString();
8227 const char *Str = Data.data();
8228 llvm::SmallBitVector BV;
8229 UncoveredArgHandler UA;
8230 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8231 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8232 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8233 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8234 UA, Args);
8235
8237 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8239 H.DoneProcessing();
8240 if (H.HadError)
8241 return false;
8242
8243 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8244 const EquatableFormatArgument &B) {
8245 return A.getPosition() < B.getPosition();
8246 });
8247 return true;
8248}
8249
8250bool DecomposePrintfHandler::HandlePrintfSpecifier(
8251 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8252 unsigned specifierLen, const TargetInfo &Target) {
8253 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8254 specifierLen, Target)) {
8255 HadError = true;
8256 return false;
8257 }
8258
8259 // Do not add any specifiers to the list for %%. This is possibly incorrect
8260 // if using a precision/width with a data argument, but that combination is
8261 // meaningless and we wouldn't know which format to attach the
8262 // precision/width to.
8263 const auto &CS = FS.getConversionSpecifier();
8265 return true;
8266
8267 // have to patch these to have the right ModifierFor if they are used
8268 const unsigned Unset = ~0;
8269 unsigned FieldWidthIndex = Unset;
8270 unsigned PrecisionIndex = Unset;
8271
8272 // field width?
8273 const auto &FieldWidth = FS.getFieldWidth();
8274 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8275 FieldWidthIndex = Specs.size();
8276 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8277 getLocationOfByte(FieldWidth.getStart()),
8279 FieldWidth.getArgType(S.Context),
8280 EquatableFormatArgument::FAR_FieldWidth,
8281 EquatableFormatArgument::SS_None,
8282 FieldWidth.usesPositionalArg()
8283 ? FieldWidth.getPositionalArgIndex() - 1
8284 : FieldWidthIndex,
8285 0);
8286 }
8287 // precision?
8288 const auto &Precision = FS.getPrecision();
8289 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8290 PrecisionIndex = Specs.size();
8291 Specs.emplace_back(
8292 getSpecifierRange(startSpecifier, specifierLen),
8293 getLocationOfByte(Precision.getStart()),
8295 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8296 EquatableFormatArgument::SS_None,
8297 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8298 : PrecisionIndex,
8299 0);
8300 }
8301
8302 // this specifier
8303 unsigned SpecIndex =
8304 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8305 if (FieldWidthIndex != Unset)
8306 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8307 if (PrecisionIndex != Unset)
8308 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8309
8310 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8311 if (FS.isPrivate())
8312 Sensitivity = EquatableFormatArgument::SS_Private;
8313 else if (FS.isPublic())
8314 Sensitivity = EquatableFormatArgument::SS_Public;
8315 else if (FS.isSensitive())
8316 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8317 else
8318 Sensitivity = EquatableFormatArgument::SS_None;
8319
8320 Specs.emplace_back(
8321 getSpecifierRange(startSpecifier, specifierLen),
8322 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8323 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8324 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8325
8326 // auxiliary argument?
8329 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8330 getLocationOfByte(CS.getStart()),
8332 CS.getCharacters(),
8334 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8335 SpecIndex + 1, SpecIndex);
8336 }
8337 return true;
8338}
8339
8340// Determines if the specified is a C++ class or struct containing
8341// a member with the specified name and kind (e.g. a CXXMethodDecl named
8342// "c_str()").
8343template<typename MemberKind>
8345CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8346 auto *RD = Ty->getAsCXXRecordDecl();
8348
8349 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8350 return Results;
8351
8352 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8355
8356 // We just need to include all members of the right kind turned up by the
8357 // filter, at this point.
8358 if (S.LookupQualifiedName(R, RD))
8359 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8360 NamedDecl *decl = (*I)->getUnderlyingDecl();
8361 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8362 Results.insert(FK);
8363 }
8364 return Results;
8365}
8366
8367/// Check if we could call '.c_str()' on an object.
8368///
8369/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8370/// allow the call, or if it would be ambiguous).
8372 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8373
8374 MethodSet Results =
8375 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8376 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8377 MI != ME; ++MI)
8378 if ((*MI)->getMinRequiredArguments() == 0)
8379 return true;
8380 return false;
8381}
8382
8383// Check if a (w)string was passed when a (w)char* was needed, and offer a
8384// better diagnostic if so. AT is assumed to be valid.
8385// Returns true when a c_str() conversion method is found.
8386bool CheckPrintfHandler::checkForCStrMembers(
8387 const analyze_printf::ArgType &AT, const Expr *E) {
8388 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8389
8390 MethodSet Results =
8392
8393 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8394 MI != ME; ++MI) {
8395 const CXXMethodDecl *Method = *MI;
8396 if (Method->getMinRequiredArguments() == 0 &&
8397 AT.matchesType(S.Context, Method->getReturnType())) {
8398 // FIXME: Suggest parens if the expression needs them.
8400 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8401 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8402 return true;
8403 }
8404 }
8405
8406 return false;
8407}
8408
8409bool CheckPrintfHandler::HandlePrintfSpecifier(
8410 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8411 unsigned specifierLen, const TargetInfo &Target) {
8412 using namespace analyze_format_string;
8413 using namespace analyze_printf;
8414
8415 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8416
8417 if (FS.consumesDataArgument()) {
8418 if (atFirstArg) {
8419 atFirstArg = false;
8420 usesPositionalArgs = FS.usesPositionalArg();
8421 }
8422 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8423 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8424 startSpecifier, specifierLen);
8425 return false;
8426 }
8427 }
8428
8429 // First check if the field width, precision, and conversion specifier
8430 // have matching data arguments.
8431 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8432 startSpecifier, specifierLen)) {
8433 return false;
8434 }
8435
8436 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8437 startSpecifier, specifierLen)) {
8438 return false;
8439 }
8440
8441 if (!CS.consumesDataArgument()) {
8442 // FIXME: Technically specifying a precision or field width here
8443 // makes no sense. Worth issuing a warning at some point.
8444 return true;
8445 }
8446
8447 // Consume the argument.
8448 unsigned argIndex = FS.getArgIndex();
8449 if (argIndex < NumDataArgs) {
8450 // The check to see if the argIndex is valid will come later.
8451 // We set the bit here because we may exit early from this
8452 // function if we encounter some other error.
8453 CoveredArgs.set(argIndex);
8454 }
8455
8456 // FreeBSD kernel extensions.
8457 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8458 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8459 // We need at least two arguments.
8460 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8461 return false;
8462
8463 if (HasFormatArguments()) {
8464 // Claim the second argument.
8465 CoveredArgs.set(argIndex + 1);
8466
8467 // Type check the first argument (int for %b, pointer for %D)
8468 const Expr *Ex = getDataArg(argIndex);
8469 const analyze_printf::ArgType &AT =
8470 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8471 ? ArgType(S.Context.IntTy)
8472 : ArgType::CPointerTy;
8473 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8474 EmitFormatDiagnostic(
8475 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8476 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8477 << false << Ex->getSourceRange(),
8478 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8479 getSpecifierRange(startSpecifier, specifierLen));
8480
8481 // Type check the second argument (char * for both %b and %D)
8482 Ex = getDataArg(argIndex + 1);
8484 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8485 EmitFormatDiagnostic(
8486 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8487 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8488 << false << Ex->getSourceRange(),
8489 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8490 getSpecifierRange(startSpecifier, specifierLen));
8491 }
8492 return true;
8493 }
8494
8495 // Check for using an Objective-C specific conversion specifier
8496 // in a non-ObjC literal.
8497 if (!allowsObjCArg() && CS.isObjCArg()) {
8498 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8499 specifierLen);
8500 }
8501
8502 // %P can only be used with os_log.
8503 if (FSType != FormatStringType::OSLog &&
8504 CS.getKind() == ConversionSpecifier::PArg) {
8505 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8506 specifierLen);
8507 }
8508
8509 // %n is not allowed with os_log.
8510 if (FSType == FormatStringType::OSLog &&
8511 CS.getKind() == ConversionSpecifier::nArg) {
8512 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8513 getLocationOfByte(CS.getStart()),
8514 /*IsStringLocation*/ false,
8515 getSpecifierRange(startSpecifier, specifierLen));
8516
8517 return true;
8518 }
8519
8520 // Only scalars are allowed for os_trace.
8521 if (FSType == FormatStringType::OSTrace &&
8522 (CS.getKind() == ConversionSpecifier::PArg ||
8523 CS.getKind() == ConversionSpecifier::sArg ||
8524 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8525 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8526 specifierLen);
8527 }
8528
8529 // Check for use of public/private annotation outside of os_log().
8530 if (FSType != FormatStringType::OSLog) {
8531 if (FS.isPublic().isSet()) {
8532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8533 << "public",
8534 getLocationOfByte(FS.isPublic().getPosition()),
8535 /*IsStringLocation*/ false,
8536 getSpecifierRange(startSpecifier, specifierLen));
8537 }
8538 if (FS.isPrivate().isSet()) {
8539 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8540 << "private",
8541 getLocationOfByte(FS.isPrivate().getPosition()),
8542 /*IsStringLocation*/ false,
8543 getSpecifierRange(startSpecifier, specifierLen));
8544 }
8545 }
8546
8547 const llvm::Triple &Triple = Target.getTriple();
8548 if (CS.getKind() == ConversionSpecifier::nArg &&
8549 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8550 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8551 getLocationOfByte(CS.getStart()),
8552 /*IsStringLocation*/ false,
8553 getSpecifierRange(startSpecifier, specifierLen));
8554 }
8555
8556 // Check for invalid use of field width
8557 if (!FS.hasValidFieldWidth()) {
8558 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8559 startSpecifier, specifierLen);
8560 }
8561
8562 // Check for invalid use of precision
8563 if (!FS.hasValidPrecision()) {
8564 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8565 startSpecifier, specifierLen);
8566 }
8567
8568 // Precision is mandatory for %P specifier.
8569 if (CS.getKind() == ConversionSpecifier::PArg &&
8571 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8572 getLocationOfByte(startSpecifier),
8573 /*IsStringLocation*/ false,
8574 getSpecifierRange(startSpecifier, specifierLen));
8575 }
8576
8577 // Check each flag does not conflict with any other component.
8579 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8580 if (!FS.hasValidLeadingZeros())
8581 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8582 if (!FS.hasValidPlusPrefix())
8583 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8584 if (!FS.hasValidSpacePrefix())
8585 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8586 if (!FS.hasValidAlternativeForm())
8587 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8588 if (!FS.hasValidLeftJustified())
8589 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8590
8591 // Check that flags are not ignored by another flag
8592 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8593 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8594 startSpecifier, specifierLen);
8595 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8596 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8597 startSpecifier, specifierLen);
8598
8599 // Check the length modifier is valid with the given conversion specifier.
8601 S.getLangOpts()))
8602 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8603 diag::warn_format_nonsensical_length);
8604 else if (!FS.hasStandardLengthModifier())
8605 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8607 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8608 diag::warn_format_non_standard_conversion_spec);
8609
8611 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8612
8613 // The remaining checks depend on the data arguments.
8614 if (!HasFormatArguments())
8615 return true;
8616
8617 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8618 return false;
8619
8620 const Expr *Arg = getDataArg(argIndex);
8621 if (!Arg)
8622 return true;
8623
8624 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8625}
8626
8627static bool requiresParensToAddCast(const Expr *E) {
8628 // FIXME: We should have a general way to reason about operator
8629 // precedence and whether parens are actually needed here.
8630 // Take care of a few common cases where they aren't.
8631 const Expr *Inside = E->IgnoreImpCasts();
8632 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8633 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8634
8635 switch (Inside->getStmtClass()) {
8636 case Stmt::ArraySubscriptExprClass:
8637 case Stmt::CallExprClass:
8638 case Stmt::CharacterLiteralClass:
8639 case Stmt::CXXBoolLiteralExprClass:
8640 case Stmt::DeclRefExprClass:
8641 case Stmt::FloatingLiteralClass:
8642 case Stmt::IntegerLiteralClass:
8643 case Stmt::MemberExprClass:
8644 case Stmt::ObjCArrayLiteralClass:
8645 case Stmt::ObjCBoolLiteralExprClass:
8646 case Stmt::ObjCBoxedExprClass:
8647 case Stmt::ObjCDictionaryLiteralClass:
8648 case Stmt::ObjCEncodeExprClass:
8649 case Stmt::ObjCIvarRefExprClass:
8650 case Stmt::ObjCMessageExprClass:
8651 case Stmt::ObjCPropertyRefExprClass:
8652 case Stmt::ObjCStringLiteralClass:
8653 case Stmt::ObjCSubscriptRefExprClass:
8654 case Stmt::ParenExprClass:
8655 case Stmt::StringLiteralClass:
8656 case Stmt::UnaryOperatorClass:
8657 return false;
8658 default:
8659 return true;
8660 }
8661}
8662
8663static std::pair<QualType, StringRef>
8665 QualType IntendedTy,
8666 const Expr *E) {
8667 // Use a 'while' to peel off layers of typedefs.
8668 QualType TyTy = IntendedTy;
8669 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8670 StringRef Name = UserTy->getDecl()->getName();
8671 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8672 .Case("CFIndex", Context.getNSIntegerType())
8673 .Case("NSInteger", Context.getNSIntegerType())
8674 .Case("NSUInteger", Context.getNSUIntegerType())
8675 .Case("SInt32", Context.IntTy)
8676 .Case("UInt32", Context.UnsignedIntTy)
8677 .Default(QualType());
8678
8679 if (!CastTy.isNull())
8680 return std::make_pair(CastTy, Name);
8681
8682 TyTy = UserTy->desugar();
8683 }
8684
8685 // Strip parens if necessary.
8686 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8687 return shouldNotPrintDirectly(Context,
8688 PE->getSubExpr()->getType(),
8689 PE->getSubExpr());
8690
8691 // If this is a conditional expression, then its result type is constructed
8692 // via usual arithmetic conversions and thus there might be no necessary
8693 // typedef sugar there. Recurse to operands to check for NSInteger &
8694 // Co. usage condition.
8695 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8696 QualType TrueTy, FalseTy;
8697 StringRef TrueName, FalseName;
8698
8699 std::tie(TrueTy, TrueName) =
8700 shouldNotPrintDirectly(Context,
8701 CO->getTrueExpr()->getType(),
8702 CO->getTrueExpr());
8703 std::tie(FalseTy, FalseName) =
8704 shouldNotPrintDirectly(Context,
8705 CO->getFalseExpr()->getType(),
8706 CO->getFalseExpr());
8707
8708 if (TrueTy == FalseTy)
8709 return std::make_pair(TrueTy, TrueName);
8710 else if (TrueTy.isNull())
8711 return std::make_pair(FalseTy, FalseName);
8712 else if (FalseTy.isNull())
8713 return std::make_pair(TrueTy, TrueName);
8714 }
8715
8716 return std::make_pair(QualType(), StringRef());
8717}
8718
8719/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8720/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8721/// type do not count.
8722static bool
8724 QualType From = ICE->getSubExpr()->getType();
8725 QualType To = ICE->getType();
8726 // It's an integer promotion if the destination type is the promoted
8727 // source type.
8728 if (ICE->getCastKind() == CK_IntegralCast &&
8730 S.Context.getPromotedIntegerType(From) == To)
8731 return true;
8732 // Look through vector types, since we do default argument promotion for
8733 // those in OpenCL.
8734 if (const auto *VecTy = From->getAs<ExtVectorType>())
8735 From = VecTy->getElementType();
8736 if (const auto *VecTy = To->getAs<ExtVectorType>())
8737 To = VecTy->getElementType();
8738 // It's a floating promotion if the source type is a lower rank.
8739 return ICE->getCastKind() == CK_FloatingCast &&
8740 S.Context.getFloatingTypeOrder(From, To) < 0;
8741}
8742
8745 DiagnosticsEngine &Diags, SourceLocation Loc) {
8747 if (Diags.isIgnored(
8748 diag::warn_format_conversion_argument_type_mismatch_signedness,
8749 Loc) ||
8750 Diags.isIgnored(
8751 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8752 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8754 }
8755 }
8756 return Match;
8757}
8758
8759bool
8760CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8761 const char *StartSpecifier,
8762 unsigned SpecifierLen,
8763 const Expr *E) {
8764 using namespace analyze_format_string;
8765 using namespace analyze_printf;
8766
8767 // Now type check the data expression that matches the
8768 // format specifier.
8769 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8770 if (!AT.isValid())
8771 return true;
8772
8773 QualType ExprTy = E->getType();
8774 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8775 ExprTy = TET->getUnderlyingExpr()->getType();
8776 }
8777
8778 // When using the format attribute in C++, you can receive a function or an
8779 // array that will necessarily decay to a pointer when passed to the final
8780 // format consumer. Apply decay before type comparison.
8781 if (ExprTy->canDecayToPointerType())
8782 ExprTy = S.Context.getDecayedType(ExprTy);
8783
8784 // Diagnose attempts to print a boolean value as a character. Unlike other
8785 // -Wformat diagnostics, this is fine from a type perspective, but it still
8786 // doesn't make sense.
8789 const CharSourceRange &CSR =
8790 getSpecifierRange(StartSpecifier, SpecifierLen);
8791 SmallString<4> FSString;
8792 llvm::raw_svector_ostream os(FSString);
8793 FS.toString(os);
8794 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8795 << FSString,
8796 E->getExprLoc(), false, CSR);
8797 return true;
8798 }
8799
8800 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8801 // dumping raw class data (like is-a pointer), not actual data.
8803 ExprTy->isObjCObjectPointerType()) {
8804 const CharSourceRange &CSR =
8805 getSpecifierRange(StartSpecifier, SpecifierLen);
8806 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8807 E->getExprLoc(), false, CSR);
8808 return true;
8809 }
8810
8811 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8813 ArgType::MatchKind OrigMatch = Match;
8814
8816 if (Match == ArgType::Match)
8817 return true;
8818
8819 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8820 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8821
8822 // Look through argument promotions for our error message's reported type.
8823 // This includes the integral and floating promotions, but excludes array
8824 // and function pointer decay (seeing that an argument intended to be a
8825 // string has type 'char [6]' is probably more confusing than 'char *') and
8826 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8827 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8828 if (isArithmeticArgumentPromotion(S, ICE)) {
8829 E = ICE->getSubExpr();
8830 ExprTy = E->getType();
8831
8832 // Check if we didn't match because of an implicit cast from a 'char'
8833 // or 'short' to an 'int'. This is done because printf is a varargs
8834 // function.
8835 if (ICE->getType() == S.Context.IntTy ||
8836 ICE->getType() == S.Context.UnsignedIntTy) {
8837 // All further checking is done on the subexpression
8838 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8839 if (OrigMatch == ArgType::NoMatchSignedness &&
8840 ImplicitMatch != ArgType::NoMatchSignedness)
8841 // If the original match was a signedness match this match on the
8842 // implicit cast type also need to be signedness match otherwise we
8843 // might introduce new unexpected warnings from -Wformat-signedness.
8844 return true;
8845 ImplicitMatch = handleFormatSignedness(
8846 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8847 if (ImplicitMatch == ArgType::Match)
8848 return true;
8849 }
8850 }
8851 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8852 // Special case for 'a', which has type 'int' in C.
8853 // Note, however, that we do /not/ want to treat multibyte constants like
8854 // 'MooV' as characters! This form is deprecated but still exists. In
8855 // addition, don't treat expressions as of type 'char' if one byte length
8856 // modifier is provided.
8857 if (ExprTy == S.Context.IntTy &&
8859 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8860 ExprTy = S.Context.CharTy;
8861 // To improve check results, we consider a character literal in C
8862 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8863 // more likely a type confusion situation, so we will suggest to
8864 // use '%hhd' instead by discarding the MatchPromotion.
8865 if (Match == ArgType::MatchPromotion)
8867 }
8868 }
8869 if (Match == ArgType::MatchPromotion) {
8870 // WG14 N2562 only clarified promotions in *printf
8871 // For NSLog in ObjC, just preserve -Wformat behavior
8872 if (!S.getLangOpts().ObjC &&
8873 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8874 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8875 return true;
8877 }
8878 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8879 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8880 Match = ImplicitMatch;
8881 assert(Match != ArgType::MatchPromotion);
8882
8883 // Look through unscoped enums to their underlying type.
8884 bool IsEnum = false;
8885 bool IsScopedEnum = false;
8886 QualType IntendedTy = ExprTy;
8887 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8888 IntendedTy = ED->getIntegerType();
8889 if (!ED->isScoped()) {
8890 ExprTy = IntendedTy;
8891 // This controls whether we're talking about the underlying type or not,
8892 // which we only want to do when it's an unscoped enum.
8893 IsEnum = true;
8894 } else {
8895 IsScopedEnum = true;
8896 }
8897 }
8898
8899 // %C in an Objective-C context prints a unichar, not a wchar_t.
8900 // If the argument is an integer of some kind, believe the %C and suggest
8901 // a cast instead of changing the conversion specifier.
8902 if (isObjCContext() &&
8905 !ExprTy->isCharType()) {
8906 // 'unichar' is defined as a typedef of unsigned short, but we should
8907 // prefer using the typedef if it is visible.
8908 IntendedTy = S.Context.UnsignedShortTy;
8909
8910 // While we are here, check if the value is an IntegerLiteral that happens
8911 // to be within the valid range.
8912 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8913 const llvm::APInt &V = IL->getValue();
8914 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8915 return true;
8916 }
8917
8918 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8920 if (S.LookupName(Result, S.getCurScope())) {
8921 NamedDecl *ND = Result.getFoundDecl();
8922 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8923 if (TD->getUnderlyingType() == IntendedTy)
8924 IntendedTy =
8926 /*Qualifier=*/std::nullopt, TD);
8927 }
8928 }
8929 }
8930
8931 // Special-case some of Darwin's platform-independence types by suggesting
8932 // casts to primitive types that are known to be large enough.
8933 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8934 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8935 QualType CastTy;
8936 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8937 if (!CastTy.isNull()) {
8938 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8939 // (long in ASTContext). Only complain to pedants or when they're the
8940 // underlying type of a scoped enum (which always needs a cast).
8941 if (!IsScopedEnum &&
8942 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8943 (AT.isSizeT() || AT.isPtrdiffT()) &&
8944 AT.matchesType(S.Context, CastTy))
8946 IntendedTy = CastTy;
8947 ShouldNotPrintDirectly = true;
8948 }
8949 }
8950
8951 // We may be able to offer a FixItHint if it is a supported type.
8952 PrintfSpecifier fixedFS = FS;
8953 bool Success =
8954 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8955
8956 if (Success) {
8957 // Get the fix string from the fixed format specifier
8958 SmallString<16> buf;
8959 llvm::raw_svector_ostream os(buf);
8960 fixedFS.toString(os);
8961
8962 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8963
8964 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8965 unsigned Diag;
8966 switch (Match) {
8967 case ArgType::Match:
8970 llvm_unreachable("expected non-matching");
8972 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8973 break;
8975 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8976 break;
8978 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8979 break;
8980 case ArgType::NoMatch:
8981 Diag = diag::warn_format_conversion_argument_type_mismatch;
8982 break;
8983 }
8984
8985 // In this case, the specifier is wrong and should be changed to match
8986 // the argument.
8987 EmitFormatDiagnostic(S.PDiag(Diag)
8989 << IntendedTy << IsEnum << E->getSourceRange(),
8990 E->getBeginLoc(),
8991 /*IsStringLocation*/ false, SpecRange,
8992 FixItHint::CreateReplacement(SpecRange, os.str()));
8993 } else {
8994 // The canonical type for formatting this value is different from the
8995 // actual type of the expression. (This occurs, for example, with Darwin's
8996 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8997 // should be printed as 'long' for 64-bit compatibility.)
8998 // Rather than emitting a normal format/argument mismatch, we want to
8999 // add a cast to the recommended type (and correct the format string
9000 // if necessary). We should also do so for scoped enumerations.
9001 SmallString<16> CastBuf;
9002 llvm::raw_svector_ostream CastFix(CastBuf);
9003 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9004 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9005 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9006
9008 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9009 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9010 E->getExprLoc());
9011 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9012 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9013
9014 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9015 // If there's already a cast present, just replace it.
9016 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9017 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9018
9019 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9020 // If the expression has high enough precedence,
9021 // just write the C-style cast.
9022 Hints.push_back(
9023 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9024 } else {
9025 // Otherwise, add parens around the expression as well as the cast.
9026 CastFix << "(";
9027 Hints.push_back(
9028 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9029
9030 // We don't use getLocForEndOfToken because it returns invalid source
9031 // locations for macro expansions (by design).
9035 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9036 }
9037
9038 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9039 // The expression has a type that should not be printed directly.
9040 // We extract the name from the typedef because we don't want to show
9041 // the underlying type in the diagnostic.
9042 StringRef Name;
9043 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9044 Name = TypedefTy->getDecl()->getName();
9045 else
9046 Name = CastTyName;
9047 unsigned Diag = Match == ArgType::NoMatchPedantic
9048 ? diag::warn_format_argument_needs_cast_pedantic
9049 : diag::warn_format_argument_needs_cast;
9050 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9051 << E->getSourceRange(),
9052 E->getBeginLoc(), /*IsStringLocation=*/false,
9053 SpecRange, Hints);
9054 } else {
9055 // In this case, the expression could be printed using a different
9056 // specifier, but we've decided that the specifier is probably correct
9057 // and we should cast instead. Just use the normal warning message.
9058
9059 unsigned Diag =
9060 IsScopedEnum
9061 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9062 : diag::warn_format_conversion_argument_type_mismatch;
9063
9064 EmitFormatDiagnostic(
9065 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9066 << IsEnum << E->getSourceRange(),
9067 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9068 }
9069 }
9070 } else {
9071 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9072 SpecifierLen);
9073 // Since the warning for passing non-POD types to variadic functions
9074 // was deferred until now, we emit a warning for non-POD
9075 // arguments here.
9076 bool EmitTypeMismatch = false;
9077 switch (S.isValidVarArgType(ExprTy)) {
9078 case VarArgKind::Valid:
9080 unsigned Diag;
9081 switch (Match) {
9082 case ArgType::Match:
9085 llvm_unreachable("expected non-matching");
9087 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9088 break;
9090 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9091 break;
9093 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9094 break;
9095 case ArgType::NoMatch:
9096 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9097 ? diag::err_format_conversion_argument_type_mismatch
9098 : diag::warn_format_conversion_argument_type_mismatch;
9099 break;
9100 }
9101
9102 EmitFormatDiagnostic(
9103 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9104 << IsEnum << CSR << E->getSourceRange(),
9105 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9106 break;
9107 }
9110 if (CallType == VariadicCallType::DoesNotApply) {
9111 EmitTypeMismatch = true;
9112 } else {
9113 EmitFormatDiagnostic(
9114 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9115 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9116 << AT.getRepresentativeTypeName(S.Context) << CSR
9117 << E->getSourceRange(),
9118 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9119 checkForCStrMembers(AT, E);
9120 }
9121 break;
9122
9124 if (CallType == VariadicCallType::DoesNotApply)
9125 EmitTypeMismatch = true;
9126 else if (ExprTy->isObjCObjectType())
9127 EmitFormatDiagnostic(
9128 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9129 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9130 << AT.getRepresentativeTypeName(S.Context) << CSR
9131 << E->getSourceRange(),
9132 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9133 else
9134 // FIXME: If this is an initializer list, suggest removing the braces
9135 // or inserting a cast to the target type.
9136 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9137 << isa<InitListExpr>(E) << ExprTy << CallType
9139 break;
9140 }
9141
9142 if (EmitTypeMismatch) {
9143 // The function is not variadic, so we do not generate warnings about
9144 // being allowed to pass that object as a variadic argument. Instead,
9145 // since there are inherently no printf specifiers for types which cannot
9146 // be passed as variadic arguments, emit a plain old specifier mismatch
9147 // argument.
9148 EmitFormatDiagnostic(
9149 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9150 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9151 << E->getSourceRange(),
9152 E->getBeginLoc(), false, CSR);
9153 }
9154
9155 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9156 "format string specifier index out of range");
9157 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9158 }
9159
9160 return true;
9161}
9162
9163//===--- CHECK: Scanf format string checking ------------------------------===//
9164
9165namespace {
9166
9167class CheckScanfHandler : public CheckFormatHandler {
9168public:
9169 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9170 const Expr *origFormatExpr, FormatStringType type,
9171 unsigned firstDataArg, unsigned numDataArgs,
9172 const char *beg, Sema::FormatArgumentPassingKind APK,
9173 ArrayRef<const Expr *> Args, unsigned formatIdx,
9174 bool inFunctionCall, VariadicCallType CallType,
9175 llvm::SmallBitVector &CheckedVarArgs,
9176 UncoveredArgHandler &UncoveredArg)
9177 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9178 numDataArgs, beg, APK, Args, formatIdx,
9179 inFunctionCall, CallType, CheckedVarArgs,
9180 UncoveredArg) {}
9181
9182 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9183 const char *startSpecifier,
9184 unsigned specifierLen) override;
9185
9186 bool HandleInvalidScanfConversionSpecifier(
9187 const analyze_scanf::ScanfSpecifier &FS,
9188 const char *startSpecifier,
9189 unsigned specifierLen) override;
9190
9191 void HandleIncompleteScanList(const char *start, const char *end) override;
9192};
9193
9194} // namespace
9195
9196void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9197 const char *end) {
9198 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9199 getLocationOfByte(end), /*IsStringLocation*/true,
9200 getSpecifierRange(start, end - start));
9201}
9202
9203bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9205 const char *startSpecifier,
9206 unsigned specifierLen) {
9209
9210 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9211 getLocationOfByte(CS.getStart()),
9212 startSpecifier, specifierLen,
9213 CS.getStart(), CS.getLength());
9214}
9215
9216bool CheckScanfHandler::HandleScanfSpecifier(
9218 const char *startSpecifier,
9219 unsigned specifierLen) {
9220 using namespace analyze_scanf;
9221 using namespace analyze_format_string;
9222
9223 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9224
9225 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9226 // be used to decide if we are using positional arguments consistently.
9227 if (FS.consumesDataArgument()) {
9228 if (atFirstArg) {
9229 atFirstArg = false;
9230 usesPositionalArgs = FS.usesPositionalArg();
9231 }
9232 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9233 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9234 startSpecifier, specifierLen);
9235 return false;
9236 }
9237 }
9238
9239 // Check if the field with is non-zero.
9240 const OptionalAmount &Amt = FS.getFieldWidth();
9242 if (Amt.getConstantAmount() == 0) {
9243 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9244 Amt.getConstantLength());
9245 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9246 getLocationOfByte(Amt.getStart()),
9247 /*IsStringLocation*/true, R,
9249 }
9250 }
9251
9252 if (!FS.consumesDataArgument()) {
9253 // FIXME: Technically specifying a precision or field width here
9254 // makes no sense. Worth issuing a warning at some point.
9255 return true;
9256 }
9257
9258 // Consume the argument.
9259 unsigned argIndex = FS.getArgIndex();
9260 if (argIndex < NumDataArgs) {
9261 // The check to see if the argIndex is valid will come later.
9262 // We set the bit here because we may exit early from this
9263 // function if we encounter some other error.
9264 CoveredArgs.set(argIndex);
9265 }
9266
9267 // Check the length modifier is valid with the given conversion specifier.
9269 S.getLangOpts()))
9270 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9271 diag::warn_format_nonsensical_length);
9272 else if (!FS.hasStandardLengthModifier())
9273 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9275 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9276 diag::warn_format_non_standard_conversion_spec);
9277
9279 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9280
9281 // The remaining checks depend on the data arguments.
9282 if (!HasFormatArguments())
9283 return true;
9284
9285 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9286 return false;
9287
9288 // Check that the argument type matches the format specifier.
9289 const Expr *Ex = getDataArg(argIndex);
9290 if (!Ex)
9291 return true;
9292
9294
9295 if (!AT.isValid()) {
9296 return true;
9297 }
9298
9300 AT.matchesType(S.Context, Ex->getType());
9303 return true;
9306
9307 ScanfSpecifier fixedFS = FS;
9308 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9309 S.getLangOpts(), S.Context);
9310
9311 unsigned Diag =
9312 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9313 : Signedness
9314 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9315 : diag::warn_format_conversion_argument_type_mismatch;
9316
9317 if (Success) {
9318 // Get the fix string from the fixed format specifier.
9319 SmallString<128> buf;
9320 llvm::raw_svector_ostream os(buf);
9321 fixedFS.toString(os);
9322
9323 EmitFormatDiagnostic(
9325 << Ex->getType() << false << Ex->getSourceRange(),
9326 Ex->getBeginLoc(),
9327 /*IsStringLocation*/ false,
9328 getSpecifierRange(startSpecifier, specifierLen),
9330 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9331 } else {
9332 EmitFormatDiagnostic(S.PDiag(Diag)
9334 << Ex->getType() << false << Ex->getSourceRange(),
9335 Ex->getBeginLoc(),
9336 /*IsStringLocation*/ false,
9337 getSpecifierRange(startSpecifier, specifierLen));
9338 }
9339
9340 return true;
9341}
9342
9343static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9345 const StringLiteral *Fmt,
9347 const Expr *FmtExpr, bool InFunctionCall) {
9348 bool HadError = false;
9349 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9350 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9351 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9352 // In positional-style format strings, the same specifier can appear
9353 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9354 // are sorted by getPosition(), and we process each range of equal
9355 // getPosition() values as one group.
9356 // RefArgs are taken from a string literal that was given to
9357 // attribute(format_matches), and if we got this far, we have already
9358 // verified that if it has positional specifiers that appear in multiple
9359 // locations, then they are all mutually compatible. What's left for us to
9360 // do is verify that all specifiers with the same position in FmtArgs are
9361 // compatible with the RefArgs specifiers. We check each specifier from
9362 // FmtArgs against the first member of the RefArgs group.
9363 for (; FmtIter < FmtEnd; ++FmtIter) {
9364 // Clang does not diagnose missing format specifiers in positional-style
9365 // strings (TODO: which it probably should do, as it is UB to skip over a
9366 // format argument). Skip specifiers if needed.
9367 if (FmtIter->getPosition() < RefIter->getPosition())
9368 continue;
9369
9370 // Delimits a new getPosition() value.
9371 if (FmtIter->getPosition() > RefIter->getPosition())
9372 break;
9373
9374 HadError |=
9375 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9376 }
9377
9378 // Jump RefIter to the start of the next group.
9379 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9380 return Arg.getPosition() != RefIter->getPosition();
9381 });
9382 }
9383
9384 if (FmtIter < FmtEnd) {
9385 CheckFormatHandler::EmitFormatDiagnostic(
9386 S, InFunctionCall, FmtExpr,
9387 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9388 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9389 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9390 } else if (RefIter < RefEnd) {
9391 CheckFormatHandler::EmitFormatDiagnostic(
9392 S, InFunctionCall, FmtExpr,
9393 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9394 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9395 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9396 << 1 << RefIter->getSourceRange();
9397 }
9398 return !HadError;
9399}
9400
9402 Sema &S, const FormatStringLiteral *FExpr,
9403 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9405 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9406 bool inFunctionCall, VariadicCallType CallType,
9407 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9408 bool IgnoreStringsWithoutSpecifiers) {
9409 // CHECK: is the format string a wide literal?
9410 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9411 CheckFormatHandler::EmitFormatDiagnostic(
9412 S, inFunctionCall, Args[format_idx],
9413 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9414 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9415 return;
9416 }
9417
9418 // Str - The format string. NOTE: this is NOT null-terminated!
9419 StringRef StrRef = FExpr->getString();
9420 const char *Str = StrRef.data();
9421 // Account for cases where the string literal is truncated in a declaration.
9422 const ConstantArrayType *T =
9423 S.Context.getAsConstantArrayType(FExpr->getType());
9424 assert(T && "String literal not of constant array type!");
9425 size_t TypeSize = T->getZExtSize();
9426 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9427 const unsigned numDataArgs = Args.size() - firstDataArg;
9428
9429 if (IgnoreStringsWithoutSpecifiers &&
9431 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9432 return;
9433
9434 // Emit a warning if the string literal is truncated and does not contain an
9435 // embedded null character.
9436 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9437 CheckFormatHandler::EmitFormatDiagnostic(
9438 S, inFunctionCall, Args[format_idx],
9439 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9440 FExpr->getBeginLoc(),
9441 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9442 return;
9443 }
9444
9445 // CHECK: empty format string?
9446 if (StrLen == 0 && numDataArgs > 0) {
9447 CheckFormatHandler::EmitFormatDiagnostic(
9448 S, inFunctionCall, Args[format_idx],
9449 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9450 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9451 return;
9452 }
9453
9458 bool IsObjC =
9460 if (ReferenceFormatString == nullptr) {
9461 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9462 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9463 inFunctionCall, CallType, CheckedVarArgs,
9464 UncoveredArg);
9465
9467 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9470 H.DoneProcessing();
9471 } else {
9473 Type, ReferenceFormatString, FExpr->getFormatString(),
9474 inFunctionCall ? nullptr : Args[format_idx]);
9475 }
9476 } else if (Type == FormatStringType::Scanf) {
9477 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9478 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9479 CallType, CheckedVarArgs, UncoveredArg);
9480
9482 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9483 H.DoneProcessing();
9484 } // TODO: handle other formats
9485}
9486
9488 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9489 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9494 return true;
9495
9496 bool IsObjC =
9499 FormatStringLiteral RefLit = AuthoritativeFormatString;
9500 FormatStringLiteral TestLit = TestedFormatString;
9501 const Expr *Arg;
9502 bool DiagAtStringLiteral;
9503 if (FunctionCallArg) {
9504 Arg = FunctionCallArg;
9505 DiagAtStringLiteral = false;
9506 } else {
9507 Arg = TestedFormatString;
9508 DiagAtStringLiteral = true;
9509 }
9510 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9511 AuthoritativeFormatString, Type,
9512 IsObjC, true, RefArgs) &&
9513 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9514 DiagAtStringLiteral, FmtArgs)) {
9515 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9516 TestedFormatString, FmtArgs, Arg,
9517 DiagAtStringLiteral);
9518 }
9519 return false;
9520}
9521
9523 const StringLiteral *Str) {
9528 return true;
9529
9530 FormatStringLiteral RefLit = Str;
9532 bool IsObjC =
9534 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9535 true, Args))
9536 return false;
9537
9538 // Group arguments by getPosition() value, and check that each member of the
9539 // group is compatible with the first member. This verifies that when
9540 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9541 // are mutually compatible. As an optimization, don't test the first member
9542 // against itself.
9543 bool HadError = false;
9544 auto Iter = Args.begin();
9545 auto End = Args.end();
9546 while (Iter != End) {
9547 const auto &FirstInGroup = *Iter;
9548 for (++Iter;
9549 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9550 ++Iter) {
9551 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9552 }
9553 }
9554 return !HadError;
9555}
9556
9558 // Str - The format string. NOTE: this is NOT null-terminated!
9559 StringRef StrRef = FExpr->getString();
9560 const char *Str = StrRef.data();
9561 // Account for cases where the string literal is truncated in a declaration.
9562 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9563 assert(T && "String literal not of constant array type!");
9564 size_t TypeSize = T->getZExtSize();
9565 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9566 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9567 getLangOpts(),
9568 Context.getTargetInfo());
9569}
9570
9571//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9572
9573// Returns the related absolute value function that is larger, of 0 if one
9574// does not exist.
9575static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9576 switch (AbsFunction) {
9577 default:
9578 return 0;
9579
9580 case Builtin::BI__builtin_abs:
9581 return Builtin::BI__builtin_labs;
9582 case Builtin::BI__builtin_labs:
9583 return Builtin::BI__builtin_llabs;
9584 case Builtin::BI__builtin_llabs:
9585 return 0;
9586
9587 case Builtin::BI__builtin_fabsf:
9588 return Builtin::BI__builtin_fabs;
9589 case Builtin::BI__builtin_fabs:
9590 return Builtin::BI__builtin_fabsl;
9591 case Builtin::BI__builtin_fabsl:
9592 return 0;
9593
9594 case Builtin::BI__builtin_cabsf:
9595 return Builtin::BI__builtin_cabs;
9596 case Builtin::BI__builtin_cabs:
9597 return Builtin::BI__builtin_cabsl;
9598 case Builtin::BI__builtin_cabsl:
9599 return 0;
9600
9601 case Builtin::BIabs:
9602 return Builtin::BIlabs;
9603 case Builtin::BIlabs:
9604 return Builtin::BIllabs;
9605 case Builtin::BIllabs:
9606 return 0;
9607
9608 case Builtin::BIfabsf:
9609 return Builtin::BIfabs;
9610 case Builtin::BIfabs:
9611 return Builtin::BIfabsl;
9612 case Builtin::BIfabsl:
9613 return 0;
9614
9615 case Builtin::BIcabsf:
9616 return Builtin::BIcabs;
9617 case Builtin::BIcabs:
9618 return Builtin::BIcabsl;
9619 case Builtin::BIcabsl:
9620 return 0;
9621 }
9622}
9623
9624// Returns the argument type of the absolute value function.
9626 unsigned AbsType) {
9627 if (AbsType == 0)
9628 return QualType();
9629
9631 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9633 return QualType();
9634
9636 if (!FT)
9637 return QualType();
9638
9639 if (FT->getNumParams() != 1)
9640 return QualType();
9641
9642 return FT->getParamType(0);
9643}
9644
9645// Returns the best absolute value function, or zero, based on type and
9646// current absolute value function.
9647static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9648 unsigned AbsFunctionKind) {
9649 unsigned BestKind = 0;
9650 uint64_t ArgSize = Context.getTypeSize(ArgType);
9651 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9652 Kind = getLargerAbsoluteValueFunction(Kind)) {
9653 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9654 if (Context.getTypeSize(ParamType) >= ArgSize) {
9655 if (BestKind == 0)
9656 BestKind = Kind;
9657 else if (Context.hasSameType(ParamType, ArgType)) {
9658 BestKind = Kind;
9659 break;
9660 }
9661 }
9662 }
9663 return BestKind;
9664}
9665
9671
9673 if (T->isIntegralOrEnumerationType())
9674 return AVK_Integer;
9675 if (T->isRealFloatingType())
9676 return AVK_Floating;
9677 if (T->isAnyComplexType())
9678 return AVK_Complex;
9679
9680 llvm_unreachable("Type not integer, floating, or complex");
9681}
9682
9683// Changes the absolute value function to a different type. Preserves whether
9684// the function is a builtin.
9685static unsigned changeAbsFunction(unsigned AbsKind,
9686 AbsoluteValueKind ValueKind) {
9687 switch (ValueKind) {
9688 case AVK_Integer:
9689 switch (AbsKind) {
9690 default:
9691 return 0;
9692 case Builtin::BI__builtin_fabsf:
9693 case Builtin::BI__builtin_fabs:
9694 case Builtin::BI__builtin_fabsl:
9695 case Builtin::BI__builtin_cabsf:
9696 case Builtin::BI__builtin_cabs:
9697 case Builtin::BI__builtin_cabsl:
9698 return Builtin::BI__builtin_abs;
9699 case Builtin::BIfabsf:
9700 case Builtin::BIfabs:
9701 case Builtin::BIfabsl:
9702 case Builtin::BIcabsf:
9703 case Builtin::BIcabs:
9704 case Builtin::BIcabsl:
9705 return Builtin::BIabs;
9706 }
9707 case AVK_Floating:
9708 switch (AbsKind) {
9709 default:
9710 return 0;
9711 case Builtin::BI__builtin_abs:
9712 case Builtin::BI__builtin_labs:
9713 case Builtin::BI__builtin_llabs:
9714 case Builtin::BI__builtin_cabsf:
9715 case Builtin::BI__builtin_cabs:
9716 case Builtin::BI__builtin_cabsl:
9717 return Builtin::BI__builtin_fabsf;
9718 case Builtin::BIabs:
9719 case Builtin::BIlabs:
9720 case Builtin::BIllabs:
9721 case Builtin::BIcabsf:
9722 case Builtin::BIcabs:
9723 case Builtin::BIcabsl:
9724 return Builtin::BIfabsf;
9725 }
9726 case AVK_Complex:
9727 switch (AbsKind) {
9728 default:
9729 return 0;
9730 case Builtin::BI__builtin_abs:
9731 case Builtin::BI__builtin_labs:
9732 case Builtin::BI__builtin_llabs:
9733 case Builtin::BI__builtin_fabsf:
9734 case Builtin::BI__builtin_fabs:
9735 case Builtin::BI__builtin_fabsl:
9736 return Builtin::BI__builtin_cabsf;
9737 case Builtin::BIabs:
9738 case Builtin::BIlabs:
9739 case Builtin::BIllabs:
9740 case Builtin::BIfabsf:
9741 case Builtin::BIfabs:
9742 case Builtin::BIfabsl:
9743 return Builtin::BIcabsf;
9744 }
9745 }
9746 llvm_unreachable("Unable to convert function");
9747}
9748
9749static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9750 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9751 if (!FnInfo)
9752 return 0;
9753
9754 switch (FDecl->getBuiltinID()) {
9755 default:
9756 return 0;
9757 case Builtin::BI__builtin_abs:
9758 case Builtin::BI__builtin_fabs:
9759 case Builtin::BI__builtin_fabsf:
9760 case Builtin::BI__builtin_fabsl:
9761 case Builtin::BI__builtin_labs:
9762 case Builtin::BI__builtin_llabs:
9763 case Builtin::BI__builtin_cabs:
9764 case Builtin::BI__builtin_cabsf:
9765 case Builtin::BI__builtin_cabsl:
9766 case Builtin::BIabs:
9767 case Builtin::BIlabs:
9768 case Builtin::BIllabs:
9769 case Builtin::BIfabs:
9770 case Builtin::BIfabsf:
9771 case Builtin::BIfabsl:
9772 case Builtin::BIcabs:
9773 case Builtin::BIcabsf:
9774 case Builtin::BIcabsl:
9775 return FDecl->getBuiltinID();
9776 }
9777 llvm_unreachable("Unknown Builtin type");
9778}
9779
9780// If the replacement is valid, emit a note with replacement function.
9781// Additionally, suggest including the proper header if not already included.
9783 unsigned AbsKind, QualType ArgType) {
9784 bool EmitHeaderHint = true;
9785 const char *HeaderName = nullptr;
9786 std::string FunctionName;
9787 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9788 FunctionName = "std::abs";
9789 if (ArgType->isIntegralOrEnumerationType()) {
9790 HeaderName = "cstdlib";
9791 } else if (ArgType->isRealFloatingType()) {
9792 HeaderName = "cmath";
9793 } else {
9794 llvm_unreachable("Invalid Type");
9795 }
9796
9797 // Lookup all std::abs
9798 if (NamespaceDecl *Std = S.getStdNamespace()) {
9799 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9801 S.LookupQualifiedName(R, Std);
9802
9803 for (const auto *I : R) {
9804 const FunctionDecl *FDecl = nullptr;
9805 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9806 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9807 } else {
9808 FDecl = dyn_cast<FunctionDecl>(I);
9809 }
9810 if (!FDecl)
9811 continue;
9812
9813 // Found std::abs(), check that they are the right ones.
9814 if (FDecl->getNumParams() != 1)
9815 continue;
9816
9817 // Check that the parameter type can handle the argument.
9818 QualType ParamType = FDecl->getParamDecl(0)->getType();
9819 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9820 S.Context.getTypeSize(ArgType) <=
9821 S.Context.getTypeSize(ParamType)) {
9822 // Found a function, don't need the header hint.
9823 EmitHeaderHint = false;
9824 break;
9825 }
9826 }
9827 }
9828 } else {
9829 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9830 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9831
9832 if (HeaderName) {
9833 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9834 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9836 S.LookupName(R, S.getCurScope());
9837
9838 if (R.isSingleResult()) {
9839 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9840 if (FD && FD->getBuiltinID() == AbsKind) {
9841 EmitHeaderHint = false;
9842 } else {
9843 return;
9844 }
9845 } else if (!R.empty()) {
9846 return;
9847 }
9848 }
9849 }
9850
9851 S.Diag(Loc, diag::note_replace_abs_function)
9852 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9853
9854 if (!HeaderName)
9855 return;
9856
9857 if (!EmitHeaderHint)
9858 return;
9859
9860 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9861 << FunctionName;
9862}
9863
9864template <std::size_t StrLen>
9865static bool IsStdFunction(const FunctionDecl *FDecl,
9866 const char (&Str)[StrLen]) {
9867 if (!FDecl)
9868 return false;
9869 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9870 return false;
9871 if (!FDecl->isInStdNamespace())
9872 return false;
9873
9874 return true;
9875}
9876
9877enum class MathCheck { NaN, Inf };
9878static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9879 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9880 return llvm::is_contained(names, calleeName);
9881 };
9882
9883 switch (Check) {
9884 case MathCheck::NaN:
9885 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9886 "__builtin_nanf16", "__builtin_nanf128"});
9887 case MathCheck::Inf:
9888 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9889 "__builtin_inff16", "__builtin_inff128"});
9890 }
9891 llvm_unreachable("unknown MathCheck");
9892}
9893
9894static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9895 if (FDecl->getName() != "infinity")
9896 return false;
9897
9898 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9899 const CXXRecordDecl *RDecl = MDecl->getParent();
9900 if (RDecl->getName() != "numeric_limits")
9901 return false;
9902
9903 if (const NamespaceDecl *NSDecl =
9904 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9905 return NSDecl->isStdNamespace();
9906 }
9907
9908 return false;
9909}
9910
9911void Sema::CheckInfNaNFunction(const CallExpr *Call,
9912 const FunctionDecl *FDecl) {
9913 if (!FDecl->getIdentifier())
9914 return;
9915
9916 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9917 if (FPO.getNoHonorNaNs() &&
9918 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9920 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9921 << 1 << 0 << Call->getSourceRange();
9922 return;
9923 }
9924
9925 if (FPO.getNoHonorInfs() &&
9926 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9927 IsInfinityFunction(FDecl) ||
9929 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9930 << 0 << 0 << Call->getSourceRange();
9931 }
9932}
9933
9934void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9935 const FunctionDecl *FDecl) {
9936 if (Call->getNumArgs() != 1)
9937 return;
9938
9939 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9940 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9941 if (AbsKind == 0 && !IsStdAbs)
9942 return;
9943
9944 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9945 QualType ParamType = Call->getArg(0)->getType();
9946
9947 // Unsigned types cannot be negative. Suggest removing the absolute value
9948 // function call.
9949 if (ArgType->isUnsignedIntegerType()) {
9950 std::string FunctionName =
9951 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9952 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9953 Diag(Call->getExprLoc(), diag::note_remove_abs)
9954 << FunctionName
9955 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9956 return;
9957 }
9958
9959 // Taking the absolute value of a pointer is very suspicious, they probably
9960 // wanted to index into an array, dereference a pointer, call a function, etc.
9961 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9962 unsigned DiagType = 0;
9963 if (ArgType->isFunctionType())
9964 DiagType = 1;
9965 else if (ArgType->isArrayType())
9966 DiagType = 2;
9967
9968 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9969 return;
9970 }
9971
9972 // std::abs has overloads which prevent most of the absolute value problems
9973 // from occurring.
9974 if (IsStdAbs)
9975 return;
9976
9977 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9978 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9979
9980 // The argument and parameter are the same kind. Check if they are the right
9981 // size.
9982 if (ArgValueKind == ParamValueKind) {
9983 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9984 return;
9985
9986 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9987 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9988 << FDecl << ArgType << ParamType;
9989
9990 if (NewAbsKind == 0)
9991 return;
9992
9993 emitReplacement(*this, Call->getExprLoc(),
9994 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9995 return;
9996 }
9997
9998 // ArgValueKind != ParamValueKind
9999 // The wrong type of absolute value function was used. Attempt to find the
10000 // proper one.
10001 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10002 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10003 if (NewAbsKind == 0)
10004 return;
10005
10006 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10007 << FDecl << ParamValueKind << ArgValueKind;
10008
10009 emitReplacement(*this, Call->getExprLoc(),
10010 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10011}
10012
10013//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10014void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10015 const FunctionDecl *FDecl) {
10016 if (!Call || !FDecl) return;
10017
10018 // Ignore template specializations and macros.
10019 if (inTemplateInstantiation()) return;
10020 if (Call->getExprLoc().isMacroID()) return;
10021
10022 // Only care about the one template argument, two function parameter std::max
10023 if (Call->getNumArgs() != 2) return;
10024 if (!IsStdFunction(FDecl, "max")) return;
10025 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10026 if (!ArgList) return;
10027 if (ArgList->size() != 1) return;
10028
10029 // Check that template type argument is unsigned integer.
10030 const auto& TA = ArgList->get(0);
10031 if (TA.getKind() != TemplateArgument::Type) return;
10032 QualType ArgType = TA.getAsType();
10033 if (!ArgType->isUnsignedIntegerType()) return;
10034
10035 // See if either argument is a literal zero.
10036 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10037 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10038 if (!MTE) return false;
10039 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10040 if (!Num) return false;
10041 if (Num->getValue() != 0) return false;
10042 return true;
10043 };
10044
10045 const Expr *FirstArg = Call->getArg(0);
10046 const Expr *SecondArg = Call->getArg(1);
10047 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10048 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10049
10050 // Only warn when exactly one argument is zero.
10051 if (IsFirstArgZero == IsSecondArgZero) return;
10052
10053 SourceRange FirstRange = FirstArg->getSourceRange();
10054 SourceRange SecondRange = SecondArg->getSourceRange();
10055
10056 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10057
10058 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10059 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10060
10061 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10062 SourceRange RemovalRange;
10063 if (IsFirstArgZero) {
10064 RemovalRange = SourceRange(FirstRange.getBegin(),
10065 SecondRange.getBegin().getLocWithOffset(-1));
10066 } else {
10067 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10068 SecondRange.getEnd());
10069 }
10070
10071 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10072 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10073 << FixItHint::CreateRemoval(RemovalRange);
10074}
10075
10076//===--- CHECK: Standard memory functions ---------------------------------===//
10077
10078/// Takes the expression passed to the size_t parameter of functions
10079/// such as memcmp, strncat, etc and warns if it's a comparison.
10080///
10081/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10083 const IdentifierInfo *FnName,
10084 SourceLocation FnLoc,
10085 SourceLocation RParenLoc) {
10086 const auto *Size = dyn_cast<BinaryOperator>(E);
10087 if (!Size)
10088 return false;
10089
10090 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10091 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10092 return false;
10093
10094 SourceRange SizeRange = Size->getSourceRange();
10095 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10096 << SizeRange << FnName;
10097 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10098 << FnName
10100 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10101 << FixItHint::CreateRemoval(RParenLoc);
10102 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10103 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10105 ")");
10106
10107 return true;
10108}
10109
10110/// Determine whether the given type is or contains a dynamic class type
10111/// (e.g., whether it has a vtable).
10113 bool &IsContained) {
10114 // Look through array types while ignoring qualifiers.
10115 const Type *Ty = T->getBaseElementTypeUnsafe();
10116 IsContained = false;
10117
10118 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10119 RD = RD ? RD->getDefinition() : nullptr;
10120 if (!RD || RD->isInvalidDecl())
10121 return nullptr;
10122
10123 if (RD->isDynamicClass())
10124 return RD;
10125
10126 // Check all the fields. If any bases were dynamic, the class is dynamic.
10127 // It's impossible for a class to transitively contain itself by value, so
10128 // infinite recursion is impossible.
10129 for (auto *FD : RD->fields()) {
10130 bool SubContained;
10131 if (const CXXRecordDecl *ContainedRD =
10132 getContainedDynamicClass(FD->getType(), SubContained)) {
10133 IsContained = true;
10134 return ContainedRD;
10135 }
10136 }
10137
10138 return nullptr;
10139}
10140
10142 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10143 if (Unary->getKind() == UETT_SizeOf)
10144 return Unary;
10145 return nullptr;
10146}
10147
10148/// If E is a sizeof expression, returns its argument expression,
10149/// otherwise returns NULL.
10150static const Expr *getSizeOfExprArg(const Expr *E) {
10152 if (!SizeOf->isArgumentType())
10153 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10154 return nullptr;
10155}
10156
10157/// If E is a sizeof expression, returns its argument type.
10160 return SizeOf->getTypeOfArgument();
10161 return QualType();
10162}
10163
10164namespace {
10165
10166struct SearchNonTrivialToInitializeField
10167 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10168 using Super =
10169 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10170
10171 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10172
10173 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10174 SourceLocation SL) {
10175 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10176 asDerived().visitArray(PDIK, AT, SL);
10177 return;
10178 }
10179
10180 Super::visitWithKind(PDIK, FT, SL);
10181 }
10182
10183 void visitARCStrong(QualType FT, SourceLocation SL) {
10184 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10185 }
10186 void visitARCWeak(QualType FT, SourceLocation SL) {
10187 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10188 }
10189 void visitStruct(QualType FT, SourceLocation SL) {
10190 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10191 visit(FD->getType(), FD->getLocation());
10192 }
10193 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10194 const ArrayType *AT, SourceLocation SL) {
10195 visit(getContext().getBaseElementType(AT), SL);
10196 }
10197 void visitTrivial(QualType FT, SourceLocation SL) {}
10198
10199 static void diag(QualType RT, const Expr *E, Sema &S) {
10200 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10201 }
10202
10203 ASTContext &getContext() { return S.getASTContext(); }
10204
10205 const Expr *E;
10206 Sema &S;
10207};
10208
10209struct SearchNonTrivialToCopyField
10210 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10211 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10212
10213 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10214
10215 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10216 SourceLocation SL) {
10217 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10218 asDerived().visitArray(PCK, AT, SL);
10219 return;
10220 }
10221
10222 Super::visitWithKind(PCK, FT, SL);
10223 }
10224
10225 void visitARCStrong(QualType FT, SourceLocation SL) {
10226 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10227 }
10228 void visitARCWeak(QualType FT, SourceLocation SL) {
10229 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10230 }
10231 void visitPtrAuth(QualType FT, SourceLocation SL) {
10232 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10233 }
10234 void visitStruct(QualType FT, SourceLocation SL) {
10235 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10236 visit(FD->getType(), FD->getLocation());
10237 }
10238 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10239 SourceLocation SL) {
10240 visit(getContext().getBaseElementType(AT), SL);
10241 }
10242 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10243 SourceLocation SL) {}
10244 void visitTrivial(QualType FT, SourceLocation SL) {}
10245 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10246
10247 static void diag(QualType RT, const Expr *E, Sema &S) {
10248 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10249 }
10250
10251 ASTContext &getContext() { return S.getASTContext(); }
10252
10253 const Expr *E;
10254 Sema &S;
10255};
10256
10257}
10258
10259/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10260static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10261 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10262
10263 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10264 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10265 return false;
10266
10267 return doesExprLikelyComputeSize(BO->getLHS()) ||
10268 doesExprLikelyComputeSize(BO->getRHS());
10269 }
10270
10271 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10272}
10273
10274/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10275///
10276/// \code
10277/// #define MACRO 0
10278/// foo(MACRO);
10279/// foo(0);
10280/// \endcode
10281///
10282/// This should return true for the first call to foo, but not for the second
10283/// (regardless of whether foo is a macro or function).
10285 SourceLocation CallLoc,
10286 SourceLocation ArgLoc) {
10287 if (!CallLoc.isMacroID())
10288 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10289
10290 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10291 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10292}
10293
10294/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10295/// last two arguments transposed.
10296static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10297 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10298 return;
10299
10300 const Expr *SizeArg =
10301 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10302
10303 auto isLiteralZero = [](const Expr *E) {
10304 return (isa<IntegerLiteral>(E) &&
10305 cast<IntegerLiteral>(E)->getValue() == 0) ||
10307 cast<CharacterLiteral>(E)->getValue() == 0);
10308 };
10309
10310 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10311 SourceLocation CallLoc = Call->getRParenLoc();
10313 if (isLiteralZero(SizeArg) &&
10314 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10315
10316 SourceLocation DiagLoc = SizeArg->getExprLoc();
10317
10318 // Some platforms #define bzero to __builtin_memset. See if this is the
10319 // case, and if so, emit a better diagnostic.
10320 if (BId == Builtin::BIbzero ||
10322 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10323 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10324 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10325 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10326 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10327 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10328 }
10329 return;
10330 }
10331
10332 // If the second argument to a memset is a sizeof expression and the third
10333 // isn't, this is also likely an error. This should catch
10334 // 'memset(buf, sizeof(buf), 0xff)'.
10335 if (BId == Builtin::BImemset &&
10336 doesExprLikelyComputeSize(Call->getArg(1)) &&
10337 !doesExprLikelyComputeSize(Call->getArg(2))) {
10338 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10339 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10340 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10341 return;
10342 }
10343}
10344
10345void Sema::CheckMemaccessArguments(const CallExpr *Call,
10346 unsigned BId,
10347 IdentifierInfo *FnName) {
10348 assert(BId != 0);
10349
10350 // It is possible to have a non-standard definition of memset. Validate
10351 // we have enough arguments, and if not, abort further checking.
10352 unsigned ExpectedNumArgs =
10353 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10354 if (Call->getNumArgs() < ExpectedNumArgs)
10355 return;
10356
10357 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10358 BId == Builtin::BIstrndup ? 1 : 2);
10359 unsigned LenArg =
10360 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10361 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10362
10363 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10364 Call->getBeginLoc(), Call->getRParenLoc()))
10365 return;
10366
10367 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10368 CheckMemaccessSize(*this, BId, Call);
10369
10370 // We have special checking when the length is a sizeof expression.
10371 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10372 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10373 llvm::FoldingSetNodeID SizeOfArgID;
10374
10375 // Although widely used, 'bzero' is not a standard function. Be more strict
10376 // with the argument types before allowing diagnostics and only allow the
10377 // form bzero(ptr, sizeof(...)).
10378 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10379 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10380 return;
10381
10382 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10383 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10384 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10385
10386 QualType DestTy = Dest->getType();
10387 QualType PointeeTy;
10388 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10389 PointeeTy = DestPtrTy->getPointeeType();
10390
10391 // Never warn about void type pointers. This can be used to suppress
10392 // false positives.
10393 if (PointeeTy->isVoidType())
10394 continue;
10395
10396 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10397 // actually comparing the expressions for equality. Because computing the
10398 // expression IDs can be expensive, we only do this if the diagnostic is
10399 // enabled.
10400 if (SizeOfArg &&
10401 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10402 SizeOfArg->getExprLoc())) {
10403 // We only compute IDs for expressions if the warning is enabled, and
10404 // cache the sizeof arg's ID.
10405 if (SizeOfArgID == llvm::FoldingSetNodeID())
10406 SizeOfArg->Profile(SizeOfArgID, Context, true);
10407 llvm::FoldingSetNodeID DestID;
10408 Dest->Profile(DestID, Context, true);
10409 if (DestID == SizeOfArgID) {
10410 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10411 // over sizeof(src) as well.
10412 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10413 StringRef ReadableName = FnName->getName();
10414
10415 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10416 if (UnaryOp->getOpcode() == UO_AddrOf)
10417 ActionIdx = 1; // If its an address-of operator, just remove it.
10418 if (!PointeeTy->isIncompleteType() &&
10419 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10420 ActionIdx = 2; // If the pointee's size is sizeof(char),
10421 // suggest an explicit length.
10422
10423 // If the function is defined as a builtin macro, do not show macro
10424 // expansion.
10425 SourceLocation SL = SizeOfArg->getExprLoc();
10426 SourceRange DSR = Dest->getSourceRange();
10427 SourceRange SSR = SizeOfArg->getSourceRange();
10428 SourceManager &SM = getSourceManager();
10429
10430 if (SM.isMacroArgExpansion(SL)) {
10431 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10432 SL = SM.getSpellingLoc(SL);
10433 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10434 SM.getSpellingLoc(DSR.getEnd()));
10435 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10436 SM.getSpellingLoc(SSR.getEnd()));
10437 }
10438
10439 DiagRuntimeBehavior(SL, SizeOfArg,
10440 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10441 << ReadableName
10442 << PointeeTy
10443 << DestTy
10444 << DSR
10445 << SSR);
10446 DiagRuntimeBehavior(SL, SizeOfArg,
10447 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10448 << ActionIdx
10449 << SSR);
10450
10451 break;
10452 }
10453 }
10454
10455 // Also check for cases where the sizeof argument is the exact same
10456 // type as the memory argument, and where it points to a user-defined
10457 // record type.
10458 if (SizeOfArgTy != QualType()) {
10459 if (PointeeTy->isRecordType() &&
10460 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10461 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10462 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10463 << FnName << SizeOfArgTy << ArgIdx
10464 << PointeeTy << Dest->getSourceRange()
10465 << LenExpr->getSourceRange());
10466 break;
10467 }
10468 }
10469 } else if (DestTy->isArrayType()) {
10470 PointeeTy = DestTy;
10471 }
10472
10473 if (PointeeTy == QualType())
10474 continue;
10475
10476 // Always complain about dynamic classes.
10477 bool IsContained;
10478 if (const CXXRecordDecl *ContainedRD =
10479 getContainedDynamicClass(PointeeTy, IsContained)) {
10480
10481 unsigned OperationType = 0;
10482 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10483 // "overwritten" if we're warning about the destination for any call
10484 // but memcmp; otherwise a verb appropriate to the call.
10485 if (ArgIdx != 0 || IsCmp) {
10486 if (BId == Builtin::BImemcpy)
10487 OperationType = 1;
10488 else if(BId == Builtin::BImemmove)
10489 OperationType = 2;
10490 else if (IsCmp)
10491 OperationType = 3;
10492 }
10493
10494 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10495 PDiag(diag::warn_dyn_class_memaccess)
10496 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10497 << IsContained << ContainedRD << OperationType
10498 << Call->getCallee()->getSourceRange());
10499 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10500 BId != Builtin::BImemset)
10502 Dest->getExprLoc(), Dest,
10503 PDiag(diag::warn_arc_object_memaccess)
10504 << ArgIdx << FnName << PointeeTy
10505 << Call->getCallee()->getSourceRange());
10506 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10507
10508 // FIXME: Do not consider incomplete types even though they may be
10509 // completed later. GCC does not diagnose such code, but we may want to
10510 // consider diagnosing it in the future, perhaps under a different, but
10511 // related, diagnostic group.
10512 bool NonTriviallyCopyableCXXRecord =
10513 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10514 !PointeeTy.isTriviallyCopyableType(Context);
10515
10516 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10518 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10519 PDiag(diag::warn_cstruct_memaccess)
10520 << ArgIdx << FnName << PointeeTy << 0);
10521 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10522 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10523 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10524 // FIXME: Limiting this warning to dest argument until we decide
10525 // whether it's valid for source argument too.
10526 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10527 PDiag(diag::warn_cxxstruct_memaccess)
10528 << FnName << PointeeTy);
10529 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10531 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10532 PDiag(diag::warn_cstruct_memaccess)
10533 << ArgIdx << FnName << PointeeTy << 1);
10534 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10535 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10536 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10537 // FIXME: Limiting this warning to dest argument until we decide
10538 // whether it's valid for source argument too.
10539 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10540 PDiag(diag::warn_cxxstruct_memaccess)
10541 << FnName << PointeeTy);
10542 } else {
10543 continue;
10544 }
10545 } else
10546 continue;
10547
10549 Dest->getExprLoc(), Dest,
10550 PDiag(diag::note_bad_memaccess_silence)
10551 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10552 break;
10553 }
10554}
10555
10556// A little helper routine: ignore addition and subtraction of integer literals.
10557// This intentionally does not ignore all integer constant expressions because
10558// we don't want to remove sizeof().
10559static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10560 Ex = Ex->IgnoreParenCasts();
10561
10562 while (true) {
10563 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10564 if (!BO || !BO->isAdditiveOp())
10565 break;
10566
10567 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10568 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10569
10570 if (isa<IntegerLiteral>(RHS))
10571 Ex = LHS;
10572 else if (isa<IntegerLiteral>(LHS))
10573 Ex = RHS;
10574 else
10575 break;
10576 }
10577
10578 return Ex;
10579}
10580
10582 ASTContext &Context) {
10583 // Only handle constant-sized or VLAs, but not flexible members.
10584 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10585 // Only issue the FIXIT for arrays of size > 1.
10586 if (CAT->getZExtSize() <= 1)
10587 return false;
10588 } else if (!Ty->isVariableArrayType()) {
10589 return false;
10590 }
10591 return true;
10592}
10593
10594void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10595 IdentifierInfo *FnName) {
10596
10597 // Don't crash if the user has the wrong number of arguments
10598 unsigned NumArgs = Call->getNumArgs();
10599 if ((NumArgs != 3) && (NumArgs != 4))
10600 return;
10601
10602 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10603 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10604 const Expr *CompareWithSrc = nullptr;
10605
10606 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10607 Call->getBeginLoc(), Call->getRParenLoc()))
10608 return;
10609
10610 // Look for 'strlcpy(dst, x, sizeof(x))'
10611 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10612 CompareWithSrc = Ex;
10613 else {
10614 // Look for 'strlcpy(dst, x, strlen(x))'
10615 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10616 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10617 SizeCall->getNumArgs() == 1)
10618 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10619 }
10620 }
10621
10622 if (!CompareWithSrc)
10623 return;
10624
10625 // Determine if the argument to sizeof/strlen is equal to the source
10626 // argument. In principle there's all kinds of things you could do
10627 // here, for instance creating an == expression and evaluating it with
10628 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10629 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10630 if (!SrcArgDRE)
10631 return;
10632
10633 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10634 if (!CompareWithSrcDRE ||
10635 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10636 return;
10637
10638 const Expr *OriginalSizeArg = Call->getArg(2);
10639 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10640 << OriginalSizeArg->getSourceRange() << FnName;
10641
10642 // Output a FIXIT hint if the destination is an array (rather than a
10643 // pointer to an array). This could be enhanced to handle some
10644 // pointers if we know the actual size, like if DstArg is 'array+2'
10645 // we could say 'sizeof(array)-2'.
10646 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10648 return;
10649
10650 SmallString<128> sizeString;
10651 llvm::raw_svector_ostream OS(sizeString);
10652 OS << "sizeof(";
10653 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10654 OS << ")";
10655
10656 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10657 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10658 OS.str());
10659}
10660
10661/// Check if two expressions refer to the same declaration.
10662static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10663 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10664 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10665 return D1->getDecl() == D2->getDecl();
10666 return false;
10667}
10668
10669static const Expr *getStrlenExprArg(const Expr *E) {
10670 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10671 const FunctionDecl *FD = CE->getDirectCallee();
10672 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10673 return nullptr;
10674 return CE->getArg(0)->IgnoreParenCasts();
10675 }
10676 return nullptr;
10677}
10678
10679void Sema::CheckStrncatArguments(const CallExpr *CE,
10680 const IdentifierInfo *FnName) {
10681 // Don't crash if the user has the wrong number of arguments.
10682 if (CE->getNumArgs() < 3)
10683 return;
10684 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10685 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10686 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10687
10688 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10689 CE->getRParenLoc()))
10690 return;
10691
10692 // Identify common expressions, which are wrongly used as the size argument
10693 // to strncat and may lead to buffer overflows.
10694 unsigned PatternType = 0;
10695 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10696 // - sizeof(dst)
10697 if (referToTheSameDecl(SizeOfArg, DstArg))
10698 PatternType = 1;
10699 // - sizeof(src)
10700 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10701 PatternType = 2;
10702 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10703 if (BE->getOpcode() == BO_Sub) {
10704 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10705 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10706 // - sizeof(dst) - strlen(dst)
10707 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10709 PatternType = 1;
10710 // - sizeof(src) - (anything)
10711 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10712 PatternType = 2;
10713 }
10714 }
10715
10716 if (PatternType == 0)
10717 return;
10718
10719 // Generate the diagnostic.
10720 SourceLocation SL = LenArg->getBeginLoc();
10721 SourceRange SR = LenArg->getSourceRange();
10722 SourceManager &SM = getSourceManager();
10723
10724 // If the function is defined as a builtin macro, do not show macro expansion.
10725 if (SM.isMacroArgExpansion(SL)) {
10726 SL = SM.getSpellingLoc(SL);
10727 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10728 SM.getSpellingLoc(SR.getEnd()));
10729 }
10730
10731 // Check if the destination is an array (rather than a pointer to an array).
10732 QualType DstTy = DstArg->getType();
10733 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10734 Context);
10735 if (!isKnownSizeArray) {
10736 if (PatternType == 1)
10737 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10738 else
10739 Diag(SL, diag::warn_strncat_src_size) << SR;
10740 return;
10741 }
10742
10743 if (PatternType == 1)
10744 Diag(SL, diag::warn_strncat_large_size) << SR;
10745 else
10746 Diag(SL, diag::warn_strncat_src_size) << SR;
10747
10748 SmallString<128> sizeString;
10749 llvm::raw_svector_ostream OS(sizeString);
10750 OS << "sizeof(";
10751 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10752 OS << ") - ";
10753 OS << "strlen(";
10754 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10755 OS << ") - 1";
10756
10757 Diag(SL, diag::note_strncat_wrong_size)
10758 << FixItHint::CreateReplacement(SR, OS.str());
10759}
10760
10761namespace {
10762void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10763 const UnaryOperator *UnaryExpr, const Decl *D) {
10765 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10766 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10767 return;
10768 }
10769}
10770
10771void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10772 const UnaryOperator *UnaryExpr) {
10773 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10774 const Decl *D = Lvalue->getDecl();
10775 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10776 if (!DD->getType()->isReferenceType())
10777 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10778 }
10779 }
10780
10781 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10782 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10783 Lvalue->getMemberDecl());
10784}
10785
10786void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10787 const UnaryOperator *UnaryExpr) {
10788 const auto *Lambda = dyn_cast<LambdaExpr>(
10790 if (!Lambda)
10791 return;
10792
10793 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10794 << CalleeName << 2 /*object: lambda expression*/;
10795}
10796
10797void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10798 const DeclRefExpr *Lvalue) {
10799 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10800 if (Var == nullptr)
10801 return;
10802
10803 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10804 << CalleeName << 0 /*object: */ << Var;
10805}
10806
10807void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10808 const CastExpr *Cast) {
10809 SmallString<128> SizeString;
10810 llvm::raw_svector_ostream OS(SizeString);
10811
10812 clang::CastKind Kind = Cast->getCastKind();
10813 if (Kind == clang::CK_BitCast &&
10814 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10815 return;
10816 if (Kind == clang::CK_IntegralToPointer &&
10818 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10819 return;
10820
10821 switch (Cast->getCastKind()) {
10822 case clang::CK_BitCast:
10823 case clang::CK_IntegralToPointer:
10824 case clang::CK_FunctionToPointerDecay:
10825 OS << '\'';
10826 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10827 OS << '\'';
10828 break;
10829 default:
10830 return;
10831 }
10832
10833 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10834 << CalleeName << 0 /*object: */ << OS.str();
10835}
10836} // namespace
10837
10838void Sema::CheckFreeArguments(const CallExpr *E) {
10839 const std::string CalleeName =
10840 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10841
10842 { // Prefer something that doesn't involve a cast to make things simpler.
10843 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10844 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10845 switch (UnaryExpr->getOpcode()) {
10846 case UnaryOperator::Opcode::UO_AddrOf:
10847 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10848 case UnaryOperator::Opcode::UO_Plus:
10849 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10850 default:
10851 break;
10852 }
10853
10854 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10855 if (Lvalue->getType()->isArrayType())
10856 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10857
10858 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10859 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10860 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10861 return;
10862 }
10863
10864 if (isa<BlockExpr>(Arg)) {
10865 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10866 << CalleeName << 1 /*object: block*/;
10867 return;
10868 }
10869 }
10870 // Maybe the cast was important, check after the other cases.
10871 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10872 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10873}
10874
10875void
10876Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10877 SourceLocation ReturnLoc,
10878 bool isObjCMethod,
10879 const AttrVec *Attrs,
10880 const FunctionDecl *FD) {
10881 // Check if the return value is null but should not be.
10882 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10883 (!isObjCMethod && isNonNullType(lhsType))) &&
10884 CheckNonNullExpr(*this, RetValExp))
10885 Diag(ReturnLoc, diag::warn_null_ret)
10886 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10887
10888 // C++11 [basic.stc.dynamic.allocation]p4:
10889 // If an allocation function declared with a non-throwing
10890 // exception-specification fails to allocate storage, it shall return
10891 // a null pointer. Any other allocation function that fails to allocate
10892 // storage shall indicate failure only by throwing an exception [...]
10893 if (FD) {
10895 if (Op == OO_New || Op == OO_Array_New) {
10896 const FunctionProtoType *Proto
10897 = FD->getType()->castAs<FunctionProtoType>();
10898 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10899 CheckNonNullExpr(*this, RetValExp))
10900 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10901 << FD << getLangOpts().CPlusPlus11;
10902 }
10903 }
10904
10905 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10906 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10907 }
10908
10909 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10910 // here prevent the user from using a PPC MMA type as trailing return type.
10911 if (Context.getTargetInfo().getTriple().isPPC64())
10912 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10913}
10914
10916 const Expr *RHS, BinaryOperatorKind Opcode) {
10917 if (!BinaryOperator::isEqualityOp(Opcode))
10918 return;
10919
10920 // Match and capture subexpressions such as "(float) X == 0.1".
10921 const FloatingLiteral *FPLiteral;
10922 const CastExpr *FPCast;
10923 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10924 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10925 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10926 return FPLiteral && FPCast;
10927 };
10928
10929 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10930 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10931 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10932 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10933 TargetTy->isFloatingPoint()) {
10934 bool Lossy;
10935 llvm::APFloat TargetC = FPLiteral->getValue();
10936 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10937 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10938 if (Lossy) {
10939 // If the literal cannot be represented in the source type, then a
10940 // check for == is always false and check for != is always true.
10941 Diag(Loc, diag::warn_float_compare_literal)
10942 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10943 << LHS->getSourceRange() << RHS->getSourceRange();
10944 return;
10945 }
10946 }
10947 }
10948
10949 // Match a more general floating-point equality comparison (-Wfloat-equal).
10950 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10951 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10952
10953 // Special case: check for x == x (which is OK).
10954 // Do not emit warnings for such cases.
10955 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10956 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10957 if (DRL->getDecl() == DRR->getDecl())
10958 return;
10959
10960 // Special case: check for comparisons against literals that can be exactly
10961 // represented by APFloat. In such cases, do not emit a warning. This
10962 // is a heuristic: often comparison against such literals are used to
10963 // detect if a value in a variable has not changed. This clearly can
10964 // lead to false negatives.
10965 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10966 if (FLL->isExact())
10967 return;
10968 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10969 if (FLR->isExact())
10970 return;
10971
10972 // Check for comparisons with builtin types.
10973 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10974 CL && CL->getBuiltinCallee())
10975 return;
10976
10977 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10978 CR && CR->getBuiltinCallee())
10979 return;
10980
10981 // Emit the diagnostic.
10982 Diag(Loc, diag::warn_floatingpoint_eq)
10983 << LHS->getSourceRange() << RHS->getSourceRange();
10984}
10985
10986//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10987//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10988
10989namespace {
10990
10991/// Structure recording the 'active' range of an integer-valued
10992/// expression.
10993struct IntRange {
10994 /// The number of bits active in the int. Note that this includes exactly one
10995 /// sign bit if !NonNegative.
10996 unsigned Width;
10997
10998 /// True if the int is known not to have negative values. If so, all leading
10999 /// bits before Width are known zero, otherwise they are known to be the
11000 /// same as the MSB within Width.
11001 bool NonNegative;
11002
11003 IntRange(unsigned Width, bool NonNegative)
11004 : Width(Width), NonNegative(NonNegative) {}
11005
11006 /// Number of bits excluding the sign bit.
11007 unsigned valueBits() const {
11008 return NonNegative ? Width : Width - 1;
11009 }
11010
11011 /// Returns the range of the bool type.
11012 static IntRange forBoolType() {
11013 return IntRange(1, true);
11014 }
11015
11016 /// Returns the range of an opaque value of the given integral type.
11017 static IntRange forValueOfType(ASTContext &C, QualType T) {
11018 return forValueOfCanonicalType(C,
11020 }
11021
11022 /// Returns the range of an opaque value of a canonical integral type.
11023 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11024 assert(T->isCanonicalUnqualified());
11025
11026 if (const auto *VT = dyn_cast<VectorType>(T))
11027 T = VT->getElementType().getTypePtr();
11028 if (const auto *CT = dyn_cast<ComplexType>(T))
11029 T = CT->getElementType().getTypePtr();
11030 if (const auto *AT = dyn_cast<AtomicType>(T))
11031 T = AT->getValueType().getTypePtr();
11032
11033 if (!C.getLangOpts().CPlusPlus) {
11034 // For enum types in C code, use the underlying datatype.
11035 if (const auto *ED = T->getAsEnumDecl())
11036 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11037 } else if (auto *Enum = T->getAsEnumDecl()) {
11038 // For enum types in C++, use the known bit width of the enumerators.
11039 // In C++11, enums can have a fixed underlying type. Use this type to
11040 // compute the range.
11041 if (Enum->isFixed()) {
11042 return IntRange(C.getIntWidth(QualType(T, 0)),
11043 !Enum->getIntegerType()->isSignedIntegerType());
11044 }
11045
11046 unsigned NumPositive = Enum->getNumPositiveBits();
11047 unsigned NumNegative = Enum->getNumNegativeBits();
11048
11049 if (NumNegative == 0)
11050 return IntRange(NumPositive, true/*NonNegative*/);
11051 else
11052 return IntRange(std::max(NumPositive + 1, NumNegative),
11053 false/*NonNegative*/);
11054 }
11055
11056 if (const auto *EIT = dyn_cast<BitIntType>(T))
11057 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11058
11059 const BuiltinType *BT = cast<BuiltinType>(T);
11060 assert(BT->isInteger());
11061
11062 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11063 }
11064
11065 /// Returns the "target" range of a canonical integral type, i.e.
11066 /// the range of values expressible in the type.
11067 ///
11068 /// This matches forValueOfCanonicalType except that enums have the
11069 /// full range of their type, not the range of their enumerators.
11070 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11071 assert(T->isCanonicalUnqualified());
11072
11073 if (const VectorType *VT = dyn_cast<VectorType>(T))
11074 T = VT->getElementType().getTypePtr();
11075 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11076 T = CT->getElementType().getTypePtr();
11077 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11078 T = AT->getValueType().getTypePtr();
11079 if (const auto *ED = T->getAsEnumDecl())
11080 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11081
11082 if (const auto *EIT = dyn_cast<BitIntType>(T))
11083 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11084
11085 const BuiltinType *BT = cast<BuiltinType>(T);
11086 assert(BT->isInteger());
11087
11088 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11089 }
11090
11091 /// Returns the supremum of two ranges: i.e. their conservative merge.
11092 static IntRange join(IntRange L, IntRange R) {
11093 bool Unsigned = L.NonNegative && R.NonNegative;
11094 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11095 L.NonNegative && R.NonNegative);
11096 }
11097
11098 /// Return the range of a bitwise-AND of the two ranges.
11099 static IntRange bit_and(IntRange L, IntRange R) {
11100 unsigned Bits = std::max(L.Width, R.Width);
11101 bool NonNegative = false;
11102 if (L.NonNegative) {
11103 Bits = std::min(Bits, L.Width);
11104 NonNegative = true;
11105 }
11106 if (R.NonNegative) {
11107 Bits = std::min(Bits, R.Width);
11108 NonNegative = true;
11109 }
11110 return IntRange(Bits, NonNegative);
11111 }
11112
11113 /// Return the range of a sum of the two ranges.
11114 static IntRange sum(IntRange L, IntRange R) {
11115 bool Unsigned = L.NonNegative && R.NonNegative;
11116 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11117 Unsigned);
11118 }
11119
11120 /// Return the range of a difference of the two ranges.
11121 static IntRange difference(IntRange L, IntRange R) {
11122 // We need a 1-bit-wider range if:
11123 // 1) LHS can be negative: least value can be reduced.
11124 // 2) RHS can be negative: greatest value can be increased.
11125 bool CanWiden = !L.NonNegative || !R.NonNegative;
11126 bool Unsigned = L.NonNegative && R.Width == 0;
11127 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11128 !Unsigned,
11129 Unsigned);
11130 }
11131
11132 /// Return the range of a product of the two ranges.
11133 static IntRange product(IntRange L, IntRange R) {
11134 // If both LHS and RHS can be negative, we can form
11135 // -2^L * -2^R = 2^(L + R)
11136 // which requires L + R + 1 value bits to represent.
11137 bool CanWiden = !L.NonNegative && !R.NonNegative;
11138 bool Unsigned = L.NonNegative && R.NonNegative;
11139 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11140 Unsigned);
11141 }
11142
11143 /// Return the range of a remainder operation between the two ranges.
11144 static IntRange rem(IntRange L, IntRange R) {
11145 // The result of a remainder can't be larger than the result of
11146 // either side. The sign of the result is the sign of the LHS.
11147 bool Unsigned = L.NonNegative;
11148 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11149 Unsigned);
11150 }
11151};
11152
11153} // namespace
11154
11155static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11156 if (value.isSigned() && value.isNegative())
11157 return IntRange(value.getSignificantBits(), false);
11158
11159 if (value.getBitWidth() > MaxWidth)
11160 value = value.trunc(MaxWidth);
11161
11162 // isNonNegative() just checks the sign bit without considering
11163 // signedness.
11164 return IntRange(value.getActiveBits(), true);
11165}
11166
11167static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11168 if (result.isInt())
11169 return GetValueRange(result.getInt(), MaxWidth);
11170
11171 if (result.isVector()) {
11172 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11173 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11174 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11175 R = IntRange::join(R, El);
11176 }
11177 return R;
11178 }
11179
11180 if (result.isComplexInt()) {
11181 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11182 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11183 return IntRange::join(R, I);
11184 }
11185
11186 // This can happen with lossless casts to intptr_t of "based" lvalues.
11187 // Assume it might use arbitrary bits.
11188 // FIXME: The only reason we need to pass the type in here is to get
11189 // the sign right on this one case. It would be nice if APValue
11190 // preserved this.
11191 assert(result.isLValue() || result.isAddrLabelDiff());
11192 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11193}
11194
11195static QualType GetExprType(const Expr *E) {
11196 QualType Ty = E->getType();
11197 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11198 Ty = AtomicRHS->getValueType();
11199 return Ty;
11200}
11201
11202/// Attempts to estimate an approximate range for the given integer expression.
11203/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11204/// reliable estimation cannot be determined.
11205///
11206/// \param MaxWidth The width to which the value will be truncated.
11207/// \param InConstantContext If \c true, interpret the expression within a
11208/// constant context.
11209/// \param Approximate If \c true, provide a likely range of values by assuming
11210/// that arithmetic on narrower types remains within those types.
11211/// If \c false, return a range that includes all possible values
11212/// resulting from the expression.
11213/// \returns A range of values that the expression might take, or
11214/// std::nullopt if a reliable estimation cannot be determined.
11215static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11216 unsigned MaxWidth,
11217 bool InConstantContext,
11218 bool Approximate) {
11219 E = E->IgnoreParens();
11220
11221 // Try a full evaluation first.
11222 Expr::EvalResult result;
11223 if (E->EvaluateAsRValue(result, C, InConstantContext))
11224 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11225
11226 // I think we only want to look through implicit casts here; if the
11227 // user has an explicit widening cast, we should treat the value as
11228 // being of the new, wider type.
11229 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11230 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11231 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11232 Approximate);
11233
11234 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11235
11236 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11237 CE->getCastKind() == CK_BooleanToSignedIntegral;
11238
11239 // Assume that non-integer casts can span the full range of the type.
11240 if (!isIntegerCast)
11241 return OutputTypeRange;
11242
11243 std::optional<IntRange> SubRange = TryGetExprRange(
11244 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11245 InConstantContext, Approximate);
11246 if (!SubRange)
11247 return std::nullopt;
11248
11249 // Bail out if the subexpr's range is as wide as the cast type.
11250 if (SubRange->Width >= OutputTypeRange.Width)
11251 return OutputTypeRange;
11252
11253 // Otherwise, we take the smaller width, and we're non-negative if
11254 // either the output type or the subexpr is.
11255 return IntRange(SubRange->Width,
11256 SubRange->NonNegative || OutputTypeRange.NonNegative);
11257 }
11258
11259 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11260 // If we can fold the condition, just take that operand.
11261 bool CondResult;
11262 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11263 return TryGetExprRange(
11264 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11265 InConstantContext, Approximate);
11266
11267 // Otherwise, conservatively merge.
11268 // TryGetExprRange requires an integer expression, but a throw expression
11269 // results in a void type.
11270 Expr *TrueExpr = CO->getTrueExpr();
11271 if (TrueExpr->getType()->isVoidType())
11272 return std::nullopt;
11273
11274 std::optional<IntRange> L =
11275 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11276 if (!L)
11277 return std::nullopt;
11278
11279 Expr *FalseExpr = CO->getFalseExpr();
11280 if (FalseExpr->getType()->isVoidType())
11281 return std::nullopt;
11282
11283 std::optional<IntRange> R =
11284 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11285 if (!R)
11286 return std::nullopt;
11287
11288 return IntRange::join(*L, *R);
11289 }
11290
11291 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11292 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11293
11294 switch (BO->getOpcode()) {
11295 case BO_Cmp:
11296 llvm_unreachable("builtin <=> should have class type");
11297
11298 // Boolean-valued operations are single-bit and positive.
11299 case BO_LAnd:
11300 case BO_LOr:
11301 case BO_LT:
11302 case BO_GT:
11303 case BO_LE:
11304 case BO_GE:
11305 case BO_EQ:
11306 case BO_NE:
11307 return IntRange::forBoolType();
11308
11309 // The type of the assignments is the type of the LHS, so the RHS
11310 // is not necessarily the same type.
11311 case BO_MulAssign:
11312 case BO_DivAssign:
11313 case BO_RemAssign:
11314 case BO_AddAssign:
11315 case BO_SubAssign:
11316 case BO_XorAssign:
11317 case BO_OrAssign:
11318 // TODO: bitfields?
11319 return IntRange::forValueOfType(C, GetExprType(E));
11320
11321 // Simple assignments just pass through the RHS, which will have
11322 // been coerced to the LHS type.
11323 case BO_Assign:
11324 // TODO: bitfields?
11325 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11326 Approximate);
11327
11328 // Operations with opaque sources are black-listed.
11329 case BO_PtrMemD:
11330 case BO_PtrMemI:
11331 return IntRange::forValueOfType(C, GetExprType(E));
11332
11333 // Bitwise-and uses the *infinum* of the two source ranges.
11334 case BO_And:
11335 case BO_AndAssign:
11336 Combine = IntRange::bit_and;
11337 break;
11338
11339 // Left shift gets black-listed based on a judgement call.
11340 case BO_Shl:
11341 // ...except that we want to treat '1 << (blah)' as logically
11342 // positive. It's an important idiom.
11343 if (IntegerLiteral *I
11344 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11345 if (I->getValue() == 1) {
11346 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11347 return IntRange(R.Width, /*NonNegative*/ true);
11348 }
11349 }
11350 [[fallthrough]];
11351
11352 case BO_ShlAssign:
11353 return IntRange::forValueOfType(C, GetExprType(E));
11354
11355 // Right shift by a constant can narrow its left argument.
11356 case BO_Shr:
11357 case BO_ShrAssign: {
11358 std::optional<IntRange> L = TryGetExprRange(
11359 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11360 if (!L)
11361 return std::nullopt;
11362
11363 // If the shift amount is a positive constant, drop the width by
11364 // that much.
11365 if (std::optional<llvm::APSInt> shift =
11366 BO->getRHS()->getIntegerConstantExpr(C)) {
11367 if (shift->isNonNegative()) {
11368 if (shift->uge(L->Width))
11369 L->Width = (L->NonNegative ? 0 : 1);
11370 else
11371 L->Width -= shift->getZExtValue();
11372 }
11373 }
11374
11375 return L;
11376 }
11377
11378 // Comma acts as its right operand.
11379 case BO_Comma:
11380 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11381 Approximate);
11382
11383 case BO_Add:
11384 if (!Approximate)
11385 Combine = IntRange::sum;
11386 break;
11387
11388 case BO_Sub:
11389 if (BO->getLHS()->getType()->isPointerType())
11390 return IntRange::forValueOfType(C, GetExprType(E));
11391 if (!Approximate)
11392 Combine = IntRange::difference;
11393 break;
11394
11395 case BO_Mul:
11396 if (!Approximate)
11397 Combine = IntRange::product;
11398 break;
11399
11400 // The width of a division result is mostly determined by the size
11401 // of the LHS.
11402 case BO_Div: {
11403 // Don't 'pre-truncate' the operands.
11404 unsigned opWidth = C.getIntWidth(GetExprType(E));
11405 std::optional<IntRange> L = TryGetExprRange(
11406 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11407 if (!L)
11408 return std::nullopt;
11409
11410 // If the divisor is constant, use that.
11411 if (std::optional<llvm::APSInt> divisor =
11412 BO->getRHS()->getIntegerConstantExpr(C)) {
11413 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11414 if (log2 >= L->Width)
11415 L->Width = (L->NonNegative ? 0 : 1);
11416 else
11417 L->Width = std::min(L->Width - log2, MaxWidth);
11418 return L;
11419 }
11420
11421 // Otherwise, just use the LHS's width.
11422 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11423 // could be -1.
11424 std::optional<IntRange> R = TryGetExprRange(
11425 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11426 if (!R)
11427 return std::nullopt;
11428
11429 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11430 }
11431
11432 case BO_Rem:
11433 Combine = IntRange::rem;
11434 break;
11435
11436 // The default behavior is okay for these.
11437 case BO_Xor:
11438 case BO_Or:
11439 break;
11440 }
11441
11442 // Combine the two ranges, but limit the result to the type in which we
11443 // performed the computation.
11444 QualType T = GetExprType(E);
11445 unsigned opWidth = C.getIntWidth(T);
11446 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11447 InConstantContext, Approximate);
11448 if (!L)
11449 return std::nullopt;
11450
11451 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11452 InConstantContext, Approximate);
11453 if (!R)
11454 return std::nullopt;
11455
11456 IntRange C = Combine(*L, *R);
11457 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11458 C.Width = std::min(C.Width, MaxWidth);
11459 return C;
11460 }
11461
11462 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11463 switch (UO->getOpcode()) {
11464 // Boolean-valued operations are white-listed.
11465 case UO_LNot:
11466 return IntRange::forBoolType();
11467
11468 // Operations with opaque sources are black-listed.
11469 case UO_Deref:
11470 case UO_AddrOf: // should be impossible
11471 return IntRange::forValueOfType(C, GetExprType(E));
11472
11473 case UO_Minus: {
11474 if (E->getType()->isUnsignedIntegerType()) {
11475 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11476 Approximate);
11477 }
11478
11479 std::optional<IntRange> SubRange = TryGetExprRange(
11480 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11481
11482 if (!SubRange)
11483 return std::nullopt;
11484
11485 // If the range was previously non-negative, we need an extra bit for the
11486 // sign bit. Otherwise, we need an extra bit because the negation of the
11487 // most-negative value is one bit wider than that value.
11488 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11489 }
11490
11491 case UO_Not: {
11492 if (E->getType()->isUnsignedIntegerType()) {
11493 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11494 Approximate);
11495 }
11496
11497 std::optional<IntRange> SubRange = TryGetExprRange(
11498 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11499
11500 if (!SubRange)
11501 return std::nullopt;
11502
11503 // The width increments by 1 if the sub-expression cannot be negative
11504 // since it now can be.
11505 return IntRange(
11506 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11507 false);
11508 }
11509
11510 default:
11511 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11512 Approximate);
11513 }
11514 }
11515
11516 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11517 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11518 Approximate);
11519
11520 if (const auto *BitField = E->getSourceBitField())
11521 return IntRange(BitField->getBitWidthValue(),
11522 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11523
11524 if (GetExprType(E)->isVoidType())
11525 return std::nullopt;
11526
11527 return IntRange::forValueOfType(C, GetExprType(E));
11528}
11529
11530static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11531 bool InConstantContext,
11532 bool Approximate) {
11533 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11534 Approximate);
11535}
11536
11537/// Checks whether the given value, which currently has the given
11538/// source semantics, has the same value when coerced through the
11539/// target semantics.
11540static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11541 const llvm::fltSemantics &Src,
11542 const llvm::fltSemantics &Tgt) {
11543 llvm::APFloat truncated = value;
11544
11545 bool ignored;
11546 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11547 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11548
11549 return truncated.bitwiseIsEqual(value);
11550}
11551
11552/// Checks whether the given value, which currently has the given
11553/// source semantics, has the same value when coerced through the
11554/// target semantics.
11555///
11556/// The value might be a vector of floats (or a complex number).
11557static bool IsSameFloatAfterCast(const APValue &value,
11558 const llvm::fltSemantics &Src,
11559 const llvm::fltSemantics &Tgt) {
11560 if (value.isFloat())
11561 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11562
11563 if (value.isVector()) {
11564 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11565 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11566 return false;
11567 return true;
11568 }
11569
11570 assert(value.isComplexFloat());
11571 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11572 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11573}
11574
11575static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11576 bool IsListInit = false);
11577
11578static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11579 // Suppress cases where we are comparing against an enum constant.
11580 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11581 if (isa<EnumConstantDecl>(DR->getDecl()))
11582 return true;
11583
11584 // Suppress cases where the value is expanded from a macro, unless that macro
11585 // is how a language represents a boolean literal. This is the case in both C
11586 // and Objective-C.
11587 SourceLocation BeginLoc = E->getBeginLoc();
11588 if (BeginLoc.isMacroID()) {
11589 StringRef MacroName = Lexer::getImmediateMacroName(
11590 BeginLoc, S.getSourceManager(), S.getLangOpts());
11591 return MacroName != "YES" && MacroName != "NO" &&
11592 MacroName != "true" && MacroName != "false";
11593 }
11594
11595 return false;
11596}
11597
11598static bool isKnownToHaveUnsignedValue(const Expr *E) {
11599 return E->getType()->isIntegerType() &&
11600 (!E->getType()->isSignedIntegerType() ||
11602}
11603
11604namespace {
11605/// The promoted range of values of a type. In general this has the
11606/// following structure:
11607///
11608/// |-----------| . . . |-----------|
11609/// ^ ^ ^ ^
11610/// Min HoleMin HoleMax Max
11611///
11612/// ... where there is only a hole if a signed type is promoted to unsigned
11613/// (in which case Min and Max are the smallest and largest representable
11614/// values).
11615struct PromotedRange {
11616 // Min, or HoleMax if there is a hole.
11617 llvm::APSInt PromotedMin;
11618 // Max, or HoleMin if there is a hole.
11619 llvm::APSInt PromotedMax;
11620
11621 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11622 if (R.Width == 0)
11623 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11624 else if (R.Width >= BitWidth && !Unsigned) {
11625 // Promotion made the type *narrower*. This happens when promoting
11626 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11627 // Treat all values of 'signed int' as being in range for now.
11628 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11629 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11630 } else {
11631 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11632 .extOrTrunc(BitWidth);
11633 PromotedMin.setIsUnsigned(Unsigned);
11634
11635 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11636 .extOrTrunc(BitWidth);
11637 PromotedMax.setIsUnsigned(Unsigned);
11638 }
11639 }
11640
11641 // Determine whether this range is contiguous (has no hole).
11642 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11643
11644 // Where a constant value is within the range.
11645 enum ComparisonResult {
11646 LT = 0x1,
11647 LE = 0x2,
11648 GT = 0x4,
11649 GE = 0x8,
11650 EQ = 0x10,
11651 NE = 0x20,
11652 InRangeFlag = 0x40,
11653
11654 Less = LE | LT | NE,
11655 Min = LE | InRangeFlag,
11656 InRange = InRangeFlag,
11657 Max = GE | InRangeFlag,
11658 Greater = GE | GT | NE,
11659
11660 OnlyValue = LE | GE | EQ | InRangeFlag,
11661 InHole = NE
11662 };
11663
11664 ComparisonResult compare(const llvm::APSInt &Value) const {
11665 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11666 Value.isUnsigned() == PromotedMin.isUnsigned());
11667 if (!isContiguous()) {
11668 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11669 if (Value.isMinValue()) return Min;
11670 if (Value.isMaxValue()) return Max;
11671 if (Value >= PromotedMin) return InRange;
11672 if (Value <= PromotedMax) return InRange;
11673 return InHole;
11674 }
11675
11676 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11677 case -1: return Less;
11678 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11679 case 1:
11680 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11681 case -1: return InRange;
11682 case 0: return Max;
11683 case 1: return Greater;
11684 }
11685 }
11686
11687 llvm_unreachable("impossible compare result");
11688 }
11689
11690 static std::optional<StringRef>
11691 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11692 if (Op == BO_Cmp) {
11693 ComparisonResult LTFlag = LT, GTFlag = GT;
11694 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11695
11696 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11697 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11698 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11699 return std::nullopt;
11700 }
11701
11702 ComparisonResult TrueFlag, FalseFlag;
11703 if (Op == BO_EQ) {
11704 TrueFlag = EQ;
11705 FalseFlag = NE;
11706 } else if (Op == BO_NE) {
11707 TrueFlag = NE;
11708 FalseFlag = EQ;
11709 } else {
11710 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11711 TrueFlag = LT;
11712 FalseFlag = GE;
11713 } else {
11714 TrueFlag = GT;
11715 FalseFlag = LE;
11716 }
11717 if (Op == BO_GE || Op == BO_LE)
11718 std::swap(TrueFlag, FalseFlag);
11719 }
11720 if (R & TrueFlag)
11721 return StringRef("true");
11722 if (R & FalseFlag)
11723 return StringRef("false");
11724 return std::nullopt;
11725 }
11726};
11727}
11728
11729static bool HasEnumType(const Expr *E) {
11730 // Strip off implicit integral promotions.
11731 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11732 if (ICE->getCastKind() != CK_IntegralCast &&
11733 ICE->getCastKind() != CK_NoOp)
11734 break;
11735 E = ICE->getSubExpr();
11736 }
11737
11738 return E->getType()->isEnumeralType();
11739}
11740
11741static int classifyConstantValue(Expr *Constant) {
11742 // The values of this enumeration are used in the diagnostics
11743 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11744 enum ConstantValueKind {
11745 Miscellaneous = 0,
11746 LiteralTrue,
11747 LiteralFalse
11748 };
11749 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11750 return BL->getValue() ? ConstantValueKind::LiteralTrue
11751 : ConstantValueKind::LiteralFalse;
11752 return ConstantValueKind::Miscellaneous;
11753}
11754
11756 Expr *Constant, Expr *Other,
11757 const llvm::APSInt &Value,
11758 bool RhsConstant) {
11760 return false;
11761
11762 Expr *OriginalOther = Other;
11763
11764 Constant = Constant->IgnoreParenImpCasts();
11765 Other = Other->IgnoreParenImpCasts();
11766
11767 // Suppress warnings on tautological comparisons between values of the same
11768 // enumeration type. There are only two ways we could warn on this:
11769 // - If the constant is outside the range of representable values of
11770 // the enumeration. In such a case, we should warn about the cast
11771 // to enumeration type, not about the comparison.
11772 // - If the constant is the maximum / minimum in-range value. For an
11773 // enumeratin type, such comparisons can be meaningful and useful.
11774 if (Constant->getType()->isEnumeralType() &&
11775 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11776 return false;
11777
11778 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11779 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11780 if (!OtherValueRange)
11781 return false;
11782
11783 QualType OtherT = Other->getType();
11784 if (const auto *AT = OtherT->getAs<AtomicType>())
11785 OtherT = AT->getValueType();
11786 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11787
11788 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11789 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11790 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11791 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11792 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11793
11794 // Whether we're treating Other as being a bool because of the form of
11795 // expression despite it having another type (typically 'int' in C).
11796 bool OtherIsBooleanDespiteType =
11797 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11798 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11799 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11800
11801 // Check if all values in the range of possible values of this expression
11802 // lead to the same comparison outcome.
11803 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11804 Value.isUnsigned());
11805 auto Cmp = OtherPromotedValueRange.compare(Value);
11806 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11807 if (!Result)
11808 return false;
11809
11810 // Also consider the range determined by the type alone. This allows us to
11811 // classify the warning under the proper diagnostic group.
11812 bool TautologicalTypeCompare = false;
11813 {
11814 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11815 Value.isUnsigned());
11816 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11817 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11818 RhsConstant)) {
11819 TautologicalTypeCompare = true;
11820 Cmp = TypeCmp;
11821 Result = TypeResult;
11822 }
11823 }
11824
11825 // Don't warn if the non-constant operand actually always evaluates to the
11826 // same value.
11827 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11828 return false;
11829
11830 // Suppress the diagnostic for an in-range comparison if the constant comes
11831 // from a macro or enumerator. We don't want to diagnose
11832 //
11833 // some_long_value <= INT_MAX
11834 //
11835 // when sizeof(int) == sizeof(long).
11836 bool InRange = Cmp & PromotedRange::InRangeFlag;
11837 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11838 return false;
11839
11840 // A comparison of an unsigned bit-field against 0 is really a type problem,
11841 // even though at the type level the bit-field might promote to 'signed int'.
11842 if (Other->refersToBitField() && InRange && Value == 0 &&
11843 Other->getType()->isUnsignedIntegerOrEnumerationType())
11844 TautologicalTypeCompare = true;
11845
11846 // If this is a comparison to an enum constant, include that
11847 // constant in the diagnostic.
11848 const EnumConstantDecl *ED = nullptr;
11849 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11850 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11851
11852 // Should be enough for uint128 (39 decimal digits)
11853 SmallString<64> PrettySourceValue;
11854 llvm::raw_svector_ostream OS(PrettySourceValue);
11855 if (ED) {
11856 OS << '\'' << *ED << "' (" << Value << ")";
11857 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11858 Constant->IgnoreParenImpCasts())) {
11859 OS << (BL->getValue() ? "YES" : "NO");
11860 } else {
11861 OS << Value;
11862 }
11863
11864 if (!TautologicalTypeCompare) {
11865 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11866 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11867 << E->getOpcodeStr() << OS.str() << *Result
11868 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11869 return true;
11870 }
11871
11872 if (IsObjCSignedCharBool) {
11874 S.PDiag(diag::warn_tautological_compare_objc_bool)
11875 << OS.str() << *Result);
11876 return true;
11877 }
11878
11879 // FIXME: We use a somewhat different formatting for the in-range cases and
11880 // cases involving boolean values for historical reasons. We should pick a
11881 // consistent way of presenting these diagnostics.
11882 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11883
11885 E->getOperatorLoc(), E,
11886 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11887 : diag::warn_tautological_bool_compare)
11888 << OS.str() << classifyConstantValue(Constant) << OtherT
11889 << OtherIsBooleanDespiteType << *Result
11890 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11891 } else {
11892 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11893 unsigned Diag =
11894 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11895 ? (HasEnumType(OriginalOther)
11896 ? diag::warn_unsigned_enum_always_true_comparison
11897 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11898 : diag::warn_unsigned_always_true_comparison)
11899 : diag::warn_tautological_constant_compare;
11900
11901 S.Diag(E->getOperatorLoc(), Diag)
11902 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11903 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11904 }
11905
11906 return true;
11907}
11908
11909/// Analyze the operands of the given comparison. Implements the
11910/// fallback case from AnalyzeComparison.
11915
11916/// Implements -Wsign-compare.
11917///
11918/// \param E the binary operator to check for warnings
11920 // The type the comparison is being performed in.
11921 QualType T = E->getLHS()->getType();
11922
11923 // Only analyze comparison operators where both sides have been converted to
11924 // the same type.
11926 return AnalyzeImpConvsInComparison(S, E);
11927
11928 // Don't analyze value-dependent comparisons directly.
11929 if (E->isValueDependent())
11930 return AnalyzeImpConvsInComparison(S, E);
11931
11932 Expr *LHS = E->getLHS();
11933 Expr *RHS = E->getRHS();
11934
11935 if (T->isIntegralType(S.Context)) {
11936 std::optional<llvm::APSInt> RHSValue =
11938 std::optional<llvm::APSInt> LHSValue =
11940
11941 // We don't care about expressions whose result is a constant.
11942 if (RHSValue && LHSValue)
11943 return AnalyzeImpConvsInComparison(S, E);
11944
11945 // We only care about expressions where just one side is literal
11946 if ((bool)RHSValue ^ (bool)LHSValue) {
11947 // Is the constant on the RHS or LHS?
11948 const bool RhsConstant = (bool)RHSValue;
11949 Expr *Const = RhsConstant ? RHS : LHS;
11950 Expr *Other = RhsConstant ? LHS : RHS;
11951 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11952
11953 // Check whether an integer constant comparison results in a value
11954 // of 'true' or 'false'.
11955 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11956 return AnalyzeImpConvsInComparison(S, E);
11957 }
11958 }
11959
11960 if (!T->hasUnsignedIntegerRepresentation()) {
11961 // We don't do anything special if this isn't an unsigned integral
11962 // comparison: we're only interested in integral comparisons, and
11963 // signed comparisons only happen in cases we don't care to warn about.
11964 return AnalyzeImpConvsInComparison(S, E);
11965 }
11966
11967 LHS = LHS->IgnoreParenImpCasts();
11968 RHS = RHS->IgnoreParenImpCasts();
11969
11970 if (!S.getLangOpts().CPlusPlus) {
11971 // Avoid warning about comparison of integers with different signs when
11972 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11973 // the type of `E`.
11974 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11975 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11976 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11977 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11978 }
11979
11980 // Check to see if one of the (unmodified) operands is of different
11981 // signedness.
11982 Expr *signedOperand, *unsignedOperand;
11984 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11985 "unsigned comparison between two signed integer expressions?");
11986 signedOperand = LHS;
11987 unsignedOperand = RHS;
11988 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11989 signedOperand = RHS;
11990 unsignedOperand = LHS;
11991 } else {
11992 return AnalyzeImpConvsInComparison(S, E);
11993 }
11994
11995 // Otherwise, calculate the effective range of the signed operand.
11996 std::optional<IntRange> signedRange =
11998 /*Approximate=*/true);
11999 if (!signedRange)
12000 return;
12001
12002 // Go ahead and analyze implicit conversions in the operands. Note
12003 // that we skip the implicit conversions on both sides.
12006
12007 // If the signed range is non-negative, -Wsign-compare won't fire.
12008 if (signedRange->NonNegative)
12009 return;
12010
12011 // For (in)equality comparisons, if the unsigned operand is a
12012 // constant which cannot collide with a overflowed signed operand,
12013 // then reinterpreting the signed operand as unsigned will not
12014 // change the result of the comparison.
12015 if (E->isEqualityOp()) {
12016 unsigned comparisonWidth = S.Context.getIntWidth(T);
12017 std::optional<IntRange> unsignedRange = TryGetExprRange(
12018 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12019 /*Approximate=*/true);
12020 if (!unsignedRange)
12021 return;
12022
12023 // We should never be unable to prove that the unsigned operand is
12024 // non-negative.
12025 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12026
12027 if (unsignedRange->Width < comparisonWidth)
12028 return;
12029 }
12030
12032 S.PDiag(diag::warn_mixed_sign_comparison)
12033 << LHS->getType() << RHS->getType()
12034 << LHS->getSourceRange() << RHS->getSourceRange());
12035}
12036
12037/// Analyzes an attempt to assign the given value to a bitfield.
12038///
12039/// Returns true if there was something fishy about the attempt.
12041 SourceLocation InitLoc) {
12042 assert(Bitfield->isBitField());
12043 if (Bitfield->isInvalidDecl())
12044 return false;
12045
12046 // White-list bool bitfields.
12047 QualType BitfieldType = Bitfield->getType();
12048 if (BitfieldType->isBooleanType())
12049 return false;
12050
12051 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12052 // If the underlying enum type was not explicitly specified as an unsigned
12053 // type and the enum contain only positive values, MSVC++ will cause an
12054 // inconsistency by storing this as a signed type.
12055 if (S.getLangOpts().CPlusPlus11 &&
12056 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12057 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12058 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12059 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12060 << BitfieldEnumDecl;
12061 }
12062 }
12063
12064 // Ignore value- or type-dependent expressions.
12065 if (Bitfield->getBitWidth()->isValueDependent() ||
12066 Bitfield->getBitWidth()->isTypeDependent() ||
12067 Init->isValueDependent() ||
12068 Init->isTypeDependent())
12069 return false;
12070
12071 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12072 unsigned FieldWidth = Bitfield->getBitWidthValue();
12073
12074 Expr::EvalResult Result;
12075 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12077 // The RHS is not constant. If the RHS has an enum type, make sure the
12078 // bitfield is wide enough to hold all the values of the enum without
12079 // truncation.
12080 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12081 const PreferredTypeAttr *PTAttr = nullptr;
12082 if (!ED) {
12083 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12084 if (PTAttr)
12085 ED = PTAttr->getType()->getAsEnumDecl();
12086 }
12087 if (ED) {
12088 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12089
12090 // Enum types are implicitly signed on Windows, so check if there are any
12091 // negative enumerators to see if the enum was intended to be signed or
12092 // not.
12093 bool SignedEnum = ED->getNumNegativeBits() > 0;
12094
12095 // Check for surprising sign changes when assigning enum values to a
12096 // bitfield of different signedness. If the bitfield is signed and we
12097 // have exactly the right number of bits to store this unsigned enum,
12098 // suggest changing the enum to an unsigned type. This typically happens
12099 // on Windows where unfixed enums always use an underlying type of 'int'.
12100 unsigned DiagID = 0;
12101 if (SignedEnum && !SignedBitfield) {
12102 DiagID =
12103 PTAttr == nullptr
12104 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12105 : diag::
12106 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12107 } else if (SignedBitfield && !SignedEnum &&
12108 ED->getNumPositiveBits() == FieldWidth) {
12109 DiagID =
12110 PTAttr == nullptr
12111 ? diag::warn_signed_bitfield_enum_conversion
12112 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12113 }
12114 if (DiagID) {
12115 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12116 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12117 SourceRange TypeRange =
12118 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12119 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12120 << SignedEnum << TypeRange;
12121 if (PTAttr)
12122 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12123 << ED;
12124 }
12125
12126 // Compute the required bitwidth. If the enum has negative values, we need
12127 // one more bit than the normal number of positive bits to represent the
12128 // sign bit.
12129 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12130 ED->getNumNegativeBits())
12131 : ED->getNumPositiveBits();
12132
12133 // Check the bitwidth.
12134 if (BitsNeeded > FieldWidth) {
12135 Expr *WidthExpr = Bitfield->getBitWidth();
12136 auto DiagID =
12137 PTAttr == nullptr
12138 ? diag::warn_bitfield_too_small_for_enum
12139 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12140 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12141 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12142 << BitsNeeded << ED << WidthExpr->getSourceRange();
12143 if (PTAttr)
12144 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12145 << ED;
12146 }
12147 }
12148
12149 return false;
12150 }
12151
12152 llvm::APSInt Value = Result.Val.getInt();
12153
12154 unsigned OriginalWidth = Value.getBitWidth();
12155
12156 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12157 // false positives where the user is demonstrating they intend to use the
12158 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12159 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12160 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12161 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12162 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12163 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12164 S.findMacroSpelling(MaybeMacroLoc, "true"))
12165 return false;
12166 }
12167
12168 if (!Value.isSigned() || Value.isNegative())
12169 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12170 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12171 OriginalWidth = Value.getSignificantBits();
12172
12173 if (OriginalWidth <= FieldWidth)
12174 return false;
12175
12176 // Compute the value which the bitfield will contain.
12177 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12178 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12179
12180 // Check whether the stored value is equal to the original value.
12181 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12182 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12183 return false;
12184
12185 std::string PrettyValue = toString(Value, 10);
12186 std::string PrettyTrunc = toString(TruncatedValue, 10);
12187
12188 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12189 ? diag::warn_impcast_single_bit_bitield_precision_constant
12190 : diag::warn_impcast_bitfield_precision_constant)
12191 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12192 << Init->getSourceRange();
12193
12194 return true;
12195}
12196
12197/// Analyze the given simple or compound assignment for warning-worthy
12198/// operations.
12200 // Just recurse on the LHS.
12202
12203 // We want to recurse on the RHS as normal unless we're assigning to
12204 // a bitfield.
12205 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12206 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12207 E->getOperatorLoc())) {
12208 // Recurse, ignoring any implicit conversions on the RHS.
12210 E->getOperatorLoc());
12211 }
12212 }
12213
12215
12216 // Diagnose implicitly sequentially-consistent atomic assignment.
12217 if (E->getLHS()->getType()->isAtomicType())
12218 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12219}
12220
12221/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12222static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12223 QualType T, SourceLocation CContext, unsigned diag,
12224 bool PruneControlFlow = false) {
12225 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12226 // address space annotations isn't really useful. The warnings aren't because
12227 // you're converting a `private int` to `unsigned int`, it is because you're
12228 // conerting `int` to `unsigned int`.
12229 if (SourceType.hasAddressSpace())
12230 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12231 if (T.hasAddressSpace())
12233 if (PruneControlFlow) {
12235 S.PDiag(diag)
12236 << SourceType << T << E->getSourceRange()
12237 << SourceRange(CContext));
12238 return;
12239 }
12240 S.Diag(E->getExprLoc(), diag)
12241 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12242}
12243
12244/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12245static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12246 SourceLocation CContext, unsigned diag,
12247 bool PruneControlFlow = false) {
12248 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12249}
12250
12251/// Diagnose an implicit cast from a floating point value to an integer value.
12252static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12253 SourceLocation CContext) {
12254 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12255 bool PruneWarnings = S.inTemplateInstantiation();
12256
12257 const Expr *InnerE = E->IgnoreParenImpCasts();
12258 // We also want to warn on, e.g., "int i = -1.234"
12259 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12260 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12261 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12262
12263 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12264
12265 llvm::APFloat Value(0.0);
12266 bool IsConstant =
12268 if (!IsConstant) {
12269 if (S.ObjC().isSignedCharBool(T)) {
12271 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12272 << E->getType());
12273 }
12274
12275 return DiagnoseImpCast(S, E, T, CContext,
12276 diag::warn_impcast_float_integer, PruneWarnings);
12277 }
12278
12279 bool isExact = false;
12280
12281 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12282 T->hasUnsignedIntegerRepresentation());
12283 llvm::APFloat::opStatus Result = Value.convertToInteger(
12284 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12285
12286 // FIXME: Force the precision of the source value down so we don't print
12287 // digits which are usually useless (we don't really care here if we
12288 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12289 // would automatically print the shortest representation, but it's a bit
12290 // tricky to implement.
12291 SmallString<16> PrettySourceValue;
12292 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12293 precision = (precision * 59 + 195) / 196;
12294 Value.toString(PrettySourceValue, precision);
12295
12296 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12298 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12299 << PrettySourceValue);
12300 }
12301
12302 if (Result == llvm::APFloat::opOK && isExact) {
12303 if (IsLiteral) return;
12304 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12305 PruneWarnings);
12306 }
12307
12308 // Conversion of a floating-point value to a non-bool integer where the
12309 // integral part cannot be represented by the integer type is undefined.
12310 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12311 return DiagnoseImpCast(
12312 S, E, T, CContext,
12313 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12314 : diag::warn_impcast_float_to_integer_out_of_range,
12315 PruneWarnings);
12316
12317 unsigned DiagID = 0;
12318 if (IsLiteral) {
12319 // Warn on floating point literal to integer.
12320 DiagID = diag::warn_impcast_literal_float_to_integer;
12321 } else if (IntegerValue == 0) {
12322 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12323 return DiagnoseImpCast(S, E, T, CContext,
12324 diag::warn_impcast_float_integer, PruneWarnings);
12325 }
12326 // Warn on non-zero to zero conversion.
12327 DiagID = diag::warn_impcast_float_to_integer_zero;
12328 } else {
12329 if (IntegerValue.isUnsigned()) {
12330 if (!IntegerValue.isMaxValue()) {
12331 return DiagnoseImpCast(S, E, T, CContext,
12332 diag::warn_impcast_float_integer, PruneWarnings);
12333 }
12334 } else { // IntegerValue.isSigned()
12335 if (!IntegerValue.isMaxSignedValue() &&
12336 !IntegerValue.isMinSignedValue()) {
12337 return DiagnoseImpCast(S, E, T, CContext,
12338 diag::warn_impcast_float_integer, PruneWarnings);
12339 }
12340 }
12341 // Warn on evaluatable floating point expression to integer conversion.
12342 DiagID = diag::warn_impcast_float_to_integer;
12343 }
12344
12345 SmallString<16> PrettyTargetValue;
12346 if (IsBool)
12347 PrettyTargetValue = Value.isZero() ? "false" : "true";
12348 else
12349 IntegerValue.toString(PrettyTargetValue);
12350
12351 if (PruneWarnings) {
12353 S.PDiag(DiagID)
12354 << E->getType() << T.getUnqualifiedType()
12355 << PrettySourceValue << PrettyTargetValue
12356 << E->getSourceRange() << SourceRange(CContext));
12357 } else {
12358 S.Diag(E->getExprLoc(), DiagID)
12359 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12360 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12361 }
12362}
12363
12364/// Analyze the given compound assignment for the possible losing of
12365/// floating-point precision.
12367 assert(isa<CompoundAssignOperator>(E) &&
12368 "Must be compound assignment operation");
12369 // Recurse on the LHS and RHS in here
12372
12373 if (E->getLHS()->getType()->isAtomicType())
12374 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12375
12376 // Now check the outermost expression
12377 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12378 const auto *RBT = cast<CompoundAssignOperator>(E)
12379 ->getComputationResultType()
12380 ->getAs<BuiltinType>();
12381
12382 // The below checks assume source is floating point.
12383 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12384
12385 // If source is floating point but target is an integer.
12386 if (ResultBT->isInteger())
12387 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12388 E->getExprLoc(), diag::warn_impcast_float_integer);
12389
12390 if (!ResultBT->isFloatingPoint())
12391 return;
12392
12393 // If both source and target are floating points, warn about losing precision.
12395 QualType(ResultBT, 0), QualType(RBT, 0));
12396 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12397 // warn about dropping FP rank.
12398 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12399 diag::warn_impcast_float_result_precision);
12400}
12401
12402static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12403 IntRange Range) {
12404 if (!Range.Width) return "0";
12405
12406 llvm::APSInt ValueInRange = Value;
12407 ValueInRange.setIsSigned(!Range.NonNegative);
12408 ValueInRange = ValueInRange.trunc(Range.Width);
12409 return toString(ValueInRange, 10);
12410}
12411
12412static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12413 bool ToBool) {
12414 if (!isa<ImplicitCastExpr>(Ex))
12415 return false;
12416
12417 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12419 const Type *Source =
12421 if (Target->isDependentType())
12422 return false;
12423
12424 const auto *FloatCandidateBT =
12425 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12426 const Type *BoolCandidateType = ToBool ? Target : Source;
12427
12428 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12429 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12430}
12431
12432static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12433 SourceLocation CC) {
12434 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12435 const Expr *CurrA = TheCall->getArg(I);
12436 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12437 continue;
12438
12439 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12440 S, TheCall->getArg(I - 1), false));
12441 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12442 S, TheCall->getArg(I + 1), false));
12443 if (IsSwapped) {
12444 // Warn on this floating-point to bool conversion.
12446 CurrA->getType(), CC,
12447 diag::warn_impcast_floating_point_to_bool);
12448 }
12449 }
12450}
12451
12453 SourceLocation CC) {
12454 // Don't warn on functions which have return type nullptr_t.
12455 if (isa<CallExpr>(E))
12456 return;
12457
12458 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12459 const Expr *NewE = E->IgnoreParenImpCasts();
12460 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12461 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12462 if (!IsGNUNullExpr && !HasNullPtrType)
12463 return;
12464
12465 // Return if target type is a safe conversion.
12466 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12467 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12468 return;
12469
12470 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12471 E->getExprLoc()))
12472 return;
12473
12475
12476 // Venture through the macro stacks to get to the source of macro arguments.
12477 // The new location is a better location than the complete location that was
12478 // passed in.
12479 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12481
12482 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12483 if (IsGNUNullExpr && Loc.isMacroID()) {
12484 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12485 Loc, S.SourceMgr, S.getLangOpts());
12486 if (MacroName == "NULL")
12488 }
12489
12490 // Only warn if the null and context location are in the same macro expansion.
12491 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12492 return;
12493
12494 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12495 << HasNullPtrType << T << SourceRange(CC)
12498}
12499
12500// Helper function to filter out cases for constant width constant conversion.
12501// Don't warn on char array initialization or for non-decimal values.
12503 SourceLocation CC) {
12504 // If initializing from a constant, and the constant starts with '0',
12505 // then it is a binary, octal, or hexadecimal. Allow these constants
12506 // to fill all the bits, even if there is a sign change.
12507 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12508 const char FirstLiteralCharacter =
12509 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12510 if (FirstLiteralCharacter == '0')
12511 return false;
12512 }
12513
12514 // If the CC location points to a '{', and the type is char, then assume
12515 // assume it is an array initialization.
12516 if (CC.isValid() && T->isCharType()) {
12517 const char FirstContextCharacter =
12519 if (FirstContextCharacter == '{')
12520 return false;
12521 }
12522
12523 return true;
12524}
12525
12527 const auto *IL = dyn_cast<IntegerLiteral>(E);
12528 if (!IL) {
12529 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12530 if (UO->getOpcode() == UO_Minus)
12531 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12532 }
12533 }
12534
12535 return IL;
12536}
12537
12539 E = E->IgnoreParenImpCasts();
12540 SourceLocation ExprLoc = E->getExprLoc();
12541
12542 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12543 BinaryOperator::Opcode Opc = BO->getOpcode();
12544 Expr::EvalResult Result;
12545 // Do not diagnose unsigned shifts.
12546 if (Opc == BO_Shl) {
12547 const auto *LHS = getIntegerLiteral(BO->getLHS());
12548 const auto *RHS = getIntegerLiteral(BO->getRHS());
12549 if (LHS && LHS->getValue() == 0)
12550 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12551 else if (!E->isValueDependent() && LHS && RHS &&
12552 RHS->getValue().isNonNegative() &&
12554 S.Diag(ExprLoc, diag::warn_left_shift_always)
12555 << (Result.Val.getInt() != 0);
12556 else if (E->getType()->isSignedIntegerType())
12557 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12560 ") != 0");
12561 }
12562 }
12563
12564 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12565 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12566 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12567 if (!LHS || !RHS)
12568 return;
12569 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12570 (RHS->getValue() == 0 || RHS->getValue() == 1))
12571 // Do not diagnose common idioms.
12572 return;
12573 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12574 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12575 }
12576}
12577
12579 const Type *Target, Expr *E,
12580 QualType T,
12581 SourceLocation CC) {
12582 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12583 Source != Target);
12584
12585 // Lone surrogates have a distinct representation in UTF-32.
12586 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12587 // so don't warn on such conversion.
12588 if (Source->isChar16Type() && Target->isChar32Type())
12589 return;
12590
12591 Expr::EvalResult Result;
12594 llvm::APSInt Value(32);
12595 Value = Result.Val.getInt();
12596 bool IsASCII = Value <= 0x7F;
12597 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12598 bool ConversionPreservesSemantics =
12599 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12600
12601 if (!ConversionPreservesSemantics) {
12602 auto IsSingleCodeUnitCP = [](const QualType &T,
12603 const llvm::APSInt &Value) {
12604 if (T->isChar8Type())
12605 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12606 if (T->isChar16Type())
12607 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12608 assert(T->isChar32Type());
12609 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12610 };
12611
12612 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12613 << E->getType() << T
12614 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12615 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12616 }
12617 } else {
12618 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12620 DiagnoseImpCast(S, E, T, CC,
12621 LosesPrecision ? diag::warn_impcast_unicode_precision
12622 : diag::warn_impcast_unicode_char_type);
12623 }
12624}
12625
12627 From = Context.getCanonicalType(From);
12628 To = Context.getCanonicalType(To);
12629 QualType MaybePointee = From->getPointeeType();
12630 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12631 From = MaybePointee;
12632 MaybePointee = To->getPointeeType();
12633 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12634 To = MaybePointee;
12635
12636 if (const auto *FromFn = From->getAs<FunctionType>()) {
12637 if (const auto *ToFn = To->getAs<FunctionType>()) {
12638 if (FromFn->getCFIUncheckedCalleeAttr() &&
12639 !ToFn->getCFIUncheckedCalleeAttr())
12640 return true;
12641 }
12642 }
12643 return false;
12644}
12645
12647 bool *ICContext, bool IsListInit) {
12648 if (E->isTypeDependent() || E->isValueDependent()) return;
12649
12650 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12651 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12652 if (Source == Target) return;
12653 if (Target->isDependentType()) return;
12654
12655 // If the conversion context location is invalid don't complain. We also
12656 // don't want to emit a warning if the issue occurs from the expansion of
12657 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12658 // delay this check as long as possible. Once we detect we are in that
12659 // scenario, we just return.
12660 if (CC.isInvalid())
12661 return;
12662
12663 if (Source->isAtomicType())
12664 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12665
12666 // Diagnose implicit casts to bool.
12667 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12668 if (isa<StringLiteral>(E))
12669 // Warn on string literal to bool. Checks for string literals in logical
12670 // and expressions, for instance, assert(0 && "error here"), are
12671 // prevented by a check in AnalyzeImplicitConversions().
12672 return DiagnoseImpCast(*this, E, T, CC,
12673 diag::warn_impcast_string_literal_to_bool);
12676 // This covers the literal expressions that evaluate to Objective-C
12677 // objects.
12678 return DiagnoseImpCast(*this, E, T, CC,
12679 diag::warn_impcast_objective_c_literal_to_bool);
12680 }
12681 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12682 // Warn on pointer to bool conversion that is always true.
12684 SourceRange(CC));
12685 }
12686 }
12687
12688 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12689 // is a typedef for signed char (macOS), then that constant value has to be 1
12690 // or 0.
12691 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12694 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12696 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12697 << toString(Result.Val.getInt(), 10));
12698 }
12699 return;
12700 }
12701 }
12702
12703 // Check implicit casts from Objective-C collection literals to specialized
12704 // collection types, e.g., NSArray<NSString *> *.
12705 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12706 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12707 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12708 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12709
12710 // Strip vector types.
12711 if (isa<VectorType>(Source)) {
12712 if (Target->isSveVLSBuiltinType() &&
12713 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12714 QualType(Source, 0)) ||
12715 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12716 QualType(Source, 0))))
12717 return;
12718
12719 if (Target->isRVVVLSBuiltinType() &&
12720 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12721 QualType(Source, 0)) ||
12722 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12723 QualType(Source, 0))))
12724 return;
12725
12726 if (!isa<VectorType>(Target)) {
12727 if (SourceMgr.isInSystemMacro(CC))
12728 return;
12729 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12730 }
12731 if (getLangOpts().HLSL &&
12732 Target->castAs<VectorType>()->getNumElements() <
12733 Source->castAs<VectorType>()->getNumElements()) {
12734 // Diagnose vector truncation but don't return. We may also want to
12735 // diagnose an element conversion.
12736 DiagnoseImpCast(*this, E, T, CC,
12737 diag::warn_hlsl_impcast_vector_truncation);
12738 }
12739
12740 // If the vector cast is cast between two vectors of the same size, it is
12741 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12742 if (!getLangOpts().HLSL &&
12743 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12744 return;
12745
12746 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12747 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12748 }
12749 if (const auto *VecTy = dyn_cast<VectorType>(Target))
12750 Target = VecTy->getElementType().getTypePtr();
12751
12752 if (isa<ConstantMatrixType>(Source)) {
12753 if (Target->isScalarType())
12754 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
12755
12756 if (getLangOpts().HLSL &&
12758 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
12759 // Diagnose Matrix truncation but don't return. We may also want to
12760 // diagnose an element conversion.
12761 DiagnoseImpCast(*this, E, T, CC,
12762 diag::warn_hlsl_impcast_matrix_truncation);
12763 }
12764 }
12765 // Strip complex types.
12766 if (isa<ComplexType>(Source)) {
12767 if (!isa<ComplexType>(Target)) {
12768 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12769 return;
12770
12771 return DiagnoseImpCast(*this, E, T, CC,
12773 ? diag::err_impcast_complex_scalar
12774 : diag::warn_impcast_complex_scalar);
12775 }
12776
12777 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12778 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12779 }
12780
12781 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12782 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12783
12784 // Strip SVE vector types
12785 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12786 // Need the original target type for vector type checks
12787 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12788 // Handle conversion from scalable to fixed when msve-vector-bits is
12789 // specified
12790 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12791 QualType(Source, 0)) ||
12792 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12793 QualType(Source, 0)))
12794 return;
12795
12796 // If the vector cast is cast between two vectors of the same size, it is
12797 // a bitcast, not a conversion.
12798 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12799 return;
12800
12801 Source = SourceBT->getSveEltType(Context).getTypePtr();
12802 }
12803
12804 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12805 Target = TargetBT->getSveEltType(Context).getTypePtr();
12806
12807 // If the source is floating point...
12808 if (SourceBT && SourceBT->isFloatingPoint()) {
12809 // ...and the target is floating point...
12810 if (TargetBT && TargetBT->isFloatingPoint()) {
12811 // ...then warn if we're dropping FP rank.
12812
12814 QualType(SourceBT, 0), QualType(TargetBT, 0));
12815 if (Order > 0) {
12816 // Don't warn about float constants that are precisely
12817 // representable in the target type.
12818 Expr::EvalResult result;
12819 if (E->EvaluateAsRValue(result, Context)) {
12820 // Value might be a float, a float vector, or a float complex.
12822 result.Val,
12823 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12824 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12825 return;
12826 }
12827
12828 if (SourceMgr.isInSystemMacro(CC))
12829 return;
12830
12831 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12832 }
12833 // ... or possibly if we're increasing rank, too
12834 else if (Order < 0) {
12835 if (SourceMgr.isInSystemMacro(CC))
12836 return;
12837
12838 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12839 }
12840 return;
12841 }
12842
12843 // If the target is integral, always warn.
12844 if (TargetBT && TargetBT->isInteger()) {
12845 if (SourceMgr.isInSystemMacro(CC))
12846 return;
12847
12848 DiagnoseFloatingImpCast(*this, E, T, CC);
12849 }
12850
12851 // Detect the case where a call result is converted from floating-point to
12852 // to bool, and the final argument to the call is converted from bool, to
12853 // discover this typo:
12854 //
12855 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12856 //
12857 // FIXME: This is an incredibly special case; is there some more general
12858 // way to detect this class of misplaced-parentheses bug?
12859 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12860 // Check last argument of function call to see if it is an
12861 // implicit cast from a type matching the type the result
12862 // is being cast to.
12863 CallExpr *CEx = cast<CallExpr>(E);
12864 if (unsigned NumArgs = CEx->getNumArgs()) {
12865 Expr *LastA = CEx->getArg(NumArgs - 1);
12866 Expr *InnerE = LastA->IgnoreParenImpCasts();
12867 if (isa<ImplicitCastExpr>(LastA) &&
12868 InnerE->getType()->isBooleanType()) {
12869 // Warn on this floating-point to bool conversion
12870 DiagnoseImpCast(*this, E, T, CC,
12871 diag::warn_impcast_floating_point_to_bool);
12872 }
12873 }
12874 }
12875 return;
12876 }
12877
12878 // Valid casts involving fixed point types should be accounted for here.
12879 if (Source->isFixedPointType()) {
12880 if (Target->isUnsaturatedFixedPointType()) {
12884 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12885 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12886 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12887 if (Value > MaxVal || Value < MinVal) {
12889 PDiag(diag::warn_impcast_fixed_point_range)
12890 << Value.toString() << T
12891 << E->getSourceRange()
12892 << clang::SourceRange(CC));
12893 return;
12894 }
12895 }
12896 } else if (Target->isIntegerType()) {
12900 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12901
12902 bool Overflowed;
12903 llvm::APSInt IntResult = FXResult.convertToInt(
12904 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12905 &Overflowed);
12906
12907 if (Overflowed) {
12909 PDiag(diag::warn_impcast_fixed_point_range)
12910 << FXResult.toString() << T
12911 << E->getSourceRange()
12912 << clang::SourceRange(CC));
12913 return;
12914 }
12915 }
12916 }
12917 } else if (Target->isUnsaturatedFixedPointType()) {
12918 if (Source->isIntegerType()) {
12922 llvm::APSInt Value = Result.Val.getInt();
12923
12924 bool Overflowed;
12925 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12926 Value, Context.getFixedPointSemantics(T), &Overflowed);
12927
12928 if (Overflowed) {
12930 PDiag(diag::warn_impcast_fixed_point_range)
12931 << toString(Value, /*Radix=*/10) << T
12932 << E->getSourceRange()
12933 << clang::SourceRange(CC));
12934 return;
12935 }
12936 }
12937 }
12938 }
12939
12940 // If we are casting an integer type to a floating point type without
12941 // initialization-list syntax, we might lose accuracy if the floating
12942 // point type has a narrower significand than the integer type.
12943 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12944 TargetBT->isFloatingType() && !IsListInit) {
12945 // Determine the number of precision bits in the source integer type.
12946 std::optional<IntRange> SourceRange =
12948 /*Approximate=*/true);
12949 if (!SourceRange)
12950 return;
12951 unsigned int SourcePrecision = SourceRange->Width;
12952
12953 // Determine the number of precision bits in the
12954 // target floating point type.
12955 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12956 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12957
12958 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12959 SourcePrecision > TargetPrecision) {
12960
12961 if (std::optional<llvm::APSInt> SourceInt =
12963 // If the source integer is a constant, convert it to the target
12964 // floating point type. Issue a warning if the value changes
12965 // during the whole conversion.
12966 llvm::APFloat TargetFloatValue(
12967 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12968 llvm::APFloat::opStatus ConversionStatus =
12969 TargetFloatValue.convertFromAPInt(
12970 *SourceInt, SourceBT->isSignedInteger(),
12971 llvm::APFloat::rmNearestTiesToEven);
12972
12973 if (ConversionStatus != llvm::APFloat::opOK) {
12974 SmallString<32> PrettySourceValue;
12975 SourceInt->toString(PrettySourceValue, 10);
12976 SmallString<32> PrettyTargetValue;
12977 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12978
12980 E->getExprLoc(), E,
12981 PDiag(diag::warn_impcast_integer_float_precision_constant)
12982 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12983 << E->getSourceRange() << clang::SourceRange(CC));
12984 }
12985 } else {
12986 // Otherwise, the implicit conversion may lose precision.
12987 DiagnoseImpCast(*this, E, T, CC,
12988 diag::warn_impcast_integer_float_precision);
12989 }
12990 }
12991 }
12992
12993 DiagnoseNullConversion(*this, E, T, CC);
12994
12996
12997 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12998 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12999 return;
13000 }
13001
13002 if (Target->isBooleanType())
13003 DiagnoseIntInBoolContext(*this, E);
13004
13006 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13007 << QualType(Source, 0) << QualType(Target, 0);
13008 }
13009
13010 if (!Source->isIntegerType() || !Target->isIntegerType())
13011 return;
13012
13013 // TODO: remove this early return once the false positives for constant->bool
13014 // in templates, macros, etc, are reduced or removed.
13015 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13016 return;
13017
13018 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13019 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13021 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13022 << E->getType());
13023 }
13024 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13025 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13026 if (!LikelySourceRange)
13027 return;
13028
13029 IntRange SourceTypeRange =
13030 IntRange::forTargetOfCanonicalType(Context, Source);
13031 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13032
13033 if (LikelySourceRange->Width > TargetRange.Width) {
13034 // If the source is a constant, use a default-on diagnostic.
13035 // TODO: this should happen for bitfield stores, too.
13039 llvm::APSInt Value(32);
13040 Value = Result.Val.getInt();
13041
13042 if (SourceMgr.isInSystemMacro(CC))
13043 return;
13044
13045 std::string PrettySourceValue = toString(Value, 10);
13046 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13047
13049 PDiag(diag::warn_impcast_integer_precision_constant)
13050 << PrettySourceValue << PrettyTargetValue
13051 << E->getType() << T << E->getSourceRange()
13052 << SourceRange(CC));
13053 return;
13054 }
13055
13056 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13057 if (SourceMgr.isInSystemMacro(CC))
13058 return;
13059
13060 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13061 if (UO->getOpcode() == UO_Minus)
13062 return DiagnoseImpCast(
13063 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13064 }
13065
13066 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13067 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13068 /* pruneControlFlow */ true);
13069 return DiagnoseImpCast(*this, E, T, CC,
13070 diag::warn_impcast_integer_precision);
13071 }
13072
13073 if (TargetRange.Width > SourceTypeRange.Width) {
13074 if (auto *UO = dyn_cast<UnaryOperator>(E))
13075 if (UO->getOpcode() == UO_Minus)
13076 if (Source->isUnsignedIntegerType()) {
13077 if (Target->isUnsignedIntegerType())
13078 return DiagnoseImpCast(*this, E, T, CC,
13079 diag::warn_impcast_high_order_zero_bits);
13080 if (Target->isSignedIntegerType())
13081 return DiagnoseImpCast(*this, E, T, CC,
13082 diag::warn_impcast_nonnegative_result);
13083 }
13084 }
13085
13086 if (TargetRange.Width == LikelySourceRange->Width &&
13087 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13088 Source->isSignedIntegerType()) {
13089 // Warn when doing a signed to signed conversion, warn if the positive
13090 // source value is exactly the width of the target type, which will
13091 // cause a negative value to be stored.
13092
13095 !SourceMgr.isInSystemMacro(CC)) {
13096 llvm::APSInt Value = Result.Val.getInt();
13097 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13098 std::string PrettySourceValue = toString(Value, 10);
13099 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13100
13101 Diag(E->getExprLoc(),
13102 PDiag(diag::warn_impcast_integer_precision_constant)
13103 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13104 << E->getSourceRange() << SourceRange(CC));
13105 return;
13106 }
13107 }
13108
13109 // Fall through for non-constants to give a sign conversion warning.
13110 }
13111
13112 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13113 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13114 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13115 LikelySourceRange->Width == TargetRange.Width))) {
13116 if (SourceMgr.isInSystemMacro(CC))
13117 return;
13118
13119 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13120 TargetBT->isInteger() &&
13121 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13122 return;
13123 }
13124
13125 unsigned DiagID = diag::warn_impcast_integer_sign;
13126
13127 // Traditionally, gcc has warned about this under -Wsign-compare.
13128 // We also want to warn about it in -Wconversion.
13129 // So if -Wconversion is off, use a completely identical diagnostic
13130 // in the sign-compare group.
13131 // The conditional-checking code will
13132 if (ICContext) {
13133 DiagID = diag::warn_impcast_integer_sign_conditional;
13134 *ICContext = true;
13135 }
13136
13137 DiagnoseImpCast(*this, E, T, CC, DiagID);
13138 }
13139
13140 // If we're implicitly converting from an integer into an enumeration, that
13141 // is valid in C but invalid in C++.
13142 QualType SourceType = E->getEnumCoercedType(Context);
13143 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13144 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13145 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13146
13147 // Diagnose conversions between different enumeration types.
13148 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13149 // type, to give us better diagnostics.
13150 Source = Context.getCanonicalType(SourceType).getTypePtr();
13151
13152 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13153 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13154 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13155 TargetEnum->getDecl()->hasNameForLinkage() &&
13156 SourceEnum != TargetEnum) {
13157 if (SourceMgr.isInSystemMacro(CC))
13158 return;
13159
13160 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13161 diag::warn_impcast_different_enum_types);
13162 }
13163}
13164
13167
13169 SourceLocation CC, bool &ICContext) {
13170 E = E->IgnoreParenImpCasts();
13171 // Diagnose incomplete type for second or third operand in C.
13172 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13173 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13174
13175 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13176 return CheckConditionalOperator(S, CO, CC, T);
13177
13179 if (E->getType() != T)
13180 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13181}
13182
13186
13187 Expr *TrueExpr = E->getTrueExpr();
13188 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13189 TrueExpr = BCO->getCommon();
13190
13191 bool Suspicious = false;
13192 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13193 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13194
13195 if (T->isBooleanType())
13197
13198 // If -Wconversion would have warned about either of the candidates
13199 // for a signedness conversion to the context type...
13200 if (!Suspicious) return;
13201
13202 // ...but it's currently ignored...
13203 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13204 return;
13205
13206 // ...then check whether it would have warned about either of the
13207 // candidates for a signedness conversion to the condition type.
13208 if (E->getType() == T) return;
13209
13210 Suspicious = false;
13211 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13212 &Suspicious);
13213 if (!Suspicious)
13215 E->getType(), CC, &Suspicious);
13216}
13217
13218/// Check conversion of given expression to boolean.
13219/// Input argument E is a logical expression.
13221 // Run the bool-like conversion checks only for C since there bools are
13222 // still not used as the return type from "boolean" operators or as the input
13223 // type for conditional operators.
13224 if (S.getLangOpts().CPlusPlus)
13225 return;
13227 return;
13229}
13230
13231namespace {
13232struct AnalyzeImplicitConversionsWorkItem {
13233 Expr *E;
13234 SourceLocation CC;
13235 bool IsListInit;
13236};
13237}
13238
13240 Sema &S, Expr *E, QualType T, SourceLocation CC,
13241 bool ExtraCheckForImplicitConversion,
13243 E = E->IgnoreParenImpCasts();
13244 WorkList.push_back({E, CC, false});
13245
13246 if (ExtraCheckForImplicitConversion && E->getType() != T)
13247 S.CheckImplicitConversion(E, T, CC);
13248}
13249
13250/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13251/// that should be visited are added to WorkList.
13253 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13255 Expr *OrigE = Item.E;
13256 SourceLocation CC = Item.CC;
13257
13258 QualType T = OrigE->getType();
13259 Expr *E = OrigE->IgnoreParenImpCasts();
13260
13261 // Propagate whether we are in a C++ list initialization expression.
13262 // If so, we do not issue warnings for implicit int-float conversion
13263 // precision loss, because C++11 narrowing already handles it.
13264 //
13265 // HLSL's initialization lists are special, so they shouldn't observe the C++
13266 // behavior here.
13267 bool IsListInit =
13268 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13269 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13270
13271 if (E->isTypeDependent() || E->isValueDependent())
13272 return;
13273
13274 Expr *SourceExpr = E;
13275 // Examine, but don't traverse into the source expression of an
13276 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13277 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13278 // evaluate it in the context of checking the specific conversion to T though.
13279 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13280 if (auto *Src = OVE->getSourceExpr())
13281 SourceExpr = Src;
13282
13283 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13284 if (UO->getOpcode() == UO_Not &&
13285 UO->getSubExpr()->isKnownToHaveBooleanValue())
13286 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13287 << OrigE->getSourceRange() << T->isBooleanType()
13288 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13289
13290 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13291 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13292 BO->getLHS()->isKnownToHaveBooleanValue() &&
13293 BO->getRHS()->isKnownToHaveBooleanValue() &&
13294 BO->getLHS()->HasSideEffects(S.Context) &&
13295 BO->getRHS()->HasSideEffects(S.Context)) {
13297 const LangOptions &LO = S.getLangOpts();
13298 SourceLocation BLoc = BO->getOperatorLoc();
13299 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13300 StringRef SR = clang::Lexer::getSourceText(
13301 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13302 // To reduce false positives, only issue the diagnostic if the operator
13303 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13304 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13305 // in C, along with other macro spellings the user might invent.
13306 if (SR.str() == "&" || SR.str() == "|") {
13307
13308 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13309 << (BO->getOpcode() == BO_And ? "&" : "|")
13310 << OrigE->getSourceRange()
13312 BO->getOperatorLoc(),
13313 (BO->getOpcode() == BO_And ? "&&" : "||"));
13314 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13315 }
13316 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13317 /// Analyze the given comma operator. The basic idea behind the analysis
13318 /// is to analyze the left and right operands slightly differently. The
13319 /// left operand needs to check whether the operand itself has an implicit
13320 /// conversion, but not whether the left operand induces an implicit
13321 /// conversion for the entire comma expression itself. This is similar to
13322 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13323 /// were directly used for the implicit conversion check.
13324 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13325 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13326 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13327 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13328 return;
13329 }
13330 }
13331
13332 // For conditional operators, we analyze the arguments as if they
13333 // were being fed directly into the output.
13334 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13335 CheckConditionalOperator(S, CO, CC, T);
13336 return;
13337 }
13338
13339 // Check implicit argument conversions for function calls.
13340 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13342
13343 // Go ahead and check any implicit conversions we might have skipped.
13344 // The non-canonical typecheck is just an optimization;
13345 // CheckImplicitConversion will filter out dead implicit conversions.
13346 if (SourceExpr->getType() != T)
13347 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13348
13349 // Now continue drilling into this expression.
13350
13351 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13352 // The bound subexpressions in a PseudoObjectExpr are not reachable
13353 // as transitive children.
13354 // FIXME: Use a more uniform representation for this.
13355 for (auto *SE : POE->semantics())
13356 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13357 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13358 }
13359
13360 // Skip past explicit casts.
13361 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13362 E = CE->getSubExpr();
13363 // In the special case of a C++ function-style cast with braces,
13364 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13365 // initializer. This InitListExpr basically belongs to the cast itself, so
13366 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13368 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13369 if (InitListE->getNumInits() == 1) {
13370 E = InitListE->getInit(0);
13371 }
13372 }
13373 }
13374 E = E->IgnoreParenImpCasts();
13375 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13376 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13377 WorkList.push_back({E, CC, IsListInit});
13378 return;
13379 }
13380
13381 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13382 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13383 // The base expression is only used to initialize the parameter for
13384 // arguments to `inout` parameters, so we only traverse down the base
13385 // expression for `inout` cases.
13386 if (OutArgE->isInOut())
13387 WorkList.push_back(
13388 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13389 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13390 return;
13391 }
13392
13393 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13394 // Do a somewhat different check with comparison operators.
13395 if (BO->isComparisonOp())
13396 return AnalyzeComparison(S, BO);
13397
13398 // And with simple assignments.
13399 if (BO->getOpcode() == BO_Assign)
13400 return AnalyzeAssignment(S, BO);
13401 // And with compound assignments.
13402 if (BO->isAssignmentOp())
13403 return AnalyzeCompoundAssignment(S, BO);
13404 }
13405
13406 // These break the otherwise-useful invariant below. Fortunately,
13407 // we don't really need to recurse into them, because any internal
13408 // expressions should have been analyzed already when they were
13409 // built into statements.
13410 if (isa<StmtExpr>(E)) return;
13411
13412 // Don't descend into unevaluated contexts.
13413 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13414
13415 // Now just recurse over the expression's children.
13416 CC = E->getExprLoc();
13417 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13418 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13419 for (Stmt *SubStmt : E->children()) {
13420 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13421 if (!ChildExpr)
13422 continue;
13423
13424 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13425 if (ChildExpr == CSE->getOperand())
13426 // Do not recurse over a CoroutineSuspendExpr's operand.
13427 // The operand is also a subexpression of getCommonExpr(), and
13428 // recursing into it directly would produce duplicate diagnostics.
13429 continue;
13430
13431 if (IsLogicalAndOperator &&
13433 // Ignore checking string literals that are in logical and operators.
13434 // This is a common pattern for asserts.
13435 continue;
13436 WorkList.push_back({ChildExpr, CC, IsListInit});
13437 }
13438
13439 if (BO && BO->isLogicalOp()) {
13440 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13441 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13442 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13443
13444 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13445 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13446 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13447 }
13448
13449 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13450 if (U->getOpcode() == UO_LNot) {
13451 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13452 } else if (U->getOpcode() != UO_AddrOf) {
13453 if (U->getSubExpr()->getType()->isAtomicType())
13454 S.Diag(U->getSubExpr()->getBeginLoc(),
13455 diag::warn_atomic_implicit_seq_cst);
13456 }
13457 }
13458}
13459
13460/// AnalyzeImplicitConversions - Find and report any interesting
13461/// implicit conversions in the given expression. There are a couple
13462/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13464 bool IsListInit/*= false*/) {
13466 WorkList.push_back({OrigE, CC, IsListInit});
13467 while (!WorkList.empty())
13468 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13469}
13470
13471// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13472// Returns true when emitting a warning about taking the address of a reference.
13473static bool CheckForReference(Sema &SemaRef, const Expr *E,
13474 const PartialDiagnostic &PD) {
13475 E = E->IgnoreParenImpCasts();
13476
13477 const FunctionDecl *FD = nullptr;
13478
13479 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13480 if (!DRE->getDecl()->getType()->isReferenceType())
13481 return false;
13482 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13483 if (!M->getMemberDecl()->getType()->isReferenceType())
13484 return false;
13485 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13486 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13487 return false;
13488 FD = Call->getDirectCallee();
13489 } else {
13490 return false;
13491 }
13492
13493 SemaRef.Diag(E->getExprLoc(), PD);
13494
13495 // If possible, point to location of function.
13496 if (FD) {
13497 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13498 }
13499
13500 return true;
13501}
13502
13503// Returns true if the SourceLocation is expanded from any macro body.
13504// Returns false if the SourceLocation is invalid, is from not in a macro
13505// expansion, or is from expanded from a top-level macro argument.
13507 if (Loc.isInvalid())
13508 return false;
13509
13510 while (Loc.isMacroID()) {
13511 if (SM.isMacroBodyExpansion(Loc))
13512 return true;
13513 Loc = SM.getImmediateMacroCallerLoc(Loc);
13514 }
13515
13516 return false;
13517}
13518
13521 bool IsEqual, SourceRange Range) {
13522 if (!E)
13523 return;
13524
13525 // Don't warn inside macros.
13526 if (E->getExprLoc().isMacroID()) {
13528 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13529 IsInAnyMacroBody(SM, Range.getBegin()))
13530 return;
13531 }
13532 E = E->IgnoreImpCasts();
13533
13534 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13535
13536 if (isa<CXXThisExpr>(E)) {
13537 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13538 : diag::warn_this_bool_conversion;
13539 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13540 return;
13541 }
13542
13543 bool IsAddressOf = false;
13544
13545 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13546 if (UO->getOpcode() != UO_AddrOf)
13547 return;
13548 IsAddressOf = true;
13549 E = UO->getSubExpr();
13550 }
13551
13552 if (IsAddressOf) {
13553 unsigned DiagID = IsCompare
13554 ? diag::warn_address_of_reference_null_compare
13555 : diag::warn_address_of_reference_bool_conversion;
13556 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13557 << IsEqual;
13558 if (CheckForReference(*this, E, PD)) {
13559 return;
13560 }
13561 }
13562
13563 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13564 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13565 std::string Str;
13566 llvm::raw_string_ostream S(Str);
13567 E->printPretty(S, nullptr, getPrintingPolicy());
13568 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13569 : diag::warn_cast_nonnull_to_bool;
13570 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13571 << E->getSourceRange() << Range << IsEqual;
13572 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13573 };
13574
13575 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13576 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13577 if (auto *Callee = Call->getDirectCallee()) {
13578 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13579 ComplainAboutNonnullParamOrCall(A);
13580 return;
13581 }
13582 }
13583 }
13584
13585 // Complain if we are converting a lambda expression to a boolean value
13586 // outside of instantiation.
13587 if (!inTemplateInstantiation()) {
13588 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13589 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13590 MRecordDecl && MRecordDecl->isLambda()) {
13591 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13592 << /*LambdaPointerConversionOperatorType=*/3
13593 << MRecordDecl->getSourceRange() << Range << IsEqual;
13594 return;
13595 }
13596 }
13597 }
13598
13599 // Expect to find a single Decl. Skip anything more complicated.
13600 ValueDecl *D = nullptr;
13601 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13602 D = R->getDecl();
13603 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13604 D = M->getMemberDecl();
13605 }
13606
13607 // Weak Decls can be null.
13608 if (!D || D->isWeak())
13609 return;
13610
13611 // Check for parameter decl with nonnull attribute
13612 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13613 if (getCurFunction() &&
13614 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13615 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13616 ComplainAboutNonnullParamOrCall(A);
13617 return;
13618 }
13619
13620 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13621 // Skip function template not specialized yet.
13623 return;
13624 auto ParamIter = llvm::find(FD->parameters(), PV);
13625 assert(ParamIter != FD->param_end());
13626 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13627
13628 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13629 if (!NonNull->args_size()) {
13630 ComplainAboutNonnullParamOrCall(NonNull);
13631 return;
13632 }
13633
13634 for (const ParamIdx &ArgNo : NonNull->args()) {
13635 if (ArgNo.getASTIndex() == ParamNo) {
13636 ComplainAboutNonnullParamOrCall(NonNull);
13637 return;
13638 }
13639 }
13640 }
13641 }
13642 }
13643 }
13644
13645 QualType T = D->getType();
13646 const bool IsArray = T->isArrayType();
13647 const bool IsFunction = T->isFunctionType();
13648
13649 // Address of function is used to silence the function warning.
13650 if (IsAddressOf && IsFunction) {
13651 return;
13652 }
13653
13654 // Found nothing.
13655 if (!IsAddressOf && !IsFunction && !IsArray)
13656 return;
13657
13658 // Pretty print the expression for the diagnostic.
13659 std::string Str;
13660 llvm::raw_string_ostream S(Str);
13661 E->printPretty(S, nullptr, getPrintingPolicy());
13662
13663 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13664 : diag::warn_impcast_pointer_to_bool;
13665 enum {
13666 AddressOf,
13667 FunctionPointer,
13668 ArrayPointer
13669 } DiagType;
13670 if (IsAddressOf)
13671 DiagType = AddressOf;
13672 else if (IsFunction)
13673 DiagType = FunctionPointer;
13674 else if (IsArray)
13675 DiagType = ArrayPointer;
13676 else
13677 llvm_unreachable("Could not determine diagnostic.");
13678 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13679 << Range << IsEqual;
13680
13681 if (!IsFunction)
13682 return;
13683
13684 // Suggest '&' to silence the function warning.
13685 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13687
13688 // Check to see if '()' fixit should be emitted.
13689 QualType ReturnType;
13690 UnresolvedSet<4> NonTemplateOverloads;
13691 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13692 if (ReturnType.isNull())
13693 return;
13694
13695 if (IsCompare) {
13696 // There are two cases here. If there is null constant, the only suggest
13697 // for a pointer return type. If the null is 0, then suggest if the return
13698 // type is a pointer or an integer type.
13699 if (!ReturnType->isPointerType()) {
13700 if (NullKind == Expr::NPCK_ZeroExpression ||
13701 NullKind == Expr::NPCK_ZeroLiteral) {
13702 if (!ReturnType->isIntegerType())
13703 return;
13704 } else {
13705 return;
13706 }
13707 }
13708 } else { // !IsCompare
13709 // For function to bool, only suggest if the function pointer has bool
13710 // return type.
13711 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13712 return;
13713 }
13714 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13716}
13717
13718void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13719 // Don't diagnose in unevaluated contexts.
13721 return;
13722
13723 // Don't diagnose for value- or type-dependent expressions.
13724 if (E->isTypeDependent() || E->isValueDependent())
13725 return;
13726
13727 // Check for array bounds violations in cases where the check isn't triggered
13728 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13729 // ArraySubscriptExpr is on the RHS of a variable initialization.
13730 CheckArrayAccess(E);
13731
13732 // This is not the right CC for (e.g.) a variable initialization.
13733 AnalyzeImplicitConversions(*this, E, CC);
13734}
13735
13736void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13737 ::CheckBoolLikeConversion(*this, E, CC);
13738}
13739
13740void Sema::CheckForIntOverflow (const Expr *E) {
13741 // Use a work list to deal with nested struct initializers.
13742 SmallVector<const Expr *, 2> Exprs(1, E);
13743
13744 do {
13745 const Expr *OriginalE = Exprs.pop_back_val();
13746 const Expr *E = OriginalE->IgnoreParenCasts();
13747
13750 continue;
13751 }
13752
13753 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13754 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13755 else if (isa<ObjCBoxedExpr>(OriginalE))
13757 else if (const auto *Call = dyn_cast<CallExpr>(E))
13758 Exprs.append(Call->arg_begin(), Call->arg_end());
13759 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13760 Exprs.append(Message->arg_begin(), Message->arg_end());
13761 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13762 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13763 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13764 Exprs.push_back(Temporary->getSubExpr());
13765 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13766 Exprs.push_back(Array->getIdx());
13767 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13768 Exprs.push_back(Compound->getInitializer());
13769 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13770 New && New->isArray()) {
13771 if (auto ArraySize = New->getArraySize())
13772 Exprs.push_back(*ArraySize);
13773 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13774 Exprs.push_back(MTE->getSubExpr());
13775 } while (!Exprs.empty());
13776}
13777
13778namespace {
13779
13780/// Visitor for expressions which looks for unsequenced operations on the
13781/// same object.
13782class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13783 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13784
13785 /// A tree of sequenced regions within an expression. Two regions are
13786 /// unsequenced if one is an ancestor or a descendent of the other. When we
13787 /// finish processing an expression with sequencing, such as a comma
13788 /// expression, we fold its tree nodes into its parent, since they are
13789 /// unsequenced with respect to nodes we will visit later.
13790 class SequenceTree {
13791 struct Value {
13792 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13793 unsigned Parent : 31;
13794 LLVM_PREFERRED_TYPE(bool)
13795 unsigned Merged : 1;
13796 };
13797 SmallVector<Value, 8> Values;
13798
13799 public:
13800 /// A region within an expression which may be sequenced with respect
13801 /// to some other region.
13802 class Seq {
13803 friend class SequenceTree;
13804
13805 unsigned Index;
13806
13807 explicit Seq(unsigned N) : Index(N) {}
13808
13809 public:
13810 Seq() : Index(0) {}
13811 };
13812
13813 SequenceTree() { Values.push_back(Value(0)); }
13814 Seq root() const { return Seq(0); }
13815
13816 /// Create a new sequence of operations, which is an unsequenced
13817 /// subset of \p Parent. This sequence of operations is sequenced with
13818 /// respect to other children of \p Parent.
13819 Seq allocate(Seq Parent) {
13820 Values.push_back(Value(Parent.Index));
13821 return Seq(Values.size() - 1);
13822 }
13823
13824 /// Merge a sequence of operations into its parent.
13825 void merge(Seq S) {
13826 Values[S.Index].Merged = true;
13827 }
13828
13829 /// Determine whether two operations are unsequenced. This operation
13830 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13831 /// should have been merged into its parent as appropriate.
13832 bool isUnsequenced(Seq Cur, Seq Old) {
13833 unsigned C = representative(Cur.Index);
13834 unsigned Target = representative(Old.Index);
13835 while (C >= Target) {
13836 if (C == Target)
13837 return true;
13838 C = Values[C].Parent;
13839 }
13840 return false;
13841 }
13842
13843 private:
13844 /// Pick a representative for a sequence.
13845 unsigned representative(unsigned K) {
13846 if (Values[K].Merged)
13847 // Perform path compression as we go.
13848 return Values[K].Parent = representative(Values[K].Parent);
13849 return K;
13850 }
13851 };
13852
13853 /// An object for which we can track unsequenced uses.
13854 using Object = const NamedDecl *;
13855
13856 /// Different flavors of object usage which we track. We only track the
13857 /// least-sequenced usage of each kind.
13858 enum UsageKind {
13859 /// A read of an object. Multiple unsequenced reads are OK.
13860 UK_Use,
13861
13862 /// A modification of an object which is sequenced before the value
13863 /// computation of the expression, such as ++n in C++.
13864 UK_ModAsValue,
13865
13866 /// A modification of an object which is not sequenced before the value
13867 /// computation of the expression, such as n++.
13868 UK_ModAsSideEffect,
13869
13870 UK_Count = UK_ModAsSideEffect + 1
13871 };
13872
13873 /// Bundle together a sequencing region and the expression corresponding
13874 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13875 struct Usage {
13876 const Expr *UsageExpr = nullptr;
13877 SequenceTree::Seq Seq;
13878
13879 Usage() = default;
13880 };
13881
13882 struct UsageInfo {
13883 Usage Uses[UK_Count];
13884
13885 /// Have we issued a diagnostic for this object already?
13886 bool Diagnosed = false;
13887
13888 UsageInfo();
13889 };
13890 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13891
13892 Sema &SemaRef;
13893
13894 /// Sequenced regions within the expression.
13895 SequenceTree Tree;
13896
13897 /// Declaration modifications and references which we have seen.
13898 UsageInfoMap UsageMap;
13899
13900 /// The region we are currently within.
13901 SequenceTree::Seq Region;
13902
13903 /// Filled in with declarations which were modified as a side-effect
13904 /// (that is, post-increment operations).
13905 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13906
13907 /// Expressions to check later. We defer checking these to reduce
13908 /// stack usage.
13909 SmallVectorImpl<const Expr *> &WorkList;
13910
13911 /// RAII object wrapping the visitation of a sequenced subexpression of an
13912 /// expression. At the end of this process, the side-effects of the evaluation
13913 /// become sequenced with respect to the value computation of the result, so
13914 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13915 /// UK_ModAsValue.
13916 struct SequencedSubexpression {
13917 SequencedSubexpression(SequenceChecker &Self)
13918 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13919 Self.ModAsSideEffect = &ModAsSideEffect;
13920 }
13921
13922 ~SequencedSubexpression() {
13923 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13924 // Add a new usage with usage kind UK_ModAsValue, and then restore
13925 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13926 // the previous one was empty).
13927 UsageInfo &UI = Self.UsageMap[M.first];
13928 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13929 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13930 SideEffectUsage = M.second;
13931 }
13932 Self.ModAsSideEffect = OldModAsSideEffect;
13933 }
13934
13935 SequenceChecker &Self;
13936 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13937 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13938 };
13939
13940 /// RAII object wrapping the visitation of a subexpression which we might
13941 /// choose to evaluate as a constant. If any subexpression is evaluated and
13942 /// found to be non-constant, this allows us to suppress the evaluation of
13943 /// the outer expression.
13944 class EvaluationTracker {
13945 public:
13946 EvaluationTracker(SequenceChecker &Self)
13947 : Self(Self), Prev(Self.EvalTracker) {
13948 Self.EvalTracker = this;
13949 }
13950
13951 ~EvaluationTracker() {
13952 Self.EvalTracker = Prev;
13953 if (Prev)
13954 Prev->EvalOK &= EvalOK;
13955 }
13956
13957 bool evaluate(const Expr *E, bool &Result) {
13958 if (!EvalOK || E->isValueDependent())
13959 return false;
13960 EvalOK = E->EvaluateAsBooleanCondition(
13961 Result, Self.SemaRef.Context,
13962 Self.SemaRef.isConstantEvaluatedContext());
13963 return EvalOK;
13964 }
13965
13966 private:
13967 SequenceChecker &Self;
13968 EvaluationTracker *Prev;
13969 bool EvalOK = true;
13970 } *EvalTracker = nullptr;
13971
13972 /// Find the object which is produced by the specified expression,
13973 /// if any.
13974 Object getObject(const Expr *E, bool Mod) const {
13975 E = E->IgnoreParenCasts();
13976 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13977 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13978 return getObject(UO->getSubExpr(), Mod);
13979 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13980 if (BO->getOpcode() == BO_Comma)
13981 return getObject(BO->getRHS(), Mod);
13982 if (Mod && BO->isAssignmentOp())
13983 return getObject(BO->getLHS(), Mod);
13984 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13985 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13986 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13987 return ME->getMemberDecl();
13988 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13989 // FIXME: If this is a reference, map through to its value.
13990 return DRE->getDecl();
13991 return nullptr;
13992 }
13993
13994 /// Note that an object \p O was modified or used by an expression
13995 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13996 /// the object \p O as obtained via the \p UsageMap.
13997 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13998 // Get the old usage for the given object and usage kind.
13999 Usage &U = UI.Uses[UK];
14000 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14001 // If we have a modification as side effect and are in a sequenced
14002 // subexpression, save the old Usage so that we can restore it later
14003 // in SequencedSubexpression::~SequencedSubexpression.
14004 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14005 ModAsSideEffect->push_back(std::make_pair(O, U));
14006 // Then record the new usage with the current sequencing region.
14007 U.UsageExpr = UsageExpr;
14008 U.Seq = Region;
14009 }
14010 }
14011
14012 /// Check whether a modification or use of an object \p O in an expression
14013 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14014 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14015 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14016 /// usage and false we are checking for a mod-use unsequenced usage.
14017 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14018 UsageKind OtherKind, bool IsModMod) {
14019 if (UI.Diagnosed)
14020 return;
14021
14022 const Usage &U = UI.Uses[OtherKind];
14023 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14024 return;
14025
14026 const Expr *Mod = U.UsageExpr;
14027 const Expr *ModOrUse = UsageExpr;
14028 if (OtherKind == UK_Use)
14029 std::swap(Mod, ModOrUse);
14030
14031 SemaRef.DiagRuntimeBehavior(
14032 Mod->getExprLoc(), {Mod, ModOrUse},
14033 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14034 : diag::warn_unsequenced_mod_use)
14035 << O << SourceRange(ModOrUse->getExprLoc()));
14036 UI.Diagnosed = true;
14037 }
14038
14039 // A note on note{Pre, Post}{Use, Mod}:
14040 //
14041 // (It helps to follow the algorithm with an expression such as
14042 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14043 // operations before C++17 and both are well-defined in C++17).
14044 //
14045 // When visiting a node which uses/modify an object we first call notePreUse
14046 // or notePreMod before visiting its sub-expression(s). At this point the
14047 // children of the current node have not yet been visited and so the eventual
14048 // uses/modifications resulting from the children of the current node have not
14049 // been recorded yet.
14050 //
14051 // We then visit the children of the current node. After that notePostUse or
14052 // notePostMod is called. These will 1) detect an unsequenced modification
14053 // as side effect (as in "k++ + k") and 2) add a new usage with the
14054 // appropriate usage kind.
14055 //
14056 // We also have to be careful that some operation sequences modification as
14057 // side effect as well (for example: || or ,). To account for this we wrap
14058 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14059 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14060 // which record usages which are modifications as side effect, and then
14061 // downgrade them (or more accurately restore the previous usage which was a
14062 // modification as side effect) when exiting the scope of the sequenced
14063 // subexpression.
14064
14065 void notePreUse(Object O, const Expr *UseExpr) {
14066 UsageInfo &UI = UsageMap[O];
14067 // Uses conflict with other modifications.
14068 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14069 }
14070
14071 void notePostUse(Object O, const Expr *UseExpr) {
14072 UsageInfo &UI = UsageMap[O];
14073 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14074 /*IsModMod=*/false);
14075 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14076 }
14077
14078 void notePreMod(Object O, const Expr *ModExpr) {
14079 UsageInfo &UI = UsageMap[O];
14080 // Modifications conflict with other modifications and with uses.
14081 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14082 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14083 }
14084
14085 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14086 UsageInfo &UI = UsageMap[O];
14087 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14088 /*IsModMod=*/true);
14089 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14090 }
14091
14092public:
14093 SequenceChecker(Sema &S, const Expr *E,
14094 SmallVectorImpl<const Expr *> &WorkList)
14095 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14096 Visit(E);
14097 // Silence a -Wunused-private-field since WorkList is now unused.
14098 // TODO: Evaluate if it can be used, and if not remove it.
14099 (void)this->WorkList;
14100 }
14101
14102 void VisitStmt(const Stmt *S) {
14103 // Skip all statements which aren't expressions for now.
14104 }
14105
14106 void VisitExpr(const Expr *E) {
14107 // By default, just recurse to evaluated subexpressions.
14108 Base::VisitStmt(E);
14109 }
14110
14111 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14112 for (auto *Sub : CSE->children()) {
14113 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14114 if (!ChildExpr)
14115 continue;
14116
14117 if (ChildExpr == CSE->getOperand())
14118 // Do not recurse over a CoroutineSuspendExpr's operand.
14119 // The operand is also a subexpression of getCommonExpr(), and
14120 // recursing into it directly could confuse object management
14121 // for the sake of sequence tracking.
14122 continue;
14123
14124 Visit(Sub);
14125 }
14126 }
14127
14128 void VisitCastExpr(const CastExpr *E) {
14129 Object O = Object();
14130 if (E->getCastKind() == CK_LValueToRValue)
14131 O = getObject(E->getSubExpr(), false);
14132
14133 if (O)
14134 notePreUse(O, E);
14135 VisitExpr(E);
14136 if (O)
14137 notePostUse(O, E);
14138 }
14139
14140 void VisitSequencedExpressions(const Expr *SequencedBefore,
14141 const Expr *SequencedAfter) {
14142 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14143 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14144 SequenceTree::Seq OldRegion = Region;
14145
14146 {
14147 SequencedSubexpression SeqBefore(*this);
14148 Region = BeforeRegion;
14149 Visit(SequencedBefore);
14150 }
14151
14152 Region = AfterRegion;
14153 Visit(SequencedAfter);
14154
14155 Region = OldRegion;
14156
14157 Tree.merge(BeforeRegion);
14158 Tree.merge(AfterRegion);
14159 }
14160
14161 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14162 // C++17 [expr.sub]p1:
14163 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14164 // expression E1 is sequenced before the expression E2.
14165 if (SemaRef.getLangOpts().CPlusPlus17)
14166 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14167 else {
14168 Visit(ASE->getLHS());
14169 Visit(ASE->getRHS());
14170 }
14171 }
14172
14173 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14174 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14175 void VisitBinPtrMem(const BinaryOperator *BO) {
14176 // C++17 [expr.mptr.oper]p4:
14177 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14178 // the expression E1 is sequenced before the expression E2.
14179 if (SemaRef.getLangOpts().CPlusPlus17)
14180 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14181 else {
14182 Visit(BO->getLHS());
14183 Visit(BO->getRHS());
14184 }
14185 }
14186
14187 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14188 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14189 void VisitBinShlShr(const BinaryOperator *BO) {
14190 // C++17 [expr.shift]p4:
14191 // The expression E1 is sequenced before the expression E2.
14192 if (SemaRef.getLangOpts().CPlusPlus17)
14193 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14194 else {
14195 Visit(BO->getLHS());
14196 Visit(BO->getRHS());
14197 }
14198 }
14199
14200 void VisitBinComma(const BinaryOperator *BO) {
14201 // C++11 [expr.comma]p1:
14202 // Every value computation and side effect associated with the left
14203 // expression is sequenced before every value computation and side
14204 // effect associated with the right expression.
14205 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14206 }
14207
14208 void VisitBinAssign(const BinaryOperator *BO) {
14209 SequenceTree::Seq RHSRegion;
14210 SequenceTree::Seq LHSRegion;
14211 if (SemaRef.getLangOpts().CPlusPlus17) {
14212 RHSRegion = Tree.allocate(Region);
14213 LHSRegion = Tree.allocate(Region);
14214 } else {
14215 RHSRegion = Region;
14216 LHSRegion = Region;
14217 }
14218 SequenceTree::Seq OldRegion = Region;
14219
14220 // C++11 [expr.ass]p1:
14221 // [...] the assignment is sequenced after the value computation
14222 // of the right and left operands, [...]
14223 //
14224 // so check it before inspecting the operands and update the
14225 // map afterwards.
14226 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14227 if (O)
14228 notePreMod(O, BO);
14229
14230 if (SemaRef.getLangOpts().CPlusPlus17) {
14231 // C++17 [expr.ass]p1:
14232 // [...] The right operand is sequenced before the left operand. [...]
14233 {
14234 SequencedSubexpression SeqBefore(*this);
14235 Region = RHSRegion;
14236 Visit(BO->getRHS());
14237 }
14238
14239 Region = LHSRegion;
14240 Visit(BO->getLHS());
14241
14242 if (O && isa<CompoundAssignOperator>(BO))
14243 notePostUse(O, BO);
14244
14245 } else {
14246 // C++11 does not specify any sequencing between the LHS and RHS.
14247 Region = LHSRegion;
14248 Visit(BO->getLHS());
14249
14250 if (O && isa<CompoundAssignOperator>(BO))
14251 notePostUse(O, BO);
14252
14253 Region = RHSRegion;
14254 Visit(BO->getRHS());
14255 }
14256
14257 // C++11 [expr.ass]p1:
14258 // the assignment is sequenced [...] before the value computation of the
14259 // assignment expression.
14260 // C11 6.5.16/3 has no such rule.
14261 Region = OldRegion;
14262 if (O)
14263 notePostMod(O, BO,
14264 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14265 : UK_ModAsSideEffect);
14266 if (SemaRef.getLangOpts().CPlusPlus17) {
14267 Tree.merge(RHSRegion);
14268 Tree.merge(LHSRegion);
14269 }
14270 }
14271
14272 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14273 VisitBinAssign(CAO);
14274 }
14275
14276 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14277 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14278 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14279 Object O = getObject(UO->getSubExpr(), true);
14280 if (!O)
14281 return VisitExpr(UO);
14282
14283 notePreMod(O, UO);
14284 Visit(UO->getSubExpr());
14285 // C++11 [expr.pre.incr]p1:
14286 // the expression ++x is equivalent to x+=1
14287 notePostMod(O, UO,
14288 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14289 : UK_ModAsSideEffect);
14290 }
14291
14292 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14293 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14294 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14295 Object O = getObject(UO->getSubExpr(), true);
14296 if (!O)
14297 return VisitExpr(UO);
14298
14299 notePreMod(O, UO);
14300 Visit(UO->getSubExpr());
14301 notePostMod(O, UO, UK_ModAsSideEffect);
14302 }
14303
14304 void VisitBinLOr(const BinaryOperator *BO) {
14305 // C++11 [expr.log.or]p2:
14306 // If the second expression is evaluated, every value computation and
14307 // side effect associated with the first expression is sequenced before
14308 // every value computation and side effect associated with the
14309 // second expression.
14310 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14311 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14312 SequenceTree::Seq OldRegion = Region;
14313
14314 EvaluationTracker Eval(*this);
14315 {
14316 SequencedSubexpression Sequenced(*this);
14317 Region = LHSRegion;
14318 Visit(BO->getLHS());
14319 }
14320
14321 // C++11 [expr.log.or]p1:
14322 // [...] the second operand is not evaluated if the first operand
14323 // evaluates to true.
14324 bool EvalResult = false;
14325 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14326 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14327 if (ShouldVisitRHS) {
14328 Region = RHSRegion;
14329 Visit(BO->getRHS());
14330 }
14331
14332 Region = OldRegion;
14333 Tree.merge(LHSRegion);
14334 Tree.merge(RHSRegion);
14335 }
14336
14337 void VisitBinLAnd(const BinaryOperator *BO) {
14338 // C++11 [expr.log.and]p2:
14339 // If the second expression is evaluated, every value computation and
14340 // side effect associated with the first expression is sequenced before
14341 // every value computation and side effect associated with the
14342 // second expression.
14343 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14344 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14345 SequenceTree::Seq OldRegion = Region;
14346
14347 EvaluationTracker Eval(*this);
14348 {
14349 SequencedSubexpression Sequenced(*this);
14350 Region = LHSRegion;
14351 Visit(BO->getLHS());
14352 }
14353
14354 // C++11 [expr.log.and]p1:
14355 // [...] the second operand is not evaluated if the first operand is false.
14356 bool EvalResult = false;
14357 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14358 bool ShouldVisitRHS = !EvalOK || EvalResult;
14359 if (ShouldVisitRHS) {
14360 Region = RHSRegion;
14361 Visit(BO->getRHS());
14362 }
14363
14364 Region = OldRegion;
14365 Tree.merge(LHSRegion);
14366 Tree.merge(RHSRegion);
14367 }
14368
14369 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14370 // C++11 [expr.cond]p1:
14371 // [...] Every value computation and side effect associated with the first
14372 // expression is sequenced before every value computation and side effect
14373 // associated with the second or third expression.
14374 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14375
14376 // No sequencing is specified between the true and false expression.
14377 // However since exactly one of both is going to be evaluated we can
14378 // consider them to be sequenced. This is needed to avoid warning on
14379 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14380 // both the true and false expressions because we can't evaluate x.
14381 // This will still allow us to detect an expression like (pre C++17)
14382 // "(x ? y += 1 : y += 2) = y".
14383 //
14384 // We don't wrap the visitation of the true and false expression with
14385 // SequencedSubexpression because we don't want to downgrade modifications
14386 // as side effect in the true and false expressions after the visition
14387 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14388 // not warn between the two "y++", but we should warn between the "y++"
14389 // and the "y".
14390 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14391 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14392 SequenceTree::Seq OldRegion = Region;
14393
14394 EvaluationTracker Eval(*this);
14395 {
14396 SequencedSubexpression Sequenced(*this);
14397 Region = ConditionRegion;
14398 Visit(CO->getCond());
14399 }
14400
14401 // C++11 [expr.cond]p1:
14402 // [...] The first expression is contextually converted to bool (Clause 4).
14403 // It is evaluated and if it is true, the result of the conditional
14404 // expression is the value of the second expression, otherwise that of the
14405 // third expression. Only one of the second and third expressions is
14406 // evaluated. [...]
14407 bool EvalResult = false;
14408 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14409 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14410 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14411 if (ShouldVisitTrueExpr) {
14412 Region = TrueRegion;
14413 Visit(CO->getTrueExpr());
14414 }
14415 if (ShouldVisitFalseExpr) {
14416 Region = FalseRegion;
14417 Visit(CO->getFalseExpr());
14418 }
14419
14420 Region = OldRegion;
14421 Tree.merge(ConditionRegion);
14422 Tree.merge(TrueRegion);
14423 Tree.merge(FalseRegion);
14424 }
14425
14426 void VisitCallExpr(const CallExpr *CE) {
14427 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14428
14429 if (CE->isUnevaluatedBuiltinCall(Context))
14430 return;
14431
14432 // C++11 [intro.execution]p15:
14433 // When calling a function [...], every value computation and side effect
14434 // associated with any argument expression, or with the postfix expression
14435 // designating the called function, is sequenced before execution of every
14436 // expression or statement in the body of the function [and thus before
14437 // the value computation of its result].
14438 SequencedSubexpression Sequenced(*this);
14439 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14440 // C++17 [expr.call]p5
14441 // The postfix-expression is sequenced before each expression in the
14442 // expression-list and any default argument. [...]
14443 SequenceTree::Seq CalleeRegion;
14444 SequenceTree::Seq OtherRegion;
14445 if (SemaRef.getLangOpts().CPlusPlus17) {
14446 CalleeRegion = Tree.allocate(Region);
14447 OtherRegion = Tree.allocate(Region);
14448 } else {
14449 CalleeRegion = Region;
14450 OtherRegion = Region;
14451 }
14452 SequenceTree::Seq OldRegion = Region;
14453
14454 // Visit the callee expression first.
14455 Region = CalleeRegion;
14456 if (SemaRef.getLangOpts().CPlusPlus17) {
14457 SequencedSubexpression Sequenced(*this);
14458 Visit(CE->getCallee());
14459 } else {
14460 Visit(CE->getCallee());
14461 }
14462
14463 // Then visit the argument expressions.
14464 Region = OtherRegion;
14465 for (const Expr *Argument : CE->arguments())
14466 Visit(Argument);
14467
14468 Region = OldRegion;
14469 if (SemaRef.getLangOpts().CPlusPlus17) {
14470 Tree.merge(CalleeRegion);
14471 Tree.merge(OtherRegion);
14472 }
14473 });
14474 }
14475
14476 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14477 // C++17 [over.match.oper]p2:
14478 // [...] the operator notation is first transformed to the equivalent
14479 // function-call notation as summarized in Table 12 (where @ denotes one
14480 // of the operators covered in the specified subclause). However, the
14481 // operands are sequenced in the order prescribed for the built-in
14482 // operator (Clause 8).
14483 //
14484 // From the above only overloaded binary operators and overloaded call
14485 // operators have sequencing rules in C++17 that we need to handle
14486 // separately.
14487 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14488 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14489 return VisitCallExpr(CXXOCE);
14490
14491 enum {
14492 NoSequencing,
14493 LHSBeforeRHS,
14494 RHSBeforeLHS,
14495 LHSBeforeRest
14496 } SequencingKind;
14497 switch (CXXOCE->getOperator()) {
14498 case OO_Equal:
14499 case OO_PlusEqual:
14500 case OO_MinusEqual:
14501 case OO_StarEqual:
14502 case OO_SlashEqual:
14503 case OO_PercentEqual:
14504 case OO_CaretEqual:
14505 case OO_AmpEqual:
14506 case OO_PipeEqual:
14507 case OO_LessLessEqual:
14508 case OO_GreaterGreaterEqual:
14509 SequencingKind = RHSBeforeLHS;
14510 break;
14511
14512 case OO_LessLess:
14513 case OO_GreaterGreater:
14514 case OO_AmpAmp:
14515 case OO_PipePipe:
14516 case OO_Comma:
14517 case OO_ArrowStar:
14518 case OO_Subscript:
14519 SequencingKind = LHSBeforeRHS;
14520 break;
14521
14522 case OO_Call:
14523 SequencingKind = LHSBeforeRest;
14524 break;
14525
14526 default:
14527 SequencingKind = NoSequencing;
14528 break;
14529 }
14530
14531 if (SequencingKind == NoSequencing)
14532 return VisitCallExpr(CXXOCE);
14533
14534 // This is a call, so all subexpressions are sequenced before the result.
14535 SequencedSubexpression Sequenced(*this);
14536
14537 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14538 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14539 "Should only get there with C++17 and above!");
14540 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14541 "Should only get there with an overloaded binary operator"
14542 " or an overloaded call operator!");
14543
14544 if (SequencingKind == LHSBeforeRest) {
14545 assert(CXXOCE->getOperator() == OO_Call &&
14546 "We should only have an overloaded call operator here!");
14547
14548 // This is very similar to VisitCallExpr, except that we only have the
14549 // C++17 case. The postfix-expression is the first argument of the
14550 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14551 // are in the following arguments.
14552 //
14553 // Note that we intentionally do not visit the callee expression since
14554 // it is just a decayed reference to a function.
14555 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14556 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14557 SequenceTree::Seq OldRegion = Region;
14558
14559 assert(CXXOCE->getNumArgs() >= 1 &&
14560 "An overloaded call operator must have at least one argument"
14561 " for the postfix-expression!");
14562 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14563 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14564 CXXOCE->getNumArgs() - 1);
14565
14566 // Visit the postfix-expression first.
14567 {
14568 Region = PostfixExprRegion;
14569 SequencedSubexpression Sequenced(*this);
14570 Visit(PostfixExpr);
14571 }
14572
14573 // Then visit the argument expressions.
14574 Region = ArgsRegion;
14575 for (const Expr *Arg : Args)
14576 Visit(Arg);
14577
14578 Region = OldRegion;
14579 Tree.merge(PostfixExprRegion);
14580 Tree.merge(ArgsRegion);
14581 } else {
14582 assert(CXXOCE->getNumArgs() == 2 &&
14583 "Should only have two arguments here!");
14584 assert((SequencingKind == LHSBeforeRHS ||
14585 SequencingKind == RHSBeforeLHS) &&
14586 "Unexpected sequencing kind!");
14587
14588 // We do not visit the callee expression since it is just a decayed
14589 // reference to a function.
14590 const Expr *E1 = CXXOCE->getArg(0);
14591 const Expr *E2 = CXXOCE->getArg(1);
14592 if (SequencingKind == RHSBeforeLHS)
14593 std::swap(E1, E2);
14594
14595 return VisitSequencedExpressions(E1, E2);
14596 }
14597 });
14598 }
14599
14600 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14601 // This is a call, so all subexpressions are sequenced before the result.
14602 SequencedSubexpression Sequenced(*this);
14603
14604 if (!CCE->isListInitialization())
14605 return VisitExpr(CCE);
14606
14607 // In C++11, list initializations are sequenced.
14608 SequenceExpressionsInOrder(
14609 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14610 }
14611
14612 void VisitInitListExpr(const InitListExpr *ILE) {
14613 if (!SemaRef.getLangOpts().CPlusPlus11)
14614 return VisitExpr(ILE);
14615
14616 // In C++11, list initializations are sequenced.
14617 SequenceExpressionsInOrder(ILE->inits());
14618 }
14619
14620 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14621 // C++20 parenthesized list initializations are sequenced. See C++20
14622 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14623 SequenceExpressionsInOrder(PLIE->getInitExprs());
14624 }
14625
14626private:
14627 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14629 SequenceTree::Seq Parent = Region;
14630 for (const Expr *E : ExpressionList) {
14631 if (!E)
14632 continue;
14633 Region = Tree.allocate(Parent);
14634 Elts.push_back(Region);
14635 Visit(E);
14636 }
14637
14638 // Forget that the initializers are sequenced.
14639 Region = Parent;
14640 for (unsigned I = 0; I < Elts.size(); ++I)
14641 Tree.merge(Elts[I]);
14642 }
14643};
14644
14645SequenceChecker::UsageInfo::UsageInfo() = default;
14646
14647} // namespace
14648
14649void Sema::CheckUnsequencedOperations(const Expr *E) {
14650 SmallVector<const Expr *, 8> WorkList;
14651 WorkList.push_back(E);
14652 while (!WorkList.empty()) {
14653 const Expr *Item = WorkList.pop_back_val();
14654 SequenceChecker(*this, Item, WorkList);
14655 }
14656}
14657
14658void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14659 bool IsConstexpr) {
14660 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14661 IsConstexpr || isa<ConstantExpr>(E));
14662 CheckImplicitConversions(E, CheckLoc);
14663 if (!E->isInstantiationDependent())
14664 CheckUnsequencedOperations(E);
14665 if (!IsConstexpr && !E->isValueDependent())
14666 CheckForIntOverflow(E);
14667}
14668
14669void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14670 FieldDecl *BitField,
14671 Expr *Init) {
14672 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14673}
14674
14676 SourceLocation Loc) {
14677 if (!PType->isVariablyModifiedType())
14678 return;
14679 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14680 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14681 return;
14682 }
14683 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14684 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14685 return;
14686 }
14687 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14688 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14689 return;
14690 }
14691
14692 const ArrayType *AT = S.Context.getAsArrayType(PType);
14693 if (!AT)
14694 return;
14695
14698 return;
14699 }
14700
14701 S.Diag(Loc, diag::err_array_star_in_function_definition);
14702}
14703
14705 bool CheckParameterNames) {
14706 bool HasInvalidParm = false;
14707 for (ParmVarDecl *Param : Parameters) {
14708 assert(Param && "null in a parameter list");
14709 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14710 // function declarator that is part of a function definition of
14711 // that function shall not have incomplete type.
14712 //
14713 // C++23 [dcl.fct.def.general]/p2
14714 // The type of a parameter [...] for a function definition
14715 // shall not be a (possibly cv-qualified) class type that is incomplete
14716 // or abstract within the function body unless the function is deleted.
14717 if (!Param->isInvalidDecl() &&
14718 (RequireCompleteType(Param->getLocation(), Param->getType(),
14719 diag::err_typecheck_decl_incomplete_type) ||
14720 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14721 diag::err_abstract_type_in_decl,
14723 Param->setInvalidDecl();
14724 HasInvalidParm = true;
14725 }
14726
14727 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14728 // declaration of each parameter shall include an identifier.
14729 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14730 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14731 // Diagnose this as an extension in C17 and earlier.
14732 if (!getLangOpts().C23)
14733 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14734 }
14735
14736 // C99 6.7.5.3p12:
14737 // If the function declarator is not part of a definition of that
14738 // function, parameters may have incomplete type and may use the [*]
14739 // notation in their sequences of declarator specifiers to specify
14740 // variable length array types.
14741 QualType PType = Param->getOriginalType();
14742 // FIXME: This diagnostic should point the '[*]' if source-location
14743 // information is added for it.
14744 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14745
14746 // If the parameter is a c++ class type and it has to be destructed in the
14747 // callee function, declare the destructor so that it can be called by the
14748 // callee function. Do not perform any direct access check on the dtor here.
14749 if (!Param->isInvalidDecl()) {
14750 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14751 if (!ClassDecl->isInvalidDecl() &&
14752 !ClassDecl->hasIrrelevantDestructor() &&
14753 !ClassDecl->isDependentContext() &&
14754 ClassDecl->isParamDestroyedInCallee()) {
14756 MarkFunctionReferenced(Param->getLocation(), Destructor);
14757 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14758 }
14759 }
14760 }
14761
14762 // Parameters with the pass_object_size attribute only need to be marked
14763 // constant at function definitions. Because we lack information about
14764 // whether we're on a declaration or definition when we're instantiating the
14765 // attribute, we need to check for constness here.
14766 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14767 if (!Param->getType().isConstQualified())
14768 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14769 << Attr->getSpelling() << 1;
14770
14771 // Check for parameter names shadowing fields from the class.
14772 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14773 // The owning context for the parameter should be the function, but we
14774 // want to see if this function's declaration context is a record.
14775 DeclContext *DC = Param->getDeclContext();
14776 if (DC && DC->isFunctionOrMethod()) {
14777 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14778 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14779 RD, /*DeclIsField*/ false);
14780 }
14781 }
14782
14783 if (!Param->isInvalidDecl() &&
14784 Param->getOriginalType()->isWebAssemblyTableType()) {
14785 Param->setInvalidDecl();
14786 HasInvalidParm = true;
14787 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14788 }
14789 }
14790
14791 return HasInvalidParm;
14792}
14793
14794std::optional<std::pair<
14796 *E,
14798 &Ctx);
14799
14800/// Compute the alignment and offset of the base class object given the
14801/// derived-to-base cast expression and the alignment and offset of the derived
14802/// class object.
14803static std::pair<CharUnits, CharUnits>
14805 CharUnits BaseAlignment, CharUnits Offset,
14806 ASTContext &Ctx) {
14807 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14808 ++PathI) {
14809 const CXXBaseSpecifier *Base = *PathI;
14810 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14811 if (Base->isVirtual()) {
14812 // The complete object may have a lower alignment than the non-virtual
14813 // alignment of the base, in which case the base may be misaligned. Choose
14814 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14815 // conservative lower bound of the complete object alignment.
14816 CharUnits NonVirtualAlignment =
14818 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14819 Offset = CharUnits::Zero();
14820 } else {
14821 const ASTRecordLayout &RL =
14822 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14823 Offset += RL.getBaseClassOffset(BaseDecl);
14824 }
14825 DerivedType = Base->getType();
14826 }
14827
14828 return std::make_pair(BaseAlignment, Offset);
14829}
14830
14831/// Compute the alignment and offset of a binary additive operator.
14832static std::optional<std::pair<CharUnits, CharUnits>>
14834 bool IsSub, ASTContext &Ctx) {
14835 QualType PointeeType = PtrE->getType()->getPointeeType();
14836
14837 if (!PointeeType->isConstantSizeType())
14838 return std::nullopt;
14839
14840 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14841
14842 if (!P)
14843 return std::nullopt;
14844
14845 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14846 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14847 CharUnits Offset = EltSize * IdxRes->getExtValue();
14848 if (IsSub)
14849 Offset = -Offset;
14850 return std::make_pair(P->first, P->second + Offset);
14851 }
14852
14853 // If the integer expression isn't a constant expression, compute the lower
14854 // bound of the alignment using the alignment and offset of the pointer
14855 // expression and the element size.
14856 return std::make_pair(
14857 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14858 CharUnits::Zero());
14859}
14860
14861/// This helper function takes an lvalue expression and returns the alignment of
14862/// a VarDecl and a constant offset from the VarDecl.
14863std::optional<std::pair<
14864 CharUnits,
14866 ASTContext &Ctx) {
14867 E = E->IgnoreParens();
14868 switch (E->getStmtClass()) {
14869 default:
14870 break;
14871 case Stmt::CStyleCastExprClass:
14872 case Stmt::CXXStaticCastExprClass:
14873 case Stmt::ImplicitCastExprClass: {
14874 auto *CE = cast<CastExpr>(E);
14875 const Expr *From = CE->getSubExpr();
14876 switch (CE->getCastKind()) {
14877 default:
14878 break;
14879 case CK_NoOp:
14880 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14881 case CK_UncheckedDerivedToBase:
14882 case CK_DerivedToBase: {
14883 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14884 if (!P)
14885 break;
14886 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14887 P->second, Ctx);
14888 }
14889 }
14890 break;
14891 }
14892 case Stmt::ArraySubscriptExprClass: {
14893 auto *ASE = cast<ArraySubscriptExpr>(E);
14895 false, Ctx);
14896 }
14897 case Stmt::DeclRefExprClass: {
14898 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14899 // FIXME: If VD is captured by copy or is an escaping __block variable,
14900 // use the alignment of VD's type.
14901 if (!VD->getType()->isReferenceType()) {
14902 // Dependent alignment cannot be resolved -> bail out.
14903 if (VD->hasDependentAlignment())
14904 break;
14905 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14906 }
14907 if (VD->hasInit())
14908 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14909 }
14910 break;
14911 }
14912 case Stmt::MemberExprClass: {
14913 auto *ME = cast<MemberExpr>(E);
14914 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14915 if (!FD || FD->getType()->isReferenceType() ||
14916 FD->getParent()->isInvalidDecl())
14917 break;
14918 std::optional<std::pair<CharUnits, CharUnits>> P;
14919 if (ME->isArrow())
14920 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14921 else
14922 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14923 if (!P)
14924 break;
14925 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14926 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14927 return std::make_pair(P->first,
14928 P->second + CharUnits::fromQuantity(Offset));
14929 }
14930 case Stmt::UnaryOperatorClass: {
14931 auto *UO = cast<UnaryOperator>(E);
14932 switch (UO->getOpcode()) {
14933 default:
14934 break;
14935 case UO_Deref:
14937 }
14938 break;
14939 }
14940 case Stmt::BinaryOperatorClass: {
14941 auto *BO = cast<BinaryOperator>(E);
14942 auto Opcode = BO->getOpcode();
14943 switch (Opcode) {
14944 default:
14945 break;
14946 case BO_Comma:
14948 }
14949 break;
14950 }
14951 }
14952 return std::nullopt;
14953}
14954
14955/// This helper function takes a pointer expression and returns the alignment of
14956/// a VarDecl and a constant offset from the VarDecl.
14957std::optional<std::pair<
14959 *E,
14961 &Ctx) {
14962 E = E->IgnoreParens();
14963 switch (E->getStmtClass()) {
14964 default:
14965 break;
14966 case Stmt::CStyleCastExprClass:
14967 case Stmt::CXXStaticCastExprClass:
14968 case Stmt::ImplicitCastExprClass: {
14969 auto *CE = cast<CastExpr>(E);
14970 const Expr *From = CE->getSubExpr();
14971 switch (CE->getCastKind()) {
14972 default:
14973 break;
14974 case CK_NoOp:
14975 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14976 case CK_ArrayToPointerDecay:
14977 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14978 case CK_UncheckedDerivedToBase:
14979 case CK_DerivedToBase: {
14980 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14981 if (!P)
14982 break;
14984 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14985 }
14986 }
14987 break;
14988 }
14989 case Stmt::CXXThisExprClass: {
14990 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14992 return std::make_pair(Alignment, CharUnits::Zero());
14993 }
14994 case Stmt::UnaryOperatorClass: {
14995 auto *UO = cast<UnaryOperator>(E);
14996 if (UO->getOpcode() == UO_AddrOf)
14998 break;
14999 }
15000 case Stmt::BinaryOperatorClass: {
15001 auto *BO = cast<BinaryOperator>(E);
15002 auto Opcode = BO->getOpcode();
15003 switch (Opcode) {
15004 default:
15005 break;
15006 case BO_Add:
15007 case BO_Sub: {
15008 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15009 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15010 std::swap(LHS, RHS);
15011 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15012 Ctx);
15013 }
15014 case BO_Comma:
15015 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15016 }
15017 break;
15018 }
15019 }
15020 return std::nullopt;
15021}
15022
15024 // See if we can compute the alignment of a VarDecl and an offset from it.
15025 std::optional<std::pair<CharUnits, CharUnits>> P =
15027
15028 if (P)
15029 return P->first.alignmentAtOffset(P->second);
15030
15031 // If that failed, return the type's alignment.
15033}
15034
15036 // This is actually a lot of work to potentially be doing on every
15037 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15038 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15039 return;
15040
15041 // Ignore dependent types.
15042 if (T->isDependentType() || Op->getType()->isDependentType())
15043 return;
15044
15045 // Require that the destination be a pointer type.
15046 const PointerType *DestPtr = T->getAs<PointerType>();
15047 if (!DestPtr) return;
15048
15049 // If the destination has alignment 1, we're done.
15050 QualType DestPointee = DestPtr->getPointeeType();
15051 if (DestPointee->isIncompleteType()) return;
15052 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15053 if (DestAlign.isOne()) return;
15054
15055 // Require that the source be a pointer type.
15056 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15057 if (!SrcPtr) return;
15058 QualType SrcPointee = SrcPtr->getPointeeType();
15059
15060 // Explicitly allow casts from cv void*. We already implicitly
15061 // allowed casts to cv void*, since they have alignment 1.
15062 // Also allow casts involving incomplete types, which implicitly
15063 // includes 'void'.
15064 if (SrcPointee->isIncompleteType()) return;
15065
15066 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15067
15068 if (SrcAlign >= DestAlign) return;
15069
15070 Diag(TRange.getBegin(), diag::warn_cast_align)
15071 << Op->getType() << T
15072 << static_cast<unsigned>(SrcAlign.getQuantity())
15073 << static_cast<unsigned>(DestAlign.getQuantity())
15074 << TRange << Op->getSourceRange();
15075}
15076
15077void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15078 const ArraySubscriptExpr *ASE,
15079 bool AllowOnePastEnd, bool IndexNegated) {
15080 // Already diagnosed by the constant evaluator.
15082 return;
15083
15084 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15085 if (IndexExpr->isValueDependent())
15086 return;
15087
15088 const Type *EffectiveType =
15090 BaseExpr = BaseExpr->IgnoreParenCasts();
15091 const ConstantArrayType *ArrayTy =
15092 Context.getAsConstantArrayType(BaseExpr->getType());
15093
15095 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15096
15097 const Type *BaseType =
15098 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15099 bool IsUnboundedArray =
15100 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15101 Context, StrictFlexArraysLevel,
15102 /*IgnoreTemplateOrMacroSubstitution=*/true);
15103 if (EffectiveType->isDependentType() ||
15104 (!IsUnboundedArray && BaseType->isDependentType()))
15105 return;
15106
15108 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15109 return;
15110
15111 llvm::APSInt index = Result.Val.getInt();
15112 if (IndexNegated) {
15113 index.setIsUnsigned(false);
15114 index = -index;
15115 }
15116
15117 if (IsUnboundedArray) {
15118 if (EffectiveType->isFunctionType())
15119 return;
15120 if (index.isUnsigned() || !index.isNegative()) {
15121 const auto &ASTC = getASTContext();
15122 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15123 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15124 if (index.getBitWidth() < AddrBits)
15125 index = index.zext(AddrBits);
15126 std::optional<CharUnits> ElemCharUnits =
15127 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15128 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15129 // pointer) bounds-checking isn't meaningful.
15130 if (!ElemCharUnits || ElemCharUnits->isZero())
15131 return;
15132 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15133 // If index has more active bits than address space, we already know
15134 // we have a bounds violation to warn about. Otherwise, compute
15135 // address of (index + 1)th element, and warn about bounds violation
15136 // only if that address exceeds address space.
15137 if (index.getActiveBits() <= AddrBits) {
15138 bool Overflow;
15139 llvm::APInt Product(index);
15140 Product += 1;
15141 Product = Product.umul_ov(ElemBytes, Overflow);
15142 if (!Overflow && Product.getActiveBits() <= AddrBits)
15143 return;
15144 }
15145
15146 // Need to compute max possible elements in address space, since that
15147 // is included in diag message.
15148 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15149 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15150 MaxElems += 1;
15151 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15152 MaxElems = MaxElems.udiv(ElemBytes);
15153
15154 unsigned DiagID =
15155 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15156 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15157
15158 // Diag message shows element size in bits and in "bytes" (platform-
15159 // dependent CharUnits)
15160 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15161 PDiag(DiagID) << index << AddrBits
15162 << (unsigned)ASTC.toBits(*ElemCharUnits)
15163 << ElemBytes << MaxElems
15164 << MaxElems.getZExtValue()
15165 << IndexExpr->getSourceRange());
15166
15167 const NamedDecl *ND = nullptr;
15168 // Try harder to find a NamedDecl to point at in the note.
15169 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15170 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15171 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15172 ND = DRE->getDecl();
15173 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15174 ND = ME->getMemberDecl();
15175
15176 if (ND)
15177 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15178 PDiag(diag::note_array_declared_here) << ND);
15179 }
15180 return;
15181 }
15182
15183 if (index.isUnsigned() || !index.isNegative()) {
15184 // It is possible that the type of the base expression after
15185 // IgnoreParenCasts is incomplete, even though the type of the base
15186 // expression before IgnoreParenCasts is complete (see PR39746 for an
15187 // example). In this case we have no information about whether the array
15188 // access exceeds the array bounds. However we can still diagnose an array
15189 // access which precedes the array bounds.
15190 if (BaseType->isIncompleteType())
15191 return;
15192
15193 llvm::APInt size = ArrayTy->getSize();
15194
15195 if (BaseType != EffectiveType) {
15196 // Make sure we're comparing apples to apples when comparing index to
15197 // size.
15198 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15199 uint64_t array_typesize = Context.getTypeSize(BaseType);
15200
15201 // Handle ptrarith_typesize being zero, such as when casting to void*.
15202 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15203 if (!ptrarith_typesize)
15204 ptrarith_typesize = Context.getCharWidth();
15205
15206 if (ptrarith_typesize != array_typesize) {
15207 // There's a cast to a different size type involved.
15208 uint64_t ratio = array_typesize / ptrarith_typesize;
15209
15210 // TODO: Be smarter about handling cases where array_typesize is not a
15211 // multiple of ptrarith_typesize.
15212 if (ptrarith_typesize * ratio == array_typesize)
15213 size *= llvm::APInt(size.getBitWidth(), ratio);
15214 }
15215 }
15216
15217 if (size.getBitWidth() > index.getBitWidth())
15218 index = index.zext(size.getBitWidth());
15219 else if (size.getBitWidth() < index.getBitWidth())
15220 size = size.zext(index.getBitWidth());
15221
15222 // For array subscripting the index must be less than size, but for pointer
15223 // arithmetic also allow the index (offset) to be equal to size since
15224 // computing the next address after the end of the array is legal and
15225 // commonly done e.g. in C++ iterators and range-based for loops.
15226 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15227 return;
15228
15229 // Suppress the warning if the subscript expression (as identified by the
15230 // ']' location) and the index expression are both from macro expansions
15231 // within a system header.
15232 if (ASE) {
15233 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15234 ASE->getRBracketLoc());
15235 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15236 SourceLocation IndexLoc =
15237 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15238 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15239 return;
15240 }
15241 }
15242
15243 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15244 : diag::warn_ptr_arith_exceeds_bounds;
15245 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15246 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15247
15248 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15249 PDiag(DiagID)
15250 << index << ArrayTy->desugar() << CastMsg
15251 << CastMsgTy << IndexExpr->getSourceRange());
15252 } else {
15253 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15254 if (!ASE) {
15255 DiagID = diag::warn_ptr_arith_precedes_bounds;
15256 if (index.isNegative()) index = -index;
15257 }
15258
15259 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15260 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15261 }
15262
15263 const NamedDecl *ND = nullptr;
15264 // Try harder to find a NamedDecl to point at in the note.
15265 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15266 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15267 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15268 ND = DRE->getDecl();
15269 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15270 ND = ME->getMemberDecl();
15271
15272 if (ND)
15273 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15274 PDiag(diag::note_array_declared_here) << ND);
15275}
15276
15277void Sema::CheckArrayAccess(const Expr *expr) {
15278 int AllowOnePastEnd = 0;
15279 while (expr) {
15280 expr = expr->IgnoreParenImpCasts();
15281 switch (expr->getStmtClass()) {
15282 case Stmt::ArraySubscriptExprClass: {
15283 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15284 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15285 AllowOnePastEnd > 0);
15286 expr = ASE->getBase();
15287 break;
15288 }
15289 case Stmt::MemberExprClass: {
15290 expr = cast<MemberExpr>(expr)->getBase();
15291 break;
15292 }
15293 case Stmt::ArraySectionExprClass: {
15294 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15295 // FIXME: We should probably be checking all of the elements to the
15296 // 'length' here as well.
15297 if (ASE->getLowerBound())
15298 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15299 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15300 return;
15301 }
15302 case Stmt::UnaryOperatorClass: {
15303 // Only unwrap the * and & unary operators
15304 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15305 expr = UO->getSubExpr();
15306 switch (UO->getOpcode()) {
15307 case UO_AddrOf:
15308 AllowOnePastEnd++;
15309 break;
15310 case UO_Deref:
15311 AllowOnePastEnd--;
15312 break;
15313 default:
15314 return;
15315 }
15316 break;
15317 }
15318 case Stmt::ConditionalOperatorClass: {
15319 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15320 if (const Expr *lhs = cond->getLHS())
15321 CheckArrayAccess(lhs);
15322 if (const Expr *rhs = cond->getRHS())
15323 CheckArrayAccess(rhs);
15324 return;
15325 }
15326 case Stmt::CXXOperatorCallExprClass: {
15327 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15328 for (const auto *Arg : OCE->arguments())
15329 CheckArrayAccess(Arg);
15330 return;
15331 }
15332 default:
15333 return;
15334 }
15335 }
15336}
15337
15339 Expr *RHS, bool isProperty) {
15340 // Check if RHS is an Objective-C object literal, which also can get
15341 // immediately zapped in a weak reference. Note that we explicitly
15342 // allow ObjCStringLiterals, since those are designed to never really die.
15343 RHS = RHS->IgnoreParenImpCasts();
15344
15345 // This enum needs to match with the 'select' in
15346 // warn_objc_arc_literal_assign (off-by-1).
15348 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15349 return false;
15350
15351 S.Diag(Loc, diag::warn_arc_literal_assign)
15352 << (unsigned) Kind
15353 << (isProperty ? 0 : 1)
15354 << RHS->getSourceRange();
15355
15356 return true;
15357}
15358
15361 Expr *RHS, bool isProperty) {
15362 // Strip off any implicit cast added to get to the one ARC-specific.
15363 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15364 if (cast->getCastKind() == CK_ARCConsumeObject) {
15365 S.Diag(Loc, diag::warn_arc_retained_assign)
15367 << (isProperty ? 0 : 1)
15368 << RHS->getSourceRange();
15369 return true;
15370 }
15371 RHS = cast->getSubExpr();
15372 }
15373
15374 if (LT == Qualifiers::OCL_Weak &&
15375 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15376 return true;
15377
15378 return false;
15379}
15380
15382 QualType LHS, Expr *RHS) {
15384
15386 return false;
15387
15388 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15389 return true;
15390
15391 return false;
15392}
15393
15395 Expr *LHS, Expr *RHS) {
15396 QualType LHSType;
15397 // PropertyRef on LHS type need be directly obtained from
15398 // its declaration as it has a PseudoType.
15400 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15401 if (PRE && !PRE->isImplicitProperty()) {
15402 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15403 if (PD)
15404 LHSType = PD->getType();
15405 }
15406
15407 if (LHSType.isNull())
15408 LHSType = LHS->getType();
15409
15411
15412 if (LT == Qualifiers::OCL_Weak) {
15413 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15415 }
15416
15417 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15418 return;
15419
15420 // FIXME. Check for other life times.
15421 if (LT != Qualifiers::OCL_None)
15422 return;
15423
15424 if (PRE) {
15425 if (PRE->isImplicitProperty())
15426 return;
15427 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15428 if (!PD)
15429 return;
15430
15431 unsigned Attributes = PD->getPropertyAttributes();
15432 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15433 // when 'assign' attribute was not explicitly specified
15434 // by user, ignore it and rely on property type itself
15435 // for lifetime info.
15436 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15437 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15438 LHSType->isObjCRetainableType())
15439 return;
15440
15441 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15442 if (cast->getCastKind() == CK_ARCConsumeObject) {
15443 Diag(Loc, diag::warn_arc_retained_property_assign)
15444 << RHS->getSourceRange();
15445 return;
15446 }
15447 RHS = cast->getSubExpr();
15448 }
15449 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15450 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15451 return;
15452 }
15453 }
15454}
15455
15456//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15457
15458static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15459 SourceLocation StmtLoc,
15460 const NullStmt *Body) {
15461 // Do not warn if the body is a macro that expands to nothing, e.g:
15462 //
15463 // #define CALL(x)
15464 // if (condition)
15465 // CALL(0);
15466 if (Body->hasLeadingEmptyMacro())
15467 return false;
15468
15469 // Get line numbers of statement and body.
15470 bool StmtLineInvalid;
15471 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15472 &StmtLineInvalid);
15473 if (StmtLineInvalid)
15474 return false;
15475
15476 bool BodyLineInvalid;
15477 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15478 &BodyLineInvalid);
15479 if (BodyLineInvalid)
15480 return false;
15481
15482 // Warn if null statement and body are on the same line.
15483 if (StmtLine != BodyLine)
15484 return false;
15485
15486 return true;
15487}
15488
15490 const Stmt *Body,
15491 unsigned DiagID) {
15492 // Since this is a syntactic check, don't emit diagnostic for template
15493 // instantiations, this just adds noise.
15495 return;
15496
15497 // The body should be a null statement.
15498 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15499 if (!NBody)
15500 return;
15501
15502 // Do the usual checks.
15503 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15504 return;
15505
15506 Diag(NBody->getSemiLoc(), DiagID);
15507 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15508}
15509
15511 const Stmt *PossibleBody) {
15512 assert(!CurrentInstantiationScope); // Ensured by caller
15513
15514 SourceLocation StmtLoc;
15515 const Stmt *Body;
15516 unsigned DiagID;
15517 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15518 StmtLoc = FS->getRParenLoc();
15519 Body = FS->getBody();
15520 DiagID = diag::warn_empty_for_body;
15521 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15522 StmtLoc = WS->getRParenLoc();
15523 Body = WS->getBody();
15524 DiagID = diag::warn_empty_while_body;
15525 } else
15526 return; // Neither `for' nor `while'.
15527
15528 // The body should be a null statement.
15529 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15530 if (!NBody)
15531 return;
15532
15533 // Skip expensive checks if diagnostic is disabled.
15534 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15535 return;
15536
15537 // Do the usual checks.
15538 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15539 return;
15540
15541 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15542 // noise level low, emit diagnostics only if for/while is followed by a
15543 // CompoundStmt, e.g.:
15544 // for (int i = 0; i < n; i++);
15545 // {
15546 // a(i);
15547 // }
15548 // or if for/while is followed by a statement with more indentation
15549 // than for/while itself:
15550 // for (int i = 0; i < n; i++);
15551 // a(i);
15552 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15553 if (!ProbableTypo) {
15554 bool BodyColInvalid;
15555 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15556 PossibleBody->getBeginLoc(), &BodyColInvalid);
15557 if (BodyColInvalid)
15558 return;
15559
15560 bool StmtColInvalid;
15561 unsigned StmtCol =
15562 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15563 if (StmtColInvalid)
15564 return;
15565
15566 if (BodyCol > StmtCol)
15567 ProbableTypo = true;
15568 }
15569
15570 if (ProbableTypo) {
15571 Diag(NBody->getSemiLoc(), DiagID);
15572 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15573 }
15574}
15575
15576//===--- CHECK: Warn on self move with std::move. -------------------------===//
15577
15578void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15579 SourceLocation OpLoc) {
15580 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15581 return;
15582
15584 return;
15585
15586 // Strip parens and casts away.
15587 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15588 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15589
15590 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15591 // which we can treat as an inlined std::move
15592 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15593 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15594 RHSExpr = CE->getArg(0);
15595 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15596 CXXSCE && CXXSCE->isXValue())
15597 RHSExpr = CXXSCE->getSubExpr();
15598 else
15599 return;
15600
15601 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15602 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15603
15604 // Two DeclRefExpr's, check that the decls are the same.
15605 if (LHSDeclRef && RHSDeclRef) {
15606 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15607 return;
15608 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15609 RHSDeclRef->getDecl()->getCanonicalDecl())
15610 return;
15611
15612 auto D = Diag(OpLoc, diag::warn_self_move)
15613 << LHSExpr->getType() << LHSExpr->getSourceRange()
15614 << RHSExpr->getSourceRange();
15615 if (const FieldDecl *F =
15617 D << 1 << F
15618 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15619 else
15620 D << 0;
15621 return;
15622 }
15623
15624 // Member variables require a different approach to check for self moves.
15625 // MemberExpr's are the same if every nested MemberExpr refers to the same
15626 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15627 // the base Expr's are CXXThisExpr's.
15628 const Expr *LHSBase = LHSExpr;
15629 const Expr *RHSBase = RHSExpr;
15630 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15631 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15632 if (!LHSME || !RHSME)
15633 return;
15634
15635 while (LHSME && RHSME) {
15636 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15637 RHSME->getMemberDecl()->getCanonicalDecl())
15638 return;
15639
15640 LHSBase = LHSME->getBase();
15641 RHSBase = RHSME->getBase();
15642 LHSME = dyn_cast<MemberExpr>(LHSBase);
15643 RHSME = dyn_cast<MemberExpr>(RHSBase);
15644 }
15645
15646 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15647 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15648 if (LHSDeclRef && RHSDeclRef) {
15649 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15650 return;
15651 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15652 RHSDeclRef->getDecl()->getCanonicalDecl())
15653 return;
15654
15655 Diag(OpLoc, diag::warn_self_move)
15656 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15657 << RHSExpr->getSourceRange();
15658 return;
15659 }
15660
15661 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15662 Diag(OpLoc, diag::warn_self_move)
15663 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15664 << RHSExpr->getSourceRange();
15665}
15666
15667//===--- Layout compatibility ----------------------------------------------//
15668
15669static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15670
15671/// Check if two enumeration types are layout-compatible.
15672static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15673 const EnumDecl *ED2) {
15674 // C++11 [dcl.enum] p8:
15675 // Two enumeration types are layout-compatible if they have the same
15676 // underlying type.
15677 return ED1->isComplete() && ED2->isComplete() &&
15678 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15679}
15680
15681/// Check if two fields are layout-compatible.
15682/// Can be used on union members, which are exempt from alignment requirement
15683/// of common initial sequence.
15684static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15685 const FieldDecl *Field2,
15686 bool AreUnionMembers = false) {
15687#ifndef NDEBUG
15688 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15689 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15690 assert(((Field1Parent->isStructureOrClassType() &&
15691 Field2Parent->isStructureOrClassType()) ||
15692 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15693 "Can't evaluate layout compatibility between a struct field and a "
15694 "union field.");
15695 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15696 (AreUnionMembers && Field1Parent->isUnionType())) &&
15697 "AreUnionMembers should be 'true' for union fields (only).");
15698#endif
15699
15700 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15701 return false;
15702
15703 if (Field1->isBitField() != Field2->isBitField())
15704 return false;
15705
15706 if (Field1->isBitField()) {
15707 // Make sure that the bit-fields are the same length.
15708 unsigned Bits1 = Field1->getBitWidthValue();
15709 unsigned Bits2 = Field2->getBitWidthValue();
15710
15711 if (Bits1 != Bits2)
15712 return false;
15713 }
15714
15715 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15716 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15717 return false;
15718
15719 if (!AreUnionMembers &&
15720 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15721 return false;
15722
15723 return true;
15724}
15725
15726/// Check if two standard-layout structs are layout-compatible.
15727/// (C++11 [class.mem] p17)
15728static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15729 const RecordDecl *RD2) {
15730 // Get to the class where the fields are declared
15731 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15732 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15733
15734 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15735 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15736
15737 // Check the fields.
15738 return llvm::equal(RD1->fields(), RD2->fields(),
15739 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15740 return isLayoutCompatible(C, F1, F2);
15741 });
15742}
15743
15744/// Check if two standard-layout unions are layout-compatible.
15745/// (C++11 [class.mem] p18)
15746static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15747 const RecordDecl *RD2) {
15748 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15749 RD2->fields());
15750
15751 for (auto *Field1 : RD1->fields()) {
15752 auto I = UnmatchedFields.begin();
15753 auto E = UnmatchedFields.end();
15754
15755 for ( ; I != E; ++I) {
15756 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15757 bool Result = UnmatchedFields.erase(*I);
15758 (void) Result;
15759 assert(Result);
15760 break;
15761 }
15762 }
15763 if (I == E)
15764 return false;
15765 }
15766
15767 return UnmatchedFields.empty();
15768}
15769
15770static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15771 const RecordDecl *RD2) {
15772 if (RD1->isUnion() != RD2->isUnion())
15773 return false;
15774
15775 if (RD1->isUnion())
15776 return isLayoutCompatibleUnion(C, RD1, RD2);
15777 else
15778 return isLayoutCompatibleStruct(C, RD1, RD2);
15779}
15780
15781/// Check if two types are layout-compatible in C++11 sense.
15782static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15783 if (T1.isNull() || T2.isNull())
15784 return false;
15785
15786 // C++20 [basic.types] p11:
15787 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15788 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15789 // or layout-compatible standard-layout class types (11.4).
15792
15793 if (C.hasSameType(T1, T2))
15794 return true;
15795
15796 const Type::TypeClass TC1 = T1->getTypeClass();
15797 const Type::TypeClass TC2 = T2->getTypeClass();
15798
15799 if (TC1 != TC2)
15800 return false;
15801
15802 if (TC1 == Type::Enum)
15803 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15804 if (TC1 == Type::Record) {
15805 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15806 return false;
15807
15809 T2->castAsRecordDecl());
15810 }
15811
15812 return false;
15813}
15814
15816 return isLayoutCompatible(getASTContext(), T1, T2);
15817}
15818
15819//===-------------- Pointer interconvertibility ----------------------------//
15820
15822 const TypeSourceInfo *Derived) {
15823 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15824 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15825
15826 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15827 getASTContext().hasSameType(BaseT, DerivedT))
15828 return true;
15829
15830 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15831 return false;
15832
15833 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15834 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15835 return true;
15836
15837 return false;
15838}
15839
15840//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15841
15842/// Given a type tag expression find the type tag itself.
15843///
15844/// \param TypeExpr Type tag expression, as it appears in user's code.
15845///
15846/// \param VD Declaration of an identifier that appears in a type tag.
15847///
15848/// \param MagicValue Type tag magic value.
15849///
15850/// \param isConstantEvaluated whether the evalaution should be performed in
15851
15852/// constant context.
15853static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15854 const ValueDecl **VD, uint64_t *MagicValue,
15855 bool isConstantEvaluated) {
15856 while(true) {
15857 if (!TypeExpr)
15858 return false;
15859
15860 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15861
15862 switch (TypeExpr->getStmtClass()) {
15863 case Stmt::UnaryOperatorClass: {
15864 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15865 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15866 TypeExpr = UO->getSubExpr();
15867 continue;
15868 }
15869 return false;
15870 }
15871
15872 case Stmt::DeclRefExprClass: {
15873 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15874 *VD = DRE->getDecl();
15875 return true;
15876 }
15877
15878 case Stmt::IntegerLiteralClass: {
15879 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15880 llvm::APInt MagicValueAPInt = IL->getValue();
15881 if (MagicValueAPInt.getActiveBits() <= 64) {
15882 *MagicValue = MagicValueAPInt.getZExtValue();
15883 return true;
15884 } else
15885 return false;
15886 }
15887
15888 case Stmt::BinaryConditionalOperatorClass:
15889 case Stmt::ConditionalOperatorClass: {
15890 const AbstractConditionalOperator *ACO =
15892 bool Result;
15893 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15894 isConstantEvaluated)) {
15895 if (Result)
15896 TypeExpr = ACO->getTrueExpr();
15897 else
15898 TypeExpr = ACO->getFalseExpr();
15899 continue;
15900 }
15901 return false;
15902 }
15903
15904 case Stmt::BinaryOperatorClass: {
15905 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15906 if (BO->getOpcode() == BO_Comma) {
15907 TypeExpr = BO->getRHS();
15908 continue;
15909 }
15910 return false;
15911 }
15912
15913 default:
15914 return false;
15915 }
15916 }
15917}
15918
15919/// Retrieve the C type corresponding to type tag TypeExpr.
15920///
15921/// \param TypeExpr Expression that specifies a type tag.
15922///
15923/// \param MagicValues Registered magic values.
15924///
15925/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15926/// kind.
15927///
15928/// \param TypeInfo Information about the corresponding C type.
15929///
15930/// \param isConstantEvaluated whether the evalaution should be performed in
15931/// constant context.
15932///
15933/// \returns true if the corresponding C type was found.
15935 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15936 const ASTContext &Ctx,
15937 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15938 *MagicValues,
15939 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15940 bool isConstantEvaluated) {
15941 FoundWrongKind = false;
15942
15943 // Variable declaration that has type_tag_for_datatype attribute.
15944 const ValueDecl *VD = nullptr;
15945
15946 uint64_t MagicValue;
15947
15948 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15949 return false;
15950
15951 if (VD) {
15952 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15953 if (I->getArgumentKind() != ArgumentKind) {
15954 FoundWrongKind = true;
15955 return false;
15956 }
15957 TypeInfo.Type = I->getMatchingCType();
15958 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15959 TypeInfo.MustBeNull = I->getMustBeNull();
15960 return true;
15961 }
15962 return false;
15963 }
15964
15965 if (!MagicValues)
15966 return false;
15967
15968 llvm::DenseMap<Sema::TypeTagMagicValue,
15970 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15971 if (I == MagicValues->end())
15972 return false;
15973
15974 TypeInfo = I->second;
15975 return true;
15976}
15977
15979 uint64_t MagicValue, QualType Type,
15980 bool LayoutCompatible,
15981 bool MustBeNull) {
15982 if (!TypeTagForDatatypeMagicValues)
15983 TypeTagForDatatypeMagicValues.reset(
15984 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15985
15986 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15987 (*TypeTagForDatatypeMagicValues)[Magic] =
15988 TypeTagData(Type, LayoutCompatible, MustBeNull);
15989}
15990
15991static bool IsSameCharType(QualType T1, QualType T2) {
15992 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15993 if (!BT1)
15994 return false;
15995
15996 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15997 if (!BT2)
15998 return false;
15999
16000 BuiltinType::Kind T1Kind = BT1->getKind();
16001 BuiltinType::Kind T2Kind = BT2->getKind();
16002
16003 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16004 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16005 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16006 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16007}
16008
16009void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16010 const ArrayRef<const Expr *> ExprArgs,
16011 SourceLocation CallSiteLoc) {
16012 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16013 bool IsPointerAttr = Attr->getIsPointer();
16014
16015 // Retrieve the argument representing the 'type_tag'.
16016 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16017 if (TypeTagIdxAST >= ExprArgs.size()) {
16018 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16019 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16020 return;
16021 }
16022 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16023 bool FoundWrongKind;
16024 TypeTagData TypeInfo;
16025 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16026 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16027 TypeInfo, isConstantEvaluatedContext())) {
16028 if (FoundWrongKind)
16029 Diag(TypeTagExpr->getExprLoc(),
16030 diag::warn_type_tag_for_datatype_wrong_kind)
16031 << TypeTagExpr->getSourceRange();
16032 return;
16033 }
16034
16035 // Retrieve the argument representing the 'arg_idx'.
16036 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16037 if (ArgumentIdxAST >= ExprArgs.size()) {
16038 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16039 << 1 << Attr->getArgumentIdx().getSourceIndex();
16040 return;
16041 }
16042 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16043 if (IsPointerAttr) {
16044 // Skip implicit cast of pointer to `void *' (as a function argument).
16045 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16046 if (ICE->getType()->isVoidPointerType() &&
16047 ICE->getCastKind() == CK_BitCast)
16048 ArgumentExpr = ICE->getSubExpr();
16049 }
16050 QualType ArgumentType = ArgumentExpr->getType();
16051
16052 // Passing a `void*' pointer shouldn't trigger a warning.
16053 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16054 return;
16055
16056 if (TypeInfo.MustBeNull) {
16057 // Type tag with matching void type requires a null pointer.
16058 if (!ArgumentExpr->isNullPointerConstant(Context,
16060 Diag(ArgumentExpr->getExprLoc(),
16061 diag::warn_type_safety_null_pointer_required)
16062 << ArgumentKind->getName()
16063 << ArgumentExpr->getSourceRange()
16064 << TypeTagExpr->getSourceRange();
16065 }
16066 return;
16067 }
16068
16069 QualType RequiredType = TypeInfo.Type;
16070 if (IsPointerAttr)
16071 RequiredType = Context.getPointerType(RequiredType);
16072
16073 bool mismatch = false;
16074 if (!TypeInfo.LayoutCompatible) {
16075 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16076
16077 // C++11 [basic.fundamental] p1:
16078 // Plain char, signed char, and unsigned char are three distinct types.
16079 //
16080 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16081 // char' depending on the current char signedness mode.
16082 if (mismatch)
16083 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16084 RequiredType->getPointeeType())) ||
16085 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16086 mismatch = false;
16087 } else
16088 if (IsPointerAttr)
16089 mismatch = !isLayoutCompatible(Context,
16090 ArgumentType->getPointeeType(),
16091 RequiredType->getPointeeType());
16092 else
16093 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16094
16095 if (mismatch)
16096 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16097 << ArgumentType << ArgumentKind
16098 << TypeInfo.LayoutCompatible << RequiredType
16099 << ArgumentExpr->getSourceRange()
16100 << TypeTagExpr->getSourceRange();
16101}
16102
16103void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16104 CharUnits Alignment) {
16105 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16106 Alignment);
16107}
16108
16110 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16111 const NamedDecl *ND = m.RD;
16112 if (ND->getName().empty()) {
16113 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16114 ND = TD;
16115 }
16116 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16117 << m.MD << ND << m.E->getSourceRange();
16118 }
16120}
16121
16123 E = E->IgnoreParens();
16124 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16125 return;
16126 if (isa<UnaryOperator>(E) &&
16127 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16128 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16129 if (isa<MemberExpr>(Op)) {
16130 auto &MisalignedMembersForExpr =
16132 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16133 if (MA != MisalignedMembersForExpr.end() &&
16134 (T->isDependentType() || T->isIntegerType() ||
16135 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16136 Context.getTypeAlignInChars(
16137 T->getPointeeType()) <= MA->Alignment))))
16138 MisalignedMembersForExpr.erase(MA);
16139 }
16140 }
16141}
16142
16144 Expr *E,
16145 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16146 Action) {
16147 const auto *ME = dyn_cast<MemberExpr>(E);
16148 if (!ME)
16149 return;
16150
16151 // No need to check expressions with an __unaligned-qualified type.
16152 if (E->getType().getQualifiers().hasUnaligned())
16153 return;
16154
16155 // For a chain of MemberExpr like "a.b.c.d" this list
16156 // will keep FieldDecl's like [d, c, b].
16157 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16158 const MemberExpr *TopME = nullptr;
16159 bool AnyIsPacked = false;
16160 do {
16161 QualType BaseType = ME->getBase()->getType();
16162 if (BaseType->isDependentType())
16163 return;
16164 if (ME->isArrow())
16165 BaseType = BaseType->getPointeeType();
16166 auto *RD = BaseType->castAsRecordDecl();
16167 if (RD->isInvalidDecl())
16168 return;
16169
16170 ValueDecl *MD = ME->getMemberDecl();
16171 auto *FD = dyn_cast<FieldDecl>(MD);
16172 // We do not care about non-data members.
16173 if (!FD || FD->isInvalidDecl())
16174 return;
16175
16176 AnyIsPacked =
16177 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16178 ReverseMemberChain.push_back(FD);
16179
16180 TopME = ME;
16181 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16182 } while (ME);
16183 assert(TopME && "We did not compute a topmost MemberExpr!");
16184
16185 // Not the scope of this diagnostic.
16186 if (!AnyIsPacked)
16187 return;
16188
16189 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16190 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16191 // TODO: The innermost base of the member expression may be too complicated.
16192 // For now, just disregard these cases. This is left for future
16193 // improvement.
16194 if (!DRE && !isa<CXXThisExpr>(TopBase))
16195 return;
16196
16197 // Alignment expected by the whole expression.
16198 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16199
16200 // No need to do anything else with this case.
16201 if (ExpectedAlignment.isOne())
16202 return;
16203
16204 // Synthesize offset of the whole access.
16205 CharUnits Offset;
16206 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16207 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16208
16209 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16210 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16211 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16212
16213 // The base expression of the innermost MemberExpr may give
16214 // stronger guarantees than the class containing the member.
16215 if (DRE && !TopME->isArrow()) {
16216 const ValueDecl *VD = DRE->getDecl();
16217 if (!VD->getType()->isReferenceType())
16218 CompleteObjectAlignment =
16219 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16220 }
16221
16222 // Check if the synthesized offset fulfills the alignment.
16223 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16224 // It may fulfill the offset it but the effective alignment may still be
16225 // lower than the expected expression alignment.
16226 CompleteObjectAlignment < ExpectedAlignment) {
16227 // If this happens, we want to determine a sensible culprit of this.
16228 // Intuitively, watching the chain of member expressions from right to
16229 // left, we start with the required alignment (as required by the field
16230 // type) but some packed attribute in that chain has reduced the alignment.
16231 // It may happen that another packed structure increases it again. But if
16232 // we are here such increase has not been enough. So pointing the first
16233 // FieldDecl that either is packed or else its RecordDecl is,
16234 // seems reasonable.
16235 FieldDecl *FD = nullptr;
16236 CharUnits Alignment;
16237 for (FieldDecl *FDI : ReverseMemberChain) {
16238 if (FDI->hasAttr<PackedAttr>() ||
16239 FDI->getParent()->hasAttr<PackedAttr>()) {
16240 FD = FDI;
16241 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16242 Context.getTypeAlignInChars(
16243 Context.getCanonicalTagType(FD->getParent())));
16244 break;
16245 }
16246 }
16247 assert(FD && "We did not find a packed FieldDecl!");
16248 Action(E, FD->getParent(), FD, Alignment);
16249 }
16250}
16251
16252void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16253 using namespace std::placeholders;
16254
16256 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16257 _2, _3, _4));
16258}
16259
16261 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16262 if (checkArgCount(TheCall, 1))
16263 return true;
16264
16265 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16266 if (A.isInvalid())
16267 return true;
16268
16269 TheCall->setArg(0, A.get());
16270 QualType TyA = A.get()->getType();
16271
16272 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16273 ArgTyRestr, 1))
16274 return true;
16275
16276 TheCall->setType(TyA);
16277 return false;
16278}
16279
16280bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16281 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16282 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16283 TheCall->setType(*Res);
16284 return false;
16285 }
16286 return true;
16287}
16288
16290 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16291 if (!Res)
16292 return true;
16293
16294 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16295 TheCall->setType(VecTy0->getElementType());
16296 else
16297 TheCall->setType(*Res);
16298
16299 return false;
16300}
16301
16303 SourceLocation Loc) {
16305 R = RHS->getEnumCoercedType(S.Context);
16306 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16308 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16309 << LHS->getSourceRange() << RHS->getSourceRange()
16310 << /*Arithmetic Between*/ 0 << L << R;
16311 }
16312 return false;
16313}
16314
16315/// Check if all arguments have the same type. If the types don't match, emit an
16316/// error message and return true. Otherwise return false.
16317///
16318/// For scalars we directly compare their unqualified types. But even if we
16319/// compare unqualified vector types, a difference in qualifiers in the element
16320/// types can make the vector types be considered not equal. For example,
16321/// vector of 4 'const float' values vs vector of 4 'float' values.
16322/// So we compare unqualified types of their elements and number of elements.
16324 ArrayRef<Expr *> Args) {
16325 assert(!Args.empty() && "Should have at least one argument.");
16326
16327 Expr *Arg0 = Args.front();
16328 QualType Ty0 = Arg0->getType();
16329
16330 auto EmitError = [&](Expr *ArgI) {
16331 SemaRef.Diag(Arg0->getBeginLoc(),
16332 diag::err_typecheck_call_different_arg_types)
16333 << Arg0->getType() << ArgI->getType();
16334 };
16335
16336 // Compare scalar types.
16337 if (!Ty0->isVectorType()) {
16338 for (Expr *ArgI : Args.drop_front())
16339 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16340 EmitError(ArgI);
16341 return true;
16342 }
16343
16344 return false;
16345 }
16346
16347 // Compare vector types.
16348 const auto *Vec0 = Ty0->castAs<VectorType>();
16349 for (Expr *ArgI : Args.drop_front()) {
16350 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16351 if (!VecI ||
16352 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16353 VecI->getElementType()) ||
16354 Vec0->getNumElements() != VecI->getNumElements()) {
16355 EmitError(ArgI);
16356 return true;
16357 }
16358 }
16359
16360 return false;
16361}
16362
16363std::optional<QualType>
16365 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16366 if (checkArgCount(TheCall, 2))
16367 return std::nullopt;
16368
16370 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16371 return std::nullopt;
16372
16373 Expr *Args[2];
16374 for (int I = 0; I < 2; ++I) {
16375 ExprResult Converted =
16376 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16377 if (Converted.isInvalid())
16378 return std::nullopt;
16379 Args[I] = Converted.get();
16380 }
16381
16382 SourceLocation LocA = Args[0]->getBeginLoc();
16383 QualType TyA = Args[0]->getType();
16384
16385 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16386 return std::nullopt;
16387
16388 if (checkBuiltinVectorMathArgTypes(*this, Args))
16389 return std::nullopt;
16390
16391 TheCall->setArg(0, Args[0]);
16392 TheCall->setArg(1, Args[1]);
16393 return TyA;
16394}
16395
16397 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16398 if (checkArgCount(TheCall, 3))
16399 return true;
16400
16401 SourceLocation Loc = TheCall->getExprLoc();
16402 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16403 TheCall->getArg(1), Loc) ||
16404 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16405 TheCall->getArg(2), Loc))
16406 return true;
16407
16408 Expr *Args[3];
16409 for (int I = 0; I < 3; ++I) {
16410 ExprResult Converted =
16411 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16412 if (Converted.isInvalid())
16413 return true;
16414 Args[I] = Converted.get();
16415 }
16416
16417 int ArgOrdinal = 1;
16418 for (Expr *Arg : Args) {
16419 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16420 ArgTyRestr, ArgOrdinal++))
16421 return true;
16422 }
16423
16424 if (checkBuiltinVectorMathArgTypes(*this, Args))
16425 return true;
16426
16427 for (int I = 0; I < 3; ++I)
16428 TheCall->setArg(I, Args[I]);
16429
16430 TheCall->setType(Args[0]->getType());
16431 return false;
16432}
16433
16434bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16435 if (checkArgCount(TheCall, 1))
16436 return true;
16437
16438 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16439 if (A.isInvalid())
16440 return true;
16441
16442 TheCall->setArg(0, A.get());
16443 return false;
16444}
16445
16446bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16447 if (checkArgCount(TheCall, 1))
16448 return true;
16449
16450 ExprResult Arg = TheCall->getArg(0);
16451 QualType TyArg = Arg.get()->getType();
16452
16453 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16454 return Diag(TheCall->getArg(0)->getBeginLoc(),
16455 diag::err_builtin_invalid_arg_type)
16456 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16457
16458 TheCall->setType(TyArg);
16459 return false;
16460}
16461
16462ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16463 ExprResult CallResult) {
16464 if (checkArgCount(TheCall, 1))
16465 return ExprError();
16466
16467 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16468 if (MatrixArg.isInvalid())
16469 return MatrixArg;
16470 Expr *Matrix = MatrixArg.get();
16471
16472 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16473 if (!MType) {
16474 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16475 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16476 << Matrix->getType();
16477 return ExprError();
16478 }
16479
16480 // Create returned matrix type by swapping rows and columns of the argument
16481 // matrix type.
16482 QualType ResultType = Context.getConstantMatrixType(
16483 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16484
16485 // Change the return type to the type of the returned matrix.
16486 TheCall->setType(ResultType);
16487
16488 // Update call argument to use the possibly converted matrix argument.
16489 TheCall->setArg(0, Matrix);
16490 return CallResult;
16491}
16492
16493// Get and verify the matrix dimensions.
16494static std::optional<unsigned>
16496 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16497 if (!Value) {
16498 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16499 << Name;
16500 return {};
16501 }
16502 uint64_t Dim = Value->getZExtValue();
16503 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16504 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16505 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16506 return {};
16507 }
16508 return Dim;
16509}
16510
16511ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16512 ExprResult CallResult) {
16513 if (!getLangOpts().MatrixTypes) {
16514 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16515 return ExprError();
16516 }
16517
16518 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16520 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16521 << /*column*/ 1 << /*load*/ 0;
16522 return ExprError();
16523 }
16524
16525 if (checkArgCount(TheCall, 4))
16526 return ExprError();
16527
16528 unsigned PtrArgIdx = 0;
16529 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16530 Expr *RowsExpr = TheCall->getArg(1);
16531 Expr *ColumnsExpr = TheCall->getArg(2);
16532 Expr *StrideExpr = TheCall->getArg(3);
16533
16534 bool ArgError = false;
16535
16536 // Check pointer argument.
16537 {
16539 if (PtrConv.isInvalid())
16540 return PtrConv;
16541 PtrExpr = PtrConv.get();
16542 TheCall->setArg(0, PtrExpr);
16543 if (PtrExpr->isTypeDependent()) {
16544 TheCall->setType(Context.DependentTy);
16545 return TheCall;
16546 }
16547 }
16548
16549 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16550 QualType ElementTy;
16551 if (!PtrTy) {
16552 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16553 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16554 << PtrExpr->getType();
16555 ArgError = true;
16556 } else {
16557 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16558
16560 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16561 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16562 << /* no fp */ 0 << PtrExpr->getType();
16563 ArgError = true;
16564 }
16565 }
16566
16567 // Apply default Lvalue conversions and convert the expression to size_t.
16568 auto ApplyArgumentConversions = [this](Expr *E) {
16570 if (Conv.isInvalid())
16571 return Conv;
16572
16573 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16574 };
16575
16576 // Apply conversion to row and column expressions.
16577 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16578 if (!RowsConv.isInvalid()) {
16579 RowsExpr = RowsConv.get();
16580 TheCall->setArg(1, RowsExpr);
16581 } else
16582 RowsExpr = nullptr;
16583
16584 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16585 if (!ColumnsConv.isInvalid()) {
16586 ColumnsExpr = ColumnsConv.get();
16587 TheCall->setArg(2, ColumnsExpr);
16588 } else
16589 ColumnsExpr = nullptr;
16590
16591 // If any part of the result matrix type is still pending, just use
16592 // Context.DependentTy, until all parts are resolved.
16593 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16594 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16595 TheCall->setType(Context.DependentTy);
16596 return CallResult;
16597 }
16598
16599 // Check row and column dimensions.
16600 std::optional<unsigned> MaybeRows;
16601 if (RowsExpr)
16602 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16603
16604 std::optional<unsigned> MaybeColumns;
16605 if (ColumnsExpr)
16606 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16607
16608 // Check stride argument.
16609 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16610 if (StrideConv.isInvalid())
16611 return ExprError();
16612 StrideExpr = StrideConv.get();
16613 TheCall->setArg(3, StrideExpr);
16614
16615 if (MaybeRows) {
16616 if (std::optional<llvm::APSInt> Value =
16617 StrideExpr->getIntegerConstantExpr(Context)) {
16618 uint64_t Stride = Value->getZExtValue();
16619 if (Stride < *MaybeRows) {
16620 Diag(StrideExpr->getBeginLoc(),
16621 diag::err_builtin_matrix_stride_too_small);
16622 ArgError = true;
16623 }
16624 }
16625 }
16626
16627 if (ArgError || !MaybeRows || !MaybeColumns)
16628 return ExprError();
16629
16630 TheCall->setType(
16631 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16632 return CallResult;
16633}
16634
16635ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16636 ExprResult CallResult) {
16637 if (!getLangOpts().MatrixTypes) {
16638 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16639 return ExprError();
16640 }
16641
16642 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16644 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16645 << /*column*/ 1 << /*store*/ 1;
16646 return ExprError();
16647 }
16648
16649 if (checkArgCount(TheCall, 3))
16650 return ExprError();
16651
16652 unsigned PtrArgIdx = 1;
16653 Expr *MatrixExpr = TheCall->getArg(0);
16654 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16655 Expr *StrideExpr = TheCall->getArg(2);
16656
16657 bool ArgError = false;
16658
16659 {
16660 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16661 if (MatrixConv.isInvalid())
16662 return MatrixConv;
16663 MatrixExpr = MatrixConv.get();
16664 TheCall->setArg(0, MatrixExpr);
16665 }
16666 if (MatrixExpr->isTypeDependent()) {
16667 TheCall->setType(Context.DependentTy);
16668 return TheCall;
16669 }
16670
16671 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16672 if (!MatrixTy) {
16673 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16674 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16675 ArgError = true;
16676 }
16677
16678 {
16680 if (PtrConv.isInvalid())
16681 return PtrConv;
16682 PtrExpr = PtrConv.get();
16683 TheCall->setArg(1, PtrExpr);
16684 if (PtrExpr->isTypeDependent()) {
16685 TheCall->setType(Context.DependentTy);
16686 return TheCall;
16687 }
16688 }
16689
16690 // Check pointer argument.
16691 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16692 if (!PtrTy) {
16693 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16694 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16695 << PtrExpr->getType();
16696 ArgError = true;
16697 } else {
16698 QualType ElementTy = PtrTy->getPointeeType();
16699 if (ElementTy.isConstQualified()) {
16700 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16701 ArgError = true;
16702 }
16703 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16704 if (MatrixTy &&
16705 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16706 Diag(PtrExpr->getBeginLoc(),
16707 diag::err_builtin_matrix_pointer_arg_mismatch)
16708 << ElementTy << MatrixTy->getElementType();
16709 ArgError = true;
16710 }
16711 }
16712
16713 // Apply default Lvalue conversions and convert the stride expression to
16714 // size_t.
16715 {
16716 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16717 if (StrideConv.isInvalid())
16718 return StrideConv;
16719
16720 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16721 if (StrideConv.isInvalid())
16722 return StrideConv;
16723 StrideExpr = StrideConv.get();
16724 TheCall->setArg(2, StrideExpr);
16725 }
16726
16727 // Check stride argument.
16728 if (MatrixTy) {
16729 if (std::optional<llvm::APSInt> Value =
16730 StrideExpr->getIntegerConstantExpr(Context)) {
16731 uint64_t Stride = Value->getZExtValue();
16732 if (Stride < MatrixTy->getNumRows()) {
16733 Diag(StrideExpr->getBeginLoc(),
16734 diag::err_builtin_matrix_stride_too_small);
16735 ArgError = true;
16736 }
16737 }
16738 }
16739
16740 if (ArgError)
16741 return ExprError();
16742
16743 return CallResult;
16744}
16745
16747 const NamedDecl *Callee) {
16748 // This warning does not make sense in code that has no runtime behavior.
16750 return;
16751
16752 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16753
16754 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16755 return;
16756
16757 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16758 // all TCBs the callee is a part of.
16759 llvm::StringSet<> CalleeTCBs;
16760 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16761 CalleeTCBs.insert(A->getTCBName());
16762 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16763 CalleeTCBs.insert(A->getTCBName());
16764
16765 // Go through the TCBs the caller is a part of and emit warnings if Caller
16766 // is in a TCB that the Callee is not.
16767 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16768 StringRef CallerTCB = A->getTCBName();
16769 if (CalleeTCBs.count(CallerTCB) == 0) {
16770 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16771 << Callee << CallerTCB;
16772 }
16773 }
16774}
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:791
Builtin::Context & BuiltinInfo
Definition ASTContext.h:793
const LangOptions & getLangOpts() const
Definition ASTContext.h:945
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:844
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:910
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4287
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4465
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4471
SourceLocation getQuestionLoc() const
Definition Expr.h:4314
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4477
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Expr * getBase()
Get base of the array section.
Definition Expr.h:7183
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7187
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getRBracketLoc() const
Definition Expr.h:2769
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h: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:6814
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:6963
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:6945
Attr - This represents one attribute.
Definition Attr.h:45
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
SourceLocation getExprLoc() const
Definition Expr.h:4013
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
BinaryOperatorKind Opcode
Definition Expr.h:3977
Pointer to a block type.
Definition TypeBase.h: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:3903
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1630
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1688
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:154
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3094
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1591
arg_iterator arg_begin()
Definition Expr.h:3134
arg_iterator arg_end()
Definition Expr.h:3137
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
bool isCallToStdMove() const
Definition Expr.cpp:3623
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3170
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
arg_range arguments()
Definition Expr.h:3129
SourceLocation getEndLoc() const
Definition Expr.h:3230
SourceLocation getRParenLoc() const
Definition Expr.h:3208
Decl * getCalleeDecl()
Definition Expr.h:3054
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition Expr.cpp:1596
void setCallee(Expr *F)
Definition Expr.h:3026
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3113
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
Expr * getSubExpr()
Definition Expr.h:3660
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getLHS() const
Definition Expr.h:4359
Expr * getRHS() const
Definition Expr.h:4360
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h: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:5558
Expr * getOperand() const
Definition ExprCXX.h:5324
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:487
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1995
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4007
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4239
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4180
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:671
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:205
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4207
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3669
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3069
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4046
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:265
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:225
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h: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:4748
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2878
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4549
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3758
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3861
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3129
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4325
bool isStatic() const
Definition Decl.h:2929
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4140
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4126
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3822
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h: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:3787
Describes an C or C++ initializer list.
Definition Expr.h:5233
ArrayRef< Expr * > inits()
Definition Expr.h:5283
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:974
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1020
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1056
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:498
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1103
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:848
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
static bool isValidElementType(QualType T, 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:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h: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:1937
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1693
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1707
SourceLocation getSemiLoc() const
Definition Stmt.h:1704
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:614
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:703
bool isImplicitProperty() const
Definition ExprObjC.h:700
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:52
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:273
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6690
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5075
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8377
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2866
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8293
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8419
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8333
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:8345
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8387
void removeLocalVolatile()
Definition TypeBase.h:8409
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8401
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8366
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8414
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8339
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4321
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4407
field_range fields() const
Definition Decl.h:4524
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4399
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1025
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1108
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:97
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:277
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:283
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:526
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
SemaAMDGPU & AMDGPU()
Definition Sema.h:1416
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13030
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2640
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9319
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9327
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9364
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
bool FormatStringHasSArg(const StringLiteral *FExpr)
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6917
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2045
SemaHexagon & Hexagon()
Definition Sema.h:1456
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1654
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:833
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1546
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ASTContext & Context
Definition Sema.h:1283
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
SemaObjC & ObjC()
Definition Sema.h:1486
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:754
ASTContext & getASTContext() const
Definition Sema.h:925
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2585
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
AtomicArgumentOrder
Definition Sema.h:2692
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:918
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
SemaBPF & BPF()
Definition Sema.h:1431
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
SemaDirectX & DirectX()
Definition Sema.h:1446
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition Sema.h:1281
static const uint64_t MaximumAlignment
Definition Sema.h:1214
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:952
SemaHLSL & HLSL()
Definition Sema.h:1451
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1471
SemaRISCV & RISCV()
Definition Sema.h:1516
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2758
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6950
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1666
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1314
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2665
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15348
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2295
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:639
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1414
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
SemaOpenCL & OpenCL()
Definition Sema.h:1496
FormatArgumentPassingKind
Definition Sema.h:2595
@ FAPK_Elsewhere
Definition Sema.h:2599
@ FAPK_Fixed
Definition Sema.h:2596
@ FAPK_Variadic
Definition Sema.h:2597
@ FAPK_VAList
Definition Sema.h:2598
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8161
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13909
SourceManager & getSourceManager() const
Definition Sema.h:923
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
Definition Sema.h:2587
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::FloatTy)
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
SemaPPC & PPC()
Definition Sema.h:1506
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1246
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FormatStringI...
SemaSystemZ & SystemZ()
Definition Sema.h:1536
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
SourceManager & SourceMgr
Definition Sema.h:1286
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:783
DiagnosticsEngine & Diags
Definition Sema.h:1285
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
SemaNVPTX & NVPTX()
Definition Sema.h:1481
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:625
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
@ AbstractParamType
Definition Sema.h:6217
SemaSPIRV & SPIRV()
Definition Sema.h:1521
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
SemaLoongArch & LoongArch()
Definition Sema.h:1461
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6405
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
SemaWasm & Wasm()
Definition Sema.h:1541
SemaARM & ARM()
Definition Sema.h:1421
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4577
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition Stmt.cpp:299
StmtClass getStmtClass() const
Definition Stmt.h:1483
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
bool isUTF8() const
Definition Expr.h:1918
bool isWide() const
Definition Expr.h:1917
bool isPascal() const
Definition Expr.h:1922
unsigned getLength() const
Definition Expr.h:1909
StringLiteralKind getKind() const
Definition Expr.h:1912
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition Expr.cpp:1325
bool isUTF32() const
Definition Expr.h:1920
unsigned getByteLength() const
Definition Expr.h:1908
StringRef getString() const
Definition Expr.h:1867
bool isUTF16() const
Definition Expr.h:1919
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1974
bool isOrdinary() const
Definition Expr.h:1916
unsigned getCharByteWidth() const
Definition Expr.h:1910
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3832
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isUnion() const
Definition Decl.h:3922
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:388
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6180
A container of type source information.
Definition TypeBase.h:8264
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:8275
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8550
bool isVoidType() const
Definition TypeBase.h:8892
bool isBooleanType() const
Definition TypeBase.h:9022
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9072
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9052
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2066
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2425
bool isArrayType() const
Definition TypeBase.h:8629
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8597
bool isPointerType() const
Definition TypeBase.h:8530
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8936
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9179
bool isReferenceType() const
Definition TypeBase.h:8554
bool isEnumeralType() const
Definition TypeBase.h:8661
bool isScalarType() const
Definition TypeBase.h:8994
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1909
bool isVariableArrayType() const
Definition TypeBase.h:8641
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isExtVectorType() const
Definition TypeBase.h:8673
bool isExtVectorBoolType() const
Definition TypeBase.h:8677
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2646
bool isBitIntType() const
Definition TypeBase.h:8801
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8861
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8653
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:2243
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:2557
bool isAtomicType() const
Definition TypeBase.h:8718
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3074
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2801
bool isUnscopedEnumerationType() const
Definition Type.cpp:2125
bool isObjCObjectType() const
Definition TypeBase.h:8709
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9165
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9028
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8526
bool isObjCObjectPointerType() const
Definition TypeBase.h:8705
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2312
bool isStructureOrClassType() const
Definition Type.cpp:706
bool isVectorType() const
Definition TypeBase.h:8669
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
bool isAnyPointerType() const
Definition TypeBase.h:8538
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:9112
bool isNullPtrType() const
Definition TypeBase.h:8929
bool isRecordType() const
Definition TypeBase.h:8657
bool isObjCRetainableType() const
Definition Type.cpp:5283
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2569
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2634
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2362
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3395
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5515
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4176
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2687
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:216
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1257
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1242
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1235
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1249
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2492
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1203
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1264
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:511
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:661
@ Comparison
A comparison.
Definition Sema.h:665
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:24
@ Success
Annotation was successful.
Definition Parser.h:65
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
PointerAuthDiscArgKind
Definition Sema.h:592
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:545
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:112
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:497
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:519
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:127
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
StringLiteralKind
Definition Expr.h:1763
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Win64
Definition Specifiers.h:285
@ CC_X86_64SysV
Definition Specifiers.h:286
@ Generic
not a target-specific vector type
Definition TypeBase.h: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:13201
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13227
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13217
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13176
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6811
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2607
#define log2(__x)
Definition tgmath.h:970