clang 24.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"
48#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"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any unrecoverable errors, even if we managed
545 // to build the call.
546 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150namespace {
1151/// Helper class for buffer overflow/overread checking in fortified functions.
1152class FortifiedBufferChecker {
1153public:
1154 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1155 : S(S), TheCall(TheCall), FD(FD),
1156 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1157 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1158 SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1159 }
1160
1161 std::optional<unsigned> TranslateIndex(unsigned Index) {
1162 // If we refer to a diagnose_as_builtin attribute, we need to change the
1163 // argument index to refer to the arguments of the called function. Unless
1164 // the index is out of bounds, which presumably means it's a variadic
1165 // function.
1166 if (!DABAttr)
1167 return Index;
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 unsigned NewIndex = Index < DABIndices
1170 ? DABAttr->argIndices_begin()[Index]
1171 : Index - DABIndices + FD->getNumParams();
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 std::optional<llvm::APSInt>
1178 ComputeExplicitObjectSizeArgument(unsigned Index) {
1179 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1180 if (!IndexOptional)
1181 return std::nullopt;
1182 unsigned NewIndex = *IndexOptional;
1183 Expr::EvalResult Result;
1184 Expr *SizeArg = TheCall->getArg(NewIndex);
1185 if (!SizeArg->EvaluateAsInt(Result, S.getASTContext()))
1186 return std::nullopt;
1187 llvm::APSInt Integer = Result.Val.getInt();
1188 assert(Integer.isUnsigned() &&
1189 "size arg should be unsigned after implicit conversion to size_t");
1190 return Integer;
1191 }
1192
1193 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1194 // If the parameter has a pass_object_size attribute, then we should use its
1195 // (potentially) more strict checking mode. Otherwise, conservatively assume
1196 // type 0.
1197 int BOSType = 0;
1198 // This check can fail for variadic functions.
1199 if (Index < FD->getNumParams()) {
1200 if (const auto *POS =
1201 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1202 BOSType = POS->getType();
1203 }
1204
1205 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1206 if (!IndexOptional)
1207 return std::nullopt;
1208 unsigned NewIndex = *IndexOptional;
1209
1210 if (NewIndex >= TheCall->getNumArgs())
1211 return std::nullopt;
1212
1213 const Expr *ObjArg = TheCall->getArg(NewIndex);
1214 if (std::optional<uint64_t> ObjSize =
1215 ObjArg->tryEvaluateObjectSize(S.getASTContext(), BOSType)) {
1216 // Get the object size in the target's size_t width.
1217 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1218 }
1219 return std::nullopt;
1220 }
1221
1222 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1223 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1224 if (!IndexOptional)
1225 return std::nullopt;
1226 unsigned NewIndex = *IndexOptional;
1227
1228 const Expr *ObjArg = TheCall->getArg(NewIndex);
1229
1230 if (std::optional<uint64_t> Result =
1231 ObjArg->tryEvaluateStrLen(S.getASTContext())) {
1232 // Add 1 for null byte.
1233 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1234 }
1235 return std::nullopt;
1236 }
1237
1238 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1239
1240 unsigned getBuiltinID() const {
1241 const FunctionDecl *UseDecl = FD;
1242 if (DABAttr) {
1243 UseDecl = DABAttr->getFunction();
1244 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1245 }
1246 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1247 }
1248
1249 /// Return function name after stripping __builtin_ and _chk affixes.
1250 std::string getFunctionName() const {
1251 unsigned ID = getBuiltinID();
1252 if (!ID) {
1253 // Use callee name directly if not a builtin.
1254 const FunctionDecl *Callee = TheCall->getDirectCallee();
1255 assert(Callee && "expected callee");
1256 return Callee->getName().str();
1257 }
1258 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1259 StringRef Ref = Name;
1260 // Strip __builtin___*_chk or __builtin_ prefix.
1261 if (!(Ref.consume_front("__builtin___") && Ref.consume_back("_chk")))
1262 Ref.consume_front("__builtin_");
1263 assert(!Ref.empty() && "expected non-empty function name");
1264 return Ref.str();
1265 }
1266
1267 /// Check for source buffer overread in memory functions.
1268 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1270 return;
1271
1272 const Expr *SrcArg = TheCall->getArg(SrcArgIdx);
1273 const Expr *SizeArg = TheCall->getArg(SizeArgIdx);
1274 if (SrcArg->isInstantiationDependent() ||
1275 SizeArg->isInstantiationDependent())
1276 return;
1277
1278 std::optional<llvm::APSInt> CopyLen =
1279 ComputeExplicitObjectSizeArgument(SizeArgIdx);
1280 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(SrcArgIdx);
1281
1282 if (!CopyLen || !SrcBufSize)
1283 return;
1284
1285 // Warn only if copy length exceeds source buffer size.
1286 if (llvm::APSInt::compareValues(*CopyLen, *SrcBufSize) <= 0)
1287 return;
1288
1289 S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1290 S.PDiag(diag::warn_stringop_overread)
1291 << getFunctionName() << CopyLen->getZExtValue()
1292 << SrcBufSize->getZExtValue());
1293 }
1294
1295private:
1296 Sema &S;
1297 CallExpr *TheCall;
1298 FunctionDecl *FD;
1299 const DiagnoseAsBuiltinAttr *DABAttr;
1300 unsigned SizeTypeWidth;
1301};
1302} // anonymous namespace
1303
1304void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1305 CallExpr *TheCall) {
1307 return;
1308
1309 FortifiedBufferChecker Checker(*this, FD, TheCall);
1310
1311 unsigned BuiltinID = Checker.getBuiltinID();
1312 if (!BuiltinID)
1313 return;
1314
1315 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1316
1317 std::optional<llvm::APSInt> SourceSize;
1318 std::optional<llvm::APSInt> DestinationSize;
1319 unsigned DiagID = 0;
1320
1321 switch (BuiltinID) {
1322 default:
1323 return;
1324 case Builtin::BI__builtin_strcat:
1325 case Builtin::BIstrcat:
1326 case Builtin::BI__builtin_stpcpy:
1327 case Builtin::BIstpcpy:
1328 case Builtin::BI__builtin_strcpy:
1329 case Builtin::BIstrcpy: {
1330 DiagID = diag::warn_fortify_strlen_overflow;
1331 SourceSize = Checker.ComputeStrLenArgument(1);
1332 DestinationSize = Checker.ComputeSizeArgument(0);
1333 break;
1334 }
1335
1336 case Builtin::BI__builtin___strcat_chk:
1337 case Builtin::BI__builtin___stpcpy_chk:
1338 case Builtin::BI__builtin___strcpy_chk: {
1339 DiagID = diag::warn_fortify_strlen_overflow;
1340 SourceSize = Checker.ComputeStrLenArgument(1);
1341 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(2);
1342 break;
1343 }
1344
1345 case Builtin::BIscanf:
1346 case Builtin::BIfscanf:
1347 case Builtin::BIsscanf: {
1348 unsigned FormatIndex = 1;
1349 unsigned DataIndex = 2;
1350 if (BuiltinID == Builtin::BIscanf) {
1351 FormatIndex = 0;
1352 DataIndex = 1;
1353 }
1354
1355 const auto *FormatExpr =
1356 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1357
1358 StringRef FormatStrRef;
1359 size_t StrLen;
1360 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1361 return;
1362
1363 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1364 unsigned SourceSize) {
1365 DiagID = diag::warn_fortify_scanf_overflow;
1366 unsigned Index = ArgIndex + DataIndex;
1367 std::string FunctionName = Checker.getFunctionName();
1368 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1369 PDiag(DiagID) << FunctionName << (Index + 1)
1370 << DestSize << SourceSize);
1371 };
1372
1373 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1374 return Checker.ComputeSizeArgument(Index + DataIndex);
1375 };
1376 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1377 const char *FormatBytes = FormatStrRef.data();
1379 FormatBytes + StrLen, getLangOpts(),
1380 Context.getTargetInfo());
1381
1382 // Unlike the other cases, in this one we have already issued the diagnostic
1383 // here, so no need to continue (because unlike the other cases, here the
1384 // diagnostic refers to the argument number).
1385 return;
1386 }
1387
1388 case Builtin::BIsprintf:
1389 case Builtin::BI__builtin___sprintf_chk: {
1390 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1391 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1392
1393 StringRef FormatStrRef;
1394 size_t StrLen;
1395 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1396 EstimateSizeFormatHandler H(FormatStrRef);
1397 const char *FormatBytes = FormatStrRef.data();
1399 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1400 Context.getTargetInfo(), false)) {
1401 DiagID = H.isKernelCompatible()
1402 ? diag::warn_format_overflow
1403 : diag::warn_format_overflow_non_kprintf;
1404 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1405 .extOrTrunc(SizeTypeWidth);
1406 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1407 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(2);
1408 } else {
1409 DestinationSize = Checker.ComputeSizeArgument(0);
1410 }
1411 break;
1412 }
1413 }
1414 return;
1415 }
1416 case Builtin::BI__builtin___memcpy_chk:
1417 case Builtin::BI__builtin___memmove_chk:
1418 case Builtin::BI__builtin___memset_chk:
1419 case Builtin::BI__builtin___strlcat_chk:
1420 case Builtin::BI__builtin___strlcpy_chk:
1421 case Builtin::BI__builtin___strncat_chk:
1422 case Builtin::BI__builtin___strncpy_chk:
1423 case Builtin::BI__builtin___stpncpy_chk:
1424 case Builtin::BI__builtin___memccpy_chk:
1425 case Builtin::BI__builtin___mempcpy_chk: {
1426 DiagID = diag::warn_builtin_chk_overflow;
1427 SourceSize =
1428 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1429 DestinationSize =
1430 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1431
1432 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1433 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1434 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1435 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1436 }
1437 break;
1438 }
1439
1440 case Builtin::BI__builtin___snprintf_chk:
1441 case Builtin::BI__builtin___vsnprintf_chk: {
1442 DiagID = diag::warn_builtin_chk_overflow;
1443 SourceSize = Checker.ComputeExplicitObjectSizeArgument(1);
1444 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(3);
1445 break;
1446 }
1447
1448 case Builtin::BIstrncat:
1449 case Builtin::BI__builtin_strncat:
1450 case Builtin::BIstrncpy:
1451 case Builtin::BI__builtin_strncpy:
1452 case Builtin::BIstpncpy:
1453 case Builtin::BI__builtin_stpncpy: {
1454 // Whether these functions overflow depends on the runtime strlen of the
1455 // string, not just the buffer size, so emitting the "always overflow"
1456 // diagnostic isn't quite right. We should still diagnose passing a buffer
1457 // size larger than the destination buffer though; this is a runtime abort
1458 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1459 DiagID = diag::warn_fortify_source_size_mismatch;
1460 SourceSize =
1461 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1462 DestinationSize = Checker.ComputeSizeArgument(0);
1463 break;
1464 }
1465
1466 case Builtin::BIbzero:
1467 case Builtin::BI__builtin_bzero:
1468 case Builtin::BImemcpy:
1469 case Builtin::BI__builtin_memcpy:
1470 case Builtin::BImemmove:
1471 case Builtin::BI__builtin_memmove:
1472 case Builtin::BImemset:
1473 case Builtin::BI__builtin_memset:
1474 case Builtin::BImempcpy:
1475 case Builtin::BI__builtin_mempcpy: {
1476 DiagID = diag::warn_fortify_source_overflow;
1477 SourceSize =
1478 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1479 DestinationSize = Checker.ComputeSizeArgument(0);
1480
1481 // Buffer overread doesn't make sense for memset/bzero.
1482 if (BuiltinID != Builtin::BImemset &&
1483 BuiltinID != Builtin::BI__builtin_memset &&
1484 BuiltinID != Builtin::BIbzero &&
1485 BuiltinID != Builtin::BI__builtin_bzero) {
1486 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1487 }
1488 break;
1489 }
1490 case Builtin::BIbcopy:
1491 case Builtin::BI__builtin_bcopy: {
1492 DiagID = diag::warn_fortify_source_overflow;
1493 SourceSize =
1494 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1495 DestinationSize = Checker.ComputeSizeArgument(1);
1496 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1497 break;
1498 }
1499
1500 // memchr(buf, val, size)
1501 case Builtin::BImemchr:
1502 case Builtin::BI__builtin_memchr: {
1503 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1504 return;
1505 }
1506
1507 // memcmp/bcmp(buf0, buf1, size)
1508 // Two checks since each buffer is read
1509 case Builtin::BImemcmp:
1510 case Builtin::BI__builtin_memcmp:
1511 case Builtin::BIbcmp:
1512 case Builtin::BI__builtin_bcmp: {
1513 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1514 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1515 return;
1516 }
1517 case Builtin::BIsnprintf:
1518 case Builtin::BI__builtin_snprintf:
1519 case Builtin::BIvsnprintf:
1520 case Builtin::BI__builtin_vsnprintf: {
1521 DiagID = diag::warn_fortify_source_size_mismatch;
1522 SourceSize = Checker.ComputeExplicitObjectSizeArgument(1);
1523 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1524 StringRef FormatStrRef;
1525 size_t StrLen;
1526 if (SourceSize &&
1527 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1528 EstimateSizeFormatHandler H(FormatStrRef);
1529 const char *FormatBytes = FormatStrRef.data();
1531 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1532 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1533 llvm::APSInt FormatSize =
1534 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1535 .extOrTrunc(SizeTypeWidth);
1536 if (FormatSize > *SourceSize && *SourceSize != 0) {
1537 unsigned TruncationDiagID =
1538 H.isKernelCompatible() ? diag::warn_format_truncation
1539 : diag::warn_format_truncation_non_kprintf;
1540 SmallString<16> SpecifiedSizeStr;
1541 SmallString<16> FormatSizeStr;
1542 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1543 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1544 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1545 PDiag(TruncationDiagID)
1546 << Checker.getFunctionName()
1547 << SpecifiedSizeStr << FormatSizeStr);
1548 }
1549 }
1550 }
1551 DestinationSize = Checker.ComputeSizeArgument(0);
1552 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1553 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1554 IdentifierInfo *FnInfo = FD->getIdentifier();
1555 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1556 }
1557 }
1558
1559 if (!SourceSize || !DestinationSize ||
1560 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1561 return;
1562
1563 std::string FunctionName = Checker.getFunctionName();
1564
1565 SmallString<16> DestinationStr;
1566 SmallString<16> SourceStr;
1567 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1568 SourceSize->toString(SourceStr, /*Radix=*/10);
1569 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1570 PDiag(DiagID)
1571 << FunctionName << DestinationStr << SourceStr);
1572}
1573
1574void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1575 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1576 return;
1577
1578 // Recognize the libc function by builtin identity rather than by name and
1579 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1580 // builtin id is attached to any file-scope, C-linkage declaration of umask
1581 // regardless of the libc's mode_t spelling -- including a hand-written
1582 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1583 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1584 if (FD->getBuiltinID() != Builtin::BIumask)
1585 return;
1586
1587 // umask(mode_t): warn when the constant-evaluated argument has bits set
1588 // outside the file-permission mask (0777). Those bits are ignored.
1589 if (TheCall->getNumArgs() != 1)
1590 return;
1591 Expr *Arg = TheCall->getArg(0);
1592 if (!Arg->getType()->isIntegerType())
1593 return;
1594 Expr::EvalResult R;
1595 if (!Arg->EvaluateAsInt(R, getASTContext()))
1596 return;
1597 // Operate on the raw two's-complement bit pattern so that negative literals
1598 // (which convert to large unsigned mode_t values) are caught.
1599 llvm::APInt RawValue = R.Val.getInt();
1600 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1601 llvm::APInt Extra = RawValue & ~Mask;
1602 if (Extra == 0)
1603 return;
1604 SmallString<16> ExtraStr;
1605 Extra.toString(ExtraStr, /*Radix=*/8, /*Signed=*/false);
1606 Diag(TheCall->getBeginLoc(), diag::warn_fortify_umask_unused_bits)
1607 << ExtraStr;
1608}
1609
1610static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1611 Scope::ScopeFlags NeededScopeFlags,
1612 unsigned DiagID) {
1613 // Scopes aren't available during instantiation. Fortunately, builtin
1614 // functions cannot be template args so they cannot be formed through template
1615 // instantiation. Therefore checking once during the parse is sufficient.
1616 if (SemaRef.inTemplateInstantiation())
1617 return false;
1618
1619 Scope *S = SemaRef.getCurScope();
1620 while (S && !S->isSEHExceptScope())
1621 S = S->getParent();
1622 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1623 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1624 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1625 << DRE->getDecl()->getIdentifier();
1626 return true;
1627 }
1628
1629 return false;
1630}
1631
1632// In OpenCL, __builtin_alloca_* should return a pointer to address space
1633// that corresponds to the stack address space i.e private address space.
1634static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1635 QualType RT = TheCall->getType();
1636 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1637 "__builtin_alloca has invalid address space");
1638
1639 RT = RT->getPointeeType();
1641 TheCall->setType(S.Context.getPointerType(RT));
1642}
1643
1644static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1645 if (S.checkArgCountAtLeast(TheCall, 1))
1646 return true;
1647
1648 for (Expr *Arg : TheCall->arguments()) {
1649 // If argument is dependent on a template parameter, we can't resolve now.
1650 if (Arg->isTypeDependent() || Arg->isValueDependent())
1651 continue;
1652 // Reject void types.
1653 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1654 if (ArgTy->isVoidType())
1655 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1656 }
1657
1658 TheCall->setType(S.Context.getSizeType());
1659 return false;
1660}
1661
1662namespace {
1663enum PointerAuthOpKind {
1664 PAO_Strip,
1665 PAO_Sign,
1666 PAO_Auth,
1667 PAO_SignGeneric,
1668 PAO_Discriminator,
1669 PAO_BlendPointer,
1670 PAO_BlendInteger,
1671 PAO_BlendPC
1672};
1673}
1674
1676 if (getLangOpts().PointerAuthIntrinsics)
1677 return false;
1678
1679 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1680 return true;
1681}
1682
1683static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1685}
1686
1687static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1688 // Convert it to type 'int'.
1689 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1690 return true;
1691
1692 // Value-dependent expressions are okay; wait for template instantiation.
1693 if (Arg->isValueDependent())
1694 return false;
1695
1696 unsigned KeyValue;
1697 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1698}
1699
1701 // Attempt to constant-evaluate the expression.
1702 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1703 if (!KeyValue) {
1704 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1705 << 0 << Arg->getSourceRange();
1706 return true;
1707 }
1708
1709 // Ask the target to validate the key parameter.
1710 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1712 {
1713 llvm::raw_svector_ostream Str(Value);
1714 Str << *KeyValue;
1715 }
1716
1717 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1718 << Value << Arg->getSourceRange();
1719 return true;
1720 }
1721
1722 Result = KeyValue->getZExtValue();
1723 return false;
1724}
1725
1728 unsigned &IntVal) {
1729 if (!Arg) {
1730 IntVal = 0;
1731 return true;
1732 }
1733
1734 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1735 if (!Result) {
1736 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1737 return false;
1738 }
1739
1740 unsigned Max;
1741 bool IsAddrDiscArg = false;
1742
1743 switch (Kind) {
1745 Max = 1;
1746 IsAddrDiscArg = true;
1747 break;
1750 break;
1751 };
1752
1754 if (IsAddrDiscArg)
1755 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1756 << Result->getExtValue();
1757 else
1758 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1759 << Result->getExtValue() << Max;
1760
1761 return false;
1762 };
1763
1764 IntVal = Result->getZExtValue();
1765 return true;
1766}
1767
1768static std::pair<const ValueDecl *, CharUnits>
1770 // Must evaluate as a pointer.
1772 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1773 return {nullptr, CharUnits()};
1774
1775 const auto *BaseDecl =
1776 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1777 if (!BaseDecl)
1778 return {nullptr, CharUnits()};
1779
1780 return {BaseDecl, Result.Val.getLValueOffset()};
1781}
1782
1783static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1784 bool RequireConstant = false) {
1785 if (Arg->hasPlaceholderType()) {
1787 if (R.isInvalid())
1788 return true;
1789 Arg = R.get();
1790 }
1791
1792 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1793 return OpKind != PAO_BlendInteger;
1794 };
1795 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1796 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1797 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1798 };
1799
1800 // Require the value to have the right range of type.
1801 QualType ExpectedTy;
1802 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1803 ExpectedTy = Arg->getType().getUnqualifiedType();
1804 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1805 ExpectedTy = S.Context.VoidPtrTy;
1806 } else if (AllowsInteger(OpKind) &&
1808 ExpectedTy = S.Context.getUIntPtrType();
1809
1810 } else {
1811 // Diagnose the failures.
1812 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1813 << unsigned(OpKind == PAO_Discriminator ? 1
1814 : OpKind == PAO_BlendPointer ? 2
1815 : OpKind == PAO_BlendInteger ? 3
1816 : OpKind == PAO_BlendPC ? 4
1817 : 0)
1818 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1819 << Arg->getType() << Arg->getSourceRange();
1820 return true;
1821 }
1822
1823 // Convert to that type. This should just be an lvalue-to-rvalue
1824 // conversion.
1825 if (convertArgumentToType(S, Arg, ExpectedTy))
1826 return true;
1827
1828 if (!RequireConstant) {
1829 // Warn about null pointers for non-generic sign and auth operations.
1830 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1832 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1833 ? diag::warn_ptrauth_sign_null_pointer
1834 : diag::warn_ptrauth_auth_null_pointer)
1835 << Arg->getSourceRange();
1836 }
1837
1838 return false;
1839 }
1840
1841 // Perform special checking on the arguments to ptrauth_sign_constant.
1842
1843 // The main argument.
1844 if (OpKind == PAO_Sign) {
1845 // Require the value we're signing to have a special form.
1846 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1847 bool Invalid;
1848
1849 // Must be rooted in a declaration reference.
1850 if (!BaseDecl)
1851 Invalid = true;
1852
1853 // If it's a function declaration, we can't have an offset.
1854 else if (isa<FunctionDecl>(BaseDecl))
1855 Invalid = !Offset.isZero();
1856
1857 // Otherwise we're fine.
1858 else
1859 Invalid = false;
1860
1861 if (Invalid)
1862 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1863 return Invalid;
1864 }
1865
1866 // The discriminator argument.
1867 assert(OpKind == PAO_Discriminator);
1868
1869 // Must be a pointer or integer or blend thereof.
1870 Expr *Pointer = nullptr;
1871 Expr *Integer = nullptr;
1872 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1873 if (Call->getBuiltinCallee() ==
1874 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1875 Pointer = Call->getArg(0);
1876 Integer = Call->getArg(1);
1877 }
1878 }
1879 if (!Pointer && !Integer) {
1880 if (Arg->getType()->isPointerType())
1881 Pointer = Arg;
1882 else
1883 Integer = Arg;
1884 }
1885
1886 // Check the pointer.
1887 bool Invalid = false;
1888 if (Pointer) {
1889 assert(Pointer->getType()->isPointerType());
1890
1891 // TODO: if we're initializing a global, check that the address is
1892 // somehow related to what we're initializing. This probably will
1893 // never really be feasible and we'll have to catch it at link-time.
1894 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1895 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1896 Invalid = true;
1897 }
1898
1899 // Check the integer.
1900 if (Integer) {
1901 assert(Integer->getType()->isIntegerType());
1902 if (!Integer->isEvaluatable(S.Context))
1903 Invalid = true;
1904 }
1905
1906 if (Invalid)
1907 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1908 return Invalid;
1909}
1910
1912 if (S.checkArgCount(Call, 2))
1913 return ExprError();
1915 return ExprError();
1916 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1917 checkPointerAuthKey(S, Call->getArgs()[1]))
1918 return ExprError();
1919
1920 Call->setType(Call->getArgs()[0]->getType());
1921 return Call;
1922}
1923
1925 if (S.checkArgCount(Call, 2))
1926 return ExprError();
1928 return ExprError();
1929 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1930 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1931 return ExprError();
1932
1933 Call->setType(S.Context.getUIntPtrType());
1934 return Call;
1935}
1936
1938 if (S.checkArgCount(Call, 2))
1939 return ExprError();
1941 return ExprError();
1942 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1943 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1944 return ExprError();
1945
1946 Call->setType(S.Context.getUIntPtrType());
1947 return Call;
1948}
1949
1951 PointerAuthOpKind OpKind,
1952 bool RequireConstant) {
1953 if (S.checkArgCount(Call, 3))
1954 return ExprError();
1956 return ExprError();
1957 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1958 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1959 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1960 RequireConstant))
1961 return ExprError();
1962
1963 Call->setType(Call->getArgs()[0]->getType());
1964 return Call;
1965}
1966
1968 if (S.checkArgCount(Call, 5))
1969 return ExprError();
1971 return ExprError();
1972 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1973 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1974 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1975 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1976 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1977 return ExprError();
1978
1979 Call->setType(Call->getArgs()[0]->getType());
1980 return Call;
1981}
1982
1984 if (S.checkArgCount(Call, 6))
1985 return ExprError();
1987 return ExprError();
1988 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1989 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1990 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1991 checkPointerAuthValue(S, Call->getArgs()[3], PAO_BlendPC) ||
1992 checkPointerAuthKey(S, Call->getArgs()[4]) ||
1993 checkPointerAuthValue(S, Call->getArgs()[5], PAO_Discriminator))
1994 return ExprError();
1995
1996 // Validate that the oldKey is IA or IB, not DA or DB.
1997 // This enforces the constraint that auth_with_pc_and_resign only supports
1998 // IA/IB keys for authentication, as only those keys support the PC-based
1999 // signing instructions (paciasppc/pacibsppc).
2000 unsigned OldKey = 0;
2001 if (!S.checkConstantPointerAuthKey(Call->getArgs()[1], OldKey)) {
2003 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2004 OldKey != static_cast<unsigned>(AK::ASIB)) {
2005 S.Diag(Call->getArgs()[1]->getExprLoc(),
2006 diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2007 << OldKey << Call->getArgs()[1]->getSourceRange();
2008 return ExprError();
2009 }
2010 }
2011
2012 Call->setType(Call->getArgs()[0]->getType());
2013 return Call;
2014}
2015
2017 if (S.checkArgCount(Call, 6))
2018 return ExprError();
2020 return ExprError();
2021 const Expr *AddendExpr = Call->getArg(5);
2022 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
2023 if (!AddendIsConstInt) {
2024 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
2025 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
2026 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2027 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
2028 << FDecl->getDeclName() << Arg->getSourceRange();
2029 }
2030 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2031 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2032 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2033 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2034 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
2035 !AddendIsConstInt)
2036 return ExprError();
2037
2038 Call->setType(Call->getArgs()[0]->getType());
2039 return Call;
2040}
2041
2044 return ExprError();
2045
2046 // We've already performed normal call type-checking.
2047 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
2048
2049 // Operand must be an ordinary or UTF-8 string literal.
2050 const auto *Literal = dyn_cast<StringLiteral>(Arg);
2051 if (!Literal || Literal->getCharByteWidth() != 1) {
2052 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
2053 << (Literal ? 1 : 0) << Arg->getSourceRange();
2054 return ExprError();
2055 }
2056
2057 return Call;
2058}
2059
2061 if (S.checkArgCount(Call, 1))
2062 return ExprError();
2063 Expr *FirstArg = Call->getArg(0);
2064 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
2065 if (FirstValue.isInvalid())
2066 return ExprError();
2067 Call->setArg(0, FirstValue.get());
2068 QualType FirstArgType = FirstArg->getType();
2069 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2070 FirstArgType = S.Context.getDecayedType(FirstArgType);
2071
2072 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2073 if (!FirstArgRecord) {
2074 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2075 << /*isPolymorphic=*/0 << FirstArgType;
2076 return ExprError();
2077 }
2078 if (S.RequireCompleteType(
2079 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
2080 diag::err_get_vtable_pointer_requires_complete_type)) {
2081 return ExprError();
2082 }
2083
2084 if (!FirstArgRecord->isPolymorphic()) {
2085 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2086 << /*isPolymorphic=*/1 << FirstArgRecord;
2087 return ExprError();
2088 }
2090 Call->setType(ReturnType);
2091 return Call;
2092}
2093
2095 if (S.checkArgCount(TheCall, 1))
2096 return ExprError();
2097
2098 // Compute __builtin_launder's parameter type from the argument.
2099 // The parameter type is:
2100 // * The type of the argument if it's not an array or function type,
2101 // Otherwise,
2102 // * The decayed argument type.
2103 QualType ParamTy = [&]() {
2104 QualType ArgTy = TheCall->getArg(0)->getType();
2105 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2106 return S.Context.getPointerType(Ty->getElementType());
2107 if (ArgTy->isFunctionType()) {
2108 return S.Context.getPointerType(ArgTy);
2109 }
2110 return ArgTy;
2111 }();
2112
2113 TheCall->setType(ParamTy);
2114
2115 auto DiagSelect = [&]() -> std::optional<unsigned> {
2116 if (!ParamTy->isPointerType())
2117 return 0;
2118 if (ParamTy->isFunctionPointerType())
2119 return 1;
2120 if (ParamTy->isVoidPointerType())
2121 return 2;
2122 return std::optional<unsigned>{};
2123 }();
2124 if (DiagSelect) {
2125 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2126 << *DiagSelect << TheCall->getSourceRange();
2127 return ExprError();
2128 }
2129
2130 // We either have an incomplete class type, or we have a class template
2131 // whose instantiation has not been forced. Example:
2132 //
2133 // template <class T> struct Foo { T value; };
2134 // Foo<int> *p = nullptr;
2135 // auto *d = __builtin_launder(p);
2136 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2137 diag::err_incomplete_type))
2138 return ExprError();
2139
2140 assert(ParamTy->getPointeeType()->isObjectType() &&
2141 "Unhandled non-object pointer case");
2142
2143 InitializedEntity Entity =
2145 ExprResult Arg =
2146 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2147 if (Arg.isInvalid())
2148 return ExprError();
2149 TheCall->setArg(0, Arg.get());
2150
2151 return TheCall;
2152}
2153
2155 if (S.checkArgCount(TheCall, 1))
2156 return ExprError();
2157
2159 if (Arg.isInvalid())
2160 return ExprError();
2161 QualType ParamTy = Arg.get()->getType();
2162 TheCall->setArg(0, Arg.get());
2163 TheCall->setType(S.Context.BoolTy);
2164
2165 // Only accept pointers to objects as arguments, which should have object
2166 // pointer or void pointer types.
2167 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2168 // LWG4138: Function pointer types not allowed
2169 if (PT->getPointeeType()->isFunctionType()) {
2170 S.Diag(TheCall->getArg(0)->getExprLoc(),
2171 diag::err_builtin_is_within_lifetime_invalid_arg)
2172 << 1;
2173 return ExprError();
2174 }
2175 // Disallow VLAs too since those shouldn't be able to
2176 // be a template parameter for `std::is_within_lifetime`
2177 if (PT->getPointeeType()->isVariableArrayType()) {
2178 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2179 << 1 << "__builtin_is_within_lifetime";
2180 return ExprError();
2181 }
2182 } else {
2183 S.Diag(TheCall->getArg(0)->getExprLoc(),
2184 diag::err_builtin_is_within_lifetime_invalid_arg)
2185 << 0;
2186 return ExprError();
2187 }
2188 return TheCall;
2189}
2190
2192 if (S.checkArgCount(TheCall, 3))
2193 return ExprError();
2194
2195 QualType Dest = TheCall->getArg(0)->getType();
2196 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2197 S.Diag(TheCall->getArg(0)->getExprLoc(),
2198 diag::err_builtin_trivially_relocate_invalid_arg_type)
2199 << /*a pointer*/ 0;
2200 return ExprError();
2201 }
2202
2203 QualType T = Dest->getPointeeType();
2204 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2205 diag::err_incomplete_type))
2206 return ExprError();
2207
2208 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2209 T->isIncompleteArrayType()) {
2210 S.Diag(TheCall->getArg(0)->getExprLoc(),
2211 diag::err_builtin_trivially_relocate_invalid_arg_type)
2212 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2213 return ExprError();
2214 }
2215
2216 TheCall->setType(Dest);
2217
2218 QualType Src = TheCall->getArg(1)->getType();
2219 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2220 S.Diag(TheCall->getArg(1)->getExprLoc(),
2221 diag::err_builtin_trivially_relocate_invalid_arg_type)
2222 << /*the same*/ 3;
2223 return ExprError();
2224 }
2225
2226 Expr *SizeExpr = TheCall->getArg(2);
2227 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2228 if (Size.isInvalid())
2229 return ExprError();
2230
2231 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2232 if (Size.isInvalid())
2233 return ExprError();
2234 SizeExpr = Size.get();
2235 TheCall->setArg(2, SizeExpr);
2236
2237 return TheCall;
2238}
2239
2240// Emit an error and return true if the current object format type is in the
2241// list of unsupported types.
2243 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2244 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2245 llvm::Triple::ObjectFormatType CurObjFormat =
2246 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2247 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2248 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2249 << TheCall->getSourceRange();
2250 return true;
2251 }
2252 return false;
2253}
2254
2255// Emit an error and return true if the current architecture is not in the list
2256// of supported architectures.
2257static bool
2259 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2260 llvm::Triple::ArchType CurArch =
2261 S.getASTContext().getTargetInfo().getTriple().getArch();
2262 if (llvm::is_contained(SupportedArchs, CurArch))
2263 return false;
2264 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2265 << TheCall->getSourceRange();
2266 return true;
2267}
2268
2269static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2270 SourceLocation CallSiteLoc);
2271
2272bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2273 CallExpr *TheCall) {
2274 switch (TI.getTriple().getArch()) {
2275 default:
2276 // Some builtins don't require additional checking, so just consider these
2277 // acceptable.
2278 return false;
2279 case llvm::Triple::arm:
2280 case llvm::Triple::armeb:
2281 case llvm::Triple::thumb:
2282 case llvm::Triple::thumbeb:
2283 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2284 case llvm::Triple::aarch64:
2285 case llvm::Triple::aarch64_32:
2286 case llvm::Triple::aarch64_be:
2287 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2288 case llvm::Triple::bpfeb:
2289 case llvm::Triple::bpfel:
2290 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2291 case llvm::Triple::dxil:
2292 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2293 case llvm::Triple::hexagon:
2294 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2295 case llvm::Triple::mips:
2296 case llvm::Triple::mipsel:
2297 case llvm::Triple::mips64:
2298 case llvm::Triple::mips64el:
2299 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2300 case llvm::Triple::spirv:
2301 case llvm::Triple::spirv32:
2302 case llvm::Triple::spirv64:
2303 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2304 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2305 return false;
2306 case llvm::Triple::systemz:
2307 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2308 case llvm::Triple::x86:
2309 case llvm::Triple::x86_64:
2310 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2311 case llvm::Triple::ppc:
2312 case llvm::Triple::ppcle:
2313 case llvm::Triple::ppc64:
2314 case llvm::Triple::ppc64le:
2315 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2316 case llvm::Triple::amdgpu:
2317 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2318 case llvm::Triple::riscv32:
2319 case llvm::Triple::riscv64:
2320 case llvm::Triple::riscv32be:
2321 case llvm::Triple::riscv64be:
2322 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2323 case llvm::Triple::loongarch32:
2324 case llvm::Triple::loongarch64:
2325 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2326 TheCall);
2327 case llvm::Triple::wasm32:
2328 case llvm::Triple::wasm64:
2329 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2330 case llvm::Triple::nvptx:
2331 case llvm::Triple::nvptx64:
2332 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2333 }
2334}
2335
2337 return T->isDependentType() ||
2338 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2339}
2340
2341// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2342// not a valid type, emit an error message and return true. Otherwise return
2343// false.
2344static bool
2347 int ArgOrdinal) {
2348 clang::QualType EltTy =
2349 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2350 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2351 : ArgTy;
2352
2353 switch (ArgTyRestr) {
2355 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2356 !isValidMathElementType(ArgTy)) {
2357 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2358 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2359 << ArgTy;
2360 }
2361 break;
2363 if (!EltTy->isRealFloatingType()) {
2364 // FIXME: make diagnostic's wording correct for matrices
2365 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2366 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2367 << /* floating-point */ 1 << ArgTy;
2368 }
2369 break;
2371 if (!EltTy->isIntegerType()) {
2372 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2373 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2374 << /* no fp */ 0 << ArgTy;
2375 }
2376 break;
2378 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2379 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2380 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2381 << /* or fp */ 1 << ArgTy;
2382 }
2383 break;
2384 }
2385
2386 return false;
2387}
2388
2389/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2390/// This checks that the target supports the builtin and that the string
2391/// argument is constant and valid.
2392static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2393 const TargetInfo *AuxTI, unsigned BuiltinID) {
2394 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2395 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2396 "Expecting __builtin_cpu_...");
2397
2398 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2399 const TargetInfo *TheTI = &TI;
2400 auto SupportsBI = [=](const TargetInfo *TInfo) {
2401 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2402 (!IsCPUSupports && TInfo->supportsCpuIs()));
2403 };
2404 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2405 TheTI = AuxTI;
2406
2407 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2408 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2409 return S.Diag(TheCall->getBeginLoc(),
2410 TI.getTriple().isOSAIX()
2411 ? diag::err_builtin_aix_os_unsupported
2412 : diag::err_builtin_target_unsupported)
2413 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2414
2415 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2416 // Check if the argument is a string literal.
2417 if (!isa<StringLiteral>(Arg))
2418 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2419 << Arg->getSourceRange();
2420
2421 // Check the contents of the string.
2422 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2423 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2424 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2425 << Arg->getSourceRange();
2426 return false;
2427 }
2428 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2429 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2430 << Arg->getSourceRange();
2431 return false;
2432}
2433
2434/// Checks that __builtin_bswapg was called with a single argument, which is an
2435/// unsigned integer, and overrides the return value type to the integer type.
2436static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2437 if (S.checkArgCount(TheCall, 1))
2438 return true;
2439 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2440 if (ArgRes.isInvalid())
2441 return true;
2442
2443 Expr *Arg = ArgRes.get();
2444 TheCall->setArg(0, Arg);
2445 if (Arg->isTypeDependent())
2446 return false;
2447
2448 QualType ArgTy = Arg->getType();
2449
2450 if (!ArgTy->isIntegerType()) {
2451 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2452 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2453 << ArgTy;
2454 return true;
2455 }
2456 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2457 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2458 BT->getNumBits() != 1) {
2459 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2460 << ArgTy << BT->getNumBits();
2461 return true;
2462 }
2463 }
2464 TheCall->setType(ArgTy);
2465 return false;
2466}
2467
2468/// Checks that __builtin_bitreverseg was called with a single argument, which
2469/// is an integer
2470static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2471 if (S.checkArgCount(TheCall, 1))
2472 return true;
2473 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2474 if (ArgRes.isInvalid())
2475 return true;
2476
2477 Expr *Arg = ArgRes.get();
2478 TheCall->setArg(0, Arg);
2479 if (Arg->isTypeDependent())
2480 return false;
2481
2482 QualType ArgTy = Arg->getType();
2483
2484 if (!ArgTy->isIntegerType()) {
2485 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2486 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2487 << ArgTy;
2488 return true;
2489 }
2490 TheCall->setType(ArgTy);
2491 return false;
2492}
2493
2494/// Checks that __builtin_popcountg was called with a single argument, which is
2495/// an unsigned integer.
2496static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2497 if (S.checkArgCount(TheCall, 1))
2498 return true;
2499
2500 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2501 if (ArgRes.isInvalid())
2502 return true;
2503
2504 Expr *Arg = ArgRes.get();
2505 TheCall->setArg(0, Arg);
2506
2507 QualType ArgTy = Arg->getType();
2508
2509 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2510 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2511 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2512 << ArgTy;
2513 return true;
2514 }
2515 return false;
2516}
2517
2518/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2519/// argument and return either int, bool, or the argument type.
2520static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2521 QualType ReturnType) {
2522 if (S.checkArgCount(TheCall, 1))
2523 return true;
2524
2525 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2526 if (ArgRes.isInvalid())
2527 return true;
2528
2529 Expr *Arg = ArgRes.get();
2530 TheCall->setArg(0, Arg);
2531
2532 QualType ArgTy = Arg->getType();
2533 // C23 stdbit.h functions do not permit bool or enumeration types.
2534 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2535 return S.Diag(Arg->getBeginLoc(),
2536 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2537 << 1 /*1st argument*/ << ArgTy;
2538 if (!ArgTy->isUnsignedIntegerType())
2539 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2540 << 1 /*1st argument*/ << ArgTy;
2541
2542 // For builtins returning unsigned int, verify the argument's bit width fits.
2543 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2544 // produce a count that overflows the return type.
2545 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2546 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2547 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2548 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2549 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2550 << ArgTy;
2551 }
2552
2553 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2554 return false;
2555}
2556
2557/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2558/// an unsigned integer, and an optional second argument, which is promoted to
2559/// an 'int'.
2560static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2561 if (S.checkArgCountRange(TheCall, 1, 2))
2562 return true;
2563
2564 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2565 if (Arg0Res.isInvalid())
2566 return true;
2567
2568 Expr *Arg0 = Arg0Res.get();
2569 TheCall->setArg(0, Arg0);
2570
2571 QualType Arg0Ty = Arg0->getType();
2572
2573 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2574 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2575 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2576 << Arg0Ty;
2577 return true;
2578 }
2579
2580 if (TheCall->getNumArgs() > 1) {
2581 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2582 if (Arg1Res.isInvalid())
2583 return true;
2584
2585 Expr *Arg1 = Arg1Res.get();
2586 TheCall->setArg(1, Arg1);
2587
2588 QualType Arg1Ty = Arg1->getType();
2589
2590 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2591 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2592 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2593 return true;
2594 }
2595 }
2596
2597 return false;
2598}
2599
2601 unsigned ArgIndex;
2602 bool OnlyUnsigned;
2603
2605 QualType T) {
2606 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2607 << ArgIndex << /*scalar*/ 1
2608 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2609 << /*no fp*/ 0 << T;
2610 }
2611
2612public:
2613 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2614 : ContextualImplicitConverter(/*Suppress=*/false,
2615 /*SuppressConversion=*/true),
2616 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2617
2618 bool match(QualType T) override {
2619 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2620 }
2621
2623 QualType T) override {
2624 return emitError(S, Loc, T);
2625 }
2626
2628 QualType T) override {
2629 return emitError(S, Loc, T);
2630 }
2631
2633 QualType T,
2634 QualType ConvTy) override {
2635 return emitError(S, Loc, T);
2636 }
2637
2639 QualType ConvTy) override {
2640 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2641 }
2642
2644 QualType T) override {
2645 return emitError(S, Loc, T);
2646 }
2647
2649 QualType ConvTy) override {
2650 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2651 }
2652
2654 QualType T,
2655 QualType ConvTy) override {
2656 llvm_unreachable("conversion functions are permitted");
2657 }
2658};
2659
2660/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2661/// arguments, that the first argument is an unsigned integer type, and that
2662/// the second argument is an integer type.
2663static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2664 if (S.checkArgCount(TheCall, 2))
2665 return true;
2666
2667 // First argument (value to rotate) must be unsigned integer type.
2668 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2670 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2671 if (Arg0Res.isInvalid())
2672 return true;
2673
2674 Expr *Arg0 = Arg0Res.get();
2675 TheCall->setArg(0, Arg0);
2676
2677 QualType Arg0Ty = Arg0->getType();
2678 if (!Arg0Ty->isUnsignedIntegerType())
2679 return true;
2680
2681 // Second argument (rotation count) must be integer type.
2682 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2684 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2685 if (Arg1Res.isInvalid())
2686 return true;
2687
2688 Expr *Arg1 = Arg1Res.get();
2689 TheCall->setArg(1, Arg1);
2690
2691 QualType Arg1Ty = Arg1->getType();
2692 if (!Arg1Ty->isIntegerType())
2693 return true;
2694
2695 TheCall->setType(Arg0Ty);
2696 return false;
2697}
2698
2699static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2700 unsigned Pos, bool AllowConst,
2701 bool AllowAS) {
2702 QualType MaskTy = MaskArg->getType();
2703 if (!MaskTy->isExtVectorBoolType())
2704 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2705 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2706 << MaskTy;
2707
2708 QualType PtrTy = PtrArg->getType();
2709 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2710 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2711 << Pos << "scalar pointer";
2712
2713 QualType PointeeTy = PtrTy->getPointeeType();
2714 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2715 (!AllowConst && PointeeTy.isConstQualified()) ||
2716 (!AllowAS && PointeeTy.hasAddressSpace())) {
2719 return S.Diag(PtrArg->getExprLoc(),
2720 diag::err_typecheck_convert_incompatible)
2721 << PtrTy << Target << /*different qualifiers=*/5
2722 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2723 << PtrTy << Target;
2724 }
2725 return false;
2726}
2727
2728static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2729 bool TypeDependent = false;
2730 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2731 ExprResult Converted =
2733 if (Converted.isInvalid())
2734 return true;
2735 TheCall->setArg(Arg, Converted.get());
2736 TypeDependent |= Converted.get()->isTypeDependent();
2737 }
2738
2739 if (TypeDependent)
2740 TheCall->setType(S.Context.DependentTy);
2741 return false;
2742}
2743
2745 if (S.checkArgCountRange(TheCall, 2, 3))
2746 return ExprError();
2747
2748 if (ConvertMaskedBuiltinArgs(S, TheCall))
2749 return ExprError();
2750
2751 Expr *MaskArg = TheCall->getArg(0);
2752 Expr *PtrArg = TheCall->getArg(1);
2753 if (TheCall->isTypeDependent())
2754 return TheCall;
2755
2756 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2757 TheCall->getBuiltinCallee() ==
2758 Builtin::BI__builtin_masked_load))
2759 return ExprError();
2760
2761 QualType MaskTy = MaskArg->getType();
2762 QualType PtrTy = PtrArg->getType();
2763 QualType PointeeTy = PtrTy->getPointeeType();
2764 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2765
2767 MaskVecTy->getNumElements());
2768 if (TheCall->getNumArgs() == 3) {
2769 Expr *PassThruArg = TheCall->getArg(2);
2770 QualType PassThruTy = PassThruArg->getType();
2771 if (!S.Context.hasSameType(PassThruTy, RetTy))
2772 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2773 << /* third argument */ 3 << RetTy;
2774 }
2775
2776 TheCall->setType(RetTy);
2777 return TheCall;
2778}
2779
2781 if (S.checkArgCount(TheCall, 3))
2782 return ExprError();
2783
2784 if (ConvertMaskedBuiltinArgs(S, TheCall))
2785 return ExprError();
2786
2787 Expr *MaskArg = TheCall->getArg(0);
2788 Expr *ValArg = TheCall->getArg(1);
2789 Expr *PtrArg = TheCall->getArg(2);
2790 if (TheCall->isTypeDependent())
2791 return TheCall;
2792
2793 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2794 TheCall->getBuiltinCallee() ==
2795 Builtin::BI__builtin_masked_store))
2796 return ExprError();
2797
2798 QualType MaskTy = MaskArg->getType();
2799 QualType PtrTy = PtrArg->getType();
2800 QualType ValTy = ValArg->getType();
2801 if (!ValTy->isVectorType())
2802 return ExprError(
2803 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2804 << 2 << "vector");
2805
2806 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2807 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2808
2809 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2810 return ExprError(
2811 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2813 TheCall->getBuiltinCallee())
2814 << MaskTy << ValTy);
2815 }
2816
2817 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2818 PtrTy->getPointeeType().getUnqualifiedType()))
2819 return ExprError(S.Diag(TheCall->getBeginLoc(),
2820 diag::err_vec_builtin_incompatible_vector)
2821 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2822 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2823 TheCall->getArg(1)->getEndLoc()));
2824
2825 TheCall->setType(S.Context.VoidTy);
2826 return TheCall;
2827}
2828
2830 if (S.checkArgCountRange(TheCall, 3, 4))
2831 return ExprError();
2832
2833 if (ConvertMaskedBuiltinArgs(S, TheCall))
2834 return ExprError();
2835
2836 Expr *MaskArg = TheCall->getArg(0);
2837 Expr *IdxArg = TheCall->getArg(1);
2838 Expr *PtrArg = TheCall->getArg(2);
2839 if (TheCall->isTypeDependent())
2840 return TheCall;
2841
2842 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2843 /*AllowAS=*/true))
2844 return ExprError();
2845
2846 QualType IdxTy = IdxArg->getType();
2847 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2848 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2849 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2850 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2851 << IdxTy;
2852
2853 QualType MaskTy = MaskArg->getType();
2854 QualType PtrTy = PtrArg->getType();
2855 QualType PointeeTy = PtrTy->getPointeeType();
2856 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2857 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2858 return ExprError(
2859 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2861 TheCall->getBuiltinCallee())
2862 << MaskTy << IdxTy);
2863
2865 MaskVecTy->getNumElements());
2866 if (TheCall->getNumArgs() == 4) {
2867 Expr *PassThruArg = TheCall->getArg(3);
2868 QualType PassThruTy = PassThruArg->getType();
2869 if (!S.Context.hasSameType(PassThruTy, RetTy))
2870 return S.Diag(PassThruArg->getExprLoc(),
2871 diag::err_vec_masked_load_store_ptr)
2872 << /* fourth argument */ 4 << RetTy;
2873 }
2874
2875 TheCall->setType(RetTy);
2876 return TheCall;
2877}
2878
2880 if (S.checkArgCount(TheCall, 4))
2881 return ExprError();
2882
2883 if (ConvertMaskedBuiltinArgs(S, TheCall))
2884 return ExprError();
2885
2886 Expr *MaskArg = TheCall->getArg(0);
2887 Expr *IdxArg = TheCall->getArg(1);
2888 Expr *ValArg = TheCall->getArg(2);
2889 Expr *PtrArg = TheCall->getArg(3);
2890 if (TheCall->isTypeDependent())
2891 return TheCall;
2892
2893 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2894 /*AllowAS=*/true))
2895 return ExprError();
2896
2897 QualType IdxTy = IdxArg->getType();
2898 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2899 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2900 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2901 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2902 << IdxTy;
2903
2904 QualType ValTy = ValArg->getType();
2905 QualType MaskTy = MaskArg->getType();
2906 QualType PtrTy = PtrArg->getType();
2907
2908 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2909 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2910 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2911 return ExprError(
2912 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2914 TheCall->getBuiltinCallee())
2915 << MaskTy << IdxTy);
2916 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2917 return ExprError(
2918 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2920 TheCall->getBuiltinCallee())
2921 << MaskTy << ValTy);
2922
2923 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2924 PtrTy->getPointeeType().getUnqualifiedType()))
2925 return ExprError(S.Diag(TheCall->getBeginLoc(),
2926 diag::err_vec_builtin_incompatible_vector)
2927 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2928 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2929 TheCall->getArg(1)->getEndLoc()));
2930
2931 TheCall->setType(S.Context.VoidTy);
2932 return TheCall;
2933}
2934
2936 SourceLocation Loc = TheCall->getBeginLoc();
2937 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2938 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2939
2940 if (Args.size() == 0) {
2941 S.Diag(TheCall->getBeginLoc(),
2942 diag::err_typecheck_call_too_few_args_at_least)
2943 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2944 << /*is_non_object=*/0 << TheCall->getSourceRange();
2945 return ExprError();
2946 }
2947
2948 QualType FuncT = Args[0]->getType();
2949
2950 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2951 if (Args.size() < 2) {
2952 S.Diag(TheCall->getBeginLoc(),
2953 diag::err_typecheck_call_too_few_args_at_least)
2954 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2955 << /*is_non_object=*/0 << TheCall->getSourceRange();
2956 return ExprError();
2957 }
2958
2959 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2960 QualType ObjectT = Args[1]->getType();
2961
2962 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2963 return ExprError();
2964
2965 ExprResult ObjectArg = [&]() -> ExprResult {
2966 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2967 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2968 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2969 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2970 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2971 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2972 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2973 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2974 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2975 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2976 return Args[1];
2977 }
2978
2979 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2980 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2981 // reference_wrapper;
2982 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2983 if (RD->isInStdNamespace() &&
2984 RD->getDeclName().getAsString() == "reference_wrapper") {
2985 CXXScopeSpec SS;
2986 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2987 UnqualifiedId GetID;
2988 GetID.setIdentifier(GetName, Loc);
2989
2991 S.getCurScope(), Args[1], Loc, tok::period, SS,
2992 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2993
2994 if (MemExpr.isInvalid())
2995 return ExprError();
2996
2997 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2998 }
2999 }
3000
3001 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3002 // class T and t1 does not satisfy the previous two items;
3003
3004 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
3005 }();
3006
3007 if (ObjectArg.isInvalid())
3008 return ExprError();
3009
3010 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
3011 tok::periodstar, ObjectArg.get(), Args[0]);
3012 if (BinOp.isInvalid())
3013 return ExprError();
3014
3015 if (MPT->isMemberDataPointer())
3016 return BinOp;
3017
3018 auto *MemCall = new (S.Context)
3020
3021 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
3022 Args.drop_front(2), TheCall->getRParenLoc());
3023 }
3024 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
3025 Args.drop_front(), TheCall->getRParenLoc());
3026}
3027
3028// Performs a similar job to Sema::UsualUnaryConversions, but without any
3029// implicit promotion of integral/enumeration types.
3031 // First, convert to an r-value.
3033 if (Res.isInvalid())
3034 return ExprError();
3035
3036 // Promote floating-point types.
3037 return S.UsualUnaryFPConversions(Res.get());
3038}
3039
3041 if (const auto *TyA = VecTy->getAs<VectorType>())
3042 return TyA->getElementType();
3043 if (VecTy->isSizelessVectorType())
3044 return VecTy->getSizelessVectorEltType(Context);
3045 return QualType();
3046}
3047
3049Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3050 CallExpr *TheCall) {
3051 ExprResult TheCallResult(TheCall);
3052
3053 // Find out if any arguments are required to be integer constant expressions.
3054 unsigned ICEArguments = 0;
3056 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
3058 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3059
3060 // If any arguments are required to be ICE's, check and diagnose.
3061 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3062 // Skip arguments not required to be ICE's.
3063 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3064
3065 llvm::APSInt Result;
3066 // If we don't have enough arguments, continue so we can issue better
3067 // diagnostic in checkArgCount(...)
3068 if (ArgNo < TheCall->getNumArgs() &&
3069 BuiltinConstantArg(TheCall, ArgNo, Result))
3070 return true;
3071 ICEArguments &= ~(1 << ArgNo);
3072 }
3073
3074 FPOptions FPO;
3075 switch (BuiltinID) {
3076 case Builtin::BI__builtin___get_unsafe_stack_start:
3077 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3078 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3079 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3080 << "__safestack_get_unsafe_stack_bottom";
3081 break;
3082 case Builtin::BI__builtin___get_unsafe_stack_top:
3083 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3084 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3085 << "__safestack_get_unsafe_stack_top";
3086 break;
3087 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3088 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3089 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3090 << "__safestack_get_unsafe_stack_ptr";
3091 break;
3092 case Builtin::BI__builtin_cpu_supports:
3093 case Builtin::BI__builtin_cpu_is:
3094 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
3095 Context.getAuxTargetInfo(), BuiltinID))
3096 return ExprError();
3097 break;
3098 case Builtin::BI__builtin_cpu_init:
3099 if (!Context.getTargetInfo().supportsCpuInit()) {
3100 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3101 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3102 return ExprError();
3103 }
3104 break;
3105 case Builtin::BI__builtin___CFStringMakeConstantString:
3106 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3107 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3109 *this, BuiltinID, TheCall,
3110 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3111 return ExprError();
3112 assert(TheCall->getNumArgs() == 1 &&
3113 "Wrong # arguments to builtin CFStringMakeConstantString");
3114 if (ObjC().CheckObjCString(TheCall->getArg(0)))
3115 return ExprError();
3116 break;
3117 case Builtin::BI__builtin_ms_va_start:
3118 case Builtin::BI__builtin_zos_va_start:
3119 case Builtin::BI__builtin_stdarg_start:
3120 case Builtin::BI__builtin_va_start:
3121 case Builtin::BI__builtin_c23_va_start:
3122 if (BuiltinVAStart(BuiltinID, TheCall))
3123 return ExprError();
3124 break;
3125 case Builtin::BI__va_start: {
3126 switch (Context.getTargetInfo().getTriple().getArch()) {
3127 case llvm::Triple::aarch64:
3128 case llvm::Triple::arm:
3129 case llvm::Triple::thumb:
3130 if (BuiltinVAStartARMMicrosoft(TheCall))
3131 return ExprError();
3132 break;
3133 default:
3134 if (BuiltinVAStart(BuiltinID, TheCall))
3135 return ExprError();
3136 break;
3137 }
3138 break;
3139 }
3140
3141 // The acquire, release, and no fence variants are ARM and AArch64 only.
3142 case Builtin::BI_interlockedbittestandset_acq:
3143 case Builtin::BI_interlockedbittestandset_rel:
3144 case Builtin::BI_interlockedbittestandset_nf:
3145 case Builtin::BI_interlockedbittestandreset_acq:
3146 case Builtin::BI_interlockedbittestandreset_rel:
3147 case Builtin::BI_interlockedbittestandreset_nf:
3149 *this, TheCall,
3150 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3151 return ExprError();
3152 break;
3153
3154 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3155 case Builtin::BI_bittest64:
3156 case Builtin::BI_bittestandcomplement64:
3157 case Builtin::BI_bittestandreset64:
3158 case Builtin::BI_bittestandset64:
3159 case Builtin::BI_interlockedbittestandreset64:
3160 case Builtin::BI_interlockedbittestandset64:
3162 *this, TheCall,
3163 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3164 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3165 return ExprError();
3166 break;
3167
3168 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3169 case Builtin::BI_interlockedbittestandreset64_acq:
3170 case Builtin::BI_interlockedbittestandreset64_rel:
3171 case Builtin::BI_interlockedbittestandreset64_nf:
3172 case Builtin::BI_interlockedbittestandset64_acq:
3173 case Builtin::BI_interlockedbittestandset64_rel:
3174 case Builtin::BI_interlockedbittestandset64_nf:
3175 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3176 return ExprError();
3177 break;
3178
3179 case Builtin::BI__builtin_set_flt_rounds:
3181 *this, TheCall,
3182 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3183 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3184 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3185 llvm::Triple::ppc64le}))
3186 return ExprError();
3187 break;
3188
3189 case Builtin::BI__builtin_isgreater:
3190 case Builtin::BI__builtin_isgreaterequal:
3191 case Builtin::BI__builtin_isless:
3192 case Builtin::BI__builtin_islessequal:
3193 case Builtin::BI__builtin_islessgreater:
3194 case Builtin::BI__builtin_isunordered:
3195 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3196 return ExprError();
3197 break;
3198 case Builtin::BI__builtin_fpclassify:
3199 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3200 return ExprError();
3201 break;
3202 case Builtin::BI__builtin_isfpclass:
3203 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3204 return ExprError();
3205 break;
3206 case Builtin::BI__builtin_isfinite:
3207 case Builtin::BI__builtin_isinf:
3208 case Builtin::BI__builtin_isinf_sign:
3209 case Builtin::BI__builtin_isnan:
3210 case Builtin::BI__builtin_issignaling:
3211 case Builtin::BI__builtin_isnormal:
3212 case Builtin::BI__builtin_issubnormal:
3213 case Builtin::BI__builtin_iszero:
3214 case Builtin::BI__builtin_signbit:
3215 case Builtin::BI__builtin_signbitf:
3216 case Builtin::BI__builtin_signbitl:
3217 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3218 return ExprError();
3219 break;
3220 case Builtin::BI__builtin_shufflevector:
3221 return BuiltinShuffleVector(TheCall);
3222 // TheCall will be freed by the smart pointer here, but that's fine, since
3223 // BuiltinShuffleVector guts it, but then doesn't release it.
3224 case Builtin::BI__builtin_masked_load:
3225 case Builtin::BI__builtin_masked_expand_load:
3226 return BuiltinMaskedLoad(*this, TheCall);
3227 case Builtin::BI__builtin_masked_store:
3228 case Builtin::BI__builtin_masked_compress_store:
3229 return BuiltinMaskedStore(*this, TheCall);
3230 case Builtin::BI__builtin_masked_gather:
3231 return BuiltinMaskedGather(*this, TheCall);
3232 case Builtin::BI__builtin_masked_scatter:
3233 return BuiltinMaskedScatter(*this, TheCall);
3234 case Builtin::BI__builtin_invoke:
3235 return BuiltinInvoke(*this, TheCall);
3236 case Builtin::BI__builtin_prefetch:
3237 if (BuiltinPrefetch(TheCall))
3238 return ExprError();
3239 break;
3240 case Builtin::BI__builtin_alloca_with_align:
3241 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3242 if (BuiltinAllocaWithAlign(TheCall))
3243 return ExprError();
3244 [[fallthrough]];
3245 case Builtin::BI__builtin_alloca:
3246 case Builtin::BI__builtin_alloca_uninitialized:
3247 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3248 << TheCall->getDirectCallee();
3249 if (getLangOpts().OpenCL) {
3250 builtinAllocaAddrSpace(*this, TheCall);
3251 }
3252 break;
3253 case Builtin::BI__builtin_infer_alloc_token:
3254 if (checkBuiltinInferAllocToken(*this, TheCall))
3255 return ExprError();
3256 break;
3257 case Builtin::BI__arithmetic_fence:
3258 if (BuiltinArithmeticFence(TheCall))
3259 return ExprError();
3260 break;
3261 case Builtin::BI__assume:
3262 case Builtin::BI__builtin_assume:
3263 if (BuiltinAssume(TheCall))
3264 return ExprError();
3265 break;
3266 case Builtin::BI__builtin_assume_aligned:
3267 if (BuiltinAssumeAligned(TheCall))
3268 return ExprError();
3269 break;
3270 case Builtin::BI__builtin_dynamic_object_size:
3271 case Builtin::BI__builtin_object_size:
3272 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3273 return ExprError();
3274 break;
3275 case Builtin::BI__builtin_longjmp:
3276 if (BuiltinLongjmp(TheCall))
3277 return ExprError();
3278 break;
3279 case Builtin::BI__builtin_setjmp:
3280 if (BuiltinSetjmp(TheCall))
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_complex:
3284 if (BuiltinComplex(TheCall))
3285 return ExprError();
3286 break;
3287 case Builtin::BI__builtin_classify_type:
3288 case Builtin::BI__builtin_constant_p: {
3289 if (checkArgCount(TheCall, 1))
3290 return true;
3292 if (Arg.isInvalid()) return true;
3293 TheCall->setArg(0, Arg.get());
3294 TheCall->setType(Context.IntTy);
3295 break;
3296 }
3297 case Builtin::BI__builtin_launder:
3298 return BuiltinLaunder(*this, TheCall);
3299 case Builtin::BI__builtin_is_within_lifetime:
3300 return BuiltinIsWithinLifetime(*this, TheCall);
3301 case Builtin::BI__builtin_trivially_relocate:
3302 return BuiltinTriviallyRelocate(*this, TheCall);
3303 case Builtin::BI__builtin_clear_padding: {
3304 if (checkArgCount(TheCall, 1))
3305 return ExprError();
3306
3307 const Expr *PtrArg = TheCall->getArg(0);
3308 const QualType PtrArgType = PtrArg->getType();
3309 if (!PtrArgType->isPointerType()) {
3310 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3311 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3312 << "pointer";
3313 return ExprError();
3314 }
3315 QualType PointeeType = PtrArgType->getPointeeType();
3316 if (PointeeType.isConstQualified()) {
3317 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3318 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3319 return ExprError();
3320 }
3321 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3322 diag::err_typecheck_decl_incomplete_type))
3323 return ExprError();
3324
3325 // For non trivially copyable types, we try to match gcc's behaviour.
3326 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3327 // object, either a local variable or a function parameter passed by value
3328 auto IsAddrOfDeclExpr = [&]() {
3329 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3330 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3331 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3332 return false;
3333
3334 const Expr *Operand =
3335 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3336 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3337 if (!DeclRef)
3338 return false;
3339
3340 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3341 if (!VarDecl || VarDecl->getType()->isReferenceType())
3342 return false;
3343
3344 // matching GCC behaviour
3345 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3346 QualType VarQType = VarDecl->getType();
3347 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3348 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3349 };
3350
3351 if (!PointeeType.isTriviallyCopyableType(Context) &&
3352 !PointeeType->isAtomicType() // _Atomic is not copyable
3353 && !IsAddrOfDeclExpr()) {
3354 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3355 << PtrArg->getType() << PtrArg->getSourceRange();
3356 return ExprError();
3357 }
3358
3359 if (auto *Record = PointeeType->getAsRecordDecl();
3361 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3362 << PointeeType << PtrArg->getSourceRange();
3363 return ExprError();
3364 }
3365
3366 break;
3367 }
3368 case Builtin::BI__sync_fetch_and_add:
3369 case Builtin::BI__sync_fetch_and_add_1:
3370 case Builtin::BI__sync_fetch_and_add_2:
3371 case Builtin::BI__sync_fetch_and_add_4:
3372 case Builtin::BI__sync_fetch_and_add_8:
3373 case Builtin::BI__sync_fetch_and_add_16:
3374 case Builtin::BI__sync_fetch_and_sub:
3375 case Builtin::BI__sync_fetch_and_sub_1:
3376 case Builtin::BI__sync_fetch_and_sub_2:
3377 case Builtin::BI__sync_fetch_and_sub_4:
3378 case Builtin::BI__sync_fetch_and_sub_8:
3379 case Builtin::BI__sync_fetch_and_sub_16:
3380 case Builtin::BI__sync_fetch_and_or:
3381 case Builtin::BI__sync_fetch_and_or_1:
3382 case Builtin::BI__sync_fetch_and_or_2:
3383 case Builtin::BI__sync_fetch_and_or_4:
3384 case Builtin::BI__sync_fetch_and_or_8:
3385 case Builtin::BI__sync_fetch_and_or_16:
3386 case Builtin::BI__sync_fetch_and_and:
3387 case Builtin::BI__sync_fetch_and_and_1:
3388 case Builtin::BI__sync_fetch_and_and_2:
3389 case Builtin::BI__sync_fetch_and_and_4:
3390 case Builtin::BI__sync_fetch_and_and_8:
3391 case Builtin::BI__sync_fetch_and_and_16:
3392 case Builtin::BI__sync_fetch_and_xor:
3393 case Builtin::BI__sync_fetch_and_xor_1:
3394 case Builtin::BI__sync_fetch_and_xor_2:
3395 case Builtin::BI__sync_fetch_and_xor_4:
3396 case Builtin::BI__sync_fetch_and_xor_8:
3397 case Builtin::BI__sync_fetch_and_xor_16:
3398 case Builtin::BI__sync_fetch_and_nand:
3399 case Builtin::BI__sync_fetch_and_nand_1:
3400 case Builtin::BI__sync_fetch_and_nand_2:
3401 case Builtin::BI__sync_fetch_and_nand_4:
3402 case Builtin::BI__sync_fetch_and_nand_8:
3403 case Builtin::BI__sync_fetch_and_nand_16:
3404 case Builtin::BI__sync_add_and_fetch:
3405 case Builtin::BI__sync_add_and_fetch_1:
3406 case Builtin::BI__sync_add_and_fetch_2:
3407 case Builtin::BI__sync_add_and_fetch_4:
3408 case Builtin::BI__sync_add_and_fetch_8:
3409 case Builtin::BI__sync_add_and_fetch_16:
3410 case Builtin::BI__sync_sub_and_fetch:
3411 case Builtin::BI__sync_sub_and_fetch_1:
3412 case Builtin::BI__sync_sub_and_fetch_2:
3413 case Builtin::BI__sync_sub_and_fetch_4:
3414 case Builtin::BI__sync_sub_and_fetch_8:
3415 case Builtin::BI__sync_sub_and_fetch_16:
3416 case Builtin::BI__sync_and_and_fetch:
3417 case Builtin::BI__sync_and_and_fetch_1:
3418 case Builtin::BI__sync_and_and_fetch_2:
3419 case Builtin::BI__sync_and_and_fetch_4:
3420 case Builtin::BI__sync_and_and_fetch_8:
3421 case Builtin::BI__sync_and_and_fetch_16:
3422 case Builtin::BI__sync_or_and_fetch:
3423 case Builtin::BI__sync_or_and_fetch_1:
3424 case Builtin::BI__sync_or_and_fetch_2:
3425 case Builtin::BI__sync_or_and_fetch_4:
3426 case Builtin::BI__sync_or_and_fetch_8:
3427 case Builtin::BI__sync_or_and_fetch_16:
3428 case Builtin::BI__sync_xor_and_fetch:
3429 case Builtin::BI__sync_xor_and_fetch_1:
3430 case Builtin::BI__sync_xor_and_fetch_2:
3431 case Builtin::BI__sync_xor_and_fetch_4:
3432 case Builtin::BI__sync_xor_and_fetch_8:
3433 case Builtin::BI__sync_xor_and_fetch_16:
3434 case Builtin::BI__sync_nand_and_fetch:
3435 case Builtin::BI__sync_nand_and_fetch_1:
3436 case Builtin::BI__sync_nand_and_fetch_2:
3437 case Builtin::BI__sync_nand_and_fetch_4:
3438 case Builtin::BI__sync_nand_and_fetch_8:
3439 case Builtin::BI__sync_nand_and_fetch_16:
3440 case Builtin::BI__sync_val_compare_and_swap:
3441 case Builtin::BI__sync_val_compare_and_swap_1:
3442 case Builtin::BI__sync_val_compare_and_swap_2:
3443 case Builtin::BI__sync_val_compare_and_swap_4:
3444 case Builtin::BI__sync_val_compare_and_swap_8:
3445 case Builtin::BI__sync_val_compare_and_swap_16:
3446 case Builtin::BI__sync_bool_compare_and_swap:
3447 case Builtin::BI__sync_bool_compare_and_swap_1:
3448 case Builtin::BI__sync_bool_compare_and_swap_2:
3449 case Builtin::BI__sync_bool_compare_and_swap_4:
3450 case Builtin::BI__sync_bool_compare_and_swap_8:
3451 case Builtin::BI__sync_bool_compare_and_swap_16:
3452 case Builtin::BI__sync_lock_test_and_set:
3453 case Builtin::BI__sync_lock_test_and_set_1:
3454 case Builtin::BI__sync_lock_test_and_set_2:
3455 case Builtin::BI__sync_lock_test_and_set_4:
3456 case Builtin::BI__sync_lock_test_and_set_8:
3457 case Builtin::BI__sync_lock_test_and_set_16:
3458 case Builtin::BI__sync_lock_release:
3459 case Builtin::BI__sync_lock_release_1:
3460 case Builtin::BI__sync_lock_release_2:
3461 case Builtin::BI__sync_lock_release_4:
3462 case Builtin::BI__sync_lock_release_8:
3463 case Builtin::BI__sync_lock_release_16:
3464 case Builtin::BI__sync_swap:
3465 case Builtin::BI__sync_swap_1:
3466 case Builtin::BI__sync_swap_2:
3467 case Builtin::BI__sync_swap_4:
3468 case Builtin::BI__sync_swap_8:
3469 case Builtin::BI__sync_swap_16:
3470 return BuiltinAtomicOverloaded(TheCallResult);
3471 case Builtin::BI__sync_synchronize:
3472 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3473 << TheCall->getCallee()->getSourceRange();
3474 break;
3475 case Builtin::BI__builtin_nontemporal_load:
3476 case Builtin::BI__builtin_nontemporal_store:
3477 return BuiltinNontemporalOverloaded(TheCallResult);
3478 case Builtin::BI__builtin_memcpy_inline: {
3479 clang::Expr *SizeOp = TheCall->getArg(2);
3480 // We warn about copying to or from `nullptr` pointers when `size` is
3481 // greater than 0. When `size` is value dependent we cannot evaluate its
3482 // value so we bail out.
3483 if (SizeOp->isValueDependent())
3484 break;
3485 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3486 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3487 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3488 }
3489 break;
3490 }
3491 case Builtin::BI__builtin_memset_inline: {
3492 clang::Expr *SizeOp = TheCall->getArg(2);
3493 // We warn about filling to `nullptr` pointers when `size` is greater than
3494 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3495 // out.
3496 if (SizeOp->isValueDependent())
3497 break;
3498 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3499 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3500 break;
3501 }
3502#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3503 case Builtin::BI##ID: \
3504 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3505#include "clang/Basic/Builtins.inc"
3506 case Builtin::BI__annotation: {
3507 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3508 if (!TT.isOSWindows() && !TT.isUEFI()) {
3509 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3510 << TheCall->getSourceRange();
3511 return ExprError();
3512 }
3513 if (BuiltinMSVCAnnotation(*this, TheCall))
3514 return ExprError();
3515 break;
3516 }
3517 case Builtin::BI__builtin_annotation:
3518 if (BuiltinAnnotation(*this, TheCall))
3519 return ExprError();
3520 break;
3521 case Builtin::BI__builtin_addressof:
3522 if (BuiltinAddressof(*this, TheCall))
3523 return ExprError();
3524 break;
3525 case Builtin::BI__builtin_function_start:
3526 if (BuiltinFunctionStart(*this, TheCall))
3527 return ExprError();
3528 break;
3529 case Builtin::BI__builtin_is_aligned:
3530 case Builtin::BI__builtin_align_up:
3531 case Builtin::BI__builtin_align_down:
3532 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3533 return ExprError();
3534 break;
3535 case Builtin::BI__builtin_add_overflow:
3536 case Builtin::BI__builtin_sub_overflow:
3537 case Builtin::BI__builtin_mul_overflow:
3538 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3539 return ExprError();
3540 break;
3541 case Builtin::BI__builtin_operator_new:
3542 case Builtin::BI__builtin_operator_delete: {
3543 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3544 ExprResult Res =
3545 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3546 return Res;
3547 }
3548 case Builtin::BI__builtin_dump_struct:
3549 return BuiltinDumpStruct(*this, TheCall);
3550 case Builtin::BI__builtin_expect_with_probability: {
3551 // We first want to ensure we are called with 3 arguments
3552 if (checkArgCount(TheCall, 3))
3553 return ExprError();
3554 // then check probability is constant float in range [0.0, 1.0]
3555 const Expr *ProbArg = TheCall->getArg(2);
3556 SmallVector<PartialDiagnosticAt, 8> Notes;
3557 Expr::EvalResult Eval;
3558 Eval.Diag = &Notes;
3559 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3560 !Eval.Val.isFloat()) {
3561 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3562 << ProbArg->getSourceRange();
3563 for (const PartialDiagnosticAt &PDiag : Notes)
3564 Diag(PDiag.first, PDiag.second);
3565 return ExprError();
3566 }
3567 llvm::APFloat Probability = Eval.Val.getFloat();
3568 bool LoseInfo = false;
3569 Probability.convert(llvm::APFloat::IEEEdouble(),
3570 llvm::RoundingMode::Dynamic, &LoseInfo);
3571 if (!(Probability >= llvm::APFloat(0.0) &&
3572 Probability <= llvm::APFloat(1.0))) {
3573 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3574 << ProbArg->getSourceRange();
3575 return ExprError();
3576 }
3577 break;
3578 }
3579 case Builtin::BI__builtin_preserve_access_index:
3580 if (BuiltinPreserveAI(*this, TheCall))
3581 return ExprError();
3582 break;
3583 case Builtin::BI__builtin_call_with_static_chain:
3584 if (BuiltinCallWithStaticChain(*this, TheCall))
3585 return ExprError();
3586 break;
3587 case Builtin::BI__exception_code:
3588 case Builtin::BI_exception_code:
3589 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3590 diag::err_seh___except_block))
3591 return ExprError();
3592 break;
3593 case Builtin::BI__exception_info:
3594 case Builtin::BI_exception_info:
3595 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3596 diag::err_seh___except_filter))
3597 return ExprError();
3598 break;
3599 case Builtin::BI__GetExceptionInfo:
3600 if (checkArgCount(TheCall, 1))
3601 return ExprError();
3602
3604 TheCall->getBeginLoc(),
3605 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3606 TheCall))
3607 return ExprError();
3608
3609 TheCall->setType(Context.VoidPtrTy);
3610 break;
3611 case Builtin::BIaddressof:
3612 case Builtin::BI__addressof:
3613 case Builtin::BIforward:
3614 case Builtin::BIforward_like:
3615 case Builtin::BImove:
3616 case Builtin::BImove_if_noexcept:
3617 case Builtin::BIas_const: {
3618 // These are all expected to be of the form
3619 // T &/&&/* f(U &/&&)
3620 // where T and U only differ in qualification.
3621 if (checkArgCount(TheCall, 1))
3622 return ExprError();
3623 QualType Param = FDecl->getParamDecl(0)->getType();
3624 QualType Result = FDecl->getReturnType();
3625 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3626 BuiltinID == Builtin::BI__addressof;
3627 if (!(Param->isReferenceType() &&
3628 (ReturnsPointer ? Result->isAnyPointerType()
3629 : Result->isReferenceType()) &&
3630 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3631 Result->getPointeeType()))) {
3632 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3633 << FDecl;
3634 return ExprError();
3635 }
3636 break;
3637 }
3638 case Builtin::BI__builtin_ptrauth_strip:
3639 return PointerAuthStrip(*this, TheCall);
3640 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3641 return PointerAuthBlendDiscriminator(*this, TheCall);
3642 case Builtin::BI__builtin_ptrauth_sign_constant:
3643 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3644 /*RequireConstant=*/true);
3645 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3646 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3647 /*RequireConstant=*/false);
3648 case Builtin::BI__builtin_ptrauth_auth:
3649 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3650 /*RequireConstant=*/false);
3651 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3652 return PointerAuthSignGenericData(*this, TheCall);
3653 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3654 return PointerAuthAuthAndResign(*this, TheCall);
3655 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3656 return PointerAuthAuthWithPCAndResign(*this, TheCall);
3657 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3658 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3659 case Builtin::BI__builtin_ptrauth_string_discriminator:
3660 return PointerAuthStringDiscriminator(*this, TheCall);
3661
3662 case Builtin::BI__builtin_get_vtable_pointer:
3663 return GetVTablePointer(*this, TheCall);
3664
3665 // OpenCL v2.0, s6.13.16 - Pipe functions
3666 case Builtin::BIread_pipe:
3667 case Builtin::BIwrite_pipe:
3668 // Since those two functions are declared with var args, we need a semantic
3669 // check for the argument.
3670 if (OpenCL().checkBuiltinRWPipe(TheCall))
3671 return ExprError();
3672 break;
3673 case Builtin::BIreserve_read_pipe:
3674 case Builtin::BIreserve_write_pipe:
3675 case Builtin::BIwork_group_reserve_read_pipe:
3676 case Builtin::BIwork_group_reserve_write_pipe:
3677 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3678 return ExprError();
3679 break;
3680 case Builtin::BIsub_group_reserve_read_pipe:
3681 case Builtin::BIsub_group_reserve_write_pipe:
3682 if (OpenCL().checkSubgroupExt(TheCall) ||
3683 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3684 return ExprError();
3685 break;
3686 case Builtin::BIcommit_read_pipe:
3687 case Builtin::BIcommit_write_pipe:
3688 case Builtin::BIwork_group_commit_read_pipe:
3689 case Builtin::BIwork_group_commit_write_pipe:
3690 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3691 return ExprError();
3692 break;
3693 case Builtin::BIsub_group_commit_read_pipe:
3694 case Builtin::BIsub_group_commit_write_pipe:
3695 if (OpenCL().checkSubgroupExt(TheCall) ||
3696 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3697 return ExprError();
3698 break;
3699 case Builtin::BIget_pipe_num_packets:
3700 case Builtin::BIget_pipe_max_packets:
3701 if (OpenCL().checkBuiltinPipePackets(TheCall))
3702 return ExprError();
3703 break;
3704 case Builtin::BIto_global:
3705 case Builtin::BIto_local:
3706 case Builtin::BIto_private:
3707 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3708 return ExprError();
3709 break;
3710 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3711 case Builtin::BIenqueue_kernel:
3712 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3713 return ExprError();
3714 break;
3715 case Builtin::BIget_kernel_work_group_size:
3716 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3717 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3718 return ExprError();
3719 break;
3720 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3721 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3722 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3723 return ExprError();
3724 break;
3725 case Builtin::BI__builtin_os_log_format:
3726 Cleanup.setExprNeedsCleanups(true);
3727 [[fallthrough]];
3728 case Builtin::BI__builtin_os_log_format_buffer_size:
3729 if (BuiltinOSLogFormat(TheCall))
3730 return ExprError();
3731 break;
3732 case Builtin::BI__builtin_frame_address:
3733 case Builtin::BI__builtin_return_address: {
3734 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3735 return ExprError();
3736
3737 // -Wframe-address warning if non-zero passed to builtin
3738 // return/frame address.
3739 Expr::EvalResult Result;
3740 if (!TheCall->getArg(0)->isValueDependent() &&
3741 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3742 Result.Val.getInt() != 0)
3743 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3744 << ((BuiltinID == Builtin::BI__builtin_return_address)
3745 ? "__builtin_return_address"
3746 : "__builtin_frame_address")
3747 << TheCall->getSourceRange();
3748 break;
3749 }
3750
3751 case Builtin::BI__builtin_nondeterministic_value: {
3752 if (BuiltinNonDeterministicValue(TheCall))
3753 return ExprError();
3754 break;
3755 }
3756
3757 // __builtin_elementwise_abs restricts the element type to signed integers or
3758 // floating point types only.
3759 case Builtin::BI__builtin_elementwise_abs:
3762 return ExprError();
3763 break;
3764
3765 // These builtins restrict the element type to floating point
3766 // types only.
3767 case Builtin::BI__builtin_elementwise_acos:
3768 case Builtin::BI__builtin_elementwise_asin:
3769 case Builtin::BI__builtin_elementwise_atan:
3770 case Builtin::BI__builtin_elementwise_ceil:
3771 case Builtin::BI__builtin_elementwise_cos:
3772 case Builtin::BI__builtin_elementwise_cosh:
3773 case Builtin::BI__builtin_elementwise_exp:
3774 case Builtin::BI__builtin_elementwise_exp2:
3775 case Builtin::BI__builtin_elementwise_exp10:
3776 case Builtin::BI__builtin_elementwise_floor:
3777 case Builtin::BI__builtin_elementwise_log:
3778 case Builtin::BI__builtin_elementwise_log2:
3779 case Builtin::BI__builtin_elementwise_log10:
3780 case Builtin::BI__builtin_elementwise_roundeven:
3781 case Builtin::BI__builtin_elementwise_round:
3782 case Builtin::BI__builtin_elementwise_rint:
3783 case Builtin::BI__builtin_elementwise_nearbyint:
3784 case Builtin::BI__builtin_elementwise_sin:
3785 case Builtin::BI__builtin_elementwise_sinh:
3786 case Builtin::BI__builtin_elementwise_sqrt:
3787 case Builtin::BI__builtin_elementwise_tan:
3788 case Builtin::BI__builtin_elementwise_tanh:
3789 case Builtin::BI__builtin_elementwise_trunc:
3790 case Builtin::BI__builtin_elementwise_canonicalize:
3793 return ExprError();
3794 break;
3795 case Builtin::BI__builtin_elementwise_fma:
3796 if (BuiltinElementwiseTernaryMath(TheCall))
3797 return ExprError();
3798 break;
3799
3800 case Builtin::BI__builtin_elementwise_ldexp: {
3801 if (checkArgCount(TheCall, 2))
3802 return ExprError();
3803
3804 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3805 if (A.isInvalid())
3806 return ExprError();
3807 QualType TyA = A.get()->getType();
3808 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3810 return ExprError();
3811
3812 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3813 if (Exp.isInvalid())
3814 return ExprError();
3815 QualType TyExp = Exp.get()->getType();
3816 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3818 2))
3819 return ExprError();
3820
3821 // Check the two arguments are either scalars or vectors of equal length.
3822 const auto *Vec0 = TyA->getAs<VectorType>();
3823 const auto *Vec1 = TyExp->getAs<VectorType>();
3824 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3825 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3826 if (Arg0Length != Arg1Length) {
3827 Diag(Exp.get()->getBeginLoc(),
3828 diag::err_typecheck_vector_lengths_not_equal)
3829 << TyA << TyExp << A.get()->getSourceRange()
3830 << Exp.get()->getSourceRange();
3831 return ExprError();
3832 }
3833
3834 TheCall->setArg(0, A.get());
3835 TheCall->setArg(1, Exp.get());
3836 TheCall->setType(TyA);
3837 break;
3838 }
3839
3840 // These builtins restrict the element type to floating point
3841 // types only, and take in two arguments.
3842 case Builtin::BI__builtin_elementwise_minnum:
3843 case Builtin::BI__builtin_elementwise_maxnum:
3844 case Builtin::BI__builtin_elementwise_minimum:
3845 case Builtin::BI__builtin_elementwise_maximum:
3846 case Builtin::BI__builtin_elementwise_minimumnum:
3847 case Builtin::BI__builtin_elementwise_maximumnum:
3848 case Builtin::BI__builtin_elementwise_atan2:
3849 case Builtin::BI__builtin_elementwise_fmod:
3850 case Builtin::BI__builtin_elementwise_pow:
3851 if (BuiltinElementwiseMath(TheCall,
3853 return ExprError();
3854 break;
3855 // These builtins restrict the element type to integer
3856 // types only.
3857 case Builtin::BI__builtin_elementwise_add_sat:
3858 case Builtin::BI__builtin_elementwise_sub_sat:
3859 case Builtin::BI__builtin_elementwise_clmul:
3860 case Builtin::BI__builtin_elementwise_pext:
3861 case Builtin::BI__builtin_elementwise_pdep:
3862 if (BuiltinElementwiseMath(TheCall,
3864 return ExprError();
3865 break;
3866 case Builtin::BI__builtin_elementwise_fshl:
3867 case Builtin::BI__builtin_elementwise_fshr:
3870 return ExprError();
3871 break;
3872 case Builtin::BI__builtin_elementwise_min:
3873 case Builtin::BI__builtin_elementwise_max: {
3874 if (BuiltinElementwiseMath(TheCall))
3875 return ExprError();
3876 Expr *Arg0 = TheCall->getArg(0);
3877 Expr *Arg1 = TheCall->getArg(1);
3878 QualType Ty0 = Arg0->getType();
3879 QualType Ty1 = Arg1->getType();
3880 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3881 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3882 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3883 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3884 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3885 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3886 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3887 break;
3888 }
3889 case Builtin::BI__builtin_elementwise_popcount:
3890 case Builtin::BI__builtin_elementwise_bitreverse:
3893 return ExprError();
3894 break;
3895 case Builtin::BI__builtin_elementwise_copysign: {
3896 if (checkArgCount(TheCall, 2))
3897 return ExprError();
3898
3899 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3900 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3901 if (Magnitude.isInvalid() || Sign.isInvalid())
3902 return ExprError();
3903
3904 QualType MagnitudeTy = Magnitude.get()->getType();
3905 QualType SignTy = Sign.get()->getType();
3907 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3910 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3912 return ExprError();
3913 }
3914
3915 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3916 return Diag(Sign.get()->getBeginLoc(),
3917 diag::err_typecheck_call_different_arg_types)
3918 << MagnitudeTy << SignTy;
3919 }
3920
3921 TheCall->setArg(0, Magnitude.get());
3922 TheCall->setArg(1, Sign.get());
3923 TheCall->setType(Magnitude.get()->getType());
3924 break;
3925 }
3926 case Builtin::BI__builtin_elementwise_clzg:
3927 case Builtin::BI__builtin_elementwise_ctzg:
3928 // These builtins can be unary or binary. Note for empty calls we call the
3929 // unary checker in order to not emit an error that says the function
3930 // expects 2 arguments, which would be misleading.
3931 if (TheCall->getNumArgs() <= 1) {
3934 return ExprError();
3935 } else if (BuiltinElementwiseMath(
3937 return ExprError();
3938 break;
3939 case Builtin::BI__builtin_reduce_max:
3940 case Builtin::BI__builtin_reduce_min: {
3941 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3942 return ExprError();
3943
3944 const Expr *Arg = TheCall->getArg(0);
3945 const auto *TyA = Arg->getType()->getAs<VectorType>();
3946
3947 QualType ElTy;
3948 if (TyA)
3949 ElTy = TyA->getElementType();
3950 else if (Arg->getType()->isSizelessVectorType())
3952
3953 if (ElTy.isNull()) {
3954 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3955 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3956 << Arg->getType();
3957 return ExprError();
3958 }
3959
3960 TheCall->setType(ElTy);
3961 break;
3962 }
3963 case Builtin::BI__builtin_reduce_maximum:
3964 case Builtin::BI__builtin_reduce_minimum: {
3965 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3966 return ExprError();
3967
3968 const Expr *Arg = TheCall->getArg(0);
3969 const auto *TyA = Arg->getType()->getAs<VectorType>();
3970
3971 QualType ElTy;
3972 if (TyA)
3973 ElTy = TyA->getElementType();
3974 else if (Arg->getType()->isSizelessVectorType())
3976
3977 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3978 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3979 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3980 << Arg->getType();
3981 return ExprError();
3982 }
3983
3984 TheCall->setType(ElTy);
3985 break;
3986 }
3987
3988 // These builtins support vectors of integers only.
3989 // TODO: ADD/MUL should support floating-point types.
3990 case Builtin::BI__builtin_reduce_add:
3991 case Builtin::BI__builtin_reduce_mul:
3992 case Builtin::BI__builtin_reduce_xor:
3993 case Builtin::BI__builtin_reduce_or:
3994 case Builtin::BI__builtin_reduce_and: {
3995 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3996 return ExprError();
3997
3998 const Expr *Arg = TheCall->getArg(0);
3999
4000 QualType ElTy = getVectorElementType(Context, Arg->getType());
4001 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4002 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4003 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4004 << Arg->getType();
4005 return ExprError();
4006 }
4007
4008 TheCall->setType(ElTy);
4009 break;
4010 }
4011
4012 case Builtin::BI__builtin_reduce_assoc_fadd:
4013 case Builtin::BI__builtin_reduce_in_order_fadd: {
4014 // For in-order reductions require the user to specify the start value.
4015 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4016 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
4017 return ExprError();
4018
4019 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
4020 if (Vec.isInvalid())
4021 return ExprError();
4022
4023 TheCall->setArg(0, Vec.get());
4024
4025 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
4026 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4027 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4028 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4029 << Vec.get()->getType();
4030 return ExprError();
4031 }
4032
4033 if (TheCall->getNumArgs() == 2) {
4034 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
4035 if (StartValue.isInvalid())
4036 return ExprError();
4037
4038 if (!StartValue.get()->getType()->isRealFloatingType()) {
4039 Diag(StartValue.get()->getBeginLoc(),
4040 diag::err_builtin_invalid_arg_type)
4041 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4042 << StartValue.get()->getType();
4043 return ExprError();
4044 }
4045 TheCall->setArg(1, StartValue.get());
4046 }
4047
4048 TheCall->setType(ElTy);
4049 break;
4050 }
4051
4052 case Builtin::BI__builtin_matrix_transpose:
4053 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4054
4055 case Builtin::BI__builtin_matrix_column_major_load:
4056 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4057
4058 case Builtin::BI__builtin_matrix_column_major_store:
4059 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4060
4061 case Builtin::BI__builtin_verbose_trap:
4062 if (!checkBuiltinVerboseTrap(TheCall, *this))
4063 return ExprError();
4064 break;
4065
4066 case Builtin::BI__builtin_get_device_side_mangled_name: {
4067 auto Check = [](CallExpr *TheCall) {
4068 if (TheCall->getNumArgs() != 1)
4069 return false;
4070 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
4071 if (!DRE)
4072 return false;
4073 auto *D = DRE->getDecl();
4074 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
4075 return false;
4076 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4077 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4078 };
4079 if (!Check(TheCall)) {
4080 Diag(TheCall->getBeginLoc(),
4081 diag::err_hip_invalid_args_builtin_mangled_name);
4082 return ExprError();
4083 }
4084 break;
4085 }
4086 case Builtin::BI__builtin_bswapg:
4087 if (BuiltinBswapg(*this, TheCall))
4088 return ExprError();
4089 break;
4090 case Builtin::BI__builtin_bitreverseg:
4091 if (BuiltinBitreverseg(*this, TheCall))
4092 return ExprError();
4093 break;
4094 case Builtin::BI__builtin_popcountg:
4095 if (BuiltinPopcountg(*this, TheCall))
4096 return ExprError();
4097 break;
4098 case Builtin::BI__builtin_clzg:
4099 case Builtin::BI__builtin_ctzg:
4100 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
4101 return ExprError();
4102 break;
4103
4104 case Builtin::BI__builtin_stdc_rotate_left:
4105 case Builtin::BI__builtin_stdc_rotate_right:
4106 if (BuiltinRotateGeneric(*this, TheCall))
4107 return ExprError();
4108 break;
4109
4110 case Builtin::BI__builtin_stdc_memreverse8:
4111 case Builtin::BIstdc_memreverse8:
4112 case Builtin::BIstdc_memreverse8u8:
4113 case Builtin::BIstdc_memreverse8u16:
4114 case Builtin::BIstdc_memreverse8u32:
4115 case Builtin::BIstdc_memreverse8u64:
4116 if (Context.getTargetInfo().getCharWidth() != 8) {
4117 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
4118 << TheCall->getDirectCallee()->getName();
4119 return ExprError();
4120 }
4121 break;
4122
4123 case Builtin::BI__builtin_stdc_bit_floor:
4124 case Builtin::BI__builtin_stdc_bit_ceil:
4125 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4126 return ExprError();
4127 break;
4128 case Builtin::BI__builtin_stdc_has_single_bit:
4129 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4130 return ExprError();
4131 break;
4132 case Builtin::BI__builtin_stdc_leading_zeros:
4133 case Builtin::BI__builtin_stdc_leading_ones:
4134 case Builtin::BI__builtin_stdc_trailing_zeros:
4135 case Builtin::BI__builtin_stdc_trailing_ones:
4136 case Builtin::BI__builtin_stdc_first_leading_zero:
4137 case Builtin::BI__builtin_stdc_first_leading_one:
4138 case Builtin::BI__builtin_stdc_first_trailing_zero:
4139 case Builtin::BI__builtin_stdc_first_trailing_one:
4140 case Builtin::BI__builtin_stdc_count_zeros:
4141 case Builtin::BI__builtin_stdc_count_ones:
4142 case Builtin::BI__builtin_stdc_bit_width:
4143 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4144 return ExprError();
4145 break;
4146
4147 case Builtin::BI__builtin_allow_runtime_check: {
4148 Expr *Arg = TheCall->getArg(0);
4149 // Check if the argument is a string literal.
4151 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4152 << Arg->getSourceRange();
4153 return ExprError();
4154 }
4155 break;
4156 }
4157
4158 case Builtin::BI__builtin_allow_sanitize_check: {
4159 if (checkArgCount(TheCall, 1))
4160 return ExprError();
4161
4162 Expr *Arg = TheCall->getArg(0);
4163 // Check if the argument is a string literal.
4164 const StringLiteral *SanitizerName =
4165 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4166 if (!SanitizerName) {
4167 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4168 << Arg->getSourceRange();
4169 return ExprError();
4170 }
4171 // Validate the sanitizer name.
4172 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4173 .Cases({"address", "thread", "memory", "hwaddress",
4174 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4175 true)
4176 .Default(false)) {
4177 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4178 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4179 << Arg->getSourceRange();
4180 return ExprError();
4181 }
4182 break;
4183 }
4184 case Builtin::BI__builtin_counted_by_ref:
4185 if (BuiltinCountedByRef(TheCall))
4186 return ExprError();
4187 break;
4188 }
4189
4190 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4191 return ExprError();
4192
4193 // Since the target specific builtins for each arch overlap, only check those
4194 // of the arch we are compiling for.
4195 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4196 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4197 assert(Context.getAuxTargetInfo() &&
4198 "Aux Target Builtin, but not an aux target?");
4199
4200 if (CheckTSBuiltinFunctionCall(
4201 *Context.getAuxTargetInfo(),
4202 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4203 return ExprError();
4204 } else {
4205 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4206 TheCall))
4207 return ExprError();
4208 }
4209 }
4210
4211 return TheCallResult;
4212}
4213
4214bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4215 llvm::APSInt Result;
4216 // We can't check the value of a dependent argument.
4217 Expr *Arg = TheCall->getArg(ArgNum);
4218 if (Arg->isTypeDependent() || Arg->isValueDependent())
4219 return false;
4220
4221 // Check constant-ness first.
4222 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4223 return true;
4224
4225 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4226 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4227 return false;
4228
4229 return Diag(TheCall->getBeginLoc(),
4230 diag::err_argument_not_contiguous_bit_field)
4231 << ArgNum << Arg->getSourceRange();
4232}
4233
4234bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4235 unsigned FirstArg, FormatStringInfo *FSI) {
4236 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4237 bool IsVariadic = false;
4238 if (const FunctionType *FnTy = D->getFunctionType())
4239 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4240 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4241 IsVariadic = BD->isVariadic();
4242 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4243 IsVariadic = OMD->isVariadic();
4244
4245 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4246 IsVariadic, FSI);
4247}
4248
4249bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4250 bool HasImplicitThisParam, bool IsVariadic,
4251 FormatStringInfo *FSI) {
4252 if (FirstArg == 0)
4254 else if (IsVariadic)
4256 else
4258 FSI->FormatIdx = FormatIdx - 1;
4259 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4260
4261 // The way the format attribute works in GCC, the implicit this argument
4262 // of member functions is counted. However, it doesn't appear in our own
4263 // lists, so decrement format_idx in that case.
4264 if (HasImplicitThisParam) {
4265 if(FSI->FormatIdx == 0)
4266 return false;
4267 --FSI->FormatIdx;
4268 if (FSI->FirstDataArg != 0)
4269 --FSI->FirstDataArg;
4270 }
4271 return true;
4272}
4273
4274/// Checks if a the given expression evaluates to null.
4275///
4276/// Returns true if the value evaluates to null.
4277static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4278 // Treat (smart) pointers constructed from nullptr as null, whether we can
4279 // const-evaluate them or not.
4280 // This must happen first: the smart pointer expr might have _Nonnull type!
4284 return true;
4285
4286 // If the expression has non-null type, it doesn't evaluate to null.
4287 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4288 if (*nullability == NullabilityKind::NonNull)
4289 return false;
4290 }
4291
4292 // As a special case, transparent unions initialized with zero are
4293 // considered null for the purposes of the nonnull attribute.
4294 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4295 UT &&
4296 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4297 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4298 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4299 Expr = ILE->getInit(0);
4300 }
4301
4302 bool Result;
4303 return (!Expr->isValueDependent() &&
4305 !Result);
4306}
4307
4309 const Expr *ArgExpr,
4310 SourceLocation CallSiteLoc) {
4311 if (CheckNonNullExpr(S, ArgExpr))
4312 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4313 S.PDiag(diag::warn_null_arg)
4314 << ArgExpr->getSourceRange());
4315}
4316
4317/// Determine whether the given type has a non-null nullability annotation.
4319 if (auto nullability = type->getNullability())
4320 return *nullability == NullabilityKind::NonNull;
4321
4322 return false;
4323}
4324
4326 const NamedDecl *FDecl,
4327 const FunctionProtoType *Proto,
4329 SourceLocation CallSiteLoc) {
4330 assert((FDecl || Proto) && "Need a function declaration or prototype");
4331
4332 // Already checked by constant evaluator.
4334 return;
4335 // Check the attributes attached to the method/function itself.
4336 llvm::SmallBitVector NonNullArgs;
4337 if (FDecl) {
4338 // Handle the nonnull attribute on the function/method declaration itself.
4339 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4340 if (!NonNull->args_size()) {
4341 // Easy case: all pointer arguments are nonnull.
4342 for (const auto *Arg : Args)
4343 if (S.isValidPointerAttrType(Arg->getType()))
4344 CheckNonNullArgument(S, Arg, CallSiteLoc);
4345 return;
4346 }
4347
4348 for (const ParamIdx &Idx : NonNull->args()) {
4349 unsigned IdxAST = Idx.getASTIndex();
4350 if (IdxAST >= Args.size())
4351 continue;
4352 if (NonNullArgs.empty())
4353 NonNullArgs.resize(Args.size());
4354 NonNullArgs.set(IdxAST);
4355 }
4356 }
4357 }
4358
4359 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4360 // Handle the nonnull attribute on the parameters of the
4361 // function/method.
4363 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4364 parms = FD->parameters();
4365 else
4366 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4367
4368 unsigned ParamIndex = 0;
4369 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4370 I != E; ++I, ++ParamIndex) {
4371 const ParmVarDecl *PVD = *I;
4372 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4373 if (NonNullArgs.empty())
4374 NonNullArgs.resize(Args.size());
4375
4376 NonNullArgs.set(ParamIndex);
4377 }
4378 }
4379 } else {
4380 // If we have a non-function, non-method declaration but no
4381 // function prototype, try to dig out the function prototype.
4382 if (!Proto) {
4383 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4384 QualType type = VD->getType().getNonReferenceType();
4385 if (auto pointerType = type->getAs<PointerType>())
4386 type = pointerType->getPointeeType();
4387 else if (auto blockType = type->getAs<BlockPointerType>())
4388 type = blockType->getPointeeType();
4389 // FIXME: data member pointers?
4390
4391 // Dig out the function prototype, if there is one.
4392 Proto = type->getAs<FunctionProtoType>();
4393 }
4394 }
4395
4396 // Fill in non-null argument information from the nullability
4397 // information on the parameter types (if we have them).
4398 if (Proto) {
4399 unsigned Index = 0;
4400 for (auto paramType : Proto->getParamTypes()) {
4401 if (isNonNullType(paramType)) {
4402 if (NonNullArgs.empty())
4403 NonNullArgs.resize(Args.size());
4404
4405 NonNullArgs.set(Index);
4406 }
4407
4408 ++Index;
4409 }
4410 }
4411 }
4412
4413 // Check for non-null arguments.
4414 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4415 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4416 if (NonNullArgs[ArgIndex])
4417 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4418 }
4419}
4420
4421void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4422 StringRef ParamName, QualType ArgTy,
4423 QualType ParamTy) {
4424
4425 // If a function accepts a pointer or reference type
4426 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4427 return;
4428
4429 // If the parameter is a pointer type, get the pointee type for the
4430 // argument too. If the parameter is a reference type, don't try to get
4431 // the pointee type for the argument.
4432 if (ParamTy->isPointerType())
4433 ArgTy = ArgTy->getPointeeType();
4434
4435 // Remove reference or pointer
4436 ParamTy = ParamTy->getPointeeType();
4437
4438 // Find expected alignment, and the actual alignment of the passed object.
4439 // getTypeAlignInChars requires complete types
4440 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4441 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4442 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4443 return;
4444
4445 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4446 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4447
4448 // If the argument is less aligned than the parameter, there is a
4449 // potential alignment issue.
4450 if (ArgAlign < ParamAlign)
4451 Diag(Loc, diag::warn_param_mismatched_alignment)
4452 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4453 << ParamName << (FDecl != nullptr) << FDecl;
4454}
4455
4456void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4457 const Expr *ThisArg,
4459 if (!FD || Args.empty())
4460 return;
4461 auto GetArgAt = [&](int Idx) -> const Expr * {
4462 if (Idx == LifetimeCaptureByAttr::Global ||
4463 Idx == LifetimeCaptureByAttr::Unknown)
4464 return nullptr;
4465 if (IsMemberFunction && Idx == 0)
4466 return ThisArg;
4467 return Args[Idx - IsMemberFunction];
4468 };
4469 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4470 unsigned ArgIdx) {
4471 if (!Attr)
4472 return;
4473
4474 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4475 for (int CapturingParamIdx : Attr->params()) {
4476 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4477 continue;
4478 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4479 // initialization codepath.
4480 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4482 continue;
4483 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4484 CapturingEntity CE{Capturing};
4485 // Ensure that 'Captured' outlives the 'Capturing' entity.
4486 checkCaptureByLifetime(*this, CE, Captured);
4487 }
4488 };
4489 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4490 for (const auto *A :
4491 FD->getParamDecl(I)->specific_attrs<LifetimeCaptureByAttr>())
4492 HandleCaptureByAttr(A, I + IsMemberFunction);
4493 // Check when the implicit object param is captured.
4494 if (IsMemberFunction) {
4495 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4496 if (!TSI)
4497 return;
4499 for (TypeLoc TL = TSI->getTypeLoc();
4500 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4501 TL = ATL.getModifiedLoc())
4502 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4503 }
4504}
4505
4507 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4508 bool IsMemberFunction, SourceLocation Loc,
4509 SourceRange Range, VariadicCallType CallType) {
4510
4511 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4512 llvm::any_of(Args, [](const Expr *E) {
4513 return E && E->isInstantiationDependent();
4514 }))
4515 return;
4516
4517 // Printf and scanf checking.
4518 llvm::SmallBitVector CheckedVarArgs;
4519 if (FDecl) {
4520 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4521 // Only create vector if there are format attributes.
4522 CheckedVarArgs.resize(Args.size());
4523 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4524 CheckedVarArgs);
4525 }
4526
4527 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4528 CheckedVarArgs.resize(Args.size());
4529 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4530 CheckedVarArgs);
4531 }
4532 }
4533
4534 // Refuse POD arguments that weren't caught by the format string
4535 // checks above.
4536 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4537 if (CallType != VariadicCallType::DoesNotApply &&
4538 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4539 unsigned NumParams = Proto ? Proto->getNumParams()
4540 : isa_and_nonnull<FunctionDecl>(FDecl)
4541 ? cast<FunctionDecl>(FDecl)->getNumParams()
4542 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4543 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4544 : 0;
4545
4546 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4547 // Args[ArgIdx] can be null in malformed code.
4548 if (const Expr *Arg = Args[ArgIdx]) {
4549 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4550 checkVariadicArgument(Arg, CallType);
4551 }
4552 }
4553 }
4554 if (FD)
4555 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4556 if (FDecl || Proto) {
4557 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4558
4559 // Type safety checking.
4560 if (FDecl) {
4561 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4562 CheckArgumentWithTypeTag(I, Args, Loc);
4563 }
4564 }
4565
4566 // Check that passed arguments match the alignment of original arguments.
4567 // Try to get the missing prototype from the declaration.
4568 if (!Proto && FDecl) {
4569 const auto *FT = FDecl->getFunctionType();
4570 if (isa_and_nonnull<FunctionProtoType>(FT))
4571 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4572 }
4573 if (Proto) {
4574 // For variadic functions, we may have more args than parameters.
4575 // For some K&R functions, we may have less args than parameters.
4576 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4577 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4578 bool IsScalableArg = false;
4579 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4580 // Args[ArgIdx] can be null in malformed code.
4581 if (const Expr *Arg = Args[ArgIdx]) {
4582 if (Arg->containsErrors())
4583 continue;
4584
4585 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4586 FDecl->hasLinkage() &&
4587 FDecl->getFormalLinkage() != Linkage::Internal &&
4589 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4590
4591 QualType ParamTy = Proto->getParamType(ArgIdx);
4592 if (ParamTy->isSizelessVectorType())
4593 IsScalableArg = true;
4594 QualType ArgTy = Arg->getType();
4595 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4596 ArgTy, ParamTy);
4597 }
4598 }
4599
4600 // If the callee has an AArch64 SME attribute to indicate that it is an
4601 // __arm_streaming function, then the caller requires SME to be available.
4604 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4605 llvm::StringMap<bool> CallerFeatureMap;
4606 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4607 if (!CallerFeatureMap.contains("sme"))
4608 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4609 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4610 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4611 }
4612 }
4613
4614 // If the call requires a streaming-mode change and has scalable vector
4615 // arguments or return values, then warn the user that the streaming and
4616 // non-streaming vector lengths may be different.
4617 // When both streaming and non-streaming vector lengths are defined and
4618 // mismatched, produce an error.
4619 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4620 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4621 (IsScalableArg || IsScalableRet)) {
4622 bool IsCalleeStreaming =
4624 bool IsCalleeStreamingCompatible =
4625 ExtInfo.AArch64SMEAttributes &
4627 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4628 if (!IsCalleeStreamingCompatible &&
4629 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4630 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4631 const LangOptions &LO = getLangOpts();
4632 unsigned VL = LO.VScaleMin * 128;
4633 unsigned SVL = LO.VScaleStreamingMin * 128;
4634 bool IsVLMismatch = VL && SVL && VL != SVL;
4635
4636 auto EmitDiag = [&](bool IsArg) {
4637 if (IsVLMismatch) {
4638 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4639 // Emit warning for streaming-compatible callers
4640 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4641 << IsArg << IsCalleeStreaming << SVL << VL;
4642 else
4643 // Emit error otherwise
4644 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4645 << IsArg << SVL << VL;
4646 } else
4647 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4648 << IsArg;
4649 };
4650
4651 if (IsScalableArg)
4652 EmitDiag(true);
4653 if (IsScalableRet)
4654 EmitDiag(false);
4655 }
4656 }
4657
4658 FunctionType::ArmStateValue CalleeArmZAState =
4660 FunctionType::ArmStateValue CalleeArmZT0State =
4662 if (CalleeArmZAState != FunctionType::ARM_None ||
4663 CalleeArmZT0State != FunctionType::ARM_None) {
4664 bool CallerHasZAState = false;
4665 bool CallerHasZT0State = false;
4666 if (CallerFD) {
4667 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4668 if (Attr && Attr->isNewZA())
4669 CallerHasZAState = true;
4670 if (Attr && Attr->isNewZT0())
4671 CallerHasZT0State = true;
4672 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4673 CallerHasZAState |=
4675 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4677 CallerHasZT0State |=
4679 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4681 }
4682 }
4683
4684 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4685 Diag(Loc, diag::err_sme_za_call_no_za_state);
4686
4687 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4688 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4689
4690 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4691 CalleeArmZT0State != FunctionType::ARM_None) {
4692 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4693 Diag(Loc, diag::note_sme_use_preserves_za);
4694 }
4695 }
4696 }
4697
4698 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4699 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4700 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4701 if (!Arg->isValueDependent()) {
4702 Expr::EvalResult Align;
4703 if (Arg->EvaluateAsInt(Align, Context)) {
4704 const llvm::APSInt &I = Align.Val.getInt();
4705 if (!I.isPowerOf2())
4706 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4707 << Arg->getSourceRange();
4708
4709 if (I > Sema::MaximumAlignment)
4710 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4711 << Arg->getSourceRange() << Sema::MaximumAlignment;
4712 }
4713 }
4714 }
4715
4716 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4718 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4719 << diag::OffloadLang::SYCL;
4720
4721 if (FD)
4722 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4723}
4724
4725void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4726 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4727 DiagnoseUseOfDecl(Decl, Loc);
4728 }
4729}
4730
4731void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4733 const FunctionProtoType *Proto,
4734 SourceLocation Loc) {
4735 VariadicCallType CallType = Proto->isVariadic()
4738
4739 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4740 CheckArgAlignment(
4741 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4742 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4743
4744 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4745 Loc, SourceRange(), CallType);
4746}
4747
4749 const FunctionProtoType *Proto) {
4750 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4751 isa<CXXMethodDecl>(FDecl);
4752 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4753 IsMemberOperatorCall;
4754 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4755 TheCall->getCallee());
4756 Expr** Args = TheCall->getArgs();
4757 unsigned NumArgs = TheCall->getNumArgs();
4758
4759 Expr *ImplicitThis = nullptr;
4760 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4761 // If this is a call to a member operator, hide the first
4762 // argument from checkCall.
4763 // FIXME: Our choice of AST representation here is less than ideal.
4764 ImplicitThis = Args[0];
4765 ++Args;
4766 --NumArgs;
4767 } else if (IsMemberFunction && !FDecl->isStatic() &&
4769 ImplicitThis =
4770 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4771
4772 if (ImplicitThis) {
4773 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4774 // used.
4775 QualType ThisType = ImplicitThis->getType();
4776 if (!ThisType->isPointerType()) {
4777 assert(!ThisType->isReferenceType());
4778 ThisType = Context.getPointerType(ThisType);
4779 }
4780
4781 QualType ThisTypeFromDecl = Context.getPointerType(
4782 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4783
4784 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4785 ThisTypeFromDecl);
4786 }
4787
4788 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4789 IsMemberFunction, TheCall->getRParenLoc(),
4790 TheCall->getCallee()->getSourceRange(), CallType);
4791
4792 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4793 // None of the checks below are needed for functions that don't have
4794 // simple names (e.g., C++ conversion functions).
4795 if (!FnInfo)
4796 return false;
4797
4798 // Enforce TCB except for builtin calls, which are always allowed.
4799 if (FDecl->getBuiltinID() == 0)
4800 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4801
4802 CheckAbsoluteValueFunction(TheCall, FDecl);
4803 CheckMaxUnsignedZero(TheCall, FDecl);
4804 CheckInfNaNFunction(TheCall, FDecl);
4805
4806 if (getLangOpts().ObjC)
4807 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4808
4809 unsigned CMId = FDecl->getMemoryFunctionKind();
4810
4811 // Handle memory setting and copying functions.
4812 switch (CMId) {
4813 case 0:
4814 return false;
4815 case Builtin::BIstrlcpy: // fallthrough
4816 case Builtin::BIstrlcat:
4817 CheckStrlcpycatArguments(TheCall, FnInfo);
4818 break;
4819 case Builtin::BIstrncat:
4820 CheckStrncatArguments(TheCall, FnInfo);
4821 break;
4822 case Builtin::BIfree:
4823 CheckFreeArguments(TheCall);
4824 break;
4825 default:
4826 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4827 }
4828
4829 return false;
4830}
4831
4832bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4833 const FunctionProtoType *Proto) {
4834 QualType Ty;
4835 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4836 Ty = V->getType().getNonReferenceType();
4837 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4838 Ty = F->getType().getNonReferenceType();
4839 else
4840 return false;
4841
4842 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4843 !Ty->isFunctionProtoType())
4844 return false;
4845
4846 VariadicCallType CallType;
4847 if (!Proto || !Proto->isVariadic()) {
4849 } else if (Ty->isBlockPointerType()) {
4850 CallType = VariadicCallType::Block;
4851 } else { // Ty->isFunctionPointerType()
4852 CallType = VariadicCallType::Function;
4853 }
4854
4855 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4856 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4857 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4858 TheCall->getCallee()->getSourceRange(), CallType);
4859
4860 return false;
4861}
4862
4863bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4864 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4865 TheCall->getCallee());
4866 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4867 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4868 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4869 TheCall->getCallee()->getSourceRange(), CallType);
4870
4871 return false;
4872}
4873
4874static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4875 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4876 return false;
4877
4878 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4879 switch (Op) {
4880 case AtomicExpr::AO__c11_atomic_init:
4881 case AtomicExpr::AO__opencl_atomic_init:
4882 llvm_unreachable("There is no ordering argument for an init");
4883
4884 case AtomicExpr::AO__c11_atomic_load:
4885 case AtomicExpr::AO__opencl_atomic_load:
4886 case AtomicExpr::AO__hip_atomic_load:
4887 case AtomicExpr::AO__atomic_load_n:
4888 case AtomicExpr::AO__atomic_load:
4889 case AtomicExpr::AO__scoped_atomic_load_n:
4890 case AtomicExpr::AO__scoped_atomic_load:
4891 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4892 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4893
4894 case AtomicExpr::AO__c11_atomic_store:
4895 case AtomicExpr::AO__opencl_atomic_store:
4896 case AtomicExpr::AO__hip_atomic_store:
4897 case AtomicExpr::AO__atomic_store:
4898 case AtomicExpr::AO__atomic_store_n:
4899 case AtomicExpr::AO__scoped_atomic_store:
4900 case AtomicExpr::AO__scoped_atomic_store_n:
4901 case AtomicExpr::AO__atomic_clear:
4902 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4903 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4904 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4905
4906 default:
4907 return true;
4908 }
4909}
4910
4911ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4913 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4914 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4915 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4916 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4917 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4918 Op);
4919}
4920
4921/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4922/// equivalents. Provide a fixit when the scope is a compile-time constant and
4923/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4924/// compare_exchange builtins differ in how they accept the desired value, so
4925/// only a warning (without a fixit) is emitted for those.
4927 MultiExprArg Args,
4929 StringRef OldName;
4930 StringRef NewName;
4931 bool CanFixIt;
4932
4933 switch (Op) {
4934#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4935 case AtomicExpr::AO__hip_atomic_##hip: \
4936 OldName = "__hip_atomic_" #hip; \
4937 NewName = "__scoped_atomic_" #scoped; \
4938 CanFixIt = true; \
4939 break;
4940 HIP_ATOMIC_FIXABLE(load, load_n)
4941 HIP_ATOMIC_FIXABLE(store, store_n)
4942 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4943 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4944 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4945 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4946 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4947 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4948 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4949 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4950#undef HIP_ATOMIC_FIXABLE
4951 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4952 OldName = "__hip_atomic_compare_exchange_weak";
4953 NewName = "__scoped_atomic_compare_exchange";
4954 CanFixIt = false;
4955 break;
4956 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4957 OldName = "__hip_atomic_compare_exchange_strong";
4958 NewName = "__scoped_atomic_compare_exchange";
4959 CanFixIt = false;
4960 break;
4961 default:
4962 llvm_unreachable("unhandled HIP atomic op");
4963 }
4964
4965 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4966 << OldName << NewName;
4967 if (!CanFixIt)
4968 return;
4969
4970 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4971
4972 Expr *Scope = Args[Args.size() - 1];
4973 std::optional<llvm::APSInt> ScopeVal =
4974 Scope->getIntegerConstantExpr(S.Context);
4975 if (!ScopeVal)
4976 return;
4977
4978 StringRef ScopeName;
4979 switch (ScopeVal->getZExtValue()) {
4981 ScopeName = "__MEMORY_SCOPE_SINGLE";
4982 break;
4984 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4985 break;
4987 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4988 break;
4990 ScopeName = "__MEMORY_SCOPE_DEVICE";
4991 break;
4993 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4994 break;
4996 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4997 break;
4998 default:
4999 return;
5000 }
5001
5003 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
5004}
5005
5007 SourceLocation RParenLoc, MultiExprArg Args,
5009 AtomicArgumentOrder ArgOrder) {
5010 // All the non-OpenCL operations take one of the following forms.
5011 // The OpenCL operations take the __c11 forms with one extra argument for
5012 // synchronization scope.
5013 enum {
5014 // C __c11_atomic_init(A *, C)
5015 Init,
5016
5017 // C __c11_atomic_load(A *, int)
5018 Load,
5019
5020 // void __atomic_load(A *, CP, int)
5021 LoadCopy,
5022
5023 // void __atomic_store(A *, CP, int)
5024 Copy,
5025
5026 // C __c11_atomic_add(A *, M, int)
5027 Arithmetic,
5028
5029 // C __atomic_exchange_n(A *, CP, int)
5030 Xchg,
5031
5032 // void __atomic_exchange(A *, C *, CP, int)
5033 GNUXchg,
5034
5035 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5036 C11CmpXchg,
5037
5038 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5039 GNUCmpXchg,
5040
5041 // bool __atomic_test_and_set(A *, int)
5042 TestAndSetByte,
5043
5044 // void __atomic_clear(A *, int)
5045 ClearByte,
5046 } Form = Init;
5047
5048 const unsigned NumForm = ClearByte + 1;
5049 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5050 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5051 // where:
5052 // C is an appropriate type,
5053 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5054 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5055 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5056 // the int parameters are for orderings.
5057
5058 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5059 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5060 "need to update code for modified forms");
5061 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5062 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5063 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5064 "need to update code for modified C11 atomics");
5065 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5066 Op <= AtomicExpr::AO__opencl_atomic_store;
5067 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5068 Op <= AtomicExpr::AO__hip_atomic_store;
5069 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5070 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5071 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5072 Op <= AtomicExpr::AO__c11_atomic_store) ||
5073 IsOpenCL;
5074 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5075 Op == AtomicExpr::AO__atomic_store_n ||
5076 Op == AtomicExpr::AO__atomic_exchange_n ||
5077 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5078 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5079 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5080 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5081 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5082 // Bit mask for extra allowed value types other than integers for atomic
5083 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5084 // allow floating point.
5085 enum ArithOpExtraValueType {
5086 AOEVT_None = 0,
5087 AOEVT_Pointer = 1,
5088 AOEVT_FP = 2,
5089 AOEVT_Int = 4,
5090 };
5091 unsigned ArithAllows = AOEVT_None;
5092
5093 switch (Op) {
5094 case AtomicExpr::AO__c11_atomic_init:
5095 case AtomicExpr::AO__opencl_atomic_init:
5096 Form = Init;
5097 break;
5098
5099 case AtomicExpr::AO__c11_atomic_load:
5100 case AtomicExpr::AO__opencl_atomic_load:
5101 case AtomicExpr::AO__hip_atomic_load:
5102 case AtomicExpr::AO__atomic_load_n:
5103 case AtomicExpr::AO__scoped_atomic_load_n:
5104 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5105 Form = Load;
5106 break;
5107
5108 case AtomicExpr::AO__atomic_load:
5109 case AtomicExpr::AO__scoped_atomic_load:
5110 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5111 Form = LoadCopy;
5112 break;
5113
5114 case AtomicExpr::AO__c11_atomic_store:
5115 case AtomicExpr::AO__opencl_atomic_store:
5116 case AtomicExpr::AO__hip_atomic_store:
5117 case AtomicExpr::AO__atomic_store:
5118 case AtomicExpr::AO__atomic_store_n:
5119 case AtomicExpr::AO__scoped_atomic_store:
5120 case AtomicExpr::AO__scoped_atomic_store_n:
5121 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5122 Form = Copy;
5123 break;
5124 case AtomicExpr::AO__atomic_fetch_add:
5125 case AtomicExpr::AO__atomic_fetch_sub:
5126 case AtomicExpr::AO__atomic_add_fetch:
5127 case AtomicExpr::AO__atomic_sub_fetch:
5128 case AtomicExpr::AO__scoped_atomic_fetch_add:
5129 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5130 case AtomicExpr::AO__scoped_atomic_add_fetch:
5131 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5132 case AtomicExpr::AO__c11_atomic_fetch_add:
5133 case AtomicExpr::AO__c11_atomic_fetch_sub:
5134 case AtomicExpr::AO__opencl_atomic_fetch_add:
5135 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5136 case AtomicExpr::AO__hip_atomic_fetch_add:
5137 case AtomicExpr::AO__hip_atomic_fetch_sub:
5138 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5139 Form = Arithmetic;
5140 break;
5141 case AtomicExpr::AO__atomic_fetch_fminimum:
5142 case AtomicExpr::AO__atomic_fetch_fmaximum:
5143 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5144 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5145 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5146 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5147 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5148 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5149 ArithAllows = AOEVT_FP;
5150 Form = Arithmetic;
5151 break;
5152 case AtomicExpr::AO__atomic_fetch_max:
5153 case AtomicExpr::AO__atomic_fetch_min:
5154 case AtomicExpr::AO__atomic_max_fetch:
5155 case AtomicExpr::AO__atomic_min_fetch:
5156 case AtomicExpr::AO__scoped_atomic_fetch_max:
5157 case AtomicExpr::AO__scoped_atomic_fetch_min:
5158 case AtomicExpr::AO__scoped_atomic_max_fetch:
5159 case AtomicExpr::AO__scoped_atomic_min_fetch:
5160 case AtomicExpr::AO__c11_atomic_fetch_max:
5161 case AtomicExpr::AO__c11_atomic_fetch_min:
5162 case AtomicExpr::AO__opencl_atomic_fetch_max:
5163 case AtomicExpr::AO__opencl_atomic_fetch_min:
5164 case AtomicExpr::AO__hip_atomic_fetch_max:
5165 case AtomicExpr::AO__hip_atomic_fetch_min:
5166 ArithAllows = AOEVT_Int | AOEVT_FP;
5167 Form = Arithmetic;
5168 break;
5169 case AtomicExpr::AO__c11_atomic_fetch_and:
5170 case AtomicExpr::AO__c11_atomic_fetch_or:
5171 case AtomicExpr::AO__c11_atomic_fetch_xor:
5172 case AtomicExpr::AO__hip_atomic_fetch_and:
5173 case AtomicExpr::AO__hip_atomic_fetch_or:
5174 case AtomicExpr::AO__hip_atomic_fetch_xor:
5175 case AtomicExpr::AO__c11_atomic_fetch_nand:
5176 case AtomicExpr::AO__opencl_atomic_fetch_and:
5177 case AtomicExpr::AO__opencl_atomic_fetch_or:
5178 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5179 case AtomicExpr::AO__atomic_fetch_and:
5180 case AtomicExpr::AO__atomic_fetch_or:
5181 case AtomicExpr::AO__atomic_fetch_xor:
5182 case AtomicExpr::AO__atomic_fetch_nand:
5183 case AtomicExpr::AO__atomic_and_fetch:
5184 case AtomicExpr::AO__atomic_or_fetch:
5185 case AtomicExpr::AO__atomic_xor_fetch:
5186 case AtomicExpr::AO__atomic_nand_fetch:
5187 case AtomicExpr::AO__atomic_fetch_uinc:
5188 case AtomicExpr::AO__atomic_fetch_udec:
5189 case AtomicExpr::AO__scoped_atomic_fetch_and:
5190 case AtomicExpr::AO__scoped_atomic_fetch_or:
5191 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5192 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5193 case AtomicExpr::AO__scoped_atomic_and_fetch:
5194 case AtomicExpr::AO__scoped_atomic_or_fetch:
5195 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5196 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5197 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5198 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5199 Form = Arithmetic;
5200 break;
5201
5202 case AtomicExpr::AO__c11_atomic_exchange:
5203 case AtomicExpr::AO__hip_atomic_exchange:
5204 case AtomicExpr::AO__opencl_atomic_exchange:
5205 case AtomicExpr::AO__atomic_exchange_n:
5206 case AtomicExpr::AO__scoped_atomic_exchange_n:
5207 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5208 Form = Xchg;
5209 break;
5210
5211 case AtomicExpr::AO__atomic_exchange:
5212 case AtomicExpr::AO__scoped_atomic_exchange:
5213 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5214 Form = GNUXchg;
5215 break;
5216
5217 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5218 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5219 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5220 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5221 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5222 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5223 Form = C11CmpXchg;
5224 break;
5225
5226 case AtomicExpr::AO__atomic_compare_exchange:
5227 case AtomicExpr::AO__atomic_compare_exchange_n:
5228 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5229 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5230 ArithAllows = AOEVT_Pointer;
5231 Form = GNUCmpXchg;
5232 break;
5233
5234 case AtomicExpr::AO__atomic_test_and_set:
5235 Form = TestAndSetByte;
5236 break;
5237
5238 case AtomicExpr::AO__atomic_clear:
5239 Form = ClearByte;
5240 break;
5241 }
5242
5243 unsigned AdjustedNumArgs = NumArgs[Form];
5244 if ((IsOpenCL || IsHIP || IsScoped) &&
5245 Op != AtomicExpr::AO__opencl_atomic_init)
5246 ++AdjustedNumArgs;
5247 // Check we have the right number of arguments.
5248 if (Args.size() < AdjustedNumArgs) {
5249 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5250 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5251 << /*is non object*/ 0 << ExprRange;
5252 return ExprError();
5253 } else if (Args.size() > AdjustedNumArgs) {
5254 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5255 diag::err_typecheck_call_too_many_args)
5256 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5257 << /*is non object*/ 0 << ExprRange;
5258 return ExprError();
5259 }
5260
5261 // Inspect the first argument of the atomic operation.
5262 Expr *Ptr = Args[0];
5264 if (ConvertedPtr.isInvalid())
5265 return ExprError();
5266
5267 Ptr = ConvertedPtr.get();
5268 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5269 if (!pointerType) {
5270 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5271 << Ptr->getType() << 0 << Ptr->getSourceRange();
5272 return ExprError();
5273 }
5274
5275 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5276 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5277 QualType ValType = AtomTy; // 'C'
5278 if (IsC11) {
5279 if (!AtomTy->isAtomicType()) {
5280 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5281 << Ptr->getType() << Ptr->getSourceRange();
5282 return ExprError();
5283 }
5284 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5286 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5287 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5288 << Ptr->getSourceRange();
5289 return ExprError();
5290 }
5291 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5292 } else if (Form != Load && Form != LoadCopy) {
5293 if (ValType.isConstQualified()) {
5294 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5295 << Ptr->getType() << Ptr->getSourceRange();
5296 return ExprError();
5297 }
5298 }
5299
5300 if (Form != TestAndSetByte && Form != ClearByte) {
5301 // Pointer to object of size zero is not allowed.
5302 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5303 diag::err_incomplete_type))
5304 return ExprError();
5305
5306 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5307 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5308 << Ptr->getType() << 1 << Ptr->getSourceRange();
5309 return ExprError();
5310 }
5311 } else {
5312 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5313 // non-const pointer type, including void* and pointers to incomplete
5314 // structs, but only access the first byte.
5315 AtomTy = Context.CharTy;
5316 AtomTy = AtomTy.withCVRQualifiers(
5317 pointerType->getPointeeType().getCVRQualifiers());
5318 QualType PointerQT = Context.getPointerType(AtomTy);
5319 pointerType = PointerQT->getAs<PointerType>();
5320 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5321 ValType = AtomTy;
5322 }
5323
5324 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5325 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5326 Diag(ExprRange.getBegin(),
5327 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5328 << 0 << Ptr->getType() << Ptr->getSourceRange();
5329 return ExprError();
5330 }
5331
5332 // For an arithmetic operation, the implied arithmetic must be well-formed.
5333 // For _n operations, the value type must also be a valid atomic type.
5334 if (Form == Arithmetic || IsN) {
5335 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5336 // trivial type errors.
5337 auto IsAllowedValueType = [&](QualType ValType,
5338 unsigned AllowedType) -> bool {
5339 bool IsX87LongDouble =
5340 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5341 &Context.getTargetInfo().getLongDoubleFormat() ==
5342 &llvm::APFloat::x87DoubleExtended();
5343 if (ValType->isIntegerType())
5344 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5345 // integers. Explicit AOEVT_Int or other combinations allow integers.
5346 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5347 if (ValType->isPointerType())
5348 return AllowedType & AOEVT_Pointer;
5349 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5350 return false;
5351 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5352 if (IsX87LongDouble)
5353 return false;
5354 return true;
5355 };
5356 if (!IsAllowedValueType(ValType, ArithAllows)) {
5357 auto DID =
5358 ArithAllows == AOEVT_FP
5359 ? diag::err_atomic_op_needs_atomic_fp
5360 : (ArithAllows & AOEVT_FP
5361 ? (ArithAllows & AOEVT_Pointer
5362 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5363 : diag::err_atomic_op_needs_atomic_int_or_fp)
5364 : (ArithAllows & AOEVT_Pointer
5365 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5366 : diag::err_atomic_op_needs_atomic_int));
5367 Diag(ExprRange.getBegin(), DID)
5368 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5369 return ExprError();
5370 }
5371 if (IsC11 && ValType->isPointerType() &&
5373 diag::err_incomplete_type)) {
5374 return ExprError();
5375 }
5376 }
5377
5378 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5379 !AtomTy->isScalarType()) {
5380 // For GNU atomics, require a trivially-copyable type. This is not part of
5381 // the GNU atomics specification but we enforce it for consistency with
5382 // other atomics which generally all require a trivially-copyable type. This
5383 // is because atomics just copy bits.
5384 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5385 << Ptr->getType() << Ptr->getSourceRange();
5386 return ExprError();
5387 }
5388
5389 switch (ValType.getObjCLifetime()) {
5392 // okay
5393 break;
5394
5398 // FIXME: Can this happen? By this point, ValType should be known
5399 // to be trivially copyable.
5400 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5401 << ValType << Ptr->getSourceRange();
5402 return ExprError();
5403 }
5404
5405 // All atomic operations have an overload which takes a pointer to a volatile
5406 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5407 // into the result or the other operands. Similarly atomic_load takes a
5408 // pointer to a const 'A'.
5409 ValType.removeLocalVolatile();
5410 ValType.removeLocalConst();
5411 QualType ResultType = ValType;
5412 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5413 Form == ClearByte)
5414 ResultType = Context.VoidTy;
5415 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5416 ResultType = Context.BoolTy;
5417
5418 // The type of a parameter passed 'by value'. In the GNU atomics, such
5419 // arguments are actually passed as pointers.
5420 QualType ByValType = ValType; // 'CP'
5421 bool IsPassedByAddress = false;
5422 if (!IsC11 && !IsHIP && !IsN) {
5423 ByValType = Ptr->getType();
5424 IsPassedByAddress = true;
5425 }
5426
5427 SmallVector<Expr *, 5> APIOrderedArgs;
5428 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5429 APIOrderedArgs.push_back(Args[0]);
5430 switch (Form) {
5431 case Init:
5432 case Load:
5433 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5434 break;
5435 case LoadCopy:
5436 case Copy:
5437 case Arithmetic:
5438 case Xchg:
5439 APIOrderedArgs.push_back(Args[2]); // Val1
5440 APIOrderedArgs.push_back(Args[1]); // Order
5441 break;
5442 case GNUXchg:
5443 APIOrderedArgs.push_back(Args[2]); // Val1
5444 APIOrderedArgs.push_back(Args[3]); // Val2
5445 APIOrderedArgs.push_back(Args[1]); // Order
5446 break;
5447 case C11CmpXchg:
5448 APIOrderedArgs.push_back(Args[2]); // Val1
5449 APIOrderedArgs.push_back(Args[4]); // Val2
5450 APIOrderedArgs.push_back(Args[1]); // Order
5451 APIOrderedArgs.push_back(Args[3]); // OrderFail
5452 break;
5453 case GNUCmpXchg:
5454 APIOrderedArgs.push_back(Args[2]); // Val1
5455 APIOrderedArgs.push_back(Args[4]); // Val2
5456 APIOrderedArgs.push_back(Args[5]); // Weak
5457 APIOrderedArgs.push_back(Args[1]); // Order
5458 APIOrderedArgs.push_back(Args[3]); // OrderFail
5459 break;
5460 case TestAndSetByte:
5461 case ClearByte:
5462 APIOrderedArgs.push_back(Args[1]); // Order
5463 break;
5464 }
5465 } else
5466 APIOrderedArgs.append(Args.begin(), Args.end());
5467
5468 // The first argument's non-CV pointer type is used to deduce the type of
5469 // subsequent arguments, except for:
5470 // - weak flag (always converted to bool)
5471 // - memory order (always converted to int)
5472 // - scope (always converted to int)
5473 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5474 QualType Ty;
5475 if (i < NumVals[Form] + 1) {
5476 switch (i) {
5477 case 0:
5478 // The first argument is always a pointer. It has a fixed type.
5479 // It is always dereferenced, a nullptr is undefined.
5480 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5481 // Nothing else to do: we already know all we want about this pointer.
5482 continue;
5483 case 1:
5484 // The second argument is the non-atomic operand. For arithmetic, this
5485 // is always passed by value, and for a compare_exchange it is always
5486 // passed by address. For the rest, GNU uses by-address and C11 uses
5487 // by-value.
5488 assert(Form != Load);
5489 if (Form == Arithmetic && ValType->isPointerType())
5490 Ty = Context.getPointerDiffType();
5491 else if (Form == Init || Form == Arithmetic)
5492 Ty = ValType;
5493 else if (Form == Copy || Form == Xchg) {
5494 if (IsPassedByAddress) {
5495 // The value pointer is always dereferenced, a nullptr is undefined.
5496 CheckNonNullArgument(*this, APIOrderedArgs[i],
5497 ExprRange.getBegin());
5498 }
5499 Ty = ByValType;
5500 } else {
5501 Expr *ValArg = APIOrderedArgs[i];
5502 // The value pointer is always dereferenced, a nullptr is undefined.
5503 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5505 // Keep address space of non-atomic pointer type.
5506 if (const PointerType *PtrTy =
5507 ValArg->getType()->getAs<PointerType>()) {
5508 AS = PtrTy->getPointeeType().getAddressSpace();
5509 }
5510 Ty = Context.getPointerType(
5511 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5512 }
5513 break;
5514 case 2:
5515 // The third argument to compare_exchange / GNU exchange is the desired
5516 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5517 if (IsPassedByAddress)
5518 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5519 Ty = ByValType;
5520 break;
5521 case 3:
5522 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5523 Ty = Context.BoolTy;
5524 break;
5525 }
5526 } else {
5527 // The order(s) and scope are always converted to int.
5528 Ty = Context.IntTy;
5529 }
5530
5531 InitializedEntity Entity =
5533 ExprResult Arg = APIOrderedArgs[i];
5534 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5535 if (Arg.isInvalid())
5536 return true;
5537 APIOrderedArgs[i] = Arg.get();
5538 }
5539
5540 // Permute the arguments into a 'consistent' order.
5541 SmallVector<Expr*, 5> SubExprs;
5542 SubExprs.push_back(Ptr);
5543 switch (Form) {
5544 case Init:
5545 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5546 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5547 break;
5548 case Load:
5549 case TestAndSetByte:
5550 case ClearByte:
5551 SubExprs.push_back(APIOrderedArgs[1]); // Order
5552 break;
5553 case LoadCopy:
5554 case Copy:
5555 case Arithmetic:
5556 case Xchg:
5557 SubExprs.push_back(APIOrderedArgs[2]); // Order
5558 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5559 break;
5560 case GNUXchg:
5561 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5562 SubExprs.push_back(APIOrderedArgs[3]); // Order
5563 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5564 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5565 break;
5566 case C11CmpXchg:
5567 SubExprs.push_back(APIOrderedArgs[3]); // Order
5568 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5569 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5570 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5571 break;
5572 case GNUCmpXchg:
5573 SubExprs.push_back(APIOrderedArgs[4]); // Order
5574 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5575 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5576 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5577 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5578 break;
5579 }
5580
5581 // If the memory orders are constants, check they are valid.
5582 if (SubExprs.size() >= 2 && Form != Init) {
5583 std::optional<llvm::APSInt> Success =
5584 SubExprs[1]->getIntegerConstantExpr(Context);
5585 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5586 Diag(SubExprs[1]->getBeginLoc(),
5587 diag::warn_atomic_op_has_invalid_memory_order)
5588 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5589 << SubExprs[1]->getSourceRange();
5590 }
5591 if (SubExprs.size() >= 5) {
5592 if (std::optional<llvm::APSInt> Failure =
5593 SubExprs[3]->getIntegerConstantExpr(Context)) {
5594 if (!llvm::is_contained(
5595 {llvm::AtomicOrderingCABI::relaxed,
5596 llvm::AtomicOrderingCABI::consume,
5597 llvm::AtomicOrderingCABI::acquire,
5598 llvm::AtomicOrderingCABI::seq_cst},
5599 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5600 Diag(SubExprs[3]->getBeginLoc(),
5601 diag::warn_atomic_op_has_invalid_memory_order)
5602 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5603 }
5604 }
5605 }
5606 }
5607
5608 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5609 auto *Scope = Args[Args.size() - 1];
5610 if (std::optional<llvm::APSInt> Result =
5611 Scope->getIntegerConstantExpr(Context)) {
5612 if (!ScopeModel->isValid(Result->getZExtValue()))
5613 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5614 << Scope->getSourceRange();
5615 }
5616 SubExprs.push_back(Scope);
5617 }
5618
5619 if (IsHIP)
5620 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5621
5622 AtomicExpr *AE = new (Context)
5623 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5624
5625 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5626 Op == AtomicExpr::AO__c11_atomic_store ||
5627 Op == AtomicExpr::AO__opencl_atomic_load ||
5628 Op == AtomicExpr::AO__hip_atomic_load ||
5629 Op == AtomicExpr::AO__opencl_atomic_store ||
5630 Op == AtomicExpr::AO__hip_atomic_store) &&
5631 Context.AtomicUsesUnsupportedLibcall(AE))
5632 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5633 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5634 Op == AtomicExpr::AO__opencl_atomic_load ||
5635 Op == AtomicExpr::AO__hip_atomic_load)
5636 ? 0
5637 : 1);
5638
5639 if (ValType->isBitIntType()) {
5640 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5641 return ExprError();
5642 }
5643
5644 return AE;
5645}
5646
5647/// checkBuiltinArgument - Given a call to a builtin function, perform
5648/// normal type-checking on the given argument, updating the call in
5649/// place. This is useful when a builtin function requires custom
5650/// type-checking for some of its arguments but not necessarily all of
5651/// them.
5652///
5653/// Returns true on error.
5654static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5655 FunctionDecl *Fn = E->getDirectCallee();
5656 assert(Fn && "builtin call without direct callee!");
5657
5658 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5659 InitializedEntity Entity =
5661
5662 ExprResult Arg = E->getArg(ArgIndex);
5663 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5664 if (Arg.isInvalid())
5665 return true;
5666
5667 E->setArg(ArgIndex, Arg.get());
5668 return false;
5669}
5670
5671ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5672 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5673 Expr *Callee = TheCall->getCallee();
5674 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5675 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5676
5677 // Ensure that we have at least one argument to do type inference from.
5678 if (TheCall->getNumArgs() < 1) {
5679 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5680 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5681 << Callee->getSourceRange();
5682 return ExprError();
5683 }
5684
5685 // Inspect the first argument of the atomic builtin. This should always be
5686 // a pointer type, whose element is an integral scalar or pointer type.
5687 // Because it is a pointer type, we don't have to worry about any implicit
5688 // casts here.
5689 // FIXME: We don't allow floating point scalars as input.
5690 Expr *FirstArg = TheCall->getArg(0);
5691 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5692 if (FirstArgResult.isInvalid())
5693 return ExprError();
5694 FirstArg = FirstArgResult.get();
5695 TheCall->setArg(0, FirstArg);
5696
5697 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5698 if (!pointerType) {
5699 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5700 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5701 return ExprError();
5702 }
5703
5704 QualType ValType = pointerType->getPointeeType();
5705 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5706 !ValType->isBlockPointerType()) {
5707 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5708 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5709 return ExprError();
5710 }
5711 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5712 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5713 Diag(FirstArg->getBeginLoc(),
5714 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5715 << 1 << ValType << FirstArg->getSourceRange();
5716 return ExprError();
5717 }
5718
5719 if (ValType.isConstQualified()) {
5720 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5721 << FirstArg->getType() << FirstArg->getSourceRange();
5722 return ExprError();
5723 }
5724
5725 switch (ValType.getObjCLifetime()) {
5728 // okay
5729 break;
5730
5734 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5735 << ValType << FirstArg->getSourceRange();
5736 return ExprError();
5737 }
5738
5739 // Strip any qualifiers off ValType.
5740 ValType = ValType.getUnqualifiedType();
5741
5742 // The majority of builtins return a value, but a few have special return
5743 // types, so allow them to override appropriately below.
5744 QualType ResultType = ValType;
5745
5746 // We need to figure out which concrete builtin this maps onto. For example,
5747 // __sync_fetch_and_add with a 2 byte object turns into
5748 // __sync_fetch_and_add_2.
5749#define BUILTIN_ROW(x) \
5750 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5751 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5752
5753 static const unsigned BuiltinIndices[][5] = {
5754 BUILTIN_ROW(__sync_fetch_and_add),
5755 BUILTIN_ROW(__sync_fetch_and_sub),
5756 BUILTIN_ROW(__sync_fetch_and_or),
5757 BUILTIN_ROW(__sync_fetch_and_and),
5758 BUILTIN_ROW(__sync_fetch_and_xor),
5759 BUILTIN_ROW(__sync_fetch_and_nand),
5760
5761 BUILTIN_ROW(__sync_add_and_fetch),
5762 BUILTIN_ROW(__sync_sub_and_fetch),
5763 BUILTIN_ROW(__sync_and_and_fetch),
5764 BUILTIN_ROW(__sync_or_and_fetch),
5765 BUILTIN_ROW(__sync_xor_and_fetch),
5766 BUILTIN_ROW(__sync_nand_and_fetch),
5767
5768 BUILTIN_ROW(__sync_val_compare_and_swap),
5769 BUILTIN_ROW(__sync_bool_compare_and_swap),
5770 BUILTIN_ROW(__sync_lock_test_and_set),
5771 BUILTIN_ROW(__sync_lock_release),
5772 BUILTIN_ROW(__sync_swap)
5773 };
5774#undef BUILTIN_ROW
5775
5776 // Determine the index of the size.
5777 unsigned SizeIndex;
5778 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5779 case 1: SizeIndex = 0; break;
5780 case 2: SizeIndex = 1; break;
5781 case 4: SizeIndex = 2; break;
5782 case 8: SizeIndex = 3; break;
5783 case 16: SizeIndex = 4; break;
5784 default:
5785 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5786 << FirstArg->getType() << FirstArg->getSourceRange();
5787 return ExprError();
5788 }
5789
5790 // Each of these builtins has one pointer argument, followed by some number of
5791 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5792 // that we ignore. Find out which row of BuiltinIndices to read from as well
5793 // as the number of fixed args.
5794 unsigned BuiltinID = FDecl->getBuiltinID();
5795 unsigned BuiltinIndex, NumFixed = 1;
5796 bool WarnAboutSemanticsChange = false;
5797 switch (BuiltinID) {
5798 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5799 case Builtin::BI__sync_fetch_and_add:
5800 case Builtin::BI__sync_fetch_and_add_1:
5801 case Builtin::BI__sync_fetch_and_add_2:
5802 case Builtin::BI__sync_fetch_and_add_4:
5803 case Builtin::BI__sync_fetch_and_add_8:
5804 case Builtin::BI__sync_fetch_and_add_16:
5805 BuiltinIndex = 0;
5806 break;
5807
5808 case Builtin::BI__sync_fetch_and_sub:
5809 case Builtin::BI__sync_fetch_and_sub_1:
5810 case Builtin::BI__sync_fetch_and_sub_2:
5811 case Builtin::BI__sync_fetch_and_sub_4:
5812 case Builtin::BI__sync_fetch_and_sub_8:
5813 case Builtin::BI__sync_fetch_and_sub_16:
5814 BuiltinIndex = 1;
5815 break;
5816
5817 case Builtin::BI__sync_fetch_and_or:
5818 case Builtin::BI__sync_fetch_and_or_1:
5819 case Builtin::BI__sync_fetch_and_or_2:
5820 case Builtin::BI__sync_fetch_and_or_4:
5821 case Builtin::BI__sync_fetch_and_or_8:
5822 case Builtin::BI__sync_fetch_and_or_16:
5823 BuiltinIndex = 2;
5824 break;
5825
5826 case Builtin::BI__sync_fetch_and_and:
5827 case Builtin::BI__sync_fetch_and_and_1:
5828 case Builtin::BI__sync_fetch_and_and_2:
5829 case Builtin::BI__sync_fetch_and_and_4:
5830 case Builtin::BI__sync_fetch_and_and_8:
5831 case Builtin::BI__sync_fetch_and_and_16:
5832 BuiltinIndex = 3;
5833 break;
5834
5835 case Builtin::BI__sync_fetch_and_xor:
5836 case Builtin::BI__sync_fetch_and_xor_1:
5837 case Builtin::BI__sync_fetch_and_xor_2:
5838 case Builtin::BI__sync_fetch_and_xor_4:
5839 case Builtin::BI__sync_fetch_and_xor_8:
5840 case Builtin::BI__sync_fetch_and_xor_16:
5841 BuiltinIndex = 4;
5842 break;
5843
5844 case Builtin::BI__sync_fetch_and_nand:
5845 case Builtin::BI__sync_fetch_and_nand_1:
5846 case Builtin::BI__sync_fetch_and_nand_2:
5847 case Builtin::BI__sync_fetch_and_nand_4:
5848 case Builtin::BI__sync_fetch_and_nand_8:
5849 case Builtin::BI__sync_fetch_and_nand_16:
5850 BuiltinIndex = 5;
5851 WarnAboutSemanticsChange = true;
5852 break;
5853
5854 case Builtin::BI__sync_add_and_fetch:
5855 case Builtin::BI__sync_add_and_fetch_1:
5856 case Builtin::BI__sync_add_and_fetch_2:
5857 case Builtin::BI__sync_add_and_fetch_4:
5858 case Builtin::BI__sync_add_and_fetch_8:
5859 case Builtin::BI__sync_add_and_fetch_16:
5860 BuiltinIndex = 6;
5861 break;
5862
5863 case Builtin::BI__sync_sub_and_fetch:
5864 case Builtin::BI__sync_sub_and_fetch_1:
5865 case Builtin::BI__sync_sub_and_fetch_2:
5866 case Builtin::BI__sync_sub_and_fetch_4:
5867 case Builtin::BI__sync_sub_and_fetch_8:
5868 case Builtin::BI__sync_sub_and_fetch_16:
5869 BuiltinIndex = 7;
5870 break;
5871
5872 case Builtin::BI__sync_and_and_fetch:
5873 case Builtin::BI__sync_and_and_fetch_1:
5874 case Builtin::BI__sync_and_and_fetch_2:
5875 case Builtin::BI__sync_and_and_fetch_4:
5876 case Builtin::BI__sync_and_and_fetch_8:
5877 case Builtin::BI__sync_and_and_fetch_16:
5878 BuiltinIndex = 8;
5879 break;
5880
5881 case Builtin::BI__sync_or_and_fetch:
5882 case Builtin::BI__sync_or_and_fetch_1:
5883 case Builtin::BI__sync_or_and_fetch_2:
5884 case Builtin::BI__sync_or_and_fetch_4:
5885 case Builtin::BI__sync_or_and_fetch_8:
5886 case Builtin::BI__sync_or_and_fetch_16:
5887 BuiltinIndex = 9;
5888 break;
5889
5890 case Builtin::BI__sync_xor_and_fetch:
5891 case Builtin::BI__sync_xor_and_fetch_1:
5892 case Builtin::BI__sync_xor_and_fetch_2:
5893 case Builtin::BI__sync_xor_and_fetch_4:
5894 case Builtin::BI__sync_xor_and_fetch_8:
5895 case Builtin::BI__sync_xor_and_fetch_16:
5896 BuiltinIndex = 10;
5897 break;
5898
5899 case Builtin::BI__sync_nand_and_fetch:
5900 case Builtin::BI__sync_nand_and_fetch_1:
5901 case Builtin::BI__sync_nand_and_fetch_2:
5902 case Builtin::BI__sync_nand_and_fetch_4:
5903 case Builtin::BI__sync_nand_and_fetch_8:
5904 case Builtin::BI__sync_nand_and_fetch_16:
5905 BuiltinIndex = 11;
5906 WarnAboutSemanticsChange = true;
5907 break;
5908
5909 case Builtin::BI__sync_val_compare_and_swap:
5910 case Builtin::BI__sync_val_compare_and_swap_1:
5911 case Builtin::BI__sync_val_compare_and_swap_2:
5912 case Builtin::BI__sync_val_compare_and_swap_4:
5913 case Builtin::BI__sync_val_compare_and_swap_8:
5914 case Builtin::BI__sync_val_compare_and_swap_16:
5915 BuiltinIndex = 12;
5916 NumFixed = 2;
5917 break;
5918
5919 case Builtin::BI__sync_bool_compare_and_swap:
5920 case Builtin::BI__sync_bool_compare_and_swap_1:
5921 case Builtin::BI__sync_bool_compare_and_swap_2:
5922 case Builtin::BI__sync_bool_compare_and_swap_4:
5923 case Builtin::BI__sync_bool_compare_and_swap_8:
5924 case Builtin::BI__sync_bool_compare_and_swap_16:
5925 BuiltinIndex = 13;
5926 NumFixed = 2;
5927 ResultType = Context.BoolTy;
5928 break;
5929
5930 case Builtin::BI__sync_lock_test_and_set:
5931 case Builtin::BI__sync_lock_test_and_set_1:
5932 case Builtin::BI__sync_lock_test_and_set_2:
5933 case Builtin::BI__sync_lock_test_and_set_4:
5934 case Builtin::BI__sync_lock_test_and_set_8:
5935 case Builtin::BI__sync_lock_test_and_set_16:
5936 BuiltinIndex = 14;
5937 break;
5938
5939 case Builtin::BI__sync_lock_release:
5940 case Builtin::BI__sync_lock_release_1:
5941 case Builtin::BI__sync_lock_release_2:
5942 case Builtin::BI__sync_lock_release_4:
5943 case Builtin::BI__sync_lock_release_8:
5944 case Builtin::BI__sync_lock_release_16:
5945 BuiltinIndex = 15;
5946 NumFixed = 0;
5947 ResultType = Context.VoidTy;
5948 break;
5949
5950 case Builtin::BI__sync_swap:
5951 case Builtin::BI__sync_swap_1:
5952 case Builtin::BI__sync_swap_2:
5953 case Builtin::BI__sync_swap_4:
5954 case Builtin::BI__sync_swap_8:
5955 case Builtin::BI__sync_swap_16:
5956 BuiltinIndex = 16;
5957 break;
5958 }
5959
5960 // Now that we know how many fixed arguments we expect, first check that we
5961 // have at least that many.
5962 if (TheCall->getNumArgs() < 1+NumFixed) {
5963 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5964 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5965 << Callee->getSourceRange();
5966 return ExprError();
5967 }
5968
5969 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5970 << Callee->getSourceRange();
5971
5972 if (WarnAboutSemanticsChange) {
5973 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5974 << Callee->getSourceRange();
5975 }
5976
5977 // Get the decl for the concrete builtin from this, we can tell what the
5978 // concrete integer type we should convert to is.
5979 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5980 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5981 FunctionDecl *NewBuiltinDecl;
5982 if (NewBuiltinID == BuiltinID)
5983 NewBuiltinDecl = FDecl;
5984 else {
5985 // Perform builtin lookup to avoid redeclaring it.
5986 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5987 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5988 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5989 assert(Res.getFoundDecl());
5990 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5991 if (!NewBuiltinDecl)
5992 return ExprError();
5993 }
5994
5995 // The first argument --- the pointer --- has a fixed type; we
5996 // deduce the types of the rest of the arguments accordingly. Walk
5997 // the remaining arguments, converting them to the deduced value type.
5998 for (unsigned i = 0; i != NumFixed; ++i) {
5999 ExprResult Arg = TheCall->getArg(i+1);
6000
6001 // GCC does an implicit conversion to the pointer or integer ValType. This
6002 // can fail in some cases (1i -> int**), check for this error case now.
6003 // Initialize the argument.
6004 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6005 ValType, /*consume*/ false);
6006 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6007 if (Arg.isInvalid())
6008 return ExprError();
6009
6010 // Okay, we have something that *can* be converted to the right type. Check
6011 // to see if there is a potentially weird extension going on here. This can
6012 // happen when you do an atomic operation on something like an char* and
6013 // pass in 42. The 42 gets converted to char. This is even more strange
6014 // for things like 45.123 -> char, etc.
6015 // FIXME: Do this check.
6016 TheCall->setArg(i+1, Arg.get());
6017 }
6018
6019 // Create a new DeclRefExpr to refer to the new decl.
6020 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6021 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6022 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6023 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6024
6025 // Set the callee in the CallExpr.
6026 // FIXME: This loses syntactic information.
6027 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6028 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6029 CK_BuiltinFnToFnPtr);
6030 TheCall->setCallee(PromotedCall.get());
6031
6032 // Change the result type of the call to match the original value type. This
6033 // is arbitrary, but the codegen for these builtins ins design to handle it
6034 // gracefully.
6035 TheCall->setType(ResultType);
6036
6037 // Prohibit problematic uses of bit-precise integer types with atomic
6038 // builtins. The arguments would have already been converted to the first
6039 // argument's type, so only need to check the first argument.
6040 const auto *BitIntValType = ValType->getAs<BitIntType>();
6041 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6042 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6043 return ExprError();
6044 }
6045
6046 return TheCallResult;
6047}
6048
6049ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6050 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6051 DeclRefExpr *DRE =
6053 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6054 unsigned BuiltinID = FDecl->getBuiltinID();
6055 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6056 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6057 "Unexpected nontemporal load/store builtin!");
6058 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6059 unsigned numArgs = isStore ? 2 : 1;
6060
6061 // Ensure that we have the proper number of arguments.
6062 if (checkArgCount(TheCall, numArgs))
6063 return ExprError();
6064
6065 // Inspect the last argument of the nontemporal builtin. This should always
6066 // be a pointer type, from which we imply the type of the memory access.
6067 // Because it is a pointer type, we don't have to worry about any implicit
6068 // casts here.
6069 Expr *PointerArg = TheCall->getArg(numArgs - 1);
6070 ExprResult PointerArgResult =
6072
6073 if (PointerArgResult.isInvalid())
6074 return ExprError();
6075 PointerArg = PointerArgResult.get();
6076 TheCall->setArg(numArgs - 1, PointerArg);
6077
6078 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6079 if (!pointerType) {
6080 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6081 << PointerArg->getType() << PointerArg->getSourceRange();
6082 return ExprError();
6083 }
6084
6085 QualType ValType = pointerType->getPointeeType();
6086
6087 // Strip any qualifiers off ValType.
6088 ValType = ValType.getUnqualifiedType();
6089 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6090 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6091 !ValType->isVectorType()) {
6092 Diag(DRE->getBeginLoc(),
6093 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6094 << PointerArg->getType() << PointerArg->getSourceRange();
6095 return ExprError();
6096 }
6097
6098 if (!isStore) {
6099 TheCall->setType(ValType);
6100 return TheCallResult;
6101 }
6102
6103 ExprResult ValArg = TheCall->getArg(0);
6104 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6105 Context, ValType, /*consume*/ false);
6106 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6107 if (ValArg.isInvalid())
6108 return ExprError();
6109
6110 TheCall->setArg(0, ValArg.get());
6111 TheCall->setType(Context.VoidTy);
6112 return TheCallResult;
6113}
6114
6115/// CheckObjCString - Checks that the format string argument to the os_log()
6116/// and os_trace() functions is correct, and converts it to const char *.
6117ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6118 Arg = Arg->IgnoreParenCasts();
6119 auto *Literal = dyn_cast<StringLiteral>(Arg);
6120 if (!Literal) {
6121 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6122 Literal = ObjcLiteral->getString();
6123 }
6124 }
6125
6126 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6127 return ExprError(
6128 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6129 << Arg->getSourceRange());
6130 }
6131
6132 ExprResult Result(Literal);
6133 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6134 InitializedEntity Entity =
6136 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6137 return Result;
6138}
6139
6140/// Check that the user is calling the appropriate va_start builtin for the
6141/// target and calling convention.
6142static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6143 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6144 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6145 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6146 TT.getArch() == llvm::Triple::aarch64_32);
6147 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6148 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6149 if (IsX64 || IsAArch64) {
6150 CallingConv CC = CC_C;
6151 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6152 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6153 if (IsMSVAStart) {
6154 // Don't allow this in System V ABI functions.
6155 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6156 return S.Diag(Fn->getBeginLoc(),
6157 diag::err_ms_va_start_used_in_sysv_function);
6158 } else {
6159 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6160 // On x64 Windows, don't allow this in System V ABI functions.
6161 // (Yes, that means there's no corresponding way to support variadic
6162 // System V ABI functions on Windows.)
6163 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6164 (!IsWindowsOrUEFI && CC == CC_Win64))
6165 return S.Diag(Fn->getBeginLoc(),
6166 diag::err_va_start_used_in_wrong_abi_function)
6167 << !IsWindowsOrUEFI;
6168 }
6169 return false;
6170 }
6171
6172 if (IsMSVAStart)
6173 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6174 return false;
6175}
6176
6178 ParmVarDecl **LastParam = nullptr) {
6179 // Determine whether the current function, block, or obj-c method is variadic
6180 // and get its parameter list.
6181 bool IsVariadic = false;
6183 DeclContext *Caller = S.CurContext;
6184 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6185 IsVariadic = Block->isVariadic();
6186 Params = Block->parameters();
6187 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6188 IsVariadic = FD->isVariadic();
6189 Params = FD->parameters();
6190 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6191 IsVariadic = MD->isVariadic();
6192 // FIXME: This isn't correct for methods (results in bogus warning).
6193 Params = MD->parameters();
6194 } else if (isa<CapturedDecl>(Caller)) {
6195 // We don't support va_start in a CapturedDecl.
6196 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6197 return true;
6198 } else {
6199 // This must be some other declcontext that parses exprs.
6200 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6201 return true;
6202 }
6203
6204 if (!IsVariadic) {
6205 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6206 return true;
6207 }
6208
6209 if (LastParam)
6210 *LastParam = Params.empty() ? nullptr : Params.back();
6211
6212 return false;
6213}
6214
6215bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6216 Expr *Fn = TheCall->getCallee();
6217 if (checkVAStartABI(*this, BuiltinID, Fn))
6218 return true;
6219
6220 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6221 // This builtin requires one argument (the va_list), allows two arguments,
6222 // but diagnoses more than two arguments. e.g.,
6223 // __builtin_c23_va_start(); // error
6224 // __builtin_c23_va_start(list); // ok
6225 // __builtin_c23_va_start(list, param); // ok
6226 // __builtin_c23_va_start(list, anything, anything); // error
6227 // This differs from the GCC behavior in that they accept the last case
6228 // with a warning, but it doesn't seem like a useful behavior to allow.
6229 if (checkArgCountRange(TheCall, 1, 2))
6230 return true;
6231 } else {
6232 // In C23 mode, va_start only needs one argument. However, the builtin still
6233 // requires two arguments (which matches the behavior of the GCC builtin),
6234 // <stdarg.h> passes `0` as the second argument in C23 mode.
6235 if (checkArgCount(TheCall, 2))
6236 return true;
6237 }
6238
6239 // Type-check the first argument normally.
6240 if (checkBuiltinArgument(*this, TheCall, 0))
6241 return true;
6242
6243 // Check that the current function is variadic, and get its last parameter.
6244 ParmVarDecl *LastParam;
6245 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6246 return true;
6247
6248 // Verify that the second argument to the builtin is the last non-variadic
6249 // argument of the current function or method. In C23 mode, if the call is
6250 // not to __builtin_c23_va_start, and the second argument is an integer
6251 // constant expression with value 0, then we don't bother with this check.
6252 // For __builtin_c23_va_start, we only perform the check for the second
6253 // argument being the last argument to the current function if there is a
6254 // second argument present.
6255 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6256 TheCall->getNumArgs() < 2) {
6257 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6258 return false;
6259 }
6260
6261 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6262 if (std::optional<llvm::APSInt> Val =
6264 Val && LangOpts.C23 && *Val == 0 &&
6265 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6266 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6267 return false;
6268 }
6269
6270 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6271 // next block.
6272 QualType Type;
6273 SourceLocation ParamLoc;
6274 bool IsCRegister = false;
6275 bool SecondArgIsLastNonVariadicArgument = false;
6276 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6277 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6278 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6279
6280 Type = PV->getType();
6281 ParamLoc = PV->getLocation();
6282 IsCRegister =
6283 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6284 }
6285 }
6286
6287 if (!SecondArgIsLastNonVariadicArgument)
6288 Diag(TheCall->getArg(1)->getBeginLoc(),
6289 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6290 else if (IsCRegister || Type->isReferenceType() ||
6291 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6292 // Promotable integers are UB, but enumerations need a bit of
6293 // extra checking to see what their promotable type actually is.
6294 if (!Context.isPromotableIntegerType(Type))
6295 return false;
6296 const auto *ED = Type->getAsEnumDecl();
6297 if (!ED)
6298 return true;
6299 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6300 }()) {
6301 unsigned Reason = 0;
6302 if (Type->isReferenceType()) Reason = 1;
6303 else if (IsCRegister) Reason = 2;
6304 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6305 Diag(ParamLoc, diag::note_parameter_type) << Type;
6306 }
6307
6308 return false;
6309}
6310
6311bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6312 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6313 const LangOptions &LO = getLangOpts();
6314
6315 if (LO.CPlusPlus)
6316 return Arg->getType()
6318 .getTypePtr()
6319 ->getPointeeType()
6321
6322 // In C, allow aliasing through `char *`, this is required for AArch64 at
6323 // least.
6324 return true;
6325 };
6326
6327 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6328 // const char *named_addr);
6329
6330 Expr *Func = Call->getCallee();
6331
6332 if (Call->getNumArgs() < 3)
6333 return Diag(Call->getEndLoc(),
6334 diag::err_typecheck_call_too_few_args_at_least)
6335 << 0 /*function call*/ << 3 << Call->getNumArgs()
6336 << /*is non object*/ 0;
6337
6338 // Type-check the first argument normally.
6339 if (checkBuiltinArgument(*this, Call, 0))
6340 return true;
6341
6342 // Check that the current function is variadic.
6344 return true;
6345
6346 // __va_start on Windows does not validate the parameter qualifiers
6347
6348 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6349 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6350
6351 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6352 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6353
6354 const QualType &ConstCharPtrTy =
6355 Context.getPointerType(Context.CharTy.withConst());
6356 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6357 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6358 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6359 << 0 /* qualifier difference */
6360 << 3 /* parameter mismatch */
6361 << 2 << Arg1->getType() << ConstCharPtrTy;
6362
6363 const QualType SizeTy = Context.getSizeType();
6364 if (!Context.hasSameType(
6366 SizeTy))
6367 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6368 << Arg2->getType() << SizeTy << 1 /* different class */
6369 << 0 /* qualifier difference */
6370 << 3 /* parameter mismatch */
6371 << 3 << Arg2->getType() << SizeTy;
6372
6373 return false;
6374}
6375
6376bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6377 if (checkArgCount(TheCall, 2))
6378 return true;
6379
6380 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6381 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6382 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6383 << 1 << 0 << TheCall->getSourceRange();
6384
6385 ExprResult OrigArg0 = TheCall->getArg(0);
6386 ExprResult OrigArg1 = TheCall->getArg(1);
6387
6388 // Do standard promotions between the two arguments, returning their common
6389 // type.
6390 QualType Res = UsualArithmeticConversions(
6391 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6392 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6393 return true;
6394
6395 // Make sure any conversions are pushed back into the call; this is
6396 // type safe since unordered compare builtins are declared as "_Bool
6397 // foo(...)".
6398 TheCall->setArg(0, OrigArg0.get());
6399 TheCall->setArg(1, OrigArg1.get());
6400
6401 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6402 return false;
6403
6404 // If the common type isn't a real floating type, then the arguments were
6405 // invalid for this operation.
6406 if (Res.isNull() || !Res->isRealFloatingType())
6407 return Diag(OrigArg0.get()->getBeginLoc(),
6408 diag::err_typecheck_call_invalid_ordered_compare)
6409 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6410 << SourceRange(OrigArg0.get()->getBeginLoc(),
6411 OrigArg1.get()->getEndLoc());
6412
6413 return false;
6414}
6415
6416bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6417 unsigned BuiltinID) {
6418 if (checkArgCount(TheCall, NumArgs))
6419 return true;
6420
6421 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6422 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6423 BuiltinID == Builtin::BI__builtin_isinf ||
6424 BuiltinID == Builtin::BI__builtin_isinf_sign))
6425 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6426 << 0 << 0 << TheCall->getSourceRange();
6427
6428 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6429 BuiltinID == Builtin::BI__builtin_isunordered))
6430 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6431 << 1 << 0 << TheCall->getSourceRange();
6432
6433 bool IsFPClass = NumArgs == 2;
6434
6435 // Find out position of floating-point argument.
6436 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6437
6438 // We can count on all parameters preceding the floating-point just being int.
6439 // Try all of those.
6440 for (unsigned i = 0; i < FPArgNo; ++i) {
6441 Expr *Arg = TheCall->getArg(i);
6442
6443 if (Arg->isTypeDependent())
6444 return false;
6445
6448
6449 if (Res.isInvalid())
6450 return true;
6451 TheCall->setArg(i, Res.get());
6452 }
6453
6454 Expr *OrigArg = TheCall->getArg(FPArgNo);
6455
6456 if (OrigArg->isTypeDependent())
6457 return false;
6458
6459 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6461 if (!Res.isUsable())
6462 return true;
6463 OrigArg = Res.get();
6464
6465 TheCall->setArg(FPArgNo, OrigArg);
6466
6467 QualType VectorResultTy;
6468 QualType ElementTy = OrigArg->getType();
6469 // TODO: When all classification function are implemented with is_fpclass,
6470 // vector argument can be supported in all of them.
6471 if (ElementTy->isVectorType() && IsFPClass) {
6472 VectorResultTy = GetSignedVectorType(ElementTy);
6473 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6474 }
6475
6476 // This operation requires a non-_Complex floating-point number.
6477 if (!ElementTy->isRealFloatingType())
6478 return Diag(OrigArg->getBeginLoc(),
6479 diag::err_typecheck_call_invalid_unary_fp)
6480 << OrigArg->getType() << OrigArg->getSourceRange();
6481
6482 // __builtin_isfpclass has integer parameter that specify test mask. It is
6483 // passed in (...), so it should be analyzed completely here.
6484 if (IsFPClass)
6485 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6486 return true;
6487
6488 // TODO: enable this code to all classification functions.
6489 if (IsFPClass) {
6490 QualType ResultTy;
6491 if (!VectorResultTy.isNull())
6492 ResultTy = VectorResultTy;
6493 else
6494 ResultTy = Context.IntTy;
6495 TheCall->setType(ResultTy);
6496 }
6497
6498 return false;
6499}
6500
6501bool Sema::BuiltinComplex(CallExpr *TheCall) {
6502 if (checkArgCount(TheCall, 2))
6503 return true;
6504
6505 bool Dependent = false;
6506 for (unsigned I = 0; I != 2; ++I) {
6507 Expr *Arg = TheCall->getArg(I);
6508 QualType T = Arg->getType();
6509 if (T->isDependentType()) {
6510 Dependent = true;
6511 continue;
6512 }
6513
6514 // Despite supporting _Complex int, GCC requires a real floating point type
6515 // for the operands of __builtin_complex.
6516 if (!T->isRealFloatingType()) {
6517 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6518 << Arg->getType() << Arg->getSourceRange();
6519 }
6520
6521 ExprResult Converted = DefaultLvalueConversion(Arg);
6522 if (Converted.isInvalid())
6523 return true;
6524 TheCall->setArg(I, Converted.get());
6525 }
6526
6527 if (Dependent) {
6528 TheCall->setType(Context.DependentTy);
6529 return false;
6530 }
6531
6532 Expr *Real = TheCall->getArg(0);
6533 Expr *Imag = TheCall->getArg(1);
6534 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6535 return Diag(Real->getBeginLoc(),
6536 diag::err_typecheck_call_different_arg_types)
6537 << Real->getType() << Imag->getType()
6538 << Real->getSourceRange() << Imag->getSourceRange();
6539 }
6540
6541 TheCall->setType(Context.getComplexType(Real->getType()));
6542 return false;
6543}
6544
6545/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6546// This is declared to take (...), so we have to check everything.
6548 unsigned NumArgs = TheCall->getNumArgs();
6549 if (NumArgs < 2)
6550 return ExprError(Diag(TheCall->getEndLoc(),
6551 diag::err_typecheck_call_too_few_args_at_least)
6552 << 0 /*function call*/ << 2 << NumArgs
6553 << /*is non object*/ 0 << TheCall->getSourceRange());
6554
6555 // Determine which of the following types of shufflevector we're checking:
6556 // 1) unary, vector mask: (lhs, mask)
6557 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6558 QualType ResType = TheCall->getArg(0)->getType();
6559 unsigned NumElements = 0;
6560
6561 if (!TheCall->getArg(0)->isTypeDependent() &&
6562 !TheCall->getArg(1)->isTypeDependent()) {
6563 QualType LHSType = TheCall->getArg(0)->getType();
6564 QualType RHSType = TheCall->getArg(1)->getType();
6565
6566 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6567 return ExprError(
6568 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6569 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6570 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6571 TheCall->getArg(1)->getEndLoc()));
6572
6573 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6574 unsigned NumResElements = NumArgs - 2;
6575
6576 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6577 // with mask. If so, verify that RHS is an integer vector type with the
6578 // same number of elts as lhs.
6579 if (NumArgs == 2) {
6580 if (!RHSType->hasIntegerRepresentation() ||
6581 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6582 return ExprError(Diag(TheCall->getBeginLoc(),
6583 diag::err_vec_builtin_incompatible_vector)
6584 << TheCall->getDirectCallee()
6585 << /*isMoreThanTwoArgs*/ false
6586 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6587 TheCall->getArg(1)->getEndLoc()));
6588 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6589 return ExprError(Diag(TheCall->getBeginLoc(),
6590 diag::err_vec_builtin_incompatible_vector)
6591 << TheCall->getDirectCallee()
6592 << /*isMoreThanTwoArgs*/ false
6593 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6594 TheCall->getArg(1)->getEndLoc()));
6595 } else if (NumElements != NumResElements) {
6596 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6597 ResType = ResType->isExtVectorType()
6598 ? Context.getExtVectorType(EltType, NumResElements)
6599 : Context.getVectorType(EltType, NumResElements,
6601 }
6602 }
6603
6604 for (unsigned I = 2; I != NumArgs; ++I) {
6605 Expr *Arg = TheCall->getArg(I);
6606 if (Arg->isTypeDependent() || Arg->isValueDependent())
6607 continue;
6608
6609 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6610 if (!Result)
6611 return ExprError(Diag(TheCall->getBeginLoc(),
6612 diag::err_shufflevector_nonconstant_argument)
6613 << Arg->getSourceRange());
6614
6615 // Allow -1 which will be translated to undef in the IR.
6616 if (Result->isSigned() && Result->isAllOnes())
6617 ;
6618 else if (Result->getActiveBits() > 64 ||
6619 Result->getZExtValue() >= NumElements * 2)
6620 return ExprError(Diag(TheCall->getBeginLoc(),
6621 diag::err_shufflevector_argument_too_large)
6622 << Arg->getSourceRange());
6623
6624 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6625 }
6626
6627 auto *Result = new (Context) ShuffleVectorExpr(
6628 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6629 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6630
6631 // All moved to Result.
6632 TheCall->shrinkNumArgs(0);
6633 return Result;
6634}
6635
6637 SourceLocation BuiltinLoc,
6638 SourceLocation RParenLoc) {
6641 QualType DstTy = TInfo->getType();
6642 QualType SrcTy = E->getType();
6643
6644 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6645 return ExprError(Diag(BuiltinLoc,
6646 diag::err_convertvector_non_vector)
6647 << E->getSourceRange());
6648 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6649 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6650 << "second"
6651 << "__builtin_convertvector");
6652
6653 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6654 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6655 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6656 if (SrcElts != DstElts)
6657 return ExprError(Diag(BuiltinLoc,
6658 diag::err_convertvector_incompatible_vector)
6659 << E->getSourceRange());
6660 }
6661
6662 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6663 RParenLoc, CurFPFeatureOverrides());
6664}
6665
6666bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6667 unsigned NumArgs = TheCall->getNumArgs();
6668
6669 if (NumArgs > 3)
6670 return Diag(TheCall->getEndLoc(),
6671 diag::err_typecheck_call_too_many_args_at_most)
6672 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6673 << TheCall->getSourceRange();
6674
6675 // Argument 0 is checked for us and the remaining arguments must be
6676 // constant integers.
6677 for (unsigned i = 1; i != NumArgs; ++i)
6678 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6679 return true;
6680
6681 return false;
6682}
6683
6684bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6685 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6686 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6687 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6688 if (checkArgCount(TheCall, 1))
6689 return true;
6690 Expr *Arg = TheCall->getArg(0);
6691 if (Arg->isInstantiationDependent())
6692 return false;
6693
6694 QualType ArgTy = Arg->getType();
6695 if (!ArgTy->hasFloatingRepresentation())
6696 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6697 << ArgTy;
6698 if (Arg->isLValue()) {
6699 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6700 TheCall->setArg(0, FirstArg.get());
6701 }
6702 TheCall->setType(TheCall->getArg(0)->getType());
6703 return false;
6704}
6705
6706bool Sema::BuiltinAssume(CallExpr *TheCall) {
6707 Expr *Arg = TheCall->getArg(0);
6708 if (Arg->isInstantiationDependent()) return false;
6709
6710 if (Arg->HasSideEffects(Context))
6711 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6712 << Arg->getSourceRange()
6713 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6714
6715 return false;
6716}
6717
6718bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6719 // The alignment must be a constant integer.
6720 Expr *Arg = TheCall->getArg(1);
6721
6722 // We can't check the value of a dependent argument.
6723 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6724 if (const auto *UE =
6725 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6726 if (UE->getKind() == UETT_AlignOf ||
6727 UE->getKind() == UETT_PreferredAlignOf)
6728 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6729 << Arg->getSourceRange();
6730
6731 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6732
6733 if (!Result.isPowerOf2())
6734 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6735 << Arg->getSourceRange();
6736
6737 if (Result < Context.getCharWidth())
6738 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6739 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6740
6741 if (Result > std::numeric_limits<int32_t>::max())
6742 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6743 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6744 }
6745
6746 return false;
6747}
6748
6749bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6750 if (checkArgCountRange(TheCall, 2, 3))
6751 return true;
6752
6753 unsigned NumArgs = TheCall->getNumArgs();
6754 Expr *FirstArg = TheCall->getArg(0);
6755
6756 {
6757 ExprResult FirstArgResult =
6759 if (!FirstArgResult.get()->getType()->isPointerType()) {
6760 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6761 << TheCall->getSourceRange();
6762 return true;
6763 }
6764 TheCall->setArg(0, FirstArgResult.get());
6765 }
6766
6767 // The alignment must be a constant integer.
6768 Expr *SecondArg = TheCall->getArg(1);
6769
6770 // We can't check the value of a dependent argument.
6771 if (!SecondArg->isValueDependent()) {
6772 llvm::APSInt Result;
6773 if (BuiltinConstantArg(TheCall, 1, Result))
6774 return true;
6775
6776 if (!Result.isPowerOf2())
6777 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6778 << SecondArg->getSourceRange();
6779
6781 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6782 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6783
6784 TheCall->setArg(1,
6786 }
6787
6788 if (NumArgs > 2) {
6789 Expr *ThirdArg = TheCall->getArg(2);
6790 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6791 return true;
6792 TheCall->setArg(2, ThirdArg);
6793 }
6794
6795 return false;
6796}
6797
6798bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6799 unsigned BuiltinID =
6800 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6801 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6802
6803 unsigned NumArgs = TheCall->getNumArgs();
6804 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6805 if (NumArgs < NumRequiredArgs) {
6806 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6807 << 0 /* function call */ << NumRequiredArgs << NumArgs
6808 << /*is non object*/ 0 << TheCall->getSourceRange();
6809 }
6810 if (NumArgs >= NumRequiredArgs + 0x100) {
6811 return Diag(TheCall->getEndLoc(),
6812 diag::err_typecheck_call_too_many_args_at_most)
6813 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6814 << /*is non object*/ 0 << TheCall->getSourceRange();
6815 }
6816 unsigned i = 0;
6817
6818 // For formatting call, check buffer arg.
6819 if (!IsSizeCall) {
6820 ExprResult Arg(TheCall->getArg(i));
6821 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6822 Context, Context.VoidPtrTy, false);
6823 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6824 if (Arg.isInvalid())
6825 return true;
6826 TheCall->setArg(i, Arg.get());
6827 i++;
6828 }
6829
6830 // Check string literal arg.
6831 unsigned FormatIdx = i;
6832 {
6833 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6834 if (Arg.isInvalid())
6835 return true;
6836 TheCall->setArg(i, Arg.get());
6837 i++;
6838 }
6839
6840 // Make sure variadic args are scalar.
6841 unsigned FirstDataArg = i;
6842 while (i < NumArgs) {
6844 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6845 if (Arg.isInvalid())
6846 return true;
6847 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6848 if (ArgSize.getQuantity() >= 0x100) {
6849 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6850 << i << (int)ArgSize.getQuantity() << 0xff
6851 << TheCall->getSourceRange();
6852 }
6853 TheCall->setArg(i, Arg.get());
6854 i++;
6855 }
6856
6857 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6858 // call to avoid duplicate diagnostics.
6859 if (!IsSizeCall) {
6860 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6861 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6862 bool Success = CheckFormatArguments(
6863 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6865 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6866 if (!Success)
6867 return true;
6868 }
6869
6870 if (IsSizeCall) {
6871 TheCall->setType(Context.getSizeType());
6872 } else {
6873 TheCall->setType(Context.VoidPtrTy);
6874 }
6875 return false;
6876}
6877
6878bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6879 llvm::APSInt &Result) {
6880 Expr *Arg = TheCall->getArg(ArgNum);
6881
6882 if (Arg->isTypeDependent() || Arg->isValueDependent())
6883 return false;
6884
6885 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6886 if (!R) {
6887 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6888 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6889 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6890 << FDecl->getDeclName() << Arg->getSourceRange();
6891 }
6892 Result = *R;
6893
6894 return false;
6895}
6896
6897bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6898 int High, bool RangeIsError) {
6900 return false;
6901 llvm::APSInt Result;
6902
6903 // We can't check the value of a dependent argument.
6904 Expr *Arg = TheCall->getArg(ArgNum);
6905 if (Arg->isTypeDependent() || Arg->isValueDependent())
6906 return false;
6907
6908 // Check constant-ness first.
6909 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6910 return true;
6911
6912 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6913 if (RangeIsError)
6914 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6915 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6916 else
6917 // Defer the warning until we know if the code will be emitted so that
6918 // dead code can ignore this.
6919 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6920 PDiag(diag::warn_argument_invalid_range)
6921 << toString(Result, 10) << Low << High
6922 << Arg->getSourceRange());
6923 }
6924
6925 return false;
6926}
6927
6928bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6929 unsigned Num) {
6930 llvm::APSInt Result;
6931
6932 // We can't check the value of a dependent argument.
6933 Expr *Arg = TheCall->getArg(ArgNum);
6934 if (Arg->isTypeDependent() || Arg->isValueDependent())
6935 return false;
6936
6937 // Check constant-ness first.
6938 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6939 return true;
6940
6941 if (Result.getSExtValue() % Num != 0)
6942 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6943 << Num << Arg->getSourceRange();
6944
6945 return false;
6946}
6947
6948bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6949 llvm::APSInt Result;
6950
6951 // We can't check the value of a dependent argument.
6952 Expr *Arg = TheCall->getArg(ArgNum);
6953 if (Arg->isTypeDependent() || Arg->isValueDependent())
6954 return false;
6955
6956 // Check constant-ness first.
6957 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6958 return true;
6959
6960 if (Result.isPowerOf2())
6961 return false;
6962
6963 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6964 << Arg->getSourceRange();
6965}
6966
6967static bool IsShiftedByte(llvm::APSInt Value) {
6968 if (Value.isNegative())
6969 return false;
6970
6971 // Check if it's a shifted byte, by shifting it down
6972 while (true) {
6973 // If the value fits in the bottom byte, the check passes.
6974 if (Value < 0x100)
6975 return true;
6976
6977 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6978 // fails.
6979 if ((Value & 0xFF) != 0)
6980 return false;
6981
6982 // If the bottom 8 bits are all 0, but something above that is nonzero,
6983 // then shifting the value right by 8 bits won't affect whether it's a
6984 // shifted byte or not. So do that, and go round again.
6985 Value >>= 8;
6986 }
6987}
6988
6989bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6990 unsigned ArgBits) {
6991 llvm::APSInt Result;
6992
6993 // We can't check the value of a dependent argument.
6994 Expr *Arg = TheCall->getArg(ArgNum);
6995 if (Arg->isTypeDependent() || Arg->isValueDependent())
6996 return false;
6997
6998 // Check constant-ness first.
6999 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7000 return true;
7001
7002 // Truncate to the given size.
7003 Result = Result.getLoBits(ArgBits);
7004 Result.setIsUnsigned(true);
7005
7006 if (IsShiftedByte(Result))
7007 return false;
7008
7009 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7010 << Arg->getSourceRange();
7011}
7012
7014 unsigned ArgNum,
7015 unsigned ArgBits) {
7016 llvm::APSInt Result;
7017
7018 // We can't check the value of a dependent argument.
7019 Expr *Arg = TheCall->getArg(ArgNum);
7020 if (Arg->isTypeDependent() || Arg->isValueDependent())
7021 return false;
7022
7023 // Check constant-ness first.
7024 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7025 return true;
7026
7027 // Truncate to the given size.
7028 Result = Result.getLoBits(ArgBits);
7029 Result.setIsUnsigned(true);
7030
7031 // Check to see if it's in either of the required forms.
7032 if (IsShiftedByte(Result) ||
7033 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7034 return false;
7035
7036 return Diag(TheCall->getBeginLoc(),
7037 diag::err_argument_not_shifted_byte_or_xxff)
7038 << Arg->getSourceRange();
7039}
7040
7041bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7042 if (!Context.getTargetInfo().hasSjLjLowering())
7043 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7044 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7045
7046 Expr *Arg = TheCall->getArg(1);
7047 llvm::APSInt Result;
7048
7049 // TODO: This is less than ideal. Overload this to take a value.
7050 if (BuiltinConstantArg(TheCall, 1, Result))
7051 return true;
7052
7053 if (Result != 1)
7054 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7055 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7056
7057 return false;
7058}
7059
7060bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7061 if (!Context.getTargetInfo().hasSjLjLowering())
7062 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7063 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7064 return false;
7065}
7066
7067bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7068 if (checkArgCount(TheCall, 1))
7069 return true;
7070
7071 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
7072 if (ArgRes.isInvalid())
7073 return true;
7074
7075 // For simplicity, we support only limited expressions for the argument.
7076 // Specifically a flexible array member or a pointer with counted_by:
7077 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7078 // complex casting, which really shouldn't be a huge problem.
7079 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7080 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7081 return Diag(Arg->getBeginLoc(),
7082 diag::err_builtin_counted_by_ref_invalid_arg)
7083 << Arg->getSourceRange();
7084
7085 if (Arg->HasSideEffects(Context))
7086 return Diag(Arg->getBeginLoc(),
7087 diag::err_builtin_counted_by_ref_has_side_effects)
7088 << Arg->getSourceRange();
7089
7090 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7091 const auto *CATy =
7092 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7093
7094 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7095 // Member has counted_by attribute - return pointer to count field
7096 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
7097 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7098 TheCall->setType(Context.getPointerType(CountFD->getType()));
7099 return false;
7100 }
7101 }
7102
7103 // FAMs and pointers without counted_by return void*
7104 QualType MemberTy = ME->getMemberDecl()->getType();
7105 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7106 return Diag(Arg->getBeginLoc(),
7107 diag::err_builtin_counted_by_ref_invalid_arg)
7108 << Arg->getSourceRange();
7109 } else {
7110 return Diag(Arg->getBeginLoc(),
7111 diag::err_builtin_counted_by_ref_invalid_arg)
7112 << Arg->getSourceRange();
7113 }
7114
7115 TheCall->setType(Context.getPointerType(Context.VoidTy));
7116 return false;
7117}
7118
7119/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7120/// It allows leaking and modification of bounds safety information.
7121bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7123 const CallExpr *CE =
7124 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7125 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7126 return false;
7127
7128 switch (K) {
7131 Diag(E->getExprLoc(),
7132 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7133 << 0 << E->getSourceRange();
7134 break;
7136 Diag(E->getExprLoc(),
7137 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7138 << 1 << E->getSourceRange();
7139 break;
7141 Diag(E->getExprLoc(),
7142 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7143 << 2 << E->getSourceRange();
7144 break;
7146 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7147 << 0 << E->getSourceRange();
7148 break;
7150 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7151 << 1 << E->getSourceRange();
7152 break;
7153 }
7154
7155 return true;
7156}
7157
7158namespace {
7159
7160class UncoveredArgHandler {
7161 enum { Unknown = -1, AllCovered = -2 };
7162
7163 signed FirstUncoveredArg = Unknown;
7164 SmallVector<const Expr *, 4> DiagnosticExprs;
7165
7166public:
7167 UncoveredArgHandler() = default;
7168
7169 bool hasUncoveredArg() const {
7170 return (FirstUncoveredArg >= 0);
7171 }
7172
7173 unsigned getUncoveredArg() const {
7174 assert(hasUncoveredArg() && "no uncovered argument");
7175 return FirstUncoveredArg;
7176 }
7177
7178 void setAllCovered() {
7179 // A string has been found with all arguments covered, so clear out
7180 // the diagnostics.
7181 DiagnosticExprs.clear();
7182 FirstUncoveredArg = AllCovered;
7183 }
7184
7185 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7186 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7187
7188 // Don't update if a previous string covers all arguments.
7189 if (FirstUncoveredArg == AllCovered)
7190 return;
7191
7192 // UncoveredArgHandler tracks the highest uncovered argument index
7193 // and with it all the strings that match this index.
7194 if (NewFirstUncoveredArg == FirstUncoveredArg)
7195 DiagnosticExprs.push_back(StrExpr);
7196 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7197 DiagnosticExprs.clear();
7198 DiagnosticExprs.push_back(StrExpr);
7199 FirstUncoveredArg = NewFirstUncoveredArg;
7200 }
7201 }
7202
7203 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7204};
7205
7206enum StringLiteralCheckType {
7207 SLCT_NotALiteral,
7208 SLCT_UncheckedLiteral,
7209 SLCT_CheckedLiteral
7210};
7211
7212} // namespace
7213
7214static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7215 BinaryOperatorKind BinOpKind,
7216 bool AddendIsRight) {
7217 unsigned BitWidth = Offset.getBitWidth();
7218 unsigned AddendBitWidth = Addend.getBitWidth();
7219 // There might be negative interim results.
7220 if (Addend.isUnsigned()) {
7221 Addend = Addend.zext(++AddendBitWidth);
7222 Addend.setIsSigned(true);
7223 }
7224 // Adjust the bit width of the APSInts.
7225 if (AddendBitWidth > BitWidth) {
7226 Offset = Offset.sext(AddendBitWidth);
7227 BitWidth = AddendBitWidth;
7228 } else if (BitWidth > AddendBitWidth) {
7229 Addend = Addend.sext(BitWidth);
7230 }
7231
7232 bool Ov = false;
7233 llvm::APSInt ResOffset = Offset;
7234 if (BinOpKind == BO_Add)
7235 ResOffset = Offset.sadd_ov(Addend, Ov);
7236 else {
7237 assert(AddendIsRight && BinOpKind == BO_Sub &&
7238 "operator must be add or sub with addend on the right");
7239 ResOffset = Offset.ssub_ov(Addend, Ov);
7240 }
7241
7242 // We add an offset to a pointer here so we should support an offset as big as
7243 // possible.
7244 if (Ov) {
7245 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7246 "index (intermediate) result too big");
7247 Offset = Offset.sext(2 * BitWidth);
7248 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7249 return;
7250 }
7251
7252 Offset = std::move(ResOffset);
7253}
7254
7255namespace {
7256
7257// This is a wrapper class around StringLiteral to support offsetted string
7258// literals as format strings. It takes the offset into account when returning
7259// the string and its length or the source locations to display notes correctly.
7260class FormatStringLiteral {
7261 const StringLiteral *FExpr;
7262 int64_t Offset;
7263
7264public:
7265 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7266 : FExpr(fexpr), Offset(Offset) {}
7267
7268 const StringLiteral *getFormatString() const { return FExpr; }
7269
7270 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7271
7272 unsigned getByteLength() const {
7273 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7274 }
7275
7276 unsigned getLength() const { return FExpr->getLength() - Offset; }
7277 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7278
7279 StringLiteralKind getKind() const { return FExpr->getKind(); }
7280
7281 QualType getType() const { return FExpr->getType(); }
7282
7283 bool isAscii() const { return FExpr->isOrdinary(); }
7284 bool isWide() const { return FExpr->isWide(); }
7285 bool isUTF8() const { return FExpr->isUTF8(); }
7286 bool isUTF16() const { return FExpr->isUTF16(); }
7287 bool isUTF32() const { return FExpr->isUTF32(); }
7288 bool isPascal() const { return FExpr->isPascal(); }
7289
7290 SourceLocation getLocationOfByte(
7291 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7292 const TargetInfo &Target, unsigned *StartToken = nullptr,
7293 unsigned *StartTokenByteOffset = nullptr) const {
7294 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7295 StartToken, StartTokenByteOffset);
7296 }
7297
7298 SourceLocation getBeginLoc() const LLVM_READONLY {
7299 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7300 }
7301
7302 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7303};
7304
7305} // namespace
7306
7307static void CheckFormatString(
7308 Sema &S, const FormatStringLiteral *FExpr,
7309 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7311 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7312 bool inFunctionCall, VariadicCallType CallType,
7313 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7314 bool IgnoreStringsWithoutSpecifiers);
7315
7316static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7317 const Expr *E);
7318
7319// Determine if an expression is a string literal or constant string.
7320// If this function returns false on the arguments to a function expecting a
7321// format string, we will usually need to emit a warning.
7322// True string literals are then checked by CheckFormatString.
7323static StringLiteralCheckType
7324checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7325 const Expr *E, ArrayRef<const Expr *> Args,
7326 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7327 unsigned firstDataArg, FormatStringType Type,
7328 VariadicCallType CallType, bool InFunctionCall,
7329 llvm::SmallBitVector &CheckedVarArgs,
7330 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7331 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7332 bool IgnoreStringsWithoutSpecifiers = false) {
7334 return SLCT_NotALiteral;
7335tryAgain:
7336 assert(Offset.isSigned() && "invalid offset");
7337
7338 if (E->isTypeDependent() || E->isValueDependent())
7339 return SLCT_NotALiteral;
7340
7341 E = E->IgnoreParenCasts();
7342
7344 // Technically -Wformat-nonliteral does not warn about this case.
7345 // The behavior of printf and friends in this case is implementation
7346 // dependent. Ideally if the format string cannot be null then
7347 // it should have a 'nonnull' attribute in the function prototype.
7348 return SLCT_UncheckedLiteral;
7349
7350 switch (E->getStmtClass()) {
7351 case Stmt::InitListExprClass:
7352 // Handle expressions like {"foobar"}.
7353 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7354 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7355 format_idx, firstDataArg, Type, CallType,
7356 /*InFunctionCall*/ false, CheckedVarArgs,
7357 UncoveredArg, Offset, CallerFormatParamIdx,
7358 IgnoreStringsWithoutSpecifiers);
7359 }
7360 return SLCT_NotALiteral;
7361 case Stmt::BinaryConditionalOperatorClass:
7362 case Stmt::ConditionalOperatorClass: {
7363 // The expression is a literal if both sub-expressions were, and it was
7364 // completely checked only if both sub-expressions were checked.
7367
7368 // Determine whether it is necessary to check both sub-expressions, for
7369 // example, because the condition expression is a constant that can be
7370 // evaluated at compile time.
7371 bool CheckLeft = true, CheckRight = true;
7372
7373 bool Cond;
7374 if (C->getCond()->EvaluateAsBooleanCondition(
7376 if (Cond)
7377 CheckRight = false;
7378 else
7379 CheckLeft = false;
7380 }
7381
7382 // We need to maintain the offsets for the right and the left hand side
7383 // separately to check if every possible indexed expression is a valid
7384 // string literal. They might have different offsets for different string
7385 // literals in the end.
7386 StringLiteralCheckType Left;
7387 if (!CheckLeft)
7388 Left = SLCT_UncheckedLiteral;
7389 else {
7390 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7391 Args, APK, format_idx, firstDataArg, Type,
7392 CallType, InFunctionCall, CheckedVarArgs,
7393 UncoveredArg, Offset, CallerFormatParamIdx,
7394 IgnoreStringsWithoutSpecifiers);
7395 if (Left == SLCT_NotALiteral || !CheckRight) {
7396 return Left;
7397 }
7398 }
7399
7400 StringLiteralCheckType Right = checkFormatStringExpr(
7401 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7402 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7403 UncoveredArg, Offset, CallerFormatParamIdx,
7404 IgnoreStringsWithoutSpecifiers);
7405
7406 return (CheckLeft && Left < Right) ? Left : Right;
7407 }
7408
7409 case Stmt::ImplicitCastExprClass:
7410 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7411 goto tryAgain;
7412
7413 case Stmt::OpaqueValueExprClass:
7414 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7415 E = src;
7416 goto tryAgain;
7417 }
7418 return SLCT_NotALiteral;
7419
7420 case Stmt::PredefinedExprClass:
7421 // While __func__, etc., are technically not string literals, they
7422 // cannot contain format specifiers and thus are not a security
7423 // liability.
7424 return SLCT_UncheckedLiteral;
7425
7426 case Stmt::DeclRefExprClass: {
7427 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7428
7429 // As an exception, do not flag errors for variables binding to
7430 // const string literals.
7431 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7432 bool isConstant = false;
7433 QualType T = DR->getType();
7434
7435 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7436 isConstant = AT->getElementType().isConstant(S.Context);
7437 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7438 isConstant = T.isConstant(S.Context) &&
7439 PT->getPointeeType().isConstant(S.Context);
7440 } else if (T->isObjCObjectPointerType()) {
7441 // In ObjC, there is usually no "const ObjectPointer" type,
7442 // so don't check if the pointee type is constant.
7443 isConstant = T.isConstant(S.Context);
7444 }
7445
7446 if (isConstant) {
7447 if (const Expr *Init = VD->getAnyInitializer()) {
7448 // Look through initializers like const char c[] = { "foo" }
7449 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7450 if (InitList->isStringLiteralInit())
7451 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7452 }
7453 return checkFormatStringExpr(
7454 S, ReferenceFormatString, Init, Args, APK, format_idx,
7455 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7456 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7457 }
7458 }
7459
7460 // When the format argument is an argument of this function, and this
7461 // function also has the format attribute, there are several interactions
7462 // for which there shouldn't be a warning. For instance, when calling
7463 // v*printf from a function that has the printf format attribute, we
7464 // should not emit a warning about using `fmt`, even though it's not
7465 // constant, because the arguments have already been checked for the
7466 // caller of `logmessage`:
7467 //
7468 // __attribute__((format(printf, 1, 2)))
7469 // void logmessage(char const *fmt, ...) {
7470 // va_list ap;
7471 // va_start(ap, fmt);
7472 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7473 // ...
7474 // }
7475 //
7476 // Another interaction that we need to support is using a format string
7477 // specified by the format_matches attribute:
7478 //
7479 // __attribute__((format_matches(printf, 1, "%s %d")))
7480 // void logmessage(char const *fmt, const char *a, int b) {
7481 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7482 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7483 // ...
7484 // }
7485 //
7486 // Yet another interaction that we need to support is calling a variadic
7487 // format function from a format function that has fixed arguments. For
7488 // instance:
7489 //
7490 // __attribute__((format(printf, 1, 2)))
7491 // void logstring(char const *fmt, char const *str) {
7492 // printf(fmt, str); /* do not emit a warning about "fmt" */
7493 // }
7494 //
7495 // Same (and perhaps more relatably) for the variadic template case:
7496 //
7497 // template<typename... Args>
7498 // __attribute__((format(printf, 1, 2)))
7499 // void log(const char *fmt, Args&&... args) {
7500 // printf(fmt, forward<Args>(args)...);
7501 // /* do not emit a warning about "fmt" */
7502 // }
7503 //
7504 // Due to implementation difficulty, we only check the format, not the
7505 // format arguments, in all cases.
7506 //
7507 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7508 if (CallerFormatParamIdx)
7509 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7510 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7511 for (const auto *PVFormatMatches :
7512 D->specific_attrs<FormatMatchesAttr>()) {
7513 Sema::FormatStringInfo CalleeFSI;
7514 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7515 0, &CalleeFSI))
7516 continue;
7517 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7518 // If using the wrong type of format string, emit a diagnostic
7519 // here and stop checking to avoid irrelevant diagnostics.
7520 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7521 S.Diag(Args[format_idx]->getBeginLoc(),
7522 diag::warn_format_string_type_incompatible)
7523 << PVFormatMatches->getType()->getName()
7525 if (!InFunctionCall) {
7526 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7527 diag::note_format_string_defined);
7528 }
7529 return SLCT_UncheckedLiteral;
7530 }
7531 return checkFormatStringExpr(
7532 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7533 Args, APK, format_idx, firstDataArg, Type, CallType,
7534 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7535 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7536 }
7537 }
7538
7539 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7540 Sema::FormatStringInfo CallerFSI;
7541 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7542 PVFormat->getFirstArg(), &CallerFSI))
7543 continue;
7544 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7545 // We also check if the formats are compatible.
7546 // We can't pass a 'scanf' string to a 'printf' function.
7547 if (Type != S.GetFormatStringType(PVFormat)) {
7548 S.Diag(Args[format_idx]->getBeginLoc(),
7549 diag::warn_format_string_type_incompatible)
7550 << PVFormat->getType()->getName()
7552 if (!InFunctionCall) {
7553 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7554 }
7555 return SLCT_UncheckedLiteral;
7556 }
7557 // Lastly, check that argument passing kinds transition in a
7558 // way that makes sense:
7559 // from a caller with FAPK_VAList, allow FAPK_VAList
7560 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7561 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7562 // from a caller with FAPK_Variadic, allow FAPK_VAList
7563 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7568 return SLCT_UncheckedLiteral;
7569 }
7570 }
7571 }
7572 }
7573 }
7574 }
7575
7576 return SLCT_NotALiteral;
7577 }
7578
7579 case Stmt::CallExprClass:
7580 case Stmt::CXXMemberCallExprClass: {
7581 const CallExpr *CE = cast<CallExpr>(E);
7582 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7583 bool IsFirst = true;
7584 StringLiteralCheckType CommonResult;
7585 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7586 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7587 StringLiteralCheckType Result = checkFormatStringExpr(
7588 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7589 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7590 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7591 if (IsFirst) {
7592 CommonResult = Result;
7593 IsFirst = false;
7594 }
7595 }
7596 if (!IsFirst)
7597 return CommonResult;
7598
7599 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7600 unsigned BuiltinID = FD->getBuiltinID();
7601 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7602 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7603 const Expr *Arg = CE->getArg(0);
7604 return checkFormatStringExpr(
7605 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7606 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7607 UncoveredArg, Offset, CallerFormatParamIdx,
7608 IgnoreStringsWithoutSpecifiers);
7609 }
7610 }
7611 }
7612 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7613 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7614 format_idx, firstDataArg, Type, CallType,
7615 /*InFunctionCall*/ false, CheckedVarArgs,
7616 UncoveredArg, Offset, CallerFormatParamIdx,
7617 IgnoreStringsWithoutSpecifiers);
7618 return SLCT_NotALiteral;
7619 }
7620 case Stmt::ObjCMessageExprClass: {
7621 const auto *ME = cast<ObjCMessageExpr>(E);
7622 if (const auto *MD = ME->getMethodDecl()) {
7623 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7624 // As a special case heuristic, if we're using the method -[NSBundle
7625 // localizedStringForKey:value:table:], ignore any key strings that lack
7626 // format specifiers. The idea is that if the key doesn't have any
7627 // format specifiers then its probably just a key to map to the
7628 // localized strings. If it does have format specifiers though, then its
7629 // likely that the text of the key is the format string in the
7630 // programmer's language, and should be checked.
7631 const ObjCInterfaceDecl *IFace;
7632 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7633 IFace->getIdentifier()->isStr("NSBundle") &&
7634 MD->getSelector().isKeywordSelector(
7635 {"localizedStringForKey", "value", "table"})) {
7636 IgnoreStringsWithoutSpecifiers = true;
7637 }
7638
7639 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7640 return checkFormatStringExpr(
7641 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7642 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7643 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7644 }
7645 }
7646
7647 return SLCT_NotALiteral;
7648 }
7649 case Stmt::ObjCStringLiteralClass:
7650 case Stmt::StringLiteralClass: {
7651 const StringLiteral *StrE = nullptr;
7652
7653 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7654 StrE = ObjCFExpr->getString();
7655 else
7656 StrE = cast<StringLiteral>(E);
7657
7658 if (StrE) {
7659 if (Offset.isNegative() || Offset > StrE->getLength()) {
7660 // TODO: It would be better to have an explicit warning for out of
7661 // bounds literals.
7662 return SLCT_NotALiteral;
7663 }
7664 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7665 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7666 format_idx, firstDataArg, Type, InFunctionCall,
7667 CallType, CheckedVarArgs, UncoveredArg,
7668 IgnoreStringsWithoutSpecifiers);
7669 return SLCT_CheckedLiteral;
7670 }
7671
7672 return SLCT_NotALiteral;
7673 }
7674 case Stmt::BinaryOperatorClass: {
7675 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7676
7677 // A string literal + an int offset is still a string literal.
7678 if (BinOp->isAdditiveOp()) {
7679 Expr::EvalResult LResult, RResult;
7680
7681 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7682 LResult, S.Context, Expr::SE_NoSideEffects,
7684 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7685 RResult, S.Context, Expr::SE_NoSideEffects,
7687
7688 if (LIsInt != RIsInt) {
7689 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7690
7691 if (LIsInt) {
7692 if (BinOpKind == BO_Add) {
7693 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7694 E = BinOp->getRHS();
7695 goto tryAgain;
7696 }
7697 } else {
7698 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7699 E = BinOp->getLHS();
7700 goto tryAgain;
7701 }
7702 }
7703 }
7704
7705 return SLCT_NotALiteral;
7706 }
7707 case Stmt::UnaryOperatorClass: {
7708 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7709 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7710 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7711 Expr::EvalResult IndexResult;
7712 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7715 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7716 /*RHS is int*/ true);
7717 E = ASE->getBase();
7718 goto tryAgain;
7719 }
7720 }
7721
7722 return SLCT_NotALiteral;
7723 }
7724
7725 default:
7726 return SLCT_NotALiteral;
7727 }
7728}
7729
7730// If this expression can be evaluated at compile-time,
7731// check if the result is a StringLiteral and return it
7732// otherwise return nullptr
7734 const Expr *E) {
7736 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7737 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7738 if (isa_and_nonnull<StringLiteral>(LVE))
7739 return LVE;
7740 }
7741 return nullptr;
7742}
7743
7745 switch (FST) {
7747 return "scanf";
7749 return "printf";
7751 return "NSString";
7753 return "strftime";
7755 return "strfmon";
7757 return "kprintf";
7759 return "freebsd_kprintf";
7761 return "os_log";
7762 default:
7763 return "<unknown>";
7764 }
7765}
7766
7768 return llvm::StringSwitch<FormatStringType>(Flavor)
7769 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7770 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7772 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7773 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7774 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7775 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7777 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7778 .Case("os_trace", FormatStringType::OSLog)
7779 .Case("os_log", FormatStringType::OSLog)
7780 .Default(FormatStringType::Unknown);
7781}
7782
7784 return GetFormatStringType(Format->getType()->getName());
7785}
7786
7787FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7788 return GetFormatStringType(Format->getType()->getName());
7789}
7790
7791bool Sema::CheckFormatArguments(const FormatAttr *Format,
7792 ArrayRef<const Expr *> Args, bool IsCXXMember,
7793 VariadicCallType CallType, SourceLocation Loc,
7794 SourceRange Range,
7795 llvm::SmallBitVector &CheckedVarArgs) {
7796 FormatStringInfo FSI;
7797 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7798 IsCXXMember,
7799 CallType != VariadicCallType::DoesNotApply, &FSI))
7800 return CheckFormatArguments(
7801 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7802 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7803 return false;
7804}
7805
7806bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7807 ArrayRef<const Expr *> Args, bool IsCXXMember,
7808 VariadicCallType CallType, SourceLocation Loc,
7809 SourceRange Range,
7810 llvm::SmallBitVector &CheckedVarArgs) {
7811 FormatStringInfo FSI;
7812 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7813 &FSI)) {
7814 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7815 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7816 Format->getFormatString(), FSI.FormatIdx,
7817 FSI.FirstDataArg, GetFormatStringType(Format),
7818 CallType, Loc, Range, CheckedVarArgs);
7819 }
7820 return false;
7821}
7822
7825 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7826 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7827 SourceLocation Loc) {
7828 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7829 return false;
7830
7831 DeclContext *DC = S->CurContext;
7832 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7833 return false;
7834 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7835
7836 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7837
7838 // Find the offset to convert between attribute and parameter indexes.
7839 unsigned CallerArgumentIndexOffset =
7840 hasImplicitObjectParameter(Caller) ? 2 : 1;
7841
7842 unsigned FirstArgumentIndex = -1;
7843 switch (APK) {
7846 // As an extension, clang allows the format attribute on non-variadic
7847 // functions.
7848 // Caller must have fixed arguments to pass them to a fixed or variadic
7849 // function. Try to match caller and callee arguments. If successful, then
7850 // emit a diag with the caller idx, otherwise we can't determine the callee
7851 // arguments.
7852 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7853 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7854 // There aren't enough arguments in the caller to pass to callee.
7855 return false;
7856 }
7857 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7858 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7859 const auto *Arg =
7860 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7861 if (!Arg)
7862 return false;
7863 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7864 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7865 return false;
7866 }
7867 FirstArgumentIndex =
7868 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7869 break;
7870 }
7872 // Caller arguments are either variadic or a va_list.
7873 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7874 ? (NumCallerParams + CallerArgumentIndexOffset)
7875 : 0;
7876 break;
7878 // The callee has a format_matches attribute. We will emit that instead.
7879 if (!ReferenceFormatString)
7880 return false;
7881 break;
7882 }
7883
7884 // Emit the diagnostic and fixit.
7885 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7886 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7887 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7888 do {
7889 std::string Attr, Fixit;
7890 llvm::raw_string_ostream AttrOS(Attr);
7892 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7893 << FirstArgumentIndex << ")";
7894 } else {
7895 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7896 << ", \"";
7897 AttrOS.write_escaped(ReferenceFormatString->getString());
7898 AttrOS << "\")";
7899 }
7900 AttrOS.flush();
7901 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7902 if (ND)
7903 DB << ND;
7904 else
7905 DB << "block";
7906
7907 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7908 if (isa<BlockDecl>(Caller))
7909 break;
7910
7911 SourceLocation SL;
7912 llvm::raw_string_ostream IS(Fixit);
7913 // The attribute goes at the start of the declaration in C/C++ functions
7914 // and methods, but after the declaration for Objective-C methods.
7915 if (isa<ObjCMethodDecl>(Caller)) {
7916 IS << ' ';
7917 SL = Caller->getEndLoc();
7918 }
7919 const LangOptions &LO = S->getLangOpts();
7920 if (LO.C23 || LO.CPlusPlus11)
7921 IS << "[[gnu::" << Attr << "]]";
7922 else if (LO.ObjC || LO.GNUMode)
7923 IS << "__attribute__((" << Attr << "))";
7924 else
7925 break;
7926 if (!isa<ObjCMethodDecl>(Caller)) {
7927 IS << ' ';
7928 SL = Caller->getBeginLoc();
7929 }
7930 IS.flush();
7931
7932 DB << FixItHint::CreateInsertion(SL, Fixit);
7933 } while (false);
7934
7935 // Add implicit format or format_matches attribute.
7937 Caller->addAttr(FormatAttr::CreateImplicit(
7938 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7939 FormatStringIndex, FirstArgumentIndex));
7940 } else {
7941 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7942 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7943 FormatStringIndex, ReferenceFormatString));
7944 }
7945
7946 {
7947 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7948 if (ND)
7949 DB << ND;
7950 else
7951 DB << "block";
7952 }
7953 return true;
7954}
7955
7956bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7958 StringLiteral *ReferenceFormatString,
7959 unsigned format_idx, unsigned firstDataArg,
7961 VariadicCallType CallType, SourceLocation Loc,
7962 SourceRange Range,
7963 llvm::SmallBitVector &CheckedVarArgs) {
7964 // CHECK: printf/scanf-like function is called with no format string.
7965 if (format_idx >= Args.size()) {
7966 Diag(Loc, diag::warn_missing_format_string) << Range;
7967 return false;
7968 }
7969
7970 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7971
7972 // CHECK: format string is not a string literal.
7973 //
7974 // Dynamically generated format strings are difficult to
7975 // automatically vet at compile time. Requiring that format strings
7976 // are string literals: (1) permits the checking of format strings by
7977 // the compiler and thereby (2) can practically remove the source of
7978 // many format string exploits.
7979
7980 // Format string can be either ObjC string (e.g. @"%d") or
7981 // C string (e.g. "%d")
7982 // ObjC string uses the same format specifiers as C string, so we can use
7983 // the same format string checking logic for both ObjC and C strings.
7984 UncoveredArgHandler UncoveredArg;
7985 std::optional<unsigned> CallerParamIdx;
7986 StringLiteralCheckType CT = checkFormatStringExpr(
7987 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7988 firstDataArg, Type, CallType,
7989 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7990 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7991
7992 // Generate a diagnostic where an uncovered argument is detected.
7993 if (UncoveredArg.hasUncoveredArg()) {
7994 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7995 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7996 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7997 }
7998
7999 if (CT != SLCT_NotALiteral)
8000 // Literal format string found, check done!
8001 return CT == SLCT_CheckedLiteral;
8002
8003 // Do not emit diag when the string param is a macro expansion and the
8004 // format is either NSString or CFString. This is a hack to prevent
8005 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8006 // which are usually used in place of NS and CF string literals.
8007 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8009 SourceMgr.isInSystemMacro(FormatLoc))
8010 return false;
8011
8012 if (CallerParamIdx && CheckMissingFormatAttribute(
8013 this, Args, APK, ReferenceFormatString, format_idx,
8014 firstDataArg, Type, *CallerParamIdx, Loc))
8015 return false;
8016
8017 // Strftime is particular as it always uses a single 'time' argument,
8018 // so it is safe to pass a non-literal string.
8020 return false;
8021
8022 // If there are no arguments specified, warn with -Wformat-security, otherwise
8023 // warn only with -Wformat-nonliteral.
8024 if (Args.size() == firstDataArg) {
8025 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8026 << OrigFormatExpr->getSourceRange();
8027 switch (Type) {
8028 default:
8029 break;
8033 Diag(FormatLoc, diag::note_format_security_fixit)
8034 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8035 break;
8037 Diag(FormatLoc, diag::note_format_security_fixit)
8038 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8039 break;
8040 }
8041 } else {
8042 Diag(FormatLoc, diag::warn_format_nonliteral)
8043 << OrigFormatExpr->getSourceRange();
8044 }
8045 return false;
8046}
8047
8048namespace {
8049
8050class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8051protected:
8052 Sema &S;
8053 const FormatStringLiteral *FExpr;
8054 const Expr *OrigFormatExpr;
8055 const FormatStringType FSType;
8056 const unsigned FirstDataArg;
8057 const unsigned NumDataArgs;
8058 const char *Beg; // Start of format string.
8059 const Sema::FormatArgumentPassingKind ArgPassingKind;
8060 ArrayRef<const Expr *> Args;
8061 unsigned FormatIdx;
8062 llvm::SmallBitVector CoveredArgs;
8063 bool usesPositionalArgs = false;
8064 bool atFirstArg = true;
8065 bool inFunctionCall;
8066 VariadicCallType CallType;
8067 llvm::SmallBitVector &CheckedVarArgs;
8068 UncoveredArgHandler &UncoveredArg;
8069
8070public:
8071 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8072 const Expr *origFormatExpr, const FormatStringType type,
8073 unsigned firstDataArg, unsigned numDataArgs,
8074 const char *beg, Sema::FormatArgumentPassingKind APK,
8075 ArrayRef<const Expr *> Args, unsigned formatIdx,
8076 bool inFunctionCall, VariadicCallType callType,
8077 llvm::SmallBitVector &CheckedVarArgs,
8078 UncoveredArgHandler &UncoveredArg)
8079 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8080 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8081 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8082 inFunctionCall(inFunctionCall), CallType(callType),
8083 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8084 CoveredArgs.resize(numDataArgs);
8085 CoveredArgs.reset();
8086 }
8087
8088 bool HasFormatArguments() const {
8089 return ArgPassingKind == Sema::FAPK_Fixed ||
8090 ArgPassingKind == Sema::FAPK_Variadic;
8091 }
8092
8093 void DoneProcessing();
8094
8095 void HandleIncompleteSpecifier(const char *startSpecifier,
8096 unsigned specifierLen) override;
8097
8098 void HandleInvalidLengthModifier(
8099 const analyze_format_string::FormatSpecifier &FS,
8100 const analyze_format_string::ConversionSpecifier &CS,
8101 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8102
8103 void HandleNonStandardLengthModifier(
8104 const analyze_format_string::FormatSpecifier &FS,
8105 const char *startSpecifier, unsigned specifierLen);
8106
8107 void HandleNonStandardConversionSpecifier(
8108 const analyze_format_string::ConversionSpecifier &CS,
8109 const char *startSpecifier, unsigned specifierLen);
8110
8111 void HandlePosition(const char *startPos, unsigned posLen) override;
8112
8113 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8115
8116 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8117
8118 void HandleNullChar(const char *nullCharacter) override;
8119
8120 template <typename Range>
8121 static void
8122 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8123 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8124 bool IsStringLocation, Range StringRange,
8125 ArrayRef<FixItHint> Fixit = {});
8126
8127protected:
8128 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8129 const char *startSpec,
8130 unsigned specifierLen,
8131 const char *csStart, unsigned csLen);
8132
8133 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8134 const char *startSpec,
8135 unsigned specifierLen);
8136
8137 SourceRange getFormatStringRange();
8138 CharSourceRange getSpecifierRange(const char *startSpecifier,
8139 unsigned specifierLen);
8140 SourceLocation getLocationOfByte(const char *x);
8141
8142 const Expr *getDataArg(unsigned i) const;
8143
8144 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8145 const analyze_format_string::ConversionSpecifier &CS,
8146 const char *startSpecifier, unsigned specifierLen,
8147 unsigned argIndex);
8148
8149 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8150 const Expr *E, const char *startSpecifier,
8151 unsigned specifierLen);
8152
8153 template <typename Range>
8154 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8155 bool IsStringLocation, Range StringRange,
8156 ArrayRef<FixItHint> Fixit = {});
8157};
8158
8159} // namespace
8160
8161SourceRange CheckFormatHandler::getFormatStringRange() {
8162 return OrigFormatExpr->getSourceRange();
8163}
8164
8166CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8167 unsigned specifierLen) {
8168 SourceLocation Start = getLocationOfByte(startSpecifier);
8169 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8170
8171 // Advance the end SourceLocation by one due to half-open ranges.
8172 End = End.getLocWithOffset(1);
8173
8174 return CharSourceRange::getCharRange(Start, End);
8175}
8176
8177SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8178 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8180}
8181
8182void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8183 unsigned specifierLen) {
8184 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8185 getLocationOfByte(startSpecifier),
8186 /*IsStringLocation*/ true,
8187 getSpecifierRange(startSpecifier, specifierLen));
8188}
8189
8190bool CheckFormatHandler::CheckUnsupportedType(
8191 const analyze_format_string::ArgType &AT, const Expr *E,
8192 const char *StartSpecifier, unsigned SpecifierLen) {
8193 if (!AT.isUnsupported())
8194 return false;
8195
8196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8198 E->getExprLoc(), /*IsStringLocation=*/false,
8199 getSpecifierRange(StartSpecifier, SpecifierLen));
8200 return true;
8201}
8202
8203void CheckFormatHandler::HandleInvalidLengthModifier(
8206 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8207 using namespace analyze_format_string;
8208
8209 const LengthModifier &LM = FS.getLengthModifier();
8210 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8211
8212 // See if we know how to fix this length modifier.
8213 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8214 if (FixedLM) {
8215 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8216 getLocationOfByte(LM.getStart()),
8217 /*IsStringLocation*/ true,
8218 getSpecifierRange(startSpecifier, specifierLen));
8219
8220 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8221 << FixedLM->toString()
8222 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8223
8224 } else {
8225 FixItHint Hint;
8226 if (DiagID == diag::warn_format_nonsensical_length)
8227 Hint = FixItHint::CreateRemoval(LMRange);
8228
8229 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8230 getLocationOfByte(LM.getStart()),
8231 /*IsStringLocation*/ true,
8232 getSpecifierRange(startSpecifier, specifierLen), Hint);
8233 }
8234}
8235
8236void CheckFormatHandler::HandleNonStandardLengthModifier(
8238 const char *startSpecifier, unsigned specifierLen) {
8239 using namespace analyze_format_string;
8240
8241 const LengthModifier &LM = FS.getLengthModifier();
8242 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8243
8244 // See if we know how to fix this length modifier.
8245 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8246 if (FixedLM) {
8247 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8248 << LM.toString() << 0,
8249 getLocationOfByte(LM.getStart()),
8250 /*IsStringLocation*/ true,
8251 getSpecifierRange(startSpecifier, specifierLen));
8252
8253 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8254 << FixedLM->toString()
8255 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8256
8257 } else {
8258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8259 << LM.toString() << 0,
8260 getLocationOfByte(LM.getStart()),
8261 /*IsStringLocation*/ true,
8262 getSpecifierRange(startSpecifier, specifierLen));
8263 }
8264}
8265
8266void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8268 const char *startSpecifier, unsigned specifierLen) {
8269 using namespace analyze_format_string;
8270
8271 // See if we know how to fix this conversion specifier.
8272 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8273 if (FixedCS) {
8274 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8275 << CS.toString() << /*conversion specifier*/ 1,
8276 getLocationOfByte(CS.getStart()),
8277 /*IsStringLocation*/ true,
8278 getSpecifierRange(startSpecifier, specifierLen));
8279
8280 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8281 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8282 << FixedCS->toString()
8283 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8284 } else {
8285 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8286 << CS.toString() << /*conversion specifier*/ 1,
8287 getLocationOfByte(CS.getStart()),
8288 /*IsStringLocation*/ true,
8289 getSpecifierRange(startSpecifier, specifierLen));
8290 }
8291}
8292
8293void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8294 if (!S.getDiagnostics().isIgnored(
8295 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8296 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8297 getLocationOfByte(startPos),
8298 /*IsStringLocation*/ true,
8299 getSpecifierRange(startPos, posLen));
8300}
8301
8302void CheckFormatHandler::HandleInvalidPosition(
8303 const char *startSpecifier, unsigned specifierLen,
8305 if (!S.getDiagnostics().isIgnored(
8306 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8307 EmitFormatDiagnostic(
8308 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8309 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8310 getSpecifierRange(startSpecifier, specifierLen));
8311}
8312
8313void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8314 unsigned posLen) {
8315 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8316 SourceLocation()))
8317 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8318 getLocationOfByte(startPos),
8319 /*IsStringLocation*/ true,
8320 getSpecifierRange(startPos, posLen));
8321}
8322
8323void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8324 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8325 // The presence of a null character is likely an error.
8326 EmitFormatDiagnostic(
8327 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8328 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8329 getFormatStringRange());
8330 }
8331}
8332
8333// Note that this may return NULL if there was an error parsing or building
8334// one of the argument expressions.
8335const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8336 return Args[FirstDataArg + i];
8337}
8338
8339void CheckFormatHandler::DoneProcessing() {
8340 // Does the number of data arguments exceed the number of
8341 // format conversions in the format string?
8342 if (HasFormatArguments()) {
8343 // Find any arguments that weren't covered.
8344 CoveredArgs.flip();
8345 signed notCoveredArg = CoveredArgs.find_first();
8346 if (notCoveredArg >= 0) {
8347 assert((unsigned)notCoveredArg < NumDataArgs);
8348 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8349 } else {
8350 UncoveredArg.setAllCovered();
8351 }
8352 }
8353}
8354
8355void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8356 const Expr *ArgExpr) {
8357 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8358
8359 if (!ArgExpr)
8360 return;
8361
8362 SourceLocation Loc = ArgExpr->getBeginLoc();
8363
8364 if (S.getSourceManager().isInSystemMacro(Loc))
8365 return;
8366
8367 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8368 for (auto E : DiagnosticExprs)
8369 PDiag << E->getSourceRange();
8370
8371 CheckFormatHandler::EmitFormatDiagnostic(
8372 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8373 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8374}
8375
8376bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8377 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8378 unsigned specifierLen, const char *csStart, unsigned csLen) {
8379 bool keepGoing = true;
8380 if (argIndex < NumDataArgs) {
8381 // Consider the argument coverered, even though the specifier doesn't
8382 // make sense.
8383 CoveredArgs.set(argIndex);
8384 } else {
8385 // If argIndex exceeds the number of data arguments we
8386 // don't issue a warning because that is just a cascade of warnings (and
8387 // they may have intended '%%' anyway). We don't want to continue processing
8388 // the format string after this point, however, as we will like just get
8389 // gibberish when trying to match arguments.
8390 keepGoing = false;
8391 }
8392
8393 StringRef Specifier(csStart, csLen);
8394
8395 // If the specifier in non-printable, it could be the first byte of a UTF-8
8396 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8397 // hex value.
8398 std::string CodePointStr;
8399 if (!llvm::sys::locale::isPrint(*csStart)) {
8400 llvm::UTF32 CodePoint;
8401 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8402 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8403 llvm::ConversionResult Result =
8404 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8405
8406 if (Result != llvm::conversionOK) {
8407 unsigned char FirstChar = *csStart;
8408 CodePoint = (llvm::UTF32)FirstChar;
8409 }
8410
8411 llvm::raw_string_ostream OS(CodePointStr);
8412 if (CodePoint < 256)
8413 OS << "\\x" << llvm::format("%02x", CodePoint);
8414 else if (CodePoint <= 0xFFFF)
8415 OS << "\\u" << llvm::format("%04x", CodePoint);
8416 else
8417 OS << "\\U" << llvm::format("%08x", CodePoint);
8418 Specifier = CodePointStr;
8419 }
8420
8421 EmitFormatDiagnostic(
8422 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8423 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8424
8425 return keepGoing;
8426}
8427
8428void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8429 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8430 EmitFormatDiagnostic(
8431 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8432 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8433}
8434
8435bool CheckFormatHandler::CheckNumArgs(
8438 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8439
8440 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8441 PartialDiagnostic PDiag =
8443 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8444 << (argIndex + 1) << NumDataArgs)
8445 : S.PDiag(diag::warn_printf_insufficient_data_args);
8446 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8447 /*IsStringLocation*/ true,
8448 getSpecifierRange(startSpecifier, specifierLen));
8449
8450 // Since more arguments than conversion tokens are given, by extension
8451 // all arguments are covered, so mark this as so.
8452 UncoveredArg.setAllCovered();
8453 return false;
8454 }
8455 return true;
8456}
8457
8458template <typename Range>
8459void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8460 SourceLocation Loc,
8461 bool IsStringLocation,
8462 Range StringRange,
8463 ArrayRef<FixItHint> FixIt) {
8464 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8465 IsStringLocation, StringRange, FixIt);
8466}
8467
8468/// If the format string is not within the function call, emit a note
8469/// so that the function call and string are in diagnostic messages.
8470///
8471/// \param InFunctionCall if true, the format string is within the function
8472/// call and only one diagnostic message will be produced. Otherwise, an
8473/// extra note will be emitted pointing to location of the format string.
8474///
8475/// \param ArgumentExpr the expression that is passed as the format string
8476/// argument in the function call. Used for getting locations when two
8477/// diagnostics are emitted.
8478///
8479/// \param PDiag the callee should already have provided any strings for the
8480/// diagnostic message. This function only adds locations and fixits
8481/// to diagnostics.
8482///
8483/// \param Loc primary location for diagnostic. If two diagnostics are
8484/// required, one will be at Loc and a new SourceLocation will be created for
8485/// the other one.
8486///
8487/// \param IsStringLocation if true, Loc points to the format string should be
8488/// used for the note. Otherwise, Loc points to the argument list and will
8489/// be used with PDiag.
8490///
8491/// \param StringRange some or all of the string to highlight. This is
8492/// templated so it can accept either a CharSourceRange or a SourceRange.
8493///
8494/// \param FixIt optional fix it hint for the format string.
8495template <typename Range>
8496void CheckFormatHandler::EmitFormatDiagnostic(
8497 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8498 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8499 Range StringRange, ArrayRef<FixItHint> FixIt) {
8500 if (InFunctionCall) {
8501 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8502 D << StringRange;
8503 D << FixIt;
8504 } else {
8505 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8506 << ArgumentExpr->getSourceRange();
8507
8509 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8510 diag::note_format_string_defined);
8511
8512 Note << StringRange;
8513 Note << FixIt;
8514 }
8515}
8516
8517//===--- CHECK: Printf format string checking -----------------------------===//
8518
8519namespace {
8520
8521class CheckPrintfHandler : public CheckFormatHandler {
8522public:
8523 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8524 const Expr *origFormatExpr, const FormatStringType type,
8525 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8526 const char *beg, Sema::FormatArgumentPassingKind APK,
8527 ArrayRef<const Expr *> Args, unsigned formatIdx,
8528 bool inFunctionCall, VariadicCallType CallType,
8529 llvm::SmallBitVector &CheckedVarArgs,
8530 UncoveredArgHandler &UncoveredArg)
8531 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8532 numDataArgs, beg, APK, Args, formatIdx,
8533 inFunctionCall, CallType, CheckedVarArgs,
8534 UncoveredArg) {}
8535
8536 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8537
8538 /// Returns true if '%@' specifiers are allowed in the format string.
8539 bool allowsObjCArg() const {
8540 return FSType == FormatStringType::NSString ||
8541 FSType == FormatStringType::OSLog ||
8542 FSType == FormatStringType::OSTrace;
8543 }
8544
8545 bool HandleInvalidPrintfConversionSpecifier(
8546 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8547 unsigned specifierLen) override;
8548
8549 void handleInvalidMaskType(StringRef MaskType) override;
8550
8551 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8552 const char *startSpecifier, unsigned specifierLen,
8553 const TargetInfo &Target) override;
8554 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8555 const char *StartSpecifier, unsigned SpecifierLen,
8556 const Expr *E);
8557
8558 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8559 unsigned k, const char *startSpecifier,
8560 unsigned specifierLen);
8561 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8562 const analyze_printf::OptionalAmount &Amt,
8563 unsigned type, const char *startSpecifier,
8564 unsigned specifierLen);
8565 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8566 const analyze_printf::OptionalFlag &flag,
8567 const char *startSpecifier, unsigned specifierLen);
8568 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8569 const analyze_printf::OptionalFlag &ignoredFlag,
8570 const analyze_printf::OptionalFlag &flag,
8571 const char *startSpecifier, unsigned specifierLen);
8572 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8573
8574 void HandleEmptyObjCModifierFlag(const char *startFlag,
8575 unsigned flagLen) override;
8576
8577 void HandleInvalidObjCModifierFlag(const char *startFlag,
8578 unsigned flagLen) override;
8579
8580 void
8581 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8582 const char *flagsEnd,
8583 const char *conversionPosition) override;
8584};
8585
8586/// Keeps around the information needed to verify that two specifiers are
8587/// compatible.
8588class EquatableFormatArgument {
8589public:
8590 enum SpecifierSensitivity : unsigned {
8591 SS_None,
8592 SS_Private,
8593 SS_Public,
8594 SS_Sensitive
8595 };
8596
8597 enum FormatArgumentRole : unsigned {
8598 FAR_Data,
8599 FAR_FieldWidth,
8600 FAR_Precision,
8601 FAR_Auxiliary, // FreeBSD kernel %b and %D
8602 };
8603
8604private:
8605 analyze_format_string::ArgType ArgType;
8606 analyze_format_string::LengthModifier LengthMod;
8607 StringRef SpecifierLetter;
8608 CharSourceRange Range;
8609 SourceLocation ElementLoc;
8610 FormatArgumentRole Role : 2;
8611 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8612 unsigned Position : 14;
8613 unsigned ModifierFor : 14; // not set for FAR_Data
8614
8615 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8616 bool InFunctionCall) const;
8617
8618public:
8619 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8620 analyze_format_string::LengthModifier LengthMod,
8621 StringRef SpecifierLetter,
8622 analyze_format_string::ArgType ArgType,
8623 FormatArgumentRole Role,
8624 SpecifierSensitivity Sensitivity, unsigned Position,
8625 unsigned ModifierFor)
8626 : ArgType(ArgType), LengthMod(LengthMod),
8627 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8628 Role(Role), Sensitivity(Sensitivity), Position(Position),
8629 ModifierFor(ModifierFor) {}
8630
8631 unsigned getPosition() const { return Position; }
8632 SourceLocation getSourceLocation() const { return ElementLoc; }
8633 CharSourceRange getSourceRange() const { return Range; }
8634 analyze_format_string::LengthModifier getLengthModifier() const {
8635 return LengthMod;
8636 }
8637 void setModifierFor(unsigned V) { ModifierFor = V; }
8638
8639 std::string buildFormatSpecifier() const {
8640 std::string result;
8641 llvm::raw_string_ostream(result)
8642 << getLengthModifier().toString() << SpecifierLetter;
8643 return result;
8644 }
8645
8646 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8647 const Expr *FmtExpr, bool InFunctionCall) const;
8648};
8649
8650/// Turns format strings into lists of EquatableSpecifier objects.
8651class DecomposePrintfHandler : public CheckPrintfHandler {
8652 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8653 bool HadError;
8654
8655 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8656 const Expr *origFormatExpr,
8657 const FormatStringType type, unsigned firstDataArg,
8658 unsigned numDataArgs, bool isObjC, const char *beg,
8660 ArrayRef<const Expr *> Args, unsigned formatIdx,
8661 bool inFunctionCall, VariadicCallType CallType,
8662 llvm::SmallBitVector &CheckedVarArgs,
8663 UncoveredArgHandler &UncoveredArg,
8664 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8665 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8666 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8667 inFunctionCall, CallType, CheckedVarArgs,
8668 UncoveredArg),
8669 Specs(Specs), HadError(false) {}
8670
8671public:
8672 static bool
8673 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8674 FormatStringType type, bool IsObjC, bool InFunctionCall,
8675 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8676
8677 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8678 const char *startSpecifier,
8679 unsigned specifierLen,
8680 const TargetInfo &Target) override;
8681};
8682
8683} // namespace
8684
8685bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8686 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8687 unsigned specifierLen) {
8690
8691 return HandleInvalidConversionSpecifier(
8692 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8693 specifierLen, CS.getStart(), CS.getLength());
8694}
8695
8696void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8697 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8698}
8699
8700// Error out if struct or complex type argments are passed to os_log.
8702 QualType T) {
8703 if (FSType != FormatStringType::OSLog)
8704 return false;
8705 return T->isRecordType() || T->isComplexType();
8706}
8707
8708bool CheckPrintfHandler::HandleAmount(
8709 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8710 const char *startSpecifier, unsigned specifierLen) {
8711 if (Amt.hasDataArgument()) {
8712 if (HasFormatArguments()) {
8713 unsigned argIndex = Amt.getArgIndex();
8714 if (argIndex >= NumDataArgs) {
8715 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8716 << k,
8717 getLocationOfByte(Amt.getStart()),
8718 /*IsStringLocation*/ true,
8719 getSpecifierRange(startSpecifier, specifierLen));
8720 // Don't do any more checking. We will just emit
8721 // spurious errors.
8722 return false;
8723 }
8724
8725 // Type check the data argument. It should be an 'int'.
8726 // Although not in conformance with C99, we also allow the argument to be
8727 // an 'unsigned int' as that is a reasonably safe case. GCC also
8728 // doesn't emit a warning for that case.
8729 CoveredArgs.set(argIndex);
8730 const Expr *Arg = getDataArg(argIndex);
8731 if (!Arg)
8732 return false;
8733
8734 QualType T = Arg->getType();
8735
8736 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8737 assert(AT.isValid());
8738
8739 if (!AT.matchesType(S.Context, T)) {
8740 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8741 ? diag::err_printf_asterisk_wrong_type
8742 : diag::warn_printf_asterisk_wrong_type;
8743 EmitFormatDiagnostic(S.PDiag(DiagID)
8745 << T << Arg->getSourceRange(),
8746 getLocationOfByte(Amt.getStart()),
8747 /*IsStringLocation*/ true,
8748 getSpecifierRange(startSpecifier, specifierLen));
8749 // Don't do any more checking. We will just emit
8750 // spurious errors.
8751 return false;
8752 }
8753 }
8754 }
8755 return true;
8756}
8757
8758void CheckPrintfHandler::HandleInvalidAmount(
8760 const analyze_printf::OptionalAmount &Amt, unsigned type,
8761 const char *startSpecifier, unsigned specifierLen) {
8764
8765 FixItHint fixit =
8768 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8769 : FixItHint();
8770
8771 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8772 << type << CS.toString(),
8773 getLocationOfByte(Amt.getStart()),
8774 /*IsStringLocation*/ true,
8775 getSpecifierRange(startSpecifier, specifierLen), fixit);
8776}
8777
8778void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8779 const analyze_printf::OptionalFlag &flag,
8780 const char *startSpecifier,
8781 unsigned specifierLen) {
8782 // Warn about pointless flag with a fixit removal.
8785 EmitFormatDiagnostic(
8786 S.PDiag(diag::warn_printf_nonsensical_flag)
8787 << flag.toString() << CS.toString(),
8788 getLocationOfByte(flag.getPosition()),
8789 /*IsStringLocation*/ true,
8790 getSpecifierRange(startSpecifier, specifierLen),
8791 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8792}
8793
8794void CheckPrintfHandler::HandleIgnoredFlag(
8796 const analyze_printf::OptionalFlag &ignoredFlag,
8797 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8798 unsigned specifierLen) {
8799 // Warn about ignored flag with a fixit removal.
8800 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8801 << ignoredFlag.toString() << flag.toString(),
8802 getLocationOfByte(ignoredFlag.getPosition()),
8803 /*IsStringLocation*/ true,
8804 getSpecifierRange(startSpecifier, specifierLen),
8806 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8807}
8808
8809void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8810 unsigned flagLen) {
8811 // Warn about an empty flag.
8812 EmitFormatDiagnostic(
8813 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8814 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8815}
8816
8817void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8818 unsigned flagLen) {
8819 // Warn about an invalid flag.
8820 auto Range = getSpecifierRange(startFlag, flagLen);
8821 StringRef flag(startFlag, flagLen);
8822 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8823 getLocationOfByte(startFlag),
8824 /*IsStringLocation*/ true, Range,
8826}
8827
8828void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8829 const char *flagsStart, const char *flagsEnd,
8830 const char *conversionPosition) {
8831 // Warn about using '[...]' without a '@' conversion.
8832 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8833 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8834 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8835 getLocationOfByte(conversionPosition),
8836 /*IsStringLocation*/ true, Range,
8838}
8839
8840void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8841 const Expr *FmtExpr,
8842 bool InFunctionCall) const {
8843 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8844 ElementLoc, true, Range);
8845}
8846
8847bool EquatableFormatArgument::VerifyCompatible(
8848 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8849 bool InFunctionCall) const {
8851 if (Role != Other.Role) {
8852 // diagnose and stop
8853 EmitDiagnostic(
8854 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8855 FmtExpr, InFunctionCall);
8856 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8857 return false;
8858 }
8859
8860 if (Role != FAR_Data) {
8861 if (ModifierFor != Other.ModifierFor) {
8862 // diagnose and stop
8863 EmitDiagnostic(S,
8864 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8865 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8866 FmtExpr, InFunctionCall);
8867 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8868 return false;
8869 }
8870 return true;
8871 }
8872
8873 bool HadError = false;
8874 if (Sensitivity != Other.Sensitivity) {
8875 // diagnose and continue
8876 EmitDiagnostic(S,
8877 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8878 << Sensitivity << Other.Sensitivity,
8879 FmtExpr, InFunctionCall);
8880 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8881 << 0 << Other.Range;
8882 }
8883
8884 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8885 case MK::Match:
8886 break;
8887
8888 case MK::MatchPromotion:
8889 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8890 // MatchPromotion is treated as a failure by format_matches.
8891 case MK::NoMatch:
8892 case MK::NoMatchTypeConfusion:
8893 case MK::NoMatchPromotionTypeConfusion:
8894 EmitDiagnostic(S,
8895 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8896 << buildFormatSpecifier()
8897 << Other.buildFormatSpecifier(),
8898 FmtExpr, InFunctionCall);
8899 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8900 << 0 << Other.Range;
8901 break;
8902
8903 case MK::NoMatchPedantic:
8904 EmitDiagnostic(S,
8905 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8906 << buildFormatSpecifier()
8907 << Other.buildFormatSpecifier(),
8908 FmtExpr, InFunctionCall);
8909 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8910 << 0 << Other.Range;
8911 break;
8912
8913 case MK::NoMatchSignedness:
8914 EmitDiagnostic(S,
8915 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8916 << buildFormatSpecifier()
8917 << Other.buildFormatSpecifier(),
8918 FmtExpr, InFunctionCall);
8919 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8920 << 0 << Other.Range;
8921 break;
8922 }
8923 return !HadError;
8924}
8925
8926bool DecomposePrintfHandler::GetSpecifiers(
8927 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8928 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8930 StringRef Data = FSL->getString();
8931 const char *Str = Data.data();
8932 llvm::SmallBitVector BV;
8933 UncoveredArgHandler UA;
8934 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8935 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8936 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8937 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8938 UA, Args);
8939
8941 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8943 H.DoneProcessing();
8944 if (H.HadError)
8945 return false;
8946
8947 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8948 const EquatableFormatArgument &B) {
8949 return A.getPosition() < B.getPosition();
8950 });
8951 return true;
8952}
8953
8954bool DecomposePrintfHandler::HandlePrintfSpecifier(
8955 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8956 unsigned specifierLen, const TargetInfo &Target) {
8957 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8958 specifierLen, Target)) {
8959 HadError = true;
8960 return false;
8961 }
8962
8963 // Do not add any specifiers to the list for %%. This is possibly incorrect
8964 // if using a precision/width with a data argument, but that combination is
8965 // meaningless and we wouldn't know which format to attach the
8966 // precision/width to.
8967 const auto &CS = FS.getConversionSpecifier();
8969 return true;
8970
8971 // have to patch these to have the right ModifierFor if they are used
8972 const unsigned Unset = ~0;
8973 unsigned FieldWidthIndex = Unset;
8974 unsigned PrecisionIndex = Unset;
8975
8976 // field width?
8977 const auto &FieldWidth = FS.getFieldWidth();
8978 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8979 FieldWidthIndex = Specs.size();
8980 Specs.emplace_back(
8981 getSpecifierRange(startSpecifier, specifierLen),
8982 getLocationOfByte(FieldWidth.getStart()),
8983 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
8984 FieldWidth.getArgType(S.Context),
8985 EquatableFormatArgument::FAR_FieldWidth,
8986 EquatableFormatArgument::SS_None,
8987 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8988 : FieldWidthIndex,
8989 0);
8990 }
8991 // precision?
8992 const auto &Precision = FS.getPrecision();
8993 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8994 PrecisionIndex = Specs.size();
8995 Specs.emplace_back(
8996 getSpecifierRange(startSpecifier, specifierLen),
8997 getLocationOfByte(Precision.getStart()),
8998 analyze_format_string::LengthModifier(), Precision.getCharacters(),
8999 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
9000 EquatableFormatArgument::SS_None,
9001 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9002 : PrecisionIndex,
9003 0);
9004 }
9005
9006 // this specifier
9007 unsigned SpecIndex =
9008 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9009 if (FieldWidthIndex != Unset)
9010 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9011 if (PrecisionIndex != Unset)
9012 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9013
9014 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9015 if (FS.isPrivate())
9016 Sensitivity = EquatableFormatArgument::SS_Private;
9017 else if (FS.isPublic())
9018 Sensitivity = EquatableFormatArgument::SS_Public;
9019 else if (FS.isSensitive())
9020 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9021 else
9022 Sensitivity = EquatableFormatArgument::SS_None;
9023
9024 Specs.emplace_back(
9025 getSpecifierRange(startSpecifier, specifierLen),
9026 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
9027 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
9028 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9029
9030 // auxiliary argument?
9033 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9034 getLocationOfByte(CS.getStart()),
9036 CS.getCharacters(),
9038 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9039 SpecIndex + 1, SpecIndex);
9040 }
9041 return true;
9042}
9043
9044// Determines if the specified is a C++ class or struct containing
9045// a member with the specified name and kind (e.g. a CXXMethodDecl named
9046// "c_str()").
9047template<typename MemberKind>
9049CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9050 auto *RD = Ty->getAsCXXRecordDecl();
9052
9053 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9054 return Results;
9055
9056 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9058 R.suppressDiagnostics();
9059
9060 // We just need to include all members of the right kind turned up by the
9061 // filter, at this point.
9062 if (S.LookupQualifiedName(R, RD))
9063 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9064 NamedDecl *decl = (*I)->getUnderlyingDecl();
9065 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9066 Results.insert(FK);
9067 }
9068 return Results;
9069}
9070
9071/// Check if we could call '.c_str()' on an object.
9072///
9073/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9074/// allow the call, or if it would be ambiguous).
9076 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9077
9078 MethodSet Results =
9079 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9080 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9081 MI != ME; ++MI)
9082 if ((*MI)->getMinRequiredArguments() == 0)
9083 return true;
9084 return false;
9085}
9086
9087// Check if a (w)string was passed when a (w)char* was needed, and offer a
9088// better diagnostic if so. AT is assumed to be valid.
9089// Returns true when a c_str() conversion method is found.
9090bool CheckPrintfHandler::checkForCStrMembers(
9091 const analyze_printf::ArgType &AT, const Expr *E) {
9092 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9093
9094 MethodSet Results =
9096
9097 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9098 MI != ME; ++MI) {
9099 const CXXMethodDecl *Method = *MI;
9100 if (Method->getMinRequiredArguments() == 0 &&
9101 AT.matchesType(S.Context, Method->getReturnType())) {
9102 // FIXME: Suggest parens if the expression needs them.
9104 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9105 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9106 return true;
9107 }
9108 }
9109
9110 return false;
9111}
9112
9113bool CheckPrintfHandler::HandlePrintfSpecifier(
9114 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9115 unsigned specifierLen, const TargetInfo &Target) {
9116 using namespace analyze_format_string;
9117 using namespace analyze_printf;
9118
9119 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9120
9121 if (FS.consumesDataArgument()) {
9122 if (atFirstArg) {
9123 atFirstArg = false;
9124 usesPositionalArgs = FS.usesPositionalArg();
9125 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9126 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9127 startSpecifier, specifierLen);
9128 return false;
9129 }
9130 }
9131
9132 // First check if the field width, precision, and conversion specifier
9133 // have matching data arguments.
9134 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9135 specifierLen)) {
9136 return false;
9137 }
9138
9139 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9140 specifierLen)) {
9141 return false;
9142 }
9143
9144 if (!CS.consumesDataArgument()) {
9145 // FIXME: Technically specifying a precision or field width here
9146 // makes no sense. Worth issuing a warning at some point.
9147 return true;
9148 }
9149
9150 // Consume the argument.
9151 unsigned argIndex = FS.getArgIndex();
9152 if (argIndex < NumDataArgs) {
9153 // The check to see if the argIndex is valid will come later.
9154 // We set the bit here because we may exit early from this
9155 // function if we encounter some other error.
9156 CoveredArgs.set(argIndex);
9157 }
9158
9159 // FreeBSD kernel extensions.
9160 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9161 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9162 // We need at least two arguments.
9163 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9164 return false;
9165
9166 if (HasFormatArguments()) {
9167 // Claim the second argument.
9168 CoveredArgs.set(argIndex + 1);
9169
9170 // Type check the first argument (int for %b, pointer for %D)
9171 const Expr *Ex = getDataArg(argIndex);
9172 const analyze_printf::ArgType &AT =
9173 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9174 ? ArgType(S.Context.IntTy)
9175 : ArgType::CPointerTy;
9176 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9177 EmitFormatDiagnostic(
9178 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9179 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9180 << false << Ex->getSourceRange(),
9181 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9182 getSpecifierRange(startSpecifier, specifierLen));
9183
9184 // Type check the second argument (char * for both %b and %D)
9185 Ex = getDataArg(argIndex + 1);
9187 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9188 EmitFormatDiagnostic(
9189 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9190 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9191 << false << Ex->getSourceRange(),
9192 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9193 getSpecifierRange(startSpecifier, specifierLen));
9194 }
9195 return true;
9196 }
9197
9198 // Check for using an Objective-C specific conversion specifier
9199 // in a non-ObjC literal.
9200 if (!allowsObjCArg() && CS.isObjCArg()) {
9201 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9202 specifierLen);
9203 }
9204
9205 // %P can only be used with os_log.
9206 if (FSType != FormatStringType::OSLog &&
9207 CS.getKind() == ConversionSpecifier::PArg) {
9208 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9209 specifierLen);
9210 }
9211
9212 // %n is not allowed with os_log.
9213 if (FSType == FormatStringType::OSLog &&
9214 CS.getKind() == ConversionSpecifier::nArg) {
9215 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9216 getLocationOfByte(CS.getStart()),
9217 /*IsStringLocation*/ false,
9218 getSpecifierRange(startSpecifier, specifierLen));
9219
9220 return true;
9221 }
9222
9223 // Only scalars are allowed for os_trace.
9224 if (FSType == FormatStringType::OSTrace &&
9225 (CS.getKind() == ConversionSpecifier::PArg ||
9226 CS.getKind() == ConversionSpecifier::sArg ||
9227 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9228 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9229 specifierLen);
9230 }
9231
9232 // Check for use of public/private annotation outside of os_log().
9233 if (FSType != FormatStringType::OSLog) {
9234 if (FS.isPublic().isSet()) {
9235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9236 << "public",
9237 getLocationOfByte(FS.isPublic().getPosition()),
9238 /*IsStringLocation*/ false,
9239 getSpecifierRange(startSpecifier, specifierLen));
9240 }
9241 if (FS.isPrivate().isSet()) {
9242 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9243 << "private",
9244 getLocationOfByte(FS.isPrivate().getPosition()),
9245 /*IsStringLocation*/ false,
9246 getSpecifierRange(startSpecifier, specifierLen));
9247 }
9248 }
9249
9250 const llvm::Triple &Triple = Target.getTriple();
9251 if (CS.getKind() == ConversionSpecifier::nArg &&
9252 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9253 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9254 getLocationOfByte(CS.getStart()),
9255 /*IsStringLocation*/ false,
9256 getSpecifierRange(startSpecifier, specifierLen));
9257 }
9258
9259 // Check for invalid use of field width
9260 if (!FS.hasValidFieldWidth()) {
9261 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9262 startSpecifier, specifierLen);
9263 }
9264
9265 // Check for invalid use of precision
9266 if (!FS.hasValidPrecision()) {
9267 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9268 startSpecifier, specifierLen);
9269 }
9270
9271 // Precision is mandatory for %P specifier.
9272 if (CS.getKind() == ConversionSpecifier::PArg &&
9274 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9275 getLocationOfByte(startSpecifier),
9276 /*IsStringLocation*/ false,
9277 getSpecifierRange(startSpecifier, specifierLen));
9278 }
9279
9280 // Check each flag does not conflict with any other component.
9282 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9283 if (!FS.hasValidLeadingZeros())
9284 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9285 if (!FS.hasValidPlusPrefix())
9286 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9287 if (!FS.hasValidSpacePrefix())
9288 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9289 if (!FS.hasValidAlternativeForm())
9290 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9291 if (!FS.hasValidLeftJustified())
9292 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9293
9294 // Check that flags are not ignored by another flag
9295 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9296 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9297 startSpecifier, specifierLen);
9298 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9299 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9300 startSpecifier, specifierLen);
9301
9302 // Check the length modifier is valid with the given conversion specifier.
9304 S.getLangOpts()))
9305 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9306 diag::warn_format_nonsensical_length);
9307 else if (!FS.hasStandardLengthModifier())
9308 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9310 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9311 diag::warn_format_non_standard_conversion_spec);
9312
9314 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9315
9316 // The remaining checks depend on the data arguments.
9317 if (!HasFormatArguments())
9318 return true;
9319
9320 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9321 return false;
9322
9323 const Expr *Arg = getDataArg(argIndex);
9324 if (!Arg)
9325 return true;
9326
9327 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9328}
9329
9330static bool requiresParensToAddCast(const Expr *E) {
9331 // FIXME: We should have a general way to reason about operator
9332 // precedence and whether parens are actually needed here.
9333 // Take care of a few common cases where they aren't.
9334 const Expr *Inside = E->IgnoreImpCasts();
9335 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9336 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9337
9338 switch (Inside->getStmtClass()) {
9339 case Stmt::ArraySubscriptExprClass:
9340 case Stmt::CallExprClass:
9341 case Stmt::CharacterLiteralClass:
9342 case Stmt::CXXBoolLiteralExprClass:
9343 case Stmt::DeclRefExprClass:
9344 case Stmt::FloatingLiteralClass:
9345 case Stmt::IntegerLiteralClass:
9346 case Stmt::MemberExprClass:
9347 case Stmt::ObjCArrayLiteralClass:
9348 case Stmt::ObjCBoolLiteralExprClass:
9349 case Stmt::ObjCBoxedExprClass:
9350 case Stmt::ObjCDictionaryLiteralClass:
9351 case Stmt::ObjCEncodeExprClass:
9352 case Stmt::ObjCIvarRefExprClass:
9353 case Stmt::ObjCMessageExprClass:
9354 case Stmt::ObjCPropertyRefExprClass:
9355 case Stmt::ObjCStringLiteralClass:
9356 case Stmt::ObjCSubscriptRefExprClass:
9357 case Stmt::ParenExprClass:
9358 case Stmt::StringLiteralClass:
9359 case Stmt::UnaryOperatorClass:
9360 return false;
9361 default:
9362 return true;
9363 }
9364}
9365
9366static std::pair<QualType, StringRef>
9367shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9368 const Expr *E) {
9369 // Use a 'while' to peel off layers of typedefs.
9370 QualType TyTy = IntendedTy;
9371 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9372 StringRef Name = UserTy->getDecl()->getName();
9373 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9374 .Case("CFIndex", Context.getNSIntegerType())
9375 .Case("NSInteger", Context.getNSIntegerType())
9376 .Case("NSUInteger", Context.getNSUIntegerType())
9377 .Case("SInt32", Context.IntTy)
9378 .Case("UInt32", Context.UnsignedIntTy)
9379 .Default(QualType());
9380
9381 if (!CastTy.isNull())
9382 return std::make_pair(CastTy, Name);
9383
9384 TyTy = UserTy->desugar();
9385 }
9386
9387 // Strip parens if necessary.
9388 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9389 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9390 PE->getSubExpr());
9391
9392 // If this is a conditional expression, then its result type is constructed
9393 // via usual arithmetic conversions and thus there might be no necessary
9394 // typedef sugar there. Recurse to operands to check for NSInteger &
9395 // Co. usage condition.
9396 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9397 QualType TrueTy, FalseTy;
9398 StringRef TrueName, FalseName;
9399
9400 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9401 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9402 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9403 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9404
9405 if (TrueTy == FalseTy)
9406 return std::make_pair(TrueTy, TrueName);
9407 else if (TrueTy.isNull())
9408 return std::make_pair(FalseTy, FalseName);
9409 else if (FalseTy.isNull())
9410 return std::make_pair(TrueTy, TrueName);
9411 }
9412
9413 return std::make_pair(QualType(), StringRef());
9414}
9415
9416/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9417/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9418/// type do not count.
9420 const ImplicitCastExpr *ICE) {
9421 QualType From = ICE->getSubExpr()->getType();
9422 QualType To = ICE->getType();
9423 // It's an integer promotion if the destination type is the promoted
9424 // source type.
9425 if (ICE->getCastKind() == CK_IntegralCast &&
9427 S.Context.getPromotedIntegerType(From) == To)
9428 return true;
9429 // Look through vector types, since we do default argument promotion for
9430 // those in OpenCL.
9431 if (const auto *VecTy = From->getAs<ExtVectorType>())
9432 From = VecTy->getElementType();
9433 if (const auto *VecTy = To->getAs<ExtVectorType>())
9434 To = VecTy->getElementType();
9435 // It's a floating promotion if the source type is a lower rank.
9436 return ICE->getCastKind() == CK_FloatingCast &&
9437 S.Context.getFloatingTypeOrder(From, To) < 0;
9438}
9439
9442 DiagnosticsEngine &Diags, SourceLocation Loc) {
9444 if (Diags.isIgnored(
9445 diag::warn_format_conversion_argument_type_mismatch_signedness,
9446 Loc) ||
9447 Diags.isIgnored(
9448 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9449 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9451 }
9452 }
9453 return Match;
9454}
9455
9456bool CheckPrintfHandler::checkFormatExpr(
9457 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9458 unsigned SpecifierLen, const Expr *E) {
9459 using namespace analyze_format_string;
9460 using namespace analyze_printf;
9461
9462 // Now type check the data expression that matches the
9463 // format specifier.
9464 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9465 if (!AT.isValid())
9466 return true;
9467
9468 QualType ExprTy = E->getType();
9469 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9470 ExprTy = TET->getUnderlyingExpr()->getType();
9471 }
9472
9473 if (const OverflowBehaviorType *OBT =
9474 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9475 ExprTy = OBT->getUnderlyingType();
9476
9477 // When using the format attribute in C++, you can receive a function or an
9478 // array that will necessarily decay to a pointer when passed to the final
9479 // format consumer. Apply decay before type comparison.
9480 if (ExprTy->canDecayToPointerType())
9481 ExprTy = S.Context.getDecayedType(ExprTy);
9482
9483 // Diagnose attempts to print a boolean value as a character. Unlike other
9484 // -Wformat diagnostics, this is fine from a type perspective, but it still
9485 // doesn't make sense.
9488 const CharSourceRange &CSR =
9489 getSpecifierRange(StartSpecifier, SpecifierLen);
9490 SmallString<4> FSString;
9491 llvm::raw_svector_ostream os(FSString);
9492 FS.toString(os);
9493 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9494 << FSString,
9495 E->getExprLoc(), false, CSR);
9496 return true;
9497 }
9498
9499 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9500 // dumping raw class data (like is-a pointer), not actual data.
9502 ExprTy->isObjCObjectPointerType()) {
9503 const CharSourceRange &CSR =
9504 getSpecifierRange(StartSpecifier, SpecifierLen);
9505 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9506 E->getExprLoc(), false, CSR);
9507 return true;
9508 }
9509
9510 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9511 return true;
9512
9513 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9515 ArgType::MatchKind OrigMatch = Match;
9516
9518 if (Match == ArgType::Match)
9519 return true;
9520
9521 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9522 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9523
9524 // Look through argument promotions for our error message's reported type.
9525 // This includes the integral and floating promotions, but excludes array
9526 // and function pointer decay (seeing that an argument intended to be a
9527 // string has type 'char [6]' is probably more confusing than 'char *') and
9528 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9529 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9530 if (isArithmeticArgumentPromotion(S, ICE)) {
9531 E = ICE->getSubExpr();
9532 ExprTy = E->getType();
9533
9534 // Check if we didn't match because of an implicit cast from a 'char'
9535 // or 'short' to an 'int'. This is done because printf is a varargs
9536 // function.
9537 if (ICE->getType() == S.Context.IntTy ||
9538 ICE->getType() == S.Context.UnsignedIntTy) {
9539 // All further checking is done on the subexpression
9540 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9541 if (OrigMatch == ArgType::NoMatchSignedness &&
9542 ImplicitMatch != ArgType::NoMatchSignedness)
9543 // If the original match was a signedness match this match on the
9544 // implicit cast type also need to be signedness match otherwise we
9545 // might introduce new unexpected warnings from -Wformat-signedness.
9546 return true;
9547 ImplicitMatch = handleFormatSignedness(
9548 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9549 if (ImplicitMatch == ArgType::Match)
9550 return true;
9551 }
9552 }
9553 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9554 // Special case for 'a', which has type 'int' in C.
9555 // Note, however, that we do /not/ want to treat multibyte constants like
9556 // 'MooV' as characters! This form is deprecated but still exists. In
9557 // addition, don't treat expressions as of type 'char' if one byte length
9558 // modifier is provided.
9559 if (ExprTy == S.Context.IntTy &&
9561 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9562 ExprTy = S.Context.CharTy;
9563 // To improve check results, we consider a character literal in C
9564 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9565 // more likely a type confusion situation, so we will suggest to
9566 // use '%hhd' instead by discarding the MatchPromotion.
9567 if (Match == ArgType::MatchPromotion)
9569 }
9570 }
9571 if (Match == ArgType::MatchPromotion) {
9572 // WG14 N2562 only clarified promotions in *printf
9573 // For NSLog in ObjC, just preserve -Wformat behavior
9574 if (!S.getLangOpts().ObjC &&
9575 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9576 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9577 return true;
9579 }
9580 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9581 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9582 Match = ImplicitMatch;
9583 assert(Match != ArgType::MatchPromotion);
9584
9585 // Look through unscoped enums to their underlying type.
9586 bool IsEnum = false;
9587 bool IsScopedEnum = false;
9588 QualType IntendedTy = ExprTy;
9589 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9590 IntendedTy = ED->getIntegerType();
9591 if (!ED->isScoped()) {
9592 ExprTy = IntendedTy;
9593 // This controls whether we're talking about the underlying type or not,
9594 // which we only want to do when it's an unscoped enum.
9595 IsEnum = true;
9596 } else {
9597 IsScopedEnum = true;
9598 }
9599 }
9600
9601 // %C in an Objective-C context prints a unichar, not a wchar_t.
9602 // If the argument is an integer of some kind, believe the %C and suggest
9603 // a cast instead of changing the conversion specifier.
9604 if (isObjCContext() &&
9607 !ExprTy->isCharType()) {
9608 // 'unichar' is defined as a typedef of unsigned short, but we should
9609 // prefer using the typedef if it is visible.
9610 IntendedTy = S.Context.UnsignedShortTy;
9611
9612 // While we are here, check if the value is an IntegerLiteral that happens
9613 // to be within the valid range.
9614 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9615 const llvm::APInt &V = IL->getValue();
9616 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9617 return true;
9618 }
9619
9620 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9622 if (S.LookupName(Result, S.getCurScope())) {
9623 NamedDecl *ND = Result.getFoundDecl();
9624 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9625 if (TD->getUnderlyingType() == IntendedTy)
9626 IntendedTy =
9628 /*Qualifier=*/std::nullopt, TD);
9629 }
9630 }
9631 }
9632
9633 // Special-case some of Darwin's platform-independence types by suggesting
9634 // casts to primitive types that are known to be large enough.
9635 bool ShouldNotPrintDirectly = false;
9636 StringRef CastTyName;
9637 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9638 QualType CastTy;
9639 std::tie(CastTy, CastTyName) =
9640 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9641 if (!CastTy.isNull()) {
9642 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9643 // (long in ASTContext). Only complain to pedants or when they're the
9644 // underlying type of a scoped enum (which always needs a cast).
9645 if (!IsScopedEnum &&
9646 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9647 (AT.isSizeT() || AT.isPtrdiffT()) &&
9648 AT.matchesType(S.Context, CastTy))
9650 IntendedTy = CastTy;
9651 ShouldNotPrintDirectly = true;
9652 }
9653 }
9654
9655 // We may be able to offer a FixItHint if it is a supported type.
9656 PrintfSpecifier fixedFS = FS;
9657 bool Success =
9658 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9659
9660 if (Success) {
9661 // Get the fix string from the fixed format specifier
9662 SmallString<16> buf;
9663 llvm::raw_svector_ostream os(buf);
9664 fixedFS.toString(os);
9665
9666 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9667
9668 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9669 unsigned Diag;
9670 switch (Match) {
9671 case ArgType::Match:
9674 llvm_unreachable("expected non-matching");
9676 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9677 break;
9679 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9680 break;
9682 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9683 break;
9684 case ArgType::NoMatch:
9685 Diag = diag::warn_format_conversion_argument_type_mismatch;
9686 break;
9687 }
9688
9689 // In this case, the specifier is wrong and should be changed to match
9690 // the argument.
9691 EmitFormatDiagnostic(S.PDiag(Diag)
9693 << IntendedTy << IsEnum << E->getSourceRange(),
9694 E->getBeginLoc(),
9695 /*IsStringLocation*/ false, SpecRange,
9696 FixItHint::CreateReplacement(SpecRange, os.str()));
9697 } else {
9698 // The canonical type for formatting this value is different from the
9699 // actual type of the expression. (This occurs, for example, with Darwin's
9700 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9701 // should be printed as 'long' for 64-bit compatibility.)
9702 // Rather than emitting a normal format/argument mismatch, we want to
9703 // add a cast to the recommended type (and correct the format string
9704 // if necessary). We should also do so for scoped enumerations.
9705 SmallString<16> CastBuf;
9706 llvm::raw_svector_ostream CastFix(CastBuf);
9707 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9708 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9709 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9710
9712 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9713 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9714 E->getExprLoc());
9715 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9716 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9717
9718 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9719 // If there's already a cast present, just replace it.
9720 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9721 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9722
9723 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9724 // If the expression has high enough precedence,
9725 // just write the C-style cast.
9726 Hints.push_back(
9727 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9728 } else {
9729 // Otherwise, add parens around the expression as well as the cast.
9730 CastFix << "(";
9731 Hints.push_back(
9732 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9733
9734 // We don't use getLocForEndOfToken because it returns invalid source
9735 // locations for macro expansions (by design).
9739 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9740 }
9741
9742 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9743 // The expression has a type that should not be printed directly.
9744 // We extract the name from the typedef because we don't want to show
9745 // the underlying type in the diagnostic.
9746 StringRef Name;
9747 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9748 Name = TypedefTy->getDecl()->getName();
9749 else
9750 Name = CastTyName;
9751 unsigned Diag = Match == ArgType::NoMatchPedantic
9752 ? diag::warn_format_argument_needs_cast_pedantic
9753 : diag::warn_format_argument_needs_cast;
9754 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9755 << E->getSourceRange(),
9756 E->getBeginLoc(), /*IsStringLocation=*/false,
9757 SpecRange, Hints);
9758 } else {
9759 // In this case, the expression could be printed using a different
9760 // specifier, but we've decided that the specifier is probably correct
9761 // and we should cast instead. Just use the normal warning message.
9762
9763 unsigned Diag =
9764 IsScopedEnum
9765 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9766 : diag::warn_format_conversion_argument_type_mismatch;
9767
9768 EmitFormatDiagnostic(
9769 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9770 << IsEnum << E->getSourceRange(),
9771 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9772 }
9773 }
9774 } else {
9775 const CharSourceRange &CSR =
9776 getSpecifierRange(StartSpecifier, SpecifierLen);
9777 // Since the warning for passing non-POD types to variadic functions
9778 // was deferred until now, we emit a warning for non-POD
9779 // arguments here.
9780 bool EmitTypeMismatch = false;
9781 // Record and complex type arguments cannot be code generated for os_log
9782 // and would crash CodeGen, so they are rejected with a hard error emitted
9783 // after the switch below.
9784 bool EmitOSLogError = false;
9785 switch (S.isValidVarArgType(ExprTy)) {
9786 case VarArgKind::Valid:
9788 unsigned Diag;
9789 switch (Match) {
9790 case ArgType::Match:
9793 llvm_unreachable("expected non-matching");
9795 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9796 break;
9798 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9799 break;
9801 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9802 break;
9803 case ArgType::NoMatch:
9804 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
9805 Diag = diag::warn_format_conversion_argument_type_mismatch;
9806 break;
9807 }
9808
9809 if (!EmitOSLogError)
9810 EmitFormatDiagnostic(
9811 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9812 << IsEnum << CSR << E->getSourceRange(),
9813 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9814 break;
9815 }
9818 if (CallType == VariadicCallType::DoesNotApply) {
9819 EmitTypeMismatch = true;
9820 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
9821 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9822 // does not stop compilation.
9823 EmitOSLogError = true;
9824 } else {
9825 EmitFormatDiagnostic(
9826 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9827 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9828 << AT.getRepresentativeTypeName(S.Context) << CSR
9829 << E->getSourceRange(),
9830 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9831 checkForCStrMembers(AT, E);
9832 }
9833 break;
9834
9836 if (CallType == VariadicCallType::DoesNotApply)
9837 EmitTypeMismatch = true;
9838 else if (ExprTy->isObjCObjectType())
9839 EmitFormatDiagnostic(
9840 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9841 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9842 << AT.getRepresentativeTypeName(S.Context) << CSR
9843 << E->getSourceRange(),
9844 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9845 else
9846 // FIXME: If this is an initializer list, suggest removing the braces
9847 // or inserting a cast to the target type.
9848 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9849 << isa<InitListExpr>(E) << ExprTy << CallType
9851 break;
9852 }
9853
9854 if (EmitOSLogError)
9855 EmitFormatDiagnostic(
9856 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
9857 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9858 << CSR << E->getSourceRange(),
9859 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9860
9861 if (EmitTypeMismatch) {
9862 // The function is not variadic, so we do not generate warnings about
9863 // being allowed to pass that object as a variadic argument. Instead,
9864 // since there are inherently no printf specifiers for types which cannot
9865 // be passed as variadic arguments, emit a plain old specifier mismatch
9866 // argument.
9867 EmitFormatDiagnostic(
9868 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9869 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9870 << E->getSourceRange(),
9871 E->getBeginLoc(), false, CSR);
9872 }
9873
9874 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9875 "format string specifier index out of range");
9876 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9877 }
9878
9879 return true;
9880}
9881
9882//===--- CHECK: Scanf format string checking ------------------------------===//
9883
9884namespace {
9885
9886class CheckScanfHandler : public CheckFormatHandler {
9887public:
9888 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9889 const Expr *origFormatExpr, FormatStringType type,
9890 unsigned firstDataArg, unsigned numDataArgs,
9891 const char *beg, Sema::FormatArgumentPassingKind APK,
9892 ArrayRef<const Expr *> Args, unsigned formatIdx,
9893 bool inFunctionCall, VariadicCallType CallType,
9894 llvm::SmallBitVector &CheckedVarArgs,
9895 UncoveredArgHandler &UncoveredArg)
9896 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9897 numDataArgs, beg, APK, Args, formatIdx,
9898 inFunctionCall, CallType, CheckedVarArgs,
9899 UncoveredArg) {}
9900
9901 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9902 const char *startSpecifier,
9903 unsigned specifierLen) override;
9904
9905 bool
9906 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9907 const char *startSpecifier,
9908 unsigned specifierLen) override;
9909
9910 void HandleIncompleteScanList(const char *start, const char *end) override;
9911};
9912
9913} // namespace
9914
9915void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9916 const char *end) {
9917 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9918 getLocationOfByte(end), /*IsStringLocation*/ true,
9919 getSpecifierRange(start, end - start));
9920}
9921
9922bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9923 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9924 unsigned specifierLen) {
9927
9928 return HandleInvalidConversionSpecifier(
9929 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9930 specifierLen, CS.getStart(), CS.getLength());
9931}
9932
9933bool CheckScanfHandler::HandleScanfSpecifier(
9934 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9935 unsigned specifierLen) {
9936 using namespace analyze_scanf;
9937 using namespace analyze_format_string;
9938
9939 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9940
9941 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9942 // be used to decide if we are using positional arguments consistently.
9943 if (FS.consumesDataArgument()) {
9944 if (atFirstArg) {
9945 atFirstArg = false;
9946 usesPositionalArgs = FS.usesPositionalArg();
9947 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9948 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9949 startSpecifier, specifierLen);
9950 return false;
9951 }
9952 }
9953
9954 // Check if the field with is non-zero.
9955 const OptionalAmount &Amt = FS.getFieldWidth();
9957 if (Amt.getConstantAmount() == 0) {
9958 const CharSourceRange &R =
9959 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9960 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9961 getLocationOfByte(Amt.getStart()),
9962 /*IsStringLocation*/ true, R,
9964 }
9965 }
9966
9967 if (!FS.consumesDataArgument()) {
9968 // FIXME: Technically specifying a precision or field width here
9969 // makes no sense. Worth issuing a warning at some point.
9970 return true;
9971 }
9972
9973 // Consume the argument.
9974 unsigned argIndex = FS.getArgIndex();
9975 if (argIndex < NumDataArgs) {
9976 // The check to see if the argIndex is valid will come later.
9977 // We set the bit here because we may exit early from this
9978 // function if we encounter some other error.
9979 CoveredArgs.set(argIndex);
9980 }
9981
9982 // Check the length modifier is valid with the given conversion specifier.
9984 S.getLangOpts()))
9985 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9986 diag::warn_format_nonsensical_length);
9987 else if (!FS.hasStandardLengthModifier())
9988 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9990 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9991 diag::warn_format_non_standard_conversion_spec);
9992
9994 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9995
9996 // The remaining checks depend on the data arguments.
9997 if (!HasFormatArguments())
9998 return true;
9999
10000 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10001 return false;
10002
10003 // Check that the argument type matches the format specifier.
10004 const Expr *Ex = getDataArg(argIndex);
10005 if (!Ex)
10006 return true;
10007
10009
10010 if (!AT.isValid()) {
10011 return true;
10012 }
10013
10014 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10015 return true;
10016
10018 AT.matchesType(S.Context, Ex->getType());
10021 return true;
10024
10025 ScanfSpecifier fixedFS = FS;
10026 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10027 S.getLangOpts(), S.Context);
10028
10029 unsigned Diag =
10030 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10031 : Signedness
10032 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10033 : diag::warn_format_conversion_argument_type_mismatch;
10034
10035 if (Success) {
10036 // Get the fix string from the fixed format specifier.
10037 SmallString<128> buf;
10038 llvm::raw_svector_ostream os(buf);
10039 fixedFS.toString(os);
10040
10041 EmitFormatDiagnostic(
10043 << Ex->getType() << false << Ex->getSourceRange(),
10044 Ex->getBeginLoc(),
10045 /*IsStringLocation*/ false,
10046 getSpecifierRange(startSpecifier, specifierLen),
10048 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10049 } else {
10050 EmitFormatDiagnostic(S.PDiag(Diag)
10052 << Ex->getType() << false << Ex->getSourceRange(),
10053 Ex->getBeginLoc(),
10054 /*IsStringLocation*/ false,
10055 getSpecifierRange(startSpecifier, specifierLen));
10056 }
10057
10058 return true;
10059}
10060
10061static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10063 const StringLiteral *Fmt,
10065 const Expr *FmtExpr, bool InFunctionCall) {
10066 bool HadError = false;
10067 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10068 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10069 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10070 // In positional-style format strings, the same specifier can appear
10071 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10072 // are sorted by getPosition(), and we process each range of equal
10073 // getPosition() values as one group.
10074 // RefArgs are taken from a string literal that was given to
10075 // attribute(format_matches), and if we got this far, we have already
10076 // verified that if it has positional specifiers that appear in multiple
10077 // locations, then they are all mutually compatible. What's left for us to
10078 // do is verify that all specifiers with the same position in FmtArgs are
10079 // compatible with the RefArgs specifiers. We check each specifier from
10080 // FmtArgs against the first member of the RefArgs group.
10081 for (; FmtIter < FmtEnd; ++FmtIter) {
10082 // Clang does not diagnose missing format specifiers in positional-style
10083 // strings (TODO: which it probably should do, as it is UB to skip over a
10084 // format argument). Skip specifiers if needed.
10085 if (FmtIter->getPosition() < RefIter->getPosition())
10086 continue;
10087
10088 // Delimits a new getPosition() value.
10089 if (FmtIter->getPosition() > RefIter->getPosition())
10090 break;
10091
10092 HadError |=
10093 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10094 }
10095
10096 // Jump RefIter to the start of the next group.
10097 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
10098 return Arg.getPosition() != RefIter->getPosition();
10099 });
10100 }
10101
10102 if (FmtIter < FmtEnd) {
10103 CheckFormatHandler::EmitFormatDiagnostic(
10104 S, InFunctionCall, FmtExpr,
10105 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10106 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
10107 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
10108 } else if (RefIter < RefEnd) {
10109 CheckFormatHandler::EmitFormatDiagnostic(
10110 S, InFunctionCall, FmtExpr,
10111 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10112 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
10113 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
10114 << 1 << RefIter->getSourceRange();
10115 }
10116 return !HadError;
10117}
10118
10120 Sema &S, const FormatStringLiteral *FExpr,
10121 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10123 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10124 bool inFunctionCall, VariadicCallType CallType,
10125 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10126 bool IgnoreStringsWithoutSpecifiers) {
10127 // CHECK: is the format string a wide literal?
10128 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10129 CheckFormatHandler::EmitFormatDiagnostic(
10130 S, inFunctionCall, Args[format_idx],
10131 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10132 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10133 return;
10134 }
10135
10136 // Str - The format string. NOTE: this is NOT null-terminated!
10137 StringRef StrRef = FExpr->getString();
10138 const char *Str = StrRef.data();
10139 // Account for cases where the string literal is truncated in a declaration.
10140 const ConstantArrayType *T =
10141 S.Context.getAsConstantArrayType(FExpr->getType());
10142 assert(T && "String literal not of constant array type!");
10143 size_t TypeSize = T->getZExtSize();
10144 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10145 const unsigned numDataArgs = Args.size() - firstDataArg;
10146
10147 if (IgnoreStringsWithoutSpecifiers &&
10149 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10150 return;
10151
10152 // Emit a warning if the string literal is truncated and does not contain an
10153 // embedded null character.
10154 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10155 CheckFormatHandler::EmitFormatDiagnostic(
10156 S, inFunctionCall, Args[format_idx],
10157 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10158 FExpr->getBeginLoc(),
10159 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10160 return;
10161 }
10162
10163 // CHECK: empty format string?
10164 if (StrLen == 0 && numDataArgs > 0) {
10165 CheckFormatHandler::EmitFormatDiagnostic(
10166 S, inFunctionCall, Args[format_idx],
10167 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10168 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10169 return;
10170 }
10171
10176 bool IsObjC =
10178 if (ReferenceFormatString == nullptr) {
10179 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10180 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10181 inFunctionCall, CallType, CheckedVarArgs,
10182 UncoveredArg);
10183
10185 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10188 H.DoneProcessing();
10189 } else {
10191 Type, ReferenceFormatString, FExpr->getFormatString(),
10192 inFunctionCall ? nullptr : Args[format_idx]);
10193 }
10194 } else if (Type == FormatStringType::Scanf) {
10195 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10196 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10197 CallType, CheckedVarArgs, UncoveredArg);
10198
10200 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10201 H.DoneProcessing();
10202 } // TODO: handle other formats
10203}
10204
10206 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10207 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10212 return true;
10213
10214 bool IsObjC =
10217 FormatStringLiteral RefLit = AuthoritativeFormatString;
10218 FormatStringLiteral TestLit = TestedFormatString;
10219 const Expr *Arg;
10220 bool DiagAtStringLiteral;
10221 if (FunctionCallArg) {
10222 Arg = FunctionCallArg;
10223 DiagAtStringLiteral = false;
10224 } else {
10225 Arg = TestedFormatString;
10226 DiagAtStringLiteral = true;
10227 }
10228 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10229 AuthoritativeFormatString, Type,
10230 IsObjC, true, RefArgs) &&
10231 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10232 DiagAtStringLiteral, FmtArgs)) {
10233 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10234 TestedFormatString, FmtArgs, Arg,
10235 DiagAtStringLiteral);
10236 }
10237 return false;
10238}
10239
10241 const StringLiteral *Str) {
10246 return true;
10247
10248 FormatStringLiteral RefLit = Str;
10250 bool IsObjC =
10252 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10253 true, Args))
10254 return false;
10255
10256 // Group arguments by getPosition() value, and check that each member of the
10257 // group is compatible with the first member. This verifies that when
10258 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10259 // are mutually compatible. As an optimization, don't test the first member
10260 // against itself.
10261 bool HadError = false;
10262 auto Iter = Args.begin();
10263 auto End = Args.end();
10264 while (Iter != End) {
10265 const auto &FirstInGroup = *Iter;
10266 for (++Iter;
10267 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10268 ++Iter) {
10269 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10270 }
10271 }
10272 return !HadError;
10273}
10274
10276 // Str - The format string. NOTE: this is NOT null-terminated!
10277 StringRef StrRef = FExpr->getString();
10278 const char *Str = StrRef.data();
10279 // Account for cases where the string literal is truncated in a declaration.
10280 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10281 assert(T && "String literal not of constant array type!");
10282 size_t TypeSize = T->getZExtSize();
10283 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10285 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10286}
10287
10288//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10289
10290// Returns the related absolute value function that is larger, of 0 if one
10291// does not exist.
10292static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10293 switch (AbsFunction) {
10294 default:
10295 return 0;
10296
10297 case Builtin::BI__builtin_abs:
10298 return Builtin::BI__builtin_labs;
10299 case Builtin::BI__builtin_labs:
10300 return Builtin::BI__builtin_llabs;
10301 case Builtin::BI__builtin_llabs:
10302 return 0;
10303
10304 case Builtin::BI__builtin_fabsf:
10305 return Builtin::BI__builtin_fabs;
10306 case Builtin::BI__builtin_fabs:
10307 return Builtin::BI__builtin_fabsl;
10308 case Builtin::BI__builtin_fabsl:
10309 return 0;
10310
10311 case Builtin::BI__builtin_cabsf:
10312 return Builtin::BI__builtin_cabs;
10313 case Builtin::BI__builtin_cabs:
10314 return Builtin::BI__builtin_cabsl;
10315 case Builtin::BI__builtin_cabsl:
10316 return 0;
10317
10318 case Builtin::BIabs:
10319 return Builtin::BIlabs;
10320 case Builtin::BIlabs:
10321 return Builtin::BIllabs;
10322 case Builtin::BIllabs:
10323 return 0;
10324
10325 case Builtin::BIfabsf:
10326 return Builtin::BIfabs;
10327 case Builtin::BIfabs:
10328 return Builtin::BIfabsl;
10329 case Builtin::BIfabsl:
10330 return 0;
10331
10332 case Builtin::BIcabsf:
10333 return Builtin::BIcabs;
10334 case Builtin::BIcabs:
10335 return Builtin::BIcabsl;
10336 case Builtin::BIcabsl:
10337 return 0;
10338 }
10339}
10340
10341// Returns the argument type of the absolute value function.
10343 unsigned AbsType) {
10344 if (AbsType == 0)
10345 return QualType();
10346
10348 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10350 return QualType();
10351
10353 if (!FT)
10354 return QualType();
10355
10356 if (FT->getNumParams() != 1)
10357 return QualType();
10358
10359 return FT->getParamType(0);
10360}
10361
10362// Returns the best absolute value function, or zero, based on type and
10363// current absolute value function.
10364static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10365 unsigned AbsFunctionKind) {
10366 unsigned BestKind = 0;
10367 uint64_t ArgSize = Context.getTypeSize(ArgType);
10368 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10369 Kind = getLargerAbsoluteValueFunction(Kind)) {
10370 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10371 if (Context.getTypeSize(ParamType) >= ArgSize) {
10372 if (BestKind == 0)
10373 BestKind = Kind;
10374 else if (Context.hasSameType(ParamType, ArgType)) {
10375 BestKind = Kind;
10376 break;
10377 }
10378 }
10379 }
10380 return BestKind;
10381}
10382
10388
10390 if (T->isIntegralOrEnumerationType())
10391 return AVK_Integer;
10392 if (T->isRealFloatingType())
10393 return AVK_Floating;
10394 if (T->isAnyComplexType())
10395 return AVK_Complex;
10396
10397 llvm_unreachable("Type not integer, floating, or complex");
10398}
10399
10400// Changes the absolute value function to a different type. Preserves whether
10401// the function is a builtin.
10402static unsigned changeAbsFunction(unsigned AbsKind,
10403 AbsoluteValueKind ValueKind) {
10404 switch (ValueKind) {
10405 case AVK_Integer:
10406 switch (AbsKind) {
10407 default:
10408 return 0;
10409 case Builtin::BI__builtin_fabsf:
10410 case Builtin::BI__builtin_fabs:
10411 case Builtin::BI__builtin_fabsl:
10412 case Builtin::BI__builtin_cabsf:
10413 case Builtin::BI__builtin_cabs:
10414 case Builtin::BI__builtin_cabsl:
10415 return Builtin::BI__builtin_abs;
10416 case Builtin::BIfabsf:
10417 case Builtin::BIfabs:
10418 case Builtin::BIfabsl:
10419 case Builtin::BIcabsf:
10420 case Builtin::BIcabs:
10421 case Builtin::BIcabsl:
10422 return Builtin::BIabs;
10423 }
10424 case AVK_Floating:
10425 switch (AbsKind) {
10426 default:
10427 return 0;
10428 case Builtin::BI__builtin_abs:
10429 case Builtin::BI__builtin_labs:
10430 case Builtin::BI__builtin_llabs:
10431 case Builtin::BI__builtin_cabsf:
10432 case Builtin::BI__builtin_cabs:
10433 case Builtin::BI__builtin_cabsl:
10434 return Builtin::BI__builtin_fabsf;
10435 case Builtin::BIabs:
10436 case Builtin::BIlabs:
10437 case Builtin::BIllabs:
10438 case Builtin::BIcabsf:
10439 case Builtin::BIcabs:
10440 case Builtin::BIcabsl:
10441 return Builtin::BIfabsf;
10442 }
10443 case AVK_Complex:
10444 switch (AbsKind) {
10445 default:
10446 return 0;
10447 case Builtin::BI__builtin_abs:
10448 case Builtin::BI__builtin_labs:
10449 case Builtin::BI__builtin_llabs:
10450 case Builtin::BI__builtin_fabsf:
10451 case Builtin::BI__builtin_fabs:
10452 case Builtin::BI__builtin_fabsl:
10453 return Builtin::BI__builtin_cabsf;
10454 case Builtin::BIabs:
10455 case Builtin::BIlabs:
10456 case Builtin::BIllabs:
10457 case Builtin::BIfabsf:
10458 case Builtin::BIfabs:
10459 case Builtin::BIfabsl:
10460 return Builtin::BIcabsf;
10461 }
10462 }
10463 llvm_unreachable("Unable to convert function");
10464}
10465
10466static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10467 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10468 if (!FnInfo)
10469 return 0;
10470
10471 switch (FDecl->getBuiltinID()) {
10472 default:
10473 return 0;
10474 case Builtin::BI__builtin_abs:
10475 case Builtin::BI__builtin_fabs:
10476 case Builtin::BI__builtin_fabsf:
10477 case Builtin::BI__builtin_fabsl:
10478 case Builtin::BI__builtin_labs:
10479 case Builtin::BI__builtin_llabs:
10480 case Builtin::BI__builtin_cabs:
10481 case Builtin::BI__builtin_cabsf:
10482 case Builtin::BI__builtin_cabsl:
10483 case Builtin::BIabs:
10484 case Builtin::BIlabs:
10485 case Builtin::BIllabs:
10486 case Builtin::BIfabs:
10487 case Builtin::BIfabsf:
10488 case Builtin::BIfabsl:
10489 case Builtin::BIcabs:
10490 case Builtin::BIcabsf:
10491 case Builtin::BIcabsl:
10492 return FDecl->getBuiltinID();
10493 }
10494 llvm_unreachable("Unknown Builtin type");
10495}
10496
10497// If the replacement is valid, emit a note with replacement function.
10498// Additionally, suggest including the proper header if not already included.
10500 unsigned AbsKind, QualType ArgType) {
10501 bool EmitHeaderHint = true;
10502 const char *HeaderName = nullptr;
10503 std::string FunctionName;
10504 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10505 FunctionName = "std::abs";
10506 if (ArgType->isIntegralOrEnumerationType()) {
10507 HeaderName = "cstdlib";
10508 } else if (ArgType->isRealFloatingType()) {
10509 HeaderName = "cmath";
10510 } else {
10511 llvm_unreachable("Invalid Type");
10512 }
10513
10514 // Lookup all std::abs
10515 if (NamespaceDecl *Std = S.getStdNamespace()) {
10516 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10517 R.suppressDiagnostics();
10518 S.LookupQualifiedName(R, Std);
10519
10520 for (const auto *I : R) {
10521 const FunctionDecl *FDecl = nullptr;
10522 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10523 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10524 } else {
10525 FDecl = dyn_cast<FunctionDecl>(I);
10526 }
10527 if (!FDecl)
10528 continue;
10529
10530 // Found std::abs(), check that they are the right ones.
10531 if (FDecl->getNumParams() != 1)
10532 continue;
10533
10534 // Check that the parameter type can handle the argument.
10535 QualType ParamType = FDecl->getParamDecl(0)->getType();
10536 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10537 S.Context.getTypeSize(ArgType) <=
10538 S.Context.getTypeSize(ParamType)) {
10539 // Found a function, don't need the header hint.
10540 EmitHeaderHint = false;
10541 break;
10542 }
10543 }
10544 }
10545 } else {
10546 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10547 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10548
10549 if (HeaderName) {
10550 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10551 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10552 R.suppressDiagnostics();
10553 S.LookupName(R, S.getCurScope());
10554
10555 if (R.isSingleResult()) {
10556 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10557 if (FD && FD->getBuiltinID() == AbsKind) {
10558 EmitHeaderHint = false;
10559 } else {
10560 return;
10561 }
10562 } else if (!R.empty()) {
10563 return;
10564 }
10565 }
10566 }
10567
10568 S.Diag(Loc, diag::note_replace_abs_function)
10569 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10570
10571 if (!HeaderName)
10572 return;
10573
10574 if (!EmitHeaderHint)
10575 return;
10576
10577 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10578 << FunctionName;
10579}
10580
10581template <std::size_t StrLen>
10582static bool IsStdFunction(const FunctionDecl *FDecl,
10583 const char (&Str)[StrLen]) {
10584 if (!FDecl)
10585 return false;
10586 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10587 return false;
10588 if (!FDecl->isInStdNamespace())
10589 return false;
10590
10591 return true;
10592}
10593
10594enum class MathCheck { NaN, Inf };
10595static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10596 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10597 return llvm::is_contained(names, calleeName);
10598 };
10599
10600 switch (Check) {
10601 case MathCheck::NaN:
10602 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10603 "__builtin_nanf16", "__builtin_nanf128"});
10604 case MathCheck::Inf:
10605 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10606 "__builtin_inff16", "__builtin_inff128"});
10607 }
10608 llvm_unreachable("unknown MathCheck");
10609}
10610
10611static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10612 if (FDecl->getName() != "infinity")
10613 return false;
10614
10615 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10616 const CXXRecordDecl *RDecl = MDecl->getParent();
10617 if (RDecl->getName() != "numeric_limits")
10618 return false;
10619
10620 if (const NamespaceDecl *NSDecl =
10621 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10622 return NSDecl->isStdNamespace();
10623 }
10624
10625 return false;
10626}
10627
10628void Sema::CheckInfNaNFunction(const CallExpr *Call,
10629 const FunctionDecl *FDecl) {
10630 if (!FDecl->getIdentifier())
10631 return;
10632
10633 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10634 if (FPO.getNoHonorNaNs() &&
10635 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10637 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10638 << 1 << 0 << Call->getSourceRange();
10639 return;
10640 }
10641
10642 if (FPO.getNoHonorInfs() &&
10643 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10644 IsInfinityFunction(FDecl) ||
10646 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10647 << 0 << 0 << Call->getSourceRange();
10648 }
10649}
10650
10651void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10652 const FunctionDecl *FDecl) {
10653 if (Call->getNumArgs() != 1)
10654 return;
10655
10656 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10657 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10658 if (AbsKind == 0 && !IsStdAbs)
10659 return;
10660
10661 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10662 QualType ParamType = Call->getArg(0)->getType();
10663
10664 // Unsigned types cannot be negative. Suggest removing the absolute value
10665 // function call.
10666 if (ArgType->isUnsignedIntegerType()) {
10667 std::string FunctionName =
10668 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10669 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10670 Diag(Call->getExprLoc(), diag::note_remove_abs)
10671 << FunctionName
10672 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10673 return;
10674 }
10675
10676 // Taking the absolute value of a pointer is very suspicious, they probably
10677 // wanted to index into an array, dereference a pointer, call a function, etc.
10678 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10679 unsigned DiagType = 0;
10680 if (ArgType->isFunctionType())
10681 DiagType = 1;
10682 else if (ArgType->isArrayType())
10683 DiagType = 2;
10684
10685 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10686 return;
10687 }
10688
10689 // std::abs has overloads which prevent most of the absolute value problems
10690 // from occurring.
10691 if (IsStdAbs)
10692 return;
10693
10694 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10695 // types.
10696 if (!ArgType->isIntegralOrEnumerationType() &&
10697 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10698 return;
10699
10700 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10701 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10702
10703 // The argument and parameter are the same kind. Check if they are the right
10704 // size.
10705 if (ArgValueKind == ParamValueKind) {
10706 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10707 return;
10708
10709 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10710 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10711 << FDecl << ArgType << ParamType;
10712
10713 if (NewAbsKind == 0)
10714 return;
10715
10716 emitReplacement(*this, Call->getExprLoc(),
10717 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10718 return;
10719 }
10720
10721 // ArgValueKind != ParamValueKind
10722 // The wrong type of absolute value function was used. Attempt to find the
10723 // proper one.
10724 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10725 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10726 if (NewAbsKind == 0)
10727 return;
10728
10729 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10730 << FDecl << ParamValueKind << ArgValueKind;
10731
10732 emitReplacement(*this, Call->getExprLoc(),
10733 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10734}
10735
10736//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10737void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10738 const FunctionDecl *FDecl) {
10739 if (!Call || !FDecl) return;
10740
10741 // Ignore template specializations and macros.
10742 if (inTemplateInstantiation()) return;
10743 if (Call->getExprLoc().isMacroID()) return;
10744
10745 // Only care about the one template argument, two function parameter std::max
10746 if (Call->getNumArgs() != 2) return;
10747 if (!IsStdFunction(FDecl, "max")) return;
10748 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10749 if (!ArgList) return;
10750 if (ArgList->size() != 1) return;
10751
10752 // Check that template type argument is unsigned integer.
10753 const auto& TA = ArgList->get(0);
10754 if (TA.getKind() != TemplateArgument::Type) return;
10755 QualType ArgType = TA.getAsType();
10756 if (!ArgType->isUnsignedIntegerType()) return;
10757
10758 // See if either argument is a literal zero.
10759 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10760 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10761 if (!MTE) return false;
10762 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10763 if (!Num) return false;
10764 if (Num->getValue() != 0) return false;
10765 return true;
10766 };
10767
10768 const Expr *FirstArg = Call->getArg(0);
10769 const Expr *SecondArg = Call->getArg(1);
10770 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10771 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10772
10773 // Only warn when exactly one argument is zero.
10774 if (IsFirstArgZero == IsSecondArgZero) return;
10775
10776 SourceRange FirstRange = FirstArg->getSourceRange();
10777 SourceRange SecondRange = SecondArg->getSourceRange();
10778
10779 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10780
10781 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10782 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10783
10784 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10785 SourceRange RemovalRange;
10786 if (IsFirstArgZero) {
10787 RemovalRange = SourceRange(FirstRange.getBegin(),
10788 SecondRange.getBegin().getLocWithOffset(-1));
10789 } else {
10790 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10791 SecondRange.getEnd());
10792 }
10793
10794 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10795 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10796 << FixItHint::CreateRemoval(RemovalRange);
10797}
10798
10799//===--- CHECK: Standard memory functions ---------------------------------===//
10800
10801/// Takes the expression passed to the size_t parameter of functions
10802/// such as memcmp, strncat, etc and warns if it's a comparison.
10803///
10804/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10806 const IdentifierInfo *FnName,
10807 SourceLocation FnLoc,
10808 SourceLocation RParenLoc) {
10809 const auto *Size = dyn_cast<BinaryOperator>(E);
10810 if (!Size)
10811 return false;
10812
10813 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10814 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10815 return false;
10816
10817 SourceRange SizeRange = Size->getSourceRange();
10818 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10819 << SizeRange << FnName;
10820 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10821 << FnName
10823 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10824 << FixItHint::CreateRemoval(RParenLoc);
10825 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10826 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10828 ")");
10829
10830 return true;
10831}
10832
10833/// Determine whether the given type is or contains a dynamic class type
10834/// (e.g., whether it has a vtable).
10836 bool &IsContained) {
10837 // Look through array types while ignoring qualifiers.
10838 const Type *Ty = T->getBaseElementTypeUnsafe();
10839 IsContained = false;
10840
10841 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10842 RD = RD ? RD->getDefinition() : nullptr;
10843 if (!RD || RD->isInvalidDecl())
10844 return nullptr;
10845
10846 if (RD->isDynamicClass())
10847 return RD;
10848
10849 // Check all the fields. If any bases were dynamic, the class is dynamic.
10850 // It's impossible for a class to transitively contain itself by value, so
10851 // infinite recursion is impossible.
10852 for (auto *FD : RD->fields()) {
10853 bool SubContained;
10854 if (const CXXRecordDecl *ContainedRD =
10855 getContainedDynamicClass(FD->getType(), SubContained)) {
10856 IsContained = true;
10857 return ContainedRD;
10858 }
10859 }
10860
10861 return nullptr;
10862}
10863
10865 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10866 if (Unary->getKind() == UETT_SizeOf)
10867 return Unary;
10868 return nullptr;
10869}
10870
10871/// If E is a sizeof expression, returns its argument expression,
10872/// otherwise returns NULL.
10873static const Expr *getSizeOfExprArg(const Expr *E) {
10875 if (!SizeOf->isArgumentType())
10876 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10877 return nullptr;
10878}
10879
10880/// If E is a sizeof expression, returns its argument type.
10883 return SizeOf->getTypeOfArgument();
10884 return QualType();
10885}
10886
10887namespace {
10888
10889struct SearchNonTrivialToInitializeField
10890 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10891 using Super =
10892 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10893
10894 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10895
10896 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10897 SourceLocation SL) {
10898 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10899 asDerived().visitArray(PDIK, AT, SL);
10900 return;
10901 }
10902
10903 Super::visitWithKind(PDIK, FT, SL);
10904 }
10905
10906 void visitARCStrong(QualType FT, SourceLocation SL) {
10907 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10908 }
10909 void visitARCWeak(QualType FT, SourceLocation SL) {
10910 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10911 }
10912 void visitStruct(QualType FT, SourceLocation SL) {
10913 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10914 visit(FD->getType(), FD->getLocation());
10915 }
10916 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10917 const ArrayType *AT, SourceLocation SL) {
10918 visit(getContext().getBaseElementType(AT), SL);
10919 }
10920 void visitTrivial(QualType FT, SourceLocation SL) {}
10921
10922 static void diag(QualType RT, const Expr *E, Sema &S) {
10923 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10924 }
10925
10926 ASTContext &getContext() { return S.getASTContext(); }
10927
10928 const Expr *E;
10929 Sema &S;
10930};
10931
10932struct SearchNonTrivialToCopyField
10933 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10934 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10935
10936 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10937
10938 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10939 SourceLocation SL) {
10940 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10941 asDerived().visitArray(PCK, AT, SL);
10942 return;
10943 }
10944
10945 Super::visitWithKind(PCK, FT, SL);
10946 }
10947
10948 void visitARCStrong(QualType FT, SourceLocation SL) {
10949 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10950 }
10951 void visitARCWeak(QualType FT, SourceLocation SL) {
10952 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10953 }
10954 void visitPtrAuth(QualType FT, SourceLocation SL) {
10955 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10956 }
10957 void visitStruct(QualType FT, SourceLocation SL) {
10958 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10959 visit(FD->getType(), FD->getLocation());
10960 }
10961 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10962 SourceLocation SL) {
10963 visit(getContext().getBaseElementType(AT), SL);
10964 }
10965 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10966 SourceLocation SL) {}
10967 void visitTrivial(QualType FT, SourceLocation SL) {}
10968 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10969
10970 static void diag(QualType RT, const Expr *E, Sema &S) {
10971 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10972 }
10973
10974 ASTContext &getContext() { return S.getASTContext(); }
10975
10976 const Expr *E;
10977 Sema &S;
10978};
10979
10980}
10981
10982/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10983static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10984 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10985
10986 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10987 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10988 return false;
10989
10990 return doesExprLikelyComputeSize(BO->getLHS()) ||
10991 doesExprLikelyComputeSize(BO->getRHS());
10992 }
10993
10994 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10995}
10996
10997/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10998///
10999/// \code
11000/// #define MACRO 0
11001/// foo(MACRO);
11002/// foo(0);
11003/// \endcode
11004///
11005/// This should return true for the first call to foo, but not for the second
11006/// (regardless of whether foo is a macro or function).
11008 SourceLocation CallLoc,
11009 SourceLocation ArgLoc) {
11010 if (!CallLoc.isMacroID())
11011 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11012
11013 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11015}
11016
11017/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11018/// last two arguments transposed.
11019static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11020 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11021 return;
11022
11023 const Expr *SizeArg =
11024 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11025
11026 auto isLiteralZero = [](const Expr *E) {
11027 return (isa<IntegerLiteral>(E) &&
11028 cast<IntegerLiteral>(E)->getValue() == 0) ||
11030 cast<CharacterLiteral>(E)->getValue() == 0);
11031 };
11032
11033 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11034 SourceLocation CallLoc = Call->getRParenLoc();
11036 if (isLiteralZero(SizeArg) &&
11037 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11038
11039 SourceLocation DiagLoc = SizeArg->getExprLoc();
11040
11041 // Some platforms #define bzero to __builtin_memset. See if this is the
11042 // case, and if so, emit a better diagnostic.
11043 if (BId == Builtin::BIbzero ||
11045 CallLoc, SM, S.getLangOpts()) == "bzero")) {
11046 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11047 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11048 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11049 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11050 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11051 }
11052 return;
11053 }
11054
11055 // If the second argument to a memset is a sizeof expression and the third
11056 // isn't, this is also likely an error. This should catch
11057 // 'memset(buf, sizeof(buf), 0xff)'.
11058 if (BId == Builtin::BImemset &&
11059 doesExprLikelyComputeSize(Call->getArg(1)) &&
11060 !doesExprLikelyComputeSize(Call->getArg(2))) {
11061 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11062 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11063 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11064 return;
11065 }
11066}
11067
11068void Sema::CheckMemaccessArguments(const CallExpr *Call,
11069 unsigned BId,
11070 IdentifierInfo *FnName) {
11071 assert(BId != 0);
11072
11073 // It is possible to have a non-standard definition of memset. Validate
11074 // we have enough arguments, and if not, abort further checking.
11075 unsigned ExpectedNumArgs =
11076 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11077 if (Call->getNumArgs() < ExpectedNumArgs)
11078 return;
11079
11080 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11081 BId == Builtin::BIstrndup ? 1 : 2);
11082 unsigned LenArg =
11083 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11084 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11085
11086 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11087 Call->getBeginLoc(), Call->getRParenLoc()))
11088 return;
11089
11090 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11091 CheckMemaccessSize(*this, BId, Call);
11092
11093 // We have special checking when the length is a sizeof expression.
11094 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11095
11096 // Although widely used, 'bzero' is not a standard function. Be more strict
11097 // with the argument types before allowing diagnostics and only allow the
11098 // form bzero(ptr, sizeof(...)).
11099 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11100 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11101 return;
11102
11103 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11104 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11105 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11106
11107 QualType DestTy = Dest->getType();
11108 QualType PointeeTy;
11109 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11110 PointeeTy = DestPtrTy->getPointeeType();
11111
11112 // Never warn about void type pointers. This can be used to suppress
11113 // false positives.
11114 if (PointeeTy->isVoidType())
11115 continue;
11116
11117 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11118 // actually comparing the expressions for equality. Because computing the
11119 // expression IDs can be expensive, we only do this if the diagnostic is
11120 // enabled.
11121 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11122 break;
11123
11124 // Also check for cases where the sizeof argument is the exact same
11125 // type as the memory argument, and where it points to a user-defined
11126 // record type.
11127 if (SizeOfArgTy != QualType()) {
11128 if (PointeeTy->isRecordType() &&
11129 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11130 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11131 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11132 << FnName << SizeOfArgTy << ArgIdx
11133 << PointeeTy << Dest->getSourceRange()
11134 << LenExpr->getSourceRange());
11135 break;
11136 }
11137 }
11138 } else if (DestTy->isArrayType()) {
11139 PointeeTy = DestTy;
11140 }
11141
11142 if (PointeeTy == QualType())
11143 continue;
11144
11145 // Always complain about dynamic classes.
11146 bool IsContained;
11147 if (const CXXRecordDecl *ContainedRD =
11148 getContainedDynamicClass(PointeeTy, IsContained)) {
11149
11150 unsigned OperationType = 0;
11151 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11152 // "overwritten" if we're warning about the destination for any call
11153 // but memcmp; otherwise a verb appropriate to the call.
11154 if (ArgIdx != 0 || IsCmp) {
11155 if (BId == Builtin::BImemcpy)
11156 OperationType = 1;
11157 else if(BId == Builtin::BImemmove)
11158 OperationType = 2;
11159 else if (IsCmp)
11160 OperationType = 3;
11161 }
11162
11163 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11164 PDiag(diag::warn_dyn_class_memaccess)
11165 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11166 << IsContained << ContainedRD << OperationType
11167 << Call->getCallee()->getSourceRange());
11168 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11169 BId != Builtin::BImemset)
11171 Dest->getExprLoc(), Dest,
11172 PDiag(diag::warn_arc_object_memaccess)
11173 << ArgIdx << FnName << PointeeTy
11174 << Call->getCallee()->getSourceRange());
11175 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11176
11177 // FIXME: Do not consider incomplete types even though they may be
11178 // completed later. GCC does not diagnose such code, but we may want to
11179 // consider diagnosing it in the future, perhaps under a different, but
11180 // related, diagnostic group.
11181 bool NonTriviallyCopyableCXXRecord =
11182 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11183 !PointeeTy.isTriviallyCopyableType(Context);
11184
11185 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11187 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11188 PDiag(diag::warn_cstruct_memaccess)
11189 << ArgIdx << FnName << PointeeTy << 0);
11190 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11191 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11192 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11193 // FIXME: Limiting this warning to dest argument until we decide
11194 // whether it's valid for source argument too.
11195 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11196 PDiag(diag::warn_cxxstruct_memaccess)
11197 << FnName << PointeeTy);
11198 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11200 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11201 PDiag(diag::warn_cstruct_memaccess)
11202 << ArgIdx << FnName << PointeeTy << 1);
11203 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11204 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11205 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11206 // FIXME: Limiting this warning to dest argument until we decide
11207 // whether it's valid for source argument too.
11208 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11209 PDiag(diag::warn_cxxstruct_memaccess)
11210 << FnName << PointeeTy);
11211 } else {
11212 continue;
11213 }
11214 } else
11215 continue;
11216
11218 Dest->getExprLoc(), Dest,
11219 PDiag(diag::note_bad_memaccess_silence)
11220 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11221 break;
11222 }
11223}
11224
11225bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11226 IdentifierInfo *FnName) {
11227 llvm::FoldingSetNodeID SizeOfArgID;
11228 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11229 if (!SizeOfArg)
11230 return false;
11231 // Computing this warning is expensive, so we only do so if the warning is
11232 // enabled.
11233 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11234 SizeOfArg->getExprLoc()))
11235 return false;
11236 QualType DestTy = Dest->getType();
11237 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11238 if (!DestPtrTy)
11239 return false;
11240
11241 QualType PointeeTy = DestPtrTy->getPointeeType();
11242
11243 if (SizeOfArgID == llvm::FoldingSetNodeID())
11244 SizeOfArg->Profile(SizeOfArgID, Context, true);
11245
11246 llvm::FoldingSetNodeID DestID;
11247 Dest->Profile(DestID, Context, true);
11248 if (DestID == SizeOfArgID) {
11249 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11250 // over sizeof(src) as well.
11251 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11252 StringRef ReadableName = FnName->getName();
11253
11254 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11255 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11256 ActionIdx = 1; // If its an address-of operator, just remove it.
11257 if (!PointeeTy->isIncompleteType() &&
11258 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11259 ActionIdx = 2; // If the pointee's size is sizeof(char),
11260 // suggest an explicit length.
11261
11262 // If the function is defined as a builtin macro, do not show macro
11263 // expansion.
11264 SourceLocation SL = SizeOfArg->getExprLoc();
11265 SourceRange DSR = Dest->getSourceRange();
11266 SourceRange SSR = SizeOfArg->getSourceRange();
11267 SourceManager &SM = getSourceManager();
11268
11269 if (SM.isMacroArgExpansion(SL)) {
11270 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11271 SL = SM.getSpellingLoc(SL);
11272 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11273 SM.getSpellingLoc(DSR.getEnd()));
11274 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11275 SM.getSpellingLoc(SSR.getEnd()));
11276 }
11277
11278 DiagRuntimeBehavior(SL, SizeOfArg,
11279 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11280 << ReadableName << PointeeTy << DestTy << DSR
11281 << SSR);
11282 DiagRuntimeBehavior(SL, SizeOfArg,
11283 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11284 << ActionIdx << SSR);
11285 return true;
11286 }
11287 return false;
11288}
11289
11290// A little helper routine: ignore addition and subtraction of integer literals.
11291// This intentionally does not ignore all integer constant expressions because
11292// we don't want to remove sizeof().
11293static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11294 Ex = Ex->IgnoreParenCasts();
11295
11296 while (true) {
11297 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11298 if (!BO || !BO->isAdditiveOp())
11299 break;
11300
11301 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11302 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11303
11304 if (isa<IntegerLiteral>(RHS))
11305 Ex = LHS;
11306 else if (isa<IntegerLiteral>(LHS))
11307 Ex = RHS;
11308 else
11309 break;
11310 }
11311
11312 return Ex;
11313}
11314
11316 ASTContext &Context) {
11317 // Only handle constant-sized or VLAs, but not flexible members.
11318 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11319 // Only issue the FIXIT for arrays of size > 1.
11320 if (CAT->getZExtSize() <= 1)
11321 return false;
11322 } else if (!Ty->isVariableArrayType()) {
11323 return false;
11324 }
11325 return true;
11326}
11327
11328void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11329 IdentifierInfo *FnName) {
11330
11331 // Don't crash if the user has the wrong number of arguments
11332 unsigned NumArgs = Call->getNumArgs();
11333 if ((NumArgs != 3) && (NumArgs != 4))
11334 return;
11335
11336 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11337 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11338 const Expr *CompareWithSrc = nullptr;
11339
11340 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11341 Call->getBeginLoc(), Call->getRParenLoc()))
11342 return;
11343
11344 // Look for 'strlcpy(dst, x, sizeof(x))'
11345 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11346 CompareWithSrc = Ex;
11347 else {
11348 // Look for 'strlcpy(dst, x, strlen(x))'
11349 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11350 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11351 SizeCall->getNumArgs() == 1)
11352 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11353 }
11354 }
11355
11356 if (!CompareWithSrc)
11357 return;
11358
11359 // Determine if the argument to sizeof/strlen is equal to the source
11360 // argument. In principle there's all kinds of things you could do
11361 // here, for instance creating an == expression and evaluating it with
11362 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11363 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11364 if (!SrcArgDRE)
11365 return;
11366
11367 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11368 if (!CompareWithSrcDRE ||
11369 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11370 return;
11371
11372 const Expr *OriginalSizeArg = Call->getArg(2);
11373 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11374 << OriginalSizeArg->getSourceRange() << FnName;
11375
11376 // Output a FIXIT hint if the destination is an array (rather than a
11377 // pointer to an array). This could be enhanced to handle some
11378 // pointers if we know the actual size, like if DstArg is 'array+2'
11379 // we could say 'sizeof(array)-2'.
11380 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11382 return;
11383
11384 SmallString<128> sizeString;
11385 llvm::raw_svector_ostream OS(sizeString);
11386 OS << "sizeof(";
11387 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11388 OS << ")";
11389
11390 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11391 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11392 OS.str());
11393}
11394
11395/// Check if two expressions refer to the same declaration.
11396static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11397 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11398 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11399 return D1->getDecl() == D2->getDecl();
11400 return false;
11401}
11402
11403static const Expr *getStrlenExprArg(const Expr *E) {
11404 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11405 const FunctionDecl *FD = CE->getDirectCallee();
11406 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11407 return nullptr;
11408 return CE->getArg(0)->IgnoreParenCasts();
11409 }
11410 return nullptr;
11411}
11412
11413void Sema::CheckStrncatArguments(const CallExpr *CE,
11414 const IdentifierInfo *FnName) {
11415 // Don't crash if the user has the wrong number of arguments.
11416 if (CE->getNumArgs() < 3)
11417 return;
11418 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11419 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11420 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11421
11422 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11423 CE->getRParenLoc()))
11424 return;
11425
11426 // Identify common expressions, which are wrongly used as the size argument
11427 // to strncat and may lead to buffer overflows.
11428 unsigned PatternType = 0;
11429 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11430 // - sizeof(dst)
11431 if (referToTheSameDecl(SizeOfArg, DstArg))
11432 PatternType = 1;
11433 // - sizeof(src)
11434 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11435 PatternType = 2;
11436 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11437 if (BE->getOpcode() == BO_Sub) {
11438 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11439 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11440 // - sizeof(dst) - strlen(dst)
11441 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11443 PatternType = 1;
11444 // - sizeof(src) - (anything)
11445 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11446 PatternType = 2;
11447 }
11448 }
11449
11450 if (PatternType == 0)
11451 return;
11452
11453 // Generate the diagnostic.
11454 SourceLocation SL = LenArg->getBeginLoc();
11455 SourceRange SR = LenArg->getSourceRange();
11456 SourceManager &SM = getSourceManager();
11457
11458 // If the function is defined as a builtin macro, do not show macro expansion.
11459 if (SM.isMacroArgExpansion(SL)) {
11460 SL = SM.getSpellingLoc(SL);
11461 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11462 SM.getSpellingLoc(SR.getEnd()));
11463 }
11464
11465 // Check if the destination is an array (rather than a pointer to an array).
11466 QualType DstTy = DstArg->getType();
11467 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11468 Context);
11469 if (!isKnownSizeArray) {
11470 if (PatternType == 1)
11471 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11472 else
11473 Diag(SL, diag::warn_strncat_src_size) << SR;
11474 return;
11475 }
11476
11477 if (PatternType == 1)
11478 Diag(SL, diag::warn_strncat_large_size) << SR;
11479 else
11480 Diag(SL, diag::warn_strncat_src_size) << SR;
11481
11482 SmallString<128> sizeString;
11483 llvm::raw_svector_ostream OS(sizeString);
11484 OS << "sizeof(";
11485 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11486 OS << ") - ";
11487 OS << "strlen(";
11488 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11489 OS << ") - 1";
11490
11491 Diag(SL, diag::note_strncat_wrong_size)
11492 << FixItHint::CreateReplacement(SR, OS.str());
11493}
11494
11495namespace {
11496void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11497 const UnaryOperator *UnaryExpr, const Decl *D) {
11499 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11500 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11501 return;
11502 }
11503}
11504
11505void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11506 const UnaryOperator *UnaryExpr) {
11507 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11508 const Decl *D = Lvalue->getDecl();
11509 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11510 if (!DD->getType()->isReferenceType())
11511 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11512 }
11513 }
11514
11515 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11516 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11517 Lvalue->getMemberDecl());
11518}
11519
11520void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11521 const UnaryOperator *UnaryExpr) {
11522 const auto *Lambda = dyn_cast<LambdaExpr>(
11524 if (!Lambda)
11525 return;
11526
11527 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11528 << CalleeName << 2 /*object: lambda expression*/;
11529}
11530
11531void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11532 const DeclRefExpr *Lvalue) {
11533 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11534 if (Var == nullptr)
11535 return;
11536
11537 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11538 << CalleeName << 0 /*object: */ << Var;
11539}
11540
11541void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11542 const CastExpr *Cast) {
11543 SmallString<128> SizeString;
11544 llvm::raw_svector_ostream OS(SizeString);
11545
11546 clang::CastKind Kind = Cast->getCastKind();
11547 if (Kind == clang::CK_BitCast &&
11548 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11549 return;
11550 if (Kind == clang::CK_IntegralToPointer &&
11552 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11553 return;
11554
11555 switch (Cast->getCastKind()) {
11556 case clang::CK_BitCast:
11557 case clang::CK_IntegralToPointer:
11558 case clang::CK_FunctionToPointerDecay:
11559 OS << '\'';
11560 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11561 OS << '\'';
11562 break;
11563 default:
11564 return;
11565 }
11566
11567 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11568 << CalleeName << 0 /*object: */ << OS.str();
11569}
11570} // namespace
11571
11572void Sema::CheckFreeArguments(const CallExpr *E) {
11573 const std::string CalleeName =
11574 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11575
11576 { // Prefer something that doesn't involve a cast to make things simpler.
11577 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11578 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11579 switch (UnaryExpr->getOpcode()) {
11580 case UnaryOperator::Opcode::UO_AddrOf:
11581 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11582 case UnaryOperator::Opcode::UO_Plus:
11583 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11584 default:
11585 break;
11586 }
11587
11588 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11589 if (Lvalue->getType()->isArrayType())
11590 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11591
11592 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11593 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11594 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11595 return;
11596 }
11597
11598 if (isa<BlockExpr>(Arg)) {
11599 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11600 << CalleeName << 1 /*object: block*/;
11601 return;
11602 }
11603 }
11604 // Maybe the cast was important, check after the other cases.
11605 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11606 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11607}
11608
11609void
11610Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11611 SourceLocation ReturnLoc,
11612 bool isObjCMethod,
11613 const AttrVec *Attrs,
11614 const FunctionDecl *FD) {
11615 // Check if the return value is null but should not be.
11616 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11617 (!isObjCMethod && isNonNullType(lhsType))) &&
11618 CheckNonNullExpr(*this, RetValExp))
11619 Diag(ReturnLoc, diag::warn_null_ret)
11620 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11621
11622 // C++11 [basic.stc.dynamic.allocation]p4:
11623 // If an allocation function declared with a non-throwing
11624 // exception-specification fails to allocate storage, it shall return
11625 // a null pointer. Any other allocation function that fails to allocate
11626 // storage shall indicate failure only by throwing an exception [...]
11627 if (FD) {
11629 if (Op == OO_New || Op == OO_Array_New) {
11630 const FunctionProtoType *Proto
11631 = FD->getType()->castAs<FunctionProtoType>();
11632 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11633 CheckNonNullExpr(*this, RetValExp))
11634 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11635 << FD << getLangOpts().CPlusPlus11;
11636 }
11637 }
11638
11639 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11640 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11641 }
11642
11643 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11644 // here prevent the user from using a PPC MMA type as trailing return type.
11645 if (Context.getTargetInfo().getTriple().isPPC64())
11646 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11647}
11648
11650 const Expr *RHS, BinaryOperatorKind Opcode) {
11651 if (!BinaryOperator::isEqualityOp(Opcode))
11652 return;
11653
11654 // Match and capture subexpressions such as "(float) X == 0.1".
11655 const FloatingLiteral *FPLiteral;
11656 const CastExpr *FPCast;
11657 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11658 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11659 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11660 return FPLiteral && FPCast;
11661 };
11662
11663 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11664 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11665 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11666 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11667 TargetTy->isFloatingPoint()) {
11668 bool Lossy;
11669 llvm::APFloat TargetC = FPLiteral->getValue();
11670 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11671 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11672 if (Lossy) {
11673 // If the literal cannot be represented in the source type, then a
11674 // check for == is always false and check for != is always true.
11675 Diag(Loc, diag::warn_float_compare_literal)
11676 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11677 << LHS->getSourceRange() << RHS->getSourceRange();
11678 return;
11679 }
11680 }
11681 }
11682
11683 // Match a more general floating-point equality comparison (-Wfloat-equal).
11684 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11685 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11686
11687 // Special case: check for x == x (which is OK).
11688 // Do not emit warnings for such cases.
11689 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11690 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11691 if (DRL->getDecl() == DRR->getDecl())
11692 return;
11693
11694 // Special case: check for comparisons against literals that can be exactly
11695 // represented by APFloat. In such cases, do not emit a warning. This
11696 // is a heuristic: often comparison against such literals are used to
11697 // detect if a value in a variable has not changed. This clearly can
11698 // lead to false negatives.
11699 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11700 if (FLL->isExact())
11701 return;
11702 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11703 if (FLR->isExact())
11704 return;
11705
11706 // Check for comparisons with builtin types.
11707 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11708 CL && CL->getBuiltinCallee())
11709 return;
11710
11711 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11712 CR && CR->getBuiltinCallee())
11713 return;
11714
11715 // Emit the diagnostic.
11716 Diag(Loc, diag::warn_floatingpoint_eq)
11717 << LHS->getSourceRange() << RHS->getSourceRange();
11718}
11719
11720//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11721//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11722
11723namespace {
11724
11725/// Structure recording the 'active' range of an integer-valued
11726/// expression.
11727struct IntRange {
11728 /// The number of bits active in the int. Note that this includes exactly one
11729 /// sign bit if !NonNegative.
11730 unsigned Width;
11731
11732 /// True if the int is known not to have negative values. If so, all leading
11733 /// bits before Width are known zero, otherwise they are known to be the
11734 /// same as the MSB within Width.
11735 bool NonNegative;
11736
11737 IntRange(unsigned Width, bool NonNegative)
11738 : Width(Width), NonNegative(NonNegative) {}
11739
11740 /// Number of bits excluding the sign bit.
11741 unsigned valueBits() const {
11742 return NonNegative ? Width : Width - 1;
11743 }
11744
11745 /// Returns the range of the bool type.
11746 static IntRange forBoolType() {
11747 return IntRange(1, true);
11748 }
11749
11750 /// Returns the range of an opaque value of the given integral type.
11751 static IntRange forValueOfType(ASTContext &C, QualType T) {
11752 return forValueOfCanonicalType(C,
11754 }
11755
11756 /// Returns the range of an opaque value of a canonical integral type.
11757 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11758 assert(T->isCanonicalUnqualified());
11759
11760 if (const auto *VT = dyn_cast<VectorType>(T))
11761 T = VT->getElementType().getTypePtr();
11762 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11763 T = MT->getElementType().getTypePtr();
11764 if (const auto *CT = dyn_cast<ComplexType>(T))
11765 T = CT->getElementType().getTypePtr();
11766 if (const auto *AT = dyn_cast<AtomicType>(T))
11767 T = AT->getValueType().getTypePtr();
11768 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11769 T = OBT->getUnderlyingType().getTypePtr();
11770
11771 if (!C.getLangOpts().CPlusPlus) {
11772 // For enum types in C code, use the underlying datatype.
11773 if (const auto *ED = T->getAsEnumDecl())
11774 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11775 } else if (auto *Enum = T->getAsEnumDecl()) {
11776 // For enum types in C++, use the known bit width of the enumerators.
11777 // In C++11, enums can have a fixed underlying type. Use this type to
11778 // compute the range.
11779 if (Enum->isFixed()) {
11780 return IntRange(C.getIntWidth(QualType(T, 0)),
11781 !Enum->getIntegerType()->isSignedIntegerType());
11782 }
11783
11784 unsigned NumPositive = Enum->getNumPositiveBits();
11785 unsigned NumNegative = Enum->getNumNegativeBits();
11786
11787 if (NumNegative == 0)
11788 return IntRange(NumPositive, true/*NonNegative*/);
11789 else
11790 return IntRange(std::max(NumPositive + 1, NumNegative),
11791 false/*NonNegative*/);
11792 }
11793
11794 if (const auto *EIT = dyn_cast<BitIntType>(T))
11795 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11796
11797 const BuiltinType *BT = cast<BuiltinType>(T);
11798 assert(BT->isInteger());
11799
11800 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11801 }
11802
11803 /// Returns the "target" range of a canonical integral type, i.e.
11804 /// the range of values expressible in the type.
11805 ///
11806 /// This matches forValueOfCanonicalType except that enums have the
11807 /// full range of their type, not the range of their enumerators.
11808 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11809 assert(T->isCanonicalUnqualified());
11810
11811 if (const VectorType *VT = dyn_cast<VectorType>(T))
11812 T = VT->getElementType().getTypePtr();
11813 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11814 T = MT->getElementType().getTypePtr();
11815 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11816 T = CT->getElementType().getTypePtr();
11817 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11818 T = AT->getValueType().getTypePtr();
11819 if (const auto *ED = T->getAsEnumDecl())
11820 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11821 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11822 T = OBT->getUnderlyingType().getTypePtr();
11823
11824 if (const auto *EIT = dyn_cast<BitIntType>(T))
11825 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11826
11827 const BuiltinType *BT = cast<BuiltinType>(T);
11828 assert(BT->isInteger());
11829
11830 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11831 }
11832
11833 /// Returns the supremum of two ranges: i.e. their conservative merge.
11834 static IntRange join(IntRange L, IntRange R) {
11835 bool Unsigned = L.NonNegative && R.NonNegative;
11836 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11837 L.NonNegative && R.NonNegative);
11838 }
11839
11840 /// Return the range of a bitwise-AND of the two ranges.
11841 static IntRange bit_and(IntRange L, IntRange R) {
11842 unsigned Bits = std::max(L.Width, R.Width);
11843 bool NonNegative = false;
11844 if (L.NonNegative) {
11845 Bits = std::min(Bits, L.Width);
11846 NonNegative = true;
11847 }
11848 if (R.NonNegative) {
11849 Bits = std::min(Bits, R.Width);
11850 NonNegative = true;
11851 }
11852 return IntRange(Bits, NonNegative);
11853 }
11854
11855 /// Return the range of a sum of the two ranges.
11856 static IntRange sum(IntRange L, IntRange R) {
11857 bool Unsigned = L.NonNegative && R.NonNegative;
11858 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11859 Unsigned);
11860 }
11861
11862 /// Return the range of a difference of the two ranges.
11863 static IntRange difference(IntRange L, IntRange R) {
11864 // We need a 1-bit-wider range if:
11865 // 1) LHS can be negative: least value can be reduced.
11866 // 2) RHS can be negative: greatest value can be increased.
11867 bool CanWiden = !L.NonNegative || !R.NonNegative;
11868 bool Unsigned = L.NonNegative && R.Width == 0;
11869 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11870 !Unsigned,
11871 Unsigned);
11872 }
11873
11874 /// Return the range of a product of the two ranges.
11875 static IntRange product(IntRange L, IntRange R) {
11876 // If both LHS and RHS can be negative, we can form
11877 // -2^L * -2^R = 2^(L + R)
11878 // which requires L + R + 1 value bits to represent.
11879 bool CanWiden = !L.NonNegative && !R.NonNegative;
11880 bool Unsigned = L.NonNegative && R.NonNegative;
11881 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11882 Unsigned);
11883 }
11884
11885 /// Return the range of a remainder operation between the two ranges.
11886 static IntRange rem(IntRange L, IntRange R) {
11887 // The result of a remainder can't be larger than the result of
11888 // either side. The sign of the result is the sign of the LHS.
11889 bool Unsigned = L.NonNegative;
11890 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11891 Unsigned);
11892 }
11893};
11894
11895} // namespace
11896
11897static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11898 if (value.isSigned() && value.isNegative())
11899 return IntRange(value.getSignificantBits(), false);
11900
11901 if (value.getBitWidth() > MaxWidth)
11902 value = value.trunc(MaxWidth);
11903
11904 // isNonNegative() just checks the sign bit without considering
11905 // signedness.
11906 return IntRange(value.getActiveBits(), true);
11907}
11908
11909static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11910 if (result.isInt())
11911 return GetValueRange(result.getInt(), MaxWidth);
11912
11913 if (result.isVector()) {
11914 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11915 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11916 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11917 R = IntRange::join(R, El);
11918 }
11919 return R;
11920 }
11921
11922 if (result.isComplexInt()) {
11923 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11924 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11925 return IntRange::join(R, I);
11926 }
11927
11928 // This can happen with lossless casts to intptr_t of "based" lvalues.
11929 // Assume it might use arbitrary bits.
11930 // FIXME: The only reason we need to pass the type in here is to get
11931 // the sign right on this one case. It would be nice if APValue
11932 // preserved this.
11933 assert(result.isLValue() || result.isAddrLabelDiff());
11934 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11935}
11936
11937static QualType GetExprType(const Expr *E) {
11938 QualType Ty = E->getType();
11939 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11940 Ty = AtomicRHS->getValueType();
11941 return Ty;
11942}
11943
11944/// Attempts to estimate an approximate range for the given integer expression.
11945/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11946/// reliable estimation cannot be determined.
11947///
11948/// \param MaxWidth The width to which the value will be truncated.
11949/// \param InConstantContext If \c true, interpret the expression within a
11950/// constant context.
11951/// \param Approximate If \c true, provide a likely range of values by assuming
11952/// that arithmetic on narrower types remains within those types.
11953/// If \c false, return a range that includes all possible values
11954/// resulting from the expression.
11955/// \returns A range of values that the expression might take, or
11956/// std::nullopt if a reliable estimation cannot be determined.
11957static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11958 unsigned MaxWidth,
11959 bool InConstantContext,
11960 bool Approximate) {
11961 E = E->IgnoreParens();
11962
11963 // Try a full evaluation first.
11964 Expr::EvalResult result;
11965 if (E->EvaluateAsRValue(result, C, InConstantContext))
11966 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11967
11968 // I think we only want to look through implicit casts here; if the
11969 // user has an explicit widening cast, we should treat the value as
11970 // being of the new, wider type.
11971 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11972 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11973 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11974 Approximate);
11975
11976 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11977
11978 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11979 CE->getCastKind() == CK_BooleanToSignedIntegral;
11980
11981 // Assume that non-integer casts can span the full range of the type.
11982 if (!isIntegerCast)
11983 return OutputTypeRange;
11984
11985 std::optional<IntRange> SubRange = TryGetExprRange(
11986 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11987 InConstantContext, Approximate);
11988 if (!SubRange)
11989 return std::nullopt;
11990
11991 // Bail out if the subexpr's range is as wide as the cast type.
11992 if (SubRange->Width >= OutputTypeRange.Width)
11993 return OutputTypeRange;
11994
11995 // Otherwise, we take the smaller width, and we're non-negative if
11996 // either the output type or the subexpr is.
11997 return IntRange(SubRange->Width,
11998 SubRange->NonNegative || OutputTypeRange.NonNegative);
11999 }
12000
12001 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12002 // If we can fold the condition, just take that operand.
12003 bool CondResult;
12004 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12005 return TryGetExprRange(
12006 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12007 InConstantContext, Approximate);
12008
12009 // Otherwise, conservatively merge.
12010 // TryGetExprRange requires an integer expression, but a throw expression
12011 // results in a void type.
12012 Expr *TrueExpr = CO->getTrueExpr();
12013 if (TrueExpr->getType()->isVoidType())
12014 return std::nullopt;
12015
12016 std::optional<IntRange> L =
12017 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
12018 if (!L)
12019 return std::nullopt;
12020
12021 Expr *FalseExpr = CO->getFalseExpr();
12022 if (FalseExpr->getType()->isVoidType())
12023 return std::nullopt;
12024
12025 std::optional<IntRange> R =
12026 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
12027 if (!R)
12028 return std::nullopt;
12029
12030 return IntRange::join(*L, *R);
12031 }
12032
12033 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12034 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12035
12036 switch (BO->getOpcode()) {
12037 case BO_Cmp:
12038 llvm_unreachable("builtin <=> should have class type");
12039
12040 // Boolean-valued operations are single-bit and positive.
12041 case BO_LAnd:
12042 case BO_LOr:
12043 case BO_LT:
12044 case BO_GT:
12045 case BO_LE:
12046 case BO_GE:
12047 case BO_EQ:
12048 case BO_NE:
12049 return IntRange::forBoolType();
12050
12051 // The type of the assignments is the type of the LHS, so the RHS
12052 // is not necessarily the same type.
12053 case BO_MulAssign:
12054 case BO_DivAssign:
12055 case BO_RemAssign:
12056 case BO_AddAssign:
12057 case BO_SubAssign:
12058 case BO_XorAssign:
12059 case BO_OrAssign:
12060 // TODO: bitfields?
12061 return IntRange::forValueOfType(C, GetExprType(E));
12062
12063 // Simple assignments just pass through the RHS, which will have
12064 // been coerced to the LHS type.
12065 case BO_Assign:
12066 // TODO: bitfields?
12067 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12068 Approximate);
12069
12070 // Operations with opaque sources are black-listed.
12071 case BO_PtrMemD:
12072 case BO_PtrMemI:
12073 return IntRange::forValueOfType(C, GetExprType(E));
12074
12075 // Bitwise-and uses the *infinum* of the two source ranges.
12076 case BO_And:
12077 case BO_AndAssign:
12078 Combine = IntRange::bit_and;
12079 break;
12080
12081 // Left shift gets black-listed based on a judgement call.
12082 case BO_Shl:
12083 // ...except that we want to treat '1 << (blah)' as logically
12084 // positive. It's an important idiom.
12085 if (IntegerLiteral *I
12086 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12087 if (I->getValue() == 1) {
12088 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12089 return IntRange(R.Width, /*NonNegative*/ true);
12090 }
12091 }
12092 [[fallthrough]];
12093
12094 case BO_ShlAssign:
12095 return IntRange::forValueOfType(C, GetExprType(E));
12096
12097 // Right shift by a constant can narrow its left argument.
12098 case BO_Shr:
12099 case BO_ShrAssign: {
12100 std::optional<IntRange> L = TryGetExprRange(
12101 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12102 if (!L)
12103 return std::nullopt;
12104
12105 // If the shift amount is a positive constant, drop the width by
12106 // that much.
12107 if (std::optional<llvm::APSInt> shift =
12108 BO->getRHS()->getIntegerConstantExpr(C)) {
12109 if (shift->isNonNegative()) {
12110 if (shift->uge(L->Width))
12111 L->Width = (L->NonNegative ? 0 : 1);
12112 else
12113 L->Width -= shift->getZExtValue();
12114 }
12115 }
12116
12117 return L;
12118 }
12119
12120 // Comma acts as its right operand.
12121 case BO_Comma:
12122 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12123 Approximate);
12124
12125 case BO_Add:
12126 if (!Approximate)
12127 Combine = IntRange::sum;
12128 break;
12129
12130 case BO_Sub:
12131 if (BO->getLHS()->getType()->isPointerType())
12132 return IntRange::forValueOfType(C, GetExprType(E));
12133 if (!Approximate)
12134 Combine = IntRange::difference;
12135 break;
12136
12137 case BO_Mul:
12138 if (!Approximate)
12139 Combine = IntRange::product;
12140 break;
12141
12142 // The width of a division result is mostly determined by the size
12143 // of the LHS.
12144 case BO_Div: {
12145 // Don't 'pre-truncate' the operands.
12146 unsigned opWidth = C.getIntWidth(GetExprType(E));
12147 std::optional<IntRange> L = TryGetExprRange(
12148 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12149 if (!L)
12150 return std::nullopt;
12151
12152 // If the divisor is constant, use that.
12153 if (std::optional<llvm::APSInt> divisor =
12154 BO->getRHS()->getIntegerConstantExpr(C)) {
12155 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12156 if (log2 >= L->Width)
12157 L->Width = (L->NonNegative ? 0 : 1);
12158 else
12159 L->Width = std::min(L->Width - log2, MaxWidth);
12160 return L;
12161 }
12162
12163 // Otherwise, just use the LHS's width.
12164 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12165 // could be -1.
12166 std::optional<IntRange> R = TryGetExprRange(
12167 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12168 if (!R)
12169 return std::nullopt;
12170
12171 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12172 }
12173
12174 case BO_Rem:
12175 Combine = IntRange::rem;
12176 break;
12177
12178 // The default behavior is okay for these.
12179 case BO_Xor:
12180 case BO_Or:
12181 break;
12182 }
12183
12184 // Combine the two ranges, but limit the result to the type in which we
12185 // performed the computation.
12186 QualType T = GetExprType(E);
12187 unsigned opWidth = C.getIntWidth(T);
12188 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12189 InConstantContext, Approximate);
12190 if (!L)
12191 return std::nullopt;
12192
12193 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12194 InConstantContext, Approximate);
12195 if (!R)
12196 return std::nullopt;
12197
12198 IntRange C = Combine(*L, *R);
12199 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12200 C.Width = std::min(C.Width, MaxWidth);
12201 return C;
12202 }
12203
12204 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12205 switch (UO->getOpcode()) {
12206 // Boolean-valued operations are white-listed.
12207 case UO_LNot:
12208 return IntRange::forBoolType();
12209
12210 // Operations with opaque sources are black-listed.
12211 case UO_Deref:
12212 case UO_AddrOf: // should be impossible
12213 return IntRange::forValueOfType(C, GetExprType(E));
12214
12215 case UO_Minus: {
12216 if (E->getType()->isUnsignedIntegerType()) {
12217 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12218 Approximate);
12219 }
12220
12221 std::optional<IntRange> SubRange = TryGetExprRange(
12222 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12223
12224 if (!SubRange)
12225 return std::nullopt;
12226
12227 // If the range was previously non-negative, we need an extra bit for the
12228 // sign bit. Otherwise, we need an extra bit because the negation of the
12229 // most-negative value is one bit wider than that value.
12230 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12231 }
12232
12233 case UO_Not: {
12234 if (E->getType()->isUnsignedIntegerType()) {
12235 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12236 Approximate);
12237 }
12238
12239 std::optional<IntRange> SubRange = TryGetExprRange(
12240 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12241
12242 if (!SubRange)
12243 return std::nullopt;
12244
12245 // The width increments by 1 if the sub-expression cannot be negative
12246 // since it now can be.
12247 return IntRange(
12248 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12249 false);
12250 }
12251
12252 default:
12253 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12254 Approximate);
12255 }
12256 }
12257
12258 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12259 // The source expression is null for the OpaqueValueExpr that stands in for
12260 // a non-type template argument of pointer or reference type; fall back to
12261 // the range of the type in that case.
12262 if (const Expr *SourceExpr = OVE->getSourceExpr())
12263 return TryGetExprRange(C, SourceExpr, MaxWidth, InConstantContext,
12264 Approximate);
12265 }
12266
12267 if (const auto *BitField = E->getSourceBitField())
12268 return IntRange(BitField->getBitWidthValue(),
12269 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12270
12271 if (GetExprType(E)->isVoidType())
12272 return std::nullopt;
12273
12274 return IntRange::forValueOfType(C, GetExprType(E));
12275}
12276
12277static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12278 bool InConstantContext,
12279 bool Approximate) {
12280 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12281 Approximate);
12282}
12283
12284/// Checks whether the given value, which currently has the given
12285/// source semantics, has the same value when coerced through the
12286/// target semantics.
12287static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12288 const llvm::fltSemantics &Src,
12289 const llvm::fltSemantics &Tgt) {
12290 llvm::APFloat truncated = value;
12291
12292 bool ignored;
12293 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12294 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12295
12296 return truncated.bitwiseIsEqual(value);
12297}
12298
12299/// Checks whether the given value, which currently has the given
12300/// source semantics, has the same value when coerced through the
12301/// target semantics.
12302///
12303/// The value might be a vector of floats (or a complex number).
12304static bool IsSameFloatAfterCast(const APValue &value,
12305 const llvm::fltSemantics &Src,
12306 const llvm::fltSemantics &Tgt) {
12307 if (value.isFloat())
12308 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12309
12310 if (value.isVector()) {
12311 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12312 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12313 return false;
12314 return true;
12315 }
12316
12317 if (value.isMatrix()) {
12318 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12319 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12320 return false;
12321 return true;
12322 }
12323
12324 assert(value.isComplexFloat());
12325 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12326 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12327}
12328
12329static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12330 bool IsListInit = false);
12331
12332static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12333 // Suppress cases where we are comparing against an enum constant.
12334 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12335 if (isa<EnumConstantDecl>(DR->getDecl()))
12336 return true;
12337
12338 // Suppress cases where the value is expanded from a macro, unless that macro
12339 // is how a language represents a boolean literal. This is the case in both C
12340 // and Objective-C.
12341 SourceLocation BeginLoc = E->getBeginLoc();
12342 if (BeginLoc.isMacroID()) {
12343 StringRef MacroName = Lexer::getImmediateMacroName(
12344 BeginLoc, S.getSourceManager(), S.getLangOpts());
12345 return MacroName != "YES" && MacroName != "NO" &&
12346 MacroName != "true" && MacroName != "false";
12347 }
12348
12349 return false;
12350}
12351
12352static bool isKnownToHaveUnsignedValue(const Expr *E) {
12353 return E->getType()->isIntegerType() &&
12354 (!E->getType()->isSignedIntegerType() ||
12356}
12357
12358namespace {
12359/// The promoted range of values of a type. In general this has the
12360/// following structure:
12361///
12362/// |-----------| . . . |-----------|
12363/// ^ ^ ^ ^
12364/// Min HoleMin HoleMax Max
12365///
12366/// ... where there is only a hole if a signed type is promoted to unsigned
12367/// (in which case Min and Max are the smallest and largest representable
12368/// values).
12369struct PromotedRange {
12370 // Min, or HoleMax if there is a hole.
12371 llvm::APSInt PromotedMin;
12372 // Max, or HoleMin if there is a hole.
12373 llvm::APSInt PromotedMax;
12374
12375 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12376 if (R.Width == 0)
12377 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12378 else if (R.Width >= BitWidth && !Unsigned) {
12379 // Promotion made the type *narrower*. This happens when promoting
12380 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12381 // Treat all values of 'signed int' as being in range for now.
12382 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12383 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12384 } else {
12385 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12386 .extOrTrunc(BitWidth);
12387 PromotedMin.setIsUnsigned(Unsigned);
12388
12389 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12390 .extOrTrunc(BitWidth);
12391 PromotedMax.setIsUnsigned(Unsigned);
12392 }
12393 }
12394
12395 // Determine whether this range is contiguous (has no hole).
12396 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12397
12398 // Where a constant value is within the range.
12399 enum ComparisonResult {
12400 LT = 0x1,
12401 LE = 0x2,
12402 GT = 0x4,
12403 GE = 0x8,
12404 EQ = 0x10,
12405 NE = 0x20,
12406 InRangeFlag = 0x40,
12407
12408 Less = LE | LT | NE,
12409 Min = LE | InRangeFlag,
12410 InRange = InRangeFlag,
12411 Max = GE | InRangeFlag,
12412 Greater = GE | GT | NE,
12413
12414 OnlyValue = LE | GE | EQ | InRangeFlag,
12415 InHole = NE
12416 };
12417
12418 ComparisonResult compare(const llvm::APSInt &Value) const {
12419 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12420 Value.isUnsigned() == PromotedMin.isUnsigned());
12421 if (!isContiguous()) {
12422 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12423 if (Value.isMinValue()) return Min;
12424 if (Value.isMaxValue()) return Max;
12425 if (Value >= PromotedMin) return InRange;
12426 if (Value <= PromotedMax) return InRange;
12427 return InHole;
12428 }
12429
12430 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12431 case -1: return Less;
12432 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12433 case 1:
12434 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12435 case -1: return InRange;
12436 case 0: return Max;
12437 case 1: return Greater;
12438 }
12439 }
12440
12441 llvm_unreachable("impossible compare result");
12442 }
12443
12444 static std::optional<StringRef>
12445 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12446 if (Op == BO_Cmp) {
12447 ComparisonResult LTFlag = LT, GTFlag = GT;
12448 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12449
12450 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12451 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12452 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12453 return std::nullopt;
12454 }
12455
12456 ComparisonResult TrueFlag, FalseFlag;
12457 if (Op == BO_EQ) {
12458 TrueFlag = EQ;
12459 FalseFlag = NE;
12460 } else if (Op == BO_NE) {
12461 TrueFlag = NE;
12462 FalseFlag = EQ;
12463 } else {
12464 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12465 TrueFlag = LT;
12466 FalseFlag = GE;
12467 } else {
12468 TrueFlag = GT;
12469 FalseFlag = LE;
12470 }
12471 if (Op == BO_GE || Op == BO_LE)
12472 std::swap(TrueFlag, FalseFlag);
12473 }
12474 if (R & TrueFlag)
12475 return StringRef("true");
12476 if (R & FalseFlag)
12477 return StringRef("false");
12478 return std::nullopt;
12479 }
12480};
12481}
12482
12483static bool HasEnumType(const Expr *E) {
12484 // Strip off implicit integral promotions.
12485 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12486 if (ICE->getCastKind() != CK_IntegralCast &&
12487 ICE->getCastKind() != CK_NoOp)
12488 break;
12489 E = ICE->getSubExpr();
12490 }
12491
12492 return E->getType()->isEnumeralType();
12493}
12494
12496 // The values of this enumeration are used in the diagnostics
12497 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12498 enum ConstantValueKind {
12499 Miscellaneous = 0,
12500 LiteralTrue,
12501 LiteralFalse
12502 };
12503 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12504 return BL->getValue() ? ConstantValueKind::LiteralTrue
12505 : ConstantValueKind::LiteralFalse;
12506 return ConstantValueKind::Miscellaneous;
12507}
12508
12511 const llvm::APSInt &Value,
12512 bool RhsConstant) {
12514 return false;
12515
12516 Expr *OriginalOther = Other;
12517
12518 Constant = Constant->IgnoreParenImpCasts();
12519 Other = Other->IgnoreParenImpCasts();
12520
12521 // Suppress warnings on tautological comparisons between values of the same
12522 // enumeration type. There are only two ways we could warn on this:
12523 // - If the constant is outside the range of representable values of
12524 // the enumeration. In such a case, we should warn about the cast
12525 // to enumeration type, not about the comparison.
12526 // - If the constant is the maximum / minimum in-range value. For an
12527 // enumeratin type, such comparisons can be meaningful and useful.
12528 if (Constant->getType()->isEnumeralType() &&
12529 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12530 return false;
12531
12532 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12533 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12534 if (!OtherValueRange)
12535 return false;
12536
12537 QualType OtherT = Other->getType();
12538 if (const auto *AT = OtherT->getAs<AtomicType>())
12539 OtherT = AT->getValueType();
12540 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12541
12542 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12543 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12544 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12545 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12546 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12547
12548 // Whether we're treating Other as being a bool because of the form of
12549 // expression despite it having another type (typically 'int' in C).
12550 bool OtherIsBooleanDespiteType =
12551 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12552 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12553 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12554
12555 // Check if all values in the range of possible values of this expression
12556 // lead to the same comparison outcome.
12557 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12558 Value.isUnsigned());
12559 auto Cmp = OtherPromotedValueRange.compare(Value);
12560 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12561 if (!Result)
12562 return false;
12563
12564 // Also consider the range determined by the type alone. This allows us to
12565 // classify the warning under the proper diagnostic group.
12566 bool TautologicalTypeCompare = false;
12567 {
12568 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12569 Value.isUnsigned());
12570 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12571 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12572 RhsConstant)) {
12573 TautologicalTypeCompare = true;
12574 Cmp = TypeCmp;
12576 }
12577 }
12578
12579 // Don't warn if the non-constant operand actually always evaluates to the
12580 // same value.
12581 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12582 return false;
12583
12584 // Suppress the diagnostic for an in-range comparison if the constant comes
12585 // from a macro or enumerator. We don't want to diagnose
12586 //
12587 // some_long_value <= INT_MAX
12588 //
12589 // when sizeof(int) == sizeof(long).
12590 bool InRange = Cmp & PromotedRange::InRangeFlag;
12591 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12592 return false;
12593
12594 // A comparison of an unsigned bit-field against 0 is really a type problem,
12595 // even though at the type level the bit-field might promote to 'signed int'.
12596 if (Other->refersToBitField() && InRange && Value == 0 &&
12597 Other->getType()->isUnsignedIntegerOrEnumerationType())
12598 TautologicalTypeCompare = true;
12599
12600 // If this is a comparison to an enum constant, include that
12601 // constant in the diagnostic.
12602 const EnumConstantDecl *ED = nullptr;
12603 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12604 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12605
12606 // Should be enough for uint128 (39 decimal digits)
12607 SmallString<64> PrettySourceValue;
12608 llvm::raw_svector_ostream OS(PrettySourceValue);
12609 if (ED) {
12610 OS << '\'' << *ED << "' (" << Value << ")";
12611 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12612 Constant->IgnoreParenImpCasts())) {
12613 OS << (BL->getValue() ? "YES" : "NO");
12614 } else {
12615 OS << Value;
12616 }
12617
12618 if (!TautologicalTypeCompare) {
12619 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12620 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12621 << E->getOpcodeStr() << OS.str() << *Result
12622 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12623 return true;
12624 }
12625
12626 if (IsObjCSignedCharBool) {
12628 S.PDiag(diag::warn_tautological_compare_objc_bool)
12629 << OS.str() << *Result);
12630 return true;
12631 }
12632
12633 // FIXME: We use a somewhat different formatting for the in-range cases and
12634 // cases involving boolean values for historical reasons. We should pick a
12635 // consistent way of presenting these diagnostics.
12636 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12637
12639 E->getOperatorLoc(), E,
12640 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12641 : diag::warn_tautological_bool_compare)
12642 << OS.str() << classifyConstantValue(Constant) << OtherT
12643 << OtherIsBooleanDespiteType << *Result
12644 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12645 } else {
12646 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12647 unsigned Diag =
12648 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12649 ? (HasEnumType(OriginalOther)
12650 ? diag::warn_unsigned_enum_always_true_comparison
12651 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12652 : diag::warn_unsigned_always_true_comparison)
12653 : diag::warn_tautological_constant_compare;
12654
12655 S.Diag(E->getOperatorLoc(), Diag)
12656 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12657 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12658 }
12659
12660 return true;
12661}
12662
12663/// Analyze the operands of the given comparison. Implements the
12664/// fallback case from AnalyzeComparison.
12669
12670/// Implements -Wsign-compare.
12671///
12672/// \param E the binary operator to check for warnings
12674 // The type the comparison is being performed in.
12675 QualType T = E->getLHS()->getType();
12676
12677 // Only analyze comparison operators where both sides have been converted to
12678 // the same type.
12680 return AnalyzeImpConvsInComparison(S, E);
12681
12682 // Don't analyze value-dependent comparisons directly.
12683 if (E->isValueDependent())
12684 return AnalyzeImpConvsInComparison(S, E);
12685
12686 Expr *LHS = E->getLHS();
12687 Expr *RHS = E->getRHS();
12688
12689 if (T->isIntegralType(S.Context)) {
12690 std::optional<llvm::APSInt> RHSValue =
12692 std::optional<llvm::APSInt> LHSValue =
12694
12695 // We don't care about expressions whose result is a constant.
12696 if (RHSValue && LHSValue)
12697 return AnalyzeImpConvsInComparison(S, E);
12698
12699 // We only care about expressions where just one side is literal
12700 if ((bool)RHSValue ^ (bool)LHSValue) {
12701 // Is the constant on the RHS or LHS?
12702 const bool RhsConstant = (bool)RHSValue;
12703 Expr *Const = RhsConstant ? RHS : LHS;
12704 Expr *Other = RhsConstant ? LHS : RHS;
12705 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12706
12707 // Check whether an integer constant comparison results in a value
12708 // of 'true' or 'false'.
12709 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12710 return AnalyzeImpConvsInComparison(S, E);
12711 }
12712 }
12713
12714 if (!T->hasUnsignedIntegerRepresentation()) {
12715 // We don't do anything special if this isn't an unsigned integral
12716 // comparison: we're only interested in integral comparisons, and
12717 // signed comparisons only happen in cases we don't care to warn about.
12718 return AnalyzeImpConvsInComparison(S, E);
12719 }
12720
12721 LHS = LHS->IgnoreParenImpCasts();
12722 RHS = RHS->IgnoreParenImpCasts();
12723
12724 if (!S.getLangOpts().CPlusPlus) {
12725 // Avoid warning about comparison of integers with different signs when
12726 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12727 // the type of `E`.
12728 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12729 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12730 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12731 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12732 }
12733
12734 // Check to see if one of the (unmodified) operands is of different
12735 // signedness.
12736 Expr *signedOperand, *unsignedOperand;
12738 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12739 "unsigned comparison between two signed integer expressions?");
12740 signedOperand = LHS;
12741 unsignedOperand = RHS;
12742 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12743 signedOperand = RHS;
12744 unsignedOperand = LHS;
12745 } else {
12746 return AnalyzeImpConvsInComparison(S, E);
12747 }
12748
12749 // Otherwise, calculate the effective range of the signed operand.
12750 std::optional<IntRange> signedRange =
12752 /*Approximate=*/true);
12753 if (!signedRange)
12754 return;
12755
12756 // Go ahead and analyze implicit conversions in the operands. Note
12757 // that we skip the implicit conversions on both sides.
12760
12761 // If the signed range is non-negative, -Wsign-compare won't fire.
12762 if (signedRange->NonNegative)
12763 return;
12764
12765 // For (in)equality comparisons, if the unsigned operand is a
12766 // constant which cannot collide with a overflowed signed operand,
12767 // then reinterpreting the signed operand as unsigned will not
12768 // change the result of the comparison.
12769 if (E->isEqualityOp()) {
12770 unsigned comparisonWidth = S.Context.getIntWidth(T);
12771 std::optional<IntRange> unsignedRange = TryGetExprRange(
12772 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12773 /*Approximate=*/true);
12774 if (!unsignedRange)
12775 return;
12776
12777 // We should never be unable to prove that the unsigned operand is
12778 // non-negative.
12779 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12780
12781 if (unsignedRange->Width < comparisonWidth)
12782 return;
12783 }
12784
12786 S.PDiag(diag::warn_mixed_sign_comparison)
12787 << LHS->getType() << RHS->getType()
12788 << LHS->getSourceRange() << RHS->getSourceRange());
12789}
12790
12791/// Analyzes an attempt to assign the given value to a bitfield.
12792///
12793/// Returns true if there was something fishy about the attempt.
12795 SourceLocation InitLoc) {
12796 assert(Bitfield->isBitField());
12797 if (Bitfield->isInvalidDecl())
12798 return false;
12799
12800 // White-list bool bitfields.
12801 QualType BitfieldType = Bitfield->getType();
12802 if (BitfieldType->isBooleanType())
12803 return false;
12804
12805 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12806 // If the underlying enum type was not explicitly specified as an unsigned
12807 // type and the enum contain only positive values, MSVC++ will cause an
12808 // inconsistency by storing this as a signed type.
12809 if (S.getLangOpts().CPlusPlus11 &&
12810 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12811 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12812 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12813 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12814 << BitfieldEnumDecl;
12815 }
12816 }
12817
12818 // Ignore value- or type-dependent expressions.
12819 if (Bitfield->getBitWidth()->isValueDependent() ||
12820 Bitfield->getBitWidth()->isTypeDependent() ||
12821 Init->isValueDependent() ||
12822 Init->isTypeDependent())
12823 return false;
12824
12825 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12826 unsigned FieldWidth = Bitfield->getBitWidthValue();
12827
12829 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12831 // The RHS is not constant. If the RHS has an enum type, make sure the
12832 // bitfield is wide enough to hold all the values of the enum without
12833 // truncation.
12834 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12835 const PreferredTypeAttr *PTAttr = nullptr;
12836 if (!ED) {
12837 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12838 if (PTAttr)
12839 ED = PTAttr->getType()->getAsEnumDecl();
12840 }
12841 if (ED) {
12842 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12843
12844 // Enum types are implicitly signed on Windows, so check if there are any
12845 // negative enumerators to see if the enum was intended to be signed or
12846 // not.
12847 bool SignedEnum = ED->getNumNegativeBits() > 0;
12848
12849 // Check for surprising sign changes when assigning enum values to a
12850 // bitfield of different signedness. If the bitfield is signed and we
12851 // have exactly the right number of bits to store this unsigned enum,
12852 // suggest changing the enum to an unsigned type. This typically happens
12853 // on Windows where unfixed enums always use an underlying type of 'int'.
12854 unsigned DiagID = 0;
12855 if (SignedEnum && !SignedBitfield) {
12856 DiagID =
12857 PTAttr == nullptr
12858 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12859 : diag::
12860 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12861 } else if (SignedBitfield && !SignedEnum &&
12862 ED->getNumPositiveBits() == FieldWidth) {
12863 DiagID =
12864 PTAttr == nullptr
12865 ? diag::warn_signed_bitfield_enum_conversion
12866 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12867 }
12868 if (DiagID) {
12869 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12870 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12871 SourceRange TypeRange =
12872 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12873 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12874 << SignedEnum << TypeRange;
12875 if (PTAttr)
12876 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12877 << ED;
12878 }
12879
12880 // Compute the required bitwidth. If the enum has negative values, we need
12881 // one more bit than the normal number of positive bits to represent the
12882 // sign bit.
12883 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12884 ED->getNumNegativeBits())
12885 : ED->getNumPositiveBits();
12886
12887 // Check the bitwidth.
12888 if (BitsNeeded > FieldWidth) {
12889 Expr *WidthExpr = Bitfield->getBitWidth();
12890 auto DiagID =
12891 PTAttr == nullptr
12892 ? diag::warn_bitfield_too_small_for_enum
12893 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12894 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12895 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12896 << BitsNeeded << ED << WidthExpr->getSourceRange();
12897 if (PTAttr)
12898 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12899 << ED;
12900 }
12901 }
12902
12903 return false;
12904 }
12905
12906 llvm::APSInt Value = Result.Val.getInt();
12907
12908 unsigned OriginalWidth = Value.getBitWidth();
12909
12910 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12911 // false positives where the user is demonstrating they intend to use the
12912 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12913 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12914 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12915 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12916 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12917 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12918 S.findMacroSpelling(MaybeMacroLoc, "true"))
12919 return false;
12920 }
12921
12922 if (!Value.isSigned() || Value.isNegative())
12923 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12924 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12925 OriginalWidth = Value.getSignificantBits();
12926
12927 if (OriginalWidth <= FieldWidth)
12928 return false;
12929
12930 // Compute the value which the bitfield will contain.
12931 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12932 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12933
12934 // Check whether the stored value is equal to the original value.
12935 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12936 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12937 return false;
12938
12939 std::string PrettyValue = toString(Value, 10);
12940 std::string PrettyTrunc = toString(TruncatedValue, 10);
12941
12942 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12943 ? diag::warn_impcast_single_bit_bitield_precision_constant
12944 : diag::warn_impcast_bitfield_precision_constant)
12945 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12946 << Init->getSourceRange();
12947
12948 return true;
12949}
12950
12951/// Analyze the given simple or compound assignment for warning-worthy
12952/// operations.
12954 // Just recurse on the LHS.
12956
12957 // We want to recurse on the RHS as normal unless we're assigning to
12958 // a bitfield.
12959 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12960 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12961 E->getOperatorLoc())) {
12962 // Recurse, ignoring any implicit conversions on the RHS.
12964 E->getOperatorLoc());
12965 }
12966 }
12967
12968 // Set context flag for overflow behavior type assignment analysis, use RAII
12969 // pattern to handle nested assignments.
12970 llvm::SaveAndRestore OBTAssignmentContext(
12972
12974
12975 // Diagnose implicitly sequentially-consistent atomic assignment.
12976 if (E->getLHS()->getType()->isAtomicType())
12977 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12978}
12979
12980/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12981static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12982 QualType T, SourceLocation CContext, unsigned diag,
12983 bool PruneControlFlow = false) {
12984 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12985 // address space annotations isn't really useful. The warnings aren't because
12986 // you're converting a `private int` to `unsigned int`, it is because you're
12987 // conerting `int` to `unsigned int`.
12988 if (SourceType.hasAddressSpace())
12989 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12990 if (T.hasAddressSpace())
12992 if (PruneControlFlow) {
12994 S.PDiag(diag)
12995 << SourceType << T << E->getSourceRange()
12996 << SourceRange(CContext));
12997 return;
12998 }
12999 S.Diag(E->getExprLoc(), diag)
13000 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13001}
13002
13003/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13004static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13005 SourceLocation CContext, unsigned diag,
13006 bool PruneControlFlow = false) {
13007 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
13008}
13009
13010/// Diagnose an implicit cast from a floating point value to an integer value.
13011static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13012 SourceLocation CContext) {
13013 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13014 bool PruneWarnings = S.inTemplateInstantiation();
13015
13016 const Expr *InnerE = E->IgnoreParenImpCasts();
13017 // We also want to warn on, e.g., "int i = -1.234"
13018 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13019 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13020 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13021
13022 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13023
13024 llvm::APFloat Value(0.0);
13025 bool IsConstant =
13027 if (!IsConstant) {
13028 if (S.ObjC().isSignedCharBool(T)) {
13030 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13031 << E->getType());
13032 }
13033
13034 return DiagnoseImpCast(S, E, T, CContext,
13035 diag::warn_impcast_float_integer, PruneWarnings);
13036 }
13037
13038 bool isExact = false;
13039
13040 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13041 T->hasUnsignedIntegerRepresentation());
13042 llvm::APFloat::opStatus Result = Value.convertToInteger(
13043 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13044
13045 // FIXME: Force the precision of the source value down so we don't print
13046 // digits which are usually useless (we don't really care here if we
13047 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13048 // would automatically print the shortest representation, but it's a bit
13049 // tricky to implement.
13050 SmallString<16> PrettySourceValue;
13051 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13052 precision = (precision * 59 + 195) / 196;
13053 Value.toString(PrettySourceValue, precision);
13054
13055 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
13057 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13058 << PrettySourceValue);
13059 }
13060
13061 if (Result == llvm::APFloat::opOK && isExact) {
13062 if (IsLiteral) return;
13063 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13064 PruneWarnings);
13065 }
13066
13067 // Conversion of a floating-point value to a non-bool integer where the
13068 // integral part cannot be represented by the integer type is undefined.
13069 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13070 return DiagnoseImpCast(
13071 S, E, T, CContext,
13072 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13073 : diag::warn_impcast_float_to_integer_out_of_range,
13074 PruneWarnings);
13075
13076 unsigned DiagID = 0;
13077 if (IsLiteral) {
13078 // Warn on floating point literal to integer.
13079 DiagID = diag::warn_impcast_literal_float_to_integer;
13080 } else if (IntegerValue == 0) {
13081 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13082 return DiagnoseImpCast(S, E, T, CContext,
13083 diag::warn_impcast_float_integer, PruneWarnings);
13084 }
13085 // Warn on non-zero to zero conversion.
13086 DiagID = diag::warn_impcast_float_to_integer_zero;
13087 } else {
13088 if (IntegerValue.isUnsigned()) {
13089 if (!IntegerValue.isMaxValue()) {
13090 return DiagnoseImpCast(S, E, T, CContext,
13091 diag::warn_impcast_float_integer, PruneWarnings);
13092 }
13093 } else { // IntegerValue.isSigned()
13094 if (!IntegerValue.isMaxSignedValue() &&
13095 !IntegerValue.isMinSignedValue()) {
13096 return DiagnoseImpCast(S, E, T, CContext,
13097 diag::warn_impcast_float_integer, PruneWarnings);
13098 }
13099 }
13100 // Warn on evaluatable floating point expression to integer conversion.
13101 DiagID = diag::warn_impcast_float_to_integer;
13102 }
13103
13104 SmallString<16> PrettyTargetValue;
13105 if (IsBool)
13106 PrettyTargetValue = Value.isZero() ? "false" : "true";
13107 else
13108 IntegerValue.toString(PrettyTargetValue);
13109
13110 if (PruneWarnings) {
13112 S.PDiag(DiagID)
13113 << E->getType() << T.getUnqualifiedType()
13114 << PrettySourceValue << PrettyTargetValue
13115 << E->getSourceRange() << SourceRange(CContext));
13116 } else {
13117 S.Diag(E->getExprLoc(), DiagID)
13118 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13119 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13120 }
13121}
13122
13123/// Analyze the given compound assignment for the possible losing of
13124/// floating-point precision.
13126 assert(isa<CompoundAssignOperator>(E) &&
13127 "Must be compound assignment operation");
13128 // Recurse on the LHS and RHS in here
13131
13132 if (E->getLHS()->getType()->isAtomicType())
13133 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13134
13135 // Now check the outermost expression
13136 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13137 const auto *RBT = cast<CompoundAssignOperator>(E)
13138 ->getComputationResultType()
13139 ->getAs<BuiltinType>();
13140
13141 // The below checks assume source is floating point.
13142 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13143
13144 // If source is floating point but target is an integer.
13145 if (ResultBT->isInteger())
13146 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13147 E->getExprLoc(), diag::warn_impcast_float_integer);
13148
13149 if (!ResultBT->isFloatingPoint())
13150 return;
13151
13152 // If both source and target are floating points, warn about losing precision.
13154 QualType(ResultBT, 0), QualType(RBT, 0));
13155 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13156 // warn about dropping FP rank.
13157 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13158 diag::warn_impcast_float_result_precision);
13159}
13160
13161static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13162 IntRange Range) {
13163 if (!Range.Width) return "0";
13164
13165 llvm::APSInt ValueInRange = Value;
13166 ValueInRange.setIsSigned(!Range.NonNegative);
13167 ValueInRange = ValueInRange.trunc(Range.Width);
13168 return toString(ValueInRange, 10);
13169}
13170
13171static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13172 bool ToBool) {
13173 if (!isa<ImplicitCastExpr>(Ex))
13174 return false;
13175
13176 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13178 const Type *Source =
13180 if (Target->isDependentType())
13181 return false;
13182
13183 const auto *FloatCandidateBT =
13184 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13185 const Type *BoolCandidateType = ToBool ? Target : Source;
13186
13187 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13188 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13189}
13190
13191static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13192 SourceLocation CC) {
13193 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13194 const Expr *CurrA = TheCall->getArg(I);
13195 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13196 continue;
13197
13198 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13199 S, TheCall->getArg(I - 1), false));
13200 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13201 S, TheCall->getArg(I + 1), false));
13202 if (IsSwapped) {
13203 // Warn on this floating-point to bool conversion.
13205 CurrA->getType(), CC,
13206 diag::warn_impcast_floating_point_to_bool);
13207 }
13208 }
13209}
13210
13212 SourceLocation CC) {
13213 // Don't warn on functions which have return type nullptr_t.
13214 if (isa<CallExpr>(E))
13215 return;
13216
13217 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13218 const Expr *NewE = E->IgnoreParenImpCasts();
13219 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13220 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13221 if (!IsGNUNullExpr && !HasNullPtrType)
13222 return;
13223
13224 // Return if target type is a safe conversion.
13225 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13226 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13227 return;
13228
13229 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13230 E->getExprLoc()))
13231 return;
13232
13234
13235 // Venture through the macro stacks to get to the source of macro arguments.
13236 // The new location is a better location than the complete location that was
13237 // passed in.
13238 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13240
13241 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13242 if (IsGNUNullExpr && Loc.isMacroID()) {
13243 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13244 Loc, S.SourceMgr, S.getLangOpts());
13245 if (MacroName == "NULL")
13247 }
13248
13249 // Only warn if the null and context location are in the same macro expansion.
13250 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13251 return;
13252
13253 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13254 << HasNullPtrType << T << SourceRange(CC)
13257}
13258
13259// Helper function to filter out cases for constant width constant conversion.
13260// Don't warn on char array initialization or for non-decimal values.
13262 SourceLocation CC) {
13263 // If initializing from a constant, and the constant starts with '0',
13264 // then it is a binary, octal, or hexadecimal. Allow these constants
13265 // to fill all the bits, even if there is a sign change.
13266 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13267 const char FirstLiteralCharacter =
13268 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13269 if (FirstLiteralCharacter == '0')
13270 return false;
13271 }
13272
13273 // If the CC location points to a '{', and the type is char, then assume
13274 // assume it is an array initialization.
13275 if (CC.isValid() && T->isCharType()) {
13276 const char FirstContextCharacter =
13278 if (FirstContextCharacter == '{')
13279 return false;
13280 }
13281
13282 return true;
13283}
13284
13286 const auto *IL = dyn_cast<IntegerLiteral>(E);
13287 if (!IL) {
13288 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13289 if (UO->getOpcode() == UO_Minus)
13290 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13291 }
13292 }
13293
13294 return IL;
13295}
13296
13298 E = E->IgnoreParenImpCasts();
13299 SourceLocation ExprLoc = E->getExprLoc();
13300
13301 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13302 BinaryOperator::Opcode Opc = BO->getOpcode();
13304 // Do not diagnose unsigned shifts.
13305 if (Opc == BO_Shl) {
13306 const auto *LHS = getIntegerLiteral(BO->getLHS());
13307 const auto *RHS = getIntegerLiteral(BO->getRHS());
13308 if (LHS && LHS->getValue() == 0)
13309 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13310 else if (!E->isValueDependent() && LHS && RHS &&
13311 RHS->getValue().isNonNegative() &&
13313 S.Diag(ExprLoc, diag::warn_left_shift_always)
13314 << (Result.Val.getInt() != 0);
13315 else if (E->getType()->isSignedIntegerType())
13316 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13319 ") != 0");
13320 }
13321 }
13322
13323 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13324 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13325 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13326 if (!LHS || !RHS)
13327 return;
13328 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13329 (RHS->getValue() == 0 || RHS->getValue() == 1))
13330 // Do not diagnose common idioms.
13331 return;
13332 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13333 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13334 }
13335}
13336
13338 const Type *Target, Expr *E,
13339 QualType T,
13340 SourceLocation CC) {
13341 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13342 Source != Target);
13343
13344 // Lone surrogates have a distinct representation in UTF-32.
13345 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13346 // so don't warn on such conversion.
13347 if (Source->isChar16Type() && Target->isChar32Type())
13348 return;
13349
13353 llvm::APSInt Value(32);
13354 Value = Result.Val.getInt();
13355 bool IsASCII = Value <= 0x7F;
13356 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13357 bool ConversionPreservesSemantics =
13358 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13359
13360 if (!ConversionPreservesSemantics) {
13361 auto IsSingleCodeUnitCP = [](const QualType &T,
13362 const llvm::APSInt &Value) {
13363 if (T->isChar8Type())
13364 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13365 if (T->isChar16Type())
13366 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13367 assert(T->isChar32Type());
13368 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13369 };
13370
13371 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13372 << E->getType() << T
13373 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13374 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13375 }
13376 } else {
13377 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13379 DiagnoseImpCast(S, E, T, CC,
13380 LosesPrecision ? diag::warn_impcast_unicode_precision
13381 : diag::warn_impcast_unicode_char_type);
13382 }
13383}
13384
13386 From = Context.getCanonicalType(From);
13387 To = Context.getCanonicalType(To);
13388 QualType MaybePointee = From->getPointeeType();
13389 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13390 From = MaybePointee;
13391 MaybePointee = To->getPointeeType();
13392 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13393 To = MaybePointee;
13394
13395 if (const auto *FromFn = From->getAs<FunctionType>()) {
13396 if (const auto *ToFn = To->getAs<FunctionType>()) {
13397 if (FromFn->getCFIUncheckedCalleeAttr() &&
13398 !ToFn->getCFIUncheckedCalleeAttr())
13399 return true;
13400 }
13401 }
13402 return false;
13403}
13404
13406 bool *ICContext, bool IsListInit) {
13407 if (E->isTypeDependent() || E->isValueDependent()) return;
13408
13409 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13410 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13411 if (Source == Target) return;
13412 if (Target->isDependentType()) return;
13413
13414 // If the conversion context location is invalid don't complain. We also
13415 // don't want to emit a warning if the issue occurs from the expansion of
13416 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13417 // delay this check as long as possible. Once we detect we are in that
13418 // scenario, we just return.
13419 if (CC.isInvalid())
13420 return;
13421
13422 if (Source->isAtomicType())
13423 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13424
13425 // Diagnose implicit casts to bool.
13426 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13427 if (isa<StringLiteral>(E))
13428 // Warn on string literal to bool. Checks for string literals in logical
13429 // and expressions, for instance, assert(0 && "error here"), are
13430 // prevented by a check in AnalyzeImplicitConversions().
13431 return DiagnoseImpCast(*this, E, T, CC,
13432 diag::warn_impcast_string_literal_to_bool);
13435 // This covers the literal expressions that evaluate to Objective-C
13436 // objects.
13437 return DiagnoseImpCast(*this, E, T, CC,
13438 diag::warn_impcast_objective_c_literal_to_bool);
13439 }
13440 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13441 // Warn on pointer to bool conversion that is always true.
13443 SourceRange(CC));
13444 }
13445 }
13446
13448
13449 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13450 // is a typedef for signed char (macOS), then that constant value has to be 1
13451 // or 0.
13452 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13455 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13457 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13458 << toString(Result.Val.getInt(), 10));
13459 }
13460 return;
13461 }
13462 }
13463
13464 // Check implicit casts from Objective-C collection literals to specialized
13465 // collection types, e.g., NSArray<NSString *> *.
13466 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13467 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13468 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13469 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13470
13471 // Strip complex types.
13472 if (isa<ComplexType>(Source)) {
13473 if (!isa<ComplexType>(Target)) {
13474 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13475 return;
13476
13477 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13478 return DiagnoseImpCast(*this, E, T, CC,
13479 diag::err_impcast_incompatible_type);
13480 }
13481
13482 return DiagnoseImpCast(*this, E, T, CC,
13484 ? diag::err_impcast_complex_scalar
13485 : diag::warn_impcast_complex_scalar);
13486 }
13487
13488 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13489 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13490 }
13491
13492 // Strip vector types.
13493 if (isa<VectorType>(Source)) {
13494 if (Target->isSveVLSBuiltinType() &&
13495 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13496 QualType(Source, 0)) ||
13497 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13498 QualType(Source, 0))))
13499 return;
13500
13501 if (Target->isRVVVLSBuiltinType() &&
13502 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13503 QualType(Source, 0)) ||
13504 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13505 QualType(Source, 0))))
13506 return;
13507
13508 if (!isa<VectorType>(Target)) {
13509 if (SourceMgr.isInSystemMacro(CC))
13510 return;
13511 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13512 }
13513 if (getLangOpts().HLSL &&
13514 Target->castAs<VectorType>()->getNumElements() <
13515 Source->castAs<VectorType>()->getNumElements()) {
13516 // Diagnose vector truncation but don't return. We may also want to
13517 // diagnose an element conversion.
13518 DiagnoseImpCast(*this, E, T, CC,
13519 diag::warn_hlsl_impcast_vector_truncation);
13520 }
13521
13522 // If the vector cast is cast between two vectors of the same size, it is
13523 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13524 if (!getLangOpts().HLSL &&
13525 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13526 return;
13527
13528 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13529 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13530 }
13531 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13532 Target = VecTy->getElementType().getTypePtr();
13533
13534 // Strip matrix types.
13535 if (isa<ConstantMatrixType>(Source)) {
13536 if (Target->isScalarType())
13537 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13538
13541 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13542 // Diagnose Matrix truncation but don't return. We may also want to
13543 // diagnose an element conversion.
13544 DiagnoseImpCast(*this, E, T, CC,
13545 diag::warn_hlsl_impcast_matrix_truncation);
13546 }
13547
13548 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13549 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13550 }
13551 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13552 Target = MatTy->getElementType().getTypePtr();
13553
13554 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13555 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13556
13557 // Strip SVE vector types
13558 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13559 // Need the original target type for vector type checks
13560 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13561 // Handle conversion from scalable to fixed when msve-vector-bits is
13562 // specified
13563 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13564 QualType(Source, 0)) ||
13565 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13566 QualType(Source, 0)))
13567 return;
13568
13569 // If the vector cast is cast between two vectors of the same size, it is
13570 // a bitcast, not a conversion.
13571 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13572 return;
13573
13574 Source = SourceBT->getSveEltType(Context).getTypePtr();
13575 }
13576
13577 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13578 Target = TargetBT->getSveEltType(Context).getTypePtr();
13579
13580 // If the source is floating point...
13581 if (SourceBT && SourceBT->isFloatingPoint()) {
13582 // ...and the target is floating point...
13583 if (TargetBT && TargetBT->isFloatingPoint()) {
13584 // ...then warn if we're dropping FP rank.
13585
13587 QualType(SourceBT, 0), QualType(TargetBT, 0));
13588 if (Order > 0) {
13589 // Don't warn about float constants that are precisely
13590 // representable in the target type.
13591 Expr::EvalResult result;
13592 if (E->EvaluateAsRValue(result, Context)) {
13593 // Value might be a float, a float vector, or a float complex.
13595 result.Val,
13596 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13597 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13598 return;
13599 }
13600
13601 if (SourceMgr.isInSystemMacro(CC))
13602 return;
13603
13604 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13605 }
13606 // ... or possibly if we're increasing rank, too
13607 else if (Order < 0) {
13608 if (SourceMgr.isInSystemMacro(CC))
13609 return;
13610
13611 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13612 }
13613 return;
13614 }
13615
13616 // If the target is integral, always warn.
13617 if (TargetBT && TargetBT->isInteger()) {
13618 if (SourceMgr.isInSystemMacro(CC))
13619 return;
13620
13621 DiagnoseFloatingImpCast(*this, E, T, CC);
13622 }
13623
13624 // Detect the case where a call result is converted from floating-point to
13625 // to bool, and the final argument to the call is converted from bool, to
13626 // discover this typo:
13627 //
13628 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13629 //
13630 // FIXME: This is an incredibly special case; is there some more general
13631 // way to detect this class of misplaced-parentheses bug?
13632 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13633 // Check last argument of function call to see if it is an
13634 // implicit cast from a type matching the type the result
13635 // is being cast to.
13636 CallExpr *CEx = cast<CallExpr>(E);
13637 if (unsigned NumArgs = CEx->getNumArgs()) {
13638 Expr *LastA = CEx->getArg(NumArgs - 1);
13639 Expr *InnerE = LastA->IgnoreParenImpCasts();
13640 if (isa<ImplicitCastExpr>(LastA) &&
13641 InnerE->getType()->isBooleanType()) {
13642 // Warn on this floating-point to bool conversion
13643 DiagnoseImpCast(*this, E, T, CC,
13644 diag::warn_impcast_floating_point_to_bool);
13645 }
13646 }
13647 }
13648 return;
13649 }
13650
13651 // Valid casts involving fixed point types should be accounted for here.
13652 if (Source->isFixedPointType()) {
13653 if (Target->isUnsaturatedFixedPointType()) {
13657 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13658 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13659 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13660 if (Value > MaxVal || Value < MinVal) {
13662 PDiag(diag::warn_impcast_fixed_point_range)
13663 << Value.toString() << T
13664 << E->getSourceRange()
13665 << clang::SourceRange(CC));
13666 return;
13667 }
13668 }
13669 } else if (Target->isIntegerType()) {
13673 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13674
13675 bool Overflowed;
13676 llvm::APSInt IntResult = FXResult.convertToInt(
13677 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13678 &Overflowed);
13679
13680 if (Overflowed) {
13682 PDiag(diag::warn_impcast_fixed_point_range)
13683 << FXResult.toString() << T
13684 << E->getSourceRange()
13685 << clang::SourceRange(CC));
13686 return;
13687 }
13688 }
13689 }
13690 } else if (Target->isUnsaturatedFixedPointType()) {
13691 if (Source->isIntegerType()) {
13695 llvm::APSInt Value = Result.Val.getInt();
13696
13697 bool Overflowed;
13698 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13699 Value, Context.getFixedPointSemantics(T), &Overflowed);
13700
13701 if (Overflowed) {
13703 PDiag(diag::warn_impcast_fixed_point_range)
13704 << toString(Value, /*Radix=*/10) << T
13705 << E->getSourceRange()
13706 << clang::SourceRange(CC));
13707 return;
13708 }
13709 }
13710 }
13711 }
13712
13713 // If we are casting an integer type to a floating point type without
13714 // initialization-list syntax, we might lose accuracy if the floating
13715 // point type has a narrower significand than the integer type.
13716 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13717 TargetBT->isFloatingType() && !IsListInit) {
13718 // Determine the number of precision bits in the source integer type.
13719 std::optional<IntRange> SourceRange =
13721 /*Approximate=*/true);
13722 if (!SourceRange)
13723 return;
13724 unsigned int SourcePrecision = SourceRange->Width;
13725
13726 // Determine the number of precision bits in the
13727 // target floating point type.
13728 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13729 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13730
13731 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13732 SourcePrecision > TargetPrecision) {
13733
13734 if (std::optional<llvm::APSInt> SourceInt =
13736 // If the source integer is a constant, convert it to the target
13737 // floating point type. Issue a warning if the value changes
13738 // during the whole conversion.
13739 llvm::APFloat TargetFloatValue(
13740 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13741 llvm::APFloat::opStatus ConversionStatus =
13742 TargetFloatValue.convertFromAPInt(
13743 *SourceInt, SourceBT->isSignedInteger(),
13744 llvm::APFloat::rmNearestTiesToEven);
13745
13746 if (ConversionStatus != llvm::APFloat::opOK) {
13747 SmallString<32> PrettySourceValue;
13748 SourceInt->toString(PrettySourceValue, 10);
13749 SmallString<32> PrettyTargetValue;
13750 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13751
13753 E->getExprLoc(), E,
13754 PDiag(diag::warn_impcast_integer_float_precision_constant)
13755 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13756 << E->getSourceRange() << clang::SourceRange(CC));
13757 }
13758 } else {
13759 // Otherwise, the implicit conversion may lose precision.
13760 DiagnoseImpCast(*this, E, T, CC,
13761 diag::warn_impcast_integer_float_precision);
13762 }
13763 }
13764 }
13765
13766 DiagnoseNullConversion(*this, E, T, CC);
13767
13769
13770 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13771 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13772 return;
13773 }
13774
13775 if (Target->isBooleanType())
13776 DiagnoseIntInBoolContext(*this, E);
13777
13779 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13780 << QualType(Source, 0) << QualType(Target, 0);
13781 }
13782
13783 if (!Source->isIntegerType() || !Target->isIntegerType())
13784 return;
13785
13786 // TODO: remove this early return once the false positives for constant->bool
13787 // in templates, macros, etc, are reduced or removed.
13788 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13789 return;
13790
13791 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13792 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13794 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13795 << E->getType());
13796 }
13797 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13798 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13799 if (!LikelySourceRange)
13800 return;
13801
13802 IntRange SourceTypeRange =
13803 IntRange::forTargetOfCanonicalType(Context, Source);
13804 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13805
13806 if (LikelySourceRange->Width > TargetRange.Width) {
13807 // Check if target is a wrapping OBT - if so, don't warn about constant
13808 // conversion as this type may be used intentionally with implicit
13809 // truncation, especially during assignments.
13810 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13811 if (TargetOBT->isWrapKind()) {
13812 return;
13813 }
13814 }
13815
13816 // Check if source expression has an explicit __ob_wrap cast because if so,
13817 // wrapping was explicitly requested and we shouldn't warn
13818 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13819 if (SourceOBT->isWrapKind()) {
13820 return;
13821 }
13822 }
13823
13824 // If the source is a constant, use a default-on diagnostic.
13825 // TODO: this should happen for bitfield stores, too.
13829 llvm::APSInt Value(32);
13830 Value = Result.Val.getInt();
13831
13832 if (SourceMgr.isInSystemMacro(CC))
13833 return;
13834
13835 std::string PrettySourceValue = toString(Value, 10);
13836 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13837
13839 PDiag(diag::warn_impcast_integer_precision_constant)
13840 << PrettySourceValue << PrettyTargetValue
13841 << E->getType() << T << E->getSourceRange()
13842 << SourceRange(CC));
13843 return;
13844 }
13845
13846 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13847 if (SourceMgr.isInSystemMacro(CC))
13848 return;
13849
13850 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13851 if (UO->getOpcode() == UO_Minus)
13852 return DiagnoseImpCast(
13853 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13854 }
13855
13856 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13857 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13858 /* pruneControlFlow */ true);
13859 return DiagnoseImpCast(*this, E, T, CC,
13860 diag::warn_impcast_integer_precision);
13861 }
13862
13863 if (TargetRange.Width > SourceTypeRange.Width) {
13864 if (auto *UO = dyn_cast<UnaryOperator>(E))
13865 if (UO->getOpcode() == UO_Minus)
13866 if (Source->isUnsignedIntegerType()) {
13867 if (Target->isUnsignedIntegerType())
13868 return DiagnoseImpCast(*this, E, T, CC,
13869 diag::warn_impcast_high_order_zero_bits);
13870 if (Target->isSignedIntegerType())
13871 return DiagnoseImpCast(*this, E, T, CC,
13872 diag::warn_impcast_nonnegative_result);
13873 }
13874 }
13875
13876 if (TargetRange.Width == LikelySourceRange->Width &&
13877 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13878 Source->isSignedIntegerType()) {
13879 // Warn when doing a signed to signed conversion, warn if the positive
13880 // source value is exactly the width of the target type, which will
13881 // cause a negative value to be stored.
13882
13885 !SourceMgr.isInSystemMacro(CC)) {
13886 llvm::APSInt Value = Result.Val.getInt();
13887 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13888 std::string PrettySourceValue = toString(Value, 10);
13889 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13890
13891 Diag(E->getExprLoc(),
13892 PDiag(diag::warn_impcast_integer_precision_constant)
13893 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13894 << E->getSourceRange() << SourceRange(CC));
13895 return;
13896 }
13897 }
13898
13899 // Fall through for non-constants to give a sign conversion warning.
13900 }
13901
13902 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13903 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13904 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13905 LikelySourceRange->Width == TargetRange.Width))) {
13906 if (SourceMgr.isInSystemMacro(CC))
13907 return;
13908
13909 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13910 TargetBT->isInteger() &&
13911 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13912 return;
13913 }
13914
13915 unsigned DiagID = diag::warn_impcast_integer_sign;
13916
13917 // Traditionally, gcc has warned about this under -Wsign-compare.
13918 // We also want to warn about it in -Wconversion.
13919 // So if -Wconversion is off, use a completely identical diagnostic
13920 // in the sign-compare group.
13921 // The conditional-checking code will
13922 if (ICContext) {
13923 DiagID = diag::warn_impcast_integer_sign_conditional;
13924 *ICContext = true;
13925 }
13926
13927 DiagnoseImpCast(*this, E, T, CC, DiagID);
13928 }
13929
13930 // If we're implicitly converting from an integer into an enumeration, that
13931 // is valid in C but invalid in C++.
13932 QualType SourceType = E->getEnumCoercedType(Context);
13933 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13934 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13935 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13936
13937 // Diagnose conversions between different enumeration types.
13938 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13939 // type, to give us better diagnostics.
13940 Source = Context.getCanonicalType(SourceType).getTypePtr();
13941
13942 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13943 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13944 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13945 TargetEnum->getDecl()->hasNameForLinkage() &&
13946 SourceEnum != TargetEnum) {
13947 if (SourceMgr.isInSystemMacro(CC))
13948 return;
13949
13950 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13951 diag::warn_impcast_different_enum_types);
13952 }
13953}
13954
13957
13959 SourceLocation CC, bool &ICContext) {
13960 E = E->IgnoreParenImpCasts();
13961 // Diagnose incomplete type for second or third operand in C.
13962 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13963 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13964
13965 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13966 return CheckConditionalOperator(S, CO, CC, T);
13967
13969 if (E->getType() != T)
13970 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13971}
13972
13976
13977 Expr *TrueExpr = E->getTrueExpr();
13978 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13979 TrueExpr = BCO->getCommon();
13980
13981 bool Suspicious = false;
13982 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13983 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13984
13985 if (T->isBooleanType())
13987
13988 // If -Wconversion would have warned about either of the candidates
13989 // for a signedness conversion to the context type...
13990 if (!Suspicious) return;
13991
13992 // ...but it's currently ignored...
13993 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13994 return;
13995
13996 // ...then check whether it would have warned about either of the
13997 // candidates for a signedness conversion to the condition type.
13998 if (E->getType() == T) return;
13999
14000 Suspicious = false;
14001 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
14002 &Suspicious);
14003 if (!Suspicious)
14005 E->getType(), CC, &Suspicious);
14006}
14007
14008/// Check conversion of given expression to boolean.
14009/// Input argument E is a logical expression.
14011 // Run the bool-like conversion checks only for C since there bools are
14012 // still not used as the return type from "boolean" operators or as the input
14013 // type for conditional operators.
14014 if (S.getLangOpts().CPlusPlus)
14015 return;
14017 return;
14019}
14020
14021namespace {
14022struct AnalyzeImplicitConversionsWorkItem {
14023 Expr *E;
14024 SourceLocation CC;
14025 bool IsListInit;
14026};
14027}
14028
14030 Sema &S, Expr *E, QualType T, SourceLocation CC,
14031 bool ExtraCheckForImplicitConversion,
14033 E = E->IgnoreParenImpCasts();
14034 WorkList.push_back({E, CC, false});
14035
14036 if (ExtraCheckForImplicitConversion && E->getType() != T)
14037 S.CheckImplicitConversion(E, T, CC);
14038}
14039
14040/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14041/// that should be visited are added to WorkList.
14043 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14045 Expr *OrigE = Item.E;
14046 SourceLocation CC = Item.CC;
14047
14048 QualType T = OrigE->getType();
14049 Expr *E = OrigE->IgnoreParenImpCasts();
14050
14051 // Propagate whether we are in a C++ list initialization expression.
14052 // If so, we do not issue warnings for implicit int-float conversion
14053 // precision loss, because C++11 narrowing already handles it.
14054 //
14055 // HLSL's initialization lists are special, so they shouldn't observe the C++
14056 // behavior here.
14057 bool IsListInit =
14058 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
14059 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14060
14061 if (E->isTypeDependent() || E->isValueDependent())
14062 return;
14063
14064 Expr *SourceExpr = E;
14065 // Examine, but don't traverse into the source expression of an
14066 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14067 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14068 // evaluate it in the context of checking the specific conversion to T though.
14069 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14070 if (auto *Src = OVE->getSourceExpr())
14071 SourceExpr = Src;
14072
14073 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14074 if (UO->getOpcode() == UO_Not &&
14075 UO->getSubExpr()->isKnownToHaveBooleanValue())
14076 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14077 << OrigE->getSourceRange() << T->isBooleanType()
14078 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14079
14080 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14081 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14082 BO->getLHS()->isKnownToHaveBooleanValue() &&
14083 BO->getRHS()->isKnownToHaveBooleanValue() &&
14084 BO->getLHS()->HasSideEffects(S.Context) &&
14085 BO->getRHS()->HasSideEffects(S.Context)) {
14087 const LangOptions &LO = S.getLangOpts();
14088 SourceLocation BLoc = BO->getOperatorLoc();
14089 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
14090 StringRef SR = clang::Lexer::getSourceText(
14091 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
14092 // To reduce false positives, only issue the diagnostic if the operator
14093 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14094 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14095 // in C, along with other macro spellings the user might invent.
14096 if (SR.str() == "&" || SR.str() == "|") {
14097
14098 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14099 << (BO->getOpcode() == BO_And ? "&" : "|")
14100 << OrigE->getSourceRange()
14102 BO->getOperatorLoc(),
14103 (BO->getOpcode() == BO_And ? "&&" : "||"));
14104 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14105 }
14106 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14107 /// Analyze the given comma operator. The basic idea behind the analysis
14108 /// is to analyze the left and right operands slightly differently. The
14109 /// left operand needs to check whether the operand itself has an implicit
14110 /// conversion, but not whether the left operand induces an implicit
14111 /// conversion for the entire comma expression itself. This is similar to
14112 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14113 /// were directly used for the implicit conversion check.
14114 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
14115 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14116 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
14117 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14118 return;
14119 }
14120 }
14121
14122 // For conditional operators, we analyze the arguments as if they
14123 // were being fed directly into the output.
14124 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14125 CheckConditionalOperator(S, CO, CC, T);
14126 return;
14127 }
14128
14129 // Check implicit argument conversions for function calls.
14130 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14132
14133 // Go ahead and check any implicit conversions we might have skipped.
14134 // The non-canonical typecheck is just an optimization;
14135 // CheckImplicitConversion will filter out dead implicit conversions.
14136 if (SourceExpr->getType() != T)
14137 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14138
14139 // Now continue drilling into this expression.
14140
14141 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14142 // The bound subexpressions in a PseudoObjectExpr are not reachable
14143 // as transitive children.
14144 // FIXME: Use a more uniform representation for this.
14145 for (auto *SE : POE->semantics())
14146 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14147 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14148 }
14149
14150 // Skip past explicit casts.
14151 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14152 E = CE->getSubExpr();
14153 // In the special case of a C++ function-style cast with braces,
14154 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14155 // initializer. This InitListExpr basically belongs to the cast itself, so
14156 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14158 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14159 if (InitListE->getNumInits() == 1) {
14160 E = InitListE->getInit(0);
14161 }
14162 }
14163 }
14164 E = E->IgnoreParenImpCasts();
14165 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14166 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14167 WorkList.push_back({E, CC, IsListInit});
14168 return;
14169 }
14170
14171 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14172 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14173 // The base expression is only used to initialize the parameter for
14174 // arguments to `inout` parameters, so we only traverse down the base
14175 // expression for `inout` cases.
14176 if (OutArgE->isInOut())
14177 WorkList.push_back(
14178 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14179 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14180 return;
14181 }
14182
14183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14184 // Do a somewhat different check with comparison operators.
14185 if (BO->isComparisonOp())
14186 return AnalyzeComparison(S, BO);
14187
14188 // And with simple assignments.
14189 if (BO->getOpcode() == BO_Assign)
14190 return AnalyzeAssignment(S, BO);
14191 // And with compound assignments.
14192 if (BO->isAssignmentOp())
14193 return AnalyzeCompoundAssignment(S, BO);
14194 }
14195
14196 // These break the otherwise-useful invariant below. Fortunately,
14197 // we don't really need to recurse into them, because any internal
14198 // expressions should have been analyzed already when they were
14199 // built into statements.
14200 if (isa<StmtExpr>(E)) return;
14201
14202 // Don't descend into unevaluated contexts.
14203 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14204
14205 // Now just recurse over the expression's children.
14206 CC = E->getExprLoc();
14207 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14208 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14209 for (Stmt *SubStmt : E->children()) {
14210 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14211 if (!ChildExpr)
14212 continue;
14213
14214 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14215 if (ChildExpr == CSE->getOperand())
14216 // Do not recurse over a CoroutineSuspendExpr's operand.
14217 // The operand is also a subexpression of getCommonExpr(), and
14218 // recursing into it directly would produce duplicate diagnostics.
14219 continue;
14220
14221 if (IsLogicalAndOperator &&
14223 // Ignore checking string literals that are in logical and operators.
14224 // This is a common pattern for asserts.
14225 continue;
14226 WorkList.push_back({ChildExpr, CC, IsListInit});
14227 }
14228
14229 if (BO && BO->isLogicalOp()) {
14230 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14231 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14232 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14233
14234 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14235 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14236 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14237 }
14238
14239 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14240 if (U->getOpcode() == UO_LNot) {
14241 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14242 } else if (U->getOpcode() != UO_AddrOf) {
14243 if (U->getSubExpr()->getType()->isAtomicType())
14244 S.Diag(U->getSubExpr()->getBeginLoc(),
14245 diag::warn_atomic_implicit_seq_cst);
14246 }
14247 }
14248}
14249
14250/// AnalyzeImplicitConversions - Find and report any interesting
14251/// implicit conversions in the given expression. There are a couple
14252/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14254 bool IsListInit/*= false*/) {
14256 WorkList.push_back({OrigE, CC, IsListInit});
14257 while (!WorkList.empty())
14258 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14259}
14260
14261// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14262// Returns true when emitting a warning about taking the address of a reference.
14263static bool CheckForReference(Sema &SemaRef, const Expr *E,
14264 const PartialDiagnostic &PD) {
14265 E = E->IgnoreParenImpCasts();
14266
14267 const FunctionDecl *FD = nullptr;
14268
14269 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14270 if (!DRE->getDecl()->getType()->isReferenceType())
14271 return false;
14272 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14273 if (!M->getMemberDecl()->getType()->isReferenceType())
14274 return false;
14275 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14276 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14277 return false;
14278 FD = Call->getDirectCallee();
14279 } else {
14280 return false;
14281 }
14282
14283 SemaRef.Diag(E->getExprLoc(), PD);
14284
14285 // If possible, point to location of function.
14286 if (FD) {
14287 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14288 }
14289
14290 return true;
14291}
14292
14293// Returns true if the SourceLocation is expanded from any macro body.
14294// Returns false if the SourceLocation is invalid, is from not in a macro
14295// expansion, or is from expanded from a top-level macro argument.
14296static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14297 if (Loc.isInvalid())
14298 return false;
14299
14300 while (Loc.isMacroID()) {
14301 if (SM.isMacroBodyExpansion(Loc))
14302 return true;
14303 Loc = SM.getImmediateMacroCallerLoc(Loc);
14304 }
14305
14306 return false;
14307}
14308
14311 bool IsEqual, SourceRange Range) {
14312 if (!E)
14313 return;
14314
14315 // Don't warn inside macros.
14316 if (E->getExprLoc().isMacroID()) {
14317 const SourceManager &SM = getSourceManager();
14318 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14319 IsInAnyMacroBody(SM, Range.getBegin()))
14320 return;
14321 }
14322 E = E->IgnoreImpCasts();
14323
14324 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14325
14326 if (isa<CXXThisExpr>(E)) {
14327 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14328 : diag::warn_this_bool_conversion;
14329 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14330 return;
14331 }
14332
14333 bool IsAddressOf = false;
14334
14335 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14336 if (UO->getOpcode() != UO_AddrOf)
14337 return;
14338 IsAddressOf = true;
14339 E = UO->getSubExpr();
14340 }
14341
14342 if (IsAddressOf) {
14343 unsigned DiagID = IsCompare
14344 ? diag::warn_address_of_reference_null_compare
14345 : diag::warn_address_of_reference_bool_conversion;
14346 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14347 << IsEqual;
14348 if (CheckForReference(*this, E, PD)) {
14349 return;
14350 }
14351 }
14352
14353 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14354 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14355 std::string Str;
14356 llvm::raw_string_ostream S(Str);
14357 E->printPretty(S, nullptr, getPrintingPolicy());
14358 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14359 : diag::warn_cast_nonnull_to_bool;
14360 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14361 << E->getSourceRange() << Range << IsEqual;
14362 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14363 };
14364
14365 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14366 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14367 if (auto *Callee = Call->getDirectCallee()) {
14368 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14369 ComplainAboutNonnullParamOrCall(A);
14370 return;
14371 }
14372 }
14373 }
14374
14375 // Complain if we are converting a lambda expression to a boolean value
14376 // outside of instantiation.
14377 if (!inTemplateInstantiation()) {
14378 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14379 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14380 MRecordDecl && MRecordDecl->isLambda()) {
14381 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14382 << /*LambdaPointerConversionOperatorType=*/3
14383 << MRecordDecl->getSourceRange() << Range << IsEqual;
14384 return;
14385 }
14386 }
14387 }
14388
14389 // Expect to find a single Decl. Skip anything more complicated.
14390 ValueDecl *D = nullptr;
14391 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14392 D = R->getDecl();
14393 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14394 D = M->getMemberDecl();
14395 }
14396
14397 // Weak Decls can be null.
14398 if (!D || D->isWeak())
14399 return;
14400
14401 // Check for parameter decl with nonnull attribute
14402 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14403 if (getCurFunction() &&
14404 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14405 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14406 ComplainAboutNonnullParamOrCall(A);
14407 return;
14408 }
14409
14410 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14411 // Skip function template not specialized yet.
14413 return;
14414 auto ParamIter = llvm::find(FD->parameters(), PV);
14415 assert(ParamIter != FD->param_end());
14416 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14417
14418 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14419 if (!NonNull->args_size()) {
14420 ComplainAboutNonnullParamOrCall(NonNull);
14421 return;
14422 }
14423
14424 for (const ParamIdx &ArgNo : NonNull->args()) {
14425 if (ArgNo.getASTIndex() == ParamNo) {
14426 ComplainAboutNonnullParamOrCall(NonNull);
14427 return;
14428 }
14429 }
14430 }
14431 }
14432 }
14433 }
14434
14435 QualType T = D->getType();
14436 // A reference to a function is never null either; look through it.
14437 const bool IsFunctionReference =
14438 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14439 if (IsFunctionReference)
14440 T = T->getPointeeType();
14441 const bool IsArray = T->isArrayType();
14442 const bool IsFunction = T->isFunctionType();
14443
14444 // Address of function is used to silence the function warning.
14445 if (IsAddressOf && IsFunction) {
14446 return;
14447 }
14448
14449 // Found nothing.
14450 if (!IsAddressOf && !IsFunction && !IsArray)
14451 return;
14452
14453 // Pretty print the expression for the diagnostic.
14454 std::string Str;
14455 llvm::raw_string_ostream S(Str);
14456 E->printPretty(S, nullptr, getPrintingPolicy());
14457
14458 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14459 : diag::warn_impcast_pointer_to_bool;
14460 enum {
14461 AddressOf,
14462 FunctionPointer,
14463 ArrayPointer
14464 } DiagType;
14465 if (IsAddressOf)
14466 DiagType = AddressOf;
14467 else if (IsFunction)
14468 DiagType = FunctionPointer;
14469 else if (IsArray)
14470 DiagType = ArrayPointer;
14471 else
14472 llvm_unreachable("Could not determine diagnostic.");
14473 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14474 << Range << IsEqual;
14475
14476 // The fix-it notes below only apply to a bare function name, not a reference.
14477 if (!IsFunction || IsFunctionReference)
14478 return;
14479
14480 // Suggest '&' to silence the function warning.
14481 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14483
14484 // Check to see if '()' fixit should be emitted.
14485 QualType ReturnType;
14486 UnresolvedSet<4> NonTemplateOverloads;
14487 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14488 if (ReturnType.isNull())
14489 return;
14490
14491 if (IsCompare) {
14492 // There are two cases here. If there is null constant, the only suggest
14493 // for a pointer return type. If the null is 0, then suggest if the return
14494 // type is a pointer or an integer type.
14495 if (!ReturnType->isPointerType()) {
14496 if (NullKind == Expr::NPCK_ZeroExpression ||
14497 NullKind == Expr::NPCK_ZeroLiteral) {
14498 if (!ReturnType->isIntegerType())
14499 return;
14500 } else {
14501 return;
14502 }
14503 }
14504 } else { // !IsCompare
14505 // For function to bool, only suggest if the function pointer has bool
14506 // return type.
14507 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14508 return;
14509 }
14510 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14512}
14513
14515 SourceLocation CC) {
14516 QualType Source = E->getType();
14517 QualType Target = T;
14518
14519 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14520 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14521 // Overflow behavior type is being stripped - issue warning
14522 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14523 Target->isUnsignedIntegerType()) {
14524 // For unsigned wrap to unsigned conversions, use pedantic version
14525 unsigned DiagId =
14527 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14528 : diag::warn_impcast_overflow_behavior_pedantic;
14529 DiagnoseImpCast(*this, E, T, CC, DiagId);
14530 } else {
14531 unsigned DiagId = InOverflowBehaviorAssignmentContext
14532 ? diag::warn_impcast_overflow_behavior_assignment
14533 : diag::warn_impcast_overflow_behavior;
14534 DiagnoseImpCast(*this, E, T, CC, DiagId);
14535 }
14536 }
14537 }
14538
14539 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14540 if (TargetOBT->isWrapKind()) {
14541 return true;
14542 }
14543 }
14544
14545 return false;
14546}
14547
14548void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14549 // Don't diagnose in unevaluated contexts.
14551 return;
14552
14553 // Don't diagnose for value- or type-dependent expressions.
14554 if (E->isTypeDependent() || E->isValueDependent())
14555 return;
14556
14557 // Check for array bounds violations in cases where the check isn't triggered
14558 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14559 // ArraySubscriptExpr is on the RHS of a variable initialization.
14560 CheckArrayAccess(E);
14561
14562 // This is not the right CC for (e.g.) a variable initialization.
14563 AnalyzeImplicitConversions(*this, E, CC);
14564}
14565
14566void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14567 ::CheckBoolLikeConversion(*this, E, CC);
14568}
14569
14570void Sema::CheckForIntOverflow (const Expr *E) {
14571 // Use a work list to deal with nested struct initializers.
14572 SmallVector<const Expr *, 2> Exprs(1, E);
14573
14574 do {
14575 const Expr *OriginalE = Exprs.pop_back_val();
14576 const Expr *E = OriginalE->IgnoreParenCasts();
14577
14578 if (isa<BinaryOperator>(E) ||
14579 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14581 continue;
14582 }
14583
14584 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14585 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14586 else if (isa<ObjCBoxedExpr>(OriginalE))
14588 else if (const auto *Call = dyn_cast<CallExpr>(E))
14589 Exprs.append(Call->arg_begin(), Call->arg_end());
14590 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14591 Exprs.append(Message->arg_begin(), Message->arg_end());
14592 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14593 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14594 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14595 Exprs.push_back(Temporary->getSubExpr());
14596 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14597 Exprs.push_back(Array->getIdx());
14598 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14599 Exprs.push_back(Compound->getInitializer());
14600 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14601 New && New->isArray()) {
14602 if (auto ArraySize = New->getArraySize())
14603 Exprs.push_back(*ArraySize);
14604 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14605 Exprs.push_back(MTE->getSubExpr());
14606 } while (!Exprs.empty());
14607}
14608
14609namespace {
14610
14611/// Visitor for expressions which looks for unsequenced operations on the
14612/// same object.
14613class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14614 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14615
14616 /// A tree of sequenced regions within an expression. Two regions are
14617 /// unsequenced if one is an ancestor or a descendent of the other. When we
14618 /// finish processing an expression with sequencing, such as a comma
14619 /// expression, we fold its tree nodes into its parent, since they are
14620 /// unsequenced with respect to nodes we will visit later.
14621 class SequenceTree {
14622 struct Value {
14623 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14624 unsigned Parent : 31;
14625 LLVM_PREFERRED_TYPE(bool)
14626 unsigned Merged : 1;
14627 };
14628 SmallVector<Value, 8> Values;
14629
14630 public:
14631 /// A region within an expression which may be sequenced with respect
14632 /// to some other region.
14633 class Seq {
14634 friend class SequenceTree;
14635
14636 unsigned Index;
14637
14638 explicit Seq(unsigned N) : Index(N) {}
14639
14640 public:
14641 Seq() : Index(0) {}
14642 };
14643
14644 SequenceTree() { Values.push_back(Value(0)); }
14645 Seq root() const { return Seq(0); }
14646
14647 /// Create a new sequence of operations, which is an unsequenced
14648 /// subset of \p Parent. This sequence of operations is sequenced with
14649 /// respect to other children of \p Parent.
14650 Seq allocate(Seq Parent) {
14651 Values.push_back(Value(Parent.Index));
14652 return Seq(Values.size() - 1);
14653 }
14654
14655 /// Merge a sequence of operations into its parent.
14656 void merge(Seq S) {
14657 Values[S.Index].Merged = true;
14658 }
14659
14660 /// Determine whether two operations are unsequenced. This operation
14661 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14662 /// should have been merged into its parent as appropriate.
14663 bool isUnsequenced(Seq Cur, Seq Old) {
14664 unsigned C = representative(Cur.Index);
14665 unsigned Target = representative(Old.Index);
14666 while (C >= Target) {
14667 if (C == Target)
14668 return true;
14669 C = Values[C].Parent;
14670 }
14671 return false;
14672 }
14673
14674 private:
14675 /// Pick a representative for a sequence.
14676 unsigned representative(unsigned K) {
14677 if (Values[K].Merged)
14678 // Perform path compression as we go.
14679 return Values[K].Parent = representative(Values[K].Parent);
14680 return K;
14681 }
14682 };
14683
14684 /// An object for which we can track unsequenced uses.
14685 using Object = const NamedDecl *;
14686
14687 /// Different flavors of object usage which we track. We only track the
14688 /// least-sequenced usage of each kind.
14689 enum UsageKind {
14690 /// A read of an object. Multiple unsequenced reads are OK.
14691 UK_Use,
14692
14693 /// A modification of an object which is sequenced before the value
14694 /// computation of the expression, such as ++n in C++.
14695 UK_ModAsValue,
14696
14697 /// A modification of an object which is not sequenced before the value
14698 /// computation of the expression, such as n++.
14699 UK_ModAsSideEffect,
14700
14701 UK_Count = UK_ModAsSideEffect + 1
14702 };
14703
14704 /// Bundle together a sequencing region and the expression corresponding
14705 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14706 struct Usage {
14707 const Expr *UsageExpr = nullptr;
14708 SequenceTree::Seq Seq;
14709
14710 Usage() = default;
14711 };
14712
14713 struct UsageInfo {
14714 Usage Uses[UK_Count];
14715
14716 /// Have we issued a diagnostic for this object already?
14717 bool Diagnosed = false;
14718
14719 UsageInfo();
14720 };
14721 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14722
14723 Sema &SemaRef;
14724
14725 /// Sequenced regions within the expression.
14726 SequenceTree Tree;
14727
14728 /// Declaration modifications and references which we have seen.
14729 UsageInfoMap UsageMap;
14730
14731 /// The region we are currently within.
14732 SequenceTree::Seq Region;
14733
14734 /// Filled in with declarations which were modified as a side-effect
14735 /// (that is, post-increment operations).
14736 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14737
14738 /// Expressions to check later. We defer checking these to reduce
14739 /// stack usage.
14740 SmallVectorImpl<const Expr *> &WorkList;
14741
14742 /// RAII object wrapping the visitation of a sequenced subexpression of an
14743 /// expression. At the end of this process, the side-effects of the evaluation
14744 /// become sequenced with respect to the value computation of the result, so
14745 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14746 /// UK_ModAsValue.
14747 struct SequencedSubexpression {
14748 SequencedSubexpression(SequenceChecker &Self)
14749 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14750 Self.ModAsSideEffect = &ModAsSideEffect;
14751 }
14752
14753 ~SequencedSubexpression() {
14754 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14755 // Add a new usage with usage kind UK_ModAsValue, and then restore
14756 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14757 // the previous one was empty).
14758 UsageInfo &UI = Self.UsageMap[M.first];
14759 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14760 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14761 SideEffectUsage = M.second;
14762 }
14763 Self.ModAsSideEffect = OldModAsSideEffect;
14764 }
14765
14766 SequenceChecker &Self;
14767 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14768 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14769 };
14770
14771 /// RAII object wrapping the visitation of a subexpression which we might
14772 /// choose to evaluate as a constant. If any subexpression is evaluated and
14773 /// found to be non-constant, this allows us to suppress the evaluation of
14774 /// the outer expression.
14775 class EvaluationTracker {
14776 public:
14777 EvaluationTracker(SequenceChecker &Self)
14778 : Self(Self), Prev(Self.EvalTracker) {
14779 Self.EvalTracker = this;
14780 }
14781
14782 ~EvaluationTracker() {
14783 Self.EvalTracker = Prev;
14784 if (Prev)
14785 Prev->EvalOK &= EvalOK;
14786 }
14787
14788 bool evaluate(const Expr *E, bool &Result) {
14789 if (!EvalOK || E->isValueDependent())
14790 return false;
14791 EvalOK = E->EvaluateAsBooleanCondition(
14792 Result, Self.SemaRef.Context,
14793 Self.SemaRef.isConstantEvaluatedContext());
14794 return EvalOK;
14795 }
14796
14797 private:
14798 SequenceChecker &Self;
14799 EvaluationTracker *Prev;
14800 bool EvalOK = true;
14801 } *EvalTracker = nullptr;
14802
14803 /// Find the object which is produced by the specified expression,
14804 /// if any.
14805 Object getObject(const Expr *E, bool Mod) const {
14806 E = E->IgnoreParenCasts();
14807 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14808 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14809 return getObject(UO->getSubExpr(), Mod);
14810 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14811 if (BO->getOpcode() == BO_Comma)
14812 return getObject(BO->getRHS(), Mod);
14813 if (Mod && BO->isAssignmentOp())
14814 return getObject(BO->getLHS(), Mod);
14815 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14816 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14817 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14818 return ME->getMemberDecl();
14819 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14820 // FIXME: If this is a reference, map through to its value.
14821 return DRE->getDecl();
14822 return nullptr;
14823 }
14824
14825 /// Note that an object \p O was modified or used by an expression
14826 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14827 /// the object \p O as obtained via the \p UsageMap.
14828 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14829 // Get the old usage for the given object and usage kind.
14830 Usage &U = UI.Uses[UK];
14831 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14832 // If we have a modification as side effect and are in a sequenced
14833 // subexpression, save the old Usage so that we can restore it later
14834 // in SequencedSubexpression::~SequencedSubexpression.
14835 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14836 ModAsSideEffect->push_back(std::make_pair(O, U));
14837 // Then record the new usage with the current sequencing region.
14838 U.UsageExpr = UsageExpr;
14839 U.Seq = Region;
14840 }
14841 }
14842
14843 /// Check whether a modification or use of an object \p O in an expression
14844 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14845 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14846 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14847 /// usage and false we are checking for a mod-use unsequenced usage.
14848 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14849 UsageKind OtherKind, bool IsModMod) {
14850 if (UI.Diagnosed)
14851 return;
14852
14853 const Usage &U = UI.Uses[OtherKind];
14854 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14855 return;
14856
14857 const Expr *Mod = U.UsageExpr;
14858 const Expr *ModOrUse = UsageExpr;
14859 if (OtherKind == UK_Use)
14860 std::swap(Mod, ModOrUse);
14861
14862 SemaRef.DiagRuntimeBehavior(
14863 Mod->getExprLoc(), {Mod, ModOrUse},
14864 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14865 : diag::warn_unsequenced_mod_use)
14866 << O << SourceRange(ModOrUse->getExprLoc()));
14867 UI.Diagnosed = true;
14868 }
14869
14870 // A note on note{Pre, Post}{Use, Mod}:
14871 //
14872 // (It helps to follow the algorithm with an expression such as
14873 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14874 // operations before C++17 and both are well-defined in C++17).
14875 //
14876 // When visiting a node which uses/modify an object we first call notePreUse
14877 // or notePreMod before visiting its sub-expression(s). At this point the
14878 // children of the current node have not yet been visited and so the eventual
14879 // uses/modifications resulting from the children of the current node have not
14880 // been recorded yet.
14881 //
14882 // We then visit the children of the current node. After that notePostUse or
14883 // notePostMod is called. These will 1) detect an unsequenced modification
14884 // as side effect (as in "k++ + k") and 2) add a new usage with the
14885 // appropriate usage kind.
14886 //
14887 // We also have to be careful that some operation sequences modification as
14888 // side effect as well (for example: || or ,). To account for this we wrap
14889 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14890 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14891 // which record usages which are modifications as side effect, and then
14892 // downgrade them (or more accurately restore the previous usage which was a
14893 // modification as side effect) when exiting the scope of the sequenced
14894 // subexpression.
14895
14896 void notePreUse(Object O, const Expr *UseExpr) {
14897 UsageInfo &UI = UsageMap[O];
14898 // Uses conflict with other modifications.
14899 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14900 }
14901
14902 void notePostUse(Object O, const Expr *UseExpr) {
14903 UsageInfo &UI = UsageMap[O];
14904 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14905 /*IsModMod=*/false);
14906 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14907 }
14908
14909 void notePreMod(Object O, const Expr *ModExpr) {
14910 UsageInfo &UI = UsageMap[O];
14911 // Modifications conflict with other modifications and with uses.
14912 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14913 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14914 }
14915
14916 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14917 UsageInfo &UI = UsageMap[O];
14918 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14919 /*IsModMod=*/true);
14920 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14921 }
14922
14923public:
14924 SequenceChecker(Sema &S, const Expr *E,
14925 SmallVectorImpl<const Expr *> &WorkList)
14926 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14927 Visit(E);
14928 // Silence a -Wunused-private-field since WorkList is now unused.
14929 // TODO: Evaluate if it can be used, and if not remove it.
14930 (void)this->WorkList;
14931 }
14932
14933 void VisitStmt(const Stmt *S) {
14934 // Skip all statements which aren't expressions for now.
14935 }
14936
14937 void VisitExpr(const Expr *E) {
14938 // By default, just recurse to evaluated subexpressions.
14939 Base::VisitStmt(E);
14940 }
14941
14942 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14943 for (auto *Sub : CSE->children()) {
14944 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14945 if (!ChildExpr)
14946 continue;
14947
14948 if (ChildExpr == CSE->getOperand())
14949 // Do not recurse over a CoroutineSuspendExpr's operand.
14950 // The operand is also a subexpression of getCommonExpr(), and
14951 // recursing into it directly could confuse object management
14952 // for the sake of sequence tracking.
14953 continue;
14954
14955 Visit(Sub);
14956 }
14957 }
14958
14959 void VisitCastExpr(const CastExpr *E) {
14960 Object O = Object();
14961 if (E->getCastKind() == CK_LValueToRValue)
14962 O = getObject(E->getSubExpr(), false);
14963
14964 if (O)
14965 notePreUse(O, E);
14966 VisitExpr(E);
14967 if (O)
14968 notePostUse(O, E);
14969 }
14970
14971 void VisitSequencedExpressions(const Expr *SequencedBefore,
14972 const Expr *SequencedAfter) {
14973 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14974 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14975 SequenceTree::Seq OldRegion = Region;
14976
14977 {
14978 SequencedSubexpression SeqBefore(*this);
14979 Region = BeforeRegion;
14980 Visit(SequencedBefore);
14981 }
14982
14983 Region = AfterRegion;
14984 Visit(SequencedAfter);
14985
14986 Region = OldRegion;
14987
14988 Tree.merge(BeforeRegion);
14989 Tree.merge(AfterRegion);
14990 }
14991
14992 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14993 // C++17 [expr.sub]p1:
14994 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14995 // expression E1 is sequenced before the expression E2.
14996 if (SemaRef.getLangOpts().CPlusPlus17)
14997 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14998 else {
14999 Visit(ASE->getLHS());
15000 Visit(ASE->getRHS());
15001 }
15002 }
15003
15004 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15005 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15006 void VisitBinPtrMem(const BinaryOperator *BO) {
15007 // C++17 [expr.mptr.oper]p4:
15008 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15009 // the expression E1 is sequenced before the expression E2.
15010 if (SemaRef.getLangOpts().CPlusPlus17)
15011 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15012 else {
15013 Visit(BO->getLHS());
15014 Visit(BO->getRHS());
15015 }
15016 }
15017
15018 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15019 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15020 void VisitBinShlShr(const BinaryOperator *BO) {
15021 // C++17 [expr.shift]p4:
15022 // The expression E1 is sequenced before the expression E2.
15023 if (SemaRef.getLangOpts().CPlusPlus17)
15024 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15025 else {
15026 Visit(BO->getLHS());
15027 Visit(BO->getRHS());
15028 }
15029 }
15030
15031 void VisitBinComma(const BinaryOperator *BO) {
15032 // C++11 [expr.comma]p1:
15033 // Every value computation and side effect associated with the left
15034 // expression is sequenced before every value computation and side
15035 // effect associated with the right expression.
15036 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15037 }
15038
15039 void VisitBinAssign(const BinaryOperator *BO) {
15040 SequenceTree::Seq RHSRegion;
15041 SequenceTree::Seq LHSRegion;
15042 if (SemaRef.getLangOpts().CPlusPlus17) {
15043 RHSRegion = Tree.allocate(Region);
15044 LHSRegion = Tree.allocate(Region);
15045 } else {
15046 RHSRegion = Region;
15047 LHSRegion = Region;
15048 }
15049 SequenceTree::Seq OldRegion = Region;
15050
15051 // C++11 [expr.ass]p1:
15052 // [...] the assignment is sequenced after the value computation
15053 // of the right and left operands, [...]
15054 //
15055 // so check it before inspecting the operands and update the
15056 // map afterwards.
15057 Object O = getObject(BO->getLHS(), /*Mod=*/true);
15058 if (O)
15059 notePreMod(O, BO);
15060
15061 if (SemaRef.getLangOpts().CPlusPlus17) {
15062 // C++17 [expr.ass]p1:
15063 // [...] The right operand is sequenced before the left operand. [...]
15064 {
15065 SequencedSubexpression SeqBefore(*this);
15066 Region = RHSRegion;
15067 Visit(BO->getRHS());
15068 }
15069
15070 Region = LHSRegion;
15071 Visit(BO->getLHS());
15072
15073 if (O && isa<CompoundAssignOperator>(BO))
15074 notePostUse(O, BO);
15075
15076 } else {
15077 // C++11 does not specify any sequencing between the LHS and RHS.
15078 Region = LHSRegion;
15079 Visit(BO->getLHS());
15080
15081 if (O && isa<CompoundAssignOperator>(BO))
15082 notePostUse(O, BO);
15083
15084 Region = RHSRegion;
15085 Visit(BO->getRHS());
15086 }
15087
15088 // C++11 [expr.ass]p1:
15089 // the assignment is sequenced [...] before the value computation of the
15090 // assignment expression.
15091 // C11 6.5.16/3 has no such rule.
15092 Region = OldRegion;
15093 if (O)
15094 notePostMod(O, BO,
15095 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15096 : UK_ModAsSideEffect);
15097 if (SemaRef.getLangOpts().CPlusPlus17) {
15098 Tree.merge(RHSRegion);
15099 Tree.merge(LHSRegion);
15100 }
15101 }
15102
15103 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15104 VisitBinAssign(CAO);
15105 }
15106
15107 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15108 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15109 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15110 Object O = getObject(UO->getSubExpr(), true);
15111 if (!O)
15112 return VisitExpr(UO);
15113
15114 notePreMod(O, UO);
15115 Visit(UO->getSubExpr());
15116 // C++11 [expr.pre.incr]p1:
15117 // the expression ++x is equivalent to x+=1
15118 notePostMod(O, UO,
15119 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15120 : UK_ModAsSideEffect);
15121 }
15122
15123 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15124 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15125 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15126 Object O = getObject(UO->getSubExpr(), true);
15127 if (!O)
15128 return VisitExpr(UO);
15129
15130 notePreMod(O, UO);
15131 Visit(UO->getSubExpr());
15132 notePostMod(O, UO, UK_ModAsSideEffect);
15133 }
15134
15135 void VisitBinLOr(const BinaryOperator *BO) {
15136 // C++11 [expr.log.or]p2:
15137 // If the second expression is evaluated, every value computation and
15138 // side effect associated with the first expression is sequenced before
15139 // every value computation and side effect associated with the
15140 // second expression.
15141 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15142 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15143 SequenceTree::Seq OldRegion = Region;
15144
15145 EvaluationTracker Eval(*this);
15146 {
15147 SequencedSubexpression Sequenced(*this);
15148 Region = LHSRegion;
15149 Visit(BO->getLHS());
15150 }
15151
15152 // C++11 [expr.log.or]p1:
15153 // [...] the second operand is not evaluated if the first operand
15154 // evaluates to true.
15155 bool EvalResult = false;
15156 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15157 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15158 if (ShouldVisitRHS) {
15159 Region = RHSRegion;
15160 Visit(BO->getRHS());
15161 }
15162
15163 Region = OldRegion;
15164 Tree.merge(LHSRegion);
15165 Tree.merge(RHSRegion);
15166 }
15167
15168 void VisitBinLAnd(const BinaryOperator *BO) {
15169 // C++11 [expr.log.and]p2:
15170 // If the second expression is evaluated, every value computation and
15171 // side effect associated with the first expression is sequenced before
15172 // every value computation and side effect associated with the
15173 // second expression.
15174 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15175 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15176 SequenceTree::Seq OldRegion = Region;
15177
15178 EvaluationTracker Eval(*this);
15179 {
15180 SequencedSubexpression Sequenced(*this);
15181 Region = LHSRegion;
15182 Visit(BO->getLHS());
15183 }
15184
15185 // C++11 [expr.log.and]p1:
15186 // [...] the second operand is not evaluated if the first operand is false.
15187 bool EvalResult = false;
15188 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15189 bool ShouldVisitRHS = !EvalOK || EvalResult;
15190 if (ShouldVisitRHS) {
15191 Region = RHSRegion;
15192 Visit(BO->getRHS());
15193 }
15194
15195 Region = OldRegion;
15196 Tree.merge(LHSRegion);
15197 Tree.merge(RHSRegion);
15198 }
15199
15200 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15201 // C++11 [expr.cond]p1:
15202 // [...] Every value computation and side effect associated with the first
15203 // expression is sequenced before every value computation and side effect
15204 // associated with the second or third expression.
15205 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15206
15207 // No sequencing is specified between the true and false expression.
15208 // However since exactly one of both is going to be evaluated we can
15209 // consider them to be sequenced. This is needed to avoid warning on
15210 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15211 // both the true and false expressions because we can't evaluate x.
15212 // This will still allow us to detect an expression like (pre C++17)
15213 // "(x ? y += 1 : y += 2) = y".
15214 //
15215 // We don't wrap the visitation of the true and false expression with
15216 // SequencedSubexpression because we don't want to downgrade modifications
15217 // as side effect in the true and false expressions after the visition
15218 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15219 // not warn between the two "y++", but we should warn between the "y++"
15220 // and the "y".
15221 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15222 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15223 SequenceTree::Seq OldRegion = Region;
15224
15225 EvaluationTracker Eval(*this);
15226 {
15227 SequencedSubexpression Sequenced(*this);
15228 Region = ConditionRegion;
15229 Visit(CO->getCond());
15230 }
15231
15232 // C++11 [expr.cond]p1:
15233 // [...] The first expression is contextually converted to bool (Clause 4).
15234 // It is evaluated and if it is true, the result of the conditional
15235 // expression is the value of the second expression, otherwise that of the
15236 // third expression. Only one of the second and third expressions is
15237 // evaluated. [...]
15238 bool EvalResult = false;
15239 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15240 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15241 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15242 if (ShouldVisitTrueExpr) {
15243 Region = TrueRegion;
15244 Visit(CO->getTrueExpr());
15245 }
15246 if (ShouldVisitFalseExpr) {
15247 Region = FalseRegion;
15248 Visit(CO->getFalseExpr());
15249 }
15250
15251 Region = OldRegion;
15252 Tree.merge(ConditionRegion);
15253 Tree.merge(TrueRegion);
15254 Tree.merge(FalseRegion);
15255 }
15256
15257 void VisitCallExpr(const CallExpr *CE) {
15258 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15259
15260 if (CE->isUnevaluatedBuiltinCall(Context))
15261 return;
15262
15263 // C++11 [intro.execution]p15:
15264 // When calling a function [...], every value computation and side effect
15265 // associated with any argument expression, or with the postfix expression
15266 // designating the called function, is sequenced before execution of every
15267 // expression or statement in the body of the function [and thus before
15268 // the value computation of its result].
15269 SequencedSubexpression Sequenced(*this);
15270 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15271 // C++17 [expr.call]p5
15272 // The postfix-expression is sequenced before each expression in the
15273 // expression-list and any default argument. [...]
15274 SequenceTree::Seq CalleeRegion;
15275 SequenceTree::Seq OtherRegion;
15276 if (SemaRef.getLangOpts().CPlusPlus17) {
15277 CalleeRegion = Tree.allocate(Region);
15278 OtherRegion = Tree.allocate(Region);
15279 } else {
15280 CalleeRegion = Region;
15281 OtherRegion = Region;
15282 }
15283 SequenceTree::Seq OldRegion = Region;
15284
15285 // Visit the callee expression first.
15286 Region = CalleeRegion;
15287 if (SemaRef.getLangOpts().CPlusPlus17) {
15288 SequencedSubexpression Sequenced(*this);
15289 Visit(CE->getCallee());
15290 } else {
15291 Visit(CE->getCallee());
15292 }
15293
15294 // Then visit the argument expressions.
15295 Region = OtherRegion;
15296 for (const Expr *Argument : CE->arguments())
15297 Visit(Argument);
15298
15299 Region = OldRegion;
15300 if (SemaRef.getLangOpts().CPlusPlus17) {
15301 Tree.merge(CalleeRegion);
15302 Tree.merge(OtherRegion);
15303 }
15304 });
15305 }
15306
15307 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15308 // C++17 [over.match.oper]p2:
15309 // [...] the operator notation is first transformed to the equivalent
15310 // function-call notation as summarized in Table 12 (where @ denotes one
15311 // of the operators covered in the specified subclause). However, the
15312 // operands are sequenced in the order prescribed for the built-in
15313 // operator (Clause 8).
15314 //
15315 // From the above only overloaded binary operators and overloaded call
15316 // operators have sequencing rules in C++17 that we need to handle
15317 // separately.
15318 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15319 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15320 return VisitCallExpr(CXXOCE);
15321
15322 enum {
15323 NoSequencing,
15324 LHSBeforeRHS,
15325 RHSBeforeLHS,
15326 LHSBeforeRest
15327 } SequencingKind;
15328 switch (CXXOCE->getOperator()) {
15329 case OO_Equal:
15330 case OO_PlusEqual:
15331 case OO_MinusEqual:
15332 case OO_StarEqual:
15333 case OO_SlashEqual:
15334 case OO_PercentEqual:
15335 case OO_CaretEqual:
15336 case OO_AmpEqual:
15337 case OO_PipeEqual:
15338 case OO_LessLessEqual:
15339 case OO_GreaterGreaterEqual:
15340 SequencingKind = RHSBeforeLHS;
15341 break;
15342
15343 case OO_LessLess:
15344 case OO_GreaterGreater:
15345 case OO_AmpAmp:
15346 case OO_PipePipe:
15347 case OO_Comma:
15348 case OO_ArrowStar:
15349 case OO_Subscript:
15350 SequencingKind = LHSBeforeRHS;
15351 break;
15352
15353 case OO_Call:
15354 SequencingKind = LHSBeforeRest;
15355 break;
15356
15357 default:
15358 SequencingKind = NoSequencing;
15359 break;
15360 }
15361
15362 if (SequencingKind == NoSequencing)
15363 return VisitCallExpr(CXXOCE);
15364
15365 // This is a call, so all subexpressions are sequenced before the result.
15366 SequencedSubexpression Sequenced(*this);
15367
15368 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15369 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15370 "Should only get there with C++17 and above!");
15371 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15372 "Should only get there with an overloaded binary operator"
15373 " or an overloaded call operator!");
15374
15375 if (SequencingKind == LHSBeforeRest) {
15376 assert(CXXOCE->getOperator() == OO_Call &&
15377 "We should only have an overloaded call operator here!");
15378
15379 // This is very similar to VisitCallExpr, except that we only have the
15380 // C++17 case. The postfix-expression is the first argument of the
15381 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15382 // are in the following arguments.
15383 //
15384 // Note that we intentionally do not visit the callee expression since
15385 // it is just a decayed reference to a function.
15386 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15387 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15388 SequenceTree::Seq OldRegion = Region;
15389
15390 assert(CXXOCE->getNumArgs() >= 1 &&
15391 "An overloaded call operator must have at least one argument"
15392 " for the postfix-expression!");
15393 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15394 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15395 CXXOCE->getNumArgs() - 1);
15396
15397 // Visit the postfix-expression first.
15398 {
15399 Region = PostfixExprRegion;
15400 SequencedSubexpression Sequenced(*this);
15401 Visit(PostfixExpr);
15402 }
15403
15404 // Then visit the argument expressions.
15405 Region = ArgsRegion;
15406 for (const Expr *Arg : Args)
15407 Visit(Arg);
15408
15409 Region = OldRegion;
15410 Tree.merge(PostfixExprRegion);
15411 Tree.merge(ArgsRegion);
15412 } else {
15413 assert(CXXOCE->getNumArgs() == 2 &&
15414 "Should only have two arguments here!");
15415 assert((SequencingKind == LHSBeforeRHS ||
15416 SequencingKind == RHSBeforeLHS) &&
15417 "Unexpected sequencing kind!");
15418
15419 // We do not visit the callee expression since it is just a decayed
15420 // reference to a function.
15421 const Expr *E1 = CXXOCE->getArg(0);
15422 const Expr *E2 = CXXOCE->getArg(1);
15423 if (SequencingKind == RHSBeforeLHS)
15424 std::swap(E1, E2);
15425
15426 return VisitSequencedExpressions(E1, E2);
15427 }
15428 });
15429 }
15430
15431 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15432 // This is a call, so all subexpressions are sequenced before the result.
15433 SequencedSubexpression Sequenced(*this);
15434
15435 if (!CCE->isListInitialization())
15436 return VisitExpr(CCE);
15437
15438 // In C++11, list initializations are sequenced.
15439 SequenceExpressionsInOrder(
15440 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15441 }
15442
15443 void VisitInitListExpr(const InitListExpr *ILE) {
15444 if (!SemaRef.getLangOpts().CPlusPlus11)
15445 return VisitExpr(ILE);
15446
15447 // In C++11, list initializations are sequenced.
15448 SequenceExpressionsInOrder(ILE->inits());
15449 }
15450
15451 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15452 // C++20 parenthesized list initializations are sequenced. See C++20
15453 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15454 SequenceExpressionsInOrder(PLIE->getInitExprs());
15455 }
15456
15457private:
15458 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15460 SequenceTree::Seq Parent = Region;
15461 for (const Expr *E : ExpressionList) {
15462 if (!E)
15463 continue;
15464 Region = Tree.allocate(Parent);
15465 Elts.push_back(Region);
15466 Visit(E);
15467 }
15468
15469 // Forget that the initializers are sequenced.
15470 Region = Parent;
15471 for (unsigned I = 0; I < Elts.size(); ++I)
15472 Tree.merge(Elts[I]);
15473 }
15474};
15475
15476SequenceChecker::UsageInfo::UsageInfo() = default;
15477
15478} // namespace
15479
15480void Sema::CheckUnsequencedOperations(const Expr *E) {
15481 SmallVector<const Expr *, 8> WorkList;
15482 WorkList.push_back(E);
15483 while (!WorkList.empty()) {
15484 const Expr *Item = WorkList.pop_back_val();
15485 SequenceChecker(*this, Item, WorkList);
15486 }
15487}
15488
15489void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15490 bool IsConstexpr) {
15491 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15492 IsConstexpr || isa<ConstantExpr>(E));
15493 CheckImplicitConversions(E, CheckLoc);
15494 if (!E->isInstantiationDependent())
15495 CheckUnsequencedOperations(E);
15496 if (!IsConstexpr && !E->isValueDependent())
15497 CheckForIntOverflow(E);
15498}
15499
15500void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15501 FieldDecl *BitField,
15502 Expr *Init) {
15503 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15504}
15505
15507 SourceLocation Loc) {
15508 if (!PType->isVariablyModifiedType())
15509 return;
15510 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15511 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15512 return;
15513 }
15514 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15515 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15516 return;
15517 }
15518 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15519 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15520 return;
15521 }
15522
15523 const ArrayType *AT = S.Context.getAsArrayType(PType);
15524 if (!AT)
15525 return;
15526
15529 return;
15530 }
15531
15532 S.Diag(Loc, diag::err_array_star_in_function_definition);
15533}
15534
15536 bool CheckParameterNames) {
15537 bool HasInvalidParm = false;
15538 for (ParmVarDecl *Param : Parameters) {
15539 assert(Param && "null in a parameter list");
15540 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15541 // function declarator that is part of a function definition of
15542 // that function shall not have incomplete type.
15543 //
15544 // C++23 [dcl.fct.def.general]/p2
15545 // The type of a parameter [...] for a function definition
15546 // shall not be a (possibly cv-qualified) class type that is incomplete
15547 // or abstract within the function body unless the function is deleted.
15548 if (!Param->isInvalidDecl() &&
15549 (RequireCompleteType(Param->getLocation(), Param->getType(),
15550 diag::err_typecheck_decl_incomplete_type) ||
15551 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15552 diag::err_abstract_type_in_decl,
15554 Param->setInvalidDecl();
15555 HasInvalidParm = true;
15556 }
15557
15558 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15559 // declaration of each parameter shall include an identifier.
15560 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15561 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15562 // Diagnose this as an extension in C17 and earlier.
15563 if (!getLangOpts().C23)
15564 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15565 }
15566
15567 // C99 6.7.5.3p12:
15568 // If the function declarator is not part of a definition of that
15569 // function, parameters may have incomplete type and may use the [*]
15570 // notation in their sequences of declarator specifiers to specify
15571 // variable length array types.
15572 QualType PType = Param->getOriginalType();
15573 // FIXME: This diagnostic should point the '[*]' if source-location
15574 // information is added for it.
15575 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15576
15577 // If the parameter is a c++ class type and it has to be destructed in the
15578 // callee function, declare the destructor so that it can be called by the
15579 // callee function. Do not perform any direct access check on the dtor here.
15580 if (!Param->isInvalidDecl()) {
15581 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15582 if (!ClassDecl->isInvalidDecl() &&
15583 !ClassDecl->hasIrrelevantDestructor() &&
15584 !ClassDecl->isDependentContext() &&
15585 ClassDecl->isParamDestroyedInCallee()) {
15587 MarkFunctionReferenced(Param->getLocation(), Destructor);
15588 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15589 }
15590 }
15591 }
15592
15593 // Parameters with the pass_object_size attribute only need to be marked
15594 // constant at function definitions. Because we lack information about
15595 // whether we're on a declaration or definition when we're instantiating the
15596 // attribute, we need to check for constness here.
15597 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15598 if (!Param->getType().isConstQualified())
15599 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15600 << Attr->getSpelling() << 1;
15601
15602 // Check for parameter names shadowing fields from the class.
15603 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15604 // The owning context for the parameter should be the function, but we
15605 // want to see if this function's declaration context is a record.
15606 DeclContext *DC = Param->getDeclContext();
15607 if (DC && DC->isFunctionOrMethod()) {
15608 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15609 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15610 RD, /*DeclIsField*/ false);
15611 }
15612 }
15613
15614 if (!Param->isInvalidDecl() &&
15615 Param->getOriginalType()->isWebAssemblyTableType()) {
15616 Param->setInvalidDecl();
15617 HasInvalidParm = true;
15618 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15619 }
15620 }
15621
15622 return HasInvalidParm;
15623}
15624
15625std::optional<std::pair<
15627 *E,
15629 &Ctx);
15630
15631/// Compute the alignment and offset of the base class object given the
15632/// derived-to-base cast expression and the alignment and offset of the derived
15633/// class object.
15634static std::pair<CharUnits, CharUnits>
15636 CharUnits BaseAlignment, CharUnits Offset,
15637 ASTContext &Ctx) {
15638 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15639 ++PathI) {
15640 const CXXBaseSpecifier *Base = *PathI;
15641 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15642 if (Base->isVirtual()) {
15643 // The complete object may have a lower alignment than the non-virtual
15644 // alignment of the base, in which case the base may be misaligned. Choose
15645 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15646 // conservative lower bound of the complete object alignment.
15647 CharUnits NonVirtualAlignment =
15649 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15650 Offset = CharUnits::Zero();
15651 } else {
15652 const ASTRecordLayout &RL =
15653 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15654 Offset += RL.getBaseClassOffset(BaseDecl);
15655 }
15656 DerivedType = Base->getType();
15657 }
15658
15659 return std::make_pair(BaseAlignment, Offset);
15660}
15661
15662/// Compute the alignment and offset of a binary additive operator.
15663static std::optional<std::pair<CharUnits, CharUnits>>
15665 bool IsSub, ASTContext &Ctx) {
15666 QualType PointeeType = PtrE->getType()->getPointeeType();
15667
15668 if (!PointeeType->isConstantSizeType())
15669 return std::nullopt;
15670
15671 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15672
15673 if (!P)
15674 return std::nullopt;
15675
15676 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15677 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15678 CharUnits Offset = EltSize * IdxRes->getExtValue();
15679 if (IsSub)
15680 Offset = -Offset;
15681 return std::make_pair(P->first, P->second + Offset);
15682 }
15683
15684 // If the integer expression isn't a constant expression, compute the lower
15685 // bound of the alignment using the alignment and offset of the pointer
15686 // expression and the element size.
15687 return std::make_pair(
15688 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15689 CharUnits::Zero());
15690}
15691
15692/// This helper function takes an lvalue expression and returns the alignment of
15693/// a VarDecl and a constant offset from the VarDecl.
15694std::optional<std::pair<
15695 CharUnits,
15697 ASTContext &Ctx) {
15698 E = E->IgnoreParens();
15699 switch (E->getStmtClass()) {
15700 default:
15701 break;
15702 case Stmt::CStyleCastExprClass:
15703 case Stmt::CXXStaticCastExprClass:
15704 case Stmt::ImplicitCastExprClass: {
15705 auto *CE = cast<CastExpr>(E);
15706 const Expr *From = CE->getSubExpr();
15707 switch (CE->getCastKind()) {
15708 default:
15709 break;
15710 case CK_NoOp:
15711 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15712 case CK_UncheckedDerivedToBase:
15713 case CK_DerivedToBase: {
15714 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15715 if (!P)
15716 break;
15717 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15718 P->second, Ctx);
15719 }
15720 }
15721 break;
15722 }
15723 case Stmt::ArraySubscriptExprClass: {
15724 auto *ASE = cast<ArraySubscriptExpr>(E);
15726 false, Ctx);
15727 }
15728 case Stmt::DeclRefExprClass: {
15729 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15730 // FIXME: If VD is captured by copy or is an escaping __block variable,
15731 // use the alignment of VD's type.
15732 if (!VD->getType()->isReferenceType()) {
15733 // Dependent alignment cannot be resolved -> bail out.
15734 if (VD->hasDependentAlignment())
15735 break;
15736 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15737 }
15738 if (VD->hasInit())
15739 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15740 }
15741 break;
15742 }
15743 case Stmt::MemberExprClass: {
15744 auto *ME = cast<MemberExpr>(E);
15745 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15746 if (!FD || FD->getType()->isReferenceType() ||
15747 FD->getParent()->isInvalidDecl())
15748 break;
15749 std::optional<std::pair<CharUnits, CharUnits>> P;
15750 if (ME->isArrow())
15751 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15752 else
15753 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15754 if (!P)
15755 break;
15756 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15757 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15758 return std::make_pair(P->first,
15759 P->second + CharUnits::fromQuantity(Offset));
15760 }
15761 case Stmt::UnaryOperatorClass: {
15762 auto *UO = cast<UnaryOperator>(E);
15763 switch (UO->getOpcode()) {
15764 default:
15765 break;
15766 case UO_Deref:
15768 }
15769 break;
15770 }
15771 case Stmt::BinaryOperatorClass: {
15772 auto *BO = cast<BinaryOperator>(E);
15773 auto Opcode = BO->getOpcode();
15774 switch (Opcode) {
15775 default:
15776 break;
15777 case BO_Comma:
15779 }
15780 break;
15781 }
15782 }
15783 return std::nullopt;
15784}
15785
15786/// This helper function takes a pointer expression and returns the alignment of
15787/// a VarDecl and a constant offset from the VarDecl.
15788std::optional<std::pair<
15790 *E,
15792 &Ctx) {
15793 E = E->IgnoreParens();
15794 switch (E->getStmtClass()) {
15795 default:
15796 break;
15797 case Stmt::CStyleCastExprClass:
15798 case Stmt::CXXStaticCastExprClass:
15799 case Stmt::ImplicitCastExprClass: {
15800 auto *CE = cast<CastExpr>(E);
15801 const Expr *From = CE->getSubExpr();
15802 switch (CE->getCastKind()) {
15803 default:
15804 break;
15805 case CK_NoOp:
15806 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15807 case CK_ArrayToPointerDecay:
15808 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15809 case CK_UncheckedDerivedToBase:
15810 case CK_DerivedToBase: {
15811 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15812 if (!P)
15813 break;
15815 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15816 }
15817 }
15818 break;
15819 }
15820 case Stmt::CXXThisExprClass: {
15821 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15823 return std::make_pair(Alignment, CharUnits::Zero());
15824 }
15825 case Stmt::UnaryOperatorClass: {
15826 auto *UO = cast<UnaryOperator>(E);
15827 if (UO->getOpcode() == UO_AddrOf)
15829 break;
15830 }
15831 case Stmt::BinaryOperatorClass: {
15832 auto *BO = cast<BinaryOperator>(E);
15833 auto Opcode = BO->getOpcode();
15834 switch (Opcode) {
15835 default:
15836 break;
15837 case BO_Add:
15838 case BO_Sub: {
15839 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15840 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15841 std::swap(LHS, RHS);
15842 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15843 Ctx);
15844 }
15845 case BO_Comma:
15846 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15847 }
15848 break;
15849 }
15850 }
15851 return std::nullopt;
15852}
15853
15855 // See if we can compute the alignment of a VarDecl and an offset from it.
15856 std::optional<std::pair<CharUnits, CharUnits>> P =
15858
15859 if (P)
15860 return P->first.alignmentAtOffset(P->second);
15861
15862 // If that failed, return the type's alignment.
15864}
15865
15867 // This is actually a lot of work to potentially be doing on every
15868 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15869 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15870 return;
15871
15872 // Ignore dependent types.
15873 if (T->isDependentType() || Op->getType()->isDependentType())
15874 return;
15875
15876 // Require that the destination be a pointer type.
15877 const PointerType *DestPtr = T->getAs<PointerType>();
15878 if (!DestPtr) return;
15879
15880 // If the destination has alignment 1, we're done.
15881 QualType DestPointee = DestPtr->getPointeeType();
15882 if (DestPointee->isIncompleteType()) return;
15883 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15884 if (DestAlign.isOne()) return;
15885
15886 // Require that the source be a pointer type.
15887 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15888 if (!SrcPtr) return;
15889 QualType SrcPointee = SrcPtr->getPointeeType();
15890
15891 // Explicitly allow casts from cv void*. We already implicitly
15892 // allowed casts to cv void*, since they have alignment 1.
15893 // Also allow casts involving incomplete types, which implicitly
15894 // includes 'void'.
15895 if (SrcPointee->isIncompleteType()) return;
15896
15897 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15898
15899 if (SrcAlign >= DestAlign) return;
15900
15901 Diag(TRange.getBegin(), diag::warn_cast_align)
15902 << Op->getType() << T
15903 << static_cast<unsigned>(SrcAlign.getQuantity())
15904 << static_cast<unsigned>(DestAlign.getQuantity())
15905 << TRange << Op->getSourceRange();
15906}
15907
15908void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15909 const ArraySubscriptExpr *ASE,
15910 bool AllowOnePastEnd, bool IndexNegated) {
15911 // Already diagnosed by the constant evaluator.
15913 return;
15914
15915 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15916 if (IndexExpr->isValueDependent())
15917 return;
15918
15919 const Type *EffectiveType =
15921 BaseExpr = BaseExpr->IgnoreParenCasts();
15922 const ConstantArrayType *ArrayTy =
15923 Context.getAsConstantArrayType(BaseExpr->getType());
15924
15926 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15927
15928 const Type *BaseType =
15929 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15930 bool IsUnboundedArray =
15931 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15932 Context, StrictFlexArraysLevel,
15933 /*IgnoreTemplateOrMacroSubstitution=*/true);
15934 if (EffectiveType->isDependentType() ||
15935 (!IsUnboundedArray && BaseType->isDependentType()))
15936 return;
15937
15939 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15940 return;
15941
15942 llvm::APSInt index = Result.Val.getInt();
15943 if (IndexNegated) {
15944 index.setIsUnsigned(false);
15945 index = -index;
15946 }
15947
15948 if (IsUnboundedArray) {
15949 if (EffectiveType->isFunctionType())
15950 return;
15951 if (index.isUnsigned() || !index.isNegative()) {
15952 const auto &ASTC = getASTContext();
15953 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15954 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15955 if (index.getBitWidth() < AddrBits)
15956 index = index.zext(AddrBits);
15957 std::optional<CharUnits> ElemCharUnits =
15958 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15959 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15960 // pointer) bounds-checking isn't meaningful.
15961 if (!ElemCharUnits || ElemCharUnits->isZero())
15962 return;
15963 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15964 // If index has more active bits than address space, we already know
15965 // we have a bounds violation to warn about. Otherwise, compute
15966 // address of (index + 1)th element, and warn about bounds violation
15967 // only if that address exceeds address space.
15968 if (index.getActiveBits() <= AddrBits) {
15969 bool Overflow;
15970 llvm::APInt Product(index);
15971 Product += 1;
15972 Product = Product.umul_ov(ElemBytes, Overflow);
15973 if (!Overflow && Product.getActiveBits() <= AddrBits)
15974 return;
15975 }
15976
15977 // Need to compute max possible elements in address space, since that
15978 // is included in diag message.
15979 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15980 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15981 MaxElems += 1;
15982 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15983 MaxElems = MaxElems.udiv(ElemBytes);
15984
15985 unsigned DiagID =
15986 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15987 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15988
15989 // Diag message shows element size in bits and in "bytes" (platform-
15990 // dependent CharUnits)
15991 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15992 PDiag(DiagID) << index << AddrBits
15993 << (unsigned)ASTC.toBits(*ElemCharUnits)
15994 << ElemBytes << MaxElems
15995 << MaxElems.getZExtValue()
15996 << IndexExpr->getSourceRange());
15997
15998 const NamedDecl *ND = nullptr;
15999 // Try harder to find a NamedDecl to point at in the note.
16000 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16001 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16002 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16003 ND = DRE->getDecl();
16004 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16005 ND = ME->getMemberDecl();
16006
16007 if (ND)
16008 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16009 PDiag(diag::note_array_declared_here) << ND);
16010 }
16011 return;
16012 }
16013
16014 if (index.isUnsigned() || !index.isNegative()) {
16015 // It is possible that the type of the base expression after
16016 // IgnoreParenCasts is incomplete, even though the type of the base
16017 // expression before IgnoreParenCasts is complete (see PR39746 for an
16018 // example). In this case we have no information about whether the array
16019 // access exceeds the array bounds. However we can still diagnose an array
16020 // access which precedes the array bounds.
16021 if (BaseType->isIncompleteType())
16022 return;
16023
16024 llvm::APInt size = ArrayTy->getSize();
16025
16026 if (BaseType != EffectiveType) {
16027 // Make sure we're comparing apples to apples when comparing index to
16028 // size.
16029 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
16030 uint64_t array_typesize = Context.getTypeSize(BaseType);
16031
16032 // Handle ptrarith_typesize being zero, such as when casting to void*.
16033 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16034 if (!ptrarith_typesize)
16035 ptrarith_typesize = Context.getCharWidth();
16036
16037 if (ptrarith_typesize != array_typesize) {
16038 // There's a cast to a different size type involved.
16039 uint64_t ratio = array_typesize / ptrarith_typesize;
16040
16041 // TODO: Be smarter about handling cases where array_typesize is not a
16042 // multiple of ptrarith_typesize.
16043 if (ptrarith_typesize * ratio == array_typesize)
16044 size *= llvm::APInt(size.getBitWidth(), ratio);
16045 }
16046 }
16047
16048 if (size.getBitWidth() > index.getBitWidth())
16049 index = index.zext(size.getBitWidth());
16050 else if (size.getBitWidth() < index.getBitWidth())
16051 size = size.zext(index.getBitWidth());
16052
16053 // For array subscripting the index must be less than size, but for pointer
16054 // arithmetic also allow the index (offset) to be equal to size since
16055 // computing the next address after the end of the array is legal and
16056 // commonly done e.g. in C++ iterators and range-based for loops.
16057 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16058 return;
16059
16060 // Suppress the warning if the subscript expression (as identified by the
16061 // ']' location) and the index expression are both from macro expansions
16062 // within a system header.
16063 if (ASE) {
16064 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16065 ASE->getRBracketLoc());
16066 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
16067 SourceLocation IndexLoc =
16068 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
16069 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16070 return;
16071 }
16072 }
16073
16074 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16075 : diag::warn_ptr_arith_exceeds_bounds;
16076 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16077 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16078
16079 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16080 PDiag(DiagID)
16081 << index << ArrayTy->desugar() << CastMsg
16082 << CastMsgTy << IndexExpr->getSourceRange());
16083 } else {
16084 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16085 if (!ASE) {
16086 DiagID = diag::warn_ptr_arith_precedes_bounds;
16087 if (index.isNegative()) index = -index;
16088 }
16089
16090 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16091 PDiag(DiagID) << index << IndexExpr->getSourceRange());
16092 }
16093
16094 const NamedDecl *ND = nullptr;
16095 // Try harder to find a NamedDecl to point at in the note.
16096 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16097 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16098 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16099 ND = DRE->getDecl();
16100 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16101 ND = ME->getMemberDecl();
16102
16103 if (ND)
16104 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16105 PDiag(diag::note_array_declared_here) << ND);
16106}
16107
16108void Sema::CheckArrayAccess(const Expr *expr) {
16109 int AllowOnePastEnd = 0;
16110 while (expr) {
16111 expr = expr->IgnoreParenImpCasts();
16112 switch (expr->getStmtClass()) {
16113 case Stmt::ArraySubscriptExprClass: {
16114 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16115 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16116 AllowOnePastEnd > 0);
16117 expr = ASE->getBase();
16118 break;
16119 }
16120 case Stmt::MemberExprClass: {
16121 expr = cast<MemberExpr>(expr)->getBase();
16122 break;
16123 }
16124 case Stmt::CXXMemberCallExprClass: {
16125 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16126 break;
16127 }
16128 case Stmt::ArraySectionExprClass: {
16129 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16130 // FIXME: We should probably be checking all of the elements to the
16131 // 'length' here as well.
16132 if (ASE->getLowerBound())
16133 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16134 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16135 return;
16136 }
16137 case Stmt::UnaryOperatorClass: {
16138 // Only unwrap the * and & unary operators
16139 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16140 expr = UO->getSubExpr();
16141 switch (UO->getOpcode()) {
16142 case UO_AddrOf:
16143 AllowOnePastEnd++;
16144 break;
16145 case UO_Deref:
16146 AllowOnePastEnd--;
16147 break;
16148 default:
16149 return;
16150 }
16151 break;
16152 }
16153 case Stmt::ConditionalOperatorClass: {
16154 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16155 if (const Expr *lhs = cond->getLHS())
16156 CheckArrayAccess(lhs);
16157 if (const Expr *rhs = cond->getRHS())
16158 CheckArrayAccess(rhs);
16159 return;
16160 }
16161 case Stmt::CXXOperatorCallExprClass: {
16162 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16163 for (const auto *Arg : OCE->arguments())
16164 CheckArrayAccess(Arg);
16165 return;
16166 }
16167 default:
16168 return;
16169 }
16170 }
16171}
16172
16174 Expr *RHS, bool isProperty) {
16175 // Check if RHS is an Objective-C object literal, which also can get
16176 // immediately zapped in a weak reference. Note that we explicitly
16177 // allow ObjCStringLiterals, since those are designed to never really die.
16178 RHS = RHS->IgnoreParenImpCasts();
16179
16180 // This enum needs to match with the 'select' in
16181 // warn_objc_arc_literal_assign (off-by-1).
16183 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16184 return false;
16185
16186 S.Diag(Loc, diag::warn_arc_literal_assign)
16187 << (unsigned) Kind
16188 << (isProperty ? 0 : 1)
16189 << RHS->getSourceRange();
16190
16191 return true;
16192}
16193
16196 Expr *RHS, bool isProperty) {
16197 // Strip off any implicit cast added to get to the one ARC-specific.
16198 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16199 if (cast->getCastKind() == CK_ARCConsumeObject) {
16200 S.Diag(Loc, diag::warn_arc_retained_assign)
16202 << (isProperty ? 0 : 1)
16203 << RHS->getSourceRange();
16204 return true;
16205 }
16206 RHS = cast->getSubExpr();
16207 }
16208
16209 if (LT == Qualifiers::OCL_Weak &&
16210 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16211 return true;
16212
16213 return false;
16214}
16215
16217 QualType LHS, Expr *RHS) {
16219
16221 return false;
16222
16223 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16224 return true;
16225
16226 return false;
16227}
16228
16230 Expr *LHS, Expr *RHS) {
16231 QualType LHSType;
16232 // PropertyRef on LHS type need be directly obtained from
16233 // its declaration as it has a PseudoType.
16235 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16236 if (PRE && !PRE->isImplicitProperty()) {
16237 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16238 if (PD)
16239 LHSType = PD->getType();
16240 }
16241
16242 if (LHSType.isNull())
16243 LHSType = LHS->getType();
16244
16246
16247 if (LT == Qualifiers::OCL_Weak) {
16248 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16250 }
16251
16252 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16253 return;
16254
16255 // FIXME. Check for other life times.
16256 if (LT != Qualifiers::OCL_None)
16257 return;
16258
16259 if (PRE) {
16260 if (PRE->isImplicitProperty())
16261 return;
16262 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16263 if (!PD)
16264 return;
16265
16266 unsigned Attributes = PD->getPropertyAttributes();
16267 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16268 // when 'assign' attribute was not explicitly specified
16269 // by user, ignore it and rely on property type itself
16270 // for lifetime info.
16271 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16272 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16273 LHSType->isObjCRetainableType())
16274 return;
16275
16276 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16277 if (cast->getCastKind() == CK_ARCConsumeObject) {
16278 Diag(Loc, diag::warn_arc_retained_property_assign)
16279 << RHS->getSourceRange();
16280 return;
16281 }
16282 RHS = cast->getSubExpr();
16283 }
16284 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16285 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16286 return;
16287 }
16288 }
16289}
16290
16291//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16292
16293static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16294 SourceLocation StmtLoc,
16295 const NullStmt *Body) {
16296 // Do not warn if the body is a macro that expands to nothing, e.g:
16297 //
16298 // #define CALL(x)
16299 // if (condition)
16300 // CALL(0);
16301 if (Body->hasLeadingEmptyMacro())
16302 return false;
16303
16304 // Get line numbers of statement and body.
16305 bool StmtLineInvalid;
16306 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16307 &StmtLineInvalid);
16308 if (StmtLineInvalid)
16309 return false;
16310
16311 bool BodyLineInvalid;
16312 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16313 &BodyLineInvalid);
16314 if (BodyLineInvalid)
16315 return false;
16316
16317 // Warn if null statement and body are on the same line.
16318 if (StmtLine != BodyLine)
16319 return false;
16320
16321 return true;
16322}
16323
16325 const Stmt *Body,
16326 unsigned DiagID) {
16327 // Since this is a syntactic check, don't emit diagnostic for template
16328 // instantiations, this just adds noise.
16330 return;
16331
16332 // The body should be a null statement.
16333 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16334 if (!NBody)
16335 return;
16336
16337 // Do the usual checks.
16338 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16339 return;
16340
16341 Diag(NBody->getSemiLoc(), DiagID);
16342 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16343}
16344
16346 const Stmt *PossibleBody) {
16347 assert(!CurrentInstantiationScope); // Ensured by caller
16348
16349 SourceLocation StmtLoc;
16350 const Stmt *Body;
16351 unsigned DiagID;
16352 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16353 StmtLoc = FS->getRParenLoc();
16354 Body = FS->getBody();
16355 DiagID = diag::warn_empty_for_body;
16356 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16357 StmtLoc = WS->getRParenLoc();
16358 Body = WS->getBody();
16359 DiagID = diag::warn_empty_while_body;
16360 } else
16361 return; // Neither `for' nor `while'.
16362
16363 // The body should be a null statement.
16364 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16365 if (!NBody)
16366 return;
16367
16368 // Skip expensive checks if diagnostic is disabled.
16369 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16370 return;
16371
16372 // Do the usual checks.
16373 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16374 return;
16375
16376 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16377 // noise level low, emit diagnostics only if for/while is followed by a
16378 // CompoundStmt, e.g.:
16379 // for (int i = 0; i < n; i++);
16380 // {
16381 // a(i);
16382 // }
16383 // or if for/while is followed by a statement with more indentation
16384 // than for/while itself:
16385 // for (int i = 0; i < n; i++);
16386 // a(i);
16387 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16388 if (!ProbableTypo) {
16389 bool BodyColInvalid;
16390 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16391 PossibleBody->getBeginLoc(), &BodyColInvalid);
16392 if (BodyColInvalid)
16393 return;
16394
16395 bool StmtColInvalid;
16396 unsigned StmtCol =
16397 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16398 if (StmtColInvalid)
16399 return;
16400
16401 if (BodyCol > StmtCol)
16402 ProbableTypo = true;
16403 }
16404
16405 if (ProbableTypo) {
16406 Diag(NBody->getSemiLoc(), DiagID);
16407 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16408 }
16409}
16410
16411//===--- CHECK: Warn on self move with std::move. -------------------------===//
16412
16413void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16414 SourceLocation OpLoc) {
16415 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16416 return;
16417
16419 return;
16420
16421 // Strip parens and casts away.
16422 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16423 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16424
16425 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16426 // which we can treat as an inlined std::move
16427 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16428 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16429 RHSExpr = CE->getArg(0);
16430 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16431 CXXSCE && CXXSCE->isXValue())
16432 RHSExpr = CXXSCE->getSubExpr();
16433 else
16434 return;
16435
16436 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16437 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16438
16439 // Two DeclRefExpr's, check that the decls are the same.
16440 if (LHSDeclRef && RHSDeclRef) {
16441 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16442 return;
16443 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16444 RHSDeclRef->getDecl()->getCanonicalDecl())
16445 return;
16446
16447 auto D = Diag(OpLoc, diag::warn_self_move)
16448 << LHSExpr->getType() << LHSExpr->getSourceRange()
16449 << RHSExpr->getSourceRange();
16450 if (const FieldDecl *F =
16452 D << 1 << F
16453 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16454 else
16455 D << 0;
16456 return;
16457 }
16458
16459 // Member variables require a different approach to check for self moves.
16460 // MemberExpr's are the same if every nested MemberExpr refers to the same
16461 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16462 // the base Expr's are CXXThisExpr's.
16463 const Expr *LHSBase = LHSExpr;
16464 const Expr *RHSBase = RHSExpr;
16465 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16466 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16467 if (!LHSME || !RHSME)
16468 return;
16469
16470 while (LHSME && RHSME) {
16471 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16472 RHSME->getMemberDecl()->getCanonicalDecl())
16473 return;
16474
16475 LHSBase = LHSME->getBase();
16476 RHSBase = RHSME->getBase();
16477 LHSME = dyn_cast<MemberExpr>(LHSBase);
16478 RHSME = dyn_cast<MemberExpr>(RHSBase);
16479 }
16480
16481 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16482 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16483 if (LHSDeclRef && RHSDeclRef) {
16484 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16485 return;
16486 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16487 RHSDeclRef->getDecl()->getCanonicalDecl())
16488 return;
16489
16490 Diag(OpLoc, diag::warn_self_move)
16491 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16492 << RHSExpr->getSourceRange();
16493 return;
16494 }
16495
16496 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16497 Diag(OpLoc, diag::warn_self_move)
16498 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16499 << RHSExpr->getSourceRange();
16500}
16501
16502//===--- Layout compatibility ----------------------------------------------//
16503
16504static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16505
16506/// Check if two enumeration types are layout-compatible.
16507static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16508 const EnumDecl *ED2) {
16509 // C++11 [dcl.enum] p8:
16510 // Two enumeration types are layout-compatible if they have the same
16511 // underlying type.
16512 return ED1->isComplete() && ED2->isComplete() &&
16513 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16514}
16515
16516/// Check if two fields are layout-compatible.
16517/// Can be used on union members, which are exempt from alignment requirement
16518/// of common initial sequence.
16519static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16520 const FieldDecl *Field2,
16521 bool AreUnionMembers = false) {
16522#ifndef NDEBUG
16523 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16524 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16525 assert(((Field1Parent->isStructureOrClassType() &&
16526 Field2Parent->isStructureOrClassType()) ||
16527 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16528 "Can't evaluate layout compatibility between a struct field and a "
16529 "union field.");
16530 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16531 (AreUnionMembers && Field1Parent->isUnionType())) &&
16532 "AreUnionMembers should be 'true' for union fields (only).");
16533#endif
16534
16535 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16536 return false;
16537
16538 if (Field1->isBitField() != Field2->isBitField())
16539 return false;
16540
16541 if (Field1->isBitField()) {
16542 // Make sure that the bit-fields are the same length.
16543 unsigned Bits1 = Field1->getBitWidthValue();
16544 unsigned Bits2 = Field2->getBitWidthValue();
16545
16546 if (Bits1 != Bits2)
16547 return false;
16548 }
16549
16550 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16551 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16552 return false;
16553
16554 if (!AreUnionMembers &&
16555 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16556 return false;
16557
16558 return true;
16559}
16560
16561/// Check if two standard-layout structs are layout-compatible.
16562/// (C++11 [class.mem] p17)
16563static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16564 const RecordDecl *RD2) {
16565 // Get to the class where the fields are declared
16566 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16567 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16568
16569 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16570 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16571
16572 // Check the fields.
16573 return llvm::equal(RD1->fields(), RD2->fields(),
16574 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16575 return isLayoutCompatible(C, F1, F2);
16576 });
16577}
16578
16579/// Check if two standard-layout unions are layout-compatible.
16580/// (C++11 [class.mem] p18)
16581static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16582 const RecordDecl *RD2) {
16583 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16584 RD2->fields());
16585
16586 for (auto *Field1 : RD1->fields()) {
16587 auto I = UnmatchedFields.begin();
16588 auto E = UnmatchedFields.end();
16589
16590 for ( ; I != E; ++I) {
16591 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16592 bool Result = UnmatchedFields.erase(*I);
16593 (void) Result;
16594 assert(Result);
16595 break;
16596 }
16597 }
16598 if (I == E)
16599 return false;
16600 }
16601
16602 return UnmatchedFields.empty();
16603}
16604
16605static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16606 const RecordDecl *RD2) {
16607 if (RD1->isUnion() != RD2->isUnion())
16608 return false;
16609
16610 if (RD1->isUnion())
16611 return isLayoutCompatibleUnion(C, RD1, RD2);
16612 else
16613 return isLayoutCompatibleStruct(C, RD1, RD2);
16614}
16615
16616/// Check if two types are layout-compatible in C++11 sense.
16617static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16618 if (T1.isNull() || T2.isNull())
16619 return false;
16620
16621 // C++20 [basic.types] p11:
16622 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16623 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16624 // or layout-compatible standard-layout class types (11.4).
16627
16628 if (C.hasSameType(T1, T2))
16629 return true;
16630
16631 const Type::TypeClass TC1 = T1->getTypeClass();
16632 const Type::TypeClass TC2 = T2->getTypeClass();
16633
16634 if (TC1 != TC2)
16635 return false;
16636
16637 if (TC1 == Type::Enum)
16638 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16639 if (TC1 == Type::Record) {
16640 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16641 return false;
16642
16644 T2->castAsRecordDecl());
16645 }
16646
16647 return false;
16648}
16649
16651 return isLayoutCompatible(getASTContext(), T1, T2);
16652}
16653
16654//===-------------- Pointer interconvertibility ----------------------------//
16655
16657 const TypeSourceInfo *Derived) {
16658 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16659 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16660
16661 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16662 getASTContext().hasSameType(BaseT, DerivedT))
16663 return true;
16664
16665 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16666 return false;
16667
16668 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16669 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16670 return true;
16671
16672 return false;
16673}
16674
16675//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16676
16677/// Given a type tag expression find the type tag itself.
16678///
16679/// \param TypeExpr Type tag expression, as it appears in user's code.
16680///
16681/// \param VD Declaration of an identifier that appears in a type tag.
16682///
16683/// \param MagicValue Type tag magic value.
16684///
16685/// \param isConstantEvaluated whether the evalaution should be performed in
16686
16687/// constant context.
16688static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16689 const ValueDecl **VD, uint64_t *MagicValue,
16690 bool isConstantEvaluated) {
16691 while(true) {
16692 if (!TypeExpr)
16693 return false;
16694
16695 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16696
16697 switch (TypeExpr->getStmtClass()) {
16698 case Stmt::UnaryOperatorClass: {
16699 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16700 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16701 TypeExpr = UO->getSubExpr();
16702 continue;
16703 }
16704 return false;
16705 }
16706
16707 case Stmt::DeclRefExprClass: {
16708 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16709 *VD = DRE->getDecl();
16710 return true;
16711 }
16712
16713 case Stmt::IntegerLiteralClass: {
16714 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16715 llvm::APInt MagicValueAPInt = IL->getValue();
16716 if (MagicValueAPInt.getActiveBits() <= 64) {
16717 *MagicValue = MagicValueAPInt.getZExtValue();
16718 return true;
16719 } else
16720 return false;
16721 }
16722
16723 case Stmt::BinaryConditionalOperatorClass:
16724 case Stmt::ConditionalOperatorClass: {
16725 const AbstractConditionalOperator *ACO =
16727 bool Result;
16728 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16729 isConstantEvaluated)) {
16730 if (Result)
16731 TypeExpr = ACO->getTrueExpr();
16732 else
16733 TypeExpr = ACO->getFalseExpr();
16734 continue;
16735 }
16736 return false;
16737 }
16738
16739 case Stmt::BinaryOperatorClass: {
16740 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16741 if (BO->getOpcode() == BO_Comma) {
16742 TypeExpr = BO->getRHS();
16743 continue;
16744 }
16745 return false;
16746 }
16747
16748 default:
16749 return false;
16750 }
16751 }
16752}
16753
16754/// Retrieve the C type corresponding to type tag TypeExpr.
16755///
16756/// \param TypeExpr Expression that specifies a type tag.
16757///
16758/// \param MagicValues Registered magic values.
16759///
16760/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16761/// kind.
16762///
16763/// \param TypeInfo Information about the corresponding C type.
16764///
16765/// \param isConstantEvaluated whether the evalaution should be performed in
16766/// constant context.
16767///
16768/// \returns true if the corresponding C type was found.
16770 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16771 const ASTContext &Ctx,
16772 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16773 *MagicValues,
16774 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16775 bool isConstantEvaluated) {
16776 FoundWrongKind = false;
16777
16778 // Variable declaration that has type_tag_for_datatype attribute.
16779 const ValueDecl *VD = nullptr;
16780
16781 uint64_t MagicValue;
16782
16783 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16784 return false;
16785
16786 if (VD) {
16787 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16788 if (I->getArgumentKind() != ArgumentKind) {
16789 FoundWrongKind = true;
16790 return false;
16791 }
16792 TypeInfo.Type = I->getMatchingCType();
16793 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16794 TypeInfo.MustBeNull = I->getMustBeNull();
16795 return true;
16796 }
16797 return false;
16798 }
16799
16800 if (!MagicValues)
16801 return false;
16802
16803 llvm::DenseMap<Sema::TypeTagMagicValue,
16805 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16806 if (I == MagicValues->end())
16807 return false;
16808
16809 TypeInfo = I->second;
16810 return true;
16811}
16812
16814 uint64_t MagicValue, QualType Type,
16815 bool LayoutCompatible,
16816 bool MustBeNull) {
16817 if (!TypeTagForDatatypeMagicValues)
16818 TypeTagForDatatypeMagicValues.reset(
16819 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16820
16821 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16822 (*TypeTagForDatatypeMagicValues)[Magic] =
16823 TypeTagData(Type, LayoutCompatible, MustBeNull);
16824}
16825
16826static bool IsSameCharType(QualType T1, QualType T2) {
16827 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16828 if (!BT1)
16829 return false;
16830
16831 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16832 if (!BT2)
16833 return false;
16834
16835 BuiltinType::Kind T1Kind = BT1->getKind();
16836 BuiltinType::Kind T2Kind = BT2->getKind();
16837
16838 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16839 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16840 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16841 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16842}
16843
16844void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16845 const ArrayRef<const Expr *> ExprArgs,
16846 SourceLocation CallSiteLoc) {
16847 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16848 bool IsPointerAttr = Attr->getIsPointer();
16849
16850 // Retrieve the argument representing the 'type_tag'.
16851 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16852 if (TypeTagIdxAST >= ExprArgs.size()) {
16853 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16854 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16855 return;
16856 }
16857 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16858 bool FoundWrongKind;
16859 TypeTagData TypeInfo;
16860 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16861 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16862 TypeInfo, isConstantEvaluatedContext())) {
16863 if (FoundWrongKind)
16864 Diag(TypeTagExpr->getExprLoc(),
16865 diag::warn_type_tag_for_datatype_wrong_kind)
16866 << TypeTagExpr->getSourceRange();
16867 return;
16868 }
16869
16870 // Retrieve the argument representing the 'arg_idx'.
16871 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16872 if (ArgumentIdxAST >= ExprArgs.size()) {
16873 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16874 << 1 << Attr->getArgumentIdx().getSourceIndex();
16875 return;
16876 }
16877 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16878 if (IsPointerAttr) {
16879 // Skip implicit cast of pointer to `void *' (as a function argument).
16880 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16881 if (ICE->getType()->isVoidPointerType() &&
16882 ICE->getCastKind() == CK_BitCast)
16883 ArgumentExpr = ICE->getSubExpr();
16884 }
16885 QualType ArgumentType = ArgumentExpr->getType();
16886
16887 // Passing a `void*' pointer shouldn't trigger a warning.
16888 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16889 return;
16890
16891 if (TypeInfo.MustBeNull) {
16892 // Type tag with matching void type requires a null pointer.
16893 if (!ArgumentExpr->isNullPointerConstant(Context,
16895 Diag(ArgumentExpr->getExprLoc(),
16896 diag::warn_type_safety_null_pointer_required)
16897 << ArgumentKind->getName()
16898 << ArgumentExpr->getSourceRange()
16899 << TypeTagExpr->getSourceRange();
16900 }
16901 return;
16902 }
16903
16904 QualType RequiredType = TypeInfo.Type;
16905 if (IsPointerAttr)
16906 RequiredType = Context.getPointerType(RequiredType);
16907
16908 bool mismatch = false;
16909 if (!TypeInfo.LayoutCompatible) {
16910 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16911
16912 // C++11 [basic.fundamental] p1:
16913 // Plain char, signed char, and unsigned char are three distinct types.
16914 //
16915 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16916 // char' depending on the current char signedness mode.
16917 if (mismatch)
16918 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16919 RequiredType->getPointeeType())) ||
16920 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16921 mismatch = false;
16922 } else
16923 if (IsPointerAttr)
16924 mismatch = !isLayoutCompatible(Context,
16925 ArgumentType->getPointeeType(),
16926 RequiredType->getPointeeType());
16927 else
16928 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16929
16930 if (mismatch)
16931 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16932 << ArgumentType << ArgumentKind
16933 << TypeInfo.LayoutCompatible << RequiredType
16934 << ArgumentExpr->getSourceRange()
16935 << TypeTagExpr->getSourceRange();
16936}
16937
16938void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16939 CharUnits Alignment) {
16940 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16941 Alignment);
16942}
16943
16945 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16946 const NamedDecl *ND = m.RD;
16947 if (ND->getName().empty()) {
16948 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16949 ND = TD;
16950 }
16951 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16952 << m.MD << ND << m.E->getSourceRange();
16953 }
16955}
16956
16958 E = E->IgnoreParens();
16959 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16960 return;
16961 if (isa<UnaryOperator>(E) &&
16962 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16963 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16964 if (isa<MemberExpr>(Op)) {
16965 auto &MisalignedMembersForExpr =
16967 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16968 if (MA != MisalignedMembersForExpr.end() &&
16969 (T->isDependentType() || T->isIntegerType() ||
16970 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16971 Context.getTypeAlignInChars(
16972 T->getPointeeType()) <= MA->Alignment))))
16973 MisalignedMembersForExpr.erase(MA);
16974 }
16975 }
16976}
16977
16979 Expr *E,
16980 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16981 Action) {
16982 const auto *ME = dyn_cast<MemberExpr>(E);
16983 if (!ME)
16984 return;
16985
16986 // No need to check expressions with an __unaligned-qualified type.
16987 if (E->getType().getQualifiers().hasUnaligned())
16988 return;
16989
16990 // For a chain of MemberExpr like "a.b.c.d" this list
16991 // will keep FieldDecl's like [d, c, b].
16992 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16993 const MemberExpr *TopME = nullptr;
16994 bool AnyIsPacked = false;
16995 do {
16996 QualType BaseType = ME->getBase()->getType();
16997 if (BaseType->isDependentType())
16998 return;
16999 if (ME->isArrow())
17000 BaseType = BaseType->getPointeeType();
17001 auto *RD = BaseType->castAsRecordDecl();
17002 if (RD->isInvalidDecl())
17003 return;
17004
17005 ValueDecl *MD = ME->getMemberDecl();
17006 auto *FD = dyn_cast<FieldDecl>(MD);
17007 // We do not care about non-data members.
17008 if (!FD || FD->isInvalidDecl())
17009 return;
17010
17011 AnyIsPacked =
17012 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17013 ReverseMemberChain.push_back(FD);
17014
17015 TopME = ME;
17016 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17017 } while (ME);
17018 assert(TopME && "We did not compute a topmost MemberExpr!");
17019
17020 // Not the scope of this diagnostic.
17021 if (!AnyIsPacked)
17022 return;
17023
17024 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17025 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17026 // TODO: The innermost base of the member expression may be too complicated.
17027 // For now, just disregard these cases. This is left for future
17028 // improvement.
17029 if (!DRE && !isa<CXXThisExpr>(TopBase))
17030 return;
17031
17032 // Alignment expected by the whole expression.
17033 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17034
17035 // No need to do anything else with this case.
17036 if (ExpectedAlignment.isOne())
17037 return;
17038
17039 // Synthesize offset of the whole access.
17040 CharUnits Offset;
17041 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17042 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17043
17044 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17045 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17046 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17047
17048 // The base expression of the innermost MemberExpr may give
17049 // stronger guarantees than the class containing the member.
17050 if (DRE && !TopME->isArrow()) {
17051 const ValueDecl *VD = DRE->getDecl();
17052 if (!VD->getType()->isReferenceType())
17053 CompleteObjectAlignment =
17054 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17055 }
17056
17057 // Check if the synthesized offset fulfills the alignment.
17058 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17059 // It may fulfill the offset it but the effective alignment may still be
17060 // lower than the expected expression alignment.
17061 CompleteObjectAlignment < ExpectedAlignment) {
17062 // If this happens, we want to determine a sensible culprit of this.
17063 // Intuitively, watching the chain of member expressions from right to
17064 // left, we start with the required alignment (as required by the field
17065 // type) but some packed attribute in that chain has reduced the alignment.
17066 // It may happen that another packed structure increases it again. But if
17067 // we are here such increase has not been enough. So pointing the first
17068 // FieldDecl that either is packed or else its RecordDecl is,
17069 // seems reasonable.
17070 FieldDecl *FD = nullptr;
17071 CharUnits Alignment;
17072 for (FieldDecl *FDI : ReverseMemberChain) {
17073 if (FDI->hasAttr<PackedAttr>() ||
17074 FDI->getParent()->hasAttr<PackedAttr>()) {
17075 FD = FDI;
17076 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
17077 Context.getTypeAlignInChars(
17078 Context.getCanonicalTagType(FD->getParent())));
17079 break;
17080 }
17081 }
17082 assert(FD && "We did not find a packed FieldDecl!");
17083 Action(E, FD->getParent(), FD, Alignment);
17084 }
17085}
17086
17087void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17088 using namespace std::placeholders;
17089
17091 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17092 _2, _3, _4));
17093}
17094
17096 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17097 if (checkArgCount(TheCall, 1))
17098 return true;
17099
17100 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
17101 if (A.isInvalid())
17102 return true;
17103
17104 TheCall->setArg(0, A.get());
17105 QualType TyA = A.get()->getType();
17106
17107 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
17108 ArgTyRestr, 1))
17109 return true;
17110
17111 TheCall->setType(TyA);
17112 return false;
17113}
17114
17115bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17116 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17117 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17118 TheCall->setType(*Res);
17119 return false;
17120 }
17121 return true;
17122}
17123
17125 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17126 if (!Res)
17127 return true;
17128
17129 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17130 TheCall->setType(VecTy0->getElementType());
17131 else
17132 TheCall->setType(*Res);
17133
17134 return false;
17135}
17136
17138 SourceLocation Loc) {
17140 R = RHS->getEnumCoercedType(S.Context);
17141 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17143 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17144 << LHS->getSourceRange() << RHS->getSourceRange()
17145 << /*Arithmetic Between*/ 0 << L << R;
17146 }
17147 return false;
17148}
17149
17150/// Check if all arguments have the same type. If the types don't match, emit an
17151/// error message and return true. Otherwise return false.
17152///
17153/// For scalars we directly compare their unqualified types. But even if we
17154/// compare unqualified vector types, a difference in qualifiers in the element
17155/// types can make the vector types be considered not equal. For example,
17156/// vector of 4 'const float' values vs vector of 4 'float' values.
17157/// So we compare unqualified types of their elements and number of elements.
17159 ArrayRef<Expr *> Args) {
17160 assert(!Args.empty() && "Should have at least one argument.");
17161
17162 Expr *Arg0 = Args.front();
17163 QualType Ty0 = Arg0->getType();
17164
17165 auto EmitError = [&](Expr *ArgI) {
17166 SemaRef.Diag(Arg0->getBeginLoc(),
17167 diag::err_typecheck_call_different_arg_types)
17168 << Arg0->getType() << ArgI->getType();
17169 };
17170
17171 // Compare scalar types.
17172 if (!Ty0->isVectorType()) {
17173 for (Expr *ArgI : Args.drop_front())
17174 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17175 EmitError(ArgI);
17176 return true;
17177 }
17178
17179 return false;
17180 }
17181
17182 // Compare vector types.
17183 const auto *Vec0 = Ty0->castAs<VectorType>();
17184 for (Expr *ArgI : Args.drop_front()) {
17185 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17186 if (!VecI ||
17187 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17188 VecI->getElementType()) ||
17189 Vec0->getNumElements() != VecI->getNumElements()) {
17190 EmitError(ArgI);
17191 return true;
17192 }
17193 }
17194
17195 return false;
17196}
17197
17198std::optional<QualType>
17200 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17201 if (checkArgCount(TheCall, 2))
17202 return std::nullopt;
17203
17205 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17206 return std::nullopt;
17207
17208 Expr *Args[2];
17209 for (int I = 0; I < 2; ++I) {
17210 ExprResult Converted =
17211 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17212 if (Converted.isInvalid())
17213 return std::nullopt;
17214 Args[I] = Converted.get();
17215 }
17216
17217 SourceLocation LocA = Args[0]->getBeginLoc();
17218 QualType TyA = Args[0]->getType();
17219
17220 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17221 return std::nullopt;
17222
17223 if (checkBuiltinVectorMathArgTypes(*this, Args))
17224 return std::nullopt;
17225
17226 TheCall->setArg(0, Args[0]);
17227 TheCall->setArg(1, Args[1]);
17228 return TyA;
17229}
17230
17232 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17233 if (checkArgCount(TheCall, 3))
17234 return true;
17235
17236 SourceLocation Loc = TheCall->getExprLoc();
17237 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17238 TheCall->getArg(1), Loc) ||
17239 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17240 TheCall->getArg(2), Loc))
17241 return true;
17242
17243 Expr *Args[3];
17244 for (int I = 0; I < 3; ++I) {
17245 ExprResult Converted =
17246 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17247 if (Converted.isInvalid())
17248 return true;
17249 Args[I] = Converted.get();
17250 }
17251
17252 int ArgOrdinal = 1;
17253 for (Expr *Arg : Args) {
17254 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17255 ArgTyRestr, ArgOrdinal++))
17256 return true;
17257 }
17258
17259 if (checkBuiltinVectorMathArgTypes(*this, Args))
17260 return true;
17261
17262 for (int I = 0; I < 3; ++I)
17263 TheCall->setArg(I, Args[I]);
17264
17265 TheCall->setType(Args[0]->getType());
17266 return false;
17267}
17268
17269bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17270 if (checkArgCount(TheCall, 1))
17271 return true;
17272
17273 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17274 if (A.isInvalid())
17275 return true;
17276
17277 TheCall->setArg(0, A.get());
17278 return false;
17279}
17280
17281bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17282 if (checkArgCount(TheCall, 1))
17283 return true;
17284
17285 ExprResult Arg = TheCall->getArg(0);
17286 QualType TyArg = Arg.get()->getType();
17287
17288 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17289 return Diag(TheCall->getArg(0)->getBeginLoc(),
17290 diag::err_builtin_invalid_arg_type)
17291 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17292
17293 TheCall->setType(TyArg);
17294 return false;
17295}
17296
17297ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17298 ExprResult CallResult) {
17299 if (checkArgCount(TheCall, 1))
17300 return ExprError();
17301
17302 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17303 if (MatrixArg.isInvalid())
17304 return MatrixArg;
17305 Expr *Matrix = MatrixArg.get();
17306
17307 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17308 if (!MType) {
17309 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17310 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17311 << Matrix->getType();
17312 return ExprError();
17313 }
17314
17315 // Create returned matrix type by swapping rows and columns of the argument
17316 // matrix type.
17317 QualType ResultType = Context.getConstantMatrixType(
17318 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17319
17320 // Change the return type to the type of the returned matrix.
17321 TheCall->setType(ResultType);
17322
17323 // Update call argument to use the possibly converted matrix argument.
17324 TheCall->setArg(0, Matrix);
17325 return CallResult;
17326}
17327
17328// Get and verify the matrix dimensions.
17329static std::optional<unsigned>
17331 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17332 if (!Value) {
17333 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17334 << Name;
17335 return {};
17336 }
17337 uint64_t Dim = Value->getZExtValue();
17338 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17339 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17340 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17341 return {};
17342 }
17343 return Dim;
17344}
17345
17346ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17347 ExprResult CallResult) {
17348 if (!getLangOpts().MatrixTypes) {
17349 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17350 return ExprError();
17351 }
17352
17353 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17355 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17356 << /*column*/ 1 << /*load*/ 0;
17357 return ExprError();
17358 }
17359
17360 if (checkArgCount(TheCall, 4))
17361 return ExprError();
17362
17363 unsigned PtrArgIdx = 0;
17364 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17365 Expr *RowsExpr = TheCall->getArg(1);
17366 Expr *ColumnsExpr = TheCall->getArg(2);
17367 Expr *StrideExpr = TheCall->getArg(3);
17368
17369 bool ArgError = false;
17370
17371 // Check pointer argument.
17372 {
17374 if (PtrConv.isInvalid())
17375 return PtrConv;
17376 PtrExpr = PtrConv.get();
17377 TheCall->setArg(0, PtrExpr);
17378 if (PtrExpr->isTypeDependent()) {
17379 TheCall->setType(Context.DependentTy);
17380 return TheCall;
17381 }
17382 }
17383
17384 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17385 QualType ElementTy;
17386 if (!PtrTy) {
17387 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17388 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17389 << PtrExpr->getType();
17390 ArgError = true;
17391 } else {
17392 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17393
17395 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17396 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17397 << /* no fp */ 0 << PtrExpr->getType();
17398 ArgError = true;
17399 }
17400 }
17401
17402 // Apply default Lvalue conversions and convert the expression to size_t.
17403 auto ApplyArgumentConversions = [this](Expr *E) {
17405 if (Conv.isInvalid())
17406 return Conv;
17407
17408 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17409 };
17410
17411 // Apply conversion to row and column expressions.
17412 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17413 if (!RowsConv.isInvalid()) {
17414 RowsExpr = RowsConv.get();
17415 TheCall->setArg(1, RowsExpr);
17416 } else
17417 RowsExpr = nullptr;
17418
17419 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17420 if (!ColumnsConv.isInvalid()) {
17421 ColumnsExpr = ColumnsConv.get();
17422 TheCall->setArg(2, ColumnsExpr);
17423 } else
17424 ColumnsExpr = nullptr;
17425
17426 // If any part of the result matrix type is still pending, just use
17427 // Context.DependentTy, until all parts are resolved.
17428 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17429 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17430 TheCall->setType(Context.DependentTy);
17431 return CallResult;
17432 }
17433
17434 // Check row and column dimensions.
17435 std::optional<unsigned> MaybeRows;
17436 if (RowsExpr)
17437 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17438
17439 std::optional<unsigned> MaybeColumns;
17440 if (ColumnsExpr)
17441 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17442
17443 // Check stride argument.
17444 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17445 if (StrideConv.isInvalid())
17446 return ExprError();
17447 StrideExpr = StrideConv.get();
17448 TheCall->setArg(3, StrideExpr);
17449
17450 if (MaybeRows) {
17451 if (std::optional<llvm::APSInt> Value =
17452 StrideExpr->getIntegerConstantExpr(Context)) {
17453 uint64_t Stride = Value->getZExtValue();
17454 if (Stride < *MaybeRows) {
17455 Diag(StrideExpr->getBeginLoc(),
17456 diag::err_builtin_matrix_stride_too_small);
17457 ArgError = true;
17458 }
17459 }
17460 }
17461
17462 if (ArgError || !MaybeRows || !MaybeColumns)
17463 return ExprError();
17464
17465 TheCall->setType(
17466 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17467 return CallResult;
17468}
17469
17470ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17471 ExprResult CallResult) {
17472 if (!getLangOpts().MatrixTypes) {
17473 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17474 return ExprError();
17475 }
17476
17477 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17479 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17480 << /*column*/ 1 << /*store*/ 1;
17481 return ExprError();
17482 }
17483
17484 if (checkArgCount(TheCall, 3))
17485 return ExprError();
17486
17487 unsigned PtrArgIdx = 1;
17488 Expr *MatrixExpr = TheCall->getArg(0);
17489 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17490 Expr *StrideExpr = TheCall->getArg(2);
17491
17492 bool ArgError = false;
17493
17494 {
17495 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17496 if (MatrixConv.isInvalid())
17497 return MatrixConv;
17498 MatrixExpr = MatrixConv.get();
17499 TheCall->setArg(0, MatrixExpr);
17500 }
17501 if (MatrixExpr->isTypeDependent()) {
17502 TheCall->setType(Context.DependentTy);
17503 return TheCall;
17504 }
17505
17506 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17507 if (!MatrixTy) {
17508 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17509 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17510 ArgError = true;
17511 }
17512
17513 {
17515 if (PtrConv.isInvalid())
17516 return PtrConv;
17517 PtrExpr = PtrConv.get();
17518 TheCall->setArg(1, PtrExpr);
17519 if (PtrExpr->isTypeDependent()) {
17520 TheCall->setType(Context.DependentTy);
17521 return TheCall;
17522 }
17523 }
17524
17525 // Check pointer argument.
17526 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17527 if (!PtrTy) {
17528 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17529 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17530 << PtrExpr->getType();
17531 ArgError = true;
17532 } else {
17533 QualType ElementTy = PtrTy->getPointeeType();
17534 if (ElementTy.isConstQualified()) {
17535 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17536 ArgError = true;
17537 }
17538 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17539 if (MatrixTy &&
17540 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17541 Diag(PtrExpr->getBeginLoc(),
17542 diag::err_builtin_matrix_pointer_arg_mismatch)
17543 << ElementTy << MatrixTy->getElementType();
17544 ArgError = true;
17545 }
17546 }
17547
17548 // Apply default Lvalue conversions and convert the stride expression to
17549 // size_t.
17550 {
17551 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17552 if (StrideConv.isInvalid())
17553 return StrideConv;
17554
17555 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17556 if (StrideConv.isInvalid())
17557 return StrideConv;
17558 StrideExpr = StrideConv.get();
17559 TheCall->setArg(2, StrideExpr);
17560 }
17561
17562 // Check stride argument.
17563 if (MatrixTy) {
17564 if (std::optional<llvm::APSInt> Value =
17565 StrideExpr->getIntegerConstantExpr(Context)) {
17566 uint64_t Stride = Value->getZExtValue();
17567 if (Stride < MatrixTy->getNumRows()) {
17568 Diag(StrideExpr->getBeginLoc(),
17569 diag::err_builtin_matrix_stride_too_small);
17570 ArgError = true;
17571 }
17572 }
17573 }
17574
17575 if (ArgError)
17576 return ExprError();
17577
17578 return CallResult;
17579}
17580
17582 const NamedDecl *Callee) {
17583 // This warning does not make sense in code that has no runtime behavior.
17585 return;
17586
17587 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17588
17589 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17590 return;
17591
17592 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17593 // all TCBs the callee is a part of.
17594 llvm::StringSet<> CalleeTCBs;
17595 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17596 CalleeTCBs.insert(A->getTCBName());
17597 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17598 CalleeTCBs.insert(A->getTCBName());
17599
17600 // Go through the TCBs the caller is a part of and emit warnings if Caller
17601 // is in a TCB that the Callee is not.
17602 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17603 StringRef CallerTCB = A->getTCBName();
17604 if (CalleeTCBs.count(CallerTCB) == 0) {
17605 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17606 << Callee << CallerTCB;
17607 }
17608 }
17609}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
Defines enumerations for traits support.
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.
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.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
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
llvm::MachO::Record Record
Definition MachO.h:31
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)
llvm::json::Object Object
llvm::json::Array Array
static std::string getFunctionName(const CallEvent &Call)
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 void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
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)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
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 QualType getVectorElementType(ASTContext &Context, QualType VecTy)
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 bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
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 ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call)
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 ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
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 for SYCL 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.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
@ 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 * getStart() const
StringRef toString() 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
APSInt & getInt()
Definition APValue.h:511
bool isVector() const
Definition APValue.h:494
APSInt & getComplexIntImag()
Definition APValue.h:549
bool isComplexInt() const
Definition APValue.h:491
bool isFloat() const
Definition APValue.h:489
bool isComplexFloat() const
Definition APValue.h:492
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
bool isInt() const
Definition APValue.h:488
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:609
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
bool isMatrix() const
Definition APValue.h:495
unsigned getMatrixNumElements() const
Definition APValue.h:606
bool isAddrLabelDiff() const
Definition APValue.h:500
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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:823
Builtin::Context & BuiltinInfo
Definition ASTContext.h:825
const LangOptions & getLangOpts() const
Definition ASTContext.h:980
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:876
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:942
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:4364
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4542
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4548
SourceLocation getQuestionLoc() const
Definition Expr.h:4391
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4554
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:7314
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7318
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2732
SourceLocation getRBracketLoc() const
Definition Expr.h:2780
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2761
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3850
QualType getElementType() const
Definition TypeBase.h:3848
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6945
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7094
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7076
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:4049
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4182
Expr * getLHS() const
Definition Expr.h:4099
SourceLocation getOperatorLoc() const
Definition Expr.h:4091
SourceLocation getExprLoc() const
Definition Expr.h:4090
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2142
Expr * getRHS() const
Definition Expr.h:4101
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4135
Opcode getOpcode() const
Definition Expr.h:4094
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4146
BinaryOperatorKind Opcode
Definition Expr.h:4054
Pointer to a block type.
Definition TypeBase.h:3656
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
bool isInteger() const
Definition TypeBase.h:3305
bool isFloatingPoint() const
Definition TypeBase.h:3317
bool isSignedInteger() const
Definition TypeBase.h:3309
bool isUnsignedInteger() const
Definition TypeBase.h:3313
Kind getKind() const
Definition TypeBase.h:3292
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:99
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:383
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:3980
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1633
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1691
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2972
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:157
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:5140
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5180
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1230
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1219
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2954
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3158
SourceLocation getBeginLoc() const
Definition Expr.h:3288
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3171
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1598
arg_iterator arg_begin()
Definition Expr.h:3211
arg_iterator arg_end()
Definition Expr.h:3214
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3137
bool isCallToStdMove() const
Definition Expr.cpp:3654
Expr * getCallee()
Definition Expr.h:3101
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3145
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3247
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3148
arg_range arguments()
Definition Expr.h:3206
SourceLocation getEndLoc() const
Definition Expr.h:3307
SourceLocation getRParenLoc() const
Definition Expr.h:3285
Decl * getCalleeDecl()
Definition Expr.h:3131
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:1603
void setCallee(Expr *F)
Definition Expr.h:3103
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3190
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:3687
path_iterator path_begin()
Definition Expr.h:3757
CastKind getCastKind() const
Definition Expr.h:3731
path_iterator path_end()
Definition Expr.h:3758
Expr * getSubExpr()
Definition Expr.h:3737
Represents a byte-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:4402
Expr * getLHS() const
Definition Expr.h:4436
Expr * getRHS() const
Definition Expr.h:4437
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
QualType desugar() const
Definition TypeBase.h:3975
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3930
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4523
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:5695
Expr * getOperand() const
Definition ExprCXX.h:5323
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1281
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:494
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1374
ValueDecl * getDecl()
Definition Expr.h:1349
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1479
SourceLocation getBeginLoc() const
Definition Expr.h:1360
SourceLocation getLocation() const
Definition Expr.h:1357
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:564
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:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2005
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:972
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3557
Represents an enum.
Definition Decl.h:4145
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4377
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4318
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,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3128
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:686
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:683
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3106
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:447
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.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3089
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:3097
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:212
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4242
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:842
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:846
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
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 * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3093
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
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:3700
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
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:813
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:822
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:825
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:815
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:4081
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
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:232
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:138
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4381
Represents a member of a struct/union/class.
Definition Decl.h:3294
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3397
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4815
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3530
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3410
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
llvm::APFloat getValue() const
Definition Expr.h:1677
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2897
Represents a function declaration or definition.
Definition Decl.h:2058
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4616
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2927
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3805
param_iterator param_end()
Definition Decl.h:2917
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3908
QualType getReturnType() const
Definition Decl.h:2975
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2904
param_iterator param_begin()
Definition Decl.h:2916
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3120
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4372
bool isStatic() const
Definition Decl.h:3059
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4187
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4173
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3869
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
unsigned getNumParams() const
Definition TypeBase.h:5699
QualType getParamType(unsigned i) const
Definition TypeBase.h:5701
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5710
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5820
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5706
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4926
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4957
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:3864
Describes an C or C++ initializer list.
Definition Expr.h:5319
ArrayRef< Expr * > inits() const
Definition Expr.h:5372
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:981
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:1075
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1111
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:509
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1158
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:882
Represents the results of name lookup.
Definition Lookup.h:147
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4451
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4472
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3375
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3458
Expr * getBase() const
Definition Expr.h:3452
bool isArrow() const
Definition Expr.h:3559
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
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:1207
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1712
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1726
SourceLocation getSemiLoc() const
Definition Stmt.h:1723
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
QualType getType() const
Definition DeclObjC.h:810
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:833
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:821
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:650
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:739
bool isImplicitProperty() const
Definition ExprObjC.h:736
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:84
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2193
Represents a parameter to a function.
Definition Decl.h:1819
Pointer-authentication qualifiers.
Definition TypeBase.h:153
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:233
bool isAddressDiscriminated() const
Definition TypeBase.h:266
ARM8_3Key
Hardware pointer-signing keys in ARM8.3.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6821
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5202
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8588
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2996
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8504
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8630
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8544
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8598
void removeLocalVolatile()
Definition TypeBase.h:8620
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
void removeLocalConst()
Definition TypeBase.h:8612
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8577
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8625
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1745
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8550
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasUnaligned() const
Definition TypeBase.h:512
Represents a struct/union/class.
Definition Decl.h:4459
bool hasFlexibleArrayMember() const
Definition Decl.h:4492
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4545
field_range fields() const
Definition Decl.h:4662
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4537
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:602
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
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:1038
@ 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:1121
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:113
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:32
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp:31
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:289
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:534
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10350
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10355
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
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:1447
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:13148
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1138
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:2791
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9359
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9367
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9404
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:6953
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.
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2080
SemaHexagon & Hexagon()
Definition Sema.h:1487
SemaSYCL & SYCL()
Definition Sema.h:1557
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:1758
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:842
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1577
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:1305
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:227
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:933
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:1517
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1372
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:763
ASTContext & getASTContext() const
Definition Sema.h:936
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:777
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2640
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:1209
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:2747
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
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:929
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:1462
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:1477
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:1303
static const uint64_t MaximumAlignment
Definition Sema.h:1232
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:961
SemaHLSL & HLSL()
Definition Sema.h:1482
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1502
SemaRISCV & RISCV()
Definition Sema.h:1547
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:2813
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6989
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1770
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:1340
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:2720
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15519
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:2446
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:647
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:1445
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:1527
FormatArgumentPassingKind
Definition Sema.h:2650
@ FAPK_Elsewhere
Definition Sema.h:2654
@ FAPK_Fixed
Definition Sema.h:2651
@ FAPK_Variadic
Definition Sema.h:2652
@ FAPK_VAList
Definition Sema.h:2653
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:8194
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:14045
SourceManager & getSourceManager() const
Definition Sema.h:934
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:2642
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:1537
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:1264
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:1567
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:1308
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:792
DiagnosticsEngine & Diags
Definition Sema.h:1307
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:1512
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:646
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:6306
SemaSPIRV & SPIRV()
Definition Sema.h:1552
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:1492
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6441
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:1572
SemaARM & ARM()
Definition Sema.h:1452
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:4654
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.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
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:304
StmtClass getStmtClass() const
Definition Stmt.h:1502
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
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:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1810
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1984
bool isUTF8() const
Definition Expr.h:1929
bool isWide() const
Definition Expr.h:1928
bool isPascal() const
Definition Expr.h:1933
unsigned getLength() const
Definition Expr.h:1920
StringLiteralKind getKind() const
Definition Expr.h:1923
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:1332
bool isUTF32() const
Definition Expr.h:1931
unsigned getByteLength() const
Definition Expr.h:1919
StringRef getString() const
Definition Expr.h:1878
bool isUTF16() const
Definition Expr.h:1930
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1985
bool isOrdinary() const
Definition Expr.h:1927
unsigned getCharByteWidth() const
Definition Expr.h:1921
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3972
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3952
bool isUnion() const
Definition Decl.h:4062
Exposes information about the current target.
Definition TargetInfo.h:227
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:395
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:2766
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:6332
A container of type source information.
Definition TypeBase.h:8475
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:8486
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8761
bool isVoidType() const
Definition TypeBase.h:9113
bool isBooleanType() const
Definition TypeBase.h:9250
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2319
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9300
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2385
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
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:9280
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:2149
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2547
bool isArrayType() const
Definition TypeBase.h:8840
bool isCharType() const
Definition Type.cpp:2223
bool isFunctionPointerType() const
Definition TypeBase.h:8808
bool isPointerType() const
Definition TypeBase.h:8741
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9157
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9407
bool isReferenceType() const
Definition TypeBase.h:8765
bool isEnumeralType() const
Definition TypeBase.h:8872
bool isScalarType() const
Definition TypeBase.h:9219
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:1984
bool isVariableArrayType() const
Definition TypeBase.h:8852
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2731
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9235
bool isExtVectorType() const
Definition TypeBase.h:8884
bool isExtVectorBoolType() const
Definition TypeBase.h:8888
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2770
bool isBitIntType() const
Definition TypeBase.h:9016
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9082
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8864
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8876
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2340
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3196
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2681
bool isMemberPointerType() const
Definition TypeBase.h:8822
bool isAtomicType() const
Definition TypeBase.h:8933
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8904
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3231
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:2877
bool isUnscopedEnumerationType() const
Definition Type.cpp:2216
bool isObjCObjectType() const
Definition TypeBase.h:8924
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9393
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9256
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
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:2557
bool isFunctionType() const
Definition TypeBase.h:8737
bool isObjCObjectPointerType() const
Definition TypeBase.h:8920
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2427
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isVectorType() const
Definition TypeBase.h:8880
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2435
bool isFloatingType() const
Definition Type.cpp:2419
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:2362
bool isAnyPointerType() const
Definition TypeBase.h:8749
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9340
bool isNullPtrType() const
Definition TypeBase.h:9150
bool isRecordType() const
Definition TypeBase.h:8868
bool isObjCRetainableType() const
Definition Type.cpp:5467
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2693
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5186
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2758
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3696
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2636
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2255
Expr * getSubExpr() const
Definition Expr.h:2296
Opcode getOpcode() const
Definition Expr.h:2291
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2373
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3424
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:5644
Represents a variable declaration or definition.
Definition Decl.h:932
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2706
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
Represents the length modifier in a format string in scanf/printf.
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.
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:237
@ 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:1545
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1530
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1523
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1537
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2832
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1491
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1552
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:49
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.
Top level wrappers for InstallAPI frontend operations.
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:825
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:508
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:658
@ Comparison
A comparison.
Definition Sema.h:662
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
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:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
PointerAuthDiscArgKind
Definition Sema.h:589
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:125
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:258
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:556
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:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:144
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:559
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:494
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:516
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:158
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
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:65
StringLiteralKind
Definition Expr.h:1774
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_Win64
Definition Specifiers.h:286
@ CC_X86_64SysV
Definition Specifiers.h:287
@ Generic
not a target-specific vector type
Definition TypeBase.h:4250
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6041
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6034
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1774
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:657
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:659
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:641
Extra information about a function prototype.
Definition TypeBase.h:5506
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:13330
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13356
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13346
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13294
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6847
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2662
#define log2(__x)
Definition tgmath.h:970