clang 23.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
2330 unsigned ArgIndex;
2331 bool OnlyUnsigned;
2332
2334 QualType T) {
2335 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2336 << ArgIndex << /*scalar*/ 1
2337 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2338 << /*no fp*/ 0 << T;
2339 }
2340
2341public:
2342 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2343 : ContextualImplicitConverter(/*Suppress=*/false,
2344 /*SuppressConversion=*/true),
2345 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2346
2347 bool match(QualType T) override {
2348 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2349 }
2350
2352 QualType T) override {
2353 return emitError(S, Loc, T);
2354 }
2355
2357 QualType T) override {
2358 return emitError(S, Loc, T);
2359 }
2360
2362 QualType T,
2363 QualType ConvTy) override {
2364 return emitError(S, Loc, T);
2365 }
2366
2368 QualType ConvTy) override {
2369 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2370 }
2371
2373 QualType T) override {
2374 return emitError(S, Loc, T);
2375 }
2376
2378 QualType ConvTy) override {
2379 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2380 }
2381
2383 QualType T,
2384 QualType ConvTy) override {
2385 llvm_unreachable("conversion functions are permitted");
2386 }
2387};
2388
2389/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2390/// arguments, that the first argument is an unsigned integer type, and that
2391/// the second argument is an integer type.
2392static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2393 if (S.checkArgCount(TheCall, 2))
2394 return true;
2395
2396 // First argument (value to rotate) must be unsigned integer type.
2397 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2399 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2400 if (Arg0Res.isInvalid())
2401 return true;
2402
2403 Expr *Arg0 = Arg0Res.get();
2404 TheCall->setArg(0, Arg0);
2405
2406 QualType Arg0Ty = Arg0->getType();
2407 if (!Arg0Ty->isUnsignedIntegerType())
2408 return true;
2409
2410 // Second argument (rotation count) must be integer type.
2411 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2413 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2414 if (Arg1Res.isInvalid())
2415 return true;
2416
2417 Expr *Arg1 = Arg1Res.get();
2418 TheCall->setArg(1, Arg1);
2419
2420 QualType Arg1Ty = Arg1->getType();
2421 if (!Arg1Ty->isIntegerType())
2422 return true;
2423
2424 TheCall->setType(Arg0Ty);
2425 return false;
2426}
2427
2428static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2429 unsigned Pos, bool AllowConst,
2430 bool AllowAS) {
2431 QualType MaskTy = MaskArg->getType();
2432 if (!MaskTy->isExtVectorBoolType())
2433 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2434 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2435 << MaskTy;
2436
2437 QualType PtrTy = PtrArg->getType();
2438 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2439 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2440 << Pos << "scalar pointer";
2441
2442 QualType PointeeTy = PtrTy->getPointeeType();
2443 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2444 (!AllowConst && PointeeTy.isConstQualified()) ||
2445 (!AllowAS && PointeeTy.hasAddressSpace())) {
2448 return S.Diag(PtrArg->getExprLoc(),
2449 diag::err_typecheck_convert_incompatible)
2450 << PtrTy << Target << /*different qualifiers=*/5
2451 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2452 << PtrTy << Target;
2453 }
2454 return false;
2455}
2456
2457static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2458 bool TypeDependent = false;
2459 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2460 ExprResult Converted =
2462 if (Converted.isInvalid())
2463 return true;
2464 TheCall->setArg(Arg, Converted.get());
2465 TypeDependent |= Converted.get()->isTypeDependent();
2466 }
2467
2468 if (TypeDependent)
2469 TheCall->setType(S.Context.DependentTy);
2470 return false;
2471}
2472
2474 if (S.checkArgCountRange(TheCall, 2, 3))
2475 return ExprError();
2476
2477 if (ConvertMaskedBuiltinArgs(S, TheCall))
2478 return ExprError();
2479
2480 Expr *MaskArg = TheCall->getArg(0);
2481 Expr *PtrArg = TheCall->getArg(1);
2482 if (TheCall->isTypeDependent())
2483 return TheCall;
2484
2485 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2486 TheCall->getBuiltinCallee() ==
2487 Builtin::BI__builtin_masked_load))
2488 return ExprError();
2489
2490 QualType MaskTy = MaskArg->getType();
2491 QualType PtrTy = PtrArg->getType();
2492 QualType PointeeTy = PtrTy->getPointeeType();
2493 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2494
2496 MaskVecTy->getNumElements());
2497 if (TheCall->getNumArgs() == 3) {
2498 Expr *PassThruArg = TheCall->getArg(2);
2499 QualType PassThruTy = PassThruArg->getType();
2500 if (!S.Context.hasSameType(PassThruTy, RetTy))
2501 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2502 << /* third argument */ 3 << RetTy;
2503 }
2504
2505 TheCall->setType(RetTy);
2506 return TheCall;
2507}
2508
2510 if (S.checkArgCount(TheCall, 3))
2511 return ExprError();
2512
2513 if (ConvertMaskedBuiltinArgs(S, TheCall))
2514 return ExprError();
2515
2516 Expr *MaskArg = TheCall->getArg(0);
2517 Expr *ValArg = TheCall->getArg(1);
2518 Expr *PtrArg = TheCall->getArg(2);
2519 if (TheCall->isTypeDependent())
2520 return TheCall;
2521
2522 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2523 TheCall->getBuiltinCallee() ==
2524 Builtin::BI__builtin_masked_store))
2525 return ExprError();
2526
2527 QualType MaskTy = MaskArg->getType();
2528 QualType PtrTy = PtrArg->getType();
2529 QualType ValTy = ValArg->getType();
2530 if (!ValTy->isVectorType())
2531 return ExprError(
2532 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2533 << 2 << "vector");
2534
2535 QualType PointeeTy = PtrTy->getPointeeType();
2536 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2537 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2538 MaskVecTy->getNumElements());
2539 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2540 MemoryTy.getUnqualifiedType()))
2541 return ExprError(S.Diag(TheCall->getBeginLoc(),
2542 diag::err_vec_builtin_incompatible_vector)
2543 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2544 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2545 TheCall->getArg(1)->getEndLoc()));
2546
2547 TheCall->setType(S.Context.VoidTy);
2548 return TheCall;
2549}
2550
2552 if (S.checkArgCountRange(TheCall, 3, 4))
2553 return ExprError();
2554
2555 if (ConvertMaskedBuiltinArgs(S, TheCall))
2556 return ExprError();
2557
2558 Expr *MaskArg = TheCall->getArg(0);
2559 Expr *IdxArg = TheCall->getArg(1);
2560 Expr *PtrArg = TheCall->getArg(2);
2561 if (TheCall->isTypeDependent())
2562 return TheCall;
2563
2564 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2565 /*AllowAS=*/true))
2566 return ExprError();
2567
2568 QualType IdxTy = IdxArg->getType();
2569 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2570 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2571 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2572 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2573 << IdxTy;
2574
2575 QualType MaskTy = MaskArg->getType();
2576 QualType PtrTy = PtrArg->getType();
2577 QualType PointeeTy = PtrTy->getPointeeType();
2578 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2579 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2580 return ExprError(
2581 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2583 TheCall->getBuiltinCallee())
2584 << MaskTy << IdxTy);
2585
2587 MaskVecTy->getNumElements());
2588 if (TheCall->getNumArgs() == 4) {
2589 Expr *PassThruArg = TheCall->getArg(3);
2590 QualType PassThruTy = PassThruArg->getType();
2591 if (!S.Context.hasSameType(PassThruTy, RetTy))
2592 return S.Diag(PassThruArg->getExprLoc(),
2593 diag::err_vec_masked_load_store_ptr)
2594 << /* fourth argument */ 4 << RetTy;
2595 }
2596
2597 TheCall->setType(RetTy);
2598 return TheCall;
2599}
2600
2602 if (S.checkArgCount(TheCall, 4))
2603 return ExprError();
2604
2605 if (ConvertMaskedBuiltinArgs(S, TheCall))
2606 return ExprError();
2607
2608 Expr *MaskArg = TheCall->getArg(0);
2609 Expr *IdxArg = TheCall->getArg(1);
2610 Expr *ValArg = TheCall->getArg(2);
2611 Expr *PtrArg = TheCall->getArg(3);
2612 if (TheCall->isTypeDependent())
2613 return TheCall;
2614
2615 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2616 /*AllowAS=*/true))
2617 return ExprError();
2618
2619 QualType IdxTy = IdxArg->getType();
2620 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2621 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2622 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2623 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2624 << IdxTy;
2625
2626 QualType ValTy = ValArg->getType();
2627 QualType MaskTy = MaskArg->getType();
2628 QualType PtrTy = PtrArg->getType();
2629 QualType PointeeTy = PtrTy->getPointeeType();
2630
2631 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2632 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2633 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2634 return ExprError(
2635 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2637 TheCall->getBuiltinCallee())
2638 << MaskTy << IdxTy);
2639 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2640 return ExprError(
2641 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2643 TheCall->getBuiltinCallee())
2644 << MaskTy << ValTy);
2645
2647 MaskVecTy->getNumElements());
2648 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2649 return ExprError(S.Diag(TheCall->getBeginLoc(),
2650 diag::err_vec_builtin_incompatible_vector)
2651 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2652 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2653 TheCall->getArg(1)->getEndLoc()));
2654
2655 TheCall->setType(S.Context.VoidTy);
2656 return TheCall;
2657}
2658
2660 SourceLocation Loc = TheCall->getBeginLoc();
2661 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2662 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2663
2664 if (Args.size() == 0) {
2665 S.Diag(TheCall->getBeginLoc(),
2666 diag::err_typecheck_call_too_few_args_at_least)
2667 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2668 << /*is_non_object=*/0 << TheCall->getSourceRange();
2669 return ExprError();
2670 }
2671
2672 QualType FuncT = Args[0]->getType();
2673
2674 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2675 if (Args.size() < 2) {
2676 S.Diag(TheCall->getBeginLoc(),
2677 diag::err_typecheck_call_too_few_args_at_least)
2678 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2679 << /*is_non_object=*/0 << TheCall->getSourceRange();
2680 return ExprError();
2681 }
2682
2683 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2684 QualType ObjectT = Args[1]->getType();
2685
2686 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2687 return ExprError();
2688
2689 ExprResult ObjectArg = [&]() -> ExprResult {
2690 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2691 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2692 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2693 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2694 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2695 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2696 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2697 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2698 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2699 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2700 return Args[1];
2701 }
2702
2703 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2704 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2705 // reference_wrapper;
2706 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2707 if (RD->isInStdNamespace() &&
2708 RD->getDeclName().getAsString() == "reference_wrapper") {
2709 CXXScopeSpec SS;
2710 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2711 UnqualifiedId GetID;
2712 GetID.setIdentifier(GetName, Loc);
2713
2715 S.getCurScope(), Args[1], Loc, tok::period, SS,
2716 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2717
2718 if (MemExpr.isInvalid())
2719 return ExprError();
2720
2721 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2722 }
2723 }
2724
2725 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2726 // class T and t1 does not satisfy the previous two items;
2727
2728 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2729 }();
2730
2731 if (ObjectArg.isInvalid())
2732 return ExprError();
2733
2734 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2735 tok::periodstar, ObjectArg.get(), Args[0]);
2736 if (BinOp.isInvalid())
2737 return ExprError();
2738
2739 if (MPT->isMemberDataPointer())
2740 return BinOp;
2741
2742 auto *MemCall = new (S.Context)
2744
2745 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2746 Args.drop_front(2), TheCall->getRParenLoc());
2747 }
2748 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2749 Args.drop_front(), TheCall->getRParenLoc());
2750}
2751
2752// Performs a similar job to Sema::UsualUnaryConversions, but without any
2753// implicit promotion of integral/enumeration types.
2755 // First, convert to an r-value.
2757 if (Res.isInvalid())
2758 return ExprError();
2759
2760 // Promote floating-point types.
2761 return S.UsualUnaryFPConversions(Res.get());
2762}
2763
2765Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2766 CallExpr *TheCall) {
2767 ExprResult TheCallResult(TheCall);
2768
2769 // Find out if any arguments are required to be integer constant expressions.
2770 unsigned ICEArguments = 0;
2772 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2774 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2775
2776 // If any arguments are required to be ICE's, check and diagnose.
2777 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2778 // Skip arguments not required to be ICE's.
2779 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2780
2781 llvm::APSInt Result;
2782 // If we don't have enough arguments, continue so we can issue better
2783 // diagnostic in checkArgCount(...)
2784 if (ArgNo < TheCall->getNumArgs() &&
2785 BuiltinConstantArg(TheCall, ArgNo, Result))
2786 return true;
2787 ICEArguments &= ~(1 << ArgNo);
2788 }
2789
2790 FPOptions FPO;
2791 switch (BuiltinID) {
2792 case Builtin::BI__builtin_cpu_supports:
2793 case Builtin::BI__builtin_cpu_is:
2794 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2795 Context.getAuxTargetInfo(), BuiltinID))
2796 return ExprError();
2797 break;
2798 case Builtin::BI__builtin_cpu_init:
2799 if (!Context.getTargetInfo().supportsCpuInit()) {
2800 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2801 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2802 return ExprError();
2803 }
2804 break;
2805 case Builtin::BI__builtin___CFStringMakeConstantString:
2806 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2807 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2809 *this, BuiltinID, TheCall,
2810 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2811 return ExprError();
2812 assert(TheCall->getNumArgs() == 1 &&
2813 "Wrong # arguments to builtin CFStringMakeConstantString");
2814 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2815 return ExprError();
2816 break;
2817 case Builtin::BI__builtin_ms_va_start:
2818 case Builtin::BI__builtin_stdarg_start:
2819 case Builtin::BI__builtin_va_start:
2820 case Builtin::BI__builtin_c23_va_start:
2821 if (BuiltinVAStart(BuiltinID, TheCall))
2822 return ExprError();
2823 break;
2824 case Builtin::BI__va_start: {
2825 switch (Context.getTargetInfo().getTriple().getArch()) {
2826 case llvm::Triple::aarch64:
2827 case llvm::Triple::arm:
2828 case llvm::Triple::thumb:
2829 if (BuiltinVAStartARMMicrosoft(TheCall))
2830 return ExprError();
2831 break;
2832 default:
2833 if (BuiltinVAStart(BuiltinID, TheCall))
2834 return ExprError();
2835 break;
2836 }
2837 break;
2838 }
2839
2840 // The acquire, release, and no fence variants are ARM and AArch64 only.
2841 case Builtin::BI_interlockedbittestandset_acq:
2842 case Builtin::BI_interlockedbittestandset_rel:
2843 case Builtin::BI_interlockedbittestandset_nf:
2844 case Builtin::BI_interlockedbittestandreset_acq:
2845 case Builtin::BI_interlockedbittestandreset_rel:
2846 case Builtin::BI_interlockedbittestandreset_nf:
2848 *this, TheCall,
2849 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2850 return ExprError();
2851 break;
2852
2853 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2854 case Builtin::BI_bittest64:
2855 case Builtin::BI_bittestandcomplement64:
2856 case Builtin::BI_bittestandreset64:
2857 case Builtin::BI_bittestandset64:
2858 case Builtin::BI_interlockedbittestandreset64:
2859 case Builtin::BI_interlockedbittestandset64:
2861 *this, TheCall,
2862 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2863 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2864 return ExprError();
2865 break;
2866
2867 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2868 case Builtin::BI_interlockedbittestandreset64_acq:
2869 case Builtin::BI_interlockedbittestandreset64_rel:
2870 case Builtin::BI_interlockedbittestandreset64_nf:
2871 case Builtin::BI_interlockedbittestandset64_acq:
2872 case Builtin::BI_interlockedbittestandset64_rel:
2873 case Builtin::BI_interlockedbittestandset64_nf:
2874 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
2875 return ExprError();
2876 break;
2877
2878 case Builtin::BI__builtin_set_flt_rounds:
2880 *this, TheCall,
2881 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2882 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2883 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2884 llvm::Triple::ppc64le}))
2885 return ExprError();
2886 break;
2887
2888 case Builtin::BI__builtin_isgreater:
2889 case Builtin::BI__builtin_isgreaterequal:
2890 case Builtin::BI__builtin_isless:
2891 case Builtin::BI__builtin_islessequal:
2892 case Builtin::BI__builtin_islessgreater:
2893 case Builtin::BI__builtin_isunordered:
2894 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2895 return ExprError();
2896 break;
2897 case Builtin::BI__builtin_fpclassify:
2898 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2899 return ExprError();
2900 break;
2901 case Builtin::BI__builtin_isfpclass:
2902 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2903 return ExprError();
2904 break;
2905 case Builtin::BI__builtin_isfinite:
2906 case Builtin::BI__builtin_isinf:
2907 case Builtin::BI__builtin_isinf_sign:
2908 case Builtin::BI__builtin_isnan:
2909 case Builtin::BI__builtin_issignaling:
2910 case Builtin::BI__builtin_isnormal:
2911 case Builtin::BI__builtin_issubnormal:
2912 case Builtin::BI__builtin_iszero:
2913 case Builtin::BI__builtin_signbit:
2914 case Builtin::BI__builtin_signbitf:
2915 case Builtin::BI__builtin_signbitl:
2916 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2917 return ExprError();
2918 break;
2919 case Builtin::BI__builtin_shufflevector:
2920 return BuiltinShuffleVector(TheCall);
2921 // TheCall will be freed by the smart pointer here, but that's fine, since
2922 // BuiltinShuffleVector guts it, but then doesn't release it.
2923 case Builtin::BI__builtin_masked_load:
2924 case Builtin::BI__builtin_masked_expand_load:
2925 return BuiltinMaskedLoad(*this, TheCall);
2926 case Builtin::BI__builtin_masked_store:
2927 case Builtin::BI__builtin_masked_compress_store:
2928 return BuiltinMaskedStore(*this, TheCall);
2929 case Builtin::BI__builtin_masked_gather:
2930 return BuiltinMaskedGather(*this, TheCall);
2931 case Builtin::BI__builtin_masked_scatter:
2932 return BuiltinMaskedScatter(*this, TheCall);
2933 case Builtin::BI__builtin_invoke:
2934 return BuiltinInvoke(*this, TheCall);
2935 case Builtin::BI__builtin_prefetch:
2936 if (BuiltinPrefetch(TheCall))
2937 return ExprError();
2938 break;
2939 case Builtin::BI__builtin_alloca_with_align:
2940 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2941 if (BuiltinAllocaWithAlign(TheCall))
2942 return ExprError();
2943 [[fallthrough]];
2944 case Builtin::BI__builtin_alloca:
2945 case Builtin::BI__builtin_alloca_uninitialized:
2946 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2947 << TheCall->getDirectCallee();
2948 if (getLangOpts().OpenCL) {
2949 builtinAllocaAddrSpace(*this, TheCall);
2950 }
2951 break;
2952 case Builtin::BI__builtin_infer_alloc_token:
2953 if (checkBuiltinInferAllocToken(*this, TheCall))
2954 return ExprError();
2955 break;
2956 case Builtin::BI__arithmetic_fence:
2957 if (BuiltinArithmeticFence(TheCall))
2958 return ExprError();
2959 break;
2960 case Builtin::BI__assume:
2961 case Builtin::BI__builtin_assume:
2962 if (BuiltinAssume(TheCall))
2963 return ExprError();
2964 break;
2965 case Builtin::BI__builtin_assume_aligned:
2966 if (BuiltinAssumeAligned(TheCall))
2967 return ExprError();
2968 break;
2969 case Builtin::BI__builtin_dynamic_object_size:
2970 case Builtin::BI__builtin_object_size:
2971 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2972 return ExprError();
2973 break;
2974 case Builtin::BI__builtin_longjmp:
2975 if (BuiltinLongjmp(TheCall))
2976 return ExprError();
2977 break;
2978 case Builtin::BI__builtin_setjmp:
2979 if (BuiltinSetjmp(TheCall))
2980 return ExprError();
2981 break;
2982 case Builtin::BI__builtin_classify_type:
2983 if (checkArgCount(TheCall, 1))
2984 return true;
2985 TheCall->setType(Context.IntTy);
2986 break;
2987 case Builtin::BI__builtin_complex:
2988 if (BuiltinComplex(TheCall))
2989 return ExprError();
2990 break;
2991 case Builtin::BI__builtin_constant_p: {
2992 if (checkArgCount(TheCall, 1))
2993 return true;
2995 if (Arg.isInvalid()) return true;
2996 TheCall->setArg(0, Arg.get());
2997 TheCall->setType(Context.IntTy);
2998 break;
2999 }
3000 case Builtin::BI__builtin_launder:
3001 return BuiltinLaunder(*this, TheCall);
3002 case Builtin::BI__builtin_is_within_lifetime:
3003 return BuiltinIsWithinLifetime(*this, TheCall);
3004 case Builtin::BI__builtin_trivially_relocate:
3005 return BuiltinTriviallyRelocate(*this, TheCall);
3006
3007 case Builtin::BI__sync_fetch_and_add:
3008 case Builtin::BI__sync_fetch_and_add_1:
3009 case Builtin::BI__sync_fetch_and_add_2:
3010 case Builtin::BI__sync_fetch_and_add_4:
3011 case Builtin::BI__sync_fetch_and_add_8:
3012 case Builtin::BI__sync_fetch_and_add_16:
3013 case Builtin::BI__sync_fetch_and_sub:
3014 case Builtin::BI__sync_fetch_and_sub_1:
3015 case Builtin::BI__sync_fetch_and_sub_2:
3016 case Builtin::BI__sync_fetch_and_sub_4:
3017 case Builtin::BI__sync_fetch_and_sub_8:
3018 case Builtin::BI__sync_fetch_and_sub_16:
3019 case Builtin::BI__sync_fetch_and_or:
3020 case Builtin::BI__sync_fetch_and_or_1:
3021 case Builtin::BI__sync_fetch_and_or_2:
3022 case Builtin::BI__sync_fetch_and_or_4:
3023 case Builtin::BI__sync_fetch_and_or_8:
3024 case Builtin::BI__sync_fetch_and_or_16:
3025 case Builtin::BI__sync_fetch_and_and:
3026 case Builtin::BI__sync_fetch_and_and_1:
3027 case Builtin::BI__sync_fetch_and_and_2:
3028 case Builtin::BI__sync_fetch_and_and_4:
3029 case Builtin::BI__sync_fetch_and_and_8:
3030 case Builtin::BI__sync_fetch_and_and_16:
3031 case Builtin::BI__sync_fetch_and_xor:
3032 case Builtin::BI__sync_fetch_and_xor_1:
3033 case Builtin::BI__sync_fetch_and_xor_2:
3034 case Builtin::BI__sync_fetch_and_xor_4:
3035 case Builtin::BI__sync_fetch_and_xor_8:
3036 case Builtin::BI__sync_fetch_and_xor_16:
3037 case Builtin::BI__sync_fetch_and_nand:
3038 case Builtin::BI__sync_fetch_and_nand_1:
3039 case Builtin::BI__sync_fetch_and_nand_2:
3040 case Builtin::BI__sync_fetch_and_nand_4:
3041 case Builtin::BI__sync_fetch_and_nand_8:
3042 case Builtin::BI__sync_fetch_and_nand_16:
3043 case Builtin::BI__sync_add_and_fetch:
3044 case Builtin::BI__sync_add_and_fetch_1:
3045 case Builtin::BI__sync_add_and_fetch_2:
3046 case Builtin::BI__sync_add_and_fetch_4:
3047 case Builtin::BI__sync_add_and_fetch_8:
3048 case Builtin::BI__sync_add_and_fetch_16:
3049 case Builtin::BI__sync_sub_and_fetch:
3050 case Builtin::BI__sync_sub_and_fetch_1:
3051 case Builtin::BI__sync_sub_and_fetch_2:
3052 case Builtin::BI__sync_sub_and_fetch_4:
3053 case Builtin::BI__sync_sub_and_fetch_8:
3054 case Builtin::BI__sync_sub_and_fetch_16:
3055 case Builtin::BI__sync_and_and_fetch:
3056 case Builtin::BI__sync_and_and_fetch_1:
3057 case Builtin::BI__sync_and_and_fetch_2:
3058 case Builtin::BI__sync_and_and_fetch_4:
3059 case Builtin::BI__sync_and_and_fetch_8:
3060 case Builtin::BI__sync_and_and_fetch_16:
3061 case Builtin::BI__sync_or_and_fetch:
3062 case Builtin::BI__sync_or_and_fetch_1:
3063 case Builtin::BI__sync_or_and_fetch_2:
3064 case Builtin::BI__sync_or_and_fetch_4:
3065 case Builtin::BI__sync_or_and_fetch_8:
3066 case Builtin::BI__sync_or_and_fetch_16:
3067 case Builtin::BI__sync_xor_and_fetch:
3068 case Builtin::BI__sync_xor_and_fetch_1:
3069 case Builtin::BI__sync_xor_and_fetch_2:
3070 case Builtin::BI__sync_xor_and_fetch_4:
3071 case Builtin::BI__sync_xor_and_fetch_8:
3072 case Builtin::BI__sync_xor_and_fetch_16:
3073 case Builtin::BI__sync_nand_and_fetch:
3074 case Builtin::BI__sync_nand_and_fetch_1:
3075 case Builtin::BI__sync_nand_and_fetch_2:
3076 case Builtin::BI__sync_nand_and_fetch_4:
3077 case Builtin::BI__sync_nand_and_fetch_8:
3078 case Builtin::BI__sync_nand_and_fetch_16:
3079 case Builtin::BI__sync_val_compare_and_swap:
3080 case Builtin::BI__sync_val_compare_and_swap_1:
3081 case Builtin::BI__sync_val_compare_and_swap_2:
3082 case Builtin::BI__sync_val_compare_and_swap_4:
3083 case Builtin::BI__sync_val_compare_and_swap_8:
3084 case Builtin::BI__sync_val_compare_and_swap_16:
3085 case Builtin::BI__sync_bool_compare_and_swap:
3086 case Builtin::BI__sync_bool_compare_and_swap_1:
3087 case Builtin::BI__sync_bool_compare_and_swap_2:
3088 case Builtin::BI__sync_bool_compare_and_swap_4:
3089 case Builtin::BI__sync_bool_compare_and_swap_8:
3090 case Builtin::BI__sync_bool_compare_and_swap_16:
3091 case Builtin::BI__sync_lock_test_and_set:
3092 case Builtin::BI__sync_lock_test_and_set_1:
3093 case Builtin::BI__sync_lock_test_and_set_2:
3094 case Builtin::BI__sync_lock_test_and_set_4:
3095 case Builtin::BI__sync_lock_test_and_set_8:
3096 case Builtin::BI__sync_lock_test_and_set_16:
3097 case Builtin::BI__sync_lock_release:
3098 case Builtin::BI__sync_lock_release_1:
3099 case Builtin::BI__sync_lock_release_2:
3100 case Builtin::BI__sync_lock_release_4:
3101 case Builtin::BI__sync_lock_release_8:
3102 case Builtin::BI__sync_lock_release_16:
3103 case Builtin::BI__sync_swap:
3104 case Builtin::BI__sync_swap_1:
3105 case Builtin::BI__sync_swap_2:
3106 case Builtin::BI__sync_swap_4:
3107 case Builtin::BI__sync_swap_8:
3108 case Builtin::BI__sync_swap_16:
3109 return BuiltinAtomicOverloaded(TheCallResult);
3110 case Builtin::BI__sync_synchronize:
3111 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3112 << TheCall->getCallee()->getSourceRange();
3113 break;
3114 case Builtin::BI__builtin_nontemporal_load:
3115 case Builtin::BI__builtin_nontemporal_store:
3116 return BuiltinNontemporalOverloaded(TheCallResult);
3117 case Builtin::BI__builtin_memcpy_inline: {
3118 clang::Expr *SizeOp = TheCall->getArg(2);
3119 // We warn about copying to or from `nullptr` pointers when `size` is
3120 // greater than 0. When `size` is value dependent we cannot evaluate its
3121 // value so we bail out.
3122 if (SizeOp->isValueDependent())
3123 break;
3124 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3125 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3126 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3127 }
3128 break;
3129 }
3130 case Builtin::BI__builtin_memset_inline: {
3131 clang::Expr *SizeOp = TheCall->getArg(2);
3132 // We warn about filling to `nullptr` pointers when `size` is greater than
3133 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3134 // out.
3135 if (SizeOp->isValueDependent())
3136 break;
3137 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3138 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3139 break;
3140 }
3141#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3142 case Builtin::BI##ID: \
3143 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3144#include "clang/Basic/Builtins.inc"
3145 case Builtin::BI__annotation:
3146 if (BuiltinMSVCAnnotation(*this, TheCall))
3147 return ExprError();
3148 break;
3149 case Builtin::BI__builtin_annotation:
3150 if (BuiltinAnnotation(*this, TheCall))
3151 return ExprError();
3152 break;
3153 case Builtin::BI__builtin_addressof:
3154 if (BuiltinAddressof(*this, TheCall))
3155 return ExprError();
3156 break;
3157 case Builtin::BI__builtin_function_start:
3158 if (BuiltinFunctionStart(*this, TheCall))
3159 return ExprError();
3160 break;
3161 case Builtin::BI__builtin_is_aligned:
3162 case Builtin::BI__builtin_align_up:
3163 case Builtin::BI__builtin_align_down:
3164 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3165 return ExprError();
3166 break;
3167 case Builtin::BI__builtin_add_overflow:
3168 case Builtin::BI__builtin_sub_overflow:
3169 case Builtin::BI__builtin_mul_overflow:
3170 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3171 return ExprError();
3172 break;
3173 case Builtin::BI__builtin_operator_new:
3174 case Builtin::BI__builtin_operator_delete: {
3175 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3176 ExprResult Res =
3177 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3178 return Res;
3179 }
3180 case Builtin::BI__builtin_dump_struct:
3181 return BuiltinDumpStruct(*this, TheCall);
3182 case Builtin::BI__builtin_expect_with_probability: {
3183 // We first want to ensure we are called with 3 arguments
3184 if (checkArgCount(TheCall, 3))
3185 return ExprError();
3186 // then check probability is constant float in range [0.0, 1.0]
3187 const Expr *ProbArg = TheCall->getArg(2);
3188 SmallVector<PartialDiagnosticAt, 8> Notes;
3189 Expr::EvalResult Eval;
3190 Eval.Diag = &Notes;
3191 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3192 !Eval.Val.isFloat()) {
3193 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3194 << ProbArg->getSourceRange();
3195 for (const PartialDiagnosticAt &PDiag : Notes)
3196 Diag(PDiag.first, PDiag.second);
3197 return ExprError();
3198 }
3199 llvm::APFloat Probability = Eval.Val.getFloat();
3200 bool LoseInfo = false;
3201 Probability.convert(llvm::APFloat::IEEEdouble(),
3202 llvm::RoundingMode::Dynamic, &LoseInfo);
3203 if (!(Probability >= llvm::APFloat(0.0) &&
3204 Probability <= llvm::APFloat(1.0))) {
3205 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3206 << ProbArg->getSourceRange();
3207 return ExprError();
3208 }
3209 break;
3210 }
3211 case Builtin::BI__builtin_preserve_access_index:
3212 if (BuiltinPreserveAI(*this, TheCall))
3213 return ExprError();
3214 break;
3215 case Builtin::BI__builtin_call_with_static_chain:
3216 if (BuiltinCallWithStaticChain(*this, TheCall))
3217 return ExprError();
3218 break;
3219 case Builtin::BI__exception_code:
3220 case Builtin::BI_exception_code:
3221 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3222 diag::err_seh___except_block))
3223 return ExprError();
3224 break;
3225 case Builtin::BI__exception_info:
3226 case Builtin::BI_exception_info:
3227 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3228 diag::err_seh___except_filter))
3229 return ExprError();
3230 break;
3231 case Builtin::BI__GetExceptionInfo:
3232 if (checkArgCount(TheCall, 1))
3233 return ExprError();
3234
3236 TheCall->getBeginLoc(),
3237 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3238 TheCall))
3239 return ExprError();
3240
3241 TheCall->setType(Context.VoidPtrTy);
3242 break;
3243 case Builtin::BIaddressof:
3244 case Builtin::BI__addressof:
3245 case Builtin::BIforward:
3246 case Builtin::BIforward_like:
3247 case Builtin::BImove:
3248 case Builtin::BImove_if_noexcept:
3249 case Builtin::BIas_const: {
3250 // These are all expected to be of the form
3251 // T &/&&/* f(U &/&&)
3252 // where T and U only differ in qualification.
3253 if (checkArgCount(TheCall, 1))
3254 return ExprError();
3255 QualType Param = FDecl->getParamDecl(0)->getType();
3256 QualType Result = FDecl->getReturnType();
3257 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3258 BuiltinID == Builtin::BI__addressof;
3259 if (!(Param->isReferenceType() &&
3260 (ReturnsPointer ? Result->isAnyPointerType()
3261 : Result->isReferenceType()) &&
3262 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3263 Result->getPointeeType()))) {
3264 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3265 << FDecl;
3266 return ExprError();
3267 }
3268 break;
3269 }
3270 case Builtin::BI__builtin_ptrauth_strip:
3271 return PointerAuthStrip(*this, TheCall);
3272 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3273 return PointerAuthBlendDiscriminator(*this, TheCall);
3274 case Builtin::BI__builtin_ptrauth_sign_constant:
3275 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3276 /*RequireConstant=*/true);
3277 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3278 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3279 /*RequireConstant=*/false);
3280 case Builtin::BI__builtin_ptrauth_auth:
3281 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3282 /*RequireConstant=*/false);
3283 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3284 return PointerAuthSignGenericData(*this, TheCall);
3285 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3286 return PointerAuthAuthAndResign(*this, TheCall);
3287 case Builtin::BI__builtin_ptrauth_string_discriminator:
3288 return PointerAuthStringDiscriminator(*this, TheCall);
3289
3290 case Builtin::BI__builtin_get_vtable_pointer:
3291 return GetVTablePointer(*this, TheCall);
3292
3293 // OpenCL v2.0, s6.13.16 - Pipe functions
3294 case Builtin::BIread_pipe:
3295 case Builtin::BIwrite_pipe:
3296 // Since those two functions are declared with var args, we need a semantic
3297 // check for the argument.
3298 if (OpenCL().checkBuiltinRWPipe(TheCall))
3299 return ExprError();
3300 break;
3301 case Builtin::BIreserve_read_pipe:
3302 case Builtin::BIreserve_write_pipe:
3303 case Builtin::BIwork_group_reserve_read_pipe:
3304 case Builtin::BIwork_group_reserve_write_pipe:
3305 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3306 return ExprError();
3307 break;
3308 case Builtin::BIsub_group_reserve_read_pipe:
3309 case Builtin::BIsub_group_reserve_write_pipe:
3310 if (OpenCL().checkSubgroupExt(TheCall) ||
3311 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3312 return ExprError();
3313 break;
3314 case Builtin::BIcommit_read_pipe:
3315 case Builtin::BIcommit_write_pipe:
3316 case Builtin::BIwork_group_commit_read_pipe:
3317 case Builtin::BIwork_group_commit_write_pipe:
3318 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3319 return ExprError();
3320 break;
3321 case Builtin::BIsub_group_commit_read_pipe:
3322 case Builtin::BIsub_group_commit_write_pipe:
3323 if (OpenCL().checkSubgroupExt(TheCall) ||
3324 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3325 return ExprError();
3326 break;
3327 case Builtin::BIget_pipe_num_packets:
3328 case Builtin::BIget_pipe_max_packets:
3329 if (OpenCL().checkBuiltinPipePackets(TheCall))
3330 return ExprError();
3331 break;
3332 case Builtin::BIto_global:
3333 case Builtin::BIto_local:
3334 case Builtin::BIto_private:
3335 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3336 return ExprError();
3337 break;
3338 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3339 case Builtin::BIenqueue_kernel:
3340 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3341 return ExprError();
3342 break;
3343 case Builtin::BIget_kernel_work_group_size:
3344 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3345 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3346 return ExprError();
3347 break;
3348 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3349 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3350 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3351 return ExprError();
3352 break;
3353 case Builtin::BI__builtin_os_log_format:
3354 Cleanup.setExprNeedsCleanups(true);
3355 [[fallthrough]];
3356 case Builtin::BI__builtin_os_log_format_buffer_size:
3357 if (BuiltinOSLogFormat(TheCall))
3358 return ExprError();
3359 break;
3360 case Builtin::BI__builtin_frame_address:
3361 case Builtin::BI__builtin_return_address: {
3362 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3363 return ExprError();
3364
3365 // -Wframe-address warning if non-zero passed to builtin
3366 // return/frame address.
3367 Expr::EvalResult Result;
3368 if (!TheCall->getArg(0)->isValueDependent() &&
3369 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3370 Result.Val.getInt() != 0)
3371 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3372 << ((BuiltinID == Builtin::BI__builtin_return_address)
3373 ? "__builtin_return_address"
3374 : "__builtin_frame_address")
3375 << TheCall->getSourceRange();
3376 break;
3377 }
3378
3379 case Builtin::BI__builtin_nondeterministic_value: {
3380 if (BuiltinNonDeterministicValue(TheCall))
3381 return ExprError();
3382 break;
3383 }
3384
3385 // __builtin_elementwise_abs restricts the element type to signed integers or
3386 // floating point types only.
3387 case Builtin::BI__builtin_elementwise_abs:
3390 return ExprError();
3391 break;
3392
3393 // These builtins restrict the element type to floating point
3394 // types only.
3395 case Builtin::BI__builtin_elementwise_acos:
3396 case Builtin::BI__builtin_elementwise_asin:
3397 case Builtin::BI__builtin_elementwise_atan:
3398 case Builtin::BI__builtin_elementwise_ceil:
3399 case Builtin::BI__builtin_elementwise_cos:
3400 case Builtin::BI__builtin_elementwise_cosh:
3401 case Builtin::BI__builtin_elementwise_exp:
3402 case Builtin::BI__builtin_elementwise_exp2:
3403 case Builtin::BI__builtin_elementwise_exp10:
3404 case Builtin::BI__builtin_elementwise_floor:
3405 case Builtin::BI__builtin_elementwise_log:
3406 case Builtin::BI__builtin_elementwise_log2:
3407 case Builtin::BI__builtin_elementwise_log10:
3408 case Builtin::BI__builtin_elementwise_roundeven:
3409 case Builtin::BI__builtin_elementwise_round:
3410 case Builtin::BI__builtin_elementwise_rint:
3411 case Builtin::BI__builtin_elementwise_nearbyint:
3412 case Builtin::BI__builtin_elementwise_sin:
3413 case Builtin::BI__builtin_elementwise_sinh:
3414 case Builtin::BI__builtin_elementwise_sqrt:
3415 case Builtin::BI__builtin_elementwise_tan:
3416 case Builtin::BI__builtin_elementwise_tanh:
3417 case Builtin::BI__builtin_elementwise_trunc:
3418 case Builtin::BI__builtin_elementwise_canonicalize:
3421 return ExprError();
3422 break;
3423 case Builtin::BI__builtin_elementwise_fma:
3424 if (BuiltinElementwiseTernaryMath(TheCall))
3425 return ExprError();
3426 break;
3427
3428 case Builtin::BI__builtin_elementwise_ldexp: {
3429 if (checkArgCount(TheCall, 2))
3430 return ExprError();
3431
3432 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3433 if (A.isInvalid())
3434 return ExprError();
3435 QualType TyA = A.get()->getType();
3436 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3438 return ExprError();
3439
3440 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3441 if (Exp.isInvalid())
3442 return ExprError();
3443 QualType TyExp = Exp.get()->getType();
3444 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3446 2))
3447 return ExprError();
3448
3449 // Check the two arguments are either scalars or vectors of equal length.
3450 const auto *Vec0 = TyA->getAs<VectorType>();
3451 const auto *Vec1 = TyExp->getAs<VectorType>();
3452 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3453 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3454 if (Arg0Length != Arg1Length) {
3455 Diag(Exp.get()->getBeginLoc(),
3456 diag::err_typecheck_vector_lengths_not_equal)
3457 << TyA << TyExp << A.get()->getSourceRange()
3458 << Exp.get()->getSourceRange();
3459 return ExprError();
3460 }
3461
3462 TheCall->setArg(0, A.get());
3463 TheCall->setArg(1, Exp.get());
3464 TheCall->setType(TyA);
3465 break;
3466 }
3467
3468 // These builtins restrict the element type to floating point
3469 // types only, and take in two arguments.
3470 case Builtin::BI__builtin_elementwise_minnum:
3471 case Builtin::BI__builtin_elementwise_maxnum:
3472 case Builtin::BI__builtin_elementwise_minimum:
3473 case Builtin::BI__builtin_elementwise_maximum:
3474 case Builtin::BI__builtin_elementwise_minimumnum:
3475 case Builtin::BI__builtin_elementwise_maximumnum:
3476 case Builtin::BI__builtin_elementwise_atan2:
3477 case Builtin::BI__builtin_elementwise_fmod:
3478 case Builtin::BI__builtin_elementwise_pow:
3479 if (BuiltinElementwiseMath(TheCall,
3481 return ExprError();
3482 break;
3483 // These builtins restrict the element type to integer
3484 // types only.
3485 case Builtin::BI__builtin_elementwise_add_sat:
3486 case Builtin::BI__builtin_elementwise_sub_sat:
3487 if (BuiltinElementwiseMath(TheCall,
3489 return ExprError();
3490 break;
3491 case Builtin::BI__builtin_elementwise_fshl:
3492 case Builtin::BI__builtin_elementwise_fshr:
3495 return ExprError();
3496 break;
3497 case Builtin::BI__builtin_elementwise_min:
3498 case Builtin::BI__builtin_elementwise_max:
3499 if (BuiltinElementwiseMath(TheCall))
3500 return ExprError();
3501 break;
3502 case Builtin::BI__builtin_elementwise_popcount:
3503 case Builtin::BI__builtin_elementwise_bitreverse:
3506 return ExprError();
3507 break;
3508 case Builtin::BI__builtin_elementwise_copysign: {
3509 if (checkArgCount(TheCall, 2))
3510 return ExprError();
3511
3512 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3513 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3514 if (Magnitude.isInvalid() || Sign.isInvalid())
3515 return ExprError();
3516
3517 QualType MagnitudeTy = Magnitude.get()->getType();
3518 QualType SignTy = Sign.get()->getType();
3520 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3523 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3525 return ExprError();
3526 }
3527
3528 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3529 return Diag(Sign.get()->getBeginLoc(),
3530 diag::err_typecheck_call_different_arg_types)
3531 << MagnitudeTy << SignTy;
3532 }
3533
3534 TheCall->setArg(0, Magnitude.get());
3535 TheCall->setArg(1, Sign.get());
3536 TheCall->setType(Magnitude.get()->getType());
3537 break;
3538 }
3539 case Builtin::BI__builtin_elementwise_clzg:
3540 case Builtin::BI__builtin_elementwise_ctzg:
3541 // These builtins can be unary or binary. Note for empty calls we call the
3542 // unary checker in order to not emit an error that says the function
3543 // expects 2 arguments, which would be misleading.
3544 if (TheCall->getNumArgs() <= 1) {
3547 return ExprError();
3548 } else if (BuiltinElementwiseMath(
3550 return ExprError();
3551 break;
3552 case Builtin::BI__builtin_reduce_max:
3553 case Builtin::BI__builtin_reduce_min: {
3554 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3555 return ExprError();
3556
3557 const Expr *Arg = TheCall->getArg(0);
3558 const auto *TyA = Arg->getType()->getAs<VectorType>();
3559
3560 QualType ElTy;
3561 if (TyA)
3562 ElTy = TyA->getElementType();
3563 else if (Arg->getType()->isSizelessVectorType())
3565
3566 if (ElTy.isNull()) {
3567 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3568 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3569 << Arg->getType();
3570 return ExprError();
3571 }
3572
3573 TheCall->setType(ElTy);
3574 break;
3575 }
3576 case Builtin::BI__builtin_reduce_maximum:
3577 case Builtin::BI__builtin_reduce_minimum: {
3578 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3579 return ExprError();
3580
3581 const Expr *Arg = TheCall->getArg(0);
3582 const auto *TyA = Arg->getType()->getAs<VectorType>();
3583
3584 QualType ElTy;
3585 if (TyA)
3586 ElTy = TyA->getElementType();
3587 else if (Arg->getType()->isSizelessVectorType())
3589
3590 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3591 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3592 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3593 << Arg->getType();
3594 return ExprError();
3595 }
3596
3597 TheCall->setType(ElTy);
3598 break;
3599 }
3600
3601 // These builtins support vectors of integers only.
3602 // TODO: ADD/MUL should support floating-point types.
3603 case Builtin::BI__builtin_reduce_add:
3604 case Builtin::BI__builtin_reduce_mul:
3605 case Builtin::BI__builtin_reduce_xor:
3606 case Builtin::BI__builtin_reduce_or:
3607 case Builtin::BI__builtin_reduce_and: {
3608 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3609 return ExprError();
3610
3611 const Expr *Arg = TheCall->getArg(0);
3612 const auto *TyA = Arg->getType()->getAs<VectorType>();
3613
3614 QualType ElTy;
3615 if (TyA)
3616 ElTy = TyA->getElementType();
3617 else if (Arg->getType()->isSizelessVectorType())
3619
3620 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3621 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3622 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3623 << Arg->getType();
3624 return ExprError();
3625 }
3626
3627 TheCall->setType(ElTy);
3628 break;
3629 }
3630
3631 case Builtin::BI__builtin_matrix_transpose:
3632 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3633
3634 case Builtin::BI__builtin_matrix_column_major_load:
3635 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3636
3637 case Builtin::BI__builtin_matrix_column_major_store:
3638 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3639
3640 case Builtin::BI__builtin_verbose_trap:
3641 if (!checkBuiltinVerboseTrap(TheCall, *this))
3642 return ExprError();
3643 break;
3644
3645 case Builtin::BI__builtin_get_device_side_mangled_name: {
3646 auto Check = [](CallExpr *TheCall) {
3647 if (TheCall->getNumArgs() != 1)
3648 return false;
3649 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3650 if (!DRE)
3651 return false;
3652 auto *D = DRE->getDecl();
3653 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3654 return false;
3655 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3656 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3657 };
3658 if (!Check(TheCall)) {
3659 Diag(TheCall->getBeginLoc(),
3660 diag::err_hip_invalid_args_builtin_mangled_name);
3661 return ExprError();
3662 }
3663 break;
3664 }
3665 case Builtin::BI__builtin_bswapg:
3666 if (BuiltinBswapg(*this, TheCall))
3667 return ExprError();
3668 break;
3669 case Builtin::BI__builtin_popcountg:
3670 if (BuiltinPopcountg(*this, TheCall))
3671 return ExprError();
3672 break;
3673 case Builtin::BI__builtin_clzg:
3674 case Builtin::BI__builtin_ctzg:
3675 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3676 return ExprError();
3677 break;
3678
3679 case Builtin::BI__builtin_stdc_rotate_left:
3680 case Builtin::BI__builtin_stdc_rotate_right:
3681 if (BuiltinRotateGeneric(*this, TheCall))
3682 return ExprError();
3683 break;
3684
3685 case Builtin::BI__builtin_allow_runtime_check: {
3686 Expr *Arg = TheCall->getArg(0);
3687 // Check if the argument is a string literal.
3689 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3690 << Arg->getSourceRange();
3691 return ExprError();
3692 }
3693 break;
3694 }
3695
3696 case Builtin::BI__builtin_allow_sanitize_check: {
3697 Expr *Arg = TheCall->getArg(0);
3698 // Check if the argument is a string literal.
3699 const StringLiteral *SanitizerName =
3700 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
3701 if (!SanitizerName) {
3702 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3703 << Arg->getSourceRange();
3704 return ExprError();
3705 }
3706 // Validate the sanitizer name.
3707 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3708 .Cases({"address", "thread", "memory", "hwaddress",
3709 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3710 true)
3711 .Default(false)) {
3712 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
3713 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3714 << Arg->getSourceRange();
3715 return ExprError();
3716 }
3717 break;
3718 }
3719 case Builtin::BI__builtin_counted_by_ref:
3720 if (BuiltinCountedByRef(TheCall))
3721 return ExprError();
3722 break;
3723 }
3724
3725 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3726 return ExprError();
3727
3728 // Since the target specific builtins for each arch overlap, only check those
3729 // of the arch we are compiling for.
3730 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3731 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3732 assert(Context.getAuxTargetInfo() &&
3733 "Aux Target Builtin, but not an aux target?");
3734
3735 if (CheckTSBuiltinFunctionCall(
3736 *Context.getAuxTargetInfo(),
3737 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3738 return ExprError();
3739 } else {
3740 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3741 TheCall))
3742 return ExprError();
3743 }
3744 }
3745
3746 return TheCallResult;
3747}
3748
3749bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3750 llvm::APSInt Result;
3751 // We can't check the value of a dependent argument.
3752 Expr *Arg = TheCall->getArg(ArgNum);
3753 if (Arg->isTypeDependent() || Arg->isValueDependent())
3754 return false;
3755
3756 // Check constant-ness first.
3757 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3758 return true;
3759
3760 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3761 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3762 return false;
3763
3764 return Diag(TheCall->getBeginLoc(),
3765 diag::err_argument_not_contiguous_bit_field)
3766 << ArgNum << Arg->getSourceRange();
3767}
3768
3769bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3770 unsigned FirstArg, FormatStringInfo *FSI) {
3771 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3772 bool IsVariadic = false;
3773 if (const FunctionType *FnTy = D->getFunctionType())
3774 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3775 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3776 IsVariadic = BD->isVariadic();
3777 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3778 IsVariadic = OMD->isVariadic();
3779
3780 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3781 IsVariadic, FSI);
3782}
3783
3784bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3785 bool HasImplicitThisParam, bool IsVariadic,
3786 FormatStringInfo *FSI) {
3787 if (FirstArg == 0)
3789 else if (IsVariadic)
3791 else
3793 FSI->FormatIdx = FormatIdx - 1;
3794 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3795
3796 // The way the format attribute works in GCC, the implicit this argument
3797 // of member functions is counted. However, it doesn't appear in our own
3798 // lists, so decrement format_idx in that case.
3799 if (HasImplicitThisParam) {
3800 if(FSI->FormatIdx == 0)
3801 return false;
3802 --FSI->FormatIdx;
3803 if (FSI->FirstDataArg != 0)
3804 --FSI->FirstDataArg;
3805 }
3806 return true;
3807}
3808
3809/// Checks if a the given expression evaluates to null.
3810///
3811/// Returns true if the value evaluates to null.
3812static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3813 // Treat (smart) pointers constructed from nullptr as null, whether we can
3814 // const-evaluate them or not.
3815 // This must happen first: the smart pointer expr might have _Nonnull type!
3819 return true;
3820
3821 // If the expression has non-null type, it doesn't evaluate to null.
3822 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3823 if (*nullability == NullabilityKind::NonNull)
3824 return false;
3825 }
3826
3827 // As a special case, transparent unions initialized with zero are
3828 // considered null for the purposes of the nonnull attribute.
3829 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3830 UT &&
3831 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3832 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3833 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3834 Expr = ILE->getInit(0);
3835 }
3836
3837 bool Result;
3838 return (!Expr->isValueDependent() &&
3840 !Result);
3841}
3842
3844 const Expr *ArgExpr,
3845 SourceLocation CallSiteLoc) {
3846 if (CheckNonNullExpr(S, ArgExpr))
3847 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3848 S.PDiag(diag::warn_null_arg)
3849 << ArgExpr->getSourceRange());
3850}
3851
3852/// Determine whether the given type has a non-null nullability annotation.
3854 if (auto nullability = type->getNullability())
3855 return *nullability == NullabilityKind::NonNull;
3856
3857 return false;
3858}
3859
3861 const NamedDecl *FDecl,
3862 const FunctionProtoType *Proto,
3864 SourceLocation CallSiteLoc) {
3865 assert((FDecl || Proto) && "Need a function declaration or prototype");
3866
3867 // Already checked by constant evaluator.
3869 return;
3870 // Check the attributes attached to the method/function itself.
3871 llvm::SmallBitVector NonNullArgs;
3872 if (FDecl) {
3873 // Handle the nonnull attribute on the function/method declaration itself.
3874 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3875 if (!NonNull->args_size()) {
3876 // Easy case: all pointer arguments are nonnull.
3877 for (const auto *Arg : Args)
3878 if (S.isValidPointerAttrType(Arg->getType()))
3879 CheckNonNullArgument(S, Arg, CallSiteLoc);
3880 return;
3881 }
3882
3883 for (const ParamIdx &Idx : NonNull->args()) {
3884 unsigned IdxAST = Idx.getASTIndex();
3885 if (IdxAST >= Args.size())
3886 continue;
3887 if (NonNullArgs.empty())
3888 NonNullArgs.resize(Args.size());
3889 NonNullArgs.set(IdxAST);
3890 }
3891 }
3892 }
3893
3894 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3895 // Handle the nonnull attribute on the parameters of the
3896 // function/method.
3898 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3899 parms = FD->parameters();
3900 else
3901 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3902
3903 unsigned ParamIndex = 0;
3904 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3905 I != E; ++I, ++ParamIndex) {
3906 const ParmVarDecl *PVD = *I;
3907 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3908 if (NonNullArgs.empty())
3909 NonNullArgs.resize(Args.size());
3910
3911 NonNullArgs.set(ParamIndex);
3912 }
3913 }
3914 } else {
3915 // If we have a non-function, non-method declaration but no
3916 // function prototype, try to dig out the function prototype.
3917 if (!Proto) {
3918 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3919 QualType type = VD->getType().getNonReferenceType();
3920 if (auto pointerType = type->getAs<PointerType>())
3921 type = pointerType->getPointeeType();
3922 else if (auto blockType = type->getAs<BlockPointerType>())
3923 type = blockType->getPointeeType();
3924 // FIXME: data member pointers?
3925
3926 // Dig out the function prototype, if there is one.
3927 Proto = type->getAs<FunctionProtoType>();
3928 }
3929 }
3930
3931 // Fill in non-null argument information from the nullability
3932 // information on the parameter types (if we have them).
3933 if (Proto) {
3934 unsigned Index = 0;
3935 for (auto paramType : Proto->getParamTypes()) {
3936 if (isNonNullType(paramType)) {
3937 if (NonNullArgs.empty())
3938 NonNullArgs.resize(Args.size());
3939
3940 NonNullArgs.set(Index);
3941 }
3942
3943 ++Index;
3944 }
3945 }
3946 }
3947
3948 // Check for non-null arguments.
3949 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3950 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3951 if (NonNullArgs[ArgIndex])
3952 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3953 }
3954}
3955
3956void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3957 StringRef ParamName, QualType ArgTy,
3958 QualType ParamTy) {
3959
3960 // If a function accepts a pointer or reference type
3961 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3962 return;
3963
3964 // If the parameter is a pointer type, get the pointee type for the
3965 // argument too. If the parameter is a reference type, don't try to get
3966 // the pointee type for the argument.
3967 if (ParamTy->isPointerType())
3968 ArgTy = ArgTy->getPointeeType();
3969
3970 // Remove reference or pointer
3971 ParamTy = ParamTy->getPointeeType();
3972
3973 // Find expected alignment, and the actual alignment of the passed object.
3974 // getTypeAlignInChars requires complete types
3975 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3976 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3977 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3978 return;
3979
3980 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3981 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3982
3983 // If the argument is less aligned than the parameter, there is a
3984 // potential alignment issue.
3985 if (ArgAlign < ParamAlign)
3986 Diag(Loc, diag::warn_param_mismatched_alignment)
3987 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3988 << ParamName << (FDecl != nullptr) << FDecl;
3989}
3990
3991void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3992 const Expr *ThisArg,
3994 if (!FD || Args.empty())
3995 return;
3996 auto GetArgAt = [&](int Idx) -> const Expr * {
3997 if (Idx == LifetimeCaptureByAttr::Global ||
3998 Idx == LifetimeCaptureByAttr::Unknown)
3999 return nullptr;
4000 if (IsMemberFunction && Idx == 0)
4001 return ThisArg;
4002 return Args[Idx - IsMemberFunction];
4003 };
4004 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4005 unsigned ArgIdx) {
4006 if (!Attr)
4007 return;
4008
4009 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4010 for (int CapturingParamIdx : Attr->params()) {
4011 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4012 // initialization codepath.
4013 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4015 continue;
4016 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4017 CapturingEntity CE{Capturing};
4018 // Ensure that 'Captured' outlives the 'Capturing' entity.
4019 checkCaptureByLifetime(*this, CE, Captured);
4020 }
4021 };
4022 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4023 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4024 I + IsMemberFunction);
4025 // Check when the implicit object param is captured.
4026 if (IsMemberFunction) {
4027 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4028 if (!TSI)
4029 return;
4031 for (TypeLoc TL = TSI->getTypeLoc();
4032 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4033 TL = ATL.getModifiedLoc())
4034 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4035 }
4036}
4037
4039 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4040 bool IsMemberFunction, SourceLocation Loc,
4041 SourceRange Range, VariadicCallType CallType) {
4042 // FIXME: We should check as much as we can in the template definition.
4043 if (CurContext->isDependentContext())
4044 return;
4045
4046 // Printf and scanf checking.
4047 llvm::SmallBitVector CheckedVarArgs;
4048 if (FDecl) {
4049 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4050 // Only create vector if there are format attributes.
4051 CheckedVarArgs.resize(Args.size());
4052 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4053 CheckedVarArgs);
4054 }
4055
4056 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4057 CheckedVarArgs.resize(Args.size());
4058 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4059 CheckedVarArgs);
4060 }
4061 }
4062
4063 // Refuse POD arguments that weren't caught by the format string
4064 // checks above.
4065 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4066 if (CallType != VariadicCallType::DoesNotApply &&
4067 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4068 unsigned NumParams = Proto ? Proto->getNumParams()
4069 : isa_and_nonnull<FunctionDecl>(FDecl)
4070 ? cast<FunctionDecl>(FDecl)->getNumParams()
4071 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4072 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4073 : 0;
4074
4075 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4076 // Args[ArgIdx] can be null in malformed code.
4077 if (const Expr *Arg = Args[ArgIdx]) {
4078 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4079 checkVariadicArgument(Arg, CallType);
4080 }
4081 }
4082 }
4083 if (FD)
4084 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4085 if (FDecl || Proto) {
4086 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4087
4088 // Type safety checking.
4089 if (FDecl) {
4090 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4091 CheckArgumentWithTypeTag(I, Args, Loc);
4092 }
4093 }
4094
4095 // Check that passed arguments match the alignment of original arguments.
4096 // Try to get the missing prototype from the declaration.
4097 if (!Proto && FDecl) {
4098 const auto *FT = FDecl->getFunctionType();
4099 if (isa_and_nonnull<FunctionProtoType>(FT))
4100 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4101 }
4102 if (Proto) {
4103 // For variadic functions, we may have more args than parameters.
4104 // For some K&R functions, we may have less args than parameters.
4105 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4106 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4107 bool IsScalableArg = false;
4108 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4109 // Args[ArgIdx] can be null in malformed code.
4110 if (const Expr *Arg = Args[ArgIdx]) {
4111 if (Arg->containsErrors())
4112 continue;
4113
4114 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4115 FDecl->hasLinkage() &&
4116 FDecl->getFormalLinkage() != Linkage::Internal &&
4118 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4119
4120 QualType ParamTy = Proto->getParamType(ArgIdx);
4121 if (ParamTy->isSizelessVectorType())
4122 IsScalableArg = true;
4123 QualType ArgTy = Arg->getType();
4124 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4125 ArgTy, ParamTy);
4126 }
4127 }
4128
4129 // If the callee has an AArch64 SME attribute to indicate that it is an
4130 // __arm_streaming function, then the caller requires SME to be available.
4133 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4134 llvm::StringMap<bool> CallerFeatureMap;
4135 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4136 if (!CallerFeatureMap.contains("sme"))
4137 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4138 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4139 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4140 }
4141 }
4142
4143 // If the call requires a streaming-mode change and has scalable vector
4144 // arguments or return values, then warn the user that the streaming and
4145 // non-streaming vector lengths may be different.
4146 // When both streaming and non-streaming vector lengths are defined and
4147 // mismatched, produce an error.
4148 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4149 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4150 (IsScalableArg || IsScalableRet)) {
4151 bool IsCalleeStreaming =
4153 bool IsCalleeStreamingCompatible =
4154 ExtInfo.AArch64SMEAttributes &
4156 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4157 if (!IsCalleeStreamingCompatible &&
4158 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4159 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4160 const LangOptions &LO = getLangOpts();
4161 unsigned VL = LO.VScaleMin * 128;
4162 unsigned SVL = LO.VScaleStreamingMin * 128;
4163 bool IsVLMismatch = VL && SVL && VL != SVL;
4164
4165 auto EmitDiag = [&](bool IsArg) {
4166 if (IsVLMismatch) {
4167 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4168 // Emit warning for streaming-compatible callers
4169 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4170 << IsArg << IsCalleeStreaming << SVL << VL;
4171 else
4172 // Emit error otherwise
4173 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4174 << IsArg << SVL << VL;
4175 } else
4176 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4177 << IsArg;
4178 };
4179
4180 if (IsScalableArg)
4181 EmitDiag(true);
4182 if (IsScalableRet)
4183 EmitDiag(false);
4184 }
4185 }
4186
4187 FunctionType::ArmStateValue CalleeArmZAState =
4189 FunctionType::ArmStateValue CalleeArmZT0State =
4191 if (CalleeArmZAState != FunctionType::ARM_None ||
4192 CalleeArmZT0State != FunctionType::ARM_None) {
4193 bool CallerHasZAState = false;
4194 bool CallerHasZT0State = false;
4195 if (CallerFD) {
4196 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4197 if (Attr && Attr->isNewZA())
4198 CallerHasZAState = true;
4199 if (Attr && Attr->isNewZT0())
4200 CallerHasZT0State = true;
4201 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4202 CallerHasZAState |=
4204 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4206 CallerHasZT0State |=
4208 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4210 }
4211 }
4212
4213 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4214 Diag(Loc, diag::err_sme_za_call_no_za_state);
4215
4216 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4217 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4218
4219 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4220 CalleeArmZT0State != FunctionType::ARM_None) {
4221 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4222 Diag(Loc, diag::note_sme_use_preserves_za);
4223 }
4224 }
4225 }
4226
4227 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4228 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4229 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4230 if (!Arg->isValueDependent()) {
4231 Expr::EvalResult Align;
4232 if (Arg->EvaluateAsInt(Align, Context)) {
4233 const llvm::APSInt &I = Align.Val.getInt();
4234 if (!I.isPowerOf2())
4235 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4236 << Arg->getSourceRange();
4237
4238 if (I > Sema::MaximumAlignment)
4239 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4240 << Arg->getSourceRange() << Sema::MaximumAlignment;
4241 }
4242 }
4243 }
4244
4245 if (FD)
4246 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4247}
4248
4249void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4250 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4251 DiagnoseUseOfDecl(Decl, Loc);
4252 }
4253}
4254
4255void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4257 const FunctionProtoType *Proto,
4258 SourceLocation Loc) {
4259 VariadicCallType CallType = Proto->isVariadic()
4262
4263 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4264 CheckArgAlignment(
4265 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4266 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4267
4268 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4269 Loc, SourceRange(), CallType);
4270}
4271
4273 const FunctionProtoType *Proto) {
4274 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4275 isa<CXXMethodDecl>(FDecl);
4276 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4277 IsMemberOperatorCall;
4278 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4279 TheCall->getCallee());
4280 Expr** Args = TheCall->getArgs();
4281 unsigned NumArgs = TheCall->getNumArgs();
4282
4283 Expr *ImplicitThis = nullptr;
4284 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4285 // If this is a call to a member operator, hide the first
4286 // argument from checkCall.
4287 // FIXME: Our choice of AST representation here is less than ideal.
4288 ImplicitThis = Args[0];
4289 ++Args;
4290 --NumArgs;
4291 } else if (IsMemberFunction && !FDecl->isStatic() &&
4293 ImplicitThis =
4294 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4295
4296 if (ImplicitThis) {
4297 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4298 // used.
4299 QualType ThisType = ImplicitThis->getType();
4300 if (!ThisType->isPointerType()) {
4301 assert(!ThisType->isReferenceType());
4302 ThisType = Context.getPointerType(ThisType);
4303 }
4304
4305 QualType ThisTypeFromDecl = Context.getPointerType(
4306 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4307
4308 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4309 ThisTypeFromDecl);
4310 }
4311
4312 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4313 IsMemberFunction, TheCall->getRParenLoc(),
4314 TheCall->getCallee()->getSourceRange(), CallType);
4315
4316 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4317 // None of the checks below are needed for functions that don't have
4318 // simple names (e.g., C++ conversion functions).
4319 if (!FnInfo)
4320 return false;
4321
4322 // Enforce TCB except for builtin calls, which are always allowed.
4323 if (FDecl->getBuiltinID() == 0)
4324 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4325
4326 CheckAbsoluteValueFunction(TheCall, FDecl);
4327 CheckMaxUnsignedZero(TheCall, FDecl);
4328 CheckInfNaNFunction(TheCall, FDecl);
4329
4330 if (getLangOpts().ObjC)
4331 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4332
4333 unsigned CMId = FDecl->getMemoryFunctionKind();
4334
4335 // Handle memory setting and copying functions.
4336 switch (CMId) {
4337 case 0:
4338 return false;
4339 case Builtin::BIstrlcpy: // fallthrough
4340 case Builtin::BIstrlcat:
4341 CheckStrlcpycatArguments(TheCall, FnInfo);
4342 break;
4343 case Builtin::BIstrncat:
4344 CheckStrncatArguments(TheCall, FnInfo);
4345 break;
4346 case Builtin::BIfree:
4347 CheckFreeArguments(TheCall);
4348 break;
4349 default:
4350 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4351 }
4352
4353 return false;
4354}
4355
4356bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4357 const FunctionProtoType *Proto) {
4358 QualType Ty;
4359 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4360 Ty = V->getType().getNonReferenceType();
4361 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4362 Ty = F->getType().getNonReferenceType();
4363 else
4364 return false;
4365
4366 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4367 !Ty->isFunctionProtoType())
4368 return false;
4369
4370 VariadicCallType CallType;
4371 if (!Proto || !Proto->isVariadic()) {
4373 } else if (Ty->isBlockPointerType()) {
4374 CallType = VariadicCallType::Block;
4375 } else { // Ty->isFunctionPointerType()
4376 CallType = VariadicCallType::Function;
4377 }
4378
4379 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4380 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4381 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4382 TheCall->getCallee()->getSourceRange(), CallType);
4383
4384 return false;
4385}
4386
4387bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4388 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4389 TheCall->getCallee());
4390 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4391 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4392 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4393 TheCall->getCallee()->getSourceRange(), CallType);
4394
4395 return false;
4396}
4397
4398static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4399 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4400 return false;
4401
4402 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4403 switch (Op) {
4404 case AtomicExpr::AO__c11_atomic_init:
4405 case AtomicExpr::AO__opencl_atomic_init:
4406 llvm_unreachable("There is no ordering argument for an init");
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__atomic_load:
4413 case AtomicExpr::AO__scoped_atomic_load_n:
4414 case AtomicExpr::AO__scoped_atomic_load:
4415 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4416 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4417
4418 case AtomicExpr::AO__c11_atomic_store:
4419 case AtomicExpr::AO__opencl_atomic_store:
4420 case AtomicExpr::AO__hip_atomic_store:
4421 case AtomicExpr::AO__atomic_store:
4422 case AtomicExpr::AO__atomic_store_n:
4423 case AtomicExpr::AO__scoped_atomic_store:
4424 case AtomicExpr::AO__scoped_atomic_store_n:
4425 case AtomicExpr::AO__atomic_clear:
4426 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4427 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4428 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4429
4430 default:
4431 return true;
4432 }
4433}
4434
4435ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4437 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4438 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4439 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4440 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4441 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4442 Op);
4443}
4444
4446 SourceLocation RParenLoc, MultiExprArg Args,
4448 AtomicArgumentOrder ArgOrder) {
4449 // All the non-OpenCL operations take one of the following forms.
4450 // The OpenCL operations take the __c11 forms with one extra argument for
4451 // synchronization scope.
4452 enum {
4453 // C __c11_atomic_init(A *, C)
4454 Init,
4455
4456 // C __c11_atomic_load(A *, int)
4457 Load,
4458
4459 // void __atomic_load(A *, CP, int)
4460 LoadCopy,
4461
4462 // void __atomic_store(A *, CP, int)
4463 Copy,
4464
4465 // C __c11_atomic_add(A *, M, int)
4466 Arithmetic,
4467
4468 // C __atomic_exchange_n(A *, CP, int)
4469 Xchg,
4470
4471 // void __atomic_exchange(A *, C *, CP, int)
4472 GNUXchg,
4473
4474 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4475 C11CmpXchg,
4476
4477 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4478 GNUCmpXchg,
4479
4480 // bool __atomic_test_and_set(A *, int)
4481 TestAndSetByte,
4482
4483 // void __atomic_clear(A *, int)
4484 ClearByte,
4485 } Form = Init;
4486
4487 const unsigned NumForm = ClearByte + 1;
4488 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4489 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4490 // where:
4491 // C is an appropriate type,
4492 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4493 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4494 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4495 // the int parameters are for orderings.
4496
4497 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4498 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4499 "need to update code for modified forms");
4500 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4501 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4502 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4503 "need to update code for modified C11 atomics");
4504 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4505 Op <= AtomicExpr::AO__opencl_atomic_store;
4506 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4507 Op <= AtomicExpr::AO__hip_atomic_store;
4508 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4509 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4510 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4511 Op <= AtomicExpr::AO__c11_atomic_store) ||
4512 IsOpenCL;
4513 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4514 Op == AtomicExpr::AO__atomic_store_n ||
4515 Op == AtomicExpr::AO__atomic_exchange_n ||
4516 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4517 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4518 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4519 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4520 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4521 // Bit mask for extra allowed value types other than integers for atomic
4522 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4523 // allow floating point.
4524 enum ArithOpExtraValueType {
4525 AOEVT_None = 0,
4526 AOEVT_Pointer = 1,
4527 AOEVT_FP = 2,
4528 };
4529 unsigned ArithAllows = AOEVT_None;
4530
4531 switch (Op) {
4532 case AtomicExpr::AO__c11_atomic_init:
4533 case AtomicExpr::AO__opencl_atomic_init:
4534 Form = Init;
4535 break;
4536
4537 case AtomicExpr::AO__c11_atomic_load:
4538 case AtomicExpr::AO__opencl_atomic_load:
4539 case AtomicExpr::AO__hip_atomic_load:
4540 case AtomicExpr::AO__atomic_load_n:
4541 case AtomicExpr::AO__scoped_atomic_load_n:
4542 Form = Load;
4543 break;
4544
4545 case AtomicExpr::AO__atomic_load:
4546 case AtomicExpr::AO__scoped_atomic_load:
4547 Form = LoadCopy;
4548 break;
4549
4550 case AtomicExpr::AO__c11_atomic_store:
4551 case AtomicExpr::AO__opencl_atomic_store:
4552 case AtomicExpr::AO__hip_atomic_store:
4553 case AtomicExpr::AO__atomic_store:
4554 case AtomicExpr::AO__atomic_store_n:
4555 case AtomicExpr::AO__scoped_atomic_store:
4556 case AtomicExpr::AO__scoped_atomic_store_n:
4557 Form = Copy;
4558 break;
4559 case AtomicExpr::AO__atomic_fetch_add:
4560 case AtomicExpr::AO__atomic_fetch_sub:
4561 case AtomicExpr::AO__atomic_add_fetch:
4562 case AtomicExpr::AO__atomic_sub_fetch:
4563 case AtomicExpr::AO__scoped_atomic_fetch_add:
4564 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4565 case AtomicExpr::AO__scoped_atomic_add_fetch:
4566 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4567 case AtomicExpr::AO__c11_atomic_fetch_add:
4568 case AtomicExpr::AO__c11_atomic_fetch_sub:
4569 case AtomicExpr::AO__opencl_atomic_fetch_add:
4570 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4571 case AtomicExpr::AO__hip_atomic_fetch_add:
4572 case AtomicExpr::AO__hip_atomic_fetch_sub:
4573 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4574 Form = Arithmetic;
4575 break;
4576 case AtomicExpr::AO__atomic_fetch_max:
4577 case AtomicExpr::AO__atomic_fetch_min:
4578 case AtomicExpr::AO__atomic_max_fetch:
4579 case AtomicExpr::AO__atomic_min_fetch:
4580 case AtomicExpr::AO__scoped_atomic_fetch_max:
4581 case AtomicExpr::AO__scoped_atomic_fetch_min:
4582 case AtomicExpr::AO__scoped_atomic_max_fetch:
4583 case AtomicExpr::AO__scoped_atomic_min_fetch:
4584 case AtomicExpr::AO__c11_atomic_fetch_max:
4585 case AtomicExpr::AO__c11_atomic_fetch_min:
4586 case AtomicExpr::AO__opencl_atomic_fetch_max:
4587 case AtomicExpr::AO__opencl_atomic_fetch_min:
4588 case AtomicExpr::AO__hip_atomic_fetch_max:
4589 case AtomicExpr::AO__hip_atomic_fetch_min:
4590 ArithAllows = AOEVT_FP;
4591 Form = Arithmetic;
4592 break;
4593 case AtomicExpr::AO__c11_atomic_fetch_and:
4594 case AtomicExpr::AO__c11_atomic_fetch_or:
4595 case AtomicExpr::AO__c11_atomic_fetch_xor:
4596 case AtomicExpr::AO__hip_atomic_fetch_and:
4597 case AtomicExpr::AO__hip_atomic_fetch_or:
4598 case AtomicExpr::AO__hip_atomic_fetch_xor:
4599 case AtomicExpr::AO__c11_atomic_fetch_nand:
4600 case AtomicExpr::AO__opencl_atomic_fetch_and:
4601 case AtomicExpr::AO__opencl_atomic_fetch_or:
4602 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4603 case AtomicExpr::AO__atomic_fetch_and:
4604 case AtomicExpr::AO__atomic_fetch_or:
4605 case AtomicExpr::AO__atomic_fetch_xor:
4606 case AtomicExpr::AO__atomic_fetch_nand:
4607 case AtomicExpr::AO__atomic_and_fetch:
4608 case AtomicExpr::AO__atomic_or_fetch:
4609 case AtomicExpr::AO__atomic_xor_fetch:
4610 case AtomicExpr::AO__atomic_nand_fetch:
4611 case AtomicExpr::AO__atomic_fetch_uinc:
4612 case AtomicExpr::AO__atomic_fetch_udec:
4613 case AtomicExpr::AO__scoped_atomic_fetch_and:
4614 case AtomicExpr::AO__scoped_atomic_fetch_or:
4615 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4616 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4617 case AtomicExpr::AO__scoped_atomic_and_fetch:
4618 case AtomicExpr::AO__scoped_atomic_or_fetch:
4619 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4620 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4621 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4622 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4623 Form = Arithmetic;
4624 break;
4625
4626 case AtomicExpr::AO__c11_atomic_exchange:
4627 case AtomicExpr::AO__hip_atomic_exchange:
4628 case AtomicExpr::AO__opencl_atomic_exchange:
4629 case AtomicExpr::AO__atomic_exchange_n:
4630 case AtomicExpr::AO__scoped_atomic_exchange_n:
4631 Form = Xchg;
4632 break;
4633
4634 case AtomicExpr::AO__atomic_exchange:
4635 case AtomicExpr::AO__scoped_atomic_exchange:
4636 Form = GNUXchg;
4637 break;
4638
4639 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4640 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4641 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4642 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4643 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4644 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4645 Form = C11CmpXchg;
4646 break;
4647
4648 case AtomicExpr::AO__atomic_compare_exchange:
4649 case AtomicExpr::AO__atomic_compare_exchange_n:
4650 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4651 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4652 Form = GNUCmpXchg;
4653 break;
4654
4655 case AtomicExpr::AO__atomic_test_and_set:
4656 Form = TestAndSetByte;
4657 break;
4658
4659 case AtomicExpr::AO__atomic_clear:
4660 Form = ClearByte;
4661 break;
4662 }
4663
4664 unsigned AdjustedNumArgs = NumArgs[Form];
4665 if ((IsOpenCL || IsHIP || IsScoped) &&
4666 Op != AtomicExpr::AO__opencl_atomic_init)
4667 ++AdjustedNumArgs;
4668 // Check we have the right number of arguments.
4669 if (Args.size() < AdjustedNumArgs) {
4670 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4671 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4672 << /*is non object*/ 0 << ExprRange;
4673 return ExprError();
4674 } else if (Args.size() > AdjustedNumArgs) {
4675 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4676 diag::err_typecheck_call_too_many_args)
4677 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4678 << /*is non object*/ 0 << ExprRange;
4679 return ExprError();
4680 }
4681
4682 // Inspect the first argument of the atomic operation.
4683 Expr *Ptr = Args[0];
4685 if (ConvertedPtr.isInvalid())
4686 return ExprError();
4687
4688 Ptr = ConvertedPtr.get();
4689 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4690 if (!pointerType) {
4691 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4692 << Ptr->getType() << 0 << Ptr->getSourceRange();
4693 return ExprError();
4694 }
4695
4696 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4697 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4698 QualType ValType = AtomTy; // 'C'
4699 if (IsC11) {
4700 if (!AtomTy->isAtomicType()) {
4701 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4702 << Ptr->getType() << Ptr->getSourceRange();
4703 return ExprError();
4704 }
4705 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4707 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4708 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4709 << Ptr->getSourceRange();
4710 return ExprError();
4711 }
4712 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4713 } else if (Form != Load && Form != LoadCopy) {
4714 if (ValType.isConstQualified()) {
4715 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4716 << Ptr->getType() << Ptr->getSourceRange();
4717 return ExprError();
4718 }
4719 }
4720
4721 if (Form != TestAndSetByte && Form != ClearByte) {
4722 // Pointer to object of size zero is not allowed.
4723 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4724 diag::err_incomplete_type))
4725 return ExprError();
4726
4727 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4728 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4729 << Ptr->getType() << 1 << Ptr->getSourceRange();
4730 return ExprError();
4731 }
4732 } else {
4733 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4734 // non-const pointer type, including void* and pointers to incomplete
4735 // structs, but only access the first byte.
4736 AtomTy = Context.CharTy;
4737 AtomTy = AtomTy.withCVRQualifiers(
4738 pointerType->getPointeeType().getCVRQualifiers());
4739 QualType PointerQT = Context.getPointerType(AtomTy);
4740 pointerType = PointerQT->getAs<PointerType>();
4741 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4742 ValType = AtomTy;
4743 }
4744
4745 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4746 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4747 Diag(ExprRange.getBegin(),
4748 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4749 << 0 << Ptr->getType() << Ptr->getSourceRange();
4750 return ExprError();
4751 }
4752
4753 // For an arithmetic operation, the implied arithmetic must be well-formed.
4754 if (Form == Arithmetic) {
4755 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4756 // trivial type errors.
4757 auto IsAllowedValueType = [&](QualType ValType,
4758 unsigned AllowedType) -> bool {
4759 if (ValType->isIntegerType())
4760 return true;
4761 if (ValType->isPointerType())
4762 return AllowedType & AOEVT_Pointer;
4763 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4764 return false;
4765 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4766 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4767 &Context.getTargetInfo().getLongDoubleFormat() ==
4768 &llvm::APFloat::x87DoubleExtended())
4769 return false;
4770 return true;
4771 };
4772 if (!IsAllowedValueType(ValType, ArithAllows)) {
4773 auto DID = ArithAllows & AOEVT_FP
4774 ? (ArithAllows & AOEVT_Pointer
4775 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4776 : diag::err_atomic_op_needs_atomic_int_or_fp)
4777 : diag::err_atomic_op_needs_atomic_int;
4778 Diag(ExprRange.getBegin(), DID)
4779 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4780 return ExprError();
4781 }
4782 if (IsC11 && ValType->isPointerType() &&
4784 diag::err_incomplete_type)) {
4785 return ExprError();
4786 }
4787 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4788 // For __atomic_*_n operations, the value type must be a scalar integral or
4789 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4790 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4791 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4792 return ExprError();
4793 }
4794
4795 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4796 !AtomTy->isScalarType()) {
4797 // For GNU atomics, require a trivially-copyable type. This is not part of
4798 // the GNU atomics specification but we enforce it for consistency with
4799 // other atomics which generally all require a trivially-copyable type. This
4800 // is because atomics just copy bits.
4801 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4802 << Ptr->getType() << Ptr->getSourceRange();
4803 return ExprError();
4804 }
4805
4806 switch (ValType.getObjCLifetime()) {
4809 // okay
4810 break;
4811
4815 // FIXME: Can this happen? By this point, ValType should be known
4816 // to be trivially copyable.
4817 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4818 << ValType << Ptr->getSourceRange();
4819 return ExprError();
4820 }
4821
4822 // All atomic operations have an overload which takes a pointer to a volatile
4823 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4824 // into the result or the other operands. Similarly atomic_load takes a
4825 // pointer to a const 'A'.
4826 ValType.removeLocalVolatile();
4827 ValType.removeLocalConst();
4828 QualType ResultType = ValType;
4829 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4830 Form == ClearByte)
4831 ResultType = Context.VoidTy;
4832 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4833 ResultType = Context.BoolTy;
4834
4835 // The type of a parameter passed 'by value'. In the GNU atomics, such
4836 // arguments are actually passed as pointers.
4837 QualType ByValType = ValType; // 'CP'
4838 bool IsPassedByAddress = false;
4839 if (!IsC11 && !IsHIP && !IsN) {
4840 ByValType = Ptr->getType();
4841 IsPassedByAddress = true;
4842 }
4843
4844 SmallVector<Expr *, 5> APIOrderedArgs;
4845 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4846 APIOrderedArgs.push_back(Args[0]);
4847 switch (Form) {
4848 case Init:
4849 case Load:
4850 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4851 break;
4852 case LoadCopy:
4853 case Copy:
4854 case Arithmetic:
4855 case Xchg:
4856 APIOrderedArgs.push_back(Args[2]); // Val1
4857 APIOrderedArgs.push_back(Args[1]); // Order
4858 break;
4859 case GNUXchg:
4860 APIOrderedArgs.push_back(Args[2]); // Val1
4861 APIOrderedArgs.push_back(Args[3]); // Val2
4862 APIOrderedArgs.push_back(Args[1]); // Order
4863 break;
4864 case C11CmpXchg:
4865 APIOrderedArgs.push_back(Args[2]); // Val1
4866 APIOrderedArgs.push_back(Args[4]); // Val2
4867 APIOrderedArgs.push_back(Args[1]); // Order
4868 APIOrderedArgs.push_back(Args[3]); // OrderFail
4869 break;
4870 case GNUCmpXchg:
4871 APIOrderedArgs.push_back(Args[2]); // Val1
4872 APIOrderedArgs.push_back(Args[4]); // Val2
4873 APIOrderedArgs.push_back(Args[5]); // Weak
4874 APIOrderedArgs.push_back(Args[1]); // Order
4875 APIOrderedArgs.push_back(Args[3]); // OrderFail
4876 break;
4877 case TestAndSetByte:
4878 case ClearByte:
4879 APIOrderedArgs.push_back(Args[1]); // Order
4880 break;
4881 }
4882 } else
4883 APIOrderedArgs.append(Args.begin(), Args.end());
4884
4885 // The first argument's non-CV pointer type is used to deduce the type of
4886 // subsequent arguments, except for:
4887 // - weak flag (always converted to bool)
4888 // - memory order (always converted to int)
4889 // - scope (always converted to int)
4890 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4891 QualType Ty;
4892 if (i < NumVals[Form] + 1) {
4893 switch (i) {
4894 case 0:
4895 // The first argument is always a pointer. It has a fixed type.
4896 // It is always dereferenced, a nullptr is undefined.
4897 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4898 // Nothing else to do: we already know all we want about this pointer.
4899 continue;
4900 case 1:
4901 // The second argument is the non-atomic operand. For arithmetic, this
4902 // is always passed by value, and for a compare_exchange it is always
4903 // passed by address. For the rest, GNU uses by-address and C11 uses
4904 // by-value.
4905 assert(Form != Load);
4906 if (Form == Arithmetic && ValType->isPointerType())
4907 Ty = Context.getPointerDiffType();
4908 else if (Form == Init || Form == Arithmetic)
4909 Ty = ValType;
4910 else if (Form == Copy || Form == Xchg) {
4911 if (IsPassedByAddress) {
4912 // The value pointer is always dereferenced, a nullptr is undefined.
4913 CheckNonNullArgument(*this, APIOrderedArgs[i],
4914 ExprRange.getBegin());
4915 }
4916 Ty = ByValType;
4917 } else {
4918 Expr *ValArg = APIOrderedArgs[i];
4919 // The value pointer is always dereferenced, a nullptr is undefined.
4920 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4922 // Keep address space of non-atomic pointer type.
4923 if (const PointerType *PtrTy =
4924 ValArg->getType()->getAs<PointerType>()) {
4925 AS = PtrTy->getPointeeType().getAddressSpace();
4926 }
4927 Ty = Context.getPointerType(
4928 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4929 }
4930 break;
4931 case 2:
4932 // The third argument to compare_exchange / GNU exchange is the desired
4933 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4934 if (IsPassedByAddress)
4935 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4936 Ty = ByValType;
4937 break;
4938 case 3:
4939 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4940 Ty = Context.BoolTy;
4941 break;
4942 }
4943 } else {
4944 // The order(s) and scope are always converted to int.
4945 Ty = Context.IntTy;
4946 }
4947
4948 InitializedEntity Entity =
4950 ExprResult Arg = APIOrderedArgs[i];
4951 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4952 if (Arg.isInvalid())
4953 return true;
4954 APIOrderedArgs[i] = Arg.get();
4955 }
4956
4957 // Permute the arguments into a 'consistent' order.
4958 SmallVector<Expr*, 5> SubExprs;
4959 SubExprs.push_back(Ptr);
4960 switch (Form) {
4961 case Init:
4962 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4963 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4964 break;
4965 case Load:
4966 case TestAndSetByte:
4967 case ClearByte:
4968 SubExprs.push_back(APIOrderedArgs[1]); // Order
4969 break;
4970 case LoadCopy:
4971 case Copy:
4972 case Arithmetic:
4973 case Xchg:
4974 SubExprs.push_back(APIOrderedArgs[2]); // Order
4975 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4976 break;
4977 case GNUXchg:
4978 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4979 SubExprs.push_back(APIOrderedArgs[3]); // Order
4980 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4981 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4982 break;
4983 case C11CmpXchg:
4984 SubExprs.push_back(APIOrderedArgs[3]); // Order
4985 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4986 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4987 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4988 break;
4989 case GNUCmpXchg:
4990 SubExprs.push_back(APIOrderedArgs[4]); // Order
4991 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4992 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4993 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4994 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4995 break;
4996 }
4997
4998 // If the memory orders are constants, check they are valid.
4999 if (SubExprs.size() >= 2 && Form != Init) {
5000 std::optional<llvm::APSInt> Success =
5001 SubExprs[1]->getIntegerConstantExpr(Context);
5002 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5003 Diag(SubExprs[1]->getBeginLoc(),
5004 diag::warn_atomic_op_has_invalid_memory_order)
5005 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5006 << SubExprs[1]->getSourceRange();
5007 }
5008 if (SubExprs.size() >= 5) {
5009 if (std::optional<llvm::APSInt> Failure =
5010 SubExprs[3]->getIntegerConstantExpr(Context)) {
5011 if (!llvm::is_contained(
5012 {llvm::AtomicOrderingCABI::relaxed,
5013 llvm::AtomicOrderingCABI::consume,
5014 llvm::AtomicOrderingCABI::acquire,
5015 llvm::AtomicOrderingCABI::seq_cst},
5016 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5017 Diag(SubExprs[3]->getBeginLoc(),
5018 diag::warn_atomic_op_has_invalid_memory_order)
5019 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5020 }
5021 }
5022 }
5023 }
5024
5025 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5026 auto *Scope = Args[Args.size() - 1];
5027 if (std::optional<llvm::APSInt> Result =
5028 Scope->getIntegerConstantExpr(Context)) {
5029 if (!ScopeModel->isValid(Result->getZExtValue()))
5030 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5031 << Scope->getSourceRange();
5032 }
5033 SubExprs.push_back(Scope);
5034 }
5035
5036 AtomicExpr *AE = new (Context)
5037 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5038
5039 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5040 Op == AtomicExpr::AO__c11_atomic_store ||
5041 Op == AtomicExpr::AO__opencl_atomic_load ||
5042 Op == AtomicExpr::AO__hip_atomic_load ||
5043 Op == AtomicExpr::AO__opencl_atomic_store ||
5044 Op == AtomicExpr::AO__hip_atomic_store) &&
5045 Context.AtomicUsesUnsupportedLibcall(AE))
5046 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5047 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5048 Op == AtomicExpr::AO__opencl_atomic_load ||
5049 Op == AtomicExpr::AO__hip_atomic_load)
5050 ? 0
5051 : 1);
5052
5053 if (ValType->isBitIntType()) {
5054 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5055 return ExprError();
5056 }
5057
5058 return AE;
5059}
5060
5061/// checkBuiltinArgument - Given a call to a builtin function, perform
5062/// normal type-checking on the given argument, updating the call in
5063/// place. This is useful when a builtin function requires custom
5064/// type-checking for some of its arguments but not necessarily all of
5065/// them.
5066///
5067/// Returns true on error.
5068static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5069 FunctionDecl *Fn = E->getDirectCallee();
5070 assert(Fn && "builtin call without direct callee!");
5071
5072 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5073 InitializedEntity Entity =
5075
5076 ExprResult Arg = E->getArg(ArgIndex);
5077 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5078 if (Arg.isInvalid())
5079 return true;
5080
5081 E->setArg(ArgIndex, Arg.get());
5082 return false;
5083}
5084
5085ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5086 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5087 Expr *Callee = TheCall->getCallee();
5088 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5089 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5090
5091 // Ensure that we have at least one argument to do type inference from.
5092 if (TheCall->getNumArgs() < 1) {
5093 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5094 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5095 << Callee->getSourceRange();
5096 return ExprError();
5097 }
5098
5099 // Inspect the first argument of the atomic builtin. This should always be
5100 // a pointer type, whose element is an integral scalar or pointer type.
5101 // Because it is a pointer type, we don't have to worry about any implicit
5102 // casts here.
5103 // FIXME: We don't allow floating point scalars as input.
5104 Expr *FirstArg = TheCall->getArg(0);
5105 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5106 if (FirstArgResult.isInvalid())
5107 return ExprError();
5108 FirstArg = FirstArgResult.get();
5109 TheCall->setArg(0, FirstArg);
5110
5111 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5112 if (!pointerType) {
5113 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5114 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5115 return ExprError();
5116 }
5117
5118 QualType ValType = pointerType->getPointeeType();
5119 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5120 !ValType->isBlockPointerType()) {
5121 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5122 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5123 return ExprError();
5124 }
5125 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5126 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5127 Diag(FirstArg->getBeginLoc(),
5128 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5129 << 1 << ValType << FirstArg->getSourceRange();
5130 return ExprError();
5131 }
5132
5133 if (ValType.isConstQualified()) {
5134 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5135 << FirstArg->getType() << FirstArg->getSourceRange();
5136 return ExprError();
5137 }
5138
5139 switch (ValType.getObjCLifetime()) {
5142 // okay
5143 break;
5144
5148 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5149 << ValType << FirstArg->getSourceRange();
5150 return ExprError();
5151 }
5152
5153 // Strip any qualifiers off ValType.
5154 ValType = ValType.getUnqualifiedType();
5155
5156 // The majority of builtins return a value, but a few have special return
5157 // types, so allow them to override appropriately below.
5158 QualType ResultType = ValType;
5159
5160 // We need to figure out which concrete builtin this maps onto. For example,
5161 // __sync_fetch_and_add with a 2 byte object turns into
5162 // __sync_fetch_and_add_2.
5163#define BUILTIN_ROW(x) \
5164 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5165 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5166
5167 static const unsigned BuiltinIndices[][5] = {
5168 BUILTIN_ROW(__sync_fetch_and_add),
5169 BUILTIN_ROW(__sync_fetch_and_sub),
5170 BUILTIN_ROW(__sync_fetch_and_or),
5171 BUILTIN_ROW(__sync_fetch_and_and),
5172 BUILTIN_ROW(__sync_fetch_and_xor),
5173 BUILTIN_ROW(__sync_fetch_and_nand),
5174
5175 BUILTIN_ROW(__sync_add_and_fetch),
5176 BUILTIN_ROW(__sync_sub_and_fetch),
5177 BUILTIN_ROW(__sync_and_and_fetch),
5178 BUILTIN_ROW(__sync_or_and_fetch),
5179 BUILTIN_ROW(__sync_xor_and_fetch),
5180 BUILTIN_ROW(__sync_nand_and_fetch),
5181
5182 BUILTIN_ROW(__sync_val_compare_and_swap),
5183 BUILTIN_ROW(__sync_bool_compare_and_swap),
5184 BUILTIN_ROW(__sync_lock_test_and_set),
5185 BUILTIN_ROW(__sync_lock_release),
5186 BUILTIN_ROW(__sync_swap)
5187 };
5188#undef BUILTIN_ROW
5189
5190 // Determine the index of the size.
5191 unsigned SizeIndex;
5192 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5193 case 1: SizeIndex = 0; break;
5194 case 2: SizeIndex = 1; break;
5195 case 4: SizeIndex = 2; break;
5196 case 8: SizeIndex = 3; break;
5197 case 16: SizeIndex = 4; break;
5198 default:
5199 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5200 << FirstArg->getType() << FirstArg->getSourceRange();
5201 return ExprError();
5202 }
5203
5204 // Each of these builtins has one pointer argument, followed by some number of
5205 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5206 // that we ignore. Find out which row of BuiltinIndices to read from as well
5207 // as the number of fixed args.
5208 unsigned BuiltinID = FDecl->getBuiltinID();
5209 unsigned BuiltinIndex, NumFixed = 1;
5210 bool WarnAboutSemanticsChange = false;
5211 switch (BuiltinID) {
5212 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5213 case Builtin::BI__sync_fetch_and_add:
5214 case Builtin::BI__sync_fetch_and_add_1:
5215 case Builtin::BI__sync_fetch_and_add_2:
5216 case Builtin::BI__sync_fetch_and_add_4:
5217 case Builtin::BI__sync_fetch_and_add_8:
5218 case Builtin::BI__sync_fetch_and_add_16:
5219 BuiltinIndex = 0;
5220 break;
5221
5222 case Builtin::BI__sync_fetch_and_sub:
5223 case Builtin::BI__sync_fetch_and_sub_1:
5224 case Builtin::BI__sync_fetch_and_sub_2:
5225 case Builtin::BI__sync_fetch_and_sub_4:
5226 case Builtin::BI__sync_fetch_and_sub_8:
5227 case Builtin::BI__sync_fetch_and_sub_16:
5228 BuiltinIndex = 1;
5229 break;
5230
5231 case Builtin::BI__sync_fetch_and_or:
5232 case Builtin::BI__sync_fetch_and_or_1:
5233 case Builtin::BI__sync_fetch_and_or_2:
5234 case Builtin::BI__sync_fetch_and_or_4:
5235 case Builtin::BI__sync_fetch_and_or_8:
5236 case Builtin::BI__sync_fetch_and_or_16:
5237 BuiltinIndex = 2;
5238 break;
5239
5240 case Builtin::BI__sync_fetch_and_and:
5241 case Builtin::BI__sync_fetch_and_and_1:
5242 case Builtin::BI__sync_fetch_and_and_2:
5243 case Builtin::BI__sync_fetch_and_and_4:
5244 case Builtin::BI__sync_fetch_and_and_8:
5245 case Builtin::BI__sync_fetch_and_and_16:
5246 BuiltinIndex = 3;
5247 break;
5248
5249 case Builtin::BI__sync_fetch_and_xor:
5250 case Builtin::BI__sync_fetch_and_xor_1:
5251 case Builtin::BI__sync_fetch_and_xor_2:
5252 case Builtin::BI__sync_fetch_and_xor_4:
5253 case Builtin::BI__sync_fetch_and_xor_8:
5254 case Builtin::BI__sync_fetch_and_xor_16:
5255 BuiltinIndex = 4;
5256 break;
5257
5258 case Builtin::BI__sync_fetch_and_nand:
5259 case Builtin::BI__sync_fetch_and_nand_1:
5260 case Builtin::BI__sync_fetch_and_nand_2:
5261 case Builtin::BI__sync_fetch_and_nand_4:
5262 case Builtin::BI__sync_fetch_and_nand_8:
5263 case Builtin::BI__sync_fetch_and_nand_16:
5264 BuiltinIndex = 5;
5265 WarnAboutSemanticsChange = true;
5266 break;
5267
5268 case Builtin::BI__sync_add_and_fetch:
5269 case Builtin::BI__sync_add_and_fetch_1:
5270 case Builtin::BI__sync_add_and_fetch_2:
5271 case Builtin::BI__sync_add_and_fetch_4:
5272 case Builtin::BI__sync_add_and_fetch_8:
5273 case Builtin::BI__sync_add_and_fetch_16:
5274 BuiltinIndex = 6;
5275 break;
5276
5277 case Builtin::BI__sync_sub_and_fetch:
5278 case Builtin::BI__sync_sub_and_fetch_1:
5279 case Builtin::BI__sync_sub_and_fetch_2:
5280 case Builtin::BI__sync_sub_and_fetch_4:
5281 case Builtin::BI__sync_sub_and_fetch_8:
5282 case Builtin::BI__sync_sub_and_fetch_16:
5283 BuiltinIndex = 7;
5284 break;
5285
5286 case Builtin::BI__sync_and_and_fetch:
5287 case Builtin::BI__sync_and_and_fetch_1:
5288 case Builtin::BI__sync_and_and_fetch_2:
5289 case Builtin::BI__sync_and_and_fetch_4:
5290 case Builtin::BI__sync_and_and_fetch_8:
5291 case Builtin::BI__sync_and_and_fetch_16:
5292 BuiltinIndex = 8;
5293 break;
5294
5295 case Builtin::BI__sync_or_and_fetch:
5296 case Builtin::BI__sync_or_and_fetch_1:
5297 case Builtin::BI__sync_or_and_fetch_2:
5298 case Builtin::BI__sync_or_and_fetch_4:
5299 case Builtin::BI__sync_or_and_fetch_8:
5300 case Builtin::BI__sync_or_and_fetch_16:
5301 BuiltinIndex = 9;
5302 break;
5303
5304 case Builtin::BI__sync_xor_and_fetch:
5305 case Builtin::BI__sync_xor_and_fetch_1:
5306 case Builtin::BI__sync_xor_and_fetch_2:
5307 case Builtin::BI__sync_xor_and_fetch_4:
5308 case Builtin::BI__sync_xor_and_fetch_8:
5309 case Builtin::BI__sync_xor_and_fetch_16:
5310 BuiltinIndex = 10;
5311 break;
5312
5313 case Builtin::BI__sync_nand_and_fetch:
5314 case Builtin::BI__sync_nand_and_fetch_1:
5315 case Builtin::BI__sync_nand_and_fetch_2:
5316 case Builtin::BI__sync_nand_and_fetch_4:
5317 case Builtin::BI__sync_nand_and_fetch_8:
5318 case Builtin::BI__sync_nand_and_fetch_16:
5319 BuiltinIndex = 11;
5320 WarnAboutSemanticsChange = true;
5321 break;
5322
5323 case Builtin::BI__sync_val_compare_and_swap:
5324 case Builtin::BI__sync_val_compare_and_swap_1:
5325 case Builtin::BI__sync_val_compare_and_swap_2:
5326 case Builtin::BI__sync_val_compare_and_swap_4:
5327 case Builtin::BI__sync_val_compare_and_swap_8:
5328 case Builtin::BI__sync_val_compare_and_swap_16:
5329 BuiltinIndex = 12;
5330 NumFixed = 2;
5331 break;
5332
5333 case Builtin::BI__sync_bool_compare_and_swap:
5334 case Builtin::BI__sync_bool_compare_and_swap_1:
5335 case Builtin::BI__sync_bool_compare_and_swap_2:
5336 case Builtin::BI__sync_bool_compare_and_swap_4:
5337 case Builtin::BI__sync_bool_compare_and_swap_8:
5338 case Builtin::BI__sync_bool_compare_and_swap_16:
5339 BuiltinIndex = 13;
5340 NumFixed = 2;
5341 ResultType = Context.BoolTy;
5342 break;
5343
5344 case Builtin::BI__sync_lock_test_and_set:
5345 case Builtin::BI__sync_lock_test_and_set_1:
5346 case Builtin::BI__sync_lock_test_and_set_2:
5347 case Builtin::BI__sync_lock_test_and_set_4:
5348 case Builtin::BI__sync_lock_test_and_set_8:
5349 case Builtin::BI__sync_lock_test_and_set_16:
5350 BuiltinIndex = 14;
5351 break;
5352
5353 case Builtin::BI__sync_lock_release:
5354 case Builtin::BI__sync_lock_release_1:
5355 case Builtin::BI__sync_lock_release_2:
5356 case Builtin::BI__sync_lock_release_4:
5357 case Builtin::BI__sync_lock_release_8:
5358 case Builtin::BI__sync_lock_release_16:
5359 BuiltinIndex = 15;
5360 NumFixed = 0;
5361 ResultType = Context.VoidTy;
5362 break;
5363
5364 case Builtin::BI__sync_swap:
5365 case Builtin::BI__sync_swap_1:
5366 case Builtin::BI__sync_swap_2:
5367 case Builtin::BI__sync_swap_4:
5368 case Builtin::BI__sync_swap_8:
5369 case Builtin::BI__sync_swap_16:
5370 BuiltinIndex = 16;
5371 break;
5372 }
5373
5374 // Now that we know how many fixed arguments we expect, first check that we
5375 // have at least that many.
5376 if (TheCall->getNumArgs() < 1+NumFixed) {
5377 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5378 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5379 << Callee->getSourceRange();
5380 return ExprError();
5381 }
5382
5383 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5384 << Callee->getSourceRange();
5385
5386 if (WarnAboutSemanticsChange) {
5387 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5388 << Callee->getSourceRange();
5389 }
5390
5391 // Get the decl for the concrete builtin from this, we can tell what the
5392 // concrete integer type we should convert to is.
5393 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5394 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5395 FunctionDecl *NewBuiltinDecl;
5396 if (NewBuiltinID == BuiltinID)
5397 NewBuiltinDecl = FDecl;
5398 else {
5399 // Perform builtin lookup to avoid redeclaring it.
5400 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5401 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5402 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5403 assert(Res.getFoundDecl());
5404 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5405 if (!NewBuiltinDecl)
5406 return ExprError();
5407 }
5408
5409 // The first argument --- the pointer --- has a fixed type; we
5410 // deduce the types of the rest of the arguments accordingly. Walk
5411 // the remaining arguments, converting them to the deduced value type.
5412 for (unsigned i = 0; i != NumFixed; ++i) {
5413 ExprResult Arg = TheCall->getArg(i+1);
5414
5415 // GCC does an implicit conversion to the pointer or integer ValType. This
5416 // can fail in some cases (1i -> int**), check for this error case now.
5417 // Initialize the argument.
5418 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5419 ValType, /*consume*/ false);
5420 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5421 if (Arg.isInvalid())
5422 return ExprError();
5423
5424 // Okay, we have something that *can* be converted to the right type. Check
5425 // to see if there is a potentially weird extension going on here. This can
5426 // happen when you do an atomic operation on something like an char* and
5427 // pass in 42. The 42 gets converted to char. This is even more strange
5428 // for things like 45.123 -> char, etc.
5429 // FIXME: Do this check.
5430 TheCall->setArg(i+1, Arg.get());
5431 }
5432
5433 // Create a new DeclRefExpr to refer to the new decl.
5434 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5435 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5436 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5437 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5438
5439 // Set the callee in the CallExpr.
5440 // FIXME: This loses syntactic information.
5441 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5442 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5443 CK_BuiltinFnToFnPtr);
5444 TheCall->setCallee(PromotedCall.get());
5445
5446 // Change the result type of the call to match the original value type. This
5447 // is arbitrary, but the codegen for these builtins ins design to handle it
5448 // gracefully.
5449 TheCall->setType(ResultType);
5450
5451 // Prohibit problematic uses of bit-precise integer types with atomic
5452 // builtins. The arguments would have already been converted to the first
5453 // argument's type, so only need to check the first argument.
5454 const auto *BitIntValType = ValType->getAs<BitIntType>();
5455 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5456 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5457 return ExprError();
5458 }
5459
5460 return TheCallResult;
5461}
5462
5463ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5464 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5465 DeclRefExpr *DRE =
5467 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5468 unsigned BuiltinID = FDecl->getBuiltinID();
5469 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5470 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5471 "Unexpected nontemporal load/store builtin!");
5472 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5473 unsigned numArgs = isStore ? 2 : 1;
5474
5475 // Ensure that we have the proper number of arguments.
5476 if (checkArgCount(TheCall, numArgs))
5477 return ExprError();
5478
5479 // Inspect the last argument of the nontemporal builtin. This should always
5480 // be a pointer type, from which we imply the type of the memory access.
5481 // Because it is a pointer type, we don't have to worry about any implicit
5482 // casts here.
5483 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5484 ExprResult PointerArgResult =
5486
5487 if (PointerArgResult.isInvalid())
5488 return ExprError();
5489 PointerArg = PointerArgResult.get();
5490 TheCall->setArg(numArgs - 1, PointerArg);
5491
5492 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5493 if (!pointerType) {
5494 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5495 << PointerArg->getType() << PointerArg->getSourceRange();
5496 return ExprError();
5497 }
5498
5499 QualType ValType = pointerType->getPointeeType();
5500
5501 // Strip any qualifiers off ValType.
5502 ValType = ValType.getUnqualifiedType();
5503 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5504 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5505 !ValType->isVectorType()) {
5506 Diag(DRE->getBeginLoc(),
5507 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5508 << PointerArg->getType() << PointerArg->getSourceRange();
5509 return ExprError();
5510 }
5511
5512 if (!isStore) {
5513 TheCall->setType(ValType);
5514 return TheCallResult;
5515 }
5516
5517 ExprResult ValArg = TheCall->getArg(0);
5518 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5519 Context, ValType, /*consume*/ false);
5520 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5521 if (ValArg.isInvalid())
5522 return ExprError();
5523
5524 TheCall->setArg(0, ValArg.get());
5525 TheCall->setType(Context.VoidTy);
5526 return TheCallResult;
5527}
5528
5529/// CheckObjCString - Checks that the format string argument to the os_log()
5530/// and os_trace() functions is correct, and converts it to const char *.
5531ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5532 Arg = Arg->IgnoreParenCasts();
5533 auto *Literal = dyn_cast<StringLiteral>(Arg);
5534 if (!Literal) {
5535 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5536 Literal = ObjcLiteral->getString();
5537 }
5538 }
5539
5540 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5541 return ExprError(
5542 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5543 << Arg->getSourceRange());
5544 }
5545
5546 ExprResult Result(Literal);
5547 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5548 InitializedEntity Entity =
5550 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5551 return Result;
5552}
5553
5554/// Check that the user is calling the appropriate va_start builtin for the
5555/// target and calling convention.
5556static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5557 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5558 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5559 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5560 TT.getArch() == llvm::Triple::aarch64_32);
5561 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5562 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5563 if (IsX64 || IsAArch64) {
5564 CallingConv CC = CC_C;
5565 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5566 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5567 if (IsMSVAStart) {
5568 // Don't allow this in System V ABI functions.
5569 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5570 return S.Diag(Fn->getBeginLoc(),
5571 diag::err_ms_va_start_used_in_sysv_function);
5572 } else {
5573 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5574 // On x64 Windows, don't allow this in System V ABI functions.
5575 // (Yes, that means there's no corresponding way to support variadic
5576 // System V ABI functions on Windows.)
5577 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5578 (!IsWindowsOrUEFI && CC == CC_Win64))
5579 return S.Diag(Fn->getBeginLoc(),
5580 diag::err_va_start_used_in_wrong_abi_function)
5581 << !IsWindowsOrUEFI;
5582 }
5583 return false;
5584 }
5585
5586 if (IsMSVAStart)
5587 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5588 return false;
5589}
5590
5592 ParmVarDecl **LastParam = nullptr) {
5593 // Determine whether the current function, block, or obj-c method is variadic
5594 // and get its parameter list.
5595 bool IsVariadic = false;
5597 DeclContext *Caller = S.CurContext;
5598 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5599 IsVariadic = Block->isVariadic();
5600 Params = Block->parameters();
5601 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5602 IsVariadic = FD->isVariadic();
5603 Params = FD->parameters();
5604 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5605 IsVariadic = MD->isVariadic();
5606 // FIXME: This isn't correct for methods (results in bogus warning).
5607 Params = MD->parameters();
5608 } else if (isa<CapturedDecl>(Caller)) {
5609 // We don't support va_start in a CapturedDecl.
5610 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5611 return true;
5612 } else {
5613 // This must be some other declcontext that parses exprs.
5614 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5615 return true;
5616 }
5617
5618 if (!IsVariadic) {
5619 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5620 return true;
5621 }
5622
5623 if (LastParam)
5624 *LastParam = Params.empty() ? nullptr : Params.back();
5625
5626 return false;
5627}
5628
5629bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5630 Expr *Fn = TheCall->getCallee();
5631 if (checkVAStartABI(*this, BuiltinID, Fn))
5632 return true;
5633
5634 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5635 // This builtin requires one argument (the va_list), allows two arguments,
5636 // but diagnoses more than two arguments. e.g.,
5637 // __builtin_c23_va_start(); // error
5638 // __builtin_c23_va_start(list); // ok
5639 // __builtin_c23_va_start(list, param); // ok
5640 // __builtin_c23_va_start(list, anything, anything); // error
5641 // This differs from the GCC behavior in that they accept the last case
5642 // with a warning, but it doesn't seem like a useful behavior to allow.
5643 if (checkArgCountRange(TheCall, 1, 2))
5644 return true;
5645 } else {
5646 // In C23 mode, va_start only needs one argument. However, the builtin still
5647 // requires two arguments (which matches the behavior of the GCC builtin),
5648 // <stdarg.h> passes `0` as the second argument in C23 mode.
5649 if (checkArgCount(TheCall, 2))
5650 return true;
5651 }
5652
5653 // Type-check the first argument normally.
5654 if (checkBuiltinArgument(*this, TheCall, 0))
5655 return true;
5656
5657 // Check that the current function is variadic, and get its last parameter.
5658 ParmVarDecl *LastParam;
5659 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5660 return true;
5661
5662 // Verify that the second argument to the builtin is the last non-variadic
5663 // argument of the current function or method. In C23 mode, if the call is
5664 // not to __builtin_c23_va_start, and the second argument is an integer
5665 // constant expression with value 0, then we don't bother with this check.
5666 // For __builtin_c23_va_start, we only perform the check for the second
5667 // argument being the last argument to the current function if there is a
5668 // second argument present.
5669 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5670 TheCall->getNumArgs() < 2) {
5671 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5672 return false;
5673 }
5674
5675 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5676 if (std::optional<llvm::APSInt> Val =
5678 Val && LangOpts.C23 && *Val == 0 &&
5679 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5680 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5681 return false;
5682 }
5683
5684 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5685 // next block.
5686 QualType Type;
5687 SourceLocation ParamLoc;
5688 bool IsCRegister = false;
5689 bool SecondArgIsLastNonVariadicArgument = false;
5690 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5691 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5692 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5693
5694 Type = PV->getType();
5695 ParamLoc = PV->getLocation();
5696 IsCRegister =
5697 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5698 }
5699 }
5700
5701 if (!SecondArgIsLastNonVariadicArgument)
5702 Diag(TheCall->getArg(1)->getBeginLoc(),
5703 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5704 else if (IsCRegister || Type->isReferenceType() ||
5705 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5706 // Promotable integers are UB, but enumerations need a bit of
5707 // extra checking to see what their promotable type actually is.
5708 if (!Context.isPromotableIntegerType(Type))
5709 return false;
5710 const auto *ED = Type->getAsEnumDecl();
5711 if (!ED)
5712 return true;
5713 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5714 }()) {
5715 unsigned Reason = 0;
5716 if (Type->isReferenceType()) Reason = 1;
5717 else if (IsCRegister) Reason = 2;
5718 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5719 Diag(ParamLoc, diag::note_parameter_type) << Type;
5720 }
5721
5722 return false;
5723}
5724
5725bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5726 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5727 const LangOptions &LO = getLangOpts();
5728
5729 if (LO.CPlusPlus)
5730 return Arg->getType()
5732 .getTypePtr()
5733 ->getPointeeType()
5735
5736 // In C, allow aliasing through `char *`, this is required for AArch64 at
5737 // least.
5738 return true;
5739 };
5740
5741 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5742 // const char *named_addr);
5743
5744 Expr *Func = Call->getCallee();
5745
5746 if (Call->getNumArgs() < 3)
5747 return Diag(Call->getEndLoc(),
5748 diag::err_typecheck_call_too_few_args_at_least)
5749 << 0 /*function call*/ << 3 << Call->getNumArgs()
5750 << /*is non object*/ 0;
5751
5752 // Type-check the first argument normally.
5753 if (checkBuiltinArgument(*this, Call, 0))
5754 return true;
5755
5756 // Check that the current function is variadic.
5758 return true;
5759
5760 // __va_start on Windows does not validate the parameter qualifiers
5761
5762 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5763 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5764
5765 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5766 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5767
5768 const QualType &ConstCharPtrTy =
5769 Context.getPointerType(Context.CharTy.withConst());
5770 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5771 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5772 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5773 << 0 /* qualifier difference */
5774 << 3 /* parameter mismatch */
5775 << 2 << Arg1->getType() << ConstCharPtrTy;
5776
5777 const QualType SizeTy = Context.getSizeType();
5778 if (!Context.hasSameType(
5780 SizeTy))
5781 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5782 << Arg2->getType() << SizeTy << 1 /* different class */
5783 << 0 /* qualifier difference */
5784 << 3 /* parameter mismatch */
5785 << 3 << Arg2->getType() << SizeTy;
5786
5787 return false;
5788}
5789
5790bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5791 if (checkArgCount(TheCall, 2))
5792 return true;
5793
5794 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5795 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5796 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5797 << 1 << 0 << TheCall->getSourceRange();
5798
5799 ExprResult OrigArg0 = TheCall->getArg(0);
5800 ExprResult OrigArg1 = TheCall->getArg(1);
5801
5802 // Do standard promotions between the two arguments, returning their common
5803 // type.
5804 QualType Res = UsualArithmeticConversions(
5805 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5806 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5807 return true;
5808
5809 // Make sure any conversions are pushed back into the call; this is
5810 // type safe since unordered compare builtins are declared as "_Bool
5811 // foo(...)".
5812 TheCall->setArg(0, OrigArg0.get());
5813 TheCall->setArg(1, OrigArg1.get());
5814
5815 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5816 return false;
5817
5818 // If the common type isn't a real floating type, then the arguments were
5819 // invalid for this operation.
5820 if (Res.isNull() || !Res->isRealFloatingType())
5821 return Diag(OrigArg0.get()->getBeginLoc(),
5822 diag::err_typecheck_call_invalid_ordered_compare)
5823 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5824 << SourceRange(OrigArg0.get()->getBeginLoc(),
5825 OrigArg1.get()->getEndLoc());
5826
5827 return false;
5828}
5829
5830bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5831 unsigned BuiltinID) {
5832 if (checkArgCount(TheCall, NumArgs))
5833 return true;
5834
5835 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5836 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5837 BuiltinID == Builtin::BI__builtin_isinf ||
5838 BuiltinID == Builtin::BI__builtin_isinf_sign))
5839 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5840 << 0 << 0 << TheCall->getSourceRange();
5841
5842 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5843 BuiltinID == Builtin::BI__builtin_isunordered))
5844 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5845 << 1 << 0 << TheCall->getSourceRange();
5846
5847 bool IsFPClass = NumArgs == 2;
5848
5849 // Find out position of floating-point argument.
5850 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5851
5852 // We can count on all parameters preceding the floating-point just being int.
5853 // Try all of those.
5854 for (unsigned i = 0; i < FPArgNo; ++i) {
5855 Expr *Arg = TheCall->getArg(i);
5856
5857 if (Arg->isTypeDependent())
5858 return false;
5859
5862
5863 if (Res.isInvalid())
5864 return true;
5865 TheCall->setArg(i, Res.get());
5866 }
5867
5868 Expr *OrigArg = TheCall->getArg(FPArgNo);
5869
5870 if (OrigArg->isTypeDependent())
5871 return false;
5872
5873 // Usual Unary Conversions will convert half to float, which we want for
5874 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5875 // type how it is, but do normal L->Rvalue conversions.
5876 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5877 ExprResult Res = UsualUnaryConversions(OrigArg);
5878
5879 if (!Res.isUsable())
5880 return true;
5881 OrigArg = Res.get();
5882 } else {
5884
5885 if (!Res.isUsable())
5886 return true;
5887 OrigArg = Res.get();
5888 }
5889 TheCall->setArg(FPArgNo, OrigArg);
5890
5891 QualType VectorResultTy;
5892 QualType ElementTy = OrigArg->getType();
5893 // TODO: When all classification function are implemented with is_fpclass,
5894 // vector argument can be supported in all of them.
5895 if (ElementTy->isVectorType() && IsFPClass) {
5896 VectorResultTy = GetSignedVectorType(ElementTy);
5897 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5898 }
5899
5900 // This operation requires a non-_Complex floating-point number.
5901 if (!ElementTy->isRealFloatingType())
5902 return Diag(OrigArg->getBeginLoc(),
5903 diag::err_typecheck_call_invalid_unary_fp)
5904 << OrigArg->getType() << OrigArg->getSourceRange();
5905
5906 // __builtin_isfpclass has integer parameter that specify test mask. It is
5907 // passed in (...), so it should be analyzed completely here.
5908 if (IsFPClass)
5909 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5910 return true;
5911
5912 // TODO: enable this code to all classification functions.
5913 if (IsFPClass) {
5914 QualType ResultTy;
5915 if (!VectorResultTy.isNull())
5916 ResultTy = VectorResultTy;
5917 else
5918 ResultTy = Context.IntTy;
5919 TheCall->setType(ResultTy);
5920 }
5921
5922 return false;
5923}
5924
5925bool Sema::BuiltinComplex(CallExpr *TheCall) {
5926 if (checkArgCount(TheCall, 2))
5927 return true;
5928
5929 bool Dependent = false;
5930 for (unsigned I = 0; I != 2; ++I) {
5931 Expr *Arg = TheCall->getArg(I);
5932 QualType T = Arg->getType();
5933 if (T->isDependentType()) {
5934 Dependent = true;
5935 continue;
5936 }
5937
5938 // Despite supporting _Complex int, GCC requires a real floating point type
5939 // for the operands of __builtin_complex.
5940 if (!T->isRealFloatingType()) {
5941 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5942 << Arg->getType() << Arg->getSourceRange();
5943 }
5944
5945 ExprResult Converted = DefaultLvalueConversion(Arg);
5946 if (Converted.isInvalid())
5947 return true;
5948 TheCall->setArg(I, Converted.get());
5949 }
5950
5951 if (Dependent) {
5952 TheCall->setType(Context.DependentTy);
5953 return false;
5954 }
5955
5956 Expr *Real = TheCall->getArg(0);
5957 Expr *Imag = TheCall->getArg(1);
5958 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5959 return Diag(Real->getBeginLoc(),
5960 diag::err_typecheck_call_different_arg_types)
5961 << Real->getType() << Imag->getType()
5962 << Real->getSourceRange() << Imag->getSourceRange();
5963 }
5964
5965 TheCall->setType(Context.getComplexType(Real->getType()));
5966 return false;
5967}
5968
5969/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5970// This is declared to take (...), so we have to check everything.
5972 unsigned NumArgs = TheCall->getNumArgs();
5973 if (NumArgs < 2)
5974 return ExprError(Diag(TheCall->getEndLoc(),
5975 diag::err_typecheck_call_too_few_args_at_least)
5976 << 0 /*function call*/ << 2 << NumArgs
5977 << /*is non object*/ 0 << TheCall->getSourceRange());
5978
5979 // Determine which of the following types of shufflevector we're checking:
5980 // 1) unary, vector mask: (lhs, mask)
5981 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5982 QualType ResType = TheCall->getArg(0)->getType();
5983 unsigned NumElements = 0;
5984
5985 if (!TheCall->getArg(0)->isTypeDependent() &&
5986 !TheCall->getArg(1)->isTypeDependent()) {
5987 QualType LHSType = TheCall->getArg(0)->getType();
5988 QualType RHSType = TheCall->getArg(1)->getType();
5989
5990 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5991 return ExprError(
5992 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5993 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5994 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5995 TheCall->getArg(1)->getEndLoc()));
5996
5997 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5998 unsigned NumResElements = NumArgs - 2;
5999
6000 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6001 // with mask. If so, verify that RHS is an integer vector type with the
6002 // same number of elts as lhs.
6003 if (NumArgs == 2) {
6004 if (!RHSType->hasIntegerRepresentation() ||
6005 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6006 return ExprError(Diag(TheCall->getBeginLoc(),
6007 diag::err_vec_builtin_incompatible_vector)
6008 << TheCall->getDirectCallee()
6009 << /*isMoreThanTwoArgs*/ false
6010 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6011 TheCall->getArg(1)->getEndLoc()));
6012 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6013 return ExprError(Diag(TheCall->getBeginLoc(),
6014 diag::err_vec_builtin_incompatible_vector)
6015 << TheCall->getDirectCallee()
6016 << /*isMoreThanTwoArgs*/ false
6017 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6018 TheCall->getArg(1)->getEndLoc()));
6019 } else if (NumElements != NumResElements) {
6020 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6021 ResType = ResType->isExtVectorType()
6022 ? Context.getExtVectorType(EltType, NumResElements)
6023 : Context.getVectorType(EltType, NumResElements,
6025 }
6026 }
6027
6028 for (unsigned I = 2; I != NumArgs; ++I) {
6029 Expr *Arg = TheCall->getArg(I);
6030 if (Arg->isTypeDependent() || Arg->isValueDependent())
6031 continue;
6032
6033 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6034 if (!Result)
6035 return ExprError(Diag(TheCall->getBeginLoc(),
6036 diag::err_shufflevector_nonconstant_argument)
6037 << Arg->getSourceRange());
6038
6039 // Allow -1 which will be translated to undef in the IR.
6040 if (Result->isSigned() && Result->isAllOnes())
6041 ;
6042 else if (Result->getActiveBits() > 64 ||
6043 Result->getZExtValue() >= NumElements * 2)
6044 return ExprError(Diag(TheCall->getBeginLoc(),
6045 diag::err_shufflevector_argument_too_large)
6046 << Arg->getSourceRange());
6047
6048 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6049 }
6050
6051 auto *Result = new (Context) ShuffleVectorExpr(
6052 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6053 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6054
6055 // All moved to Result.
6056 TheCall->shrinkNumArgs(0);
6057 return Result;
6058}
6059
6061 SourceLocation BuiltinLoc,
6062 SourceLocation RParenLoc) {
6065 QualType DstTy = TInfo->getType();
6066 QualType SrcTy = E->getType();
6067
6068 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6069 return ExprError(Diag(BuiltinLoc,
6070 diag::err_convertvector_non_vector)
6071 << E->getSourceRange());
6072 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6073 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6074 << "second"
6075 << "__builtin_convertvector");
6076
6077 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6078 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6079 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6080 if (SrcElts != DstElts)
6081 return ExprError(Diag(BuiltinLoc,
6082 diag::err_convertvector_incompatible_vector)
6083 << E->getSourceRange());
6084 }
6085
6086 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6087 RParenLoc, CurFPFeatureOverrides());
6088}
6089
6090bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6091 unsigned NumArgs = TheCall->getNumArgs();
6092
6093 if (NumArgs > 3)
6094 return Diag(TheCall->getEndLoc(),
6095 diag::err_typecheck_call_too_many_args_at_most)
6096 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6097 << TheCall->getSourceRange();
6098
6099 // Argument 0 is checked for us and the remaining arguments must be
6100 // constant integers.
6101 for (unsigned i = 1; i != NumArgs; ++i)
6102 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6103 return true;
6104
6105 return false;
6106}
6107
6108bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6109 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6110 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6111 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6112 if (checkArgCount(TheCall, 1))
6113 return true;
6114 Expr *Arg = TheCall->getArg(0);
6115 if (Arg->isInstantiationDependent())
6116 return false;
6117
6118 QualType ArgTy = Arg->getType();
6119 if (!ArgTy->hasFloatingRepresentation())
6120 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6121 << ArgTy;
6122 if (Arg->isLValue()) {
6123 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6124 TheCall->setArg(0, FirstArg.get());
6125 }
6126 TheCall->setType(TheCall->getArg(0)->getType());
6127 return false;
6128}
6129
6130bool Sema::BuiltinAssume(CallExpr *TheCall) {
6131 Expr *Arg = TheCall->getArg(0);
6132 if (Arg->isInstantiationDependent()) return false;
6133
6134 if (Arg->HasSideEffects(Context))
6135 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6136 << Arg->getSourceRange()
6137 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6138
6139 return false;
6140}
6141
6142bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6143 // The alignment must be a constant integer.
6144 Expr *Arg = TheCall->getArg(1);
6145
6146 // We can't check the value of a dependent argument.
6147 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6148 if (const auto *UE =
6149 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6150 if (UE->getKind() == UETT_AlignOf ||
6151 UE->getKind() == UETT_PreferredAlignOf)
6152 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6153 << Arg->getSourceRange();
6154
6155 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6156
6157 if (!Result.isPowerOf2())
6158 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6159 << Arg->getSourceRange();
6160
6161 if (Result < Context.getCharWidth())
6162 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6163 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6164
6165 if (Result > std::numeric_limits<int32_t>::max())
6166 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6167 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6168 }
6169
6170 return false;
6171}
6172
6173bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6174 if (checkArgCountRange(TheCall, 2, 3))
6175 return true;
6176
6177 unsigned NumArgs = TheCall->getNumArgs();
6178 Expr *FirstArg = TheCall->getArg(0);
6179
6180 {
6181 ExprResult FirstArgResult =
6183 if (!FirstArgResult.get()->getType()->isPointerType()) {
6184 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6185 << TheCall->getSourceRange();
6186 return true;
6187 }
6188 TheCall->setArg(0, FirstArgResult.get());
6189 }
6190
6191 // The alignment must be a constant integer.
6192 Expr *SecondArg = TheCall->getArg(1);
6193
6194 // We can't check the value of a dependent argument.
6195 if (!SecondArg->isValueDependent()) {
6196 llvm::APSInt Result;
6197 if (BuiltinConstantArg(TheCall, 1, Result))
6198 return true;
6199
6200 if (!Result.isPowerOf2())
6201 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6202 << SecondArg->getSourceRange();
6203
6205 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6206 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6207
6208 TheCall->setArg(1,
6210 }
6211
6212 if (NumArgs > 2) {
6213 Expr *ThirdArg = TheCall->getArg(2);
6214 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6215 return true;
6216 TheCall->setArg(2, ThirdArg);
6217 }
6218
6219 return false;
6220}
6221
6222bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6223 unsigned BuiltinID =
6224 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6225 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6226
6227 unsigned NumArgs = TheCall->getNumArgs();
6228 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6229 if (NumArgs < NumRequiredArgs) {
6230 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6231 << 0 /* function call */ << NumRequiredArgs << NumArgs
6232 << /*is non object*/ 0 << TheCall->getSourceRange();
6233 }
6234 if (NumArgs >= NumRequiredArgs + 0x100) {
6235 return Diag(TheCall->getEndLoc(),
6236 diag::err_typecheck_call_too_many_args_at_most)
6237 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6238 << /*is non object*/ 0 << TheCall->getSourceRange();
6239 }
6240 unsigned i = 0;
6241
6242 // For formatting call, check buffer arg.
6243 if (!IsSizeCall) {
6244 ExprResult Arg(TheCall->getArg(i));
6245 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6246 Context, Context.VoidPtrTy, false);
6247 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6248 if (Arg.isInvalid())
6249 return true;
6250 TheCall->setArg(i, Arg.get());
6251 i++;
6252 }
6253
6254 // Check string literal arg.
6255 unsigned FormatIdx = i;
6256 {
6257 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6258 if (Arg.isInvalid())
6259 return true;
6260 TheCall->setArg(i, Arg.get());
6261 i++;
6262 }
6263
6264 // Make sure variadic args are scalar.
6265 unsigned FirstDataArg = i;
6266 while (i < NumArgs) {
6268 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6269 if (Arg.isInvalid())
6270 return true;
6271 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6272 if (ArgSize.getQuantity() >= 0x100) {
6273 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6274 << i << (int)ArgSize.getQuantity() << 0xff
6275 << TheCall->getSourceRange();
6276 }
6277 TheCall->setArg(i, Arg.get());
6278 i++;
6279 }
6280
6281 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6282 // call to avoid duplicate diagnostics.
6283 if (!IsSizeCall) {
6284 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6285 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6286 bool Success = CheckFormatArguments(
6287 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6289 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6290 if (!Success)
6291 return true;
6292 }
6293
6294 if (IsSizeCall) {
6295 TheCall->setType(Context.getSizeType());
6296 } else {
6297 TheCall->setType(Context.VoidPtrTy);
6298 }
6299 return false;
6300}
6301
6302bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6303 llvm::APSInt &Result) {
6304 Expr *Arg = TheCall->getArg(ArgNum);
6305
6306 if (Arg->isTypeDependent() || Arg->isValueDependent())
6307 return false;
6308
6309 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6310 if (!R) {
6311 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6312 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6313 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6314 << FDecl->getDeclName() << Arg->getSourceRange();
6315 }
6316 Result = *R;
6317
6318 return false;
6319}
6320
6321bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6322 int High, bool RangeIsError) {
6324 return false;
6325 llvm::APSInt Result;
6326
6327 // We can't check the value of a dependent argument.
6328 Expr *Arg = TheCall->getArg(ArgNum);
6329 if (Arg->isTypeDependent() || Arg->isValueDependent())
6330 return false;
6331
6332 // Check constant-ness first.
6333 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6334 return true;
6335
6336 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6337 if (RangeIsError)
6338 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6339 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6340 else
6341 // Defer the warning until we know if the code will be emitted so that
6342 // dead code can ignore this.
6343 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6344 PDiag(diag::warn_argument_invalid_range)
6345 << toString(Result, 10) << Low << High
6346 << Arg->getSourceRange());
6347 }
6348
6349 return false;
6350}
6351
6352bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6353 unsigned Num) {
6354 llvm::APSInt Result;
6355
6356 // We can't check the value of a dependent argument.
6357 Expr *Arg = TheCall->getArg(ArgNum);
6358 if (Arg->isTypeDependent() || Arg->isValueDependent())
6359 return false;
6360
6361 // Check constant-ness first.
6362 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6363 return true;
6364
6365 if (Result.getSExtValue() % Num != 0)
6366 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6367 << Num << Arg->getSourceRange();
6368
6369 return false;
6370}
6371
6372bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6373 llvm::APSInt Result;
6374
6375 // We can't check the value of a dependent argument.
6376 Expr *Arg = TheCall->getArg(ArgNum);
6377 if (Arg->isTypeDependent() || Arg->isValueDependent())
6378 return false;
6379
6380 // Check constant-ness first.
6381 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6382 return true;
6383
6384 if (Result.isPowerOf2())
6385 return false;
6386
6387 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6388 << Arg->getSourceRange();
6389}
6390
6391static bool IsShiftedByte(llvm::APSInt Value) {
6392 if (Value.isNegative())
6393 return false;
6394
6395 // Check if it's a shifted byte, by shifting it down
6396 while (true) {
6397 // If the value fits in the bottom byte, the check passes.
6398 if (Value < 0x100)
6399 return true;
6400
6401 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6402 // fails.
6403 if ((Value & 0xFF) != 0)
6404 return false;
6405
6406 // If the bottom 8 bits are all 0, but something above that is nonzero,
6407 // then shifting the value right by 8 bits won't affect whether it's a
6408 // shifted byte or not. So do that, and go round again.
6409 Value >>= 8;
6410 }
6411}
6412
6413bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6414 unsigned ArgBits) {
6415 llvm::APSInt Result;
6416
6417 // We can't check the value of a dependent argument.
6418 Expr *Arg = TheCall->getArg(ArgNum);
6419 if (Arg->isTypeDependent() || Arg->isValueDependent())
6420 return false;
6421
6422 // Check constant-ness first.
6423 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6424 return true;
6425
6426 // Truncate to the given size.
6427 Result = Result.getLoBits(ArgBits);
6428 Result.setIsUnsigned(true);
6429
6430 if (IsShiftedByte(Result))
6431 return false;
6432
6433 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6434 << Arg->getSourceRange();
6435}
6436
6438 unsigned ArgNum,
6439 unsigned ArgBits) {
6440 llvm::APSInt Result;
6441
6442 // We can't check the value of a dependent argument.
6443 Expr *Arg = TheCall->getArg(ArgNum);
6444 if (Arg->isTypeDependent() || Arg->isValueDependent())
6445 return false;
6446
6447 // Check constant-ness first.
6448 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6449 return true;
6450
6451 // Truncate to the given size.
6452 Result = Result.getLoBits(ArgBits);
6453 Result.setIsUnsigned(true);
6454
6455 // Check to see if it's in either of the required forms.
6456 if (IsShiftedByte(Result) ||
6457 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6458 return false;
6459
6460 return Diag(TheCall->getBeginLoc(),
6461 diag::err_argument_not_shifted_byte_or_xxff)
6462 << Arg->getSourceRange();
6463}
6464
6465bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6466 if (!Context.getTargetInfo().hasSjLjLowering())
6467 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6468 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6469
6470 Expr *Arg = TheCall->getArg(1);
6471 llvm::APSInt Result;
6472
6473 // TODO: This is less than ideal. Overload this to take a value.
6474 if (BuiltinConstantArg(TheCall, 1, Result))
6475 return true;
6476
6477 if (Result != 1)
6478 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6479 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6480
6481 return false;
6482}
6483
6484bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6485 if (!Context.getTargetInfo().hasSjLjLowering())
6486 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6487 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6488 return false;
6489}
6490
6491bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6492 if (checkArgCount(TheCall, 1))
6493 return true;
6494
6495 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6496 if (ArgRes.isInvalid())
6497 return true;
6498
6499 // For simplicity, we support only limited expressions for the argument.
6500 // Specifically a flexible array member or a pointer with counted_by:
6501 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6502 // complex casting, which really shouldn't be a huge problem.
6503 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6504 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6505 return Diag(Arg->getBeginLoc(),
6506 diag::err_builtin_counted_by_ref_invalid_arg)
6507 << Arg->getSourceRange();
6508
6509 if (Arg->HasSideEffects(Context))
6510 return Diag(Arg->getBeginLoc(),
6511 diag::err_builtin_counted_by_ref_has_side_effects)
6512 << Arg->getSourceRange();
6513
6514 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6515 const auto *CATy =
6516 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6517
6518 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6519 // Member has counted_by attribute - return pointer to count field
6520 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6521 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6522 TheCall->setType(Context.getPointerType(CountFD->getType()));
6523 return false;
6524 }
6525 }
6526
6527 // FAMs and pointers without counted_by return void*
6528 QualType MemberTy = ME->getMemberDecl()->getType();
6529 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6530 return Diag(Arg->getBeginLoc(),
6531 diag::err_builtin_counted_by_ref_invalid_arg)
6532 << Arg->getSourceRange();
6533 } else {
6534 return Diag(Arg->getBeginLoc(),
6535 diag::err_builtin_counted_by_ref_invalid_arg)
6536 << Arg->getSourceRange();
6537 }
6538
6539 TheCall->setType(Context.getPointerType(Context.VoidTy));
6540 return false;
6541}
6542
6543/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6544/// It allows leaking and modification of bounds safety information.
6545bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6547 const CallExpr *CE =
6548 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6549 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6550 return false;
6551
6552 switch (K) {
6555 Diag(E->getExprLoc(),
6556 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6557 << 0 << E->getSourceRange();
6558 break;
6560 Diag(E->getExprLoc(),
6561 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6562 << 1 << E->getSourceRange();
6563 break;
6565 Diag(E->getExprLoc(),
6566 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6567 << 2 << E->getSourceRange();
6568 break;
6570 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6571 << 0 << E->getSourceRange();
6572 break;
6574 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6575 << 1 << E->getSourceRange();
6576 break;
6577 }
6578
6579 return true;
6580}
6581
6582namespace {
6583
6584class UncoveredArgHandler {
6585 enum { Unknown = -1, AllCovered = -2 };
6586
6587 signed FirstUncoveredArg = Unknown;
6588 SmallVector<const Expr *, 4> DiagnosticExprs;
6589
6590public:
6591 UncoveredArgHandler() = default;
6592
6593 bool hasUncoveredArg() const {
6594 return (FirstUncoveredArg >= 0);
6595 }
6596
6597 unsigned getUncoveredArg() const {
6598 assert(hasUncoveredArg() && "no uncovered argument");
6599 return FirstUncoveredArg;
6600 }
6601
6602 void setAllCovered() {
6603 // A string has been found with all arguments covered, so clear out
6604 // the diagnostics.
6605 DiagnosticExprs.clear();
6606 FirstUncoveredArg = AllCovered;
6607 }
6608
6609 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6610 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6611
6612 // Don't update if a previous string covers all arguments.
6613 if (FirstUncoveredArg == AllCovered)
6614 return;
6615
6616 // UncoveredArgHandler tracks the highest uncovered argument index
6617 // and with it all the strings that match this index.
6618 if (NewFirstUncoveredArg == FirstUncoveredArg)
6619 DiagnosticExprs.push_back(StrExpr);
6620 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6621 DiagnosticExprs.clear();
6622 DiagnosticExprs.push_back(StrExpr);
6623 FirstUncoveredArg = NewFirstUncoveredArg;
6624 }
6625 }
6626
6627 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6628};
6629
6630enum StringLiteralCheckType {
6631 SLCT_NotALiteral,
6632 SLCT_UncheckedLiteral,
6633 SLCT_CheckedLiteral
6634};
6635
6636} // namespace
6637
6638static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6639 BinaryOperatorKind BinOpKind,
6640 bool AddendIsRight) {
6641 unsigned BitWidth = Offset.getBitWidth();
6642 unsigned AddendBitWidth = Addend.getBitWidth();
6643 // There might be negative interim results.
6644 if (Addend.isUnsigned()) {
6645 Addend = Addend.zext(++AddendBitWidth);
6646 Addend.setIsSigned(true);
6647 }
6648 // Adjust the bit width of the APSInts.
6649 if (AddendBitWidth > BitWidth) {
6650 Offset = Offset.sext(AddendBitWidth);
6651 BitWidth = AddendBitWidth;
6652 } else if (BitWidth > AddendBitWidth) {
6653 Addend = Addend.sext(BitWidth);
6654 }
6655
6656 bool Ov = false;
6657 llvm::APSInt ResOffset = Offset;
6658 if (BinOpKind == BO_Add)
6659 ResOffset = Offset.sadd_ov(Addend, Ov);
6660 else {
6661 assert(AddendIsRight && BinOpKind == BO_Sub &&
6662 "operator must be add or sub with addend on the right");
6663 ResOffset = Offset.ssub_ov(Addend, Ov);
6664 }
6665
6666 // We add an offset to a pointer here so we should support an offset as big as
6667 // possible.
6668 if (Ov) {
6669 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6670 "index (intermediate) result too big");
6671 Offset = Offset.sext(2 * BitWidth);
6672 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6673 return;
6674 }
6675
6676 Offset = ResOffset;
6677}
6678
6679namespace {
6680
6681// This is a wrapper class around StringLiteral to support offsetted string
6682// literals as format strings. It takes the offset into account when returning
6683// the string and its length or the source locations to display notes correctly.
6684class FormatStringLiteral {
6685 const StringLiteral *FExpr;
6686 int64_t Offset;
6687
6688public:
6689 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6690 : FExpr(fexpr), Offset(Offset) {}
6691
6692 const StringLiteral *getFormatString() const { return FExpr; }
6693
6694 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6695
6696 unsigned getByteLength() const {
6697 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6698 }
6699
6700 unsigned getLength() const { return FExpr->getLength() - Offset; }
6701 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6702
6703 StringLiteralKind getKind() const { return FExpr->getKind(); }
6704
6705 QualType getType() const { return FExpr->getType(); }
6706
6707 bool isAscii() const { return FExpr->isOrdinary(); }
6708 bool isWide() const { return FExpr->isWide(); }
6709 bool isUTF8() const { return FExpr->isUTF8(); }
6710 bool isUTF16() const { return FExpr->isUTF16(); }
6711 bool isUTF32() const { return FExpr->isUTF32(); }
6712 bool isPascal() const { return FExpr->isPascal(); }
6713
6714 SourceLocation getLocationOfByte(
6715 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6716 const TargetInfo &Target, unsigned *StartToken = nullptr,
6717 unsigned *StartTokenByteOffset = nullptr) const {
6718 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6719 StartToken, StartTokenByteOffset);
6720 }
6721
6722 SourceLocation getBeginLoc() const LLVM_READONLY {
6723 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6724 }
6725
6726 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6727};
6728
6729} // namespace
6730
6731static void CheckFormatString(
6732 Sema &S, const FormatStringLiteral *FExpr,
6733 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6735 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6736 bool inFunctionCall, VariadicCallType CallType,
6737 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6738 bool IgnoreStringsWithoutSpecifiers);
6739
6740static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6741 const Expr *E);
6742
6743// Determine if an expression is a string literal or constant string.
6744// If this function returns false on the arguments to a function expecting a
6745// format string, we will usually need to emit a warning.
6746// True string literals are then checked by CheckFormatString.
6747static StringLiteralCheckType
6748checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6749 const Expr *E, ArrayRef<const Expr *> Args,
6750 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6751 unsigned firstDataArg, FormatStringType Type,
6752 VariadicCallType CallType, bool InFunctionCall,
6753 llvm::SmallBitVector &CheckedVarArgs,
6754 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6755 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6756 bool IgnoreStringsWithoutSpecifiers = false) {
6758 return SLCT_NotALiteral;
6759tryAgain:
6760 assert(Offset.isSigned() && "invalid offset");
6761
6762 if (E->isTypeDependent() || E->isValueDependent())
6763 return SLCT_NotALiteral;
6764
6765 E = E->IgnoreParenCasts();
6766
6768 // Technically -Wformat-nonliteral does not warn about this case.
6769 // The behavior of printf and friends in this case is implementation
6770 // dependent. Ideally if the format string cannot be null then
6771 // it should have a 'nonnull' attribute in the function prototype.
6772 return SLCT_UncheckedLiteral;
6773
6774 switch (E->getStmtClass()) {
6775 case Stmt::InitListExprClass:
6776 // Handle expressions like {"foobar"}.
6777 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6778 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
6779 format_idx, firstDataArg, Type, CallType,
6780 /*InFunctionCall*/ false, CheckedVarArgs,
6781 UncoveredArg, Offset, CallerFormatParamIdx,
6782 IgnoreStringsWithoutSpecifiers);
6783 }
6784 return SLCT_NotALiteral;
6785 case Stmt::BinaryConditionalOperatorClass:
6786 case Stmt::ConditionalOperatorClass: {
6787 // The expression is a literal if both sub-expressions were, and it was
6788 // completely checked only if both sub-expressions were checked.
6791
6792 // Determine whether it is necessary to check both sub-expressions, for
6793 // example, because the condition expression is a constant that can be
6794 // evaluated at compile time.
6795 bool CheckLeft = true, CheckRight = true;
6796
6797 bool Cond;
6798 if (C->getCond()->EvaluateAsBooleanCondition(
6800 if (Cond)
6801 CheckRight = false;
6802 else
6803 CheckLeft = false;
6804 }
6805
6806 // We need to maintain the offsets for the right and the left hand side
6807 // separately to check if every possible indexed expression is a valid
6808 // string literal. They might have different offsets for different string
6809 // literals in the end.
6810 StringLiteralCheckType Left;
6811 if (!CheckLeft)
6812 Left = SLCT_UncheckedLiteral;
6813 else {
6814 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
6815 Args, APK, format_idx, firstDataArg, Type,
6816 CallType, InFunctionCall, CheckedVarArgs,
6817 UncoveredArg, Offset, CallerFormatParamIdx,
6818 IgnoreStringsWithoutSpecifiers);
6819 if (Left == SLCT_NotALiteral || !CheckRight) {
6820 return Left;
6821 }
6822 }
6823
6824 StringLiteralCheckType Right = checkFormatStringExpr(
6825 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6826 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6827 UncoveredArg, Offset, CallerFormatParamIdx,
6828 IgnoreStringsWithoutSpecifiers);
6829
6830 return (CheckLeft && Left < Right) ? Left : Right;
6831 }
6832
6833 case Stmt::ImplicitCastExprClass:
6834 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6835 goto tryAgain;
6836
6837 case Stmt::OpaqueValueExprClass:
6838 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6839 E = src;
6840 goto tryAgain;
6841 }
6842 return SLCT_NotALiteral;
6843
6844 case Stmt::PredefinedExprClass:
6845 // While __func__, etc., are technically not string literals, they
6846 // cannot contain format specifiers and thus are not a security
6847 // liability.
6848 return SLCT_UncheckedLiteral;
6849
6850 case Stmt::DeclRefExprClass: {
6851 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6852
6853 // As an exception, do not flag errors for variables binding to
6854 // const string literals.
6855 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6856 bool isConstant = false;
6857 QualType T = DR->getType();
6858
6859 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6860 isConstant = AT->getElementType().isConstant(S.Context);
6861 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6862 isConstant = T.isConstant(S.Context) &&
6863 PT->getPointeeType().isConstant(S.Context);
6864 } else if (T->isObjCObjectPointerType()) {
6865 // In ObjC, there is usually no "const ObjectPointer" type,
6866 // so don't check if the pointee type is constant.
6867 isConstant = T.isConstant(S.Context);
6868 }
6869
6870 if (isConstant) {
6871 if (const Expr *Init = VD->getAnyInitializer()) {
6872 // Look through initializers like const char c[] = { "foo" }
6873 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6874 if (InitList->isStringLiteralInit())
6875 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6876 }
6877 return checkFormatStringExpr(
6878 S, ReferenceFormatString, Init, Args, APK, format_idx,
6879 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
6880 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
6881 }
6882 }
6883
6884 // When the format argument is an argument of this function, and this
6885 // function also has the format attribute, there are several interactions
6886 // for which there shouldn't be a warning. For instance, when calling
6887 // v*printf from a function that has the printf format attribute, we
6888 // should not emit a warning about using `fmt`, even though it's not
6889 // constant, because the arguments have already been checked for the
6890 // caller of `logmessage`:
6891 //
6892 // __attribute__((format(printf, 1, 2)))
6893 // void logmessage(char const *fmt, ...) {
6894 // va_list ap;
6895 // va_start(ap, fmt);
6896 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6897 // ...
6898 // }
6899 //
6900 // Another interaction that we need to support is using a format string
6901 // specified by the format_matches attribute:
6902 //
6903 // __attribute__((format_matches(printf, 1, "%s %d")))
6904 // void logmessage(char const *fmt, const char *a, int b) {
6905 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6906 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6907 // ...
6908 // }
6909 //
6910 // Yet another interaction that we need to support is calling a variadic
6911 // format function from a format function that has fixed arguments. For
6912 // instance:
6913 //
6914 // __attribute__((format(printf, 1, 2)))
6915 // void logstring(char const *fmt, char const *str) {
6916 // printf(fmt, str); /* do not emit a warning about "fmt" */
6917 // }
6918 //
6919 // Same (and perhaps more relatably) for the variadic template case:
6920 //
6921 // template<typename... Args>
6922 // __attribute__((format(printf, 1, 2)))
6923 // void log(const char *fmt, Args&&... args) {
6924 // printf(fmt, forward<Args>(args)...);
6925 // /* do not emit a warning about "fmt" */
6926 // }
6927 //
6928 // Due to implementation difficulty, we only check the format, not the
6929 // format arguments, in all cases.
6930 //
6931 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6932 if (CallerFormatParamIdx)
6933 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
6934 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6935 for (const auto *PVFormatMatches :
6936 D->specific_attrs<FormatMatchesAttr>()) {
6937 Sema::FormatStringInfo CalleeFSI;
6938 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6939 0, &CalleeFSI))
6940 continue;
6941 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6942 // If using the wrong type of format string, emit a diagnostic
6943 // here and stop checking to avoid irrelevant diagnostics.
6944 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6945 S.Diag(Args[format_idx]->getBeginLoc(),
6946 diag::warn_format_string_type_incompatible)
6947 << PVFormatMatches->getType()->getName()
6949 if (!InFunctionCall) {
6950 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6951 diag::note_format_string_defined);
6952 }
6953 return SLCT_UncheckedLiteral;
6954 }
6955 return checkFormatStringExpr(
6956 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6957 Args, APK, format_idx, firstDataArg, Type, CallType,
6958 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6959 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
6960 }
6961 }
6962
6963 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6964 Sema::FormatStringInfo CallerFSI;
6965 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6966 PVFormat->getFirstArg(), &CallerFSI))
6967 continue;
6968 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6969 // We also check if the formats are compatible.
6970 // We can't pass a 'scanf' string to a 'printf' function.
6971 if (Type != S.GetFormatStringType(PVFormat)) {
6972 S.Diag(Args[format_idx]->getBeginLoc(),
6973 diag::warn_format_string_type_incompatible)
6974 << PVFormat->getType()->getName()
6976 if (!InFunctionCall) {
6977 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6978 }
6979 return SLCT_UncheckedLiteral;
6980 }
6981 // Lastly, check that argument passing kinds transition in a
6982 // way that makes sense:
6983 // from a caller with FAPK_VAList, allow FAPK_VAList
6984 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6985 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6986 // from a caller with FAPK_Variadic, allow FAPK_VAList
6987 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6992 return SLCT_UncheckedLiteral;
6993 }
6994 }
6995 }
6996 }
6997 }
6998 }
6999
7000 return SLCT_NotALiteral;
7001 }
7002
7003 case Stmt::CallExprClass:
7004 case Stmt::CXXMemberCallExprClass: {
7005 const CallExpr *CE = cast<CallExpr>(E);
7006 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7007 bool IsFirst = true;
7008 StringLiteralCheckType CommonResult;
7009 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7010 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7011 StringLiteralCheckType Result = checkFormatStringExpr(
7012 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7013 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7014 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7015 if (IsFirst) {
7016 CommonResult = Result;
7017 IsFirst = false;
7018 }
7019 }
7020 if (!IsFirst)
7021 return CommonResult;
7022
7023 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7024 unsigned BuiltinID = FD->getBuiltinID();
7025 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7026 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7027 const Expr *Arg = CE->getArg(0);
7028 return checkFormatStringExpr(
7029 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7030 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7031 UncoveredArg, Offset, CallerFormatParamIdx,
7032 IgnoreStringsWithoutSpecifiers);
7033 }
7034 }
7035 }
7036 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7037 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7038 format_idx, firstDataArg, Type, CallType,
7039 /*InFunctionCall*/ false, CheckedVarArgs,
7040 UncoveredArg, Offset, CallerFormatParamIdx,
7041 IgnoreStringsWithoutSpecifiers);
7042 return SLCT_NotALiteral;
7043 }
7044 case Stmt::ObjCMessageExprClass: {
7045 const auto *ME = cast<ObjCMessageExpr>(E);
7046 if (const auto *MD = ME->getMethodDecl()) {
7047 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7048 // As a special case heuristic, if we're using the method -[NSBundle
7049 // localizedStringForKey:value:table:], ignore any key strings that lack
7050 // format specifiers. The idea is that if the key doesn't have any
7051 // format specifiers then its probably just a key to map to the
7052 // localized strings. If it does have format specifiers though, then its
7053 // likely that the text of the key is the format string in the
7054 // programmer's language, and should be checked.
7055 const ObjCInterfaceDecl *IFace;
7056 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7057 IFace->getIdentifier()->isStr("NSBundle") &&
7058 MD->getSelector().isKeywordSelector(
7059 {"localizedStringForKey", "value", "table"})) {
7060 IgnoreStringsWithoutSpecifiers = true;
7061 }
7062
7063 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7064 return checkFormatStringExpr(
7065 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7066 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7067 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7068 }
7069 }
7070
7071 return SLCT_NotALiteral;
7072 }
7073 case Stmt::ObjCStringLiteralClass:
7074 case Stmt::StringLiteralClass: {
7075 const StringLiteral *StrE = nullptr;
7076
7077 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7078 StrE = ObjCFExpr->getString();
7079 else
7080 StrE = cast<StringLiteral>(E);
7081
7082 if (StrE) {
7083 if (Offset.isNegative() || Offset > StrE->getLength()) {
7084 // TODO: It would be better to have an explicit warning for out of
7085 // bounds literals.
7086 return SLCT_NotALiteral;
7087 }
7088 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7089 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7090 format_idx, firstDataArg, Type, InFunctionCall,
7091 CallType, CheckedVarArgs, UncoveredArg,
7092 IgnoreStringsWithoutSpecifiers);
7093 return SLCT_CheckedLiteral;
7094 }
7095
7096 return SLCT_NotALiteral;
7097 }
7098 case Stmt::BinaryOperatorClass: {
7099 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7100
7101 // A string literal + an int offset is still a string literal.
7102 if (BinOp->isAdditiveOp()) {
7103 Expr::EvalResult LResult, RResult;
7104
7105 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7106 LResult, S.Context, Expr::SE_NoSideEffects,
7108 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7109 RResult, S.Context, Expr::SE_NoSideEffects,
7111
7112 if (LIsInt != RIsInt) {
7113 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7114
7115 if (LIsInt) {
7116 if (BinOpKind == BO_Add) {
7117 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7118 E = BinOp->getRHS();
7119 goto tryAgain;
7120 }
7121 } else {
7122 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7123 E = BinOp->getLHS();
7124 goto tryAgain;
7125 }
7126 }
7127 }
7128
7129 return SLCT_NotALiteral;
7130 }
7131 case Stmt::UnaryOperatorClass: {
7132 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7133 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7134 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7135 Expr::EvalResult IndexResult;
7136 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7139 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7140 /*RHS is int*/ true);
7141 E = ASE->getBase();
7142 goto tryAgain;
7143 }
7144 }
7145
7146 return SLCT_NotALiteral;
7147 }
7148
7149 default:
7150 return SLCT_NotALiteral;
7151 }
7152}
7153
7154// If this expression can be evaluated at compile-time,
7155// check if the result is a StringLiteral and return it
7156// otherwise return nullptr
7158 const Expr *E) {
7159 Expr::EvalResult Result;
7160 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7161 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7162 if (isa_and_nonnull<StringLiteral>(LVE))
7163 return LVE;
7164 }
7165 return nullptr;
7166}
7167
7169 switch (FST) {
7171 return "scanf";
7173 return "printf";
7175 return "NSString";
7177 return "strftime";
7179 return "strfmon";
7181 return "kprintf";
7183 return "freebsd_kprintf";
7185 return "os_log";
7186 default:
7187 return "<unknown>";
7188 }
7189}
7190
7192 return llvm::StringSwitch<FormatStringType>(Flavor)
7193 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7194 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7196 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7197 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7198 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7199 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7201 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7202 .Case("os_trace", FormatStringType::OSLog)
7203 .Case("os_log", FormatStringType::OSLog)
7204 .Default(FormatStringType::Unknown);
7205}
7206
7208 return GetFormatStringType(Format->getType()->getName());
7209}
7210
7211FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7212 return GetFormatStringType(Format->getType()->getName());
7213}
7214
7215bool Sema::CheckFormatArguments(const FormatAttr *Format,
7216 ArrayRef<const Expr *> Args, bool IsCXXMember,
7217 VariadicCallType CallType, SourceLocation Loc,
7218 SourceRange Range,
7219 llvm::SmallBitVector &CheckedVarArgs) {
7220 FormatStringInfo FSI;
7221 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7222 IsCXXMember,
7223 CallType != VariadicCallType::DoesNotApply, &FSI))
7224 return CheckFormatArguments(
7225 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7226 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7227 return false;
7228}
7229
7230bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7231 ArrayRef<const Expr *> Args, bool IsCXXMember,
7232 VariadicCallType CallType, SourceLocation Loc,
7233 SourceRange Range,
7234 llvm::SmallBitVector &CheckedVarArgs) {
7235 FormatStringInfo FSI;
7236 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7237 &FSI)) {
7238 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7239 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7240 Format->getFormatString(), FSI.FormatIdx,
7241 FSI.FirstDataArg, GetFormatStringType(Format),
7242 CallType, Loc, Range, CheckedVarArgs);
7243 }
7244 return false;
7245}
7246
7249 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7250 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7251 SourceLocation Loc) {
7252 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7253 return false;
7254
7255 DeclContext *DC = S->CurContext;
7256 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7257 return false;
7258 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7259
7260 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7261
7262 // Find the offset to convert between attribute and parameter indexes.
7263 unsigned CallerArgumentIndexOffset =
7264 hasImplicitObjectParameter(Caller) ? 2 : 1;
7265
7266 unsigned FirstArgumentIndex = -1;
7267 switch (APK) {
7270 // As an extension, clang allows the format attribute on non-variadic
7271 // functions.
7272 // Caller must have fixed arguments to pass them to a fixed or variadic
7273 // function. Try to match caller and callee arguments. If successful, then
7274 // emit a diag with the caller idx, otherwise we can't determine the callee
7275 // arguments.
7276 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7277 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7278 // There aren't enough arguments in the caller to pass to callee.
7279 return false;
7280 }
7281 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7282 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7283 const auto *Arg =
7284 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7285 if (!Arg)
7286 return false;
7287 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7288 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7289 return false;
7290 }
7291 FirstArgumentIndex =
7292 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7293 break;
7294 }
7296 // Caller arguments are either variadic or a va_list.
7297 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7298 ? (NumCallerParams + CallerArgumentIndexOffset)
7299 : 0;
7300 break;
7302 // The callee has a format_matches attribute. We will emit that instead.
7303 if (!ReferenceFormatString)
7304 return false;
7305 break;
7306 }
7307
7308 // Emit the diagnostic and fixit.
7309 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7310 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7311 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7312 do {
7313 std::string Attr, Fixit;
7314 llvm::raw_string_ostream AttrOS(Attr);
7316 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7317 << FirstArgumentIndex << ")";
7318 } else {
7319 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7320 << ", \"";
7321 AttrOS.write_escaped(ReferenceFormatString->getString());
7322 AttrOS << "\")";
7323 }
7324 AttrOS.flush();
7325 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7326 if (ND)
7327 DB << ND;
7328 else
7329 DB << "block";
7330
7331 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7332 if (isa<BlockDecl>(Caller))
7333 break;
7334
7335 SourceLocation SL;
7336 llvm::raw_string_ostream IS(Fixit);
7337 // The attribute goes at the start of the declaration in C/C++ functions
7338 // and methods, but after the declaration for Objective-C methods.
7339 if (isa<ObjCMethodDecl>(Caller)) {
7340 IS << ' ';
7341 SL = Caller->getEndLoc();
7342 }
7343 const LangOptions &LO = S->getLangOpts();
7344 if (LO.C23 || LO.CPlusPlus11)
7345 IS << "[[gnu::" << Attr << "]]";
7346 else if (LO.ObjC || LO.GNUMode)
7347 IS << "__attribute__((" << Attr << "))";
7348 else
7349 break;
7350 if (!isa<ObjCMethodDecl>(Caller)) {
7351 IS << ' ';
7352 SL = Caller->getBeginLoc();
7353 }
7354 IS.flush();
7355
7356 DB << FixItHint::CreateInsertion(SL, Fixit);
7357 } while (false);
7358
7359 // Add implicit format or format_matches attribute.
7361 Caller->addAttr(FormatAttr::CreateImplicit(
7362 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7363 FormatStringIndex, FirstArgumentIndex));
7364 } else {
7365 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7366 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7367 FormatStringIndex, ReferenceFormatString));
7368 }
7369
7370 {
7371 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7372 if (ND)
7373 DB << ND;
7374 else
7375 DB << "block";
7376 }
7377 return true;
7378}
7379
7380bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7382 StringLiteral *ReferenceFormatString,
7383 unsigned format_idx, unsigned firstDataArg,
7385 VariadicCallType CallType, SourceLocation Loc,
7386 SourceRange Range,
7387 llvm::SmallBitVector &CheckedVarArgs) {
7388 // CHECK: printf/scanf-like function is called with no format string.
7389 if (format_idx >= Args.size()) {
7390 Diag(Loc, diag::warn_missing_format_string) << Range;
7391 return false;
7392 }
7393
7394 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7395
7396 // CHECK: format string is not a string literal.
7397 //
7398 // Dynamically generated format strings are difficult to
7399 // automatically vet at compile time. Requiring that format strings
7400 // are string literals: (1) permits the checking of format strings by
7401 // the compiler and thereby (2) can practically remove the source of
7402 // many format string exploits.
7403
7404 // Format string can be either ObjC string (e.g. @"%d") or
7405 // C string (e.g. "%d")
7406 // ObjC string uses the same format specifiers as C string, so we can use
7407 // the same format string checking logic for both ObjC and C strings.
7408 UncoveredArgHandler UncoveredArg;
7409 std::optional<unsigned> CallerParamIdx;
7410 StringLiteralCheckType CT = checkFormatStringExpr(
7411 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7412 firstDataArg, Type, CallType,
7413 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7414 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7415
7416 // Generate a diagnostic where an uncovered argument is detected.
7417 if (UncoveredArg.hasUncoveredArg()) {
7418 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7419 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7420 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7421 }
7422
7423 if (CT != SLCT_NotALiteral)
7424 // Literal format string found, check done!
7425 return CT == SLCT_CheckedLiteral;
7426
7427 // Do not emit diag when the string param is a macro expansion and the
7428 // format is either NSString or CFString. This is a hack to prevent
7429 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7430 // which are usually used in place of NS and CF string literals.
7431 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7433 SourceMgr.isInSystemMacro(FormatLoc))
7434 return false;
7435
7436 if (CallerParamIdx && CheckMissingFormatAttribute(
7437 this, Args, APK, ReferenceFormatString, format_idx,
7438 firstDataArg, Type, *CallerParamIdx, Loc))
7439 return false;
7440
7441 // Strftime is particular as it always uses a single 'time' argument,
7442 // so it is safe to pass a non-literal string.
7444 return false;
7445
7446 // If there are no arguments specified, warn with -Wformat-security, otherwise
7447 // warn only with -Wformat-nonliteral.
7448 if (Args.size() == firstDataArg) {
7449 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7450 << OrigFormatExpr->getSourceRange();
7451 switch (Type) {
7452 default:
7453 break;
7457 Diag(FormatLoc, diag::note_format_security_fixit)
7458 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7459 break;
7461 Diag(FormatLoc, diag::note_format_security_fixit)
7462 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7463 break;
7464 }
7465 } else {
7466 Diag(FormatLoc, diag::warn_format_nonliteral)
7467 << OrigFormatExpr->getSourceRange();
7468 }
7469 return false;
7470}
7471
7472namespace {
7473
7474class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7475protected:
7476 Sema &S;
7477 const FormatStringLiteral *FExpr;
7478 const Expr *OrigFormatExpr;
7479 const FormatStringType FSType;
7480 const unsigned FirstDataArg;
7481 const unsigned NumDataArgs;
7482 const char *Beg; // Start of format string.
7483 const Sema::FormatArgumentPassingKind ArgPassingKind;
7484 ArrayRef<const Expr *> Args;
7485 unsigned FormatIdx;
7486 llvm::SmallBitVector CoveredArgs;
7487 bool usesPositionalArgs = false;
7488 bool atFirstArg = true;
7489 bool inFunctionCall;
7490 VariadicCallType CallType;
7491 llvm::SmallBitVector &CheckedVarArgs;
7492 UncoveredArgHandler &UncoveredArg;
7493
7494public:
7495 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7496 const Expr *origFormatExpr, const FormatStringType type,
7497 unsigned firstDataArg, unsigned numDataArgs,
7498 const char *beg, Sema::FormatArgumentPassingKind APK,
7499 ArrayRef<const Expr *> Args, unsigned formatIdx,
7500 bool inFunctionCall, VariadicCallType callType,
7501 llvm::SmallBitVector &CheckedVarArgs,
7502 UncoveredArgHandler &UncoveredArg)
7503 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7504 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7505 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7506 inFunctionCall(inFunctionCall), CallType(callType),
7507 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7508 CoveredArgs.resize(numDataArgs);
7509 CoveredArgs.reset();
7510 }
7511
7512 bool HasFormatArguments() const {
7513 return ArgPassingKind == Sema::FAPK_Fixed ||
7514 ArgPassingKind == Sema::FAPK_Variadic;
7515 }
7516
7517 void DoneProcessing();
7518
7519 void HandleIncompleteSpecifier(const char *startSpecifier,
7520 unsigned specifierLen) override;
7521
7522 void HandleInvalidLengthModifier(
7523 const analyze_format_string::FormatSpecifier &FS,
7524 const analyze_format_string::ConversionSpecifier &CS,
7525 const char *startSpecifier, unsigned specifierLen,
7526 unsigned DiagID);
7527
7528 void HandleNonStandardLengthModifier(
7529 const analyze_format_string::FormatSpecifier &FS,
7530 const char *startSpecifier, unsigned specifierLen);
7531
7532 void HandleNonStandardConversionSpecifier(
7533 const analyze_format_string::ConversionSpecifier &CS,
7534 const char *startSpecifier, unsigned specifierLen);
7535
7536 void HandlePosition(const char *startPos, unsigned posLen) override;
7537
7538 void HandleInvalidPosition(const char *startSpecifier,
7539 unsigned specifierLen,
7541
7542 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7543
7544 void HandleNullChar(const char *nullCharacter) override;
7545
7546 template <typename Range>
7547 static void
7548 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7549 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7550 bool IsStringLocation, Range StringRange,
7551 ArrayRef<FixItHint> Fixit = {});
7552
7553protected:
7554 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7555 const char *startSpec,
7556 unsigned specifierLen,
7557 const char *csStart, unsigned csLen);
7558
7559 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7560 const char *startSpec,
7561 unsigned specifierLen);
7562
7563 SourceRange getFormatStringRange();
7564 CharSourceRange getSpecifierRange(const char *startSpecifier,
7565 unsigned specifierLen);
7566 SourceLocation getLocationOfByte(const char *x);
7567
7568 const Expr *getDataArg(unsigned i) const;
7569
7570 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7571 const analyze_format_string::ConversionSpecifier &CS,
7572 const char *startSpecifier, unsigned specifierLen,
7573 unsigned argIndex);
7574
7575 template <typename Range>
7576 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7577 bool IsStringLocation, Range StringRange,
7578 ArrayRef<FixItHint> Fixit = {});
7579};
7580
7581} // namespace
7582
7583SourceRange CheckFormatHandler::getFormatStringRange() {
7584 return OrigFormatExpr->getSourceRange();
7585}
7586
7587CharSourceRange CheckFormatHandler::
7588getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7589 SourceLocation Start = getLocationOfByte(startSpecifier);
7590 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7591
7592 // Advance the end SourceLocation by one due to half-open ranges.
7593 End = End.getLocWithOffset(1);
7594
7595 return CharSourceRange::getCharRange(Start, End);
7596}
7597
7598SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7599 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7601}
7602
7603void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7604 unsigned specifierLen){
7605 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7606 getLocationOfByte(startSpecifier),
7607 /*IsStringLocation*/true,
7608 getSpecifierRange(startSpecifier, specifierLen));
7609}
7610
7611void CheckFormatHandler::HandleInvalidLengthModifier(
7614 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7615 using namespace analyze_format_string;
7616
7617 const LengthModifier &LM = FS.getLengthModifier();
7618 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7619
7620 // See if we know how to fix this length modifier.
7621 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7622 if (FixedLM) {
7623 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7624 getLocationOfByte(LM.getStart()),
7625 /*IsStringLocation*/true,
7626 getSpecifierRange(startSpecifier, specifierLen));
7627
7628 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7629 << FixedLM->toString()
7630 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7631
7632 } else {
7633 FixItHint Hint;
7634 if (DiagID == diag::warn_format_nonsensical_length)
7635 Hint = FixItHint::CreateRemoval(LMRange);
7636
7637 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7638 getLocationOfByte(LM.getStart()),
7639 /*IsStringLocation*/true,
7640 getSpecifierRange(startSpecifier, specifierLen),
7641 Hint);
7642 }
7643}
7644
7645void CheckFormatHandler::HandleNonStandardLengthModifier(
7647 const char *startSpecifier, unsigned specifierLen) {
7648 using namespace analyze_format_string;
7649
7650 const LengthModifier &LM = FS.getLengthModifier();
7651 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7652
7653 // See if we know how to fix this length modifier.
7654 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7655 if (FixedLM) {
7656 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7657 << LM.toString() << 0,
7658 getLocationOfByte(LM.getStart()),
7659 /*IsStringLocation*/true,
7660 getSpecifierRange(startSpecifier, specifierLen));
7661
7662 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7663 << FixedLM->toString()
7664 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7665
7666 } else {
7667 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7668 << LM.toString() << 0,
7669 getLocationOfByte(LM.getStart()),
7670 /*IsStringLocation*/true,
7671 getSpecifierRange(startSpecifier, specifierLen));
7672 }
7673}
7674
7675void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7677 const char *startSpecifier, unsigned specifierLen) {
7678 using namespace analyze_format_string;
7679
7680 // See if we know how to fix this conversion specifier.
7681 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7682 if (FixedCS) {
7683 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7684 << CS.toString() << /*conversion specifier*/1,
7685 getLocationOfByte(CS.getStart()),
7686 /*IsStringLocation*/true,
7687 getSpecifierRange(startSpecifier, specifierLen));
7688
7689 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7690 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7691 << FixedCS->toString()
7692 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7693 } else {
7694 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7695 << CS.toString() << /*conversion specifier*/1,
7696 getLocationOfByte(CS.getStart()),
7697 /*IsStringLocation*/true,
7698 getSpecifierRange(startSpecifier, specifierLen));
7699 }
7700}
7701
7702void CheckFormatHandler::HandlePosition(const char *startPos,
7703 unsigned posLen) {
7704 if (!S.getDiagnostics().isIgnored(
7705 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7706 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7707 getLocationOfByte(startPos),
7708 /*IsStringLocation*/ true,
7709 getSpecifierRange(startPos, posLen));
7710}
7711
7712void CheckFormatHandler::HandleInvalidPosition(
7713 const char *startSpecifier, unsigned specifierLen,
7715 if (!S.getDiagnostics().isIgnored(
7716 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7717 EmitFormatDiagnostic(
7718 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7719 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7720 getSpecifierRange(startSpecifier, specifierLen));
7721}
7722
7723void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7724 unsigned posLen) {
7725 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7726 SourceLocation()))
7727 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7728 getLocationOfByte(startPos),
7729 /*IsStringLocation*/ true,
7730 getSpecifierRange(startPos, posLen));
7731}
7732
7733void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7734 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7735 // The presence of a null character is likely an error.
7736 EmitFormatDiagnostic(
7737 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7738 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7739 getFormatStringRange());
7740 }
7741}
7742
7743// Note that this may return NULL if there was an error parsing or building
7744// one of the argument expressions.
7745const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7746 return Args[FirstDataArg + i];
7747}
7748
7749void CheckFormatHandler::DoneProcessing() {
7750 // Does the number of data arguments exceed the number of
7751 // format conversions in the format string?
7752 if (HasFormatArguments()) {
7753 // Find any arguments that weren't covered.
7754 CoveredArgs.flip();
7755 signed notCoveredArg = CoveredArgs.find_first();
7756 if (notCoveredArg >= 0) {
7757 assert((unsigned)notCoveredArg < NumDataArgs);
7758 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7759 } else {
7760 UncoveredArg.setAllCovered();
7761 }
7762 }
7763}
7764
7765void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7766 const Expr *ArgExpr) {
7767 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7768 "Invalid state");
7769
7770 if (!ArgExpr)
7771 return;
7772
7773 SourceLocation Loc = ArgExpr->getBeginLoc();
7774
7775 if (S.getSourceManager().isInSystemMacro(Loc))
7776 return;
7777
7778 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7779 for (auto E : DiagnosticExprs)
7780 PDiag << E->getSourceRange();
7781
7782 CheckFormatHandler::EmitFormatDiagnostic(
7783 S, IsFunctionCall, DiagnosticExprs[0],
7784 PDiag, Loc, /*IsStringLocation*/false,
7785 DiagnosticExprs[0]->getSourceRange());
7786}
7787
7788bool
7789CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7790 SourceLocation Loc,
7791 const char *startSpec,
7792 unsigned specifierLen,
7793 const char *csStart,
7794 unsigned csLen) {
7795 bool keepGoing = true;
7796 if (argIndex < NumDataArgs) {
7797 // Consider the argument coverered, even though the specifier doesn't
7798 // make sense.
7799 CoveredArgs.set(argIndex);
7800 }
7801 else {
7802 // If argIndex exceeds the number of data arguments we
7803 // don't issue a warning because that is just a cascade of warnings (and
7804 // they may have intended '%%' anyway). We don't want to continue processing
7805 // the format string after this point, however, as we will like just get
7806 // gibberish when trying to match arguments.
7807 keepGoing = false;
7808 }
7809
7810 StringRef Specifier(csStart, csLen);
7811
7812 // If the specifier in non-printable, it could be the first byte of a UTF-8
7813 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7814 // hex value.
7815 std::string CodePointStr;
7816 if (!llvm::sys::locale::isPrint(*csStart)) {
7817 llvm::UTF32 CodePoint;
7818 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7819 const llvm::UTF8 *E =
7820 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7821 llvm::ConversionResult Result =
7822 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7823
7824 if (Result != llvm::conversionOK) {
7825 unsigned char FirstChar = *csStart;
7826 CodePoint = (llvm::UTF32)FirstChar;
7827 }
7828
7829 llvm::raw_string_ostream OS(CodePointStr);
7830 if (CodePoint < 256)
7831 OS << "\\x" << llvm::format("%02x", CodePoint);
7832 else if (CodePoint <= 0xFFFF)
7833 OS << "\\u" << llvm::format("%04x", CodePoint);
7834 else
7835 OS << "\\U" << llvm::format("%08x", CodePoint);
7836 Specifier = CodePointStr;
7837 }
7838
7839 EmitFormatDiagnostic(
7840 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7841 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7842
7843 return keepGoing;
7844}
7845
7846void
7847CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7848 const char *startSpec,
7849 unsigned specifierLen) {
7850 EmitFormatDiagnostic(
7851 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7852 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7853}
7854
7855bool
7856CheckFormatHandler::CheckNumArgs(
7859 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7860
7861 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7863 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7864 << (argIndex+1) << NumDataArgs)
7865 : S.PDiag(diag::warn_printf_insufficient_data_args);
7866 EmitFormatDiagnostic(
7867 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7868 getSpecifierRange(startSpecifier, specifierLen));
7869
7870 // Since more arguments than conversion tokens are given, by extension
7871 // all arguments are covered, so mark this as so.
7872 UncoveredArg.setAllCovered();
7873 return false;
7874 }
7875 return true;
7876}
7877
7878template<typename Range>
7879void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7880 SourceLocation Loc,
7881 bool IsStringLocation,
7882 Range StringRange,
7883 ArrayRef<FixItHint> FixIt) {
7884 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7885 Loc, IsStringLocation, StringRange, FixIt);
7886}
7887
7888/// If the format string is not within the function call, emit a note
7889/// so that the function call and string are in diagnostic messages.
7890///
7891/// \param InFunctionCall if true, the format string is within the function
7892/// call and only one diagnostic message will be produced. Otherwise, an
7893/// extra note will be emitted pointing to location of the format string.
7894///
7895/// \param ArgumentExpr the expression that is passed as the format string
7896/// argument in the function call. Used for getting locations when two
7897/// diagnostics are emitted.
7898///
7899/// \param PDiag the callee should already have provided any strings for the
7900/// diagnostic message. This function only adds locations and fixits
7901/// to diagnostics.
7902///
7903/// \param Loc primary location for diagnostic. If two diagnostics are
7904/// required, one will be at Loc and a new SourceLocation will be created for
7905/// the other one.
7906///
7907/// \param IsStringLocation if true, Loc points to the format string should be
7908/// used for the note. Otherwise, Loc points to the argument list and will
7909/// be used with PDiag.
7910///
7911/// \param StringRange some or all of the string to highlight. This is
7912/// templated so it can accept either a CharSourceRange or a SourceRange.
7913///
7914/// \param FixIt optional fix it hint for the format string.
7915template <typename Range>
7916void CheckFormatHandler::EmitFormatDiagnostic(
7917 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7918 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7919 Range StringRange, ArrayRef<FixItHint> FixIt) {
7920 if (InFunctionCall) {
7921 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7922 D << StringRange;
7923 D << FixIt;
7924 } else {
7925 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7926 << ArgumentExpr->getSourceRange();
7927
7929 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7930 diag::note_format_string_defined);
7931
7932 Note << StringRange;
7933 Note << FixIt;
7934 }
7935}
7936
7937//===--- CHECK: Printf format string checking -----------------------------===//
7938
7939namespace {
7940
7941class CheckPrintfHandler : public CheckFormatHandler {
7942public:
7943 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7944 const Expr *origFormatExpr, const FormatStringType type,
7945 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7946 const char *beg, Sema::FormatArgumentPassingKind APK,
7947 ArrayRef<const Expr *> Args, unsigned formatIdx,
7948 bool inFunctionCall, VariadicCallType CallType,
7949 llvm::SmallBitVector &CheckedVarArgs,
7950 UncoveredArgHandler &UncoveredArg)
7951 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7952 numDataArgs, beg, APK, Args, formatIdx,
7953 inFunctionCall, CallType, CheckedVarArgs,
7954 UncoveredArg) {}
7955
7956 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7957
7958 /// Returns true if '%@' specifiers are allowed in the format string.
7959 bool allowsObjCArg() const {
7960 return FSType == FormatStringType::NSString ||
7961 FSType == FormatStringType::OSLog ||
7962 FSType == FormatStringType::OSTrace;
7963 }
7964
7965 bool HandleInvalidPrintfConversionSpecifier(
7966 const analyze_printf::PrintfSpecifier &FS,
7967 const char *startSpecifier,
7968 unsigned specifierLen) override;
7969
7970 void handleInvalidMaskType(StringRef MaskType) override;
7971
7972 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7973 const char *startSpecifier, unsigned specifierLen,
7974 const TargetInfo &Target) override;
7975 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7976 const char *StartSpecifier,
7977 unsigned SpecifierLen,
7978 const Expr *E);
7979
7980 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7981 const char *startSpecifier, unsigned specifierLen);
7982 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7983 const analyze_printf::OptionalAmount &Amt,
7984 unsigned type,
7985 const char *startSpecifier, unsigned specifierLen);
7986 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7987 const analyze_printf::OptionalFlag &flag,
7988 const char *startSpecifier, unsigned specifierLen);
7989 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7990 const analyze_printf::OptionalFlag &ignoredFlag,
7991 const analyze_printf::OptionalFlag &flag,
7992 const char *startSpecifier, unsigned specifierLen);
7993 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7994 const Expr *E);
7995
7996 void HandleEmptyObjCModifierFlag(const char *startFlag,
7997 unsigned flagLen) override;
7998
7999 void HandleInvalidObjCModifierFlag(const char *startFlag,
8000 unsigned flagLen) override;
8001
8002 void
8003 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8004 const char *flagsEnd,
8005 const char *conversionPosition) override;
8006};
8007
8008/// Keeps around the information needed to verify that two specifiers are
8009/// compatible.
8010class EquatableFormatArgument {
8011public:
8012 enum SpecifierSensitivity : unsigned {
8013 SS_None,
8014 SS_Private,
8015 SS_Public,
8016 SS_Sensitive
8017 };
8018
8019 enum FormatArgumentRole : unsigned {
8020 FAR_Data,
8021 FAR_FieldWidth,
8022 FAR_Precision,
8023 FAR_Auxiliary, // FreeBSD kernel %b and %D
8024 };
8025
8026private:
8027 analyze_format_string::ArgType ArgType;
8029 StringRef SpecifierLetter;
8030 CharSourceRange Range;
8031 SourceLocation ElementLoc;
8032 FormatArgumentRole Role : 2;
8033 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8034 unsigned Position : 14;
8035 unsigned ModifierFor : 14; // not set for FAR_Data
8036
8037 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8038 bool InFunctionCall) const;
8039
8040public:
8041 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8043 StringRef SpecifierLetter,
8044 analyze_format_string::ArgType ArgType,
8045 FormatArgumentRole Role,
8046 SpecifierSensitivity Sensitivity, unsigned Position,
8047 unsigned ModifierFor)
8048 : ArgType(ArgType), LengthMod(LengthMod),
8049 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8050 Role(Role), Sensitivity(Sensitivity), Position(Position),
8051 ModifierFor(ModifierFor) {}
8052
8053 unsigned getPosition() const { return Position; }
8054 SourceLocation getSourceLocation() const { return ElementLoc; }
8055 CharSourceRange getSourceRange() const { return Range; }
8056 analyze_format_string::LengthModifier getLengthModifier() const {
8057 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8058 }
8059 void setModifierFor(unsigned V) { ModifierFor = V; }
8060
8061 std::string buildFormatSpecifier() const {
8062 std::string result;
8063 llvm::raw_string_ostream(result)
8064 << getLengthModifier().toString() << SpecifierLetter;
8065 return result;
8066 }
8067
8068 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8069 const Expr *FmtExpr, bool InFunctionCall) const;
8070};
8071
8072/// Turns format strings into lists of EquatableSpecifier objects.
8073class DecomposePrintfHandler : public CheckPrintfHandler {
8074 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8075 bool HadError;
8076
8077 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8078 const Expr *origFormatExpr,
8079 const FormatStringType type, unsigned firstDataArg,
8080 unsigned numDataArgs, bool isObjC, const char *beg,
8082 ArrayRef<const Expr *> Args, unsigned formatIdx,
8083 bool inFunctionCall, VariadicCallType CallType,
8084 llvm::SmallBitVector &CheckedVarArgs,
8085 UncoveredArgHandler &UncoveredArg,
8086 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8087 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8088 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8089 inFunctionCall, CallType, CheckedVarArgs,
8090 UncoveredArg),
8091 Specs(Specs), HadError(false) {}
8092
8093public:
8094 static bool
8095 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8096 FormatStringType type, bool IsObjC, bool InFunctionCall,
8097 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8098
8099 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8100 const char *startSpecifier,
8101 unsigned specifierLen,
8102 const TargetInfo &Target) override;
8103};
8104
8105} // namespace
8106
8107bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8108 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8109 unsigned specifierLen) {
8112
8113 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8114 getLocationOfByte(CS.getStart()),
8115 startSpecifier, specifierLen,
8116 CS.getStart(), CS.getLength());
8117}
8118
8119void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8120 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8121}
8122
8123// Error out if struct or complex type argments are passed to os_log.
8125 QualType T) {
8126 if (FSType != FormatStringType::OSLog)
8127 return false;
8128 return T->isRecordType() || T->isComplexType();
8129}
8130
8131bool CheckPrintfHandler::HandleAmount(
8132 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8133 const char *startSpecifier, unsigned specifierLen) {
8134 if (Amt.hasDataArgument()) {
8135 if (HasFormatArguments()) {
8136 unsigned argIndex = Amt.getArgIndex();
8137 if (argIndex >= NumDataArgs) {
8138 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8139 << k,
8140 getLocationOfByte(Amt.getStart()),
8141 /*IsStringLocation*/ true,
8142 getSpecifierRange(startSpecifier, specifierLen));
8143 // Don't do any more checking. We will just emit
8144 // spurious errors.
8145 return false;
8146 }
8147
8148 // Type check the data argument. It should be an 'int'.
8149 // Although not in conformance with C99, we also allow the argument to be
8150 // an 'unsigned int' as that is a reasonably safe case. GCC also
8151 // doesn't emit a warning for that case.
8152 CoveredArgs.set(argIndex);
8153 const Expr *Arg = getDataArg(argIndex);
8154 if (!Arg)
8155 return false;
8156
8157 QualType T = Arg->getType();
8158
8159 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8160 assert(AT.isValid());
8161
8162 if (!AT.matchesType(S.Context, T)) {
8163 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8164 ? diag::err_printf_asterisk_wrong_type
8165 : diag::warn_printf_asterisk_wrong_type;
8166 EmitFormatDiagnostic(S.PDiag(DiagID)
8168 << T << Arg->getSourceRange(),
8169 getLocationOfByte(Amt.getStart()),
8170 /*IsStringLocation*/ true,
8171 getSpecifierRange(startSpecifier, specifierLen));
8172 // Don't do any more checking. We will just emit
8173 // spurious errors.
8174 return false;
8175 }
8176 }
8177 }
8178 return true;
8179}
8180
8181void CheckPrintfHandler::HandleInvalidAmount(
8184 unsigned type,
8185 const char *startSpecifier,
8186 unsigned specifierLen) {
8189
8190 FixItHint fixit =
8192 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8193 Amt.getConstantLength()))
8194 : FixItHint();
8195
8196 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8197 << type << CS.toString(),
8198 getLocationOfByte(Amt.getStart()),
8199 /*IsStringLocation*/true,
8200 getSpecifierRange(startSpecifier, specifierLen),
8201 fixit);
8202}
8203
8204void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8205 const analyze_printf::OptionalFlag &flag,
8206 const char *startSpecifier,
8207 unsigned specifierLen) {
8208 // Warn about pointless flag with a fixit removal.
8211 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8212 << flag.toString() << CS.toString(),
8213 getLocationOfByte(flag.getPosition()),
8214 /*IsStringLocation*/true,
8215 getSpecifierRange(startSpecifier, specifierLen),
8217 getSpecifierRange(flag.getPosition(), 1)));
8218}
8219
8220void CheckPrintfHandler::HandleIgnoredFlag(
8222 const analyze_printf::OptionalFlag &ignoredFlag,
8223 const analyze_printf::OptionalFlag &flag,
8224 const char *startSpecifier,
8225 unsigned specifierLen) {
8226 // Warn about ignored flag with a fixit removal.
8227 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8228 << ignoredFlag.toString() << flag.toString(),
8229 getLocationOfByte(ignoredFlag.getPosition()),
8230 /*IsStringLocation*/true,
8231 getSpecifierRange(startSpecifier, specifierLen),
8233 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8234}
8235
8236void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8237 unsigned flagLen) {
8238 // Warn about an empty flag.
8239 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8240 getLocationOfByte(startFlag),
8241 /*IsStringLocation*/true,
8242 getSpecifierRange(startFlag, flagLen));
8243}
8244
8245void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8246 unsigned flagLen) {
8247 // Warn about an invalid flag.
8248 auto Range = getSpecifierRange(startFlag, flagLen);
8249 StringRef flag(startFlag, flagLen);
8250 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8251 getLocationOfByte(startFlag),
8252 /*IsStringLocation*/true,
8253 Range, FixItHint::CreateRemoval(Range));
8254}
8255
8256void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8257 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8258 // Warn about using '[...]' without a '@' conversion.
8259 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8260 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8261 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8262 getLocationOfByte(conversionPosition),
8263 /*IsStringLocation*/ true, Range,
8265}
8266
8267void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8268 const Expr *FmtExpr,
8269 bool InFunctionCall) const {
8270 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8271 ElementLoc, true, Range);
8272}
8273
8274bool EquatableFormatArgument::VerifyCompatible(
8275 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8276 bool InFunctionCall) const {
8278 if (Role != Other.Role) {
8279 // diagnose and stop
8280 EmitDiagnostic(
8281 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8282 FmtExpr, InFunctionCall);
8283 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8284 return false;
8285 }
8286
8287 if (Role != FAR_Data) {
8288 if (ModifierFor != Other.ModifierFor) {
8289 // diagnose and stop
8290 EmitDiagnostic(S,
8291 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8292 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8293 FmtExpr, InFunctionCall);
8294 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8295 return false;
8296 }
8297 return true;
8298 }
8299
8300 bool HadError = false;
8301 if (Sensitivity != Other.Sensitivity) {
8302 // diagnose and continue
8303 EmitDiagnostic(S,
8304 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8305 << Sensitivity << Other.Sensitivity,
8306 FmtExpr, InFunctionCall);
8307 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8308 << 0 << Other.Range;
8309 }
8310
8311 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8312 case MK::Match:
8313 break;
8314
8315 case MK::MatchPromotion:
8316 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8317 // MatchPromotion is treated as a failure by format_matches.
8318 case MK::NoMatch:
8319 case MK::NoMatchTypeConfusion:
8320 case MK::NoMatchPromotionTypeConfusion:
8321 EmitDiagnostic(S,
8322 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8323 << buildFormatSpecifier()
8324 << Other.buildFormatSpecifier(),
8325 FmtExpr, InFunctionCall);
8326 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8327 << 0 << Other.Range;
8328 break;
8329
8330 case MK::NoMatchPedantic:
8331 EmitDiagnostic(S,
8332 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8333 << buildFormatSpecifier()
8334 << Other.buildFormatSpecifier(),
8335 FmtExpr, InFunctionCall);
8336 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8337 << 0 << Other.Range;
8338 break;
8339
8340 case MK::NoMatchSignedness:
8341 EmitDiagnostic(S,
8342 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8343 << buildFormatSpecifier()
8344 << Other.buildFormatSpecifier(),
8345 FmtExpr, InFunctionCall);
8346 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8347 << 0 << Other.Range;
8348 break;
8349 }
8350 return !HadError;
8351}
8352
8353bool DecomposePrintfHandler::GetSpecifiers(
8354 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8355 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8357 StringRef Data = FSL->getString();
8358 const char *Str = Data.data();
8359 llvm::SmallBitVector BV;
8360 UncoveredArgHandler UA;
8361 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8362 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8363 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8364 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8365 UA, Args);
8366
8368 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8370 H.DoneProcessing();
8371 if (H.HadError)
8372 return false;
8373
8374 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8375 const EquatableFormatArgument &B) {
8376 return A.getPosition() < B.getPosition();
8377 });
8378 return true;
8379}
8380
8381bool DecomposePrintfHandler::HandlePrintfSpecifier(
8382 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8383 unsigned specifierLen, const TargetInfo &Target) {
8384 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8385 specifierLen, Target)) {
8386 HadError = true;
8387 return false;
8388 }
8389
8390 // Do not add any specifiers to the list for %%. This is possibly incorrect
8391 // if using a precision/width with a data argument, but that combination is
8392 // meaningless and we wouldn't know which format to attach the
8393 // precision/width to.
8394 const auto &CS = FS.getConversionSpecifier();
8396 return true;
8397
8398 // have to patch these to have the right ModifierFor if they are used
8399 const unsigned Unset = ~0;
8400 unsigned FieldWidthIndex = Unset;
8401 unsigned PrecisionIndex = Unset;
8402
8403 // field width?
8404 const auto &FieldWidth = FS.getFieldWidth();
8405 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8406 FieldWidthIndex = Specs.size();
8407 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8408 getLocationOfByte(FieldWidth.getStart()),
8410 FieldWidth.getArgType(S.Context),
8411 EquatableFormatArgument::FAR_FieldWidth,
8412 EquatableFormatArgument::SS_None,
8413 FieldWidth.usesPositionalArg()
8414 ? FieldWidth.getPositionalArgIndex() - 1
8415 : FieldWidthIndex,
8416 0);
8417 }
8418 // precision?
8419 const auto &Precision = FS.getPrecision();
8420 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8421 PrecisionIndex = Specs.size();
8422 Specs.emplace_back(
8423 getSpecifierRange(startSpecifier, specifierLen),
8424 getLocationOfByte(Precision.getStart()),
8426 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8427 EquatableFormatArgument::SS_None,
8428 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8429 : PrecisionIndex,
8430 0);
8431 }
8432
8433 // this specifier
8434 unsigned SpecIndex =
8435 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8436 if (FieldWidthIndex != Unset)
8437 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8438 if (PrecisionIndex != Unset)
8439 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8440
8441 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8442 if (FS.isPrivate())
8443 Sensitivity = EquatableFormatArgument::SS_Private;
8444 else if (FS.isPublic())
8445 Sensitivity = EquatableFormatArgument::SS_Public;
8446 else if (FS.isSensitive())
8447 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8448 else
8449 Sensitivity = EquatableFormatArgument::SS_None;
8450
8451 Specs.emplace_back(
8452 getSpecifierRange(startSpecifier, specifierLen),
8453 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8454 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8455 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8456
8457 // auxiliary argument?
8460 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8461 getLocationOfByte(CS.getStart()),
8463 CS.getCharacters(),
8465 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8466 SpecIndex + 1, SpecIndex);
8467 }
8468 return true;
8469}
8470
8471// Determines if the specified is a C++ class or struct containing
8472// a member with the specified name and kind (e.g. a CXXMethodDecl named
8473// "c_str()").
8474template<typename MemberKind>
8476CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8477 auto *RD = Ty->getAsCXXRecordDecl();
8479
8480 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8481 return Results;
8482
8483 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8486
8487 // We just need to include all members of the right kind turned up by the
8488 // filter, at this point.
8489 if (S.LookupQualifiedName(R, RD))
8490 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8491 NamedDecl *decl = (*I)->getUnderlyingDecl();
8492 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8493 Results.insert(FK);
8494 }
8495 return Results;
8496}
8497
8498/// Check if we could call '.c_str()' on an object.
8499///
8500/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8501/// allow the call, or if it would be ambiguous).
8503 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8504
8505 MethodSet Results =
8506 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8507 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8508 MI != ME; ++MI)
8509 if ((*MI)->getMinRequiredArguments() == 0)
8510 return true;
8511 return false;
8512}
8513
8514// Check if a (w)string was passed when a (w)char* was needed, and offer a
8515// better diagnostic if so. AT is assumed to be valid.
8516// Returns true when a c_str() conversion method is found.
8517bool CheckPrintfHandler::checkForCStrMembers(
8518 const analyze_printf::ArgType &AT, const Expr *E) {
8519 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8520
8521 MethodSet Results =
8523
8524 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8525 MI != ME; ++MI) {
8526 const CXXMethodDecl *Method = *MI;
8527 if (Method->getMinRequiredArguments() == 0 &&
8528 AT.matchesType(S.Context, Method->getReturnType())) {
8529 // FIXME: Suggest parens if the expression needs them.
8531 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8532 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8533 return true;
8534 }
8535 }
8536
8537 return false;
8538}
8539
8540bool CheckPrintfHandler::HandlePrintfSpecifier(
8541 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8542 unsigned specifierLen, const TargetInfo &Target) {
8543 using namespace analyze_format_string;
8544 using namespace analyze_printf;
8545
8546 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8547
8548 if (FS.consumesDataArgument()) {
8549 if (atFirstArg) {
8550 atFirstArg = false;
8551 usesPositionalArgs = FS.usesPositionalArg();
8552 }
8553 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8554 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8555 startSpecifier, specifierLen);
8556 return false;
8557 }
8558 }
8559
8560 // First check if the field width, precision, and conversion specifier
8561 // have matching data arguments.
8562 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8563 startSpecifier, specifierLen)) {
8564 return false;
8565 }
8566
8567 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8568 startSpecifier, specifierLen)) {
8569 return false;
8570 }
8571
8572 if (!CS.consumesDataArgument()) {
8573 // FIXME: Technically specifying a precision or field width here
8574 // makes no sense. Worth issuing a warning at some point.
8575 return true;
8576 }
8577
8578 // Consume the argument.
8579 unsigned argIndex = FS.getArgIndex();
8580 if (argIndex < NumDataArgs) {
8581 // The check to see if the argIndex is valid will come later.
8582 // We set the bit here because we may exit early from this
8583 // function if we encounter some other error.
8584 CoveredArgs.set(argIndex);
8585 }
8586
8587 // FreeBSD kernel extensions.
8588 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8589 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8590 // We need at least two arguments.
8591 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8592 return false;
8593
8594 if (HasFormatArguments()) {
8595 // Claim the second argument.
8596 CoveredArgs.set(argIndex + 1);
8597
8598 // Type check the first argument (int for %b, pointer for %D)
8599 const Expr *Ex = getDataArg(argIndex);
8600 const analyze_printf::ArgType &AT =
8601 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8602 ? ArgType(S.Context.IntTy)
8603 : ArgType::CPointerTy;
8604 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8605 EmitFormatDiagnostic(
8606 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8607 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8608 << false << Ex->getSourceRange(),
8609 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8610 getSpecifierRange(startSpecifier, specifierLen));
8611
8612 // Type check the second argument (char * for both %b and %D)
8613 Ex = getDataArg(argIndex + 1);
8615 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8616 EmitFormatDiagnostic(
8617 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8618 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8619 << false << Ex->getSourceRange(),
8620 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8621 getSpecifierRange(startSpecifier, specifierLen));
8622 }
8623 return true;
8624 }
8625
8626 // Check for using an Objective-C specific conversion specifier
8627 // in a non-ObjC literal.
8628 if (!allowsObjCArg() && CS.isObjCArg()) {
8629 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8630 specifierLen);
8631 }
8632
8633 // %P can only be used with os_log.
8634 if (FSType != FormatStringType::OSLog &&
8635 CS.getKind() == ConversionSpecifier::PArg) {
8636 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8637 specifierLen);
8638 }
8639
8640 // %n is not allowed with os_log.
8641 if (FSType == FormatStringType::OSLog &&
8642 CS.getKind() == ConversionSpecifier::nArg) {
8643 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8644 getLocationOfByte(CS.getStart()),
8645 /*IsStringLocation*/ false,
8646 getSpecifierRange(startSpecifier, specifierLen));
8647
8648 return true;
8649 }
8650
8651 // Only scalars are allowed for os_trace.
8652 if (FSType == FormatStringType::OSTrace &&
8653 (CS.getKind() == ConversionSpecifier::PArg ||
8654 CS.getKind() == ConversionSpecifier::sArg ||
8655 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8656 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8657 specifierLen);
8658 }
8659
8660 // Check for use of public/private annotation outside of os_log().
8661 if (FSType != FormatStringType::OSLog) {
8662 if (FS.isPublic().isSet()) {
8663 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8664 << "public",
8665 getLocationOfByte(FS.isPublic().getPosition()),
8666 /*IsStringLocation*/ false,
8667 getSpecifierRange(startSpecifier, specifierLen));
8668 }
8669 if (FS.isPrivate().isSet()) {
8670 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8671 << "private",
8672 getLocationOfByte(FS.isPrivate().getPosition()),
8673 /*IsStringLocation*/ false,
8674 getSpecifierRange(startSpecifier, specifierLen));
8675 }
8676 }
8677
8678 const llvm::Triple &Triple = Target.getTriple();
8679 if (CS.getKind() == ConversionSpecifier::nArg &&
8680 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8681 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8682 getLocationOfByte(CS.getStart()),
8683 /*IsStringLocation*/ false,
8684 getSpecifierRange(startSpecifier, specifierLen));
8685 }
8686
8687 // Check for invalid use of field width
8688 if (!FS.hasValidFieldWidth()) {
8689 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8690 startSpecifier, specifierLen);
8691 }
8692
8693 // Check for invalid use of precision
8694 if (!FS.hasValidPrecision()) {
8695 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8696 startSpecifier, specifierLen);
8697 }
8698
8699 // Precision is mandatory for %P specifier.
8700 if (CS.getKind() == ConversionSpecifier::PArg &&
8702 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8703 getLocationOfByte(startSpecifier),
8704 /*IsStringLocation*/ false,
8705 getSpecifierRange(startSpecifier, specifierLen));
8706 }
8707
8708 // Check each flag does not conflict with any other component.
8710 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8711 if (!FS.hasValidLeadingZeros())
8712 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8713 if (!FS.hasValidPlusPrefix())
8714 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8715 if (!FS.hasValidSpacePrefix())
8716 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8717 if (!FS.hasValidAlternativeForm())
8718 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8719 if (!FS.hasValidLeftJustified())
8720 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8721
8722 // Check that flags are not ignored by another flag
8723 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8724 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8725 startSpecifier, specifierLen);
8726 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8727 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8728 startSpecifier, specifierLen);
8729
8730 // Check the length modifier is valid with the given conversion specifier.
8732 S.getLangOpts()))
8733 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8734 diag::warn_format_nonsensical_length);
8735 else if (!FS.hasStandardLengthModifier())
8736 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8738 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8739 diag::warn_format_non_standard_conversion_spec);
8740
8742 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8743
8744 // The remaining checks depend on the data arguments.
8745 if (!HasFormatArguments())
8746 return true;
8747
8748 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8749 return false;
8750
8751 const Expr *Arg = getDataArg(argIndex);
8752 if (!Arg)
8753 return true;
8754
8755 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8756}
8757
8758static bool requiresParensToAddCast(const Expr *E) {
8759 // FIXME: We should have a general way to reason about operator
8760 // precedence and whether parens are actually needed here.
8761 // Take care of a few common cases where they aren't.
8762 const Expr *Inside = E->IgnoreImpCasts();
8763 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8764 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8765
8766 switch (Inside->getStmtClass()) {
8767 case Stmt::ArraySubscriptExprClass:
8768 case Stmt::CallExprClass:
8769 case Stmt::CharacterLiteralClass:
8770 case Stmt::CXXBoolLiteralExprClass:
8771 case Stmt::DeclRefExprClass:
8772 case Stmt::FloatingLiteralClass:
8773 case Stmt::IntegerLiteralClass:
8774 case Stmt::MemberExprClass:
8775 case Stmt::ObjCArrayLiteralClass:
8776 case Stmt::ObjCBoolLiteralExprClass:
8777 case Stmt::ObjCBoxedExprClass:
8778 case Stmt::ObjCDictionaryLiteralClass:
8779 case Stmt::ObjCEncodeExprClass:
8780 case Stmt::ObjCIvarRefExprClass:
8781 case Stmt::ObjCMessageExprClass:
8782 case Stmt::ObjCPropertyRefExprClass:
8783 case Stmt::ObjCStringLiteralClass:
8784 case Stmt::ObjCSubscriptRefExprClass:
8785 case Stmt::ParenExprClass:
8786 case Stmt::StringLiteralClass:
8787 case Stmt::UnaryOperatorClass:
8788 return false;
8789 default:
8790 return true;
8791 }
8792}
8793
8794static std::pair<QualType, StringRef>
8796 QualType IntendedTy,
8797 const Expr *E) {
8798 // Use a 'while' to peel off layers of typedefs.
8799 QualType TyTy = IntendedTy;
8800 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8801 StringRef Name = UserTy->getDecl()->getName();
8802 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8803 .Case("CFIndex", Context.getNSIntegerType())
8804 .Case("NSInteger", Context.getNSIntegerType())
8805 .Case("NSUInteger", Context.getNSUIntegerType())
8806 .Case("SInt32", Context.IntTy)
8807 .Case("UInt32", Context.UnsignedIntTy)
8808 .Default(QualType());
8809
8810 if (!CastTy.isNull())
8811 return std::make_pair(CastTy, Name);
8812
8813 TyTy = UserTy->desugar();
8814 }
8815
8816 // Strip parens if necessary.
8817 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8818 return shouldNotPrintDirectly(Context,
8819 PE->getSubExpr()->getType(),
8820 PE->getSubExpr());
8821
8822 // If this is a conditional expression, then its result type is constructed
8823 // via usual arithmetic conversions and thus there might be no necessary
8824 // typedef sugar there. Recurse to operands to check for NSInteger &
8825 // Co. usage condition.
8826 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8827 QualType TrueTy, FalseTy;
8828 StringRef TrueName, FalseName;
8829
8830 std::tie(TrueTy, TrueName) =
8831 shouldNotPrintDirectly(Context,
8832 CO->getTrueExpr()->getType(),
8833 CO->getTrueExpr());
8834 std::tie(FalseTy, FalseName) =
8835 shouldNotPrintDirectly(Context,
8836 CO->getFalseExpr()->getType(),
8837 CO->getFalseExpr());
8838
8839 if (TrueTy == FalseTy)
8840 return std::make_pair(TrueTy, TrueName);
8841 else if (TrueTy.isNull())
8842 return std::make_pair(FalseTy, FalseName);
8843 else if (FalseTy.isNull())
8844 return std::make_pair(TrueTy, TrueName);
8845 }
8846
8847 return std::make_pair(QualType(), StringRef());
8848}
8849
8850/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8851/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8852/// type do not count.
8853static bool
8855 QualType From = ICE->getSubExpr()->getType();
8856 QualType To = ICE->getType();
8857 // It's an integer promotion if the destination type is the promoted
8858 // source type.
8859 if (ICE->getCastKind() == CK_IntegralCast &&
8861 S.Context.getPromotedIntegerType(From) == To)
8862 return true;
8863 // Look through vector types, since we do default argument promotion for
8864 // those in OpenCL.
8865 if (const auto *VecTy = From->getAs<ExtVectorType>())
8866 From = VecTy->getElementType();
8867 if (const auto *VecTy = To->getAs<ExtVectorType>())
8868 To = VecTy->getElementType();
8869 // It's a floating promotion if the source type is a lower rank.
8870 return ICE->getCastKind() == CK_FloatingCast &&
8871 S.Context.getFloatingTypeOrder(From, To) < 0;
8872}
8873
8876 DiagnosticsEngine &Diags, SourceLocation Loc) {
8878 if (Diags.isIgnored(
8879 diag::warn_format_conversion_argument_type_mismatch_signedness,
8880 Loc) ||
8881 Diags.isIgnored(
8882 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8883 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8885 }
8886 }
8887 return Match;
8888}
8889
8890bool
8891CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8892 const char *StartSpecifier,
8893 unsigned SpecifierLen,
8894 const Expr *E) {
8895 using namespace analyze_format_string;
8896 using namespace analyze_printf;
8897
8898 // Now type check the data expression that matches the
8899 // format specifier.
8900 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8901 if (!AT.isValid())
8902 return true;
8903
8904 QualType ExprTy = E->getType();
8905 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8906 ExprTy = TET->getUnderlyingExpr()->getType();
8907 }
8908
8909 // When using the format attribute in C++, you can receive a function or an
8910 // array that will necessarily decay to a pointer when passed to the final
8911 // format consumer. Apply decay before type comparison.
8912 if (ExprTy->canDecayToPointerType())
8913 ExprTy = S.Context.getDecayedType(ExprTy);
8914
8915 // Diagnose attempts to print a boolean value as a character. Unlike other
8916 // -Wformat diagnostics, this is fine from a type perspective, but it still
8917 // doesn't make sense.
8920 const CharSourceRange &CSR =
8921 getSpecifierRange(StartSpecifier, SpecifierLen);
8922 SmallString<4> FSString;
8923 llvm::raw_svector_ostream os(FSString);
8924 FS.toString(os);
8925 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8926 << FSString,
8927 E->getExprLoc(), false, CSR);
8928 return true;
8929 }
8930
8931 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8932 // dumping raw class data (like is-a pointer), not actual data.
8934 ExprTy->isObjCObjectPointerType()) {
8935 const CharSourceRange &CSR =
8936 getSpecifierRange(StartSpecifier, SpecifierLen);
8937 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8938 E->getExprLoc(), false, CSR);
8939 return true;
8940 }
8941
8942 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8944 ArgType::MatchKind OrigMatch = Match;
8945
8947 if (Match == ArgType::Match)
8948 return true;
8949
8950 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8951 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8952
8953 // Look through argument promotions for our error message's reported type.
8954 // This includes the integral and floating promotions, but excludes array
8955 // and function pointer decay (seeing that an argument intended to be a
8956 // string has type 'char [6]' is probably more confusing than 'char *') and
8957 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8958 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8959 if (isArithmeticArgumentPromotion(S, ICE)) {
8960 E = ICE->getSubExpr();
8961 ExprTy = E->getType();
8962
8963 // Check if we didn't match because of an implicit cast from a 'char'
8964 // or 'short' to an 'int'. This is done because printf is a varargs
8965 // function.
8966 if (ICE->getType() == S.Context.IntTy ||
8967 ICE->getType() == S.Context.UnsignedIntTy) {
8968 // All further checking is done on the subexpression
8969 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8970 if (OrigMatch == ArgType::NoMatchSignedness &&
8971 ImplicitMatch != ArgType::NoMatchSignedness)
8972 // If the original match was a signedness match this match on the
8973 // implicit cast type also need to be signedness match otherwise we
8974 // might introduce new unexpected warnings from -Wformat-signedness.
8975 return true;
8976 ImplicitMatch = handleFormatSignedness(
8977 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8978 if (ImplicitMatch == ArgType::Match)
8979 return true;
8980 }
8981 }
8982 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8983 // Special case for 'a', which has type 'int' in C.
8984 // Note, however, that we do /not/ want to treat multibyte constants like
8985 // 'MooV' as characters! This form is deprecated but still exists. In
8986 // addition, don't treat expressions as of type 'char' if one byte length
8987 // modifier is provided.
8988 if (ExprTy == S.Context.IntTy &&
8990 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8991 ExprTy = S.Context.CharTy;
8992 // To improve check results, we consider a character literal in C
8993 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8994 // more likely a type confusion situation, so we will suggest to
8995 // use '%hhd' instead by discarding the MatchPromotion.
8996 if (Match == ArgType::MatchPromotion)
8998 }
8999 }
9000 if (Match == ArgType::MatchPromotion) {
9001 // WG14 N2562 only clarified promotions in *printf
9002 // For NSLog in ObjC, just preserve -Wformat behavior
9003 if (!S.getLangOpts().ObjC &&
9004 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9005 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9006 return true;
9008 }
9009 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9010 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9011 Match = ImplicitMatch;
9012 assert(Match != ArgType::MatchPromotion);
9013
9014 // Look through unscoped enums to their underlying type.
9015 bool IsEnum = false;
9016 bool IsScopedEnum = false;
9017 QualType IntendedTy = ExprTy;
9018 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9019 IntendedTy = ED->getIntegerType();
9020 if (!ED->isScoped()) {
9021 ExprTy = IntendedTy;
9022 // This controls whether we're talking about the underlying type or not,
9023 // which we only want to do when it's an unscoped enum.
9024 IsEnum = true;
9025 } else {
9026 IsScopedEnum = true;
9027 }
9028 }
9029
9030 // %C in an Objective-C context prints a unichar, not a wchar_t.
9031 // If the argument is an integer of some kind, believe the %C and suggest
9032 // a cast instead of changing the conversion specifier.
9033 if (isObjCContext() &&
9036 !ExprTy->isCharType()) {
9037 // 'unichar' is defined as a typedef of unsigned short, but we should
9038 // prefer using the typedef if it is visible.
9039 IntendedTy = S.Context.UnsignedShortTy;
9040
9041 // While we are here, check if the value is an IntegerLiteral that happens
9042 // to be within the valid range.
9043 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9044 const llvm::APInt &V = IL->getValue();
9045 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9046 return true;
9047 }
9048
9049 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9051 if (S.LookupName(Result, S.getCurScope())) {
9052 NamedDecl *ND = Result.getFoundDecl();
9053 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9054 if (TD->getUnderlyingType() == IntendedTy)
9055 IntendedTy =
9057 /*Qualifier=*/std::nullopt, TD);
9058 }
9059 }
9060 }
9061
9062 // Special-case some of Darwin's platform-independence types by suggesting
9063 // casts to primitive types that are known to be large enough.
9064 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9065 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9066 QualType CastTy;
9067 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9068 if (!CastTy.isNull()) {
9069 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9070 // (long in ASTContext). Only complain to pedants or when they're the
9071 // underlying type of a scoped enum (which always needs a cast).
9072 if (!IsScopedEnum &&
9073 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9074 (AT.isSizeT() || AT.isPtrdiffT()) &&
9075 AT.matchesType(S.Context, CastTy))
9077 IntendedTy = CastTy;
9078 ShouldNotPrintDirectly = true;
9079 }
9080 }
9081
9082 // We may be able to offer a FixItHint if it is a supported type.
9083 PrintfSpecifier fixedFS = FS;
9084 bool Success =
9085 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9086
9087 if (Success) {
9088 // Get the fix string from the fixed format specifier
9089 SmallString<16> buf;
9090 llvm::raw_svector_ostream os(buf);
9091 fixedFS.toString(os);
9092
9093 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9094
9095 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9096 unsigned Diag;
9097 switch (Match) {
9098 case ArgType::Match:
9101 llvm_unreachable("expected non-matching");
9103 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9104 break;
9106 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9107 break;
9109 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9110 break;
9111 case ArgType::NoMatch:
9112 Diag = diag::warn_format_conversion_argument_type_mismatch;
9113 break;
9114 }
9115
9116 // In this case, the specifier is wrong and should be changed to match
9117 // the argument.
9118 EmitFormatDiagnostic(S.PDiag(Diag)
9120 << IntendedTy << IsEnum << E->getSourceRange(),
9121 E->getBeginLoc(),
9122 /*IsStringLocation*/ false, SpecRange,
9123 FixItHint::CreateReplacement(SpecRange, os.str()));
9124 } else {
9125 // The canonical type for formatting this value is different from the
9126 // actual type of the expression. (This occurs, for example, with Darwin's
9127 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9128 // should be printed as 'long' for 64-bit compatibility.)
9129 // Rather than emitting a normal format/argument mismatch, we want to
9130 // add a cast to the recommended type (and correct the format string
9131 // if necessary). We should also do so for scoped enumerations.
9132 SmallString<16> CastBuf;
9133 llvm::raw_svector_ostream CastFix(CastBuf);
9134 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9135 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9136 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9137
9139 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9140 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9141 E->getExprLoc());
9142 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9143 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9144
9145 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9146 // If there's already a cast present, just replace it.
9147 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9148 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9149
9150 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9151 // If the expression has high enough precedence,
9152 // just write the C-style cast.
9153 Hints.push_back(
9154 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9155 } else {
9156 // Otherwise, add parens around the expression as well as the cast.
9157 CastFix << "(";
9158 Hints.push_back(
9159 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9160
9161 // We don't use getLocForEndOfToken because it returns invalid source
9162 // locations for macro expansions (by design).
9166 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9167 }
9168
9169 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9170 // The expression has a type that should not be printed directly.
9171 // We extract the name from the typedef because we don't want to show
9172 // the underlying type in the diagnostic.
9173 StringRef Name;
9174 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9175 Name = TypedefTy->getDecl()->getName();
9176 else
9177 Name = CastTyName;
9178 unsigned Diag = Match == ArgType::NoMatchPedantic
9179 ? diag::warn_format_argument_needs_cast_pedantic
9180 : diag::warn_format_argument_needs_cast;
9181 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9182 << E->getSourceRange(),
9183 E->getBeginLoc(), /*IsStringLocation=*/false,
9184 SpecRange, Hints);
9185 } else {
9186 // In this case, the expression could be printed using a different
9187 // specifier, but we've decided that the specifier is probably correct
9188 // and we should cast instead. Just use the normal warning message.
9189
9190 unsigned Diag =
9191 IsScopedEnum
9192 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9193 : diag::warn_format_conversion_argument_type_mismatch;
9194
9195 EmitFormatDiagnostic(
9196 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9197 << IsEnum << E->getSourceRange(),
9198 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9199 }
9200 }
9201 } else {
9202 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9203 SpecifierLen);
9204 // Since the warning for passing non-POD types to variadic functions
9205 // was deferred until now, we emit a warning for non-POD
9206 // arguments here.
9207 bool EmitTypeMismatch = false;
9208 switch (S.isValidVarArgType(ExprTy)) {
9209 case VarArgKind::Valid:
9211 unsigned Diag;
9212 switch (Match) {
9213 case ArgType::Match:
9216 llvm_unreachable("expected non-matching");
9218 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9219 break;
9221 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9222 break;
9224 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9225 break;
9226 case ArgType::NoMatch:
9227 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9228 ? diag::err_format_conversion_argument_type_mismatch
9229 : diag::warn_format_conversion_argument_type_mismatch;
9230 break;
9231 }
9232
9233 EmitFormatDiagnostic(
9234 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9235 << IsEnum << CSR << E->getSourceRange(),
9236 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9237 break;
9238 }
9241 if (CallType == VariadicCallType::DoesNotApply) {
9242 EmitTypeMismatch = true;
9243 } else {
9244 EmitFormatDiagnostic(
9245 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9246 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9247 << AT.getRepresentativeTypeName(S.Context) << CSR
9248 << E->getSourceRange(),
9249 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9250 checkForCStrMembers(AT, E);
9251 }
9252 break;
9253
9255 if (CallType == VariadicCallType::DoesNotApply)
9256 EmitTypeMismatch = true;
9257 else if (ExprTy->isObjCObjectType())
9258 EmitFormatDiagnostic(
9259 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9260 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9261 << AT.getRepresentativeTypeName(S.Context) << CSR
9262 << E->getSourceRange(),
9263 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9264 else
9265 // FIXME: If this is an initializer list, suggest removing the braces
9266 // or inserting a cast to the target type.
9267 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9268 << isa<InitListExpr>(E) << ExprTy << CallType
9270 break;
9271 }
9272
9273 if (EmitTypeMismatch) {
9274 // The function is not variadic, so we do not generate warnings about
9275 // being allowed to pass that object as a variadic argument. Instead,
9276 // since there are inherently no printf specifiers for types which cannot
9277 // be passed as variadic arguments, emit a plain old specifier mismatch
9278 // argument.
9279 EmitFormatDiagnostic(
9280 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9281 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9282 << E->getSourceRange(),
9283 E->getBeginLoc(), false, CSR);
9284 }
9285
9286 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9287 "format string specifier index out of range");
9288 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9289 }
9290
9291 return true;
9292}
9293
9294//===--- CHECK: Scanf format string checking ------------------------------===//
9295
9296namespace {
9297
9298class CheckScanfHandler : public CheckFormatHandler {
9299public:
9300 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9301 const Expr *origFormatExpr, FormatStringType type,
9302 unsigned firstDataArg, unsigned numDataArgs,
9303 const char *beg, Sema::FormatArgumentPassingKind APK,
9304 ArrayRef<const Expr *> Args, unsigned formatIdx,
9305 bool inFunctionCall, VariadicCallType CallType,
9306 llvm::SmallBitVector &CheckedVarArgs,
9307 UncoveredArgHandler &UncoveredArg)
9308 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9309 numDataArgs, beg, APK, Args, formatIdx,
9310 inFunctionCall, CallType, CheckedVarArgs,
9311 UncoveredArg) {}
9312
9313 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9314 const char *startSpecifier,
9315 unsigned specifierLen) override;
9316
9317 bool HandleInvalidScanfConversionSpecifier(
9318 const analyze_scanf::ScanfSpecifier &FS,
9319 const char *startSpecifier,
9320 unsigned specifierLen) override;
9321
9322 void HandleIncompleteScanList(const char *start, const char *end) override;
9323};
9324
9325} // namespace
9326
9327void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9328 const char *end) {
9329 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9330 getLocationOfByte(end), /*IsStringLocation*/true,
9331 getSpecifierRange(start, end - start));
9332}
9333
9334bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9336 const char *startSpecifier,
9337 unsigned specifierLen) {
9340
9341 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9342 getLocationOfByte(CS.getStart()),
9343 startSpecifier, specifierLen,
9344 CS.getStart(), CS.getLength());
9345}
9346
9347bool CheckScanfHandler::HandleScanfSpecifier(
9349 const char *startSpecifier,
9350 unsigned specifierLen) {
9351 using namespace analyze_scanf;
9352 using namespace analyze_format_string;
9353
9354 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9355
9356 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9357 // be used to decide if we are using positional arguments consistently.
9358 if (FS.consumesDataArgument()) {
9359 if (atFirstArg) {
9360 atFirstArg = false;
9361 usesPositionalArgs = FS.usesPositionalArg();
9362 }
9363 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9364 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9365 startSpecifier, specifierLen);
9366 return false;
9367 }
9368 }
9369
9370 // Check if the field with is non-zero.
9371 const OptionalAmount &Amt = FS.getFieldWidth();
9373 if (Amt.getConstantAmount() == 0) {
9374 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9375 Amt.getConstantLength());
9376 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9377 getLocationOfByte(Amt.getStart()),
9378 /*IsStringLocation*/true, R,
9380 }
9381 }
9382
9383 if (!FS.consumesDataArgument()) {
9384 // FIXME: Technically specifying a precision or field width here
9385 // makes no sense. Worth issuing a warning at some point.
9386 return true;
9387 }
9388
9389 // Consume the argument.
9390 unsigned argIndex = FS.getArgIndex();
9391 if (argIndex < NumDataArgs) {
9392 // The check to see if the argIndex is valid will come later.
9393 // We set the bit here because we may exit early from this
9394 // function if we encounter some other error.
9395 CoveredArgs.set(argIndex);
9396 }
9397
9398 // Check the length modifier is valid with the given conversion specifier.
9400 S.getLangOpts()))
9401 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9402 diag::warn_format_nonsensical_length);
9403 else if (!FS.hasStandardLengthModifier())
9404 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9406 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9407 diag::warn_format_non_standard_conversion_spec);
9408
9410 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9411
9412 // The remaining checks depend on the data arguments.
9413 if (!HasFormatArguments())
9414 return true;
9415
9416 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9417 return false;
9418
9419 // Check that the argument type matches the format specifier.
9420 const Expr *Ex = getDataArg(argIndex);
9421 if (!Ex)
9422 return true;
9423
9425
9426 if (!AT.isValid()) {
9427 return true;
9428 }
9429
9431 AT.matchesType(S.Context, Ex->getType());
9434 return true;
9437
9438 ScanfSpecifier fixedFS = FS;
9439 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9440 S.getLangOpts(), S.Context);
9441
9442 unsigned Diag =
9443 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9444 : Signedness
9445 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9446 : diag::warn_format_conversion_argument_type_mismatch;
9447
9448 if (Success) {
9449 // Get the fix string from the fixed format specifier.
9450 SmallString<128> buf;
9451 llvm::raw_svector_ostream os(buf);
9452 fixedFS.toString(os);
9453
9454 EmitFormatDiagnostic(
9456 << Ex->getType() << false << Ex->getSourceRange(),
9457 Ex->getBeginLoc(),
9458 /*IsStringLocation*/ false,
9459 getSpecifierRange(startSpecifier, specifierLen),
9461 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9462 } else {
9463 EmitFormatDiagnostic(S.PDiag(Diag)
9465 << Ex->getType() << false << Ex->getSourceRange(),
9466 Ex->getBeginLoc(),
9467 /*IsStringLocation*/ false,
9468 getSpecifierRange(startSpecifier, specifierLen));
9469 }
9470
9471 return true;
9472}
9473
9474static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9476 const StringLiteral *Fmt,
9478 const Expr *FmtExpr, bool InFunctionCall) {
9479 bool HadError = false;
9480 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9481 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9482 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9483 // In positional-style format strings, the same specifier can appear
9484 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9485 // are sorted by getPosition(), and we process each range of equal
9486 // getPosition() values as one group.
9487 // RefArgs are taken from a string literal that was given to
9488 // attribute(format_matches), and if we got this far, we have already
9489 // verified that if it has positional specifiers that appear in multiple
9490 // locations, then they are all mutually compatible. What's left for us to
9491 // do is verify that all specifiers with the same position in FmtArgs are
9492 // compatible with the RefArgs specifiers. We check each specifier from
9493 // FmtArgs against the first member of the RefArgs group.
9494 for (; FmtIter < FmtEnd; ++FmtIter) {
9495 // Clang does not diagnose missing format specifiers in positional-style
9496 // strings (TODO: which it probably should do, as it is UB to skip over a
9497 // format argument). Skip specifiers if needed.
9498 if (FmtIter->getPosition() < RefIter->getPosition())
9499 continue;
9500
9501 // Delimits a new getPosition() value.
9502 if (FmtIter->getPosition() > RefIter->getPosition())
9503 break;
9504
9505 HadError |=
9506 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9507 }
9508
9509 // Jump RefIter to the start of the next group.
9510 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9511 return Arg.getPosition() != RefIter->getPosition();
9512 });
9513 }
9514
9515 if (FmtIter < FmtEnd) {
9516 CheckFormatHandler::EmitFormatDiagnostic(
9517 S, InFunctionCall, FmtExpr,
9518 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9519 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9520 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9521 } else if (RefIter < RefEnd) {
9522 CheckFormatHandler::EmitFormatDiagnostic(
9523 S, InFunctionCall, FmtExpr,
9524 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9525 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9526 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9527 << 1 << RefIter->getSourceRange();
9528 }
9529 return !HadError;
9530}
9531
9533 Sema &S, const FormatStringLiteral *FExpr,
9534 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9536 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9537 bool inFunctionCall, VariadicCallType CallType,
9538 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9539 bool IgnoreStringsWithoutSpecifiers) {
9540 // CHECK: is the format string a wide literal?
9541 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9542 CheckFormatHandler::EmitFormatDiagnostic(
9543 S, inFunctionCall, Args[format_idx],
9544 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9545 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9546 return;
9547 }
9548
9549 // Str - The format string. NOTE: this is NOT null-terminated!
9550 StringRef StrRef = FExpr->getString();
9551 const char *Str = StrRef.data();
9552 // Account for cases where the string literal is truncated in a declaration.
9553 const ConstantArrayType *T =
9554 S.Context.getAsConstantArrayType(FExpr->getType());
9555 assert(T && "String literal not of constant array type!");
9556 size_t TypeSize = T->getZExtSize();
9557 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9558 const unsigned numDataArgs = Args.size() - firstDataArg;
9559
9560 if (IgnoreStringsWithoutSpecifiers &&
9562 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9563 return;
9564
9565 // Emit a warning if the string literal is truncated and does not contain an
9566 // embedded null character.
9567 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9568 CheckFormatHandler::EmitFormatDiagnostic(
9569 S, inFunctionCall, Args[format_idx],
9570 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9571 FExpr->getBeginLoc(),
9572 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9573 return;
9574 }
9575
9576 // CHECK: empty format string?
9577 if (StrLen == 0 && numDataArgs > 0) {
9578 CheckFormatHandler::EmitFormatDiagnostic(
9579 S, inFunctionCall, Args[format_idx],
9580 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9581 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9582 return;
9583 }
9584
9589 bool IsObjC =
9591 if (ReferenceFormatString == nullptr) {
9592 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9593 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9594 inFunctionCall, CallType, CheckedVarArgs,
9595 UncoveredArg);
9596
9598 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9601 H.DoneProcessing();
9602 } else {
9604 Type, ReferenceFormatString, FExpr->getFormatString(),
9605 inFunctionCall ? nullptr : Args[format_idx]);
9606 }
9607 } else if (Type == FormatStringType::Scanf) {
9608 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9609 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9610 CallType, CheckedVarArgs, UncoveredArg);
9611
9613 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9614 H.DoneProcessing();
9615 } // TODO: handle other formats
9616}
9617
9619 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9620 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9625 return true;
9626
9627 bool IsObjC =
9630 FormatStringLiteral RefLit = AuthoritativeFormatString;
9631 FormatStringLiteral TestLit = TestedFormatString;
9632 const Expr *Arg;
9633 bool DiagAtStringLiteral;
9634 if (FunctionCallArg) {
9635 Arg = FunctionCallArg;
9636 DiagAtStringLiteral = false;
9637 } else {
9638 Arg = TestedFormatString;
9639 DiagAtStringLiteral = true;
9640 }
9641 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9642 AuthoritativeFormatString, Type,
9643 IsObjC, true, RefArgs) &&
9644 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9645 DiagAtStringLiteral, FmtArgs)) {
9646 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9647 TestedFormatString, FmtArgs, Arg,
9648 DiagAtStringLiteral);
9649 }
9650 return false;
9651}
9652
9654 const StringLiteral *Str) {
9659 return true;
9660
9661 FormatStringLiteral RefLit = Str;
9663 bool IsObjC =
9665 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9666 true, Args))
9667 return false;
9668
9669 // Group arguments by getPosition() value, and check that each member of the
9670 // group is compatible with the first member. This verifies that when
9671 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9672 // are mutually compatible. As an optimization, don't test the first member
9673 // against itself.
9674 bool HadError = false;
9675 auto Iter = Args.begin();
9676 auto End = Args.end();
9677 while (Iter != End) {
9678 const auto &FirstInGroup = *Iter;
9679 for (++Iter;
9680 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9681 ++Iter) {
9682 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9683 }
9684 }
9685 return !HadError;
9686}
9687
9689 // Str - The format string. NOTE: this is NOT null-terminated!
9690 StringRef StrRef = FExpr->getString();
9691 const char *Str = StrRef.data();
9692 // Account for cases where the string literal is truncated in a declaration.
9693 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9694 assert(T && "String literal not of constant array type!");
9695 size_t TypeSize = T->getZExtSize();
9696 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9697 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9698 getLangOpts(),
9699 Context.getTargetInfo());
9700}
9701
9702//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9703
9704// Returns the related absolute value function that is larger, of 0 if one
9705// does not exist.
9706static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9707 switch (AbsFunction) {
9708 default:
9709 return 0;
9710
9711 case Builtin::BI__builtin_abs:
9712 return Builtin::BI__builtin_labs;
9713 case Builtin::BI__builtin_labs:
9714 return Builtin::BI__builtin_llabs;
9715 case Builtin::BI__builtin_llabs:
9716 return 0;
9717
9718 case Builtin::BI__builtin_fabsf:
9719 return Builtin::BI__builtin_fabs;
9720 case Builtin::BI__builtin_fabs:
9721 return Builtin::BI__builtin_fabsl;
9722 case Builtin::BI__builtin_fabsl:
9723 return 0;
9724
9725 case Builtin::BI__builtin_cabsf:
9726 return Builtin::BI__builtin_cabs;
9727 case Builtin::BI__builtin_cabs:
9728 return Builtin::BI__builtin_cabsl;
9729 case Builtin::BI__builtin_cabsl:
9730 return 0;
9731
9732 case Builtin::BIabs:
9733 return Builtin::BIlabs;
9734 case Builtin::BIlabs:
9735 return Builtin::BIllabs;
9736 case Builtin::BIllabs:
9737 return 0;
9738
9739 case Builtin::BIfabsf:
9740 return Builtin::BIfabs;
9741 case Builtin::BIfabs:
9742 return Builtin::BIfabsl;
9743 case Builtin::BIfabsl:
9744 return 0;
9745
9746 case Builtin::BIcabsf:
9747 return Builtin::BIcabs;
9748 case Builtin::BIcabs:
9749 return Builtin::BIcabsl;
9750 case Builtin::BIcabsl:
9751 return 0;
9752 }
9753}
9754
9755// Returns the argument type of the absolute value function.
9757 unsigned AbsType) {
9758 if (AbsType == 0)
9759 return QualType();
9760
9762 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9764 return QualType();
9765
9767 if (!FT)
9768 return QualType();
9769
9770 if (FT->getNumParams() != 1)
9771 return QualType();
9772
9773 return FT->getParamType(0);
9774}
9775
9776// Returns the best absolute value function, or zero, based on type and
9777// current absolute value function.
9778static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9779 unsigned AbsFunctionKind) {
9780 unsigned BestKind = 0;
9781 uint64_t ArgSize = Context.getTypeSize(ArgType);
9782 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9783 Kind = getLargerAbsoluteValueFunction(Kind)) {
9784 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9785 if (Context.getTypeSize(ParamType) >= ArgSize) {
9786 if (BestKind == 0)
9787 BestKind = Kind;
9788 else if (Context.hasSameType(ParamType, ArgType)) {
9789 BestKind = Kind;
9790 break;
9791 }
9792 }
9793 }
9794 return BestKind;
9795}
9796
9802
9804 if (T->isIntegralOrEnumerationType())
9805 return AVK_Integer;
9806 if (T->isRealFloatingType())
9807 return AVK_Floating;
9808 if (T->isAnyComplexType())
9809 return AVK_Complex;
9810
9811 llvm_unreachable("Type not integer, floating, or complex");
9812}
9813
9814// Changes the absolute value function to a different type. Preserves whether
9815// the function is a builtin.
9816static unsigned changeAbsFunction(unsigned AbsKind,
9817 AbsoluteValueKind ValueKind) {
9818 switch (ValueKind) {
9819 case AVK_Integer:
9820 switch (AbsKind) {
9821 default:
9822 return 0;
9823 case Builtin::BI__builtin_fabsf:
9824 case Builtin::BI__builtin_fabs:
9825 case Builtin::BI__builtin_fabsl:
9826 case Builtin::BI__builtin_cabsf:
9827 case Builtin::BI__builtin_cabs:
9828 case Builtin::BI__builtin_cabsl:
9829 return Builtin::BI__builtin_abs;
9830 case Builtin::BIfabsf:
9831 case Builtin::BIfabs:
9832 case Builtin::BIfabsl:
9833 case Builtin::BIcabsf:
9834 case Builtin::BIcabs:
9835 case Builtin::BIcabsl:
9836 return Builtin::BIabs;
9837 }
9838 case AVK_Floating:
9839 switch (AbsKind) {
9840 default:
9841 return 0;
9842 case Builtin::BI__builtin_abs:
9843 case Builtin::BI__builtin_labs:
9844 case Builtin::BI__builtin_llabs:
9845 case Builtin::BI__builtin_cabsf:
9846 case Builtin::BI__builtin_cabs:
9847 case Builtin::BI__builtin_cabsl:
9848 return Builtin::BI__builtin_fabsf;
9849 case Builtin::BIabs:
9850 case Builtin::BIlabs:
9851 case Builtin::BIllabs:
9852 case Builtin::BIcabsf:
9853 case Builtin::BIcabs:
9854 case Builtin::BIcabsl:
9855 return Builtin::BIfabsf;
9856 }
9857 case AVK_Complex:
9858 switch (AbsKind) {
9859 default:
9860 return 0;
9861 case Builtin::BI__builtin_abs:
9862 case Builtin::BI__builtin_labs:
9863 case Builtin::BI__builtin_llabs:
9864 case Builtin::BI__builtin_fabsf:
9865 case Builtin::BI__builtin_fabs:
9866 case Builtin::BI__builtin_fabsl:
9867 return Builtin::BI__builtin_cabsf;
9868 case Builtin::BIabs:
9869 case Builtin::BIlabs:
9870 case Builtin::BIllabs:
9871 case Builtin::BIfabsf:
9872 case Builtin::BIfabs:
9873 case Builtin::BIfabsl:
9874 return Builtin::BIcabsf;
9875 }
9876 }
9877 llvm_unreachable("Unable to convert function");
9878}
9879
9880static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9881 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9882 if (!FnInfo)
9883 return 0;
9884
9885 switch (FDecl->getBuiltinID()) {
9886 default:
9887 return 0;
9888 case Builtin::BI__builtin_abs:
9889 case Builtin::BI__builtin_fabs:
9890 case Builtin::BI__builtin_fabsf:
9891 case Builtin::BI__builtin_fabsl:
9892 case Builtin::BI__builtin_labs:
9893 case Builtin::BI__builtin_llabs:
9894 case Builtin::BI__builtin_cabs:
9895 case Builtin::BI__builtin_cabsf:
9896 case Builtin::BI__builtin_cabsl:
9897 case Builtin::BIabs:
9898 case Builtin::BIlabs:
9899 case Builtin::BIllabs:
9900 case Builtin::BIfabs:
9901 case Builtin::BIfabsf:
9902 case Builtin::BIfabsl:
9903 case Builtin::BIcabs:
9904 case Builtin::BIcabsf:
9905 case Builtin::BIcabsl:
9906 return FDecl->getBuiltinID();
9907 }
9908 llvm_unreachable("Unknown Builtin type");
9909}
9910
9911// If the replacement is valid, emit a note with replacement function.
9912// Additionally, suggest including the proper header if not already included.
9914 unsigned AbsKind, QualType ArgType) {
9915 bool EmitHeaderHint = true;
9916 const char *HeaderName = nullptr;
9917 std::string FunctionName;
9918 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9919 FunctionName = "std::abs";
9920 if (ArgType->isIntegralOrEnumerationType()) {
9921 HeaderName = "cstdlib";
9922 } else if (ArgType->isRealFloatingType()) {
9923 HeaderName = "cmath";
9924 } else {
9925 llvm_unreachable("Invalid Type");
9926 }
9927
9928 // Lookup all std::abs
9929 if (NamespaceDecl *Std = S.getStdNamespace()) {
9930 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9932 S.LookupQualifiedName(R, Std);
9933
9934 for (const auto *I : R) {
9935 const FunctionDecl *FDecl = nullptr;
9936 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9937 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9938 } else {
9939 FDecl = dyn_cast<FunctionDecl>(I);
9940 }
9941 if (!FDecl)
9942 continue;
9943
9944 // Found std::abs(), check that they are the right ones.
9945 if (FDecl->getNumParams() != 1)
9946 continue;
9947
9948 // Check that the parameter type can handle the argument.
9949 QualType ParamType = FDecl->getParamDecl(0)->getType();
9950 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9951 S.Context.getTypeSize(ArgType) <=
9952 S.Context.getTypeSize(ParamType)) {
9953 // Found a function, don't need the header hint.
9954 EmitHeaderHint = false;
9955 break;
9956 }
9957 }
9958 }
9959 } else {
9960 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9961 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9962
9963 if (HeaderName) {
9964 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9965 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9967 S.LookupName(R, S.getCurScope());
9968
9969 if (R.isSingleResult()) {
9970 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9971 if (FD && FD->getBuiltinID() == AbsKind) {
9972 EmitHeaderHint = false;
9973 } else {
9974 return;
9975 }
9976 } else if (!R.empty()) {
9977 return;
9978 }
9979 }
9980 }
9981
9982 S.Diag(Loc, diag::note_replace_abs_function)
9983 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9984
9985 if (!HeaderName)
9986 return;
9987
9988 if (!EmitHeaderHint)
9989 return;
9990
9991 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9992 << FunctionName;
9993}
9994
9995template <std::size_t StrLen>
9996static bool IsStdFunction(const FunctionDecl *FDecl,
9997 const char (&Str)[StrLen]) {
9998 if (!FDecl)
9999 return false;
10000 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10001 return false;
10002 if (!FDecl->isInStdNamespace())
10003 return false;
10004
10005 return true;
10006}
10007
10008enum class MathCheck { NaN, Inf };
10009static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10010 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10011 return llvm::is_contained(names, calleeName);
10012 };
10013
10014 switch (Check) {
10015 case MathCheck::NaN:
10016 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10017 "__builtin_nanf16", "__builtin_nanf128"});
10018 case MathCheck::Inf:
10019 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10020 "__builtin_inff16", "__builtin_inff128"});
10021 }
10022 llvm_unreachable("unknown MathCheck");
10023}
10024
10025static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10026 if (FDecl->getName() != "infinity")
10027 return false;
10028
10029 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10030 const CXXRecordDecl *RDecl = MDecl->getParent();
10031 if (RDecl->getName() != "numeric_limits")
10032 return false;
10033
10034 if (const NamespaceDecl *NSDecl =
10035 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10036 return NSDecl->isStdNamespace();
10037 }
10038
10039 return false;
10040}
10041
10042void Sema::CheckInfNaNFunction(const CallExpr *Call,
10043 const FunctionDecl *FDecl) {
10044 if (!FDecl->getIdentifier())
10045 return;
10046
10047 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10048 if (FPO.getNoHonorNaNs() &&
10049 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10051 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10052 << 1 << 0 << Call->getSourceRange();
10053 return;
10054 }
10055
10056 if (FPO.getNoHonorInfs() &&
10057 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10058 IsInfinityFunction(FDecl) ||
10060 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10061 << 0 << 0 << Call->getSourceRange();
10062 }
10063}
10064
10065void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10066 const FunctionDecl *FDecl) {
10067 if (Call->getNumArgs() != 1)
10068 return;
10069
10070 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10071 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10072 if (AbsKind == 0 && !IsStdAbs)
10073 return;
10074
10075 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10076 QualType ParamType = Call->getArg(0)->getType();
10077
10078 // Unsigned types cannot be negative. Suggest removing the absolute value
10079 // function call.
10080 if (ArgType->isUnsignedIntegerType()) {
10081 std::string FunctionName =
10082 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10083 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10084 Diag(Call->getExprLoc(), diag::note_remove_abs)
10085 << FunctionName
10086 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10087 return;
10088 }
10089
10090 // Taking the absolute value of a pointer is very suspicious, they probably
10091 // wanted to index into an array, dereference a pointer, call a function, etc.
10092 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10093 unsigned DiagType = 0;
10094 if (ArgType->isFunctionType())
10095 DiagType = 1;
10096 else if (ArgType->isArrayType())
10097 DiagType = 2;
10098
10099 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10100 return;
10101 }
10102
10103 // std::abs has overloads which prevent most of the absolute value problems
10104 // from occurring.
10105 if (IsStdAbs)
10106 return;
10107
10108 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10109 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10110
10111 // The argument and parameter are the same kind. Check if they are the right
10112 // size.
10113 if (ArgValueKind == ParamValueKind) {
10114 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10115 return;
10116
10117 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10118 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10119 << FDecl << ArgType << ParamType;
10120
10121 if (NewAbsKind == 0)
10122 return;
10123
10124 emitReplacement(*this, Call->getExprLoc(),
10125 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10126 return;
10127 }
10128
10129 // ArgValueKind != ParamValueKind
10130 // The wrong type of absolute value function was used. Attempt to find the
10131 // proper one.
10132 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10133 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10134 if (NewAbsKind == 0)
10135 return;
10136
10137 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10138 << FDecl << ParamValueKind << ArgValueKind;
10139
10140 emitReplacement(*this, Call->getExprLoc(),
10141 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10142}
10143
10144//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10145void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10146 const FunctionDecl *FDecl) {
10147 if (!Call || !FDecl) return;
10148
10149 // Ignore template specializations and macros.
10150 if (inTemplateInstantiation()) return;
10151 if (Call->getExprLoc().isMacroID()) return;
10152
10153 // Only care about the one template argument, two function parameter std::max
10154 if (Call->getNumArgs() != 2) return;
10155 if (!IsStdFunction(FDecl, "max")) return;
10156 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10157 if (!ArgList) return;
10158 if (ArgList->size() != 1) return;
10159
10160 // Check that template type argument is unsigned integer.
10161 const auto& TA = ArgList->get(0);
10162 if (TA.getKind() != TemplateArgument::Type) return;
10163 QualType ArgType = TA.getAsType();
10164 if (!ArgType->isUnsignedIntegerType()) return;
10165
10166 // See if either argument is a literal zero.
10167 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10168 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10169 if (!MTE) return false;
10170 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10171 if (!Num) return false;
10172 if (Num->getValue() != 0) return false;
10173 return true;
10174 };
10175
10176 const Expr *FirstArg = Call->getArg(0);
10177 const Expr *SecondArg = Call->getArg(1);
10178 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10179 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10180
10181 // Only warn when exactly one argument is zero.
10182 if (IsFirstArgZero == IsSecondArgZero) return;
10183
10184 SourceRange FirstRange = FirstArg->getSourceRange();
10185 SourceRange SecondRange = SecondArg->getSourceRange();
10186
10187 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10188
10189 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10190 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10191
10192 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10193 SourceRange RemovalRange;
10194 if (IsFirstArgZero) {
10195 RemovalRange = SourceRange(FirstRange.getBegin(),
10196 SecondRange.getBegin().getLocWithOffset(-1));
10197 } else {
10198 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10199 SecondRange.getEnd());
10200 }
10201
10202 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10203 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10204 << FixItHint::CreateRemoval(RemovalRange);
10205}
10206
10207//===--- CHECK: Standard memory functions ---------------------------------===//
10208
10209/// Takes the expression passed to the size_t parameter of functions
10210/// such as memcmp, strncat, etc and warns if it's a comparison.
10211///
10212/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10214 const IdentifierInfo *FnName,
10215 SourceLocation FnLoc,
10216 SourceLocation RParenLoc) {
10217 const auto *Size = dyn_cast<BinaryOperator>(E);
10218 if (!Size)
10219 return false;
10220
10221 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10222 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10223 return false;
10224
10225 SourceRange SizeRange = Size->getSourceRange();
10226 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10227 << SizeRange << FnName;
10228 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10229 << FnName
10231 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10232 << FixItHint::CreateRemoval(RParenLoc);
10233 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10234 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10236 ")");
10237
10238 return true;
10239}
10240
10241/// Determine whether the given type is or contains a dynamic class type
10242/// (e.g., whether it has a vtable).
10244 bool &IsContained) {
10245 // Look through array types while ignoring qualifiers.
10246 const Type *Ty = T->getBaseElementTypeUnsafe();
10247 IsContained = false;
10248
10249 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10250 RD = RD ? RD->getDefinition() : nullptr;
10251 if (!RD || RD->isInvalidDecl())
10252 return nullptr;
10253
10254 if (RD->isDynamicClass())
10255 return RD;
10256
10257 // Check all the fields. If any bases were dynamic, the class is dynamic.
10258 // It's impossible for a class to transitively contain itself by value, so
10259 // infinite recursion is impossible.
10260 for (auto *FD : RD->fields()) {
10261 bool SubContained;
10262 if (const CXXRecordDecl *ContainedRD =
10263 getContainedDynamicClass(FD->getType(), SubContained)) {
10264 IsContained = true;
10265 return ContainedRD;
10266 }
10267 }
10268
10269 return nullptr;
10270}
10271
10273 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10274 if (Unary->getKind() == UETT_SizeOf)
10275 return Unary;
10276 return nullptr;
10277}
10278
10279/// If E is a sizeof expression, returns its argument expression,
10280/// otherwise returns NULL.
10281static const Expr *getSizeOfExprArg(const Expr *E) {
10283 if (!SizeOf->isArgumentType())
10284 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10285 return nullptr;
10286}
10287
10288/// If E is a sizeof expression, returns its argument type.
10291 return SizeOf->getTypeOfArgument();
10292 return QualType();
10293}
10294
10295namespace {
10296
10297struct SearchNonTrivialToInitializeField
10298 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10299 using Super =
10300 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10301
10302 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10303
10304 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10305 SourceLocation SL) {
10306 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10307 asDerived().visitArray(PDIK, AT, SL);
10308 return;
10309 }
10310
10311 Super::visitWithKind(PDIK, FT, SL);
10312 }
10313
10314 void visitARCStrong(QualType FT, SourceLocation SL) {
10315 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10316 }
10317 void visitARCWeak(QualType FT, SourceLocation SL) {
10318 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10319 }
10320 void visitStruct(QualType FT, SourceLocation SL) {
10321 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10322 visit(FD->getType(), FD->getLocation());
10323 }
10324 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10325 const ArrayType *AT, SourceLocation SL) {
10326 visit(getContext().getBaseElementType(AT), SL);
10327 }
10328 void visitTrivial(QualType FT, SourceLocation SL) {}
10329
10330 static void diag(QualType RT, const Expr *E, Sema &S) {
10331 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10332 }
10333
10334 ASTContext &getContext() { return S.getASTContext(); }
10335
10336 const Expr *E;
10337 Sema &S;
10338};
10339
10340struct SearchNonTrivialToCopyField
10341 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10342 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10343
10344 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10345
10346 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10347 SourceLocation SL) {
10348 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10349 asDerived().visitArray(PCK, AT, SL);
10350 return;
10351 }
10352
10353 Super::visitWithKind(PCK, FT, SL);
10354 }
10355
10356 void visitARCStrong(QualType FT, SourceLocation SL) {
10357 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10358 }
10359 void visitARCWeak(QualType FT, SourceLocation SL) {
10360 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10361 }
10362 void visitPtrAuth(QualType FT, SourceLocation SL) {
10363 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10364 }
10365 void visitStruct(QualType FT, SourceLocation SL) {
10366 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10367 visit(FD->getType(), FD->getLocation());
10368 }
10369 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10370 SourceLocation SL) {
10371 visit(getContext().getBaseElementType(AT), SL);
10372 }
10373 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10374 SourceLocation SL) {}
10375 void visitTrivial(QualType FT, SourceLocation SL) {}
10376 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10377
10378 static void diag(QualType RT, const Expr *E, Sema &S) {
10379 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10380 }
10381
10382 ASTContext &getContext() { return S.getASTContext(); }
10383
10384 const Expr *E;
10385 Sema &S;
10386};
10387
10388}
10389
10390/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10391static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10392 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10393
10394 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10395 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10396 return false;
10397
10398 return doesExprLikelyComputeSize(BO->getLHS()) ||
10399 doesExprLikelyComputeSize(BO->getRHS());
10400 }
10401
10402 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10403}
10404
10405/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10406///
10407/// \code
10408/// #define MACRO 0
10409/// foo(MACRO);
10410/// foo(0);
10411/// \endcode
10412///
10413/// This should return true for the first call to foo, but not for the second
10414/// (regardless of whether foo is a macro or function).
10416 SourceLocation CallLoc,
10417 SourceLocation ArgLoc) {
10418 if (!CallLoc.isMacroID())
10419 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10420
10421 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10422 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10423}
10424
10425/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10426/// last two arguments transposed.
10427static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10428 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10429 return;
10430
10431 const Expr *SizeArg =
10432 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10433
10434 auto isLiteralZero = [](const Expr *E) {
10435 return (isa<IntegerLiteral>(E) &&
10436 cast<IntegerLiteral>(E)->getValue() == 0) ||
10438 cast<CharacterLiteral>(E)->getValue() == 0);
10439 };
10440
10441 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10442 SourceLocation CallLoc = Call->getRParenLoc();
10444 if (isLiteralZero(SizeArg) &&
10445 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10446
10447 SourceLocation DiagLoc = SizeArg->getExprLoc();
10448
10449 // Some platforms #define bzero to __builtin_memset. See if this is the
10450 // case, and if so, emit a better diagnostic.
10451 if (BId == Builtin::BIbzero ||
10453 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10454 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10455 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10456 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10457 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10458 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10459 }
10460 return;
10461 }
10462
10463 // If the second argument to a memset is a sizeof expression and the third
10464 // isn't, this is also likely an error. This should catch
10465 // 'memset(buf, sizeof(buf), 0xff)'.
10466 if (BId == Builtin::BImemset &&
10467 doesExprLikelyComputeSize(Call->getArg(1)) &&
10468 !doesExprLikelyComputeSize(Call->getArg(2))) {
10469 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10470 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10471 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10472 return;
10473 }
10474}
10475
10476void Sema::CheckMemaccessArguments(const CallExpr *Call,
10477 unsigned BId,
10478 IdentifierInfo *FnName) {
10479 assert(BId != 0);
10480
10481 // It is possible to have a non-standard definition of memset. Validate
10482 // we have enough arguments, and if not, abort further checking.
10483 unsigned ExpectedNumArgs =
10484 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10485 if (Call->getNumArgs() < ExpectedNumArgs)
10486 return;
10487
10488 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10489 BId == Builtin::BIstrndup ? 1 : 2);
10490 unsigned LenArg =
10491 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10492 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10493
10494 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10495 Call->getBeginLoc(), Call->getRParenLoc()))
10496 return;
10497
10498 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10499 CheckMemaccessSize(*this, BId, Call);
10500
10501 // We have special checking when the length is a sizeof expression.
10502 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10503 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10504 llvm::FoldingSetNodeID SizeOfArgID;
10505
10506 // Although widely used, 'bzero' is not a standard function. Be more strict
10507 // with the argument types before allowing diagnostics and only allow the
10508 // form bzero(ptr, sizeof(...)).
10509 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10510 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10511 return;
10512
10513 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10514 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10515 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10516
10517 QualType DestTy = Dest->getType();
10518 QualType PointeeTy;
10519 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10520 PointeeTy = DestPtrTy->getPointeeType();
10521
10522 // Never warn about void type pointers. This can be used to suppress
10523 // false positives.
10524 if (PointeeTy->isVoidType())
10525 continue;
10526
10527 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10528 // actually comparing the expressions for equality. Because computing the
10529 // expression IDs can be expensive, we only do this if the diagnostic is
10530 // enabled.
10531 if (SizeOfArg &&
10532 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10533 SizeOfArg->getExprLoc())) {
10534 // We only compute IDs for expressions if the warning is enabled, and
10535 // cache the sizeof arg's ID.
10536 if (SizeOfArgID == llvm::FoldingSetNodeID())
10537 SizeOfArg->Profile(SizeOfArgID, Context, true);
10538 llvm::FoldingSetNodeID DestID;
10539 Dest->Profile(DestID, Context, true);
10540 if (DestID == SizeOfArgID) {
10541 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10542 // over sizeof(src) as well.
10543 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10544 StringRef ReadableName = FnName->getName();
10545
10546 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10547 if (UnaryOp->getOpcode() == UO_AddrOf)
10548 ActionIdx = 1; // If its an address-of operator, just remove it.
10549 if (!PointeeTy->isIncompleteType() &&
10550 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10551 ActionIdx = 2; // If the pointee's size is sizeof(char),
10552 // suggest an explicit length.
10553
10554 // If the function is defined as a builtin macro, do not show macro
10555 // expansion.
10556 SourceLocation SL = SizeOfArg->getExprLoc();
10557 SourceRange DSR = Dest->getSourceRange();
10558 SourceRange SSR = SizeOfArg->getSourceRange();
10559 SourceManager &SM = getSourceManager();
10560
10561 if (SM.isMacroArgExpansion(SL)) {
10562 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10563 SL = SM.getSpellingLoc(SL);
10564 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10565 SM.getSpellingLoc(DSR.getEnd()));
10566 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10567 SM.getSpellingLoc(SSR.getEnd()));
10568 }
10569
10570 DiagRuntimeBehavior(SL, SizeOfArg,
10571 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10572 << ReadableName
10573 << PointeeTy
10574 << DestTy
10575 << DSR
10576 << SSR);
10577 DiagRuntimeBehavior(SL, SizeOfArg,
10578 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10579 << ActionIdx
10580 << SSR);
10581
10582 break;
10583 }
10584 }
10585
10586 // Also check for cases where the sizeof argument is the exact same
10587 // type as the memory argument, and where it points to a user-defined
10588 // record type.
10589 if (SizeOfArgTy != QualType()) {
10590 if (PointeeTy->isRecordType() &&
10591 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10592 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10593 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10594 << FnName << SizeOfArgTy << ArgIdx
10595 << PointeeTy << Dest->getSourceRange()
10596 << LenExpr->getSourceRange());
10597 break;
10598 }
10599 }
10600 } else if (DestTy->isArrayType()) {
10601 PointeeTy = DestTy;
10602 }
10603
10604 if (PointeeTy == QualType())
10605 continue;
10606
10607 // Always complain about dynamic classes.
10608 bool IsContained;
10609 if (const CXXRecordDecl *ContainedRD =
10610 getContainedDynamicClass(PointeeTy, IsContained)) {
10611
10612 unsigned OperationType = 0;
10613 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10614 // "overwritten" if we're warning about the destination for any call
10615 // but memcmp; otherwise a verb appropriate to the call.
10616 if (ArgIdx != 0 || IsCmp) {
10617 if (BId == Builtin::BImemcpy)
10618 OperationType = 1;
10619 else if(BId == Builtin::BImemmove)
10620 OperationType = 2;
10621 else if (IsCmp)
10622 OperationType = 3;
10623 }
10624
10625 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10626 PDiag(diag::warn_dyn_class_memaccess)
10627 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10628 << IsContained << ContainedRD << OperationType
10629 << Call->getCallee()->getSourceRange());
10630 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10631 BId != Builtin::BImemset)
10633 Dest->getExprLoc(), Dest,
10634 PDiag(diag::warn_arc_object_memaccess)
10635 << ArgIdx << FnName << PointeeTy
10636 << Call->getCallee()->getSourceRange());
10637 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10638
10639 // FIXME: Do not consider incomplete types even though they may be
10640 // completed later. GCC does not diagnose such code, but we may want to
10641 // consider diagnosing it in the future, perhaps under a different, but
10642 // related, diagnostic group.
10643 bool NonTriviallyCopyableCXXRecord =
10644 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10645 !PointeeTy.isTriviallyCopyableType(Context);
10646
10647 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10649 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10650 PDiag(diag::warn_cstruct_memaccess)
10651 << ArgIdx << FnName << PointeeTy << 0);
10652 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10653 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10654 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10655 // FIXME: Limiting this warning to dest argument until we decide
10656 // whether it's valid for source argument too.
10657 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10658 PDiag(diag::warn_cxxstruct_memaccess)
10659 << FnName << PointeeTy);
10660 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10662 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10663 PDiag(diag::warn_cstruct_memaccess)
10664 << ArgIdx << FnName << PointeeTy << 1);
10665 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10666 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10667 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10668 // FIXME: Limiting this warning to dest argument until we decide
10669 // whether it's valid for source argument too.
10670 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10671 PDiag(diag::warn_cxxstruct_memaccess)
10672 << FnName << PointeeTy);
10673 } else {
10674 continue;
10675 }
10676 } else
10677 continue;
10678
10680 Dest->getExprLoc(), Dest,
10681 PDiag(diag::note_bad_memaccess_silence)
10682 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10683 break;
10684 }
10685}
10686
10687// A little helper routine: ignore addition and subtraction of integer literals.
10688// This intentionally does not ignore all integer constant expressions because
10689// we don't want to remove sizeof().
10690static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10691 Ex = Ex->IgnoreParenCasts();
10692
10693 while (true) {
10694 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10695 if (!BO || !BO->isAdditiveOp())
10696 break;
10697
10698 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10699 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10700
10701 if (isa<IntegerLiteral>(RHS))
10702 Ex = LHS;
10703 else if (isa<IntegerLiteral>(LHS))
10704 Ex = RHS;
10705 else
10706 break;
10707 }
10708
10709 return Ex;
10710}
10711
10713 ASTContext &Context) {
10714 // Only handle constant-sized or VLAs, but not flexible members.
10715 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10716 // Only issue the FIXIT for arrays of size > 1.
10717 if (CAT->getZExtSize() <= 1)
10718 return false;
10719 } else if (!Ty->isVariableArrayType()) {
10720 return false;
10721 }
10722 return true;
10723}
10724
10725void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10726 IdentifierInfo *FnName) {
10727
10728 // Don't crash if the user has the wrong number of arguments
10729 unsigned NumArgs = Call->getNumArgs();
10730 if ((NumArgs != 3) && (NumArgs != 4))
10731 return;
10732
10733 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10734 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10735 const Expr *CompareWithSrc = nullptr;
10736
10737 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10738 Call->getBeginLoc(), Call->getRParenLoc()))
10739 return;
10740
10741 // Look for 'strlcpy(dst, x, sizeof(x))'
10742 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10743 CompareWithSrc = Ex;
10744 else {
10745 // Look for 'strlcpy(dst, x, strlen(x))'
10746 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10747 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10748 SizeCall->getNumArgs() == 1)
10749 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10750 }
10751 }
10752
10753 if (!CompareWithSrc)
10754 return;
10755
10756 // Determine if the argument to sizeof/strlen is equal to the source
10757 // argument. In principle there's all kinds of things you could do
10758 // here, for instance creating an == expression and evaluating it with
10759 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10760 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10761 if (!SrcArgDRE)
10762 return;
10763
10764 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10765 if (!CompareWithSrcDRE ||
10766 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10767 return;
10768
10769 const Expr *OriginalSizeArg = Call->getArg(2);
10770 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10771 << OriginalSizeArg->getSourceRange() << FnName;
10772
10773 // Output a FIXIT hint if the destination is an array (rather than a
10774 // pointer to an array). This could be enhanced to handle some
10775 // pointers if we know the actual size, like if DstArg is 'array+2'
10776 // we could say 'sizeof(array)-2'.
10777 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10779 return;
10780
10781 SmallString<128> sizeString;
10782 llvm::raw_svector_ostream OS(sizeString);
10783 OS << "sizeof(";
10784 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10785 OS << ")";
10786
10787 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10788 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10789 OS.str());
10790}
10791
10792/// Check if two expressions refer to the same declaration.
10793static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10794 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10795 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10796 return D1->getDecl() == D2->getDecl();
10797 return false;
10798}
10799
10800static const Expr *getStrlenExprArg(const Expr *E) {
10801 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10802 const FunctionDecl *FD = CE->getDirectCallee();
10803 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10804 return nullptr;
10805 return CE->getArg(0)->IgnoreParenCasts();
10806 }
10807 return nullptr;
10808}
10809
10810void Sema::CheckStrncatArguments(const CallExpr *CE,
10811 const IdentifierInfo *FnName) {
10812 // Don't crash if the user has the wrong number of arguments.
10813 if (CE->getNumArgs() < 3)
10814 return;
10815 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10816 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10817 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10818
10819 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10820 CE->getRParenLoc()))
10821 return;
10822
10823 // Identify common expressions, which are wrongly used as the size argument
10824 // to strncat and may lead to buffer overflows.
10825 unsigned PatternType = 0;
10826 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10827 // - sizeof(dst)
10828 if (referToTheSameDecl(SizeOfArg, DstArg))
10829 PatternType = 1;
10830 // - sizeof(src)
10831 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10832 PatternType = 2;
10833 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10834 if (BE->getOpcode() == BO_Sub) {
10835 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10836 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10837 // - sizeof(dst) - strlen(dst)
10838 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10840 PatternType = 1;
10841 // - sizeof(src) - (anything)
10842 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10843 PatternType = 2;
10844 }
10845 }
10846
10847 if (PatternType == 0)
10848 return;
10849
10850 // Generate the diagnostic.
10851 SourceLocation SL = LenArg->getBeginLoc();
10852 SourceRange SR = LenArg->getSourceRange();
10853 SourceManager &SM = getSourceManager();
10854
10855 // If the function is defined as a builtin macro, do not show macro expansion.
10856 if (SM.isMacroArgExpansion(SL)) {
10857 SL = SM.getSpellingLoc(SL);
10858 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10859 SM.getSpellingLoc(SR.getEnd()));
10860 }
10861
10862 // Check if the destination is an array (rather than a pointer to an array).
10863 QualType DstTy = DstArg->getType();
10864 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10865 Context);
10866 if (!isKnownSizeArray) {
10867 if (PatternType == 1)
10868 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10869 else
10870 Diag(SL, diag::warn_strncat_src_size) << SR;
10871 return;
10872 }
10873
10874 if (PatternType == 1)
10875 Diag(SL, diag::warn_strncat_large_size) << SR;
10876 else
10877 Diag(SL, diag::warn_strncat_src_size) << SR;
10878
10879 SmallString<128> sizeString;
10880 llvm::raw_svector_ostream OS(sizeString);
10881 OS << "sizeof(";
10882 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10883 OS << ") - ";
10884 OS << "strlen(";
10885 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10886 OS << ") - 1";
10887
10888 Diag(SL, diag::note_strncat_wrong_size)
10889 << FixItHint::CreateReplacement(SR, OS.str());
10890}
10891
10892namespace {
10893void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10894 const UnaryOperator *UnaryExpr, const Decl *D) {
10896 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10897 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10898 return;
10899 }
10900}
10901
10902void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10903 const UnaryOperator *UnaryExpr) {
10904 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10905 const Decl *D = Lvalue->getDecl();
10906 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10907 if (!DD->getType()->isReferenceType())
10908 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10909 }
10910 }
10911
10912 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10913 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10914 Lvalue->getMemberDecl());
10915}
10916
10917void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10918 const UnaryOperator *UnaryExpr) {
10919 const auto *Lambda = dyn_cast<LambdaExpr>(
10921 if (!Lambda)
10922 return;
10923
10924 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10925 << CalleeName << 2 /*object: lambda expression*/;
10926}
10927
10928void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10929 const DeclRefExpr *Lvalue) {
10930 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10931 if (Var == nullptr)
10932 return;
10933
10934 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10935 << CalleeName << 0 /*object: */ << Var;
10936}
10937
10938void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10939 const CastExpr *Cast) {
10940 SmallString<128> SizeString;
10941 llvm::raw_svector_ostream OS(SizeString);
10942
10943 clang::CastKind Kind = Cast->getCastKind();
10944 if (Kind == clang::CK_BitCast &&
10945 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10946 return;
10947 if (Kind == clang::CK_IntegralToPointer &&
10949 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10950 return;
10951
10952 switch (Cast->getCastKind()) {
10953 case clang::CK_BitCast:
10954 case clang::CK_IntegralToPointer:
10955 case clang::CK_FunctionToPointerDecay:
10956 OS << '\'';
10957 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10958 OS << '\'';
10959 break;
10960 default:
10961 return;
10962 }
10963
10964 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10965 << CalleeName << 0 /*object: */ << OS.str();
10966}
10967} // namespace
10968
10969void Sema::CheckFreeArguments(const CallExpr *E) {
10970 const std::string CalleeName =
10971 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10972
10973 { // Prefer something that doesn't involve a cast to make things simpler.
10974 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10975 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10976 switch (UnaryExpr->getOpcode()) {
10977 case UnaryOperator::Opcode::UO_AddrOf:
10978 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10979 case UnaryOperator::Opcode::UO_Plus:
10980 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10981 default:
10982 break;
10983 }
10984
10985 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10986 if (Lvalue->getType()->isArrayType())
10987 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10988
10989 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10990 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10991 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10992 return;
10993 }
10994
10995 if (isa<BlockExpr>(Arg)) {
10996 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10997 << CalleeName << 1 /*object: block*/;
10998 return;
10999 }
11000 }
11001 // Maybe the cast was important, check after the other cases.
11002 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11003 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11004}
11005
11006void
11007Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11008 SourceLocation ReturnLoc,
11009 bool isObjCMethod,
11010 const AttrVec *Attrs,
11011 const FunctionDecl *FD) {
11012 // Check if the return value is null but should not be.
11013 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11014 (!isObjCMethod && isNonNullType(lhsType))) &&
11015 CheckNonNullExpr(*this, RetValExp))
11016 Diag(ReturnLoc, diag::warn_null_ret)
11017 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11018
11019 // C++11 [basic.stc.dynamic.allocation]p4:
11020 // If an allocation function declared with a non-throwing
11021 // exception-specification fails to allocate storage, it shall return
11022 // a null pointer. Any other allocation function that fails to allocate
11023 // storage shall indicate failure only by throwing an exception [...]
11024 if (FD) {
11026 if (Op == OO_New || Op == OO_Array_New) {
11027 const FunctionProtoType *Proto
11028 = FD->getType()->castAs<FunctionProtoType>();
11029 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11030 CheckNonNullExpr(*this, RetValExp))
11031 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11032 << FD << getLangOpts().CPlusPlus11;
11033 }
11034 }
11035
11036 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11037 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11038 }
11039
11040 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11041 // here prevent the user from using a PPC MMA type as trailing return type.
11042 if (Context.getTargetInfo().getTriple().isPPC64())
11043 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11044}
11045
11047 const Expr *RHS, BinaryOperatorKind Opcode) {
11048 if (!BinaryOperator::isEqualityOp(Opcode))
11049 return;
11050
11051 // Match and capture subexpressions such as "(float) X == 0.1".
11052 const FloatingLiteral *FPLiteral;
11053 const CastExpr *FPCast;
11054 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11055 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11056 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11057 return FPLiteral && FPCast;
11058 };
11059
11060 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11061 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11062 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11063 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11064 TargetTy->isFloatingPoint()) {
11065 bool Lossy;
11066 llvm::APFloat TargetC = FPLiteral->getValue();
11067 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11068 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11069 if (Lossy) {
11070 // If the literal cannot be represented in the source type, then a
11071 // check for == is always false and check for != is always true.
11072 Diag(Loc, diag::warn_float_compare_literal)
11073 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11074 << LHS->getSourceRange() << RHS->getSourceRange();
11075 return;
11076 }
11077 }
11078 }
11079
11080 // Match a more general floating-point equality comparison (-Wfloat-equal).
11081 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11082 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11083
11084 // Special case: check for x == x (which is OK).
11085 // Do not emit warnings for such cases.
11086 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11087 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11088 if (DRL->getDecl() == DRR->getDecl())
11089 return;
11090
11091 // Special case: check for comparisons against literals that can be exactly
11092 // represented by APFloat. In such cases, do not emit a warning. This
11093 // is a heuristic: often comparison against such literals are used to
11094 // detect if a value in a variable has not changed. This clearly can
11095 // lead to false negatives.
11096 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11097 if (FLL->isExact())
11098 return;
11099 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11100 if (FLR->isExact())
11101 return;
11102
11103 // Check for comparisons with builtin types.
11104 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11105 CL && CL->getBuiltinCallee())
11106 return;
11107
11108 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11109 CR && CR->getBuiltinCallee())
11110 return;
11111
11112 // Emit the diagnostic.
11113 Diag(Loc, diag::warn_floatingpoint_eq)
11114 << LHS->getSourceRange() << RHS->getSourceRange();
11115}
11116
11117//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11118//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11119
11120namespace {
11121
11122/// Structure recording the 'active' range of an integer-valued
11123/// expression.
11124struct IntRange {
11125 /// The number of bits active in the int. Note that this includes exactly one
11126 /// sign bit if !NonNegative.
11127 unsigned Width;
11128
11129 /// True if the int is known not to have negative values. If so, all leading
11130 /// bits before Width are known zero, otherwise they are known to be the
11131 /// same as the MSB within Width.
11132 bool NonNegative;
11133
11134 IntRange(unsigned Width, bool NonNegative)
11135 : Width(Width), NonNegative(NonNegative) {}
11136
11137 /// Number of bits excluding the sign bit.
11138 unsigned valueBits() const {
11139 return NonNegative ? Width : Width - 1;
11140 }
11141
11142 /// Returns the range of the bool type.
11143 static IntRange forBoolType() {
11144 return IntRange(1, true);
11145 }
11146
11147 /// Returns the range of an opaque value of the given integral type.
11148 static IntRange forValueOfType(ASTContext &C, QualType T) {
11149 return forValueOfCanonicalType(C,
11151 }
11152
11153 /// Returns the range of an opaque value of a canonical integral type.
11154 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11155 assert(T->isCanonicalUnqualified());
11156
11157 if (const auto *VT = dyn_cast<VectorType>(T))
11158 T = VT->getElementType().getTypePtr();
11159 if (const auto *CT = dyn_cast<ComplexType>(T))
11160 T = CT->getElementType().getTypePtr();
11161 if (const auto *AT = dyn_cast<AtomicType>(T))
11162 T = AT->getValueType().getTypePtr();
11163
11164 if (!C.getLangOpts().CPlusPlus) {
11165 // For enum types in C code, use the underlying datatype.
11166 if (const auto *ED = T->getAsEnumDecl())
11167 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11168 } else if (auto *Enum = T->getAsEnumDecl()) {
11169 // For enum types in C++, use the known bit width of the enumerators.
11170 // In C++11, enums can have a fixed underlying type. Use this type to
11171 // compute the range.
11172 if (Enum->isFixed()) {
11173 return IntRange(C.getIntWidth(QualType(T, 0)),
11174 !Enum->getIntegerType()->isSignedIntegerType());
11175 }
11176
11177 unsigned NumPositive = Enum->getNumPositiveBits();
11178 unsigned NumNegative = Enum->getNumNegativeBits();
11179
11180 if (NumNegative == 0)
11181 return IntRange(NumPositive, true/*NonNegative*/);
11182 else
11183 return IntRange(std::max(NumPositive + 1, NumNegative),
11184 false/*NonNegative*/);
11185 }
11186
11187 if (const auto *EIT = dyn_cast<BitIntType>(T))
11188 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11189
11190 const BuiltinType *BT = cast<BuiltinType>(T);
11191 assert(BT->isInteger());
11192
11193 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11194 }
11195
11196 /// Returns the "target" range of a canonical integral type, i.e.
11197 /// the range of values expressible in the type.
11198 ///
11199 /// This matches forValueOfCanonicalType except that enums have the
11200 /// full range of their type, not the range of their enumerators.
11201 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11202 assert(T->isCanonicalUnqualified());
11203
11204 if (const VectorType *VT = dyn_cast<VectorType>(T))
11205 T = VT->getElementType().getTypePtr();
11206 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11207 T = CT->getElementType().getTypePtr();
11208 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11209 T = AT->getValueType().getTypePtr();
11210 if (const auto *ED = T->getAsEnumDecl())
11211 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11212
11213 if (const auto *EIT = dyn_cast<BitIntType>(T))
11214 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11215
11216 const BuiltinType *BT = cast<BuiltinType>(T);
11217 assert(BT->isInteger());
11218
11219 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11220 }
11221
11222 /// Returns the supremum of two ranges: i.e. their conservative merge.
11223 static IntRange join(IntRange L, IntRange R) {
11224 bool Unsigned = L.NonNegative && R.NonNegative;
11225 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11226 L.NonNegative && R.NonNegative);
11227 }
11228
11229 /// Return the range of a bitwise-AND of the two ranges.
11230 static IntRange bit_and(IntRange L, IntRange R) {
11231 unsigned Bits = std::max(L.Width, R.Width);
11232 bool NonNegative = false;
11233 if (L.NonNegative) {
11234 Bits = std::min(Bits, L.Width);
11235 NonNegative = true;
11236 }
11237 if (R.NonNegative) {
11238 Bits = std::min(Bits, R.Width);
11239 NonNegative = true;
11240 }
11241 return IntRange(Bits, NonNegative);
11242 }
11243
11244 /// Return the range of a sum of the two ranges.
11245 static IntRange sum(IntRange L, IntRange R) {
11246 bool Unsigned = L.NonNegative && R.NonNegative;
11247 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11248 Unsigned);
11249 }
11250
11251 /// Return the range of a difference of the two ranges.
11252 static IntRange difference(IntRange L, IntRange R) {
11253 // We need a 1-bit-wider range if:
11254 // 1) LHS can be negative: least value can be reduced.
11255 // 2) RHS can be negative: greatest value can be increased.
11256 bool CanWiden = !L.NonNegative || !R.NonNegative;
11257 bool Unsigned = L.NonNegative && R.Width == 0;
11258 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11259 !Unsigned,
11260 Unsigned);
11261 }
11262
11263 /// Return the range of a product of the two ranges.
11264 static IntRange product(IntRange L, IntRange R) {
11265 // If both LHS and RHS can be negative, we can form
11266 // -2^L * -2^R = 2^(L + R)
11267 // which requires L + R + 1 value bits to represent.
11268 bool CanWiden = !L.NonNegative && !R.NonNegative;
11269 bool Unsigned = L.NonNegative && R.NonNegative;
11270 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11271 Unsigned);
11272 }
11273
11274 /// Return the range of a remainder operation between the two ranges.
11275 static IntRange rem(IntRange L, IntRange R) {
11276 // The result of a remainder can't be larger than the result of
11277 // either side. The sign of the result is the sign of the LHS.
11278 bool Unsigned = L.NonNegative;
11279 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11280 Unsigned);
11281 }
11282};
11283
11284} // namespace
11285
11286static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11287 if (value.isSigned() && value.isNegative())
11288 return IntRange(value.getSignificantBits(), false);
11289
11290 if (value.getBitWidth() > MaxWidth)
11291 value = value.trunc(MaxWidth);
11292
11293 // isNonNegative() just checks the sign bit without considering
11294 // signedness.
11295 return IntRange(value.getActiveBits(), true);
11296}
11297
11298static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11299 if (result.isInt())
11300 return GetValueRange(result.getInt(), MaxWidth);
11301
11302 if (result.isVector()) {
11303 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11304 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11305 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11306 R = IntRange::join(R, El);
11307 }
11308 return R;
11309 }
11310
11311 if (result.isComplexInt()) {
11312 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11313 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11314 return IntRange::join(R, I);
11315 }
11316
11317 // This can happen with lossless casts to intptr_t of "based" lvalues.
11318 // Assume it might use arbitrary bits.
11319 // FIXME: The only reason we need to pass the type in here is to get
11320 // the sign right on this one case. It would be nice if APValue
11321 // preserved this.
11322 assert(result.isLValue() || result.isAddrLabelDiff());
11323 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11324}
11325
11326static QualType GetExprType(const Expr *E) {
11327 QualType Ty = E->getType();
11328 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11329 Ty = AtomicRHS->getValueType();
11330 return Ty;
11331}
11332
11333/// Attempts to estimate an approximate range for the given integer expression.
11334/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11335/// reliable estimation cannot be determined.
11336///
11337/// \param MaxWidth The width to which the value will be truncated.
11338/// \param InConstantContext If \c true, interpret the expression within a
11339/// constant context.
11340/// \param Approximate If \c true, provide a likely range of values by assuming
11341/// that arithmetic on narrower types remains within those types.
11342/// If \c false, return a range that includes all possible values
11343/// resulting from the expression.
11344/// \returns A range of values that the expression might take, or
11345/// std::nullopt if a reliable estimation cannot be determined.
11346static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11347 unsigned MaxWidth,
11348 bool InConstantContext,
11349 bool Approximate) {
11350 E = E->IgnoreParens();
11351
11352 // Try a full evaluation first.
11353 Expr::EvalResult result;
11354 if (E->EvaluateAsRValue(result, C, InConstantContext))
11355 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11356
11357 // I think we only want to look through implicit casts here; if the
11358 // user has an explicit widening cast, we should treat the value as
11359 // being of the new, wider type.
11360 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11361 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11362 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11363 Approximate);
11364
11365 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11366
11367 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11368 CE->getCastKind() == CK_BooleanToSignedIntegral;
11369
11370 // Assume that non-integer casts can span the full range of the type.
11371 if (!isIntegerCast)
11372 return OutputTypeRange;
11373
11374 std::optional<IntRange> SubRange = TryGetExprRange(
11375 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11376 InConstantContext, Approximate);
11377 if (!SubRange)
11378 return std::nullopt;
11379
11380 // Bail out if the subexpr's range is as wide as the cast type.
11381 if (SubRange->Width >= OutputTypeRange.Width)
11382 return OutputTypeRange;
11383
11384 // Otherwise, we take the smaller width, and we're non-negative if
11385 // either the output type or the subexpr is.
11386 return IntRange(SubRange->Width,
11387 SubRange->NonNegative || OutputTypeRange.NonNegative);
11388 }
11389
11390 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11391 // If we can fold the condition, just take that operand.
11392 bool CondResult;
11393 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11394 return TryGetExprRange(
11395 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11396 InConstantContext, Approximate);
11397
11398 // Otherwise, conservatively merge.
11399 // TryGetExprRange requires an integer expression, but a throw expression
11400 // results in a void type.
11401 Expr *TrueExpr = CO->getTrueExpr();
11402 if (TrueExpr->getType()->isVoidType())
11403 return std::nullopt;
11404
11405 std::optional<IntRange> L =
11406 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11407 if (!L)
11408 return std::nullopt;
11409
11410 Expr *FalseExpr = CO->getFalseExpr();
11411 if (FalseExpr->getType()->isVoidType())
11412 return std::nullopt;
11413
11414 std::optional<IntRange> R =
11415 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11416 if (!R)
11417 return std::nullopt;
11418
11419 return IntRange::join(*L, *R);
11420 }
11421
11422 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11423 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11424
11425 switch (BO->getOpcode()) {
11426 case BO_Cmp:
11427 llvm_unreachable("builtin <=> should have class type");
11428
11429 // Boolean-valued operations are single-bit and positive.
11430 case BO_LAnd:
11431 case BO_LOr:
11432 case BO_LT:
11433 case BO_GT:
11434 case BO_LE:
11435 case BO_GE:
11436 case BO_EQ:
11437 case BO_NE:
11438 return IntRange::forBoolType();
11439
11440 // The type of the assignments is the type of the LHS, so the RHS
11441 // is not necessarily the same type.
11442 case BO_MulAssign:
11443 case BO_DivAssign:
11444 case BO_RemAssign:
11445 case BO_AddAssign:
11446 case BO_SubAssign:
11447 case BO_XorAssign:
11448 case BO_OrAssign:
11449 // TODO: bitfields?
11450 return IntRange::forValueOfType(C, GetExprType(E));
11451
11452 // Simple assignments just pass through the RHS, which will have
11453 // been coerced to the LHS type.
11454 case BO_Assign:
11455 // TODO: bitfields?
11456 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11457 Approximate);
11458
11459 // Operations with opaque sources are black-listed.
11460 case BO_PtrMemD:
11461 case BO_PtrMemI:
11462 return IntRange::forValueOfType(C, GetExprType(E));
11463
11464 // Bitwise-and uses the *infinum* of the two source ranges.
11465 case BO_And:
11466 case BO_AndAssign:
11467 Combine = IntRange::bit_and;
11468 break;
11469
11470 // Left shift gets black-listed based on a judgement call.
11471 case BO_Shl:
11472 // ...except that we want to treat '1 << (blah)' as logically
11473 // positive. It's an important idiom.
11474 if (IntegerLiteral *I
11475 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11476 if (I->getValue() == 1) {
11477 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11478 return IntRange(R.Width, /*NonNegative*/ true);
11479 }
11480 }
11481 [[fallthrough]];
11482
11483 case BO_ShlAssign:
11484 return IntRange::forValueOfType(C, GetExprType(E));
11485
11486 // Right shift by a constant can narrow its left argument.
11487 case BO_Shr:
11488 case BO_ShrAssign: {
11489 std::optional<IntRange> L = TryGetExprRange(
11490 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11491 if (!L)
11492 return std::nullopt;
11493
11494 // If the shift amount is a positive constant, drop the width by
11495 // that much.
11496 if (std::optional<llvm::APSInt> shift =
11497 BO->getRHS()->getIntegerConstantExpr(C)) {
11498 if (shift->isNonNegative()) {
11499 if (shift->uge(L->Width))
11500 L->Width = (L->NonNegative ? 0 : 1);
11501 else
11502 L->Width -= shift->getZExtValue();
11503 }
11504 }
11505
11506 return L;
11507 }
11508
11509 // Comma acts as its right operand.
11510 case BO_Comma:
11511 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11512 Approximate);
11513
11514 case BO_Add:
11515 if (!Approximate)
11516 Combine = IntRange::sum;
11517 break;
11518
11519 case BO_Sub:
11520 if (BO->getLHS()->getType()->isPointerType())
11521 return IntRange::forValueOfType(C, GetExprType(E));
11522 if (!Approximate)
11523 Combine = IntRange::difference;
11524 break;
11525
11526 case BO_Mul:
11527 if (!Approximate)
11528 Combine = IntRange::product;
11529 break;
11530
11531 // The width of a division result is mostly determined by the size
11532 // of the LHS.
11533 case BO_Div: {
11534 // Don't 'pre-truncate' the operands.
11535 unsigned opWidth = C.getIntWidth(GetExprType(E));
11536 std::optional<IntRange> L = TryGetExprRange(
11537 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11538 if (!L)
11539 return std::nullopt;
11540
11541 // If the divisor is constant, use that.
11542 if (std::optional<llvm::APSInt> divisor =
11543 BO->getRHS()->getIntegerConstantExpr(C)) {
11544 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11545 if (log2 >= L->Width)
11546 L->Width = (L->NonNegative ? 0 : 1);
11547 else
11548 L->Width = std::min(L->Width - log2, MaxWidth);
11549 return L;
11550 }
11551
11552 // Otherwise, just use the LHS's width.
11553 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11554 // could be -1.
11555 std::optional<IntRange> R = TryGetExprRange(
11556 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11557 if (!R)
11558 return std::nullopt;
11559
11560 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11561 }
11562
11563 case BO_Rem:
11564 Combine = IntRange::rem;
11565 break;
11566
11567 // The default behavior is okay for these.
11568 case BO_Xor:
11569 case BO_Or:
11570 break;
11571 }
11572
11573 // Combine the two ranges, but limit the result to the type in which we
11574 // performed the computation.
11575 QualType T = GetExprType(E);
11576 unsigned opWidth = C.getIntWidth(T);
11577 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11578 InConstantContext, Approximate);
11579 if (!L)
11580 return std::nullopt;
11581
11582 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11583 InConstantContext, Approximate);
11584 if (!R)
11585 return std::nullopt;
11586
11587 IntRange C = Combine(*L, *R);
11588 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11589 C.Width = std::min(C.Width, MaxWidth);
11590 return C;
11591 }
11592
11593 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11594 switch (UO->getOpcode()) {
11595 // Boolean-valued operations are white-listed.
11596 case UO_LNot:
11597 return IntRange::forBoolType();
11598
11599 // Operations with opaque sources are black-listed.
11600 case UO_Deref:
11601 case UO_AddrOf: // should be impossible
11602 return IntRange::forValueOfType(C, GetExprType(E));
11603
11604 case UO_Minus: {
11605 if (E->getType()->isUnsignedIntegerType()) {
11606 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11607 Approximate);
11608 }
11609
11610 std::optional<IntRange> SubRange = TryGetExprRange(
11611 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11612
11613 if (!SubRange)
11614 return std::nullopt;
11615
11616 // If the range was previously non-negative, we need an extra bit for the
11617 // sign bit. Otherwise, we need an extra bit because the negation of the
11618 // most-negative value is one bit wider than that value.
11619 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11620 }
11621
11622 case UO_Not: {
11623 if (E->getType()->isUnsignedIntegerType()) {
11624 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11625 Approximate);
11626 }
11627
11628 std::optional<IntRange> SubRange = TryGetExprRange(
11629 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11630
11631 if (!SubRange)
11632 return std::nullopt;
11633
11634 // The width increments by 1 if the sub-expression cannot be negative
11635 // since it now can be.
11636 return IntRange(
11637 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11638 false);
11639 }
11640
11641 default:
11642 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11643 Approximate);
11644 }
11645 }
11646
11647 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11648 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11649 Approximate);
11650
11651 if (const auto *BitField = E->getSourceBitField())
11652 return IntRange(BitField->getBitWidthValue(),
11653 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11654
11655 if (GetExprType(E)->isVoidType())
11656 return std::nullopt;
11657
11658 return IntRange::forValueOfType(C, GetExprType(E));
11659}
11660
11661static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11662 bool InConstantContext,
11663 bool Approximate) {
11664 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11665 Approximate);
11666}
11667
11668/// Checks whether the given value, which currently has the given
11669/// source semantics, has the same value when coerced through the
11670/// target semantics.
11671static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11672 const llvm::fltSemantics &Src,
11673 const llvm::fltSemantics &Tgt) {
11674 llvm::APFloat truncated = value;
11675
11676 bool ignored;
11677 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11678 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11679
11680 return truncated.bitwiseIsEqual(value);
11681}
11682
11683/// Checks whether the given value, which currently has the given
11684/// source semantics, has the same value when coerced through the
11685/// target semantics.
11686///
11687/// The value might be a vector of floats (or a complex number).
11688static bool IsSameFloatAfterCast(const APValue &value,
11689 const llvm::fltSemantics &Src,
11690 const llvm::fltSemantics &Tgt) {
11691 if (value.isFloat())
11692 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11693
11694 if (value.isVector()) {
11695 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11696 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11697 return false;
11698 return true;
11699 }
11700
11701 assert(value.isComplexFloat());
11702 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11703 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11704}
11705
11706static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11707 bool IsListInit = false);
11708
11709static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11710 // Suppress cases where we are comparing against an enum constant.
11711 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11712 if (isa<EnumConstantDecl>(DR->getDecl()))
11713 return true;
11714
11715 // Suppress cases where the value is expanded from a macro, unless that macro
11716 // is how a language represents a boolean literal. This is the case in both C
11717 // and Objective-C.
11718 SourceLocation BeginLoc = E->getBeginLoc();
11719 if (BeginLoc.isMacroID()) {
11720 StringRef MacroName = Lexer::getImmediateMacroName(
11721 BeginLoc, S.getSourceManager(), S.getLangOpts());
11722 return MacroName != "YES" && MacroName != "NO" &&
11723 MacroName != "true" && MacroName != "false";
11724 }
11725
11726 return false;
11727}
11728
11729static bool isKnownToHaveUnsignedValue(const Expr *E) {
11730 return E->getType()->isIntegerType() &&
11731 (!E->getType()->isSignedIntegerType() ||
11733}
11734
11735namespace {
11736/// The promoted range of values of a type. In general this has the
11737/// following structure:
11738///
11739/// |-----------| . . . |-----------|
11740/// ^ ^ ^ ^
11741/// Min HoleMin HoleMax Max
11742///
11743/// ... where there is only a hole if a signed type is promoted to unsigned
11744/// (in which case Min and Max are the smallest and largest representable
11745/// values).
11746struct PromotedRange {
11747 // Min, or HoleMax if there is a hole.
11748 llvm::APSInt PromotedMin;
11749 // Max, or HoleMin if there is a hole.
11750 llvm::APSInt PromotedMax;
11751
11752 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11753 if (R.Width == 0)
11754 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11755 else if (R.Width >= BitWidth && !Unsigned) {
11756 // Promotion made the type *narrower*. This happens when promoting
11757 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11758 // Treat all values of 'signed int' as being in range for now.
11759 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11760 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11761 } else {
11762 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11763 .extOrTrunc(BitWidth);
11764 PromotedMin.setIsUnsigned(Unsigned);
11765
11766 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11767 .extOrTrunc(BitWidth);
11768 PromotedMax.setIsUnsigned(Unsigned);
11769 }
11770 }
11771
11772 // Determine whether this range is contiguous (has no hole).
11773 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11774
11775 // Where a constant value is within the range.
11776 enum ComparisonResult {
11777 LT = 0x1,
11778 LE = 0x2,
11779 GT = 0x4,
11780 GE = 0x8,
11781 EQ = 0x10,
11782 NE = 0x20,
11783 InRangeFlag = 0x40,
11784
11785 Less = LE | LT | NE,
11786 Min = LE | InRangeFlag,
11787 InRange = InRangeFlag,
11788 Max = GE | InRangeFlag,
11789 Greater = GE | GT | NE,
11790
11791 OnlyValue = LE | GE | EQ | InRangeFlag,
11792 InHole = NE
11793 };
11794
11795 ComparisonResult compare(const llvm::APSInt &Value) const {
11796 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11797 Value.isUnsigned() == PromotedMin.isUnsigned());
11798 if (!isContiguous()) {
11799 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11800 if (Value.isMinValue()) return Min;
11801 if (Value.isMaxValue()) return Max;
11802 if (Value >= PromotedMin) return InRange;
11803 if (Value <= PromotedMax) return InRange;
11804 return InHole;
11805 }
11806
11807 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11808 case -1: return Less;
11809 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11810 case 1:
11811 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11812 case -1: return InRange;
11813 case 0: return Max;
11814 case 1: return Greater;
11815 }
11816 }
11817
11818 llvm_unreachable("impossible compare result");
11819 }
11820
11821 static std::optional<StringRef>
11822 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11823 if (Op == BO_Cmp) {
11824 ComparisonResult LTFlag = LT, GTFlag = GT;
11825 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11826
11827 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11828 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11829 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11830 return std::nullopt;
11831 }
11832
11833 ComparisonResult TrueFlag, FalseFlag;
11834 if (Op == BO_EQ) {
11835 TrueFlag = EQ;
11836 FalseFlag = NE;
11837 } else if (Op == BO_NE) {
11838 TrueFlag = NE;
11839 FalseFlag = EQ;
11840 } else {
11841 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11842 TrueFlag = LT;
11843 FalseFlag = GE;
11844 } else {
11845 TrueFlag = GT;
11846 FalseFlag = LE;
11847 }
11848 if (Op == BO_GE || Op == BO_LE)
11849 std::swap(TrueFlag, FalseFlag);
11850 }
11851 if (R & TrueFlag)
11852 return StringRef("true");
11853 if (R & FalseFlag)
11854 return StringRef("false");
11855 return std::nullopt;
11856 }
11857};
11858}
11859
11860static bool HasEnumType(const Expr *E) {
11861 // Strip off implicit integral promotions.
11862 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11863 if (ICE->getCastKind() != CK_IntegralCast &&
11864 ICE->getCastKind() != CK_NoOp)
11865 break;
11866 E = ICE->getSubExpr();
11867 }
11868
11869 return E->getType()->isEnumeralType();
11870}
11871
11872static int classifyConstantValue(Expr *Constant) {
11873 // The values of this enumeration are used in the diagnostics
11874 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11875 enum ConstantValueKind {
11876 Miscellaneous = 0,
11877 LiteralTrue,
11878 LiteralFalse
11879 };
11880 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11881 return BL->getValue() ? ConstantValueKind::LiteralTrue
11882 : ConstantValueKind::LiteralFalse;
11883 return ConstantValueKind::Miscellaneous;
11884}
11885
11887 Expr *Constant, Expr *Other,
11888 const llvm::APSInt &Value,
11889 bool RhsConstant) {
11891 return false;
11892
11893 Expr *OriginalOther = Other;
11894
11895 Constant = Constant->IgnoreParenImpCasts();
11896 Other = Other->IgnoreParenImpCasts();
11897
11898 // Suppress warnings on tautological comparisons between values of the same
11899 // enumeration type. There are only two ways we could warn on this:
11900 // - If the constant is outside the range of representable values of
11901 // the enumeration. In such a case, we should warn about the cast
11902 // to enumeration type, not about the comparison.
11903 // - If the constant is the maximum / minimum in-range value. For an
11904 // enumeratin type, such comparisons can be meaningful and useful.
11905 if (Constant->getType()->isEnumeralType() &&
11906 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11907 return false;
11908
11909 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11910 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11911 if (!OtherValueRange)
11912 return false;
11913
11914 QualType OtherT = Other->getType();
11915 if (const auto *AT = OtherT->getAs<AtomicType>())
11916 OtherT = AT->getValueType();
11917 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11918
11919 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11920 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11921 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11922 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11923 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11924
11925 // Whether we're treating Other as being a bool because of the form of
11926 // expression despite it having another type (typically 'int' in C).
11927 bool OtherIsBooleanDespiteType =
11928 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11929 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11930 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11931
11932 // Check if all values in the range of possible values of this expression
11933 // lead to the same comparison outcome.
11934 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11935 Value.isUnsigned());
11936 auto Cmp = OtherPromotedValueRange.compare(Value);
11937 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11938 if (!Result)
11939 return false;
11940
11941 // Also consider the range determined by the type alone. This allows us to
11942 // classify the warning under the proper diagnostic group.
11943 bool TautologicalTypeCompare = false;
11944 {
11945 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11946 Value.isUnsigned());
11947 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11948 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11949 RhsConstant)) {
11950 TautologicalTypeCompare = true;
11951 Cmp = TypeCmp;
11952 Result = TypeResult;
11953 }
11954 }
11955
11956 // Don't warn if the non-constant operand actually always evaluates to the
11957 // same value.
11958 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11959 return false;
11960
11961 // Suppress the diagnostic for an in-range comparison if the constant comes
11962 // from a macro or enumerator. We don't want to diagnose
11963 //
11964 // some_long_value <= INT_MAX
11965 //
11966 // when sizeof(int) == sizeof(long).
11967 bool InRange = Cmp & PromotedRange::InRangeFlag;
11968 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11969 return false;
11970
11971 // A comparison of an unsigned bit-field against 0 is really a type problem,
11972 // even though at the type level the bit-field might promote to 'signed int'.
11973 if (Other->refersToBitField() && InRange && Value == 0 &&
11974 Other->getType()->isUnsignedIntegerOrEnumerationType())
11975 TautologicalTypeCompare = true;
11976
11977 // If this is a comparison to an enum constant, include that
11978 // constant in the diagnostic.
11979 const EnumConstantDecl *ED = nullptr;
11980 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11981 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11982
11983 // Should be enough for uint128 (39 decimal digits)
11984 SmallString<64> PrettySourceValue;
11985 llvm::raw_svector_ostream OS(PrettySourceValue);
11986 if (ED) {
11987 OS << '\'' << *ED << "' (" << Value << ")";
11988 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11989 Constant->IgnoreParenImpCasts())) {
11990 OS << (BL->getValue() ? "YES" : "NO");
11991 } else {
11992 OS << Value;
11993 }
11994
11995 if (!TautologicalTypeCompare) {
11996 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11997 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11998 << E->getOpcodeStr() << OS.str() << *Result
11999 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12000 return true;
12001 }
12002
12003 if (IsObjCSignedCharBool) {
12005 S.PDiag(diag::warn_tautological_compare_objc_bool)
12006 << OS.str() << *Result);
12007 return true;
12008 }
12009
12010 // FIXME: We use a somewhat different formatting for the in-range cases and
12011 // cases involving boolean values for historical reasons. We should pick a
12012 // consistent way of presenting these diagnostics.
12013 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12014
12016 E->getOperatorLoc(), E,
12017 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12018 : diag::warn_tautological_bool_compare)
12019 << OS.str() << classifyConstantValue(Constant) << OtherT
12020 << OtherIsBooleanDespiteType << *Result
12021 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12022 } else {
12023 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12024 unsigned Diag =
12025 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12026 ? (HasEnumType(OriginalOther)
12027 ? diag::warn_unsigned_enum_always_true_comparison
12028 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12029 : diag::warn_unsigned_always_true_comparison)
12030 : diag::warn_tautological_constant_compare;
12031
12032 S.Diag(E->getOperatorLoc(), Diag)
12033 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12034 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12035 }
12036
12037 return true;
12038}
12039
12040/// Analyze the operands of the given comparison. Implements the
12041/// fallback case from AnalyzeComparison.
12046
12047/// Implements -Wsign-compare.
12048///
12049/// \param E the binary operator to check for warnings
12051 // The type the comparison is being performed in.
12052 QualType T = E->getLHS()->getType();
12053
12054 // Only analyze comparison operators where both sides have been converted to
12055 // the same type.
12057 return AnalyzeImpConvsInComparison(S, E);
12058
12059 // Don't analyze value-dependent comparisons directly.
12060 if (E->isValueDependent())
12061 return AnalyzeImpConvsInComparison(S, E);
12062
12063 Expr *LHS = E->getLHS();
12064 Expr *RHS = E->getRHS();
12065
12066 if (T->isIntegralType(S.Context)) {
12067 std::optional<llvm::APSInt> RHSValue =
12069 std::optional<llvm::APSInt> LHSValue =
12071
12072 // We don't care about expressions whose result is a constant.
12073 if (RHSValue && LHSValue)
12074 return AnalyzeImpConvsInComparison(S, E);
12075
12076 // We only care about expressions where just one side is literal
12077 if ((bool)RHSValue ^ (bool)LHSValue) {
12078 // Is the constant on the RHS or LHS?
12079 const bool RhsConstant = (bool)RHSValue;
12080 Expr *Const = RhsConstant ? RHS : LHS;
12081 Expr *Other = RhsConstant ? LHS : RHS;
12082 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12083
12084 // Check whether an integer constant comparison results in a value
12085 // of 'true' or 'false'.
12086 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12087 return AnalyzeImpConvsInComparison(S, E);
12088 }
12089 }
12090
12091 if (!T->hasUnsignedIntegerRepresentation()) {
12092 // We don't do anything special if this isn't an unsigned integral
12093 // comparison: we're only interested in integral comparisons, and
12094 // signed comparisons only happen in cases we don't care to warn about.
12095 return AnalyzeImpConvsInComparison(S, E);
12096 }
12097
12098 LHS = LHS->IgnoreParenImpCasts();
12099 RHS = RHS->IgnoreParenImpCasts();
12100
12101 if (!S.getLangOpts().CPlusPlus) {
12102 // Avoid warning about comparison of integers with different signs when
12103 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12104 // the type of `E`.
12105 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12106 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12107 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12108 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12109 }
12110
12111 // Check to see if one of the (unmodified) operands is of different
12112 // signedness.
12113 Expr *signedOperand, *unsignedOperand;
12115 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12116 "unsigned comparison between two signed integer expressions?");
12117 signedOperand = LHS;
12118 unsignedOperand = RHS;
12119 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12120 signedOperand = RHS;
12121 unsignedOperand = LHS;
12122 } else {
12123 return AnalyzeImpConvsInComparison(S, E);
12124 }
12125
12126 // Otherwise, calculate the effective range of the signed operand.
12127 std::optional<IntRange> signedRange =
12129 /*Approximate=*/true);
12130 if (!signedRange)
12131 return;
12132
12133 // Go ahead and analyze implicit conversions in the operands. Note
12134 // that we skip the implicit conversions on both sides.
12137
12138 // If the signed range is non-negative, -Wsign-compare won't fire.
12139 if (signedRange->NonNegative)
12140 return;
12141
12142 // For (in)equality comparisons, if the unsigned operand is a
12143 // constant which cannot collide with a overflowed signed operand,
12144 // then reinterpreting the signed operand as unsigned will not
12145 // change the result of the comparison.
12146 if (E->isEqualityOp()) {
12147 unsigned comparisonWidth = S.Context.getIntWidth(T);
12148 std::optional<IntRange> unsignedRange = TryGetExprRange(
12149 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12150 /*Approximate=*/true);
12151 if (!unsignedRange)
12152 return;
12153
12154 // We should never be unable to prove that the unsigned operand is
12155 // non-negative.
12156 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12157
12158 if (unsignedRange->Width < comparisonWidth)
12159 return;
12160 }
12161
12163 S.PDiag(diag::warn_mixed_sign_comparison)
12164 << LHS->getType() << RHS->getType()
12165 << LHS->getSourceRange() << RHS->getSourceRange());
12166}
12167
12168/// Analyzes an attempt to assign the given value to a bitfield.
12169///
12170/// Returns true if there was something fishy about the attempt.
12172 SourceLocation InitLoc) {
12173 assert(Bitfield->isBitField());
12174 if (Bitfield->isInvalidDecl())
12175 return false;
12176
12177 // White-list bool bitfields.
12178 QualType BitfieldType = Bitfield->getType();
12179 if (BitfieldType->isBooleanType())
12180 return false;
12181
12182 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12183 // If the underlying enum type was not explicitly specified as an unsigned
12184 // type and the enum contain only positive values, MSVC++ will cause an
12185 // inconsistency by storing this as a signed type.
12186 if (S.getLangOpts().CPlusPlus11 &&
12187 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12188 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12189 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12190 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12191 << BitfieldEnumDecl;
12192 }
12193 }
12194
12195 // Ignore value- or type-dependent expressions.
12196 if (Bitfield->getBitWidth()->isValueDependent() ||
12197 Bitfield->getBitWidth()->isTypeDependent() ||
12198 Init->isValueDependent() ||
12199 Init->isTypeDependent())
12200 return false;
12201
12202 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12203 unsigned FieldWidth = Bitfield->getBitWidthValue();
12204
12205 Expr::EvalResult Result;
12206 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12208 // The RHS is not constant. If the RHS has an enum type, make sure the
12209 // bitfield is wide enough to hold all the values of the enum without
12210 // truncation.
12211 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12212 const PreferredTypeAttr *PTAttr = nullptr;
12213 if (!ED) {
12214 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12215 if (PTAttr)
12216 ED = PTAttr->getType()->getAsEnumDecl();
12217 }
12218 if (ED) {
12219 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12220
12221 // Enum types are implicitly signed on Windows, so check if there are any
12222 // negative enumerators to see if the enum was intended to be signed or
12223 // not.
12224 bool SignedEnum = ED->getNumNegativeBits() > 0;
12225
12226 // Check for surprising sign changes when assigning enum values to a
12227 // bitfield of different signedness. If the bitfield is signed and we
12228 // have exactly the right number of bits to store this unsigned enum,
12229 // suggest changing the enum to an unsigned type. This typically happens
12230 // on Windows where unfixed enums always use an underlying type of 'int'.
12231 unsigned DiagID = 0;
12232 if (SignedEnum && !SignedBitfield) {
12233 DiagID =
12234 PTAttr == nullptr
12235 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12236 : diag::
12237 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12238 } else if (SignedBitfield && !SignedEnum &&
12239 ED->getNumPositiveBits() == FieldWidth) {
12240 DiagID =
12241 PTAttr == nullptr
12242 ? diag::warn_signed_bitfield_enum_conversion
12243 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12244 }
12245 if (DiagID) {
12246 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12247 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12248 SourceRange TypeRange =
12249 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12250 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12251 << SignedEnum << TypeRange;
12252 if (PTAttr)
12253 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12254 << ED;
12255 }
12256
12257 // Compute the required bitwidth. If the enum has negative values, we need
12258 // one more bit than the normal number of positive bits to represent the
12259 // sign bit.
12260 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12261 ED->getNumNegativeBits())
12262 : ED->getNumPositiveBits();
12263
12264 // Check the bitwidth.
12265 if (BitsNeeded > FieldWidth) {
12266 Expr *WidthExpr = Bitfield->getBitWidth();
12267 auto DiagID =
12268 PTAttr == nullptr
12269 ? diag::warn_bitfield_too_small_for_enum
12270 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12271 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12272 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12273 << BitsNeeded << ED << WidthExpr->getSourceRange();
12274 if (PTAttr)
12275 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12276 << ED;
12277 }
12278 }
12279
12280 return false;
12281 }
12282
12283 llvm::APSInt Value = Result.Val.getInt();
12284
12285 unsigned OriginalWidth = Value.getBitWidth();
12286
12287 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12288 // false positives where the user is demonstrating they intend to use the
12289 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12290 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12291 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12292 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12293 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12294 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12295 S.findMacroSpelling(MaybeMacroLoc, "true"))
12296 return false;
12297 }
12298
12299 if (!Value.isSigned() || Value.isNegative())
12300 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12301 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12302 OriginalWidth = Value.getSignificantBits();
12303
12304 if (OriginalWidth <= FieldWidth)
12305 return false;
12306
12307 // Compute the value which the bitfield will contain.
12308 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12309 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12310
12311 // Check whether the stored value is equal to the original value.
12312 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12313 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12314 return false;
12315
12316 std::string PrettyValue = toString(Value, 10);
12317 std::string PrettyTrunc = toString(TruncatedValue, 10);
12318
12319 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12320 ? diag::warn_impcast_single_bit_bitield_precision_constant
12321 : diag::warn_impcast_bitfield_precision_constant)
12322 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12323 << Init->getSourceRange();
12324
12325 return true;
12326}
12327
12328/// Analyze the given simple or compound assignment for warning-worthy
12329/// operations.
12331 // Just recurse on the LHS.
12333
12334 // We want to recurse on the RHS as normal unless we're assigning to
12335 // a bitfield.
12336 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12337 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12338 E->getOperatorLoc())) {
12339 // Recurse, ignoring any implicit conversions on the RHS.
12341 E->getOperatorLoc());
12342 }
12343 }
12344
12346
12347 // Diagnose implicitly sequentially-consistent atomic assignment.
12348 if (E->getLHS()->getType()->isAtomicType())
12349 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12350}
12351
12352/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12353static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12354 QualType T, SourceLocation CContext, unsigned diag,
12355 bool PruneControlFlow = false) {
12356 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12357 // address space annotations isn't really useful. The warnings aren't because
12358 // you're converting a `private int` to `unsigned int`, it is because you're
12359 // conerting `int` to `unsigned int`.
12360 if (SourceType.hasAddressSpace())
12361 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12362 if (T.hasAddressSpace())
12364 if (PruneControlFlow) {
12366 S.PDiag(diag)
12367 << SourceType << T << E->getSourceRange()
12368 << SourceRange(CContext));
12369 return;
12370 }
12371 S.Diag(E->getExprLoc(), diag)
12372 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12373}
12374
12375/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12376static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12377 SourceLocation CContext, unsigned diag,
12378 bool PruneControlFlow = false) {
12379 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12380}
12381
12382/// Diagnose an implicit cast from a floating point value to an integer value.
12383static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12384 SourceLocation CContext) {
12385 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12386 bool PruneWarnings = S.inTemplateInstantiation();
12387
12388 const Expr *InnerE = E->IgnoreParenImpCasts();
12389 // We also want to warn on, e.g., "int i = -1.234"
12390 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12391 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12392 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12393
12394 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12395
12396 llvm::APFloat Value(0.0);
12397 bool IsConstant =
12399 if (!IsConstant) {
12400 if (S.ObjC().isSignedCharBool(T)) {
12402 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12403 << E->getType());
12404 }
12405
12406 return DiagnoseImpCast(S, E, T, CContext,
12407 diag::warn_impcast_float_integer, PruneWarnings);
12408 }
12409
12410 bool isExact = false;
12411
12412 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12413 T->hasUnsignedIntegerRepresentation());
12414 llvm::APFloat::opStatus Result = Value.convertToInteger(
12415 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12416
12417 // FIXME: Force the precision of the source value down so we don't print
12418 // digits which are usually useless (we don't really care here if we
12419 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12420 // would automatically print the shortest representation, but it's a bit
12421 // tricky to implement.
12422 SmallString<16> PrettySourceValue;
12423 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12424 precision = (precision * 59 + 195) / 196;
12425 Value.toString(PrettySourceValue, precision);
12426
12427 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12429 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12430 << PrettySourceValue);
12431 }
12432
12433 if (Result == llvm::APFloat::opOK && isExact) {
12434 if (IsLiteral) return;
12435 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12436 PruneWarnings);
12437 }
12438
12439 // Conversion of a floating-point value to a non-bool integer where the
12440 // integral part cannot be represented by the integer type is undefined.
12441 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12442 return DiagnoseImpCast(
12443 S, E, T, CContext,
12444 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12445 : diag::warn_impcast_float_to_integer_out_of_range,
12446 PruneWarnings);
12447
12448 unsigned DiagID = 0;
12449 if (IsLiteral) {
12450 // Warn on floating point literal to integer.
12451 DiagID = diag::warn_impcast_literal_float_to_integer;
12452 } else if (IntegerValue == 0) {
12453 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12454 return DiagnoseImpCast(S, E, T, CContext,
12455 diag::warn_impcast_float_integer, PruneWarnings);
12456 }
12457 // Warn on non-zero to zero conversion.
12458 DiagID = diag::warn_impcast_float_to_integer_zero;
12459 } else {
12460 if (IntegerValue.isUnsigned()) {
12461 if (!IntegerValue.isMaxValue()) {
12462 return DiagnoseImpCast(S, E, T, CContext,
12463 diag::warn_impcast_float_integer, PruneWarnings);
12464 }
12465 } else { // IntegerValue.isSigned()
12466 if (!IntegerValue.isMaxSignedValue() &&
12467 !IntegerValue.isMinSignedValue()) {
12468 return DiagnoseImpCast(S, E, T, CContext,
12469 diag::warn_impcast_float_integer, PruneWarnings);
12470 }
12471 }
12472 // Warn on evaluatable floating point expression to integer conversion.
12473 DiagID = diag::warn_impcast_float_to_integer;
12474 }
12475
12476 SmallString<16> PrettyTargetValue;
12477 if (IsBool)
12478 PrettyTargetValue = Value.isZero() ? "false" : "true";
12479 else
12480 IntegerValue.toString(PrettyTargetValue);
12481
12482 if (PruneWarnings) {
12484 S.PDiag(DiagID)
12485 << E->getType() << T.getUnqualifiedType()
12486 << PrettySourceValue << PrettyTargetValue
12487 << E->getSourceRange() << SourceRange(CContext));
12488 } else {
12489 S.Diag(E->getExprLoc(), DiagID)
12490 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12491 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12492 }
12493}
12494
12495/// Analyze the given compound assignment for the possible losing of
12496/// floating-point precision.
12498 assert(isa<CompoundAssignOperator>(E) &&
12499 "Must be compound assignment operation");
12500 // Recurse on the LHS and RHS in here
12503
12504 if (E->getLHS()->getType()->isAtomicType())
12505 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12506
12507 // Now check the outermost expression
12508 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12509 const auto *RBT = cast<CompoundAssignOperator>(E)
12510 ->getComputationResultType()
12511 ->getAs<BuiltinType>();
12512
12513 // The below checks assume source is floating point.
12514 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12515
12516 // If source is floating point but target is an integer.
12517 if (ResultBT->isInteger())
12518 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12519 E->getExprLoc(), diag::warn_impcast_float_integer);
12520
12521 if (!ResultBT->isFloatingPoint())
12522 return;
12523
12524 // If both source and target are floating points, warn about losing precision.
12526 QualType(ResultBT, 0), QualType(RBT, 0));
12527 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12528 // warn about dropping FP rank.
12529 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12530 diag::warn_impcast_float_result_precision);
12531}
12532
12533static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12534 IntRange Range) {
12535 if (!Range.Width) return "0";
12536
12537 llvm::APSInt ValueInRange = Value;
12538 ValueInRange.setIsSigned(!Range.NonNegative);
12539 ValueInRange = ValueInRange.trunc(Range.Width);
12540 return toString(ValueInRange, 10);
12541}
12542
12543static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12544 bool ToBool) {
12545 if (!isa<ImplicitCastExpr>(Ex))
12546 return false;
12547
12548 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12550 const Type *Source =
12552 if (Target->isDependentType())
12553 return false;
12554
12555 const auto *FloatCandidateBT =
12556 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12557 const Type *BoolCandidateType = ToBool ? Target : Source;
12558
12559 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12560 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12561}
12562
12563static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12564 SourceLocation CC) {
12565 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12566 const Expr *CurrA = TheCall->getArg(I);
12567 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12568 continue;
12569
12570 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12571 S, TheCall->getArg(I - 1), false));
12572 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12573 S, TheCall->getArg(I + 1), false));
12574 if (IsSwapped) {
12575 // Warn on this floating-point to bool conversion.
12577 CurrA->getType(), CC,
12578 diag::warn_impcast_floating_point_to_bool);
12579 }
12580 }
12581}
12582
12584 SourceLocation CC) {
12585 // Don't warn on functions which have return type nullptr_t.
12586 if (isa<CallExpr>(E))
12587 return;
12588
12589 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12590 const Expr *NewE = E->IgnoreParenImpCasts();
12591 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12592 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12593 if (!IsGNUNullExpr && !HasNullPtrType)
12594 return;
12595
12596 // Return if target type is a safe conversion.
12597 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12598 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12599 return;
12600
12601 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12602 E->getExprLoc()))
12603 return;
12604
12606
12607 // Venture through the macro stacks to get to the source of macro arguments.
12608 // The new location is a better location than the complete location that was
12609 // passed in.
12610 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12612
12613 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12614 if (IsGNUNullExpr && Loc.isMacroID()) {
12615 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12616 Loc, S.SourceMgr, S.getLangOpts());
12617 if (MacroName == "NULL")
12619 }
12620
12621 // Only warn if the null and context location are in the same macro expansion.
12622 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12623 return;
12624
12625 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12626 << HasNullPtrType << T << SourceRange(CC)
12629}
12630
12631// Helper function to filter out cases for constant width constant conversion.
12632// Don't warn on char array initialization or for non-decimal values.
12634 SourceLocation CC) {
12635 // If initializing from a constant, and the constant starts with '0',
12636 // then it is a binary, octal, or hexadecimal. Allow these constants
12637 // to fill all the bits, even if there is a sign change.
12638 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12639 const char FirstLiteralCharacter =
12640 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12641 if (FirstLiteralCharacter == '0')
12642 return false;
12643 }
12644
12645 // If the CC location points to a '{', and the type is char, then assume
12646 // assume it is an array initialization.
12647 if (CC.isValid() && T->isCharType()) {
12648 const char FirstContextCharacter =
12650 if (FirstContextCharacter == '{')
12651 return false;
12652 }
12653
12654 return true;
12655}
12656
12658 const auto *IL = dyn_cast<IntegerLiteral>(E);
12659 if (!IL) {
12660 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12661 if (UO->getOpcode() == UO_Minus)
12662 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12663 }
12664 }
12665
12666 return IL;
12667}
12668
12670 E = E->IgnoreParenImpCasts();
12671 SourceLocation ExprLoc = E->getExprLoc();
12672
12673 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12674 BinaryOperator::Opcode Opc = BO->getOpcode();
12675 Expr::EvalResult Result;
12676 // Do not diagnose unsigned shifts.
12677 if (Opc == BO_Shl) {
12678 const auto *LHS = getIntegerLiteral(BO->getLHS());
12679 const auto *RHS = getIntegerLiteral(BO->getRHS());
12680 if (LHS && LHS->getValue() == 0)
12681 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12682 else if (!E->isValueDependent() && LHS && RHS &&
12683 RHS->getValue().isNonNegative() &&
12685 S.Diag(ExprLoc, diag::warn_left_shift_always)
12686 << (Result.Val.getInt() != 0);
12687 else if (E->getType()->isSignedIntegerType())
12688 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12691 ") != 0");
12692 }
12693 }
12694
12695 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12696 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12697 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12698 if (!LHS || !RHS)
12699 return;
12700 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12701 (RHS->getValue() == 0 || RHS->getValue() == 1))
12702 // Do not diagnose common idioms.
12703 return;
12704 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12705 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12706 }
12707}
12708
12710 const Type *Target, Expr *E,
12711 QualType T,
12712 SourceLocation CC) {
12713 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12714 Source != Target);
12715
12716 // Lone surrogates have a distinct representation in UTF-32.
12717 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12718 // so don't warn on such conversion.
12719 if (Source->isChar16Type() && Target->isChar32Type())
12720 return;
12721
12722 Expr::EvalResult Result;
12725 llvm::APSInt Value(32);
12726 Value = Result.Val.getInt();
12727 bool IsASCII = Value <= 0x7F;
12728 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12729 bool ConversionPreservesSemantics =
12730 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12731
12732 if (!ConversionPreservesSemantics) {
12733 auto IsSingleCodeUnitCP = [](const QualType &T,
12734 const llvm::APSInt &Value) {
12735 if (T->isChar8Type())
12736 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12737 if (T->isChar16Type())
12738 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12739 assert(T->isChar32Type());
12740 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12741 };
12742
12743 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12744 << E->getType() << T
12745 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12746 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12747 }
12748 } else {
12749 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12751 DiagnoseImpCast(S, E, T, CC,
12752 LosesPrecision ? diag::warn_impcast_unicode_precision
12753 : diag::warn_impcast_unicode_char_type);
12754 }
12755}
12756
12758 From = Context.getCanonicalType(From);
12759 To = Context.getCanonicalType(To);
12760 QualType MaybePointee = From->getPointeeType();
12761 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12762 From = MaybePointee;
12763 MaybePointee = To->getPointeeType();
12764 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12765 To = MaybePointee;
12766
12767 if (const auto *FromFn = From->getAs<FunctionType>()) {
12768 if (const auto *ToFn = To->getAs<FunctionType>()) {
12769 if (FromFn->getCFIUncheckedCalleeAttr() &&
12770 !ToFn->getCFIUncheckedCalleeAttr())
12771 return true;
12772 }
12773 }
12774 return false;
12775}
12776
12778 bool *ICContext, bool IsListInit) {
12779 if (E->isTypeDependent() || E->isValueDependent()) return;
12780
12781 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12782 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12783 if (Source == Target) return;
12784 if (Target->isDependentType()) return;
12785
12786 // If the conversion context location is invalid don't complain. We also
12787 // don't want to emit a warning if the issue occurs from the expansion of
12788 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12789 // delay this check as long as possible. Once we detect we are in that
12790 // scenario, we just return.
12791 if (CC.isInvalid())
12792 return;
12793
12794 if (Source->isAtomicType())
12795 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12796
12797 // Diagnose implicit casts to bool.
12798 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12799 if (isa<StringLiteral>(E))
12800 // Warn on string literal to bool. Checks for string literals in logical
12801 // and expressions, for instance, assert(0 && "error here"), are
12802 // prevented by a check in AnalyzeImplicitConversions().
12803 return DiagnoseImpCast(*this, E, T, CC,
12804 diag::warn_impcast_string_literal_to_bool);
12807 // This covers the literal expressions that evaluate to Objective-C
12808 // objects.
12809 return DiagnoseImpCast(*this, E, T, CC,
12810 diag::warn_impcast_objective_c_literal_to_bool);
12811 }
12812 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12813 // Warn on pointer to bool conversion that is always true.
12815 SourceRange(CC));
12816 }
12817 }
12818
12819 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12820 // is a typedef for signed char (macOS), then that constant value has to be 1
12821 // or 0.
12822 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12825 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12827 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12828 << toString(Result.Val.getInt(), 10));
12829 }
12830 return;
12831 }
12832 }
12833
12834 // Check implicit casts from Objective-C collection literals to specialized
12835 // collection types, e.g., NSArray<NSString *> *.
12836 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12837 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12838 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12839 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12840
12841 // Strip vector types.
12842 if (isa<VectorType>(Source)) {
12843 if (Target->isSveVLSBuiltinType() &&
12844 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12845 QualType(Source, 0)) ||
12846 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12847 QualType(Source, 0))))
12848 return;
12849
12850 if (Target->isRVVVLSBuiltinType() &&
12851 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12852 QualType(Source, 0)) ||
12853 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12854 QualType(Source, 0))))
12855 return;
12856
12857 if (!isa<VectorType>(Target)) {
12858 if (SourceMgr.isInSystemMacro(CC))
12859 return;
12860 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12861 }
12862 if (getLangOpts().HLSL &&
12863 Target->castAs<VectorType>()->getNumElements() <
12864 Source->castAs<VectorType>()->getNumElements()) {
12865 // Diagnose vector truncation but don't return. We may also want to
12866 // diagnose an element conversion.
12867 DiagnoseImpCast(*this, E, T, CC,
12868 diag::warn_hlsl_impcast_vector_truncation);
12869 }
12870
12871 // If the vector cast is cast between two vectors of the same size, it is
12872 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12873 if (!getLangOpts().HLSL &&
12874 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12875 return;
12876
12877 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12878 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12879 }
12880 if (const auto *VecTy = dyn_cast<VectorType>(Target))
12881 Target = VecTy->getElementType().getTypePtr();
12882
12883 if (isa<ConstantMatrixType>(Source)) {
12884 if (Target->isScalarType())
12885 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
12886
12887 if (getLangOpts().HLSL &&
12889 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
12890 // Diagnose Matrix truncation but don't return. We may also want to
12891 // diagnose an element conversion.
12892 DiagnoseImpCast(*this, E, T, CC,
12893 diag::warn_hlsl_impcast_matrix_truncation);
12894 }
12895 }
12896 // Strip complex types.
12897 if (isa<ComplexType>(Source)) {
12898 if (!isa<ComplexType>(Target)) {
12899 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12900 return;
12901
12902 return DiagnoseImpCast(*this, E, T, CC,
12904 ? diag::err_impcast_complex_scalar
12905 : diag::warn_impcast_complex_scalar);
12906 }
12907
12908 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12909 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12910 }
12911
12912 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12913 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12914
12915 // Strip SVE vector types
12916 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12917 // Need the original target type for vector type checks
12918 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12919 // Handle conversion from scalable to fixed when msve-vector-bits is
12920 // specified
12921 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12922 QualType(Source, 0)) ||
12923 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12924 QualType(Source, 0)))
12925 return;
12926
12927 // If the vector cast is cast between two vectors of the same size, it is
12928 // a bitcast, not a conversion.
12929 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12930 return;
12931
12932 Source = SourceBT->getSveEltType(Context).getTypePtr();
12933 }
12934
12935 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12936 Target = TargetBT->getSveEltType(Context).getTypePtr();
12937
12938 // If the source is floating point...
12939 if (SourceBT && SourceBT->isFloatingPoint()) {
12940 // ...and the target is floating point...
12941 if (TargetBT && TargetBT->isFloatingPoint()) {
12942 // ...then warn if we're dropping FP rank.
12943
12945 QualType(SourceBT, 0), QualType(TargetBT, 0));
12946 if (Order > 0) {
12947 // Don't warn about float constants that are precisely
12948 // representable in the target type.
12949 Expr::EvalResult result;
12950 if (E->EvaluateAsRValue(result, Context)) {
12951 // Value might be a float, a float vector, or a float complex.
12953 result.Val,
12954 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12955 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12956 return;
12957 }
12958
12959 if (SourceMgr.isInSystemMacro(CC))
12960 return;
12961
12962 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12963 }
12964 // ... or possibly if we're increasing rank, too
12965 else if (Order < 0) {
12966 if (SourceMgr.isInSystemMacro(CC))
12967 return;
12968
12969 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12970 }
12971 return;
12972 }
12973
12974 // If the target is integral, always warn.
12975 if (TargetBT && TargetBT->isInteger()) {
12976 if (SourceMgr.isInSystemMacro(CC))
12977 return;
12978
12979 DiagnoseFloatingImpCast(*this, E, T, CC);
12980 }
12981
12982 // Detect the case where a call result is converted from floating-point to
12983 // to bool, and the final argument to the call is converted from bool, to
12984 // discover this typo:
12985 //
12986 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12987 //
12988 // FIXME: This is an incredibly special case; is there some more general
12989 // way to detect this class of misplaced-parentheses bug?
12990 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12991 // Check last argument of function call to see if it is an
12992 // implicit cast from a type matching the type the result
12993 // is being cast to.
12994 CallExpr *CEx = cast<CallExpr>(E);
12995 if (unsigned NumArgs = CEx->getNumArgs()) {
12996 Expr *LastA = CEx->getArg(NumArgs - 1);
12997 Expr *InnerE = LastA->IgnoreParenImpCasts();
12998 if (isa<ImplicitCastExpr>(LastA) &&
12999 InnerE->getType()->isBooleanType()) {
13000 // Warn on this floating-point to bool conversion
13001 DiagnoseImpCast(*this, E, T, CC,
13002 diag::warn_impcast_floating_point_to_bool);
13003 }
13004 }
13005 }
13006 return;
13007 }
13008
13009 // Valid casts involving fixed point types should be accounted for here.
13010 if (Source->isFixedPointType()) {
13011 if (Target->isUnsaturatedFixedPointType()) {
13015 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13016 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13017 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13018 if (Value > MaxVal || Value < MinVal) {
13020 PDiag(diag::warn_impcast_fixed_point_range)
13021 << Value.toString() << T
13022 << E->getSourceRange()
13023 << clang::SourceRange(CC));
13024 return;
13025 }
13026 }
13027 } else if (Target->isIntegerType()) {
13031 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13032
13033 bool Overflowed;
13034 llvm::APSInt IntResult = FXResult.convertToInt(
13035 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13036 &Overflowed);
13037
13038 if (Overflowed) {
13040 PDiag(diag::warn_impcast_fixed_point_range)
13041 << FXResult.toString() << T
13042 << E->getSourceRange()
13043 << clang::SourceRange(CC));
13044 return;
13045 }
13046 }
13047 }
13048 } else if (Target->isUnsaturatedFixedPointType()) {
13049 if (Source->isIntegerType()) {
13053 llvm::APSInt Value = Result.Val.getInt();
13054
13055 bool Overflowed;
13056 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13057 Value, Context.getFixedPointSemantics(T), &Overflowed);
13058
13059 if (Overflowed) {
13061 PDiag(diag::warn_impcast_fixed_point_range)
13062 << toString(Value, /*Radix=*/10) << T
13063 << E->getSourceRange()
13064 << clang::SourceRange(CC));
13065 return;
13066 }
13067 }
13068 }
13069 }
13070
13071 // If we are casting an integer type to a floating point type without
13072 // initialization-list syntax, we might lose accuracy if the floating
13073 // point type has a narrower significand than the integer type.
13074 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13075 TargetBT->isFloatingType() && !IsListInit) {
13076 // Determine the number of precision bits in the source integer type.
13077 std::optional<IntRange> SourceRange =
13079 /*Approximate=*/true);
13080 if (!SourceRange)
13081 return;
13082 unsigned int SourcePrecision = SourceRange->Width;
13083
13084 // Determine the number of precision bits in the
13085 // target floating point type.
13086 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13087 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13088
13089 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13090 SourcePrecision > TargetPrecision) {
13091
13092 if (std::optional<llvm::APSInt> SourceInt =
13094 // If the source integer is a constant, convert it to the target
13095 // floating point type. Issue a warning if the value changes
13096 // during the whole conversion.
13097 llvm::APFloat TargetFloatValue(
13098 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13099 llvm::APFloat::opStatus ConversionStatus =
13100 TargetFloatValue.convertFromAPInt(
13101 *SourceInt, SourceBT->isSignedInteger(),
13102 llvm::APFloat::rmNearestTiesToEven);
13103
13104 if (ConversionStatus != llvm::APFloat::opOK) {
13105 SmallString<32> PrettySourceValue;
13106 SourceInt->toString(PrettySourceValue, 10);
13107 SmallString<32> PrettyTargetValue;
13108 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13109
13111 E->getExprLoc(), E,
13112 PDiag(diag::warn_impcast_integer_float_precision_constant)
13113 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13114 << E->getSourceRange() << clang::SourceRange(CC));
13115 }
13116 } else {
13117 // Otherwise, the implicit conversion may lose precision.
13118 DiagnoseImpCast(*this, E, T, CC,
13119 diag::warn_impcast_integer_float_precision);
13120 }
13121 }
13122 }
13123
13124 DiagnoseNullConversion(*this, E, T, CC);
13125
13127
13128 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13129 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13130 return;
13131 }
13132
13133 if (Target->isBooleanType())
13134 DiagnoseIntInBoolContext(*this, E);
13135
13137 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13138 << QualType(Source, 0) << QualType(Target, 0);
13139 }
13140
13141 if (!Source->isIntegerType() || !Target->isIntegerType())
13142 return;
13143
13144 // TODO: remove this early return once the false positives for constant->bool
13145 // in templates, macros, etc, are reduced or removed.
13146 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13147 return;
13148
13149 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13150 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13152 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13153 << E->getType());
13154 }
13155 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13156 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13157 if (!LikelySourceRange)
13158 return;
13159
13160 IntRange SourceTypeRange =
13161 IntRange::forTargetOfCanonicalType(Context, Source);
13162 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13163
13164 if (LikelySourceRange->Width > TargetRange.Width) {
13165 // If the source is a constant, use a default-on diagnostic.
13166 // TODO: this should happen for bitfield stores, too.
13170 llvm::APSInt Value(32);
13171 Value = Result.Val.getInt();
13172
13173 if (SourceMgr.isInSystemMacro(CC))
13174 return;
13175
13176 std::string PrettySourceValue = toString(Value, 10);
13177 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13178
13180 PDiag(diag::warn_impcast_integer_precision_constant)
13181 << PrettySourceValue << PrettyTargetValue
13182 << E->getType() << T << E->getSourceRange()
13183 << SourceRange(CC));
13184 return;
13185 }
13186
13187 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13188 if (SourceMgr.isInSystemMacro(CC))
13189 return;
13190
13191 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13192 if (UO->getOpcode() == UO_Minus)
13193 return DiagnoseImpCast(
13194 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13195 }
13196
13197 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13198 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13199 /* pruneControlFlow */ true);
13200 return DiagnoseImpCast(*this, E, T, CC,
13201 diag::warn_impcast_integer_precision);
13202 }
13203
13204 if (TargetRange.Width > SourceTypeRange.Width) {
13205 if (auto *UO = dyn_cast<UnaryOperator>(E))
13206 if (UO->getOpcode() == UO_Minus)
13207 if (Source->isUnsignedIntegerType()) {
13208 if (Target->isUnsignedIntegerType())
13209 return DiagnoseImpCast(*this, E, T, CC,
13210 diag::warn_impcast_high_order_zero_bits);
13211 if (Target->isSignedIntegerType())
13212 return DiagnoseImpCast(*this, E, T, CC,
13213 diag::warn_impcast_nonnegative_result);
13214 }
13215 }
13216
13217 if (TargetRange.Width == LikelySourceRange->Width &&
13218 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13219 Source->isSignedIntegerType()) {
13220 // Warn when doing a signed to signed conversion, warn if the positive
13221 // source value is exactly the width of the target type, which will
13222 // cause a negative value to be stored.
13223
13226 !SourceMgr.isInSystemMacro(CC)) {
13227 llvm::APSInt Value = Result.Val.getInt();
13228 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13229 std::string PrettySourceValue = toString(Value, 10);
13230 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13231
13232 Diag(E->getExprLoc(),
13233 PDiag(diag::warn_impcast_integer_precision_constant)
13234 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13235 << E->getSourceRange() << SourceRange(CC));
13236 return;
13237 }
13238 }
13239
13240 // Fall through for non-constants to give a sign conversion warning.
13241 }
13242
13243 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13244 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13245 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13246 LikelySourceRange->Width == TargetRange.Width))) {
13247 if (SourceMgr.isInSystemMacro(CC))
13248 return;
13249
13250 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13251 TargetBT->isInteger() &&
13252 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13253 return;
13254 }
13255
13256 unsigned DiagID = diag::warn_impcast_integer_sign;
13257
13258 // Traditionally, gcc has warned about this under -Wsign-compare.
13259 // We also want to warn about it in -Wconversion.
13260 // So if -Wconversion is off, use a completely identical diagnostic
13261 // in the sign-compare group.
13262 // The conditional-checking code will
13263 if (ICContext) {
13264 DiagID = diag::warn_impcast_integer_sign_conditional;
13265 *ICContext = true;
13266 }
13267
13268 DiagnoseImpCast(*this, E, T, CC, DiagID);
13269 }
13270
13271 // If we're implicitly converting from an integer into an enumeration, that
13272 // is valid in C but invalid in C++.
13273 QualType SourceType = E->getEnumCoercedType(Context);
13274 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13275 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13276 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13277
13278 // Diagnose conversions between different enumeration types.
13279 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13280 // type, to give us better diagnostics.
13281 Source = Context.getCanonicalType(SourceType).getTypePtr();
13282
13283 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13284 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13285 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13286 TargetEnum->getDecl()->hasNameForLinkage() &&
13287 SourceEnum != TargetEnum) {
13288 if (SourceMgr.isInSystemMacro(CC))
13289 return;
13290
13291 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13292 diag::warn_impcast_different_enum_types);
13293 }
13294}
13295
13298
13300 SourceLocation CC, bool &ICContext) {
13301 E = E->IgnoreParenImpCasts();
13302 // Diagnose incomplete type for second or third operand in C.
13303 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13304 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13305
13306 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13307 return CheckConditionalOperator(S, CO, CC, T);
13308
13310 if (E->getType() != T)
13311 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13312}
13313
13317
13318 Expr *TrueExpr = E->getTrueExpr();
13319 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13320 TrueExpr = BCO->getCommon();
13321
13322 bool Suspicious = false;
13323 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13324 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13325
13326 if (T->isBooleanType())
13328
13329 // If -Wconversion would have warned about either of the candidates
13330 // for a signedness conversion to the context type...
13331 if (!Suspicious) return;
13332
13333 // ...but it's currently ignored...
13334 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13335 return;
13336
13337 // ...then check whether it would have warned about either of the
13338 // candidates for a signedness conversion to the condition type.
13339 if (E->getType() == T) return;
13340
13341 Suspicious = false;
13342 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13343 &Suspicious);
13344 if (!Suspicious)
13346 E->getType(), CC, &Suspicious);
13347}
13348
13349/// Check conversion of given expression to boolean.
13350/// Input argument E is a logical expression.
13352 // Run the bool-like conversion checks only for C since there bools are
13353 // still not used as the return type from "boolean" operators or as the input
13354 // type for conditional operators.
13355 if (S.getLangOpts().CPlusPlus)
13356 return;
13358 return;
13360}
13361
13362namespace {
13363struct AnalyzeImplicitConversionsWorkItem {
13364 Expr *E;
13365 SourceLocation CC;
13366 bool IsListInit;
13367};
13368}
13369
13371 Sema &S, Expr *E, QualType T, SourceLocation CC,
13372 bool ExtraCheckForImplicitConversion,
13374 E = E->IgnoreParenImpCasts();
13375 WorkList.push_back({E, CC, false});
13376
13377 if (ExtraCheckForImplicitConversion && E->getType() != T)
13378 S.CheckImplicitConversion(E, T, CC);
13379}
13380
13381/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13382/// that should be visited are added to WorkList.
13384 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13386 Expr *OrigE = Item.E;
13387 SourceLocation CC = Item.CC;
13388
13389 QualType T = OrigE->getType();
13390 Expr *E = OrigE->IgnoreParenImpCasts();
13391
13392 // Propagate whether we are in a C++ list initialization expression.
13393 // If so, we do not issue warnings for implicit int-float conversion
13394 // precision loss, because C++11 narrowing already handles it.
13395 //
13396 // HLSL's initialization lists are special, so they shouldn't observe the C++
13397 // behavior here.
13398 bool IsListInit =
13399 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13400 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13401
13402 if (E->isTypeDependent() || E->isValueDependent())
13403 return;
13404
13405 Expr *SourceExpr = E;
13406 // Examine, but don't traverse into the source expression of an
13407 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13408 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13409 // evaluate it in the context of checking the specific conversion to T though.
13410 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13411 if (auto *Src = OVE->getSourceExpr())
13412 SourceExpr = Src;
13413
13414 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13415 if (UO->getOpcode() == UO_Not &&
13416 UO->getSubExpr()->isKnownToHaveBooleanValue())
13417 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13418 << OrigE->getSourceRange() << T->isBooleanType()
13419 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13420
13421 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13422 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13423 BO->getLHS()->isKnownToHaveBooleanValue() &&
13424 BO->getRHS()->isKnownToHaveBooleanValue() &&
13425 BO->getLHS()->HasSideEffects(S.Context) &&
13426 BO->getRHS()->HasSideEffects(S.Context)) {
13428 const LangOptions &LO = S.getLangOpts();
13429 SourceLocation BLoc = BO->getOperatorLoc();
13430 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13431 StringRef SR = clang::Lexer::getSourceText(
13432 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13433 // To reduce false positives, only issue the diagnostic if the operator
13434 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13435 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13436 // in C, along with other macro spellings the user might invent.
13437 if (SR.str() == "&" || SR.str() == "|") {
13438
13439 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13440 << (BO->getOpcode() == BO_And ? "&" : "|")
13441 << OrigE->getSourceRange()
13443 BO->getOperatorLoc(),
13444 (BO->getOpcode() == BO_And ? "&&" : "||"));
13445 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13446 }
13447 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13448 /// Analyze the given comma operator. The basic idea behind the analysis
13449 /// is to analyze the left and right operands slightly differently. The
13450 /// left operand needs to check whether the operand itself has an implicit
13451 /// conversion, but not whether the left operand induces an implicit
13452 /// conversion for the entire comma expression itself. This is similar to
13453 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13454 /// were directly used for the implicit conversion check.
13455 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13456 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13457 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13458 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13459 return;
13460 }
13461 }
13462
13463 // For conditional operators, we analyze the arguments as if they
13464 // were being fed directly into the output.
13465 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13466 CheckConditionalOperator(S, CO, CC, T);
13467 return;
13468 }
13469
13470 // Check implicit argument conversions for function calls.
13471 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13473
13474 // Go ahead and check any implicit conversions we might have skipped.
13475 // The non-canonical typecheck is just an optimization;
13476 // CheckImplicitConversion will filter out dead implicit conversions.
13477 if (SourceExpr->getType() != T)
13478 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13479
13480 // Now continue drilling into this expression.
13481
13482 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13483 // The bound subexpressions in a PseudoObjectExpr are not reachable
13484 // as transitive children.
13485 // FIXME: Use a more uniform representation for this.
13486 for (auto *SE : POE->semantics())
13487 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13488 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13489 }
13490
13491 // Skip past explicit casts.
13492 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13493 E = CE->getSubExpr();
13494 // In the special case of a C++ function-style cast with braces,
13495 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13496 // initializer. This InitListExpr basically belongs to the cast itself, so
13497 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13499 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13500 if (InitListE->getNumInits() == 1) {
13501 E = InitListE->getInit(0);
13502 }
13503 }
13504 }
13505 E = E->IgnoreParenImpCasts();
13506 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13507 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13508 WorkList.push_back({E, CC, IsListInit});
13509 return;
13510 }
13511
13512 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13513 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13514 // The base expression is only used to initialize the parameter for
13515 // arguments to `inout` parameters, so we only traverse down the base
13516 // expression for `inout` cases.
13517 if (OutArgE->isInOut())
13518 WorkList.push_back(
13519 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13520 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13521 return;
13522 }
13523
13524 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13525 // Do a somewhat different check with comparison operators.
13526 if (BO->isComparisonOp())
13527 return AnalyzeComparison(S, BO);
13528
13529 // And with simple assignments.
13530 if (BO->getOpcode() == BO_Assign)
13531 return AnalyzeAssignment(S, BO);
13532 // And with compound assignments.
13533 if (BO->isAssignmentOp())
13534 return AnalyzeCompoundAssignment(S, BO);
13535 }
13536
13537 // These break the otherwise-useful invariant below. Fortunately,
13538 // we don't really need to recurse into them, because any internal
13539 // expressions should have been analyzed already when they were
13540 // built into statements.
13541 if (isa<StmtExpr>(E)) return;
13542
13543 // Don't descend into unevaluated contexts.
13544 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13545
13546 // Now just recurse over the expression's children.
13547 CC = E->getExprLoc();
13548 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13549 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13550 for (Stmt *SubStmt : E->children()) {
13551 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13552 if (!ChildExpr)
13553 continue;
13554
13555 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13556 if (ChildExpr == CSE->getOperand())
13557 // Do not recurse over a CoroutineSuspendExpr's operand.
13558 // The operand is also a subexpression of getCommonExpr(), and
13559 // recursing into it directly would produce duplicate diagnostics.
13560 continue;
13561
13562 if (IsLogicalAndOperator &&
13564 // Ignore checking string literals that are in logical and operators.
13565 // This is a common pattern for asserts.
13566 continue;
13567 WorkList.push_back({ChildExpr, CC, IsListInit});
13568 }
13569
13570 if (BO && BO->isLogicalOp()) {
13571 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13572 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13573 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13574
13575 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13576 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13577 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13578 }
13579
13580 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13581 if (U->getOpcode() == UO_LNot) {
13582 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13583 } else if (U->getOpcode() != UO_AddrOf) {
13584 if (U->getSubExpr()->getType()->isAtomicType())
13585 S.Diag(U->getSubExpr()->getBeginLoc(),
13586 diag::warn_atomic_implicit_seq_cst);
13587 }
13588 }
13589}
13590
13591/// AnalyzeImplicitConversions - Find and report any interesting
13592/// implicit conversions in the given expression. There are a couple
13593/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13595 bool IsListInit/*= false*/) {
13597 WorkList.push_back({OrigE, CC, IsListInit});
13598 while (!WorkList.empty())
13599 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13600}
13601
13602// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13603// Returns true when emitting a warning about taking the address of a reference.
13604static bool CheckForReference(Sema &SemaRef, const Expr *E,
13605 const PartialDiagnostic &PD) {
13606 E = E->IgnoreParenImpCasts();
13607
13608 const FunctionDecl *FD = nullptr;
13609
13610 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13611 if (!DRE->getDecl()->getType()->isReferenceType())
13612 return false;
13613 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13614 if (!M->getMemberDecl()->getType()->isReferenceType())
13615 return false;
13616 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13617 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13618 return false;
13619 FD = Call->getDirectCallee();
13620 } else {
13621 return false;
13622 }
13623
13624 SemaRef.Diag(E->getExprLoc(), PD);
13625
13626 // If possible, point to location of function.
13627 if (FD) {
13628 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13629 }
13630
13631 return true;
13632}
13633
13634// Returns true if the SourceLocation is expanded from any macro body.
13635// Returns false if the SourceLocation is invalid, is from not in a macro
13636// expansion, or is from expanded from a top-level macro argument.
13638 if (Loc.isInvalid())
13639 return false;
13640
13641 while (Loc.isMacroID()) {
13642 if (SM.isMacroBodyExpansion(Loc))
13643 return true;
13644 Loc = SM.getImmediateMacroCallerLoc(Loc);
13645 }
13646
13647 return false;
13648}
13649
13652 bool IsEqual, SourceRange Range) {
13653 if (!E)
13654 return;
13655
13656 // Don't warn inside macros.
13657 if (E->getExprLoc().isMacroID()) {
13659 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13660 IsInAnyMacroBody(SM, Range.getBegin()))
13661 return;
13662 }
13663 E = E->IgnoreImpCasts();
13664
13665 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13666
13667 if (isa<CXXThisExpr>(E)) {
13668 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13669 : diag::warn_this_bool_conversion;
13670 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13671 return;
13672 }
13673
13674 bool IsAddressOf = false;
13675
13676 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13677 if (UO->getOpcode() != UO_AddrOf)
13678 return;
13679 IsAddressOf = true;
13680 E = UO->getSubExpr();
13681 }
13682
13683 if (IsAddressOf) {
13684 unsigned DiagID = IsCompare
13685 ? diag::warn_address_of_reference_null_compare
13686 : diag::warn_address_of_reference_bool_conversion;
13687 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13688 << IsEqual;
13689 if (CheckForReference(*this, E, PD)) {
13690 return;
13691 }
13692 }
13693
13694 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13695 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13696 std::string Str;
13697 llvm::raw_string_ostream S(Str);
13698 E->printPretty(S, nullptr, getPrintingPolicy());
13699 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13700 : diag::warn_cast_nonnull_to_bool;
13701 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13702 << E->getSourceRange() << Range << IsEqual;
13703 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13704 };
13705
13706 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13707 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13708 if (auto *Callee = Call->getDirectCallee()) {
13709 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13710 ComplainAboutNonnullParamOrCall(A);
13711 return;
13712 }
13713 }
13714 }
13715
13716 // Complain if we are converting a lambda expression to a boolean value
13717 // outside of instantiation.
13718 if (!inTemplateInstantiation()) {
13719 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13720 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13721 MRecordDecl && MRecordDecl->isLambda()) {
13722 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13723 << /*LambdaPointerConversionOperatorType=*/3
13724 << MRecordDecl->getSourceRange() << Range << IsEqual;
13725 return;
13726 }
13727 }
13728 }
13729
13730 // Expect to find a single Decl. Skip anything more complicated.
13731 ValueDecl *D = nullptr;
13732 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13733 D = R->getDecl();
13734 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13735 D = M->getMemberDecl();
13736 }
13737
13738 // Weak Decls can be null.
13739 if (!D || D->isWeak())
13740 return;
13741
13742 // Check for parameter decl with nonnull attribute
13743 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13744 if (getCurFunction() &&
13745 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13746 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13747 ComplainAboutNonnullParamOrCall(A);
13748 return;
13749 }
13750
13751 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13752 // Skip function template not specialized yet.
13754 return;
13755 auto ParamIter = llvm::find(FD->parameters(), PV);
13756 assert(ParamIter != FD->param_end());
13757 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13758
13759 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13760 if (!NonNull->args_size()) {
13761 ComplainAboutNonnullParamOrCall(NonNull);
13762 return;
13763 }
13764
13765 for (const ParamIdx &ArgNo : NonNull->args()) {
13766 if (ArgNo.getASTIndex() == ParamNo) {
13767 ComplainAboutNonnullParamOrCall(NonNull);
13768 return;
13769 }
13770 }
13771 }
13772 }
13773 }
13774 }
13775
13776 QualType T = D->getType();
13777 const bool IsArray = T->isArrayType();
13778 const bool IsFunction = T->isFunctionType();
13779
13780 // Address of function is used to silence the function warning.
13781 if (IsAddressOf && IsFunction) {
13782 return;
13783 }
13784
13785 // Found nothing.
13786 if (!IsAddressOf && !IsFunction && !IsArray)
13787 return;
13788
13789 // Pretty print the expression for the diagnostic.
13790 std::string Str;
13791 llvm::raw_string_ostream S(Str);
13792 E->printPretty(S, nullptr, getPrintingPolicy());
13793
13794 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13795 : diag::warn_impcast_pointer_to_bool;
13796 enum {
13797 AddressOf,
13798 FunctionPointer,
13799 ArrayPointer
13800 } DiagType;
13801 if (IsAddressOf)
13802 DiagType = AddressOf;
13803 else if (IsFunction)
13804 DiagType = FunctionPointer;
13805 else if (IsArray)
13806 DiagType = ArrayPointer;
13807 else
13808 llvm_unreachable("Could not determine diagnostic.");
13809 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13810 << Range << IsEqual;
13811
13812 if (!IsFunction)
13813 return;
13814
13815 // Suggest '&' to silence the function warning.
13816 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13818
13819 // Check to see if '()' fixit should be emitted.
13820 QualType ReturnType;
13821 UnresolvedSet<4> NonTemplateOverloads;
13822 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13823 if (ReturnType.isNull())
13824 return;
13825
13826 if (IsCompare) {
13827 // There are two cases here. If there is null constant, the only suggest
13828 // for a pointer return type. If the null is 0, then suggest if the return
13829 // type is a pointer or an integer type.
13830 if (!ReturnType->isPointerType()) {
13831 if (NullKind == Expr::NPCK_ZeroExpression ||
13832 NullKind == Expr::NPCK_ZeroLiteral) {
13833 if (!ReturnType->isIntegerType())
13834 return;
13835 } else {
13836 return;
13837 }
13838 }
13839 } else { // !IsCompare
13840 // For function to bool, only suggest if the function pointer has bool
13841 // return type.
13842 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13843 return;
13844 }
13845 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13847}
13848
13849void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13850 // Don't diagnose in unevaluated contexts.
13852 return;
13853
13854 // Don't diagnose for value- or type-dependent expressions.
13855 if (E->isTypeDependent() || E->isValueDependent())
13856 return;
13857
13858 // Check for array bounds violations in cases where the check isn't triggered
13859 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13860 // ArraySubscriptExpr is on the RHS of a variable initialization.
13861 CheckArrayAccess(E);
13862
13863 // This is not the right CC for (e.g.) a variable initialization.
13864 AnalyzeImplicitConversions(*this, E, CC);
13865}
13866
13867void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13868 ::CheckBoolLikeConversion(*this, E, CC);
13869}
13870
13871void Sema::CheckForIntOverflow (const Expr *E) {
13872 // Use a work list to deal with nested struct initializers.
13873 SmallVector<const Expr *, 2> Exprs(1, E);
13874
13875 do {
13876 const Expr *OriginalE = Exprs.pop_back_val();
13877 const Expr *E = OriginalE->IgnoreParenCasts();
13878
13881 continue;
13882 }
13883
13884 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13885 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13886 else if (isa<ObjCBoxedExpr>(OriginalE))
13888 else if (const auto *Call = dyn_cast<CallExpr>(E))
13889 Exprs.append(Call->arg_begin(), Call->arg_end());
13890 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13891 Exprs.append(Message->arg_begin(), Message->arg_end());
13892 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13893 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13894 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13895 Exprs.push_back(Temporary->getSubExpr());
13896 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13897 Exprs.push_back(Array->getIdx());
13898 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13899 Exprs.push_back(Compound->getInitializer());
13900 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13901 New && New->isArray()) {
13902 if (auto ArraySize = New->getArraySize())
13903 Exprs.push_back(*ArraySize);
13904 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13905 Exprs.push_back(MTE->getSubExpr());
13906 } while (!Exprs.empty());
13907}
13908
13909namespace {
13910
13911/// Visitor for expressions which looks for unsequenced operations on the
13912/// same object.
13913class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13914 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13915
13916 /// A tree of sequenced regions within an expression. Two regions are
13917 /// unsequenced if one is an ancestor or a descendent of the other. When we
13918 /// finish processing an expression with sequencing, such as a comma
13919 /// expression, we fold its tree nodes into its parent, since they are
13920 /// unsequenced with respect to nodes we will visit later.
13921 class SequenceTree {
13922 struct Value {
13923 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13924 unsigned Parent : 31;
13925 LLVM_PREFERRED_TYPE(bool)
13926 unsigned Merged : 1;
13927 };
13928 SmallVector<Value, 8> Values;
13929
13930 public:
13931 /// A region within an expression which may be sequenced with respect
13932 /// to some other region.
13933 class Seq {
13934 friend class SequenceTree;
13935
13936 unsigned Index;
13937
13938 explicit Seq(unsigned N) : Index(N) {}
13939
13940 public:
13941 Seq() : Index(0) {}
13942 };
13943
13944 SequenceTree() { Values.push_back(Value(0)); }
13945 Seq root() const { return Seq(0); }
13946
13947 /// Create a new sequence of operations, which is an unsequenced
13948 /// subset of \p Parent. This sequence of operations is sequenced with
13949 /// respect to other children of \p Parent.
13950 Seq allocate(Seq Parent) {
13951 Values.push_back(Value(Parent.Index));
13952 return Seq(Values.size() - 1);
13953 }
13954
13955 /// Merge a sequence of operations into its parent.
13956 void merge(Seq S) {
13957 Values[S.Index].Merged = true;
13958 }
13959
13960 /// Determine whether two operations are unsequenced. This operation
13961 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13962 /// should have been merged into its parent as appropriate.
13963 bool isUnsequenced(Seq Cur, Seq Old) {
13964 unsigned C = representative(Cur.Index);
13965 unsigned Target = representative(Old.Index);
13966 while (C >= Target) {
13967 if (C == Target)
13968 return true;
13969 C = Values[C].Parent;
13970 }
13971 return false;
13972 }
13973
13974 private:
13975 /// Pick a representative for a sequence.
13976 unsigned representative(unsigned K) {
13977 if (Values[K].Merged)
13978 // Perform path compression as we go.
13979 return Values[K].Parent = representative(Values[K].Parent);
13980 return K;
13981 }
13982 };
13983
13984 /// An object for which we can track unsequenced uses.
13985 using Object = const NamedDecl *;
13986
13987 /// Different flavors of object usage which we track. We only track the
13988 /// least-sequenced usage of each kind.
13989 enum UsageKind {
13990 /// A read of an object. Multiple unsequenced reads are OK.
13991 UK_Use,
13992
13993 /// A modification of an object which is sequenced before the value
13994 /// computation of the expression, such as ++n in C++.
13995 UK_ModAsValue,
13996
13997 /// A modification of an object which is not sequenced before the value
13998 /// computation of the expression, such as n++.
13999 UK_ModAsSideEffect,
14000
14001 UK_Count = UK_ModAsSideEffect + 1
14002 };
14003
14004 /// Bundle together a sequencing region and the expression corresponding
14005 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14006 struct Usage {
14007 const Expr *UsageExpr = nullptr;
14008 SequenceTree::Seq Seq;
14009
14010 Usage() = default;
14011 };
14012
14013 struct UsageInfo {
14014 Usage Uses[UK_Count];
14015
14016 /// Have we issued a diagnostic for this object already?
14017 bool Diagnosed = false;
14018
14019 UsageInfo();
14020 };
14021 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14022
14023 Sema &SemaRef;
14024
14025 /// Sequenced regions within the expression.
14026 SequenceTree Tree;
14027
14028 /// Declaration modifications and references which we have seen.
14029 UsageInfoMap UsageMap;
14030
14031 /// The region we are currently within.
14032 SequenceTree::Seq Region;
14033
14034 /// Filled in with declarations which were modified as a side-effect
14035 /// (that is, post-increment operations).
14036 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14037
14038 /// Expressions to check later. We defer checking these to reduce
14039 /// stack usage.
14040 SmallVectorImpl<const Expr *> &WorkList;
14041
14042 /// RAII object wrapping the visitation of a sequenced subexpression of an
14043 /// expression. At the end of this process, the side-effects of the evaluation
14044 /// become sequenced with respect to the value computation of the result, so
14045 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14046 /// UK_ModAsValue.
14047 struct SequencedSubexpression {
14048 SequencedSubexpression(SequenceChecker &Self)
14049 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14050 Self.ModAsSideEffect = &ModAsSideEffect;
14051 }
14052
14053 ~SequencedSubexpression() {
14054 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14055 // Add a new usage with usage kind UK_ModAsValue, and then restore
14056 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14057 // the previous one was empty).
14058 UsageInfo &UI = Self.UsageMap[M.first];
14059 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14060 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14061 SideEffectUsage = M.second;
14062 }
14063 Self.ModAsSideEffect = OldModAsSideEffect;
14064 }
14065
14066 SequenceChecker &Self;
14067 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14068 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14069 };
14070
14071 /// RAII object wrapping the visitation of a subexpression which we might
14072 /// choose to evaluate as a constant. If any subexpression is evaluated and
14073 /// found to be non-constant, this allows us to suppress the evaluation of
14074 /// the outer expression.
14075 class EvaluationTracker {
14076 public:
14077 EvaluationTracker(SequenceChecker &Self)
14078 : Self(Self), Prev(Self.EvalTracker) {
14079 Self.EvalTracker = this;
14080 }
14081
14082 ~EvaluationTracker() {
14083 Self.EvalTracker = Prev;
14084 if (Prev)
14085 Prev->EvalOK &= EvalOK;
14086 }
14087
14088 bool evaluate(const Expr *E, bool &Result) {
14089 if (!EvalOK || E->isValueDependent())
14090 return false;
14091 EvalOK = E->EvaluateAsBooleanCondition(
14092 Result, Self.SemaRef.Context,
14093 Self.SemaRef.isConstantEvaluatedContext());
14094 return EvalOK;
14095 }
14096
14097 private:
14098 SequenceChecker &Self;
14099 EvaluationTracker *Prev;
14100 bool EvalOK = true;
14101 } *EvalTracker = nullptr;
14102
14103 /// Find the object which is produced by the specified expression,
14104 /// if any.
14105 Object getObject(const Expr *E, bool Mod) const {
14106 E = E->IgnoreParenCasts();
14107 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14108 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14109 return getObject(UO->getSubExpr(), Mod);
14110 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14111 if (BO->getOpcode() == BO_Comma)
14112 return getObject(BO->getRHS(), Mod);
14113 if (Mod && BO->isAssignmentOp())
14114 return getObject(BO->getLHS(), Mod);
14115 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14116 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14117 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14118 return ME->getMemberDecl();
14119 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14120 // FIXME: If this is a reference, map through to its value.
14121 return DRE->getDecl();
14122 return nullptr;
14123 }
14124
14125 /// Note that an object \p O was modified or used by an expression
14126 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14127 /// the object \p O as obtained via the \p UsageMap.
14128 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14129 // Get the old usage for the given object and usage kind.
14130 Usage &U = UI.Uses[UK];
14131 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14132 // If we have a modification as side effect and are in a sequenced
14133 // subexpression, save the old Usage so that we can restore it later
14134 // in SequencedSubexpression::~SequencedSubexpression.
14135 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14136 ModAsSideEffect->push_back(std::make_pair(O, U));
14137 // Then record the new usage with the current sequencing region.
14138 U.UsageExpr = UsageExpr;
14139 U.Seq = Region;
14140 }
14141 }
14142
14143 /// Check whether a modification or use of an object \p O in an expression
14144 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14145 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14146 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14147 /// usage and false we are checking for a mod-use unsequenced usage.
14148 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14149 UsageKind OtherKind, bool IsModMod) {
14150 if (UI.Diagnosed)
14151 return;
14152
14153 const Usage &U = UI.Uses[OtherKind];
14154 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14155 return;
14156
14157 const Expr *Mod = U.UsageExpr;
14158 const Expr *ModOrUse = UsageExpr;
14159 if (OtherKind == UK_Use)
14160 std::swap(Mod, ModOrUse);
14161
14162 SemaRef.DiagRuntimeBehavior(
14163 Mod->getExprLoc(), {Mod, ModOrUse},
14164 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14165 : diag::warn_unsequenced_mod_use)
14166 << O << SourceRange(ModOrUse->getExprLoc()));
14167 UI.Diagnosed = true;
14168 }
14169
14170 // A note on note{Pre, Post}{Use, Mod}:
14171 //
14172 // (It helps to follow the algorithm with an expression such as
14173 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14174 // operations before C++17 and both are well-defined in C++17).
14175 //
14176 // When visiting a node which uses/modify an object we first call notePreUse
14177 // or notePreMod before visiting its sub-expression(s). At this point the
14178 // children of the current node have not yet been visited and so the eventual
14179 // uses/modifications resulting from the children of the current node have not
14180 // been recorded yet.
14181 //
14182 // We then visit the children of the current node. After that notePostUse or
14183 // notePostMod is called. These will 1) detect an unsequenced modification
14184 // as side effect (as in "k++ + k") and 2) add a new usage with the
14185 // appropriate usage kind.
14186 //
14187 // We also have to be careful that some operation sequences modification as
14188 // side effect as well (for example: || or ,). To account for this we wrap
14189 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14190 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14191 // which record usages which are modifications as side effect, and then
14192 // downgrade them (or more accurately restore the previous usage which was a
14193 // modification as side effect) when exiting the scope of the sequenced
14194 // subexpression.
14195
14196 void notePreUse(Object O, const Expr *UseExpr) {
14197 UsageInfo &UI = UsageMap[O];
14198 // Uses conflict with other modifications.
14199 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14200 }
14201
14202 void notePostUse(Object O, const Expr *UseExpr) {
14203 UsageInfo &UI = UsageMap[O];
14204 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14205 /*IsModMod=*/false);
14206 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14207 }
14208
14209 void notePreMod(Object O, const Expr *ModExpr) {
14210 UsageInfo &UI = UsageMap[O];
14211 // Modifications conflict with other modifications and with uses.
14212 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14213 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14214 }
14215
14216 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14217 UsageInfo &UI = UsageMap[O];
14218 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14219 /*IsModMod=*/true);
14220 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14221 }
14222
14223public:
14224 SequenceChecker(Sema &S, const Expr *E,
14225 SmallVectorImpl<const Expr *> &WorkList)
14226 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14227 Visit(E);
14228 // Silence a -Wunused-private-field since WorkList is now unused.
14229 // TODO: Evaluate if it can be used, and if not remove it.
14230 (void)this->WorkList;
14231 }
14232
14233 void VisitStmt(const Stmt *S) {
14234 // Skip all statements which aren't expressions for now.
14235 }
14236
14237 void VisitExpr(const Expr *E) {
14238 // By default, just recurse to evaluated subexpressions.
14239 Base::VisitStmt(E);
14240 }
14241
14242 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14243 for (auto *Sub : CSE->children()) {
14244 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14245 if (!ChildExpr)
14246 continue;
14247
14248 if (ChildExpr == CSE->getOperand())
14249 // Do not recurse over a CoroutineSuspendExpr's operand.
14250 // The operand is also a subexpression of getCommonExpr(), and
14251 // recursing into it directly could confuse object management
14252 // for the sake of sequence tracking.
14253 continue;
14254
14255 Visit(Sub);
14256 }
14257 }
14258
14259 void VisitCastExpr(const CastExpr *E) {
14260 Object O = Object();
14261 if (E->getCastKind() == CK_LValueToRValue)
14262 O = getObject(E->getSubExpr(), false);
14263
14264 if (O)
14265 notePreUse(O, E);
14266 VisitExpr(E);
14267 if (O)
14268 notePostUse(O, E);
14269 }
14270
14271 void VisitSequencedExpressions(const Expr *SequencedBefore,
14272 const Expr *SequencedAfter) {
14273 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14274 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14275 SequenceTree::Seq OldRegion = Region;
14276
14277 {
14278 SequencedSubexpression SeqBefore(*this);
14279 Region = BeforeRegion;
14280 Visit(SequencedBefore);
14281 }
14282
14283 Region = AfterRegion;
14284 Visit(SequencedAfter);
14285
14286 Region = OldRegion;
14287
14288 Tree.merge(BeforeRegion);
14289 Tree.merge(AfterRegion);
14290 }
14291
14292 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14293 // C++17 [expr.sub]p1:
14294 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14295 // expression E1 is sequenced before the expression E2.
14296 if (SemaRef.getLangOpts().CPlusPlus17)
14297 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14298 else {
14299 Visit(ASE->getLHS());
14300 Visit(ASE->getRHS());
14301 }
14302 }
14303
14304 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14305 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14306 void VisitBinPtrMem(const BinaryOperator *BO) {
14307 // C++17 [expr.mptr.oper]p4:
14308 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14309 // the expression E1 is sequenced before the expression E2.
14310 if (SemaRef.getLangOpts().CPlusPlus17)
14311 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14312 else {
14313 Visit(BO->getLHS());
14314 Visit(BO->getRHS());
14315 }
14316 }
14317
14318 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14319 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14320 void VisitBinShlShr(const BinaryOperator *BO) {
14321 // C++17 [expr.shift]p4:
14322 // The expression E1 is sequenced before the expression E2.
14323 if (SemaRef.getLangOpts().CPlusPlus17)
14324 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14325 else {
14326 Visit(BO->getLHS());
14327 Visit(BO->getRHS());
14328 }
14329 }
14330
14331 void VisitBinComma(const BinaryOperator *BO) {
14332 // C++11 [expr.comma]p1:
14333 // Every value computation and side effect associated with the left
14334 // expression is sequenced before every value computation and side
14335 // effect associated with the right expression.
14336 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14337 }
14338
14339 void VisitBinAssign(const BinaryOperator *BO) {
14340 SequenceTree::Seq RHSRegion;
14341 SequenceTree::Seq LHSRegion;
14342 if (SemaRef.getLangOpts().CPlusPlus17) {
14343 RHSRegion = Tree.allocate(Region);
14344 LHSRegion = Tree.allocate(Region);
14345 } else {
14346 RHSRegion = Region;
14347 LHSRegion = Region;
14348 }
14349 SequenceTree::Seq OldRegion = Region;
14350
14351 // C++11 [expr.ass]p1:
14352 // [...] the assignment is sequenced after the value computation
14353 // of the right and left operands, [...]
14354 //
14355 // so check it before inspecting the operands and update the
14356 // map afterwards.
14357 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14358 if (O)
14359 notePreMod(O, BO);
14360
14361 if (SemaRef.getLangOpts().CPlusPlus17) {
14362 // C++17 [expr.ass]p1:
14363 // [...] The right operand is sequenced before the left operand. [...]
14364 {
14365 SequencedSubexpression SeqBefore(*this);
14366 Region = RHSRegion;
14367 Visit(BO->getRHS());
14368 }
14369
14370 Region = LHSRegion;
14371 Visit(BO->getLHS());
14372
14373 if (O && isa<CompoundAssignOperator>(BO))
14374 notePostUse(O, BO);
14375
14376 } else {
14377 // C++11 does not specify any sequencing between the LHS and RHS.
14378 Region = LHSRegion;
14379 Visit(BO->getLHS());
14380
14381 if (O && isa<CompoundAssignOperator>(BO))
14382 notePostUse(O, BO);
14383
14384 Region = RHSRegion;
14385 Visit(BO->getRHS());
14386 }
14387
14388 // C++11 [expr.ass]p1:
14389 // the assignment is sequenced [...] before the value computation of the
14390 // assignment expression.
14391 // C11 6.5.16/3 has no such rule.
14392 Region = OldRegion;
14393 if (O)
14394 notePostMod(O, BO,
14395 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14396 : UK_ModAsSideEffect);
14397 if (SemaRef.getLangOpts().CPlusPlus17) {
14398 Tree.merge(RHSRegion);
14399 Tree.merge(LHSRegion);
14400 }
14401 }
14402
14403 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14404 VisitBinAssign(CAO);
14405 }
14406
14407 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14408 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14409 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14410 Object O = getObject(UO->getSubExpr(), true);
14411 if (!O)
14412 return VisitExpr(UO);
14413
14414 notePreMod(O, UO);
14415 Visit(UO->getSubExpr());
14416 // C++11 [expr.pre.incr]p1:
14417 // the expression ++x is equivalent to x+=1
14418 notePostMod(O, UO,
14419 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14420 : UK_ModAsSideEffect);
14421 }
14422
14423 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14424 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14425 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14426 Object O = getObject(UO->getSubExpr(), true);
14427 if (!O)
14428 return VisitExpr(UO);
14429
14430 notePreMod(O, UO);
14431 Visit(UO->getSubExpr());
14432 notePostMod(O, UO, UK_ModAsSideEffect);
14433 }
14434
14435 void VisitBinLOr(const BinaryOperator *BO) {
14436 // C++11 [expr.log.or]p2:
14437 // If the second expression is evaluated, every value computation and
14438 // side effect associated with the first expression is sequenced before
14439 // every value computation and side effect associated with the
14440 // second expression.
14441 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14442 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14443 SequenceTree::Seq OldRegion = Region;
14444
14445 EvaluationTracker Eval(*this);
14446 {
14447 SequencedSubexpression Sequenced(*this);
14448 Region = LHSRegion;
14449 Visit(BO->getLHS());
14450 }
14451
14452 // C++11 [expr.log.or]p1:
14453 // [...] the second operand is not evaluated if the first operand
14454 // evaluates to true.
14455 bool EvalResult = false;
14456 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14457 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14458 if (ShouldVisitRHS) {
14459 Region = RHSRegion;
14460 Visit(BO->getRHS());
14461 }
14462
14463 Region = OldRegion;
14464 Tree.merge(LHSRegion);
14465 Tree.merge(RHSRegion);
14466 }
14467
14468 void VisitBinLAnd(const BinaryOperator *BO) {
14469 // C++11 [expr.log.and]p2:
14470 // If the second expression is evaluated, every value computation and
14471 // side effect associated with the first expression is sequenced before
14472 // every value computation and side effect associated with the
14473 // second expression.
14474 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14475 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14476 SequenceTree::Seq OldRegion = Region;
14477
14478 EvaluationTracker Eval(*this);
14479 {
14480 SequencedSubexpression Sequenced(*this);
14481 Region = LHSRegion;
14482 Visit(BO->getLHS());
14483 }
14484
14485 // C++11 [expr.log.and]p1:
14486 // [...] the second operand is not evaluated if the first operand is false.
14487 bool EvalResult = false;
14488 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14489 bool ShouldVisitRHS = !EvalOK || EvalResult;
14490 if (ShouldVisitRHS) {
14491 Region = RHSRegion;
14492 Visit(BO->getRHS());
14493 }
14494
14495 Region = OldRegion;
14496 Tree.merge(LHSRegion);
14497 Tree.merge(RHSRegion);
14498 }
14499
14500 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14501 // C++11 [expr.cond]p1:
14502 // [...] Every value computation and side effect associated with the first
14503 // expression is sequenced before every value computation and side effect
14504 // associated with the second or third expression.
14505 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14506
14507 // No sequencing is specified between the true and false expression.
14508 // However since exactly one of both is going to be evaluated we can
14509 // consider them to be sequenced. This is needed to avoid warning on
14510 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14511 // both the true and false expressions because we can't evaluate x.
14512 // This will still allow us to detect an expression like (pre C++17)
14513 // "(x ? y += 1 : y += 2) = y".
14514 //
14515 // We don't wrap the visitation of the true and false expression with
14516 // SequencedSubexpression because we don't want to downgrade modifications
14517 // as side effect in the true and false expressions after the visition
14518 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14519 // not warn between the two "y++", but we should warn between the "y++"
14520 // and the "y".
14521 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14522 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14523 SequenceTree::Seq OldRegion = Region;
14524
14525 EvaluationTracker Eval(*this);
14526 {
14527 SequencedSubexpression Sequenced(*this);
14528 Region = ConditionRegion;
14529 Visit(CO->getCond());
14530 }
14531
14532 // C++11 [expr.cond]p1:
14533 // [...] The first expression is contextually converted to bool (Clause 4).
14534 // It is evaluated and if it is true, the result of the conditional
14535 // expression is the value of the second expression, otherwise that of the
14536 // third expression. Only one of the second and third expressions is
14537 // evaluated. [...]
14538 bool EvalResult = false;
14539 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14540 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14541 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14542 if (ShouldVisitTrueExpr) {
14543 Region = TrueRegion;
14544 Visit(CO->getTrueExpr());
14545 }
14546 if (ShouldVisitFalseExpr) {
14547 Region = FalseRegion;
14548 Visit(CO->getFalseExpr());
14549 }
14550
14551 Region = OldRegion;
14552 Tree.merge(ConditionRegion);
14553 Tree.merge(TrueRegion);
14554 Tree.merge(FalseRegion);
14555 }
14556
14557 void VisitCallExpr(const CallExpr *CE) {
14558 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14559
14560 if (CE->isUnevaluatedBuiltinCall(Context))
14561 return;
14562
14563 // C++11 [intro.execution]p15:
14564 // When calling a function [...], every value computation and side effect
14565 // associated with any argument expression, or with the postfix expression
14566 // designating the called function, is sequenced before execution of every
14567 // expression or statement in the body of the function [and thus before
14568 // the value computation of its result].
14569 SequencedSubexpression Sequenced(*this);
14570 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14571 // C++17 [expr.call]p5
14572 // The postfix-expression is sequenced before each expression in the
14573 // expression-list and any default argument. [...]
14574 SequenceTree::Seq CalleeRegion;
14575 SequenceTree::Seq OtherRegion;
14576 if (SemaRef.getLangOpts().CPlusPlus17) {
14577 CalleeRegion = Tree.allocate(Region);
14578 OtherRegion = Tree.allocate(Region);
14579 } else {
14580 CalleeRegion = Region;
14581 OtherRegion = Region;
14582 }
14583 SequenceTree::Seq OldRegion = Region;
14584
14585 // Visit the callee expression first.
14586 Region = CalleeRegion;
14587 if (SemaRef.getLangOpts().CPlusPlus17) {
14588 SequencedSubexpression Sequenced(*this);
14589 Visit(CE->getCallee());
14590 } else {
14591 Visit(CE->getCallee());
14592 }
14593
14594 // Then visit the argument expressions.
14595 Region = OtherRegion;
14596 for (const Expr *Argument : CE->arguments())
14597 Visit(Argument);
14598
14599 Region = OldRegion;
14600 if (SemaRef.getLangOpts().CPlusPlus17) {
14601 Tree.merge(CalleeRegion);
14602 Tree.merge(OtherRegion);
14603 }
14604 });
14605 }
14606
14607 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14608 // C++17 [over.match.oper]p2:
14609 // [...] the operator notation is first transformed to the equivalent
14610 // function-call notation as summarized in Table 12 (where @ denotes one
14611 // of the operators covered in the specified subclause). However, the
14612 // operands are sequenced in the order prescribed for the built-in
14613 // operator (Clause 8).
14614 //
14615 // From the above only overloaded binary operators and overloaded call
14616 // operators have sequencing rules in C++17 that we need to handle
14617 // separately.
14618 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14619 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14620 return VisitCallExpr(CXXOCE);
14621
14622 enum {
14623 NoSequencing,
14624 LHSBeforeRHS,
14625 RHSBeforeLHS,
14626 LHSBeforeRest
14627 } SequencingKind;
14628 switch (CXXOCE->getOperator()) {
14629 case OO_Equal:
14630 case OO_PlusEqual:
14631 case OO_MinusEqual:
14632 case OO_StarEqual:
14633 case OO_SlashEqual:
14634 case OO_PercentEqual:
14635 case OO_CaretEqual:
14636 case OO_AmpEqual:
14637 case OO_PipeEqual:
14638 case OO_LessLessEqual:
14639 case OO_GreaterGreaterEqual:
14640 SequencingKind = RHSBeforeLHS;
14641 break;
14642
14643 case OO_LessLess:
14644 case OO_GreaterGreater:
14645 case OO_AmpAmp:
14646 case OO_PipePipe:
14647 case OO_Comma:
14648 case OO_ArrowStar:
14649 case OO_Subscript:
14650 SequencingKind = LHSBeforeRHS;
14651 break;
14652
14653 case OO_Call:
14654 SequencingKind = LHSBeforeRest;
14655 break;
14656
14657 default:
14658 SequencingKind = NoSequencing;
14659 break;
14660 }
14661
14662 if (SequencingKind == NoSequencing)
14663 return VisitCallExpr(CXXOCE);
14664
14665 // This is a call, so all subexpressions are sequenced before the result.
14666 SequencedSubexpression Sequenced(*this);
14667
14668 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14669 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14670 "Should only get there with C++17 and above!");
14671 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14672 "Should only get there with an overloaded binary operator"
14673 " or an overloaded call operator!");
14674
14675 if (SequencingKind == LHSBeforeRest) {
14676 assert(CXXOCE->getOperator() == OO_Call &&
14677 "We should only have an overloaded call operator here!");
14678
14679 // This is very similar to VisitCallExpr, except that we only have the
14680 // C++17 case. The postfix-expression is the first argument of the
14681 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14682 // are in the following arguments.
14683 //
14684 // Note that we intentionally do not visit the callee expression since
14685 // it is just a decayed reference to a function.
14686 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14687 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14688 SequenceTree::Seq OldRegion = Region;
14689
14690 assert(CXXOCE->getNumArgs() >= 1 &&
14691 "An overloaded call operator must have at least one argument"
14692 " for the postfix-expression!");
14693 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14694 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14695 CXXOCE->getNumArgs() - 1);
14696
14697 // Visit the postfix-expression first.
14698 {
14699 Region = PostfixExprRegion;
14700 SequencedSubexpression Sequenced(*this);
14701 Visit(PostfixExpr);
14702 }
14703
14704 // Then visit the argument expressions.
14705 Region = ArgsRegion;
14706 for (const Expr *Arg : Args)
14707 Visit(Arg);
14708
14709 Region = OldRegion;
14710 Tree.merge(PostfixExprRegion);
14711 Tree.merge(ArgsRegion);
14712 } else {
14713 assert(CXXOCE->getNumArgs() == 2 &&
14714 "Should only have two arguments here!");
14715 assert((SequencingKind == LHSBeforeRHS ||
14716 SequencingKind == RHSBeforeLHS) &&
14717 "Unexpected sequencing kind!");
14718
14719 // We do not visit the callee expression since it is just a decayed
14720 // reference to a function.
14721 const Expr *E1 = CXXOCE->getArg(0);
14722 const Expr *E2 = CXXOCE->getArg(1);
14723 if (SequencingKind == RHSBeforeLHS)
14724 std::swap(E1, E2);
14725
14726 return VisitSequencedExpressions(E1, E2);
14727 }
14728 });
14729 }
14730
14731 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14732 // This is a call, so all subexpressions are sequenced before the result.
14733 SequencedSubexpression Sequenced(*this);
14734
14735 if (!CCE->isListInitialization())
14736 return VisitExpr(CCE);
14737
14738 // In C++11, list initializations are sequenced.
14739 SequenceExpressionsInOrder(
14740 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14741 }
14742
14743 void VisitInitListExpr(const InitListExpr *ILE) {
14744 if (!SemaRef.getLangOpts().CPlusPlus11)
14745 return VisitExpr(ILE);
14746
14747 // In C++11, list initializations are sequenced.
14748 SequenceExpressionsInOrder(ILE->inits());
14749 }
14750
14751 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14752 // C++20 parenthesized list initializations are sequenced. See C++20
14753 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14754 SequenceExpressionsInOrder(PLIE->getInitExprs());
14755 }
14756
14757private:
14758 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14760 SequenceTree::Seq Parent = Region;
14761 for (const Expr *E : ExpressionList) {
14762 if (!E)
14763 continue;
14764 Region = Tree.allocate(Parent);
14765 Elts.push_back(Region);
14766 Visit(E);
14767 }
14768
14769 // Forget that the initializers are sequenced.
14770 Region = Parent;
14771 for (unsigned I = 0; I < Elts.size(); ++I)
14772 Tree.merge(Elts[I]);
14773 }
14774};
14775
14776SequenceChecker::UsageInfo::UsageInfo() = default;
14777
14778} // namespace
14779
14780void Sema::CheckUnsequencedOperations(const Expr *E) {
14781 SmallVector<const Expr *, 8> WorkList;
14782 WorkList.push_back(E);
14783 while (!WorkList.empty()) {
14784 const Expr *Item = WorkList.pop_back_val();
14785 SequenceChecker(*this, Item, WorkList);
14786 }
14787}
14788
14789void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14790 bool IsConstexpr) {
14791 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14792 IsConstexpr || isa<ConstantExpr>(E));
14793 CheckImplicitConversions(E, CheckLoc);
14794 if (!E->isInstantiationDependent())
14795 CheckUnsequencedOperations(E);
14796 if (!IsConstexpr && !E->isValueDependent())
14797 CheckForIntOverflow(E);
14798}
14799
14800void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14801 FieldDecl *BitField,
14802 Expr *Init) {
14803 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14804}
14805
14807 SourceLocation Loc) {
14808 if (!PType->isVariablyModifiedType())
14809 return;
14810 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14811 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14812 return;
14813 }
14814 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14815 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14816 return;
14817 }
14818 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14819 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14820 return;
14821 }
14822
14823 const ArrayType *AT = S.Context.getAsArrayType(PType);
14824 if (!AT)
14825 return;
14826
14829 return;
14830 }
14831
14832 S.Diag(Loc, diag::err_array_star_in_function_definition);
14833}
14834
14836 bool CheckParameterNames) {
14837 bool HasInvalidParm = false;
14838 for (ParmVarDecl *Param : Parameters) {
14839 assert(Param && "null in a parameter list");
14840 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14841 // function declarator that is part of a function definition of
14842 // that function shall not have incomplete type.
14843 //
14844 // C++23 [dcl.fct.def.general]/p2
14845 // The type of a parameter [...] for a function definition
14846 // shall not be a (possibly cv-qualified) class type that is incomplete
14847 // or abstract within the function body unless the function is deleted.
14848 if (!Param->isInvalidDecl() &&
14849 (RequireCompleteType(Param->getLocation(), Param->getType(),
14850 diag::err_typecheck_decl_incomplete_type) ||
14851 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14852 diag::err_abstract_type_in_decl,
14854 Param->setInvalidDecl();
14855 HasInvalidParm = true;
14856 }
14857
14858 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14859 // declaration of each parameter shall include an identifier.
14860 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14861 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14862 // Diagnose this as an extension in C17 and earlier.
14863 if (!getLangOpts().C23)
14864 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14865 }
14866
14867 // C99 6.7.5.3p12:
14868 // If the function declarator is not part of a definition of that
14869 // function, parameters may have incomplete type and may use the [*]
14870 // notation in their sequences of declarator specifiers to specify
14871 // variable length array types.
14872 QualType PType = Param->getOriginalType();
14873 // FIXME: This diagnostic should point the '[*]' if source-location
14874 // information is added for it.
14875 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14876
14877 // If the parameter is a c++ class type and it has to be destructed in the
14878 // callee function, declare the destructor so that it can be called by the
14879 // callee function. Do not perform any direct access check on the dtor here.
14880 if (!Param->isInvalidDecl()) {
14881 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14882 if (!ClassDecl->isInvalidDecl() &&
14883 !ClassDecl->hasIrrelevantDestructor() &&
14884 !ClassDecl->isDependentContext() &&
14885 ClassDecl->isParamDestroyedInCallee()) {
14887 MarkFunctionReferenced(Param->getLocation(), Destructor);
14888 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14889 }
14890 }
14891 }
14892
14893 // Parameters with the pass_object_size attribute only need to be marked
14894 // constant at function definitions. Because we lack information about
14895 // whether we're on a declaration or definition when we're instantiating the
14896 // attribute, we need to check for constness here.
14897 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14898 if (!Param->getType().isConstQualified())
14899 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14900 << Attr->getSpelling() << 1;
14901
14902 // Check for parameter names shadowing fields from the class.
14903 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14904 // The owning context for the parameter should be the function, but we
14905 // want to see if this function's declaration context is a record.
14906 DeclContext *DC = Param->getDeclContext();
14907 if (DC && DC->isFunctionOrMethod()) {
14908 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14909 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14910 RD, /*DeclIsField*/ false);
14911 }
14912 }
14913
14914 if (!Param->isInvalidDecl() &&
14915 Param->getOriginalType()->isWebAssemblyTableType()) {
14916 Param->setInvalidDecl();
14917 HasInvalidParm = true;
14918 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14919 }
14920 }
14921
14922 return HasInvalidParm;
14923}
14924
14925std::optional<std::pair<
14927 *E,
14929 &Ctx);
14930
14931/// Compute the alignment and offset of the base class object given the
14932/// derived-to-base cast expression and the alignment and offset of the derived
14933/// class object.
14934static std::pair<CharUnits, CharUnits>
14936 CharUnits BaseAlignment, CharUnits Offset,
14937 ASTContext &Ctx) {
14938 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14939 ++PathI) {
14940 const CXXBaseSpecifier *Base = *PathI;
14941 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14942 if (Base->isVirtual()) {
14943 // The complete object may have a lower alignment than the non-virtual
14944 // alignment of the base, in which case the base may be misaligned. Choose
14945 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14946 // conservative lower bound of the complete object alignment.
14947 CharUnits NonVirtualAlignment =
14949 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14950 Offset = CharUnits::Zero();
14951 } else {
14952 const ASTRecordLayout &RL =
14953 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14954 Offset += RL.getBaseClassOffset(BaseDecl);
14955 }
14956 DerivedType = Base->getType();
14957 }
14958
14959 return std::make_pair(BaseAlignment, Offset);
14960}
14961
14962/// Compute the alignment and offset of a binary additive operator.
14963static std::optional<std::pair<CharUnits, CharUnits>>
14965 bool IsSub, ASTContext &Ctx) {
14966 QualType PointeeType = PtrE->getType()->getPointeeType();
14967
14968 if (!PointeeType->isConstantSizeType())
14969 return std::nullopt;
14970
14971 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14972
14973 if (!P)
14974 return std::nullopt;
14975
14976 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14977 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14978 CharUnits Offset = EltSize * IdxRes->getExtValue();
14979 if (IsSub)
14980 Offset = -Offset;
14981 return std::make_pair(P->first, P->second + Offset);
14982 }
14983
14984 // If the integer expression isn't a constant expression, compute the lower
14985 // bound of the alignment using the alignment and offset of the pointer
14986 // expression and the element size.
14987 return std::make_pair(
14988 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14989 CharUnits::Zero());
14990}
14991
14992/// This helper function takes an lvalue expression and returns the alignment of
14993/// a VarDecl and a constant offset from the VarDecl.
14994std::optional<std::pair<
14995 CharUnits,
14997 ASTContext &Ctx) {
14998 E = E->IgnoreParens();
14999 switch (E->getStmtClass()) {
15000 default:
15001 break;
15002 case Stmt::CStyleCastExprClass:
15003 case Stmt::CXXStaticCastExprClass:
15004 case Stmt::ImplicitCastExprClass: {
15005 auto *CE = cast<CastExpr>(E);
15006 const Expr *From = CE->getSubExpr();
15007 switch (CE->getCastKind()) {
15008 default:
15009 break;
15010 case CK_NoOp:
15011 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15012 case CK_UncheckedDerivedToBase:
15013 case CK_DerivedToBase: {
15014 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15015 if (!P)
15016 break;
15017 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15018 P->second, Ctx);
15019 }
15020 }
15021 break;
15022 }
15023 case Stmt::ArraySubscriptExprClass: {
15024 auto *ASE = cast<ArraySubscriptExpr>(E);
15026 false, Ctx);
15027 }
15028 case Stmt::DeclRefExprClass: {
15029 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15030 // FIXME: If VD is captured by copy or is an escaping __block variable,
15031 // use the alignment of VD's type.
15032 if (!VD->getType()->isReferenceType()) {
15033 // Dependent alignment cannot be resolved -> bail out.
15034 if (VD->hasDependentAlignment())
15035 break;
15036 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15037 }
15038 if (VD->hasInit())
15039 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15040 }
15041 break;
15042 }
15043 case Stmt::MemberExprClass: {
15044 auto *ME = cast<MemberExpr>(E);
15045 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15046 if (!FD || FD->getType()->isReferenceType() ||
15047 FD->getParent()->isInvalidDecl())
15048 break;
15049 std::optional<std::pair<CharUnits, CharUnits>> P;
15050 if (ME->isArrow())
15051 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15052 else
15053 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15054 if (!P)
15055 break;
15056 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15057 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15058 return std::make_pair(P->first,
15059 P->second + CharUnits::fromQuantity(Offset));
15060 }
15061 case Stmt::UnaryOperatorClass: {
15062 auto *UO = cast<UnaryOperator>(E);
15063 switch (UO->getOpcode()) {
15064 default:
15065 break;
15066 case UO_Deref:
15068 }
15069 break;
15070 }
15071 case Stmt::BinaryOperatorClass: {
15072 auto *BO = cast<BinaryOperator>(E);
15073 auto Opcode = BO->getOpcode();
15074 switch (Opcode) {
15075 default:
15076 break;
15077 case BO_Comma:
15079 }
15080 break;
15081 }
15082 }
15083 return std::nullopt;
15084}
15085
15086/// This helper function takes a pointer expression and returns the alignment of
15087/// a VarDecl and a constant offset from the VarDecl.
15088std::optional<std::pair<
15090 *E,
15092 &Ctx) {
15093 E = E->IgnoreParens();
15094 switch (E->getStmtClass()) {
15095 default:
15096 break;
15097 case Stmt::CStyleCastExprClass:
15098 case Stmt::CXXStaticCastExprClass:
15099 case Stmt::ImplicitCastExprClass: {
15100 auto *CE = cast<CastExpr>(E);
15101 const Expr *From = CE->getSubExpr();
15102 switch (CE->getCastKind()) {
15103 default:
15104 break;
15105 case CK_NoOp:
15106 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15107 case CK_ArrayToPointerDecay:
15108 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15109 case CK_UncheckedDerivedToBase:
15110 case CK_DerivedToBase: {
15111 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15112 if (!P)
15113 break;
15115 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15116 }
15117 }
15118 break;
15119 }
15120 case Stmt::CXXThisExprClass: {
15121 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15123 return std::make_pair(Alignment, CharUnits::Zero());
15124 }
15125 case Stmt::UnaryOperatorClass: {
15126 auto *UO = cast<UnaryOperator>(E);
15127 if (UO->getOpcode() == UO_AddrOf)
15129 break;
15130 }
15131 case Stmt::BinaryOperatorClass: {
15132 auto *BO = cast<BinaryOperator>(E);
15133 auto Opcode = BO->getOpcode();
15134 switch (Opcode) {
15135 default:
15136 break;
15137 case BO_Add:
15138 case BO_Sub: {
15139 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15140 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15141 std::swap(LHS, RHS);
15142 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15143 Ctx);
15144 }
15145 case BO_Comma:
15146 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15147 }
15148 break;
15149 }
15150 }
15151 return std::nullopt;
15152}
15153
15155 // See if we can compute the alignment of a VarDecl and an offset from it.
15156 std::optional<std::pair<CharUnits, CharUnits>> P =
15158
15159 if (P)
15160 return P->first.alignmentAtOffset(P->second);
15161
15162 // If that failed, return the type's alignment.
15164}
15165
15167 // This is actually a lot of work to potentially be doing on every
15168 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15169 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15170 return;
15171
15172 // Ignore dependent types.
15173 if (T->isDependentType() || Op->getType()->isDependentType())
15174 return;
15175
15176 // Require that the destination be a pointer type.
15177 const PointerType *DestPtr = T->getAs<PointerType>();
15178 if (!DestPtr) return;
15179
15180 // If the destination has alignment 1, we're done.
15181 QualType DestPointee = DestPtr->getPointeeType();
15182 if (DestPointee->isIncompleteType()) return;
15183 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15184 if (DestAlign.isOne()) return;
15185
15186 // Require that the source be a pointer type.
15187 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15188 if (!SrcPtr) return;
15189 QualType SrcPointee = SrcPtr->getPointeeType();
15190
15191 // Explicitly allow casts from cv void*. We already implicitly
15192 // allowed casts to cv void*, since they have alignment 1.
15193 // Also allow casts involving incomplete types, which implicitly
15194 // includes 'void'.
15195 if (SrcPointee->isIncompleteType()) return;
15196
15197 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15198
15199 if (SrcAlign >= DestAlign) return;
15200
15201 Diag(TRange.getBegin(), diag::warn_cast_align)
15202 << Op->getType() << T
15203 << static_cast<unsigned>(SrcAlign.getQuantity())
15204 << static_cast<unsigned>(DestAlign.getQuantity())
15205 << TRange << Op->getSourceRange();
15206}
15207
15208void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15209 const ArraySubscriptExpr *ASE,
15210 bool AllowOnePastEnd, bool IndexNegated) {
15211 // Already diagnosed by the constant evaluator.
15213 return;
15214
15215 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15216 if (IndexExpr->isValueDependent())
15217 return;
15218
15219 const Type *EffectiveType =
15221 BaseExpr = BaseExpr->IgnoreParenCasts();
15222 const ConstantArrayType *ArrayTy =
15223 Context.getAsConstantArrayType(BaseExpr->getType());
15224
15226 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15227
15228 const Type *BaseType =
15229 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15230 bool IsUnboundedArray =
15231 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15232 Context, StrictFlexArraysLevel,
15233 /*IgnoreTemplateOrMacroSubstitution=*/true);
15234 if (EffectiveType->isDependentType() ||
15235 (!IsUnboundedArray && BaseType->isDependentType()))
15236 return;
15237
15239 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15240 return;
15241
15242 llvm::APSInt index = Result.Val.getInt();
15243 if (IndexNegated) {
15244 index.setIsUnsigned(false);
15245 index = -index;
15246 }
15247
15248 if (IsUnboundedArray) {
15249 if (EffectiveType->isFunctionType())
15250 return;
15251 if (index.isUnsigned() || !index.isNegative()) {
15252 const auto &ASTC = getASTContext();
15253 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15254 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15255 if (index.getBitWidth() < AddrBits)
15256 index = index.zext(AddrBits);
15257 std::optional<CharUnits> ElemCharUnits =
15258 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15259 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15260 // pointer) bounds-checking isn't meaningful.
15261 if (!ElemCharUnits || ElemCharUnits->isZero())
15262 return;
15263 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15264 // If index has more active bits than address space, we already know
15265 // we have a bounds violation to warn about. Otherwise, compute
15266 // address of (index + 1)th element, and warn about bounds violation
15267 // only if that address exceeds address space.
15268 if (index.getActiveBits() <= AddrBits) {
15269 bool Overflow;
15270 llvm::APInt Product(index);
15271 Product += 1;
15272 Product = Product.umul_ov(ElemBytes, Overflow);
15273 if (!Overflow && Product.getActiveBits() <= AddrBits)
15274 return;
15275 }
15276
15277 // Need to compute max possible elements in address space, since that
15278 // is included in diag message.
15279 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15280 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15281 MaxElems += 1;
15282 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15283 MaxElems = MaxElems.udiv(ElemBytes);
15284
15285 unsigned DiagID =
15286 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15287 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15288
15289 // Diag message shows element size in bits and in "bytes" (platform-
15290 // dependent CharUnits)
15291 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15292 PDiag(DiagID) << index << AddrBits
15293 << (unsigned)ASTC.toBits(*ElemCharUnits)
15294 << ElemBytes << MaxElems
15295 << MaxElems.getZExtValue()
15296 << IndexExpr->getSourceRange());
15297
15298 const NamedDecl *ND = nullptr;
15299 // Try harder to find a NamedDecl to point at in the note.
15300 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15301 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15302 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15303 ND = DRE->getDecl();
15304 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15305 ND = ME->getMemberDecl();
15306
15307 if (ND)
15308 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15309 PDiag(diag::note_array_declared_here) << ND);
15310 }
15311 return;
15312 }
15313
15314 if (index.isUnsigned() || !index.isNegative()) {
15315 // It is possible that the type of the base expression after
15316 // IgnoreParenCasts is incomplete, even though the type of the base
15317 // expression before IgnoreParenCasts is complete (see PR39746 for an
15318 // example). In this case we have no information about whether the array
15319 // access exceeds the array bounds. However we can still diagnose an array
15320 // access which precedes the array bounds.
15321 if (BaseType->isIncompleteType())
15322 return;
15323
15324 llvm::APInt size = ArrayTy->getSize();
15325
15326 if (BaseType != EffectiveType) {
15327 // Make sure we're comparing apples to apples when comparing index to
15328 // size.
15329 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15330 uint64_t array_typesize = Context.getTypeSize(BaseType);
15331
15332 // Handle ptrarith_typesize being zero, such as when casting to void*.
15333 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15334 if (!ptrarith_typesize)
15335 ptrarith_typesize = Context.getCharWidth();
15336
15337 if (ptrarith_typesize != array_typesize) {
15338 // There's a cast to a different size type involved.
15339 uint64_t ratio = array_typesize / ptrarith_typesize;
15340
15341 // TODO: Be smarter about handling cases where array_typesize is not a
15342 // multiple of ptrarith_typesize.
15343 if (ptrarith_typesize * ratio == array_typesize)
15344 size *= llvm::APInt(size.getBitWidth(), ratio);
15345 }
15346 }
15347
15348 if (size.getBitWidth() > index.getBitWidth())
15349 index = index.zext(size.getBitWidth());
15350 else if (size.getBitWidth() < index.getBitWidth())
15351 size = size.zext(index.getBitWidth());
15352
15353 // For array subscripting the index must be less than size, but for pointer
15354 // arithmetic also allow the index (offset) to be equal to size since
15355 // computing the next address after the end of the array is legal and
15356 // commonly done e.g. in C++ iterators and range-based for loops.
15357 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15358 return;
15359
15360 // Suppress the warning if the subscript expression (as identified by the
15361 // ']' location) and the index expression are both from macro expansions
15362 // within a system header.
15363 if (ASE) {
15364 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15365 ASE->getRBracketLoc());
15366 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15367 SourceLocation IndexLoc =
15368 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15369 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15370 return;
15371 }
15372 }
15373
15374 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15375 : diag::warn_ptr_arith_exceeds_bounds;
15376 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15377 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15378
15379 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15380 PDiag(DiagID)
15381 << index << ArrayTy->desugar() << CastMsg
15382 << CastMsgTy << IndexExpr->getSourceRange());
15383 } else {
15384 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15385 if (!ASE) {
15386 DiagID = diag::warn_ptr_arith_precedes_bounds;
15387 if (index.isNegative()) index = -index;
15388 }
15389
15390 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15391 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15392 }
15393
15394 const NamedDecl *ND = nullptr;
15395 // Try harder to find a NamedDecl to point at in the note.
15396 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15397 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15398 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15399 ND = DRE->getDecl();
15400 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15401 ND = ME->getMemberDecl();
15402
15403 if (ND)
15404 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15405 PDiag(diag::note_array_declared_here) << ND);
15406}
15407
15408void Sema::CheckArrayAccess(const Expr *expr) {
15409 int AllowOnePastEnd = 0;
15410 while (expr) {
15411 expr = expr->IgnoreParenImpCasts();
15412 switch (expr->getStmtClass()) {
15413 case Stmt::ArraySubscriptExprClass: {
15414 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15415 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15416 AllowOnePastEnd > 0);
15417 expr = ASE->getBase();
15418 break;
15419 }
15420 case Stmt::MemberExprClass: {
15421 expr = cast<MemberExpr>(expr)->getBase();
15422 break;
15423 }
15424 case Stmt::ArraySectionExprClass: {
15425 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15426 // FIXME: We should probably be checking all of the elements to the
15427 // 'length' here as well.
15428 if (ASE->getLowerBound())
15429 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15430 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15431 return;
15432 }
15433 case Stmt::UnaryOperatorClass: {
15434 // Only unwrap the * and & unary operators
15435 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15436 expr = UO->getSubExpr();
15437 switch (UO->getOpcode()) {
15438 case UO_AddrOf:
15439 AllowOnePastEnd++;
15440 break;
15441 case UO_Deref:
15442 AllowOnePastEnd--;
15443 break;
15444 default:
15445 return;
15446 }
15447 break;
15448 }
15449 case Stmt::ConditionalOperatorClass: {
15450 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15451 if (const Expr *lhs = cond->getLHS())
15452 CheckArrayAccess(lhs);
15453 if (const Expr *rhs = cond->getRHS())
15454 CheckArrayAccess(rhs);
15455 return;
15456 }
15457 case Stmt::CXXOperatorCallExprClass: {
15458 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15459 for (const auto *Arg : OCE->arguments())
15460 CheckArrayAccess(Arg);
15461 return;
15462 }
15463 default:
15464 return;
15465 }
15466 }
15467}
15468
15470 Expr *RHS, bool isProperty) {
15471 // Check if RHS is an Objective-C object literal, which also can get
15472 // immediately zapped in a weak reference. Note that we explicitly
15473 // allow ObjCStringLiterals, since those are designed to never really die.
15474 RHS = RHS->IgnoreParenImpCasts();
15475
15476 // This enum needs to match with the 'select' in
15477 // warn_objc_arc_literal_assign (off-by-1).
15479 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15480 return false;
15481
15482 S.Diag(Loc, diag::warn_arc_literal_assign)
15483 << (unsigned) Kind
15484 << (isProperty ? 0 : 1)
15485 << RHS->getSourceRange();
15486
15487 return true;
15488}
15489
15492 Expr *RHS, bool isProperty) {
15493 // Strip off any implicit cast added to get to the one ARC-specific.
15494 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15495 if (cast->getCastKind() == CK_ARCConsumeObject) {
15496 S.Diag(Loc, diag::warn_arc_retained_assign)
15498 << (isProperty ? 0 : 1)
15499 << RHS->getSourceRange();
15500 return true;
15501 }
15502 RHS = cast->getSubExpr();
15503 }
15504
15505 if (LT == Qualifiers::OCL_Weak &&
15506 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15507 return true;
15508
15509 return false;
15510}
15511
15513 QualType LHS, Expr *RHS) {
15515
15517 return false;
15518
15519 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15520 return true;
15521
15522 return false;
15523}
15524
15526 Expr *LHS, Expr *RHS) {
15527 QualType LHSType;
15528 // PropertyRef on LHS type need be directly obtained from
15529 // its declaration as it has a PseudoType.
15531 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15532 if (PRE && !PRE->isImplicitProperty()) {
15533 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15534 if (PD)
15535 LHSType = PD->getType();
15536 }
15537
15538 if (LHSType.isNull())
15539 LHSType = LHS->getType();
15540
15542
15543 if (LT == Qualifiers::OCL_Weak) {
15544 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15546 }
15547
15548 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15549 return;
15550
15551 // FIXME. Check for other life times.
15552 if (LT != Qualifiers::OCL_None)
15553 return;
15554
15555 if (PRE) {
15556 if (PRE->isImplicitProperty())
15557 return;
15558 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15559 if (!PD)
15560 return;
15561
15562 unsigned Attributes = PD->getPropertyAttributes();
15563 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15564 // when 'assign' attribute was not explicitly specified
15565 // by user, ignore it and rely on property type itself
15566 // for lifetime info.
15567 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15568 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15569 LHSType->isObjCRetainableType())
15570 return;
15571
15572 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15573 if (cast->getCastKind() == CK_ARCConsumeObject) {
15574 Diag(Loc, diag::warn_arc_retained_property_assign)
15575 << RHS->getSourceRange();
15576 return;
15577 }
15578 RHS = cast->getSubExpr();
15579 }
15580 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15581 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15582 return;
15583 }
15584 }
15585}
15586
15587//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15588
15589static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15590 SourceLocation StmtLoc,
15591 const NullStmt *Body) {
15592 // Do not warn if the body is a macro that expands to nothing, e.g:
15593 //
15594 // #define CALL(x)
15595 // if (condition)
15596 // CALL(0);
15597 if (Body->hasLeadingEmptyMacro())
15598 return false;
15599
15600 // Get line numbers of statement and body.
15601 bool StmtLineInvalid;
15602 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15603 &StmtLineInvalid);
15604 if (StmtLineInvalid)
15605 return false;
15606
15607 bool BodyLineInvalid;
15608 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15609 &BodyLineInvalid);
15610 if (BodyLineInvalid)
15611 return false;
15612
15613 // Warn if null statement and body are on the same line.
15614 if (StmtLine != BodyLine)
15615 return false;
15616
15617 return true;
15618}
15619
15621 const Stmt *Body,
15622 unsigned DiagID) {
15623 // Since this is a syntactic check, don't emit diagnostic for template
15624 // instantiations, this just adds noise.
15626 return;
15627
15628 // The body should be a null statement.
15629 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15630 if (!NBody)
15631 return;
15632
15633 // Do the usual checks.
15634 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15635 return;
15636
15637 Diag(NBody->getSemiLoc(), DiagID);
15638 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15639}
15640
15642 const Stmt *PossibleBody) {
15643 assert(!CurrentInstantiationScope); // Ensured by caller
15644
15645 SourceLocation StmtLoc;
15646 const Stmt *Body;
15647 unsigned DiagID;
15648 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15649 StmtLoc = FS->getRParenLoc();
15650 Body = FS->getBody();
15651 DiagID = diag::warn_empty_for_body;
15652 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15653 StmtLoc = WS->getRParenLoc();
15654 Body = WS->getBody();
15655 DiagID = diag::warn_empty_while_body;
15656 } else
15657 return; // Neither `for' nor `while'.
15658
15659 // The body should be a null statement.
15660 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15661 if (!NBody)
15662 return;
15663
15664 // Skip expensive checks if diagnostic is disabled.
15665 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15666 return;
15667
15668 // Do the usual checks.
15669 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15670 return;
15671
15672 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15673 // noise level low, emit diagnostics only if for/while is followed by a
15674 // CompoundStmt, e.g.:
15675 // for (int i = 0; i < n; i++);
15676 // {
15677 // a(i);
15678 // }
15679 // or if for/while is followed by a statement with more indentation
15680 // than for/while itself:
15681 // for (int i = 0; i < n; i++);
15682 // a(i);
15683 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15684 if (!ProbableTypo) {
15685 bool BodyColInvalid;
15686 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15687 PossibleBody->getBeginLoc(), &BodyColInvalid);
15688 if (BodyColInvalid)
15689 return;
15690
15691 bool StmtColInvalid;
15692 unsigned StmtCol =
15693 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15694 if (StmtColInvalid)
15695 return;
15696
15697 if (BodyCol > StmtCol)
15698 ProbableTypo = true;
15699 }
15700
15701 if (ProbableTypo) {
15702 Diag(NBody->getSemiLoc(), DiagID);
15703 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15704 }
15705}
15706
15707//===--- CHECK: Warn on self move with std::move. -------------------------===//
15708
15709void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15710 SourceLocation OpLoc) {
15711 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15712 return;
15713
15715 return;
15716
15717 // Strip parens and casts away.
15718 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15719 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15720
15721 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15722 // which we can treat as an inlined std::move
15723 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15724 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15725 RHSExpr = CE->getArg(0);
15726 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15727 CXXSCE && CXXSCE->isXValue())
15728 RHSExpr = CXXSCE->getSubExpr();
15729 else
15730 return;
15731
15732 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15733 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15734
15735 // Two DeclRefExpr's, check that the decls are the same.
15736 if (LHSDeclRef && RHSDeclRef) {
15737 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15738 return;
15739 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15740 RHSDeclRef->getDecl()->getCanonicalDecl())
15741 return;
15742
15743 auto D = Diag(OpLoc, diag::warn_self_move)
15744 << LHSExpr->getType() << LHSExpr->getSourceRange()
15745 << RHSExpr->getSourceRange();
15746 if (const FieldDecl *F =
15748 D << 1 << F
15749 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15750 else
15751 D << 0;
15752 return;
15753 }
15754
15755 // Member variables require a different approach to check for self moves.
15756 // MemberExpr's are the same if every nested MemberExpr refers to the same
15757 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15758 // the base Expr's are CXXThisExpr's.
15759 const Expr *LHSBase = LHSExpr;
15760 const Expr *RHSBase = RHSExpr;
15761 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15762 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15763 if (!LHSME || !RHSME)
15764 return;
15765
15766 while (LHSME && RHSME) {
15767 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15768 RHSME->getMemberDecl()->getCanonicalDecl())
15769 return;
15770
15771 LHSBase = LHSME->getBase();
15772 RHSBase = RHSME->getBase();
15773 LHSME = dyn_cast<MemberExpr>(LHSBase);
15774 RHSME = dyn_cast<MemberExpr>(RHSBase);
15775 }
15776
15777 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15778 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15779 if (LHSDeclRef && RHSDeclRef) {
15780 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15781 return;
15782 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15783 RHSDeclRef->getDecl()->getCanonicalDecl())
15784 return;
15785
15786 Diag(OpLoc, diag::warn_self_move)
15787 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15788 << RHSExpr->getSourceRange();
15789 return;
15790 }
15791
15792 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15793 Diag(OpLoc, diag::warn_self_move)
15794 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15795 << RHSExpr->getSourceRange();
15796}
15797
15798//===--- Layout compatibility ----------------------------------------------//
15799
15800static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15801
15802/// Check if two enumeration types are layout-compatible.
15803static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15804 const EnumDecl *ED2) {
15805 // C++11 [dcl.enum] p8:
15806 // Two enumeration types are layout-compatible if they have the same
15807 // underlying type.
15808 return ED1->isComplete() && ED2->isComplete() &&
15809 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15810}
15811
15812/// Check if two fields are layout-compatible.
15813/// Can be used on union members, which are exempt from alignment requirement
15814/// of common initial sequence.
15815static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15816 const FieldDecl *Field2,
15817 bool AreUnionMembers = false) {
15818#ifndef NDEBUG
15819 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15820 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15821 assert(((Field1Parent->isStructureOrClassType() &&
15822 Field2Parent->isStructureOrClassType()) ||
15823 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15824 "Can't evaluate layout compatibility between a struct field and a "
15825 "union field.");
15826 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15827 (AreUnionMembers && Field1Parent->isUnionType())) &&
15828 "AreUnionMembers should be 'true' for union fields (only).");
15829#endif
15830
15831 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15832 return false;
15833
15834 if (Field1->isBitField() != Field2->isBitField())
15835 return false;
15836
15837 if (Field1->isBitField()) {
15838 // Make sure that the bit-fields are the same length.
15839 unsigned Bits1 = Field1->getBitWidthValue();
15840 unsigned Bits2 = Field2->getBitWidthValue();
15841
15842 if (Bits1 != Bits2)
15843 return false;
15844 }
15845
15846 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15847 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15848 return false;
15849
15850 if (!AreUnionMembers &&
15851 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15852 return false;
15853
15854 return true;
15855}
15856
15857/// Check if two standard-layout structs are layout-compatible.
15858/// (C++11 [class.mem] p17)
15859static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15860 const RecordDecl *RD2) {
15861 // Get to the class where the fields are declared
15862 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15863 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15864
15865 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15866 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15867
15868 // Check the fields.
15869 return llvm::equal(RD1->fields(), RD2->fields(),
15870 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15871 return isLayoutCompatible(C, F1, F2);
15872 });
15873}
15874
15875/// Check if two standard-layout unions are layout-compatible.
15876/// (C++11 [class.mem] p18)
15877static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15878 const RecordDecl *RD2) {
15879 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15880 RD2->fields());
15881
15882 for (auto *Field1 : RD1->fields()) {
15883 auto I = UnmatchedFields.begin();
15884 auto E = UnmatchedFields.end();
15885
15886 for ( ; I != E; ++I) {
15887 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15888 bool Result = UnmatchedFields.erase(*I);
15889 (void) Result;
15890 assert(Result);
15891 break;
15892 }
15893 }
15894 if (I == E)
15895 return false;
15896 }
15897
15898 return UnmatchedFields.empty();
15899}
15900
15901static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15902 const RecordDecl *RD2) {
15903 if (RD1->isUnion() != RD2->isUnion())
15904 return false;
15905
15906 if (RD1->isUnion())
15907 return isLayoutCompatibleUnion(C, RD1, RD2);
15908 else
15909 return isLayoutCompatibleStruct(C, RD1, RD2);
15910}
15911
15912/// Check if two types are layout-compatible in C++11 sense.
15913static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15914 if (T1.isNull() || T2.isNull())
15915 return false;
15916
15917 // C++20 [basic.types] p11:
15918 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15919 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15920 // or layout-compatible standard-layout class types (11.4).
15923
15924 if (C.hasSameType(T1, T2))
15925 return true;
15926
15927 const Type::TypeClass TC1 = T1->getTypeClass();
15928 const Type::TypeClass TC2 = T2->getTypeClass();
15929
15930 if (TC1 != TC2)
15931 return false;
15932
15933 if (TC1 == Type::Enum)
15934 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15935 if (TC1 == Type::Record) {
15936 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15937 return false;
15938
15940 T2->castAsRecordDecl());
15941 }
15942
15943 return false;
15944}
15945
15947 return isLayoutCompatible(getASTContext(), T1, T2);
15948}
15949
15950//===-------------- Pointer interconvertibility ----------------------------//
15951
15953 const TypeSourceInfo *Derived) {
15954 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15955 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15956
15957 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15958 getASTContext().hasSameType(BaseT, DerivedT))
15959 return true;
15960
15961 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15962 return false;
15963
15964 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15965 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15966 return true;
15967
15968 return false;
15969}
15970
15971//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15972
15973/// Given a type tag expression find the type tag itself.
15974///
15975/// \param TypeExpr Type tag expression, as it appears in user's code.
15976///
15977/// \param VD Declaration of an identifier that appears in a type tag.
15978///
15979/// \param MagicValue Type tag magic value.
15980///
15981/// \param isConstantEvaluated whether the evalaution should be performed in
15982
15983/// constant context.
15984static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15985 const ValueDecl **VD, uint64_t *MagicValue,
15986 bool isConstantEvaluated) {
15987 while(true) {
15988 if (!TypeExpr)
15989 return false;
15990
15991 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15992
15993 switch (TypeExpr->getStmtClass()) {
15994 case Stmt::UnaryOperatorClass: {
15995 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15996 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15997 TypeExpr = UO->getSubExpr();
15998 continue;
15999 }
16000 return false;
16001 }
16002
16003 case Stmt::DeclRefExprClass: {
16004 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16005 *VD = DRE->getDecl();
16006 return true;
16007 }
16008
16009 case Stmt::IntegerLiteralClass: {
16010 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16011 llvm::APInt MagicValueAPInt = IL->getValue();
16012 if (MagicValueAPInt.getActiveBits() <= 64) {
16013 *MagicValue = MagicValueAPInt.getZExtValue();
16014 return true;
16015 } else
16016 return false;
16017 }
16018
16019 case Stmt::BinaryConditionalOperatorClass:
16020 case Stmt::ConditionalOperatorClass: {
16021 const AbstractConditionalOperator *ACO =
16023 bool Result;
16024 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16025 isConstantEvaluated)) {
16026 if (Result)
16027 TypeExpr = ACO->getTrueExpr();
16028 else
16029 TypeExpr = ACO->getFalseExpr();
16030 continue;
16031 }
16032 return false;
16033 }
16034
16035 case Stmt::BinaryOperatorClass: {
16036 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16037 if (BO->getOpcode() == BO_Comma) {
16038 TypeExpr = BO->getRHS();
16039 continue;
16040 }
16041 return false;
16042 }
16043
16044 default:
16045 return false;
16046 }
16047 }
16048}
16049
16050/// Retrieve the C type corresponding to type tag TypeExpr.
16051///
16052/// \param TypeExpr Expression that specifies a type tag.
16053///
16054/// \param MagicValues Registered magic values.
16055///
16056/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16057/// kind.
16058///
16059/// \param TypeInfo Information about the corresponding C type.
16060///
16061/// \param isConstantEvaluated whether the evalaution should be performed in
16062/// constant context.
16063///
16064/// \returns true if the corresponding C type was found.
16066 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16067 const ASTContext &Ctx,
16068 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16069 *MagicValues,
16070 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16071 bool isConstantEvaluated) {
16072 FoundWrongKind = false;
16073
16074 // Variable declaration that has type_tag_for_datatype attribute.
16075 const ValueDecl *VD = nullptr;
16076
16077 uint64_t MagicValue;
16078
16079 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16080 return false;
16081
16082 if (VD) {
16083 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16084 if (I->getArgumentKind() != ArgumentKind) {
16085 FoundWrongKind = true;
16086 return false;
16087 }
16088 TypeInfo.Type = I->getMatchingCType();
16089 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16090 TypeInfo.MustBeNull = I->getMustBeNull();
16091 return true;
16092 }
16093 return false;
16094 }
16095
16096 if (!MagicValues)
16097 return false;
16098
16099 llvm::DenseMap<Sema::TypeTagMagicValue,
16101 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16102 if (I == MagicValues->end())
16103 return false;
16104
16105 TypeInfo = I->second;
16106 return true;
16107}
16108
16110 uint64_t MagicValue, QualType Type,
16111 bool LayoutCompatible,
16112 bool MustBeNull) {
16113 if (!TypeTagForDatatypeMagicValues)
16114 TypeTagForDatatypeMagicValues.reset(
16115 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16116
16117 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16118 (*TypeTagForDatatypeMagicValues)[Magic] =
16119 TypeTagData(Type, LayoutCompatible, MustBeNull);
16120}
16121
16122static bool IsSameCharType(QualType T1, QualType T2) {
16123 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16124 if (!BT1)
16125 return false;
16126
16127 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16128 if (!BT2)
16129 return false;
16130
16131 BuiltinType::Kind T1Kind = BT1->getKind();
16132 BuiltinType::Kind T2Kind = BT2->getKind();
16133
16134 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16135 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16136 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16137 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16138}
16139
16140void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16141 const ArrayRef<const Expr *> ExprArgs,
16142 SourceLocation CallSiteLoc) {
16143 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16144 bool IsPointerAttr = Attr->getIsPointer();
16145
16146 // Retrieve the argument representing the 'type_tag'.
16147 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16148 if (TypeTagIdxAST >= ExprArgs.size()) {
16149 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16150 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16151 return;
16152 }
16153 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16154 bool FoundWrongKind;
16155 TypeTagData TypeInfo;
16156 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16157 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16158 TypeInfo, isConstantEvaluatedContext())) {
16159 if (FoundWrongKind)
16160 Diag(TypeTagExpr->getExprLoc(),
16161 diag::warn_type_tag_for_datatype_wrong_kind)
16162 << TypeTagExpr->getSourceRange();
16163 return;
16164 }
16165
16166 // Retrieve the argument representing the 'arg_idx'.
16167 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16168 if (ArgumentIdxAST >= ExprArgs.size()) {
16169 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16170 << 1 << Attr->getArgumentIdx().getSourceIndex();
16171 return;
16172 }
16173 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16174 if (IsPointerAttr) {
16175 // Skip implicit cast of pointer to `void *' (as a function argument).
16176 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16177 if (ICE->getType()->isVoidPointerType() &&
16178 ICE->getCastKind() == CK_BitCast)
16179 ArgumentExpr = ICE->getSubExpr();
16180 }
16181 QualType ArgumentType = ArgumentExpr->getType();
16182
16183 // Passing a `void*' pointer shouldn't trigger a warning.
16184 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16185 return;
16186
16187 if (TypeInfo.MustBeNull) {
16188 // Type tag with matching void type requires a null pointer.
16189 if (!ArgumentExpr->isNullPointerConstant(Context,
16191 Diag(ArgumentExpr->getExprLoc(),
16192 diag::warn_type_safety_null_pointer_required)
16193 << ArgumentKind->getName()
16194 << ArgumentExpr->getSourceRange()
16195 << TypeTagExpr->getSourceRange();
16196 }
16197 return;
16198 }
16199
16200 QualType RequiredType = TypeInfo.Type;
16201 if (IsPointerAttr)
16202 RequiredType = Context.getPointerType(RequiredType);
16203
16204 bool mismatch = false;
16205 if (!TypeInfo.LayoutCompatible) {
16206 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16207
16208 // C++11 [basic.fundamental] p1:
16209 // Plain char, signed char, and unsigned char are three distinct types.
16210 //
16211 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16212 // char' depending on the current char signedness mode.
16213 if (mismatch)
16214 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16215 RequiredType->getPointeeType())) ||
16216 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16217 mismatch = false;
16218 } else
16219 if (IsPointerAttr)
16220 mismatch = !isLayoutCompatible(Context,
16221 ArgumentType->getPointeeType(),
16222 RequiredType->getPointeeType());
16223 else
16224 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16225
16226 if (mismatch)
16227 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16228 << ArgumentType << ArgumentKind
16229 << TypeInfo.LayoutCompatible << RequiredType
16230 << ArgumentExpr->getSourceRange()
16231 << TypeTagExpr->getSourceRange();
16232}
16233
16234void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16235 CharUnits Alignment) {
16236 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16237 Alignment);
16238}
16239
16241 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16242 const NamedDecl *ND = m.RD;
16243 if (ND->getName().empty()) {
16244 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16245 ND = TD;
16246 }
16247 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16248 << m.MD << ND << m.E->getSourceRange();
16249 }
16251}
16252
16254 E = E->IgnoreParens();
16255 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16256 return;
16257 if (isa<UnaryOperator>(E) &&
16258 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16259 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16260 if (isa<MemberExpr>(Op)) {
16261 auto &MisalignedMembersForExpr =
16263 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16264 if (MA != MisalignedMembersForExpr.end() &&
16265 (T->isDependentType() || T->isIntegerType() ||
16266 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16267 Context.getTypeAlignInChars(
16268 T->getPointeeType()) <= MA->Alignment))))
16269 MisalignedMembersForExpr.erase(MA);
16270 }
16271 }
16272}
16273
16275 Expr *E,
16276 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16277 Action) {
16278 const auto *ME = dyn_cast<MemberExpr>(E);
16279 if (!ME)
16280 return;
16281
16282 // No need to check expressions with an __unaligned-qualified type.
16283 if (E->getType().getQualifiers().hasUnaligned())
16284 return;
16285
16286 // For a chain of MemberExpr like "a.b.c.d" this list
16287 // will keep FieldDecl's like [d, c, b].
16288 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16289 const MemberExpr *TopME = nullptr;
16290 bool AnyIsPacked = false;
16291 do {
16292 QualType BaseType = ME->getBase()->getType();
16293 if (BaseType->isDependentType())
16294 return;
16295 if (ME->isArrow())
16296 BaseType = BaseType->getPointeeType();
16297 auto *RD = BaseType->castAsRecordDecl();
16298 if (RD->isInvalidDecl())
16299 return;
16300
16301 ValueDecl *MD = ME->getMemberDecl();
16302 auto *FD = dyn_cast<FieldDecl>(MD);
16303 // We do not care about non-data members.
16304 if (!FD || FD->isInvalidDecl())
16305 return;
16306
16307 AnyIsPacked =
16308 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16309 ReverseMemberChain.push_back(FD);
16310
16311 TopME = ME;
16312 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16313 } while (ME);
16314 assert(TopME && "We did not compute a topmost MemberExpr!");
16315
16316 // Not the scope of this diagnostic.
16317 if (!AnyIsPacked)
16318 return;
16319
16320 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16321 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16322 // TODO: The innermost base of the member expression may be too complicated.
16323 // For now, just disregard these cases. This is left for future
16324 // improvement.
16325 if (!DRE && !isa<CXXThisExpr>(TopBase))
16326 return;
16327
16328 // Alignment expected by the whole expression.
16329 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16330
16331 // No need to do anything else with this case.
16332 if (ExpectedAlignment.isOne())
16333 return;
16334
16335 // Synthesize offset of the whole access.
16336 CharUnits Offset;
16337 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16338 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16339
16340 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16341 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16342 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16343
16344 // The base expression of the innermost MemberExpr may give
16345 // stronger guarantees than the class containing the member.
16346 if (DRE && !TopME->isArrow()) {
16347 const ValueDecl *VD = DRE->getDecl();
16348 if (!VD->getType()->isReferenceType())
16349 CompleteObjectAlignment =
16350 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16351 }
16352
16353 // Check if the synthesized offset fulfills the alignment.
16354 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16355 // It may fulfill the offset it but the effective alignment may still be
16356 // lower than the expected expression alignment.
16357 CompleteObjectAlignment < ExpectedAlignment) {
16358 // If this happens, we want to determine a sensible culprit of this.
16359 // Intuitively, watching the chain of member expressions from right to
16360 // left, we start with the required alignment (as required by the field
16361 // type) but some packed attribute in that chain has reduced the alignment.
16362 // It may happen that another packed structure increases it again. But if
16363 // we are here such increase has not been enough. So pointing the first
16364 // FieldDecl that either is packed or else its RecordDecl is,
16365 // seems reasonable.
16366 FieldDecl *FD = nullptr;
16367 CharUnits Alignment;
16368 for (FieldDecl *FDI : ReverseMemberChain) {
16369 if (FDI->hasAttr<PackedAttr>() ||
16370 FDI->getParent()->hasAttr<PackedAttr>()) {
16371 FD = FDI;
16372 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16373 Context.getTypeAlignInChars(
16374 Context.getCanonicalTagType(FD->getParent())));
16375 break;
16376 }
16377 }
16378 assert(FD && "We did not find a packed FieldDecl!");
16379 Action(E, FD->getParent(), FD, Alignment);
16380 }
16381}
16382
16383void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16384 using namespace std::placeholders;
16385
16387 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16388 _2, _3, _4));
16389}
16390
16392 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16393 if (checkArgCount(TheCall, 1))
16394 return true;
16395
16396 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16397 if (A.isInvalid())
16398 return true;
16399
16400 TheCall->setArg(0, A.get());
16401 QualType TyA = A.get()->getType();
16402
16403 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16404 ArgTyRestr, 1))
16405 return true;
16406
16407 TheCall->setType(TyA);
16408 return false;
16409}
16410
16411bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16412 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16413 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16414 TheCall->setType(*Res);
16415 return false;
16416 }
16417 return true;
16418}
16419
16421 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16422 if (!Res)
16423 return true;
16424
16425 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16426 TheCall->setType(VecTy0->getElementType());
16427 else
16428 TheCall->setType(*Res);
16429
16430 return false;
16431}
16432
16434 SourceLocation Loc) {
16436 R = RHS->getEnumCoercedType(S.Context);
16437 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16439 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16440 << LHS->getSourceRange() << RHS->getSourceRange()
16441 << /*Arithmetic Between*/ 0 << L << R;
16442 }
16443 return false;
16444}
16445
16446/// Check if all arguments have the same type. If the types don't match, emit an
16447/// error message and return true. Otherwise return false.
16448///
16449/// For scalars we directly compare their unqualified types. But even if we
16450/// compare unqualified vector types, a difference in qualifiers in the element
16451/// types can make the vector types be considered not equal. For example,
16452/// vector of 4 'const float' values vs vector of 4 'float' values.
16453/// So we compare unqualified types of their elements and number of elements.
16455 ArrayRef<Expr *> Args) {
16456 assert(!Args.empty() && "Should have at least one argument.");
16457
16458 Expr *Arg0 = Args.front();
16459 QualType Ty0 = Arg0->getType();
16460
16461 auto EmitError = [&](Expr *ArgI) {
16462 SemaRef.Diag(Arg0->getBeginLoc(),
16463 diag::err_typecheck_call_different_arg_types)
16464 << Arg0->getType() << ArgI->getType();
16465 };
16466
16467 // Compare scalar types.
16468 if (!Ty0->isVectorType()) {
16469 for (Expr *ArgI : Args.drop_front())
16470 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16471 EmitError(ArgI);
16472 return true;
16473 }
16474
16475 return false;
16476 }
16477
16478 // Compare vector types.
16479 const auto *Vec0 = Ty0->castAs<VectorType>();
16480 for (Expr *ArgI : Args.drop_front()) {
16481 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16482 if (!VecI ||
16483 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16484 VecI->getElementType()) ||
16485 Vec0->getNumElements() != VecI->getNumElements()) {
16486 EmitError(ArgI);
16487 return true;
16488 }
16489 }
16490
16491 return false;
16492}
16493
16494std::optional<QualType>
16496 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16497 if (checkArgCount(TheCall, 2))
16498 return std::nullopt;
16499
16501 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16502 return std::nullopt;
16503
16504 Expr *Args[2];
16505 for (int I = 0; I < 2; ++I) {
16506 ExprResult Converted =
16507 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16508 if (Converted.isInvalid())
16509 return std::nullopt;
16510 Args[I] = Converted.get();
16511 }
16512
16513 SourceLocation LocA = Args[0]->getBeginLoc();
16514 QualType TyA = Args[0]->getType();
16515
16516 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16517 return std::nullopt;
16518
16519 if (checkBuiltinVectorMathArgTypes(*this, Args))
16520 return std::nullopt;
16521
16522 TheCall->setArg(0, Args[0]);
16523 TheCall->setArg(1, Args[1]);
16524 return TyA;
16525}
16526
16528 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16529 if (checkArgCount(TheCall, 3))
16530 return true;
16531
16532 SourceLocation Loc = TheCall->getExprLoc();
16533 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16534 TheCall->getArg(1), Loc) ||
16535 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16536 TheCall->getArg(2), Loc))
16537 return true;
16538
16539 Expr *Args[3];
16540 for (int I = 0; I < 3; ++I) {
16541 ExprResult Converted =
16542 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16543 if (Converted.isInvalid())
16544 return true;
16545 Args[I] = Converted.get();
16546 }
16547
16548 int ArgOrdinal = 1;
16549 for (Expr *Arg : Args) {
16550 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16551 ArgTyRestr, ArgOrdinal++))
16552 return true;
16553 }
16554
16555 if (checkBuiltinVectorMathArgTypes(*this, Args))
16556 return true;
16557
16558 for (int I = 0; I < 3; ++I)
16559 TheCall->setArg(I, Args[I]);
16560
16561 TheCall->setType(Args[0]->getType());
16562 return false;
16563}
16564
16565bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16566 if (checkArgCount(TheCall, 1))
16567 return true;
16568
16569 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16570 if (A.isInvalid())
16571 return true;
16572
16573 TheCall->setArg(0, A.get());
16574 return false;
16575}
16576
16577bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16578 if (checkArgCount(TheCall, 1))
16579 return true;
16580
16581 ExprResult Arg = TheCall->getArg(0);
16582 QualType TyArg = Arg.get()->getType();
16583
16584 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16585 return Diag(TheCall->getArg(0)->getBeginLoc(),
16586 diag::err_builtin_invalid_arg_type)
16587 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16588
16589 TheCall->setType(TyArg);
16590 return false;
16591}
16592
16593ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16594 ExprResult CallResult) {
16595 if (checkArgCount(TheCall, 1))
16596 return ExprError();
16597
16598 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16599 if (MatrixArg.isInvalid())
16600 return MatrixArg;
16601 Expr *Matrix = MatrixArg.get();
16602
16603 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16604 if (!MType) {
16605 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16606 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16607 << Matrix->getType();
16608 return ExprError();
16609 }
16610
16611 // Create returned matrix type by swapping rows and columns of the argument
16612 // matrix type.
16613 QualType ResultType = Context.getConstantMatrixType(
16614 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16615
16616 // Change the return type to the type of the returned matrix.
16617 TheCall->setType(ResultType);
16618
16619 // Update call argument to use the possibly converted matrix argument.
16620 TheCall->setArg(0, Matrix);
16621 return CallResult;
16622}
16623
16624// Get and verify the matrix dimensions.
16625static std::optional<unsigned>
16627 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16628 if (!Value) {
16629 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16630 << Name;
16631 return {};
16632 }
16633 uint64_t Dim = Value->getZExtValue();
16634 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16635 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16636 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16637 return {};
16638 }
16639 return Dim;
16640}
16641
16642ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16643 ExprResult CallResult) {
16644 if (!getLangOpts().MatrixTypes) {
16645 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16646 return ExprError();
16647 }
16648
16649 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16651 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16652 << /*column*/ 1 << /*load*/ 0;
16653 return ExprError();
16654 }
16655
16656 if (checkArgCount(TheCall, 4))
16657 return ExprError();
16658
16659 unsigned PtrArgIdx = 0;
16660 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16661 Expr *RowsExpr = TheCall->getArg(1);
16662 Expr *ColumnsExpr = TheCall->getArg(2);
16663 Expr *StrideExpr = TheCall->getArg(3);
16664
16665 bool ArgError = false;
16666
16667 // Check pointer argument.
16668 {
16670 if (PtrConv.isInvalid())
16671 return PtrConv;
16672 PtrExpr = PtrConv.get();
16673 TheCall->setArg(0, PtrExpr);
16674 if (PtrExpr->isTypeDependent()) {
16675 TheCall->setType(Context.DependentTy);
16676 return TheCall;
16677 }
16678 }
16679
16680 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16681 QualType ElementTy;
16682 if (!PtrTy) {
16683 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16684 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16685 << PtrExpr->getType();
16686 ArgError = true;
16687 } else {
16688 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16689
16691 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16692 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16693 << /* no fp */ 0 << PtrExpr->getType();
16694 ArgError = true;
16695 }
16696 }
16697
16698 // Apply default Lvalue conversions and convert the expression to size_t.
16699 auto ApplyArgumentConversions = [this](Expr *E) {
16701 if (Conv.isInvalid())
16702 return Conv;
16703
16704 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16705 };
16706
16707 // Apply conversion to row and column expressions.
16708 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16709 if (!RowsConv.isInvalid()) {
16710 RowsExpr = RowsConv.get();
16711 TheCall->setArg(1, RowsExpr);
16712 } else
16713 RowsExpr = nullptr;
16714
16715 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16716 if (!ColumnsConv.isInvalid()) {
16717 ColumnsExpr = ColumnsConv.get();
16718 TheCall->setArg(2, ColumnsExpr);
16719 } else
16720 ColumnsExpr = nullptr;
16721
16722 // If any part of the result matrix type is still pending, just use
16723 // Context.DependentTy, until all parts are resolved.
16724 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16725 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16726 TheCall->setType(Context.DependentTy);
16727 return CallResult;
16728 }
16729
16730 // Check row and column dimensions.
16731 std::optional<unsigned> MaybeRows;
16732 if (RowsExpr)
16733 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16734
16735 std::optional<unsigned> MaybeColumns;
16736 if (ColumnsExpr)
16737 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16738
16739 // Check stride argument.
16740 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16741 if (StrideConv.isInvalid())
16742 return ExprError();
16743 StrideExpr = StrideConv.get();
16744 TheCall->setArg(3, StrideExpr);
16745
16746 if (MaybeRows) {
16747 if (std::optional<llvm::APSInt> Value =
16748 StrideExpr->getIntegerConstantExpr(Context)) {
16749 uint64_t Stride = Value->getZExtValue();
16750 if (Stride < *MaybeRows) {
16751 Diag(StrideExpr->getBeginLoc(),
16752 diag::err_builtin_matrix_stride_too_small);
16753 ArgError = true;
16754 }
16755 }
16756 }
16757
16758 if (ArgError || !MaybeRows || !MaybeColumns)
16759 return ExprError();
16760
16761 TheCall->setType(
16762 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16763 return CallResult;
16764}
16765
16766ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16767 ExprResult CallResult) {
16768 if (!getLangOpts().MatrixTypes) {
16769 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16770 return ExprError();
16771 }
16772
16773 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16775 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
16776 << /*column*/ 1 << /*store*/ 1;
16777 return ExprError();
16778 }
16779
16780 if (checkArgCount(TheCall, 3))
16781 return ExprError();
16782
16783 unsigned PtrArgIdx = 1;
16784 Expr *MatrixExpr = TheCall->getArg(0);
16785 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16786 Expr *StrideExpr = TheCall->getArg(2);
16787
16788 bool ArgError = false;
16789
16790 {
16791 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16792 if (MatrixConv.isInvalid())
16793 return MatrixConv;
16794 MatrixExpr = MatrixConv.get();
16795 TheCall->setArg(0, MatrixExpr);
16796 }
16797 if (MatrixExpr->isTypeDependent()) {
16798 TheCall->setType(Context.DependentTy);
16799 return TheCall;
16800 }
16801
16802 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16803 if (!MatrixTy) {
16804 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16805 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16806 ArgError = true;
16807 }
16808
16809 {
16811 if (PtrConv.isInvalid())
16812 return PtrConv;
16813 PtrExpr = PtrConv.get();
16814 TheCall->setArg(1, PtrExpr);
16815 if (PtrExpr->isTypeDependent()) {
16816 TheCall->setType(Context.DependentTy);
16817 return TheCall;
16818 }
16819 }
16820
16821 // Check pointer argument.
16822 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16823 if (!PtrTy) {
16824 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16825 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16826 << PtrExpr->getType();
16827 ArgError = true;
16828 } else {
16829 QualType ElementTy = PtrTy->getPointeeType();
16830 if (ElementTy.isConstQualified()) {
16831 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16832 ArgError = true;
16833 }
16834 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16835 if (MatrixTy &&
16836 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16837 Diag(PtrExpr->getBeginLoc(),
16838 diag::err_builtin_matrix_pointer_arg_mismatch)
16839 << ElementTy << MatrixTy->getElementType();
16840 ArgError = true;
16841 }
16842 }
16843
16844 // Apply default Lvalue conversions and convert the stride expression to
16845 // size_t.
16846 {
16847 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16848 if (StrideConv.isInvalid())
16849 return StrideConv;
16850
16851 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16852 if (StrideConv.isInvalid())
16853 return StrideConv;
16854 StrideExpr = StrideConv.get();
16855 TheCall->setArg(2, StrideExpr);
16856 }
16857
16858 // Check stride argument.
16859 if (MatrixTy) {
16860 if (std::optional<llvm::APSInt> Value =
16861 StrideExpr->getIntegerConstantExpr(Context)) {
16862 uint64_t Stride = Value->getZExtValue();
16863 if (Stride < MatrixTy->getNumRows()) {
16864 Diag(StrideExpr->getBeginLoc(),
16865 diag::err_builtin_matrix_stride_too_small);
16866 ArgError = true;
16867 }
16868 }
16869 }
16870
16871 if (ArgError)
16872 return ExprError();
16873
16874 return CallResult;
16875}
16876
16878 const NamedDecl *Callee) {
16879 // This warning does not make sense in code that has no runtime behavior.
16881 return;
16882
16883 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16884
16885 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16886 return;
16887
16888 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16889 // all TCBs the callee is a part of.
16890 llvm::StringSet<> CalleeTCBs;
16891 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16892 CalleeTCBs.insert(A->getTCBName());
16893 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16894 CalleeTCBs.insert(A->getTCBName());
16895
16896 // Go through the TCBs the caller is a part of and emit warnings if Caller
16897 // is in a TCB that the Callee is not.
16898 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16899 StringRef CallerTCB = A->getTCBName();
16900 if (CalleeTCBs.count(CallerTCB) == 0) {
16901 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16902 << Callee << CallerTCB;
16903 }
16904 }
16905}
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 BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
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)
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
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isComplexInt() const
Definition APValue.h:470
bool isFloat() const
Definition APValue.h:468
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isInt() const
Definition APValue.h:467
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
bool isAddrLabelDiff() const
Definition APValue.h:478
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:790
Builtin::Context & BuiltinInfo
Definition ASTContext.h:792
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:843
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4353
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4531
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4537
SourceLocation getQuestionLoc() const
Definition Expr.h:4380
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4543
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Expr * getBase()
Get base of the array section.
Definition Expr.h:7249
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7253
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getRBracketLoc() const
Definition Expr.h:2769
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3723
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3737
QualType getElementType() const
Definition TypeBase.h:3735
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6880
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7029
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7011
Attr - This represents one attribute.
Definition Attr.h:46
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4171
Expr * getLHS() const
Definition Expr.h:4088
SourceLocation getOperatorLoc() const
Definition Expr.h:4080
SourceLocation getExprLoc() const
Definition Expr.h:4079
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
Expr * getRHS() const
Definition Expr.h:4090
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4124
Opcode getOpcode() const
Definition Expr.h:4083
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4135
BinaryOperatorKind Opcode
Definition Expr.h:4043
Pointer to a block type.
Definition TypeBase.h:3543
This class is used for builtin types like 'int'.
Definition TypeBase.h:3165
bool isInteger() const
Definition TypeBase.h:3226
bool isFloatingPoint() const
Definition TypeBase.h:3238
bool isSignedInteger() const
Definition TypeBase.h:3230
bool isUnsignedInteger() const
Definition TypeBase.h:3234
Kind getKind() const
Definition TypeBase.h:3213
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:382
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:3969
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1630
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1688
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:154
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3147
SourceLocation getBeginLoc() const
Definition Expr.h:3277
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3160
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1591
arg_iterator arg_begin()
Definition Expr.h:3200
arg_iterator arg_end()
Definition Expr.h:3203
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3126
bool isCallToStdMove() const
Definition Expr.cpp:3623
Expr * getCallee()
Definition Expr.h:3090
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3134
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3236
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3137
arg_range arguments()
Definition Expr.h:3195
SourceLocation getEndLoc() const
Definition Expr.h:3296
SourceLocation getRParenLoc() const
Definition Expr.h:3274
Decl * getCalleeDecl()
Definition Expr.h:3120
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition Expr.cpp:1596
void setCallee(Expr *F)
Definition Expr.h:3092
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3179
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3676
path_iterator path_begin()
Definition Expr.h:3746
CastKind getCastKind() const
Definition Expr.h:3720
path_iterator path_end()
Definition Expr.h:3747
Expr * getSubExpr()
Definition Expr.h:3726
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
ConditionalOperator - The ?
Definition Expr.h:4391
Expr * getLHS() const
Definition Expr.h:4425
Expr * getRHS() const
Definition Expr.h:4426
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
QualType desugar() const
Definition TypeBase.h:3862
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3817
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4410
static ConvertVectorExpr * Create(const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5561
Expr * getOperand() const
Definition ExprCXX.h:5324
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:487
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1999
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4010
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4242
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4183
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:671
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:205
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4208
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3669
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3069
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4047
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:265
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:225
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4268
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4752
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2880
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4553
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3762
param_iterator param_end()
Definition Decl.h:2787
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3865
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3133
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4329
bool isStatic() const
Definition Decl.h:2929
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4144
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4130
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3826
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
unsigned getNumParams() const
Definition TypeBase.h:5547
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5668
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5554
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4774
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4770
QualType getReturnType() const
Definition TypeBase.h:4805
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3853
Describes an C or C++ initializer list.
Definition Expr.h:5299
ArrayRef< Expr * > inits()
Definition Expr.h:5349
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:974
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1030
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1066
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:508
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1113
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:858
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4359
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3364
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
Expr * getBase() const
Definition Expr.h:3441
bool isArrow() const
Definition Expr.h:3548
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1941
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1695
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1709
SourceLocation getSemiLoc() const
Definition Stmt.h:1706
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:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6756
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5076
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8376
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2867
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8292
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8418
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8332
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8344
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8386
void removeLocalVolatile()
Definition TypeBase.h:8408
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8400
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8365
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8413
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1671
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8338
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4324
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4410
field_range fields() const
Definition Decl.h:4527
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4402
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1025
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1108
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:107
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:30
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:382
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:283
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:535
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10329
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10334
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:856
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:1423
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:13073
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1121
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:2646
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9353
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9361
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9398
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:6950
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:2052
SemaHexagon & Hexagon()
Definition Sema.h:1463
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:1660
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:834
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1553
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:1288
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:225
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:924
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:1493
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:755
ASTContext & getASTContext() const
Definition Sema.h:927
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:2612
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:1192
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:2719
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:920
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:1438
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:1453
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:1286
static const uint64_t MaximumAlignment
Definition Sema.h:1215
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:953
SemaHLSL & HLSL()
Definition Sema.h:1458
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1478
SemaRISCV & RISCV()
Definition Sema.h:1523
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:2785
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6983
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1672
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:1321
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:2692
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15410
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:2301
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:640
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:1421
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:1503
FormatArgumentPassingKind
Definition Sema.h:2622
@ FAPK_Elsewhere
Definition Sema.h:2626
@ FAPK_Fixed
Definition Sema.h:2623
@ FAPK_Variadic
Definition Sema.h:2624
@ FAPK_VAList
Definition Sema.h:2625
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:8199
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:13963
SourceManager & getSourceManager() const
Definition Sema.h:925
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 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:2614
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:1513
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:1247
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:1543
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:1291
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:784
DiagnosticsEngine & Diags
Definition Sema.h:1290
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:1488
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:6250
SemaSPIRV & SPIRV()
Definition Sema.h:1528
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:1468
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6438
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:1548
SemaARM & ARM()
Definition Sema.h:1428
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4643
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
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:1485
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
bool isUTF8() const
Definition Expr.h:1918
bool isWide() const
Definition Expr.h:1917
bool isPascal() const
Definition Expr.h:1922
unsigned getLength() const
Definition Expr.h:1909
StringLiteralKind getKind() const
Definition Expr.h:1912
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition Expr.cpp:1325
bool isUTF32() const
Definition Expr.h:1920
unsigned getByteLength() const
Definition Expr.h:1908
StringRef getString() const
Definition Expr.h:1867
bool isUTF16() const
Definition Expr.h:1919
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1974
bool isOrdinary() const
Definition Expr.h:1916
unsigned getCharByteWidth() const
Definition Expr.h:1910
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3835
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3815
bool isUnion() const
Definition Decl.h:3925
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:388
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6180
A container of type source information.
Definition TypeBase.h:8263
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8274
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8549
bool isVoidType() const
Definition TypeBase.h:8891
bool isBooleanType() const
Definition TypeBase.h:9021
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2226
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9071
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:788
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2206
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2274
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2116
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9051
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2067
bool isVoidPointerType() const
Definition Type.cpp:713
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8628
bool isCharType() const
Definition Type.cpp:2133
bool isFunctionPointerType() const
Definition TypeBase.h:8596
bool isPointerType() const
Definition TypeBase.h:8529
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8935
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
bool isReferenceType() const
Definition TypeBase.h:8553
bool isEnumeralType() const
Definition TypeBase.h:8660
bool isScalarType() const
Definition TypeBase.h:8993
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1910
bool isVariableArrayType() const
Definition TypeBase.h:8640
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isExtVectorType() const
Definition TypeBase.h:8672
bool isExtVectorBoolType() const
Definition TypeBase.h:8676
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2647
bool isBitIntType() const
Definition TypeBase.h:8800
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8860
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8652
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2244
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3120
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool isAtomicType() const
Definition TypeBase.h:8717
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3075
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2801
bool isUnscopedEnumerationType() const
Definition Type.cpp:2126
bool isObjCObjectType() const
Definition TypeBase.h:8708
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9164
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9027
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8525
bool isObjCObjectPointerType() const
Definition TypeBase.h:8704
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2313
bool isStructureOrClassType() const
Definition Type.cpp:707
bool isVectorType() const
Definition TypeBase.h:8668
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2321
bool isFloatingType() const
Definition Type.cpp:2305
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2254
bool isAnyPointerType() const
Definition TypeBase.h:8537
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
bool isNullPtrType() const
Definition TypeBase.h:8928
bool isRecordType() const
Definition TypeBase.h:8656
bool isObjCRetainableType() const
Definition Type.cpp:5284
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5015
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2635
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2362
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3395
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5576
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4176
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2689
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:1318
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1303
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1296
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1310
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2518
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1264
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1325
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:818
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:513
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Comparison
A comparison.
Definition Sema.h:667
@ 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:594
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:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:499
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:521
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:144
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
#define true
Definition stdbool.h:25
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:13247
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13273
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13263
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13222
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6844
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2634
#define log2(__x)
Definition tgmath.h:970