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 errors, even if we managed to build the
545 // call. We don't want to produce more than one error.
546 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
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>() && !isValidMathElementType(ArgTy)) {
2356 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2357 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2358 << ArgTy;
2359 }
2360 break;
2362 if (!EltTy->isRealFloatingType()) {
2363 // FIXME: make diagnostic's wording correct for matrices
2364 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2365 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2366 << /* floating-point */ 1 << ArgTy;
2367 }
2368 break;
2370 if (!EltTy->isIntegerType()) {
2371 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2372 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2373 << /* no fp */ 0 << ArgTy;
2374 }
2375 break;
2377 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2378 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2379 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2380 << /* or fp */ 1 << ArgTy;
2381 }
2382 break;
2383 }
2384
2385 return false;
2386}
2387
2388/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2389/// This checks that the target supports the builtin and that the string
2390/// argument is constant and valid.
2391static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2392 const TargetInfo *AuxTI, unsigned BuiltinID) {
2393 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2394 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2395 "Expecting __builtin_cpu_...");
2396
2397 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2398 const TargetInfo *TheTI = &TI;
2399 auto SupportsBI = [=](const TargetInfo *TInfo) {
2400 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2401 (!IsCPUSupports && TInfo->supportsCpuIs()));
2402 };
2403 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2404 TheTI = AuxTI;
2405
2406 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2407 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2408 return S.Diag(TheCall->getBeginLoc(),
2409 TI.getTriple().isOSAIX()
2410 ? diag::err_builtin_aix_os_unsupported
2411 : diag::err_builtin_target_unsupported)
2412 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2413
2414 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2415 // Check if the argument is a string literal.
2416 if (!isa<StringLiteral>(Arg))
2417 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2418 << Arg->getSourceRange();
2419
2420 // Check the contents of the string.
2421 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2422 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2423 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2424 << Arg->getSourceRange();
2425 return false;
2426 }
2427 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2428 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2429 << Arg->getSourceRange();
2430 return false;
2431}
2432
2433/// Checks that __builtin_bswapg was called with a single argument, which is an
2434/// unsigned integer, and overrides the return value type to the integer type.
2435static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2436 if (S.checkArgCount(TheCall, 1))
2437 return true;
2438 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2439 if (ArgRes.isInvalid())
2440 return true;
2441
2442 Expr *Arg = ArgRes.get();
2443 TheCall->setArg(0, Arg);
2444 if (Arg->isTypeDependent())
2445 return false;
2446
2447 QualType ArgTy = Arg->getType();
2448
2449 if (!ArgTy->isIntegerType()) {
2450 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2451 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2452 << ArgTy;
2453 return true;
2454 }
2455 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2456 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2457 BT->getNumBits() != 1) {
2458 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2459 << ArgTy << BT->getNumBits();
2460 return true;
2461 }
2462 }
2463 TheCall->setType(ArgTy);
2464 return false;
2465}
2466
2467/// Checks that __builtin_bitreverseg was called with a single argument, which
2468/// is an integer
2469static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2470 if (S.checkArgCount(TheCall, 1))
2471 return true;
2472 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2473 if (ArgRes.isInvalid())
2474 return true;
2475
2476 Expr *Arg = ArgRes.get();
2477 TheCall->setArg(0, Arg);
2478 if (Arg->isTypeDependent())
2479 return false;
2480
2481 QualType ArgTy = Arg->getType();
2482
2483 if (!ArgTy->isIntegerType()) {
2484 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2485 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2486 << ArgTy;
2487 return true;
2488 }
2489 TheCall->setType(ArgTy);
2490 return false;
2491}
2492
2493/// Checks that __builtin_popcountg was called with a single argument, which is
2494/// an unsigned integer.
2495static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2496 if (S.checkArgCount(TheCall, 1))
2497 return true;
2498
2499 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2500 if (ArgRes.isInvalid())
2501 return true;
2502
2503 Expr *Arg = ArgRes.get();
2504 TheCall->setArg(0, Arg);
2505
2506 QualType ArgTy = Arg->getType();
2507
2508 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2509 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2510 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2511 << ArgTy;
2512 return true;
2513 }
2514 return false;
2515}
2516
2517/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2518/// argument and return either int, bool, or the argument type.
2519static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2520 QualType ReturnType) {
2521 if (S.checkArgCount(TheCall, 1))
2522 return true;
2523
2524 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2525 if (ArgRes.isInvalid())
2526 return true;
2527
2528 Expr *Arg = ArgRes.get();
2529 TheCall->setArg(0, Arg);
2530
2531 QualType ArgTy = Arg->getType();
2532 // C23 stdbit.h functions do not permit bool or enumeration types.
2533 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2534 return S.Diag(Arg->getBeginLoc(),
2535 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2536 << 1 /*1st argument*/ << ArgTy;
2537 if (!ArgTy->isUnsignedIntegerType())
2538 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2539 << 1 /*1st argument*/ << ArgTy;
2540
2541 // For builtins returning unsigned int, verify the argument's bit width fits.
2542 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2543 // produce a count that overflows the return type.
2544 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2545 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2546 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2547 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2548 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2549 << ArgTy;
2550 }
2551
2552 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2553 return false;
2554}
2555
2556/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2557/// an unsigned integer, and an optional second argument, which is promoted to
2558/// an 'int'.
2559static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2560 if (S.checkArgCountRange(TheCall, 1, 2))
2561 return true;
2562
2563 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2564 if (Arg0Res.isInvalid())
2565 return true;
2566
2567 Expr *Arg0 = Arg0Res.get();
2568 TheCall->setArg(0, Arg0);
2569
2570 QualType Arg0Ty = Arg0->getType();
2571
2572 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2573 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2574 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2575 << Arg0Ty;
2576 return true;
2577 }
2578
2579 if (TheCall->getNumArgs() > 1) {
2580 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2581 if (Arg1Res.isInvalid())
2582 return true;
2583
2584 Expr *Arg1 = Arg1Res.get();
2585 TheCall->setArg(1, Arg1);
2586
2587 QualType Arg1Ty = Arg1->getType();
2588
2589 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2590 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2591 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2592 return true;
2593 }
2594 }
2595
2596 return false;
2597}
2598
2600 unsigned ArgIndex;
2601 bool OnlyUnsigned;
2602
2604 QualType T) {
2605 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2606 << ArgIndex << /*scalar*/ 1
2607 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2608 << /*no fp*/ 0 << T;
2609 }
2610
2611public:
2612 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2613 : ContextualImplicitConverter(/*Suppress=*/false,
2614 /*SuppressConversion=*/true),
2615 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2616
2617 bool match(QualType T) override {
2618 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2619 }
2620
2622 QualType T) override {
2623 return emitError(S, Loc, T);
2624 }
2625
2627 QualType T) override {
2628 return emitError(S, Loc, T);
2629 }
2630
2632 QualType T,
2633 QualType ConvTy) override {
2634 return emitError(S, Loc, T);
2635 }
2636
2638 QualType ConvTy) override {
2639 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2640 }
2641
2643 QualType T) override {
2644 return emitError(S, Loc, T);
2645 }
2646
2648 QualType ConvTy) override {
2649 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2650 }
2651
2653 QualType T,
2654 QualType ConvTy) override {
2655 llvm_unreachable("conversion functions are permitted");
2656 }
2657};
2658
2659/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2660/// arguments, that the first argument is an unsigned integer type, and that
2661/// the second argument is an integer type.
2662static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2663 if (S.checkArgCount(TheCall, 2))
2664 return true;
2665
2666 // First argument (value to rotate) must be unsigned integer type.
2667 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2669 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2670 if (Arg0Res.isInvalid())
2671 return true;
2672
2673 Expr *Arg0 = Arg0Res.get();
2674 TheCall->setArg(0, Arg0);
2675
2676 QualType Arg0Ty = Arg0->getType();
2677 if (!Arg0Ty->isUnsignedIntegerType())
2678 return true;
2679
2680 // Second argument (rotation count) must be integer type.
2681 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2683 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2684 if (Arg1Res.isInvalid())
2685 return true;
2686
2687 Expr *Arg1 = Arg1Res.get();
2688 TheCall->setArg(1, Arg1);
2689
2690 QualType Arg1Ty = Arg1->getType();
2691 if (!Arg1Ty->isIntegerType())
2692 return true;
2693
2694 TheCall->setType(Arg0Ty);
2695 return false;
2696}
2697
2698static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2699 unsigned Pos, bool AllowConst,
2700 bool AllowAS) {
2701 QualType MaskTy = MaskArg->getType();
2702 if (!MaskTy->isExtVectorBoolType())
2703 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2704 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2705 << MaskTy;
2706
2707 QualType PtrTy = PtrArg->getType();
2708 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2709 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2710 << Pos << "scalar pointer";
2711
2712 QualType PointeeTy = PtrTy->getPointeeType();
2713 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2714 (!AllowConst && PointeeTy.isConstQualified()) ||
2715 (!AllowAS && PointeeTy.hasAddressSpace())) {
2718 return S.Diag(PtrArg->getExprLoc(),
2719 diag::err_typecheck_convert_incompatible)
2720 << PtrTy << Target << /*different qualifiers=*/5
2721 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2722 << PtrTy << Target;
2723 }
2724 return false;
2725}
2726
2727static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2728 bool TypeDependent = false;
2729 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2730 ExprResult Converted =
2732 if (Converted.isInvalid())
2733 return true;
2734 TheCall->setArg(Arg, Converted.get());
2735 TypeDependent |= Converted.get()->isTypeDependent();
2736 }
2737
2738 if (TypeDependent)
2739 TheCall->setType(S.Context.DependentTy);
2740 return false;
2741}
2742
2744 if (S.checkArgCountRange(TheCall, 2, 3))
2745 return ExprError();
2746
2747 if (ConvertMaskedBuiltinArgs(S, TheCall))
2748 return ExprError();
2749
2750 Expr *MaskArg = TheCall->getArg(0);
2751 Expr *PtrArg = TheCall->getArg(1);
2752 if (TheCall->isTypeDependent())
2753 return TheCall;
2754
2755 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2756 TheCall->getBuiltinCallee() ==
2757 Builtin::BI__builtin_masked_load))
2758 return ExprError();
2759
2760 QualType MaskTy = MaskArg->getType();
2761 QualType PtrTy = PtrArg->getType();
2762 QualType PointeeTy = PtrTy->getPointeeType();
2763 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2764
2766 MaskVecTy->getNumElements());
2767 if (TheCall->getNumArgs() == 3) {
2768 Expr *PassThruArg = TheCall->getArg(2);
2769 QualType PassThruTy = PassThruArg->getType();
2770 if (!S.Context.hasSameType(PassThruTy, RetTy))
2771 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2772 << /* third argument */ 3 << RetTy;
2773 }
2774
2775 TheCall->setType(RetTy);
2776 return TheCall;
2777}
2778
2780 if (S.checkArgCount(TheCall, 3))
2781 return ExprError();
2782
2783 if (ConvertMaskedBuiltinArgs(S, TheCall))
2784 return ExprError();
2785
2786 Expr *MaskArg = TheCall->getArg(0);
2787 Expr *ValArg = TheCall->getArg(1);
2788 Expr *PtrArg = TheCall->getArg(2);
2789 if (TheCall->isTypeDependent())
2790 return TheCall;
2791
2792 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2793 TheCall->getBuiltinCallee() ==
2794 Builtin::BI__builtin_masked_store))
2795 return ExprError();
2796
2797 QualType MaskTy = MaskArg->getType();
2798 QualType PtrTy = PtrArg->getType();
2799 QualType ValTy = ValArg->getType();
2800 if (!ValTy->isVectorType())
2801 return ExprError(
2802 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2803 << 2 << "vector");
2804
2805 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2806 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2807
2808 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2809 return ExprError(
2810 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2812 TheCall->getBuiltinCallee())
2813 << MaskTy << ValTy);
2814 }
2815
2816 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2817 PtrTy->getPointeeType().getUnqualifiedType()))
2818 return ExprError(S.Diag(TheCall->getBeginLoc(),
2819 diag::err_vec_builtin_incompatible_vector)
2820 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2821 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2822 TheCall->getArg(1)->getEndLoc()));
2823
2824 TheCall->setType(S.Context.VoidTy);
2825 return TheCall;
2826}
2827
2829 if (S.checkArgCountRange(TheCall, 3, 4))
2830 return ExprError();
2831
2832 if (ConvertMaskedBuiltinArgs(S, TheCall))
2833 return ExprError();
2834
2835 Expr *MaskArg = TheCall->getArg(0);
2836 Expr *IdxArg = TheCall->getArg(1);
2837 Expr *PtrArg = TheCall->getArg(2);
2838 if (TheCall->isTypeDependent())
2839 return TheCall;
2840
2841 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2842 /*AllowAS=*/true))
2843 return ExprError();
2844
2845 QualType IdxTy = IdxArg->getType();
2846 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2847 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2848 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2849 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2850 << IdxTy;
2851
2852 QualType MaskTy = MaskArg->getType();
2853 QualType PtrTy = PtrArg->getType();
2854 QualType PointeeTy = PtrTy->getPointeeType();
2855 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2856 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2857 return ExprError(
2858 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2860 TheCall->getBuiltinCallee())
2861 << MaskTy << IdxTy);
2862
2864 MaskVecTy->getNumElements());
2865 if (TheCall->getNumArgs() == 4) {
2866 Expr *PassThruArg = TheCall->getArg(3);
2867 QualType PassThruTy = PassThruArg->getType();
2868 if (!S.Context.hasSameType(PassThruTy, RetTy))
2869 return S.Diag(PassThruArg->getExprLoc(),
2870 diag::err_vec_masked_load_store_ptr)
2871 << /* fourth argument */ 4 << RetTy;
2872 }
2873
2874 TheCall->setType(RetTy);
2875 return TheCall;
2876}
2877
2879 if (S.checkArgCount(TheCall, 4))
2880 return ExprError();
2881
2882 if (ConvertMaskedBuiltinArgs(S, TheCall))
2883 return ExprError();
2884
2885 Expr *MaskArg = TheCall->getArg(0);
2886 Expr *IdxArg = TheCall->getArg(1);
2887 Expr *ValArg = TheCall->getArg(2);
2888 Expr *PtrArg = TheCall->getArg(3);
2889 if (TheCall->isTypeDependent())
2890 return TheCall;
2891
2892 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2893 /*AllowAS=*/true))
2894 return ExprError();
2895
2896 QualType IdxTy = IdxArg->getType();
2897 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2898 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2899 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2900 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2901 << IdxTy;
2902
2903 QualType ValTy = ValArg->getType();
2904 QualType MaskTy = MaskArg->getType();
2905 QualType PtrTy = PtrArg->getType();
2906
2907 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2908 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2909 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2910 return ExprError(
2911 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2913 TheCall->getBuiltinCallee())
2914 << MaskTy << IdxTy);
2915 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2916 return ExprError(
2917 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2919 TheCall->getBuiltinCallee())
2920 << MaskTy << ValTy);
2921
2922 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2923 PtrTy->getPointeeType().getUnqualifiedType()))
2924 return ExprError(S.Diag(TheCall->getBeginLoc(),
2925 diag::err_vec_builtin_incompatible_vector)
2926 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2927 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2928 TheCall->getArg(1)->getEndLoc()));
2929
2930 TheCall->setType(S.Context.VoidTy);
2931 return TheCall;
2932}
2933
2935 SourceLocation Loc = TheCall->getBeginLoc();
2936 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2937 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2938
2939 if (Args.size() == 0) {
2940 S.Diag(TheCall->getBeginLoc(),
2941 diag::err_typecheck_call_too_few_args_at_least)
2942 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2943 << /*is_non_object=*/0 << TheCall->getSourceRange();
2944 return ExprError();
2945 }
2946
2947 QualType FuncT = Args[0]->getType();
2948
2949 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2950 if (Args.size() < 2) {
2951 S.Diag(TheCall->getBeginLoc(),
2952 diag::err_typecheck_call_too_few_args_at_least)
2953 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2954 << /*is_non_object=*/0 << TheCall->getSourceRange();
2955 return ExprError();
2956 }
2957
2958 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2959 QualType ObjectT = Args[1]->getType();
2960
2961 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2962 return ExprError();
2963
2964 ExprResult ObjectArg = [&]() -> ExprResult {
2965 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2966 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2967 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2968 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2969 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2970 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2971 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2972 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2973 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2974 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2975 return Args[1];
2976 }
2977
2978 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2979 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2980 // reference_wrapper;
2981 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2982 if (RD->isInStdNamespace() &&
2983 RD->getDeclName().getAsString() == "reference_wrapper") {
2984 CXXScopeSpec SS;
2985 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2986 UnqualifiedId GetID;
2987 GetID.setIdentifier(GetName, Loc);
2988
2990 S.getCurScope(), Args[1], Loc, tok::period, SS,
2991 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2992
2993 if (MemExpr.isInvalid())
2994 return ExprError();
2995
2996 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2997 }
2998 }
2999
3000 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3001 // class T and t1 does not satisfy the previous two items;
3002
3003 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
3004 }();
3005
3006 if (ObjectArg.isInvalid())
3007 return ExprError();
3008
3009 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
3010 tok::periodstar, ObjectArg.get(), Args[0]);
3011 if (BinOp.isInvalid())
3012 return ExprError();
3013
3014 if (MPT->isMemberDataPointer())
3015 return BinOp;
3016
3017 auto *MemCall = new (S.Context)
3019
3020 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
3021 Args.drop_front(2), TheCall->getRParenLoc());
3022 }
3023 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
3024 Args.drop_front(), TheCall->getRParenLoc());
3025}
3026
3027// Performs a similar job to Sema::UsualUnaryConversions, but without any
3028// implicit promotion of integral/enumeration types.
3030 // First, convert to an r-value.
3032 if (Res.isInvalid())
3033 return ExprError();
3034
3035 // Promote floating-point types.
3036 return S.UsualUnaryFPConversions(Res.get());
3037}
3038
3040 if (const auto *TyA = VecTy->getAs<VectorType>())
3041 return TyA->getElementType();
3042 if (VecTy->isSizelessVectorType())
3043 return VecTy->getSizelessVectorEltType(Context);
3044 return QualType();
3045}
3046
3048Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3049 CallExpr *TheCall) {
3050 ExprResult TheCallResult(TheCall);
3051
3052 // Find out if any arguments are required to be integer constant expressions.
3053 unsigned ICEArguments = 0;
3055 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
3057 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3058
3059 // If any arguments are required to be ICE's, check and diagnose.
3060 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3061 // Skip arguments not required to be ICE's.
3062 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3063
3064 llvm::APSInt Result;
3065 // If we don't have enough arguments, continue so we can issue better
3066 // diagnostic in checkArgCount(...)
3067 if (ArgNo < TheCall->getNumArgs() &&
3068 BuiltinConstantArg(TheCall, ArgNo, Result))
3069 return true;
3070 ICEArguments &= ~(1 << ArgNo);
3071 }
3072
3073 FPOptions FPO;
3074 switch (BuiltinID) {
3075 case Builtin::BI__builtin___get_unsafe_stack_start:
3076 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3077 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3078 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3079 << "__safestack_get_unsafe_stack_bottom";
3080 break;
3081 case Builtin::BI__builtin___get_unsafe_stack_top:
3082 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3083 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3084 << "__safestack_get_unsafe_stack_top";
3085 break;
3086 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3087 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3088 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3089 << "__safestack_get_unsafe_stack_ptr";
3090 break;
3091 case Builtin::BI__builtin_cpu_supports:
3092 case Builtin::BI__builtin_cpu_is:
3093 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
3094 Context.getAuxTargetInfo(), BuiltinID))
3095 return ExprError();
3096 break;
3097 case Builtin::BI__builtin_cpu_init:
3098 if (!Context.getTargetInfo().supportsCpuInit()) {
3099 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3100 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3101 return ExprError();
3102 }
3103 break;
3104 case Builtin::BI__builtin___CFStringMakeConstantString:
3105 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3106 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3108 *this, BuiltinID, TheCall,
3109 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3110 return ExprError();
3111 assert(TheCall->getNumArgs() == 1 &&
3112 "Wrong # arguments to builtin CFStringMakeConstantString");
3113 if (ObjC().CheckObjCString(TheCall->getArg(0)))
3114 return ExprError();
3115 break;
3116 case Builtin::BI__builtin_ms_va_start:
3117 case Builtin::BI__builtin_zos_va_start:
3118 case Builtin::BI__builtin_stdarg_start:
3119 case Builtin::BI__builtin_va_start:
3120 case Builtin::BI__builtin_c23_va_start:
3121 if (BuiltinVAStart(BuiltinID, TheCall))
3122 return ExprError();
3123 break;
3124 case Builtin::BI__va_start: {
3125 switch (Context.getTargetInfo().getTriple().getArch()) {
3126 case llvm::Triple::aarch64:
3127 case llvm::Triple::arm:
3128 case llvm::Triple::thumb:
3129 if (BuiltinVAStartARMMicrosoft(TheCall))
3130 return ExprError();
3131 break;
3132 default:
3133 if (BuiltinVAStart(BuiltinID, TheCall))
3134 return ExprError();
3135 break;
3136 }
3137 break;
3138 }
3139
3140 // The acquire, release, and no fence variants are ARM and AArch64 only.
3141 case Builtin::BI_interlockedbittestandset_acq:
3142 case Builtin::BI_interlockedbittestandset_rel:
3143 case Builtin::BI_interlockedbittestandset_nf:
3144 case Builtin::BI_interlockedbittestandreset_acq:
3145 case Builtin::BI_interlockedbittestandreset_rel:
3146 case Builtin::BI_interlockedbittestandreset_nf:
3148 *this, TheCall,
3149 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3150 return ExprError();
3151 break;
3152
3153 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3154 case Builtin::BI_bittest64:
3155 case Builtin::BI_bittestandcomplement64:
3156 case Builtin::BI_bittestandreset64:
3157 case Builtin::BI_bittestandset64:
3158 case Builtin::BI_interlockedbittestandreset64:
3159 case Builtin::BI_interlockedbittestandset64:
3161 *this, TheCall,
3162 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3163 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3164 return ExprError();
3165 break;
3166
3167 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3168 case Builtin::BI_interlockedbittestandreset64_acq:
3169 case Builtin::BI_interlockedbittestandreset64_rel:
3170 case Builtin::BI_interlockedbittestandreset64_nf:
3171 case Builtin::BI_interlockedbittestandset64_acq:
3172 case Builtin::BI_interlockedbittestandset64_rel:
3173 case Builtin::BI_interlockedbittestandset64_nf:
3174 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3175 return ExprError();
3176 break;
3177
3178 case Builtin::BI__builtin_set_flt_rounds:
3180 *this, TheCall,
3181 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3182 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3183 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3184 llvm::Triple::ppc64le}))
3185 return ExprError();
3186 break;
3187
3188 case Builtin::BI__builtin_isgreater:
3189 case Builtin::BI__builtin_isgreaterequal:
3190 case Builtin::BI__builtin_isless:
3191 case Builtin::BI__builtin_islessequal:
3192 case Builtin::BI__builtin_islessgreater:
3193 case Builtin::BI__builtin_isunordered:
3194 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3195 return ExprError();
3196 break;
3197 case Builtin::BI__builtin_fpclassify:
3198 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3199 return ExprError();
3200 break;
3201 case Builtin::BI__builtin_isfpclass:
3202 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3203 return ExprError();
3204 break;
3205 case Builtin::BI__builtin_isfinite:
3206 case Builtin::BI__builtin_isinf:
3207 case Builtin::BI__builtin_isinf_sign:
3208 case Builtin::BI__builtin_isnan:
3209 case Builtin::BI__builtin_issignaling:
3210 case Builtin::BI__builtin_isnormal:
3211 case Builtin::BI__builtin_issubnormal:
3212 case Builtin::BI__builtin_iszero:
3213 case Builtin::BI__builtin_signbit:
3214 case Builtin::BI__builtin_signbitf:
3215 case Builtin::BI__builtin_signbitl:
3216 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3217 return ExprError();
3218 break;
3219 case Builtin::BI__builtin_shufflevector:
3220 return BuiltinShuffleVector(TheCall);
3221 // TheCall will be freed by the smart pointer here, but that's fine, since
3222 // BuiltinShuffleVector guts it, but then doesn't release it.
3223 case Builtin::BI__builtin_masked_load:
3224 case Builtin::BI__builtin_masked_expand_load:
3225 return BuiltinMaskedLoad(*this, TheCall);
3226 case Builtin::BI__builtin_masked_store:
3227 case Builtin::BI__builtin_masked_compress_store:
3228 return BuiltinMaskedStore(*this, TheCall);
3229 case Builtin::BI__builtin_masked_gather:
3230 return BuiltinMaskedGather(*this, TheCall);
3231 case Builtin::BI__builtin_masked_scatter:
3232 return BuiltinMaskedScatter(*this, TheCall);
3233 case Builtin::BI__builtin_invoke:
3234 return BuiltinInvoke(*this, TheCall);
3235 case Builtin::BI__builtin_prefetch:
3236 if (BuiltinPrefetch(TheCall))
3237 return ExprError();
3238 break;
3239 case Builtin::BI__builtin_alloca_with_align:
3240 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3241 if (BuiltinAllocaWithAlign(TheCall))
3242 return ExprError();
3243 [[fallthrough]];
3244 case Builtin::BI__builtin_alloca:
3245 case Builtin::BI__builtin_alloca_uninitialized:
3246 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3247 << TheCall->getDirectCallee();
3248 if (getLangOpts().OpenCL) {
3249 builtinAllocaAddrSpace(*this, TheCall);
3250 }
3251 break;
3252 case Builtin::BI__builtin_infer_alloc_token:
3253 if (checkBuiltinInferAllocToken(*this, TheCall))
3254 return ExprError();
3255 break;
3256 case Builtin::BI__arithmetic_fence:
3257 if (BuiltinArithmeticFence(TheCall))
3258 return ExprError();
3259 break;
3260 case Builtin::BI__assume:
3261 case Builtin::BI__builtin_assume:
3262 if (BuiltinAssume(TheCall))
3263 return ExprError();
3264 break;
3265 case Builtin::BI__builtin_assume_aligned:
3266 if (BuiltinAssumeAligned(TheCall))
3267 return ExprError();
3268 break;
3269 case Builtin::BI__builtin_dynamic_object_size:
3270 case Builtin::BI__builtin_object_size:
3271 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3272 return ExprError();
3273 break;
3274 case Builtin::BI__builtin_longjmp:
3275 if (BuiltinLongjmp(TheCall))
3276 return ExprError();
3277 break;
3278 case Builtin::BI__builtin_setjmp:
3279 if (BuiltinSetjmp(TheCall))
3280 return ExprError();
3281 break;
3282 case Builtin::BI__builtin_complex:
3283 if (BuiltinComplex(TheCall))
3284 return ExprError();
3285 break;
3286 case Builtin::BI__builtin_classify_type:
3287 case Builtin::BI__builtin_constant_p: {
3288 if (checkArgCount(TheCall, 1))
3289 return true;
3291 if (Arg.isInvalid()) return true;
3292 TheCall->setArg(0, Arg.get());
3293 TheCall->setType(Context.IntTy);
3294 break;
3295 }
3296 case Builtin::BI__builtin_launder:
3297 return BuiltinLaunder(*this, TheCall);
3298 case Builtin::BI__builtin_is_within_lifetime:
3299 return BuiltinIsWithinLifetime(*this, TheCall);
3300 case Builtin::BI__builtin_trivially_relocate:
3301 return BuiltinTriviallyRelocate(*this, TheCall);
3302 case Builtin::BI__builtin_clear_padding: {
3303 if (checkArgCount(TheCall, 1))
3304 return ExprError();
3305
3306 const Expr *PtrArg = TheCall->getArg(0);
3307 const QualType PtrArgType = PtrArg->getType();
3308 if (!PtrArgType->isPointerType()) {
3309 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3310 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3311 << "pointer";
3312 return ExprError();
3313 }
3314 QualType PointeeType = PtrArgType->getPointeeType();
3315 if (PointeeType.isConstQualified()) {
3316 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3317 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3318 return ExprError();
3319 }
3320 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3321 diag::err_typecheck_decl_incomplete_type))
3322 return ExprError();
3323
3324 // For non trivially copyable types, we try to match gcc's behaviour.
3325 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3326 // object, either a local variable or a function parameter passed by value
3327 auto IsAddrOfDeclExpr = [&]() {
3328 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3329 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3330 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3331 return false;
3332
3333 const Expr *Operand =
3334 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3335 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3336 if (!DeclRef)
3337 return false;
3338
3339 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3340 if (!VarDecl || VarDecl->getType()->isReferenceType())
3341 return false;
3342
3343 // matching GCC behaviour
3344 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3345 QualType VarQType = VarDecl->getType();
3346 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3347 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3348 };
3349
3350 if (!PointeeType.isTriviallyCopyableType(Context) &&
3351 !PointeeType->isAtomicType() // _Atomic is not copyable
3352 && !IsAddrOfDeclExpr()) {
3353 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3354 << PtrArg->getType() << PtrArg->getSourceRange();
3355 return ExprError();
3356 }
3357
3358 if (auto *Record = PointeeType->getAsRecordDecl();
3360 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3361 << PointeeType << PtrArg->getSourceRange();
3362 return ExprError();
3363 }
3364
3365 break;
3366 }
3367 case Builtin::BI__sync_fetch_and_add:
3368 case Builtin::BI__sync_fetch_and_add_1:
3369 case Builtin::BI__sync_fetch_and_add_2:
3370 case Builtin::BI__sync_fetch_and_add_4:
3371 case Builtin::BI__sync_fetch_and_add_8:
3372 case Builtin::BI__sync_fetch_and_add_16:
3373 case Builtin::BI__sync_fetch_and_sub:
3374 case Builtin::BI__sync_fetch_and_sub_1:
3375 case Builtin::BI__sync_fetch_and_sub_2:
3376 case Builtin::BI__sync_fetch_and_sub_4:
3377 case Builtin::BI__sync_fetch_and_sub_8:
3378 case Builtin::BI__sync_fetch_and_sub_16:
3379 case Builtin::BI__sync_fetch_and_or:
3380 case Builtin::BI__sync_fetch_and_or_1:
3381 case Builtin::BI__sync_fetch_and_or_2:
3382 case Builtin::BI__sync_fetch_and_or_4:
3383 case Builtin::BI__sync_fetch_and_or_8:
3384 case Builtin::BI__sync_fetch_and_or_16:
3385 case Builtin::BI__sync_fetch_and_and:
3386 case Builtin::BI__sync_fetch_and_and_1:
3387 case Builtin::BI__sync_fetch_and_and_2:
3388 case Builtin::BI__sync_fetch_and_and_4:
3389 case Builtin::BI__sync_fetch_and_and_8:
3390 case Builtin::BI__sync_fetch_and_and_16:
3391 case Builtin::BI__sync_fetch_and_xor:
3392 case Builtin::BI__sync_fetch_and_xor_1:
3393 case Builtin::BI__sync_fetch_and_xor_2:
3394 case Builtin::BI__sync_fetch_and_xor_4:
3395 case Builtin::BI__sync_fetch_and_xor_8:
3396 case Builtin::BI__sync_fetch_and_xor_16:
3397 case Builtin::BI__sync_fetch_and_nand:
3398 case Builtin::BI__sync_fetch_and_nand_1:
3399 case Builtin::BI__sync_fetch_and_nand_2:
3400 case Builtin::BI__sync_fetch_and_nand_4:
3401 case Builtin::BI__sync_fetch_and_nand_8:
3402 case Builtin::BI__sync_fetch_and_nand_16:
3403 case Builtin::BI__sync_add_and_fetch:
3404 case Builtin::BI__sync_add_and_fetch_1:
3405 case Builtin::BI__sync_add_and_fetch_2:
3406 case Builtin::BI__sync_add_and_fetch_4:
3407 case Builtin::BI__sync_add_and_fetch_8:
3408 case Builtin::BI__sync_add_and_fetch_16:
3409 case Builtin::BI__sync_sub_and_fetch:
3410 case Builtin::BI__sync_sub_and_fetch_1:
3411 case Builtin::BI__sync_sub_and_fetch_2:
3412 case Builtin::BI__sync_sub_and_fetch_4:
3413 case Builtin::BI__sync_sub_and_fetch_8:
3414 case Builtin::BI__sync_sub_and_fetch_16:
3415 case Builtin::BI__sync_and_and_fetch:
3416 case Builtin::BI__sync_and_and_fetch_1:
3417 case Builtin::BI__sync_and_and_fetch_2:
3418 case Builtin::BI__sync_and_and_fetch_4:
3419 case Builtin::BI__sync_and_and_fetch_8:
3420 case Builtin::BI__sync_and_and_fetch_16:
3421 case Builtin::BI__sync_or_and_fetch:
3422 case Builtin::BI__sync_or_and_fetch_1:
3423 case Builtin::BI__sync_or_and_fetch_2:
3424 case Builtin::BI__sync_or_and_fetch_4:
3425 case Builtin::BI__sync_or_and_fetch_8:
3426 case Builtin::BI__sync_or_and_fetch_16:
3427 case Builtin::BI__sync_xor_and_fetch:
3428 case Builtin::BI__sync_xor_and_fetch_1:
3429 case Builtin::BI__sync_xor_and_fetch_2:
3430 case Builtin::BI__sync_xor_and_fetch_4:
3431 case Builtin::BI__sync_xor_and_fetch_8:
3432 case Builtin::BI__sync_xor_and_fetch_16:
3433 case Builtin::BI__sync_nand_and_fetch:
3434 case Builtin::BI__sync_nand_and_fetch_1:
3435 case Builtin::BI__sync_nand_and_fetch_2:
3436 case Builtin::BI__sync_nand_and_fetch_4:
3437 case Builtin::BI__sync_nand_and_fetch_8:
3438 case Builtin::BI__sync_nand_and_fetch_16:
3439 case Builtin::BI__sync_val_compare_and_swap:
3440 case Builtin::BI__sync_val_compare_and_swap_1:
3441 case Builtin::BI__sync_val_compare_and_swap_2:
3442 case Builtin::BI__sync_val_compare_and_swap_4:
3443 case Builtin::BI__sync_val_compare_and_swap_8:
3444 case Builtin::BI__sync_val_compare_and_swap_16:
3445 case Builtin::BI__sync_bool_compare_and_swap:
3446 case Builtin::BI__sync_bool_compare_and_swap_1:
3447 case Builtin::BI__sync_bool_compare_and_swap_2:
3448 case Builtin::BI__sync_bool_compare_and_swap_4:
3449 case Builtin::BI__sync_bool_compare_and_swap_8:
3450 case Builtin::BI__sync_bool_compare_and_swap_16:
3451 case Builtin::BI__sync_lock_test_and_set:
3452 case Builtin::BI__sync_lock_test_and_set_1:
3453 case Builtin::BI__sync_lock_test_and_set_2:
3454 case Builtin::BI__sync_lock_test_and_set_4:
3455 case Builtin::BI__sync_lock_test_and_set_8:
3456 case Builtin::BI__sync_lock_test_and_set_16:
3457 case Builtin::BI__sync_lock_release:
3458 case Builtin::BI__sync_lock_release_1:
3459 case Builtin::BI__sync_lock_release_2:
3460 case Builtin::BI__sync_lock_release_4:
3461 case Builtin::BI__sync_lock_release_8:
3462 case Builtin::BI__sync_lock_release_16:
3463 case Builtin::BI__sync_swap:
3464 case Builtin::BI__sync_swap_1:
3465 case Builtin::BI__sync_swap_2:
3466 case Builtin::BI__sync_swap_4:
3467 case Builtin::BI__sync_swap_8:
3468 case Builtin::BI__sync_swap_16:
3469 return BuiltinAtomicOverloaded(TheCallResult);
3470 case Builtin::BI__sync_synchronize:
3471 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3472 << TheCall->getCallee()->getSourceRange();
3473 break;
3474 case Builtin::BI__builtin_nontemporal_load:
3475 case Builtin::BI__builtin_nontemporal_store:
3476 return BuiltinNontemporalOverloaded(TheCallResult);
3477 case Builtin::BI__builtin_memcpy_inline: {
3478 clang::Expr *SizeOp = TheCall->getArg(2);
3479 // We warn about copying to or from `nullptr` pointers when `size` is
3480 // greater than 0. When `size` is value dependent we cannot evaluate its
3481 // value so we bail out.
3482 if (SizeOp->isValueDependent())
3483 break;
3484 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3485 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3486 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3487 }
3488 break;
3489 }
3490 case Builtin::BI__builtin_memset_inline: {
3491 clang::Expr *SizeOp = TheCall->getArg(2);
3492 // We warn about filling to `nullptr` pointers when `size` is greater than
3493 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3494 // out.
3495 if (SizeOp->isValueDependent())
3496 break;
3497 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3498 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3499 break;
3500 }
3501#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3502 case Builtin::BI##ID: \
3503 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3504#include "clang/Basic/Builtins.inc"
3505 case Builtin::BI__annotation: {
3506 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3507 if (!TT.isOSWindows() && !TT.isUEFI()) {
3508 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3509 << TheCall->getSourceRange();
3510 return ExprError();
3511 }
3512 if (BuiltinMSVCAnnotation(*this, TheCall))
3513 return ExprError();
3514 break;
3515 }
3516 case Builtin::BI__builtin_annotation:
3517 if (BuiltinAnnotation(*this, TheCall))
3518 return ExprError();
3519 break;
3520 case Builtin::BI__builtin_addressof:
3521 if (BuiltinAddressof(*this, TheCall))
3522 return ExprError();
3523 break;
3524 case Builtin::BI__builtin_function_start:
3525 if (BuiltinFunctionStart(*this, TheCall))
3526 return ExprError();
3527 break;
3528 case Builtin::BI__builtin_is_aligned:
3529 case Builtin::BI__builtin_align_up:
3530 case Builtin::BI__builtin_align_down:
3531 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3532 return ExprError();
3533 break;
3534 case Builtin::BI__builtin_add_overflow:
3535 case Builtin::BI__builtin_sub_overflow:
3536 case Builtin::BI__builtin_mul_overflow:
3537 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3538 return ExprError();
3539 break;
3540 case Builtin::BI__builtin_operator_new:
3541 case Builtin::BI__builtin_operator_delete: {
3542 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3543 ExprResult Res =
3544 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3545 return Res;
3546 }
3547 case Builtin::BI__builtin_dump_struct:
3548 return BuiltinDumpStruct(*this, TheCall);
3549 case Builtin::BI__builtin_expect_with_probability: {
3550 // We first want to ensure we are called with 3 arguments
3551 if (checkArgCount(TheCall, 3))
3552 return ExprError();
3553 // then check probability is constant float in range [0.0, 1.0]
3554 const Expr *ProbArg = TheCall->getArg(2);
3555 SmallVector<PartialDiagnosticAt, 8> Notes;
3556 Expr::EvalResult Eval;
3557 Eval.Diag = &Notes;
3558 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3559 !Eval.Val.isFloat()) {
3560 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3561 << ProbArg->getSourceRange();
3562 for (const PartialDiagnosticAt &PDiag : Notes)
3563 Diag(PDiag.first, PDiag.second);
3564 return ExprError();
3565 }
3566 llvm::APFloat Probability = Eval.Val.getFloat();
3567 bool LoseInfo = false;
3568 Probability.convert(llvm::APFloat::IEEEdouble(),
3569 llvm::RoundingMode::Dynamic, &LoseInfo);
3570 if (!(Probability >= llvm::APFloat(0.0) &&
3571 Probability <= llvm::APFloat(1.0))) {
3572 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3573 << ProbArg->getSourceRange();
3574 return ExprError();
3575 }
3576 break;
3577 }
3578 case Builtin::BI__builtin_preserve_access_index:
3579 if (BuiltinPreserveAI(*this, TheCall))
3580 return ExprError();
3581 break;
3582 case Builtin::BI__builtin_call_with_static_chain:
3583 if (BuiltinCallWithStaticChain(*this, TheCall))
3584 return ExprError();
3585 break;
3586 case Builtin::BI__exception_code:
3587 case Builtin::BI_exception_code:
3588 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3589 diag::err_seh___except_block))
3590 return ExprError();
3591 break;
3592 case Builtin::BI__exception_info:
3593 case Builtin::BI_exception_info:
3594 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3595 diag::err_seh___except_filter))
3596 return ExprError();
3597 break;
3598 case Builtin::BI__GetExceptionInfo:
3599 if (checkArgCount(TheCall, 1))
3600 return ExprError();
3601
3603 TheCall->getBeginLoc(),
3604 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3605 TheCall))
3606 return ExprError();
3607
3608 TheCall->setType(Context.VoidPtrTy);
3609 break;
3610 case Builtin::BIaddressof:
3611 case Builtin::BI__addressof:
3612 case Builtin::BIforward:
3613 case Builtin::BIforward_like:
3614 case Builtin::BImove:
3615 case Builtin::BImove_if_noexcept:
3616 case Builtin::BIas_const: {
3617 // These are all expected to be of the form
3618 // T &/&&/* f(U &/&&)
3619 // where T and U only differ in qualification.
3620 if (checkArgCount(TheCall, 1))
3621 return ExprError();
3622 QualType Param = FDecl->getParamDecl(0)->getType();
3623 QualType Result = FDecl->getReturnType();
3624 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3625 BuiltinID == Builtin::BI__addressof;
3626 if (!(Param->isReferenceType() &&
3627 (ReturnsPointer ? Result->isAnyPointerType()
3628 : Result->isReferenceType()) &&
3629 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3630 Result->getPointeeType()))) {
3631 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3632 << FDecl;
3633 return ExprError();
3634 }
3635 break;
3636 }
3637 case Builtin::BI__builtin_ptrauth_strip:
3638 return PointerAuthStrip(*this, TheCall);
3639 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3640 return PointerAuthBlendDiscriminator(*this, TheCall);
3641 case Builtin::BI__builtin_ptrauth_sign_constant:
3642 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3643 /*RequireConstant=*/true);
3644 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3645 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3646 /*RequireConstant=*/false);
3647 case Builtin::BI__builtin_ptrauth_auth:
3648 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3649 /*RequireConstant=*/false);
3650 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3651 return PointerAuthSignGenericData(*this, TheCall);
3652 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3653 return PointerAuthAuthAndResign(*this, TheCall);
3654 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3655 return PointerAuthAuthWithPCAndResign(*this, TheCall);
3656 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3657 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3658 case Builtin::BI__builtin_ptrauth_string_discriminator:
3659 return PointerAuthStringDiscriminator(*this, TheCall);
3660
3661 case Builtin::BI__builtin_get_vtable_pointer:
3662 return GetVTablePointer(*this, TheCall);
3663
3664 // OpenCL v2.0, s6.13.16 - Pipe functions
3665 case Builtin::BIread_pipe:
3666 case Builtin::BIwrite_pipe:
3667 // Since those two functions are declared with var args, we need a semantic
3668 // check for the argument.
3669 if (OpenCL().checkBuiltinRWPipe(TheCall))
3670 return ExprError();
3671 break;
3672 case Builtin::BIreserve_read_pipe:
3673 case Builtin::BIreserve_write_pipe:
3674 case Builtin::BIwork_group_reserve_read_pipe:
3675 case Builtin::BIwork_group_reserve_write_pipe:
3676 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3677 return ExprError();
3678 break;
3679 case Builtin::BIsub_group_reserve_read_pipe:
3680 case Builtin::BIsub_group_reserve_write_pipe:
3681 if (OpenCL().checkSubgroupExt(TheCall) ||
3682 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3683 return ExprError();
3684 break;
3685 case Builtin::BIcommit_read_pipe:
3686 case Builtin::BIcommit_write_pipe:
3687 case Builtin::BIwork_group_commit_read_pipe:
3688 case Builtin::BIwork_group_commit_write_pipe:
3689 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3690 return ExprError();
3691 break;
3692 case Builtin::BIsub_group_commit_read_pipe:
3693 case Builtin::BIsub_group_commit_write_pipe:
3694 if (OpenCL().checkSubgroupExt(TheCall) ||
3695 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3696 return ExprError();
3697 break;
3698 case Builtin::BIget_pipe_num_packets:
3699 case Builtin::BIget_pipe_max_packets:
3700 if (OpenCL().checkBuiltinPipePackets(TheCall))
3701 return ExprError();
3702 break;
3703 case Builtin::BIto_global:
3704 case Builtin::BIto_local:
3705 case Builtin::BIto_private:
3706 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3707 return ExprError();
3708 break;
3709 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3710 case Builtin::BIenqueue_kernel:
3711 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3712 return ExprError();
3713 break;
3714 case Builtin::BIget_kernel_work_group_size:
3715 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3716 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3717 return ExprError();
3718 break;
3719 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3720 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3721 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3722 return ExprError();
3723 break;
3724 case Builtin::BI__builtin_os_log_format:
3725 Cleanup.setExprNeedsCleanups(true);
3726 [[fallthrough]];
3727 case Builtin::BI__builtin_os_log_format_buffer_size:
3728 if (BuiltinOSLogFormat(TheCall))
3729 return ExprError();
3730 break;
3731 case Builtin::BI__builtin_frame_address:
3732 case Builtin::BI__builtin_return_address: {
3733 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3734 return ExprError();
3735
3736 // -Wframe-address warning if non-zero passed to builtin
3737 // return/frame address.
3738 Expr::EvalResult Result;
3739 if (!TheCall->getArg(0)->isValueDependent() &&
3740 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3741 Result.Val.getInt() != 0)
3742 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3743 << ((BuiltinID == Builtin::BI__builtin_return_address)
3744 ? "__builtin_return_address"
3745 : "__builtin_frame_address")
3746 << TheCall->getSourceRange();
3747 break;
3748 }
3749
3750 case Builtin::BI__builtin_nondeterministic_value: {
3751 if (BuiltinNonDeterministicValue(TheCall))
3752 return ExprError();
3753 break;
3754 }
3755
3756 // __builtin_elementwise_abs restricts the element type to signed integers or
3757 // floating point types only.
3758 case Builtin::BI__builtin_elementwise_abs:
3761 return ExprError();
3762 break;
3763
3764 // These builtins restrict the element type to floating point
3765 // types only.
3766 case Builtin::BI__builtin_elementwise_acos:
3767 case Builtin::BI__builtin_elementwise_asin:
3768 case Builtin::BI__builtin_elementwise_atan:
3769 case Builtin::BI__builtin_elementwise_ceil:
3770 case Builtin::BI__builtin_elementwise_cos:
3771 case Builtin::BI__builtin_elementwise_cosh:
3772 case Builtin::BI__builtin_elementwise_exp:
3773 case Builtin::BI__builtin_elementwise_exp2:
3774 case Builtin::BI__builtin_elementwise_exp10:
3775 case Builtin::BI__builtin_elementwise_floor:
3776 case Builtin::BI__builtin_elementwise_log:
3777 case Builtin::BI__builtin_elementwise_log2:
3778 case Builtin::BI__builtin_elementwise_log10:
3779 case Builtin::BI__builtin_elementwise_roundeven:
3780 case Builtin::BI__builtin_elementwise_round:
3781 case Builtin::BI__builtin_elementwise_rint:
3782 case Builtin::BI__builtin_elementwise_nearbyint:
3783 case Builtin::BI__builtin_elementwise_sin:
3784 case Builtin::BI__builtin_elementwise_sinh:
3785 case Builtin::BI__builtin_elementwise_sqrt:
3786 case Builtin::BI__builtin_elementwise_tan:
3787 case Builtin::BI__builtin_elementwise_tanh:
3788 case Builtin::BI__builtin_elementwise_trunc:
3789 case Builtin::BI__builtin_elementwise_canonicalize:
3792 return ExprError();
3793 break;
3794 case Builtin::BI__builtin_elementwise_fma:
3795 if (BuiltinElementwiseTernaryMath(TheCall))
3796 return ExprError();
3797 break;
3798
3799 case Builtin::BI__builtin_elementwise_ldexp: {
3800 if (checkArgCount(TheCall, 2))
3801 return ExprError();
3802
3803 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3804 if (A.isInvalid())
3805 return ExprError();
3806 QualType TyA = A.get()->getType();
3807 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3809 return ExprError();
3810
3811 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3812 if (Exp.isInvalid())
3813 return ExprError();
3814 QualType TyExp = Exp.get()->getType();
3815 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3817 2))
3818 return ExprError();
3819
3820 // Check the two arguments are either scalars or vectors of equal length.
3821 const auto *Vec0 = TyA->getAs<VectorType>();
3822 const auto *Vec1 = TyExp->getAs<VectorType>();
3823 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3824 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3825 if (Arg0Length != Arg1Length) {
3826 Diag(Exp.get()->getBeginLoc(),
3827 diag::err_typecheck_vector_lengths_not_equal)
3828 << TyA << TyExp << A.get()->getSourceRange()
3829 << Exp.get()->getSourceRange();
3830 return ExprError();
3831 }
3832
3833 TheCall->setArg(0, A.get());
3834 TheCall->setArg(1, Exp.get());
3835 TheCall->setType(TyA);
3836 break;
3837 }
3838
3839 // These builtins restrict the element type to floating point
3840 // types only, and take in two arguments.
3841 case Builtin::BI__builtin_elementwise_minnum:
3842 case Builtin::BI__builtin_elementwise_maxnum:
3843 case Builtin::BI__builtin_elementwise_minimum:
3844 case Builtin::BI__builtin_elementwise_maximum:
3845 case Builtin::BI__builtin_elementwise_minimumnum:
3846 case Builtin::BI__builtin_elementwise_maximumnum:
3847 case Builtin::BI__builtin_elementwise_atan2:
3848 case Builtin::BI__builtin_elementwise_fmod:
3849 case Builtin::BI__builtin_elementwise_pow:
3850 if (BuiltinElementwiseMath(TheCall,
3852 return ExprError();
3853 break;
3854 // These builtins restrict the element type to integer
3855 // types only.
3856 case Builtin::BI__builtin_elementwise_add_sat:
3857 case Builtin::BI__builtin_elementwise_sub_sat:
3858 case Builtin::BI__builtin_elementwise_clmul:
3859 case Builtin::BI__builtin_elementwise_pext:
3860 case Builtin::BI__builtin_elementwise_pdep:
3861 if (BuiltinElementwiseMath(TheCall,
3863 return ExprError();
3864 break;
3865 case Builtin::BI__builtin_elementwise_fshl:
3866 case Builtin::BI__builtin_elementwise_fshr:
3869 return ExprError();
3870 break;
3871 case Builtin::BI__builtin_elementwise_min:
3872 case Builtin::BI__builtin_elementwise_max: {
3873 if (BuiltinElementwiseMath(TheCall))
3874 return ExprError();
3875 Expr *Arg0 = TheCall->getArg(0);
3876 Expr *Arg1 = TheCall->getArg(1);
3877 QualType Ty0 = Arg0->getType();
3878 QualType Ty1 = Arg1->getType();
3879 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3880 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3881 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3882 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3883 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3884 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3885 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3886 break;
3887 }
3888 case Builtin::BI__builtin_elementwise_popcount:
3889 case Builtin::BI__builtin_elementwise_bitreverse:
3892 return ExprError();
3893 break;
3894 case Builtin::BI__builtin_elementwise_copysign: {
3895 if (checkArgCount(TheCall, 2))
3896 return ExprError();
3897
3898 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3899 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3900 if (Magnitude.isInvalid() || Sign.isInvalid())
3901 return ExprError();
3902
3903 QualType MagnitudeTy = Magnitude.get()->getType();
3904 QualType SignTy = Sign.get()->getType();
3906 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3909 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3911 return ExprError();
3912 }
3913
3914 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3915 return Diag(Sign.get()->getBeginLoc(),
3916 diag::err_typecheck_call_different_arg_types)
3917 << MagnitudeTy << SignTy;
3918 }
3919
3920 TheCall->setArg(0, Magnitude.get());
3921 TheCall->setArg(1, Sign.get());
3922 TheCall->setType(Magnitude.get()->getType());
3923 break;
3924 }
3925 case Builtin::BI__builtin_elementwise_clzg:
3926 case Builtin::BI__builtin_elementwise_ctzg:
3927 // These builtins can be unary or binary. Note for empty calls we call the
3928 // unary checker in order to not emit an error that says the function
3929 // expects 2 arguments, which would be misleading.
3930 if (TheCall->getNumArgs() <= 1) {
3933 return ExprError();
3934 } else if (BuiltinElementwiseMath(
3936 return ExprError();
3937 break;
3938 case Builtin::BI__builtin_reduce_max:
3939 case Builtin::BI__builtin_reduce_min: {
3940 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3941 return ExprError();
3942
3943 const Expr *Arg = TheCall->getArg(0);
3944 const auto *TyA = Arg->getType()->getAs<VectorType>();
3945
3946 QualType ElTy;
3947 if (TyA)
3948 ElTy = TyA->getElementType();
3949 else if (Arg->getType()->isSizelessVectorType())
3951
3952 if (ElTy.isNull()) {
3953 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3954 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3955 << Arg->getType();
3956 return ExprError();
3957 }
3958
3959 TheCall->setType(ElTy);
3960 break;
3961 }
3962 case Builtin::BI__builtin_reduce_maximum:
3963 case Builtin::BI__builtin_reduce_minimum: {
3964 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3965 return ExprError();
3966
3967 const Expr *Arg = TheCall->getArg(0);
3968 const auto *TyA = Arg->getType()->getAs<VectorType>();
3969
3970 QualType ElTy;
3971 if (TyA)
3972 ElTy = TyA->getElementType();
3973 else if (Arg->getType()->isSizelessVectorType())
3975
3976 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3977 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3978 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3979 << Arg->getType();
3980 return ExprError();
3981 }
3982
3983 TheCall->setType(ElTy);
3984 break;
3985 }
3986
3987 // These builtins support vectors of integers only.
3988 // TODO: ADD/MUL should support floating-point types.
3989 case Builtin::BI__builtin_reduce_add:
3990 case Builtin::BI__builtin_reduce_mul:
3991 case Builtin::BI__builtin_reduce_xor:
3992 case Builtin::BI__builtin_reduce_or:
3993 case Builtin::BI__builtin_reduce_and: {
3994 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3995 return ExprError();
3996
3997 const Expr *Arg = TheCall->getArg(0);
3998
3999 QualType ElTy = getVectorElementType(Context, Arg->getType());
4000 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4001 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4002 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4003 << Arg->getType();
4004 return ExprError();
4005 }
4006
4007 TheCall->setType(ElTy);
4008 break;
4009 }
4010
4011 case Builtin::BI__builtin_reduce_assoc_fadd:
4012 case Builtin::BI__builtin_reduce_in_order_fadd: {
4013 // For in-order reductions require the user to specify the start value.
4014 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4015 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
4016 return ExprError();
4017
4018 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
4019 if (Vec.isInvalid())
4020 return ExprError();
4021
4022 TheCall->setArg(0, Vec.get());
4023
4024 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
4025 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4026 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4027 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4028 << Vec.get()->getType();
4029 return ExprError();
4030 }
4031
4032 if (TheCall->getNumArgs() == 2) {
4033 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
4034 if (StartValue.isInvalid())
4035 return ExprError();
4036
4037 if (!StartValue.get()->getType()->isRealFloatingType()) {
4038 Diag(StartValue.get()->getBeginLoc(),
4039 diag::err_builtin_invalid_arg_type)
4040 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4041 << StartValue.get()->getType();
4042 return ExprError();
4043 }
4044 TheCall->setArg(1, StartValue.get());
4045 }
4046
4047 TheCall->setType(ElTy);
4048 break;
4049 }
4050
4051 case Builtin::BI__builtin_matrix_transpose:
4052 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4053
4054 case Builtin::BI__builtin_matrix_column_major_load:
4055 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4056
4057 case Builtin::BI__builtin_matrix_column_major_store:
4058 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4059
4060 case Builtin::BI__builtin_verbose_trap:
4061 if (!checkBuiltinVerboseTrap(TheCall, *this))
4062 return ExprError();
4063 break;
4064
4065 case Builtin::BI__builtin_get_device_side_mangled_name: {
4066 auto Check = [](CallExpr *TheCall) {
4067 if (TheCall->getNumArgs() != 1)
4068 return false;
4069 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
4070 if (!DRE)
4071 return false;
4072 auto *D = DRE->getDecl();
4073 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
4074 return false;
4075 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4076 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4077 };
4078 if (!Check(TheCall)) {
4079 Diag(TheCall->getBeginLoc(),
4080 diag::err_hip_invalid_args_builtin_mangled_name);
4081 return ExprError();
4082 }
4083 break;
4084 }
4085 case Builtin::BI__builtin_bswapg:
4086 if (BuiltinBswapg(*this, TheCall))
4087 return ExprError();
4088 break;
4089 case Builtin::BI__builtin_bitreverseg:
4090 if (BuiltinBitreverseg(*this, TheCall))
4091 return ExprError();
4092 break;
4093 case Builtin::BI__builtin_popcountg:
4094 if (BuiltinPopcountg(*this, TheCall))
4095 return ExprError();
4096 break;
4097 case Builtin::BI__builtin_clzg:
4098 case Builtin::BI__builtin_ctzg:
4099 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
4100 return ExprError();
4101 break;
4102
4103 case Builtin::BI__builtin_stdc_rotate_left:
4104 case Builtin::BI__builtin_stdc_rotate_right:
4105 if (BuiltinRotateGeneric(*this, TheCall))
4106 return ExprError();
4107 break;
4108
4109 case Builtin::BI__builtin_stdc_memreverse8:
4110 case Builtin::BIstdc_memreverse8:
4111 case Builtin::BIstdc_memreverse8u8:
4112 case Builtin::BIstdc_memreverse8u16:
4113 case Builtin::BIstdc_memreverse8u32:
4114 case Builtin::BIstdc_memreverse8u64:
4115 if (Context.getTargetInfo().getCharWidth() != 8) {
4116 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
4117 << TheCall->getDirectCallee()->getName();
4118 return ExprError();
4119 }
4120 break;
4121
4122 case Builtin::BI__builtin_stdc_bit_floor:
4123 case Builtin::BI__builtin_stdc_bit_ceil:
4124 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4125 return ExprError();
4126 break;
4127 case Builtin::BI__builtin_stdc_has_single_bit:
4128 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4129 return ExprError();
4130 break;
4131 case Builtin::BI__builtin_stdc_leading_zeros:
4132 case Builtin::BI__builtin_stdc_leading_ones:
4133 case Builtin::BI__builtin_stdc_trailing_zeros:
4134 case Builtin::BI__builtin_stdc_trailing_ones:
4135 case Builtin::BI__builtin_stdc_first_leading_zero:
4136 case Builtin::BI__builtin_stdc_first_leading_one:
4137 case Builtin::BI__builtin_stdc_first_trailing_zero:
4138 case Builtin::BI__builtin_stdc_first_trailing_one:
4139 case Builtin::BI__builtin_stdc_count_zeros:
4140 case Builtin::BI__builtin_stdc_count_ones:
4141 case Builtin::BI__builtin_stdc_bit_width:
4142 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4143 return ExprError();
4144 break;
4145
4146 case Builtin::BI__builtin_allow_runtime_check: {
4147 Expr *Arg = TheCall->getArg(0);
4148 // Check if the argument is a string literal.
4150 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4151 << Arg->getSourceRange();
4152 return ExprError();
4153 }
4154 break;
4155 }
4156
4157 case Builtin::BI__builtin_allow_sanitize_check: {
4158 if (checkArgCount(TheCall, 1))
4159 return ExprError();
4160
4161 Expr *Arg = TheCall->getArg(0);
4162 // Check if the argument is a string literal.
4163 const StringLiteral *SanitizerName =
4164 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4165 if (!SanitizerName) {
4166 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4167 << Arg->getSourceRange();
4168 return ExprError();
4169 }
4170 // Validate the sanitizer name.
4171 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4172 .Cases({"address", "thread", "memory", "hwaddress",
4173 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4174 true)
4175 .Default(false)) {
4176 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4177 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4178 << Arg->getSourceRange();
4179 return ExprError();
4180 }
4181 break;
4182 }
4183 case Builtin::BI__builtin_counted_by_ref:
4184 if (BuiltinCountedByRef(TheCall))
4185 return ExprError();
4186 break;
4187 }
4188
4189 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4190 return ExprError();
4191
4192 // Since the target specific builtins for each arch overlap, only check those
4193 // of the arch we are compiling for.
4194 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4195 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4196 assert(Context.getAuxTargetInfo() &&
4197 "Aux Target Builtin, but not an aux target?");
4198
4199 if (CheckTSBuiltinFunctionCall(
4200 *Context.getAuxTargetInfo(),
4201 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4202 return ExprError();
4203 } else {
4204 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4205 TheCall))
4206 return ExprError();
4207 }
4208 }
4209
4210 return TheCallResult;
4211}
4212
4213bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4214 llvm::APSInt Result;
4215 // We can't check the value of a dependent argument.
4216 Expr *Arg = TheCall->getArg(ArgNum);
4217 if (Arg->isTypeDependent() || Arg->isValueDependent())
4218 return false;
4219
4220 // Check constant-ness first.
4221 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4222 return true;
4223
4224 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4225 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4226 return false;
4227
4228 return Diag(TheCall->getBeginLoc(),
4229 diag::err_argument_not_contiguous_bit_field)
4230 << ArgNum << Arg->getSourceRange();
4231}
4232
4233bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4234 unsigned FirstArg, FormatStringInfo *FSI) {
4235 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4236 bool IsVariadic = false;
4237 if (const FunctionType *FnTy = D->getFunctionType())
4238 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4239 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4240 IsVariadic = BD->isVariadic();
4241 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4242 IsVariadic = OMD->isVariadic();
4243
4244 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4245 IsVariadic, FSI);
4246}
4247
4248bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4249 bool HasImplicitThisParam, bool IsVariadic,
4250 FormatStringInfo *FSI) {
4251 if (FirstArg == 0)
4253 else if (IsVariadic)
4255 else
4257 FSI->FormatIdx = FormatIdx - 1;
4258 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4259
4260 // The way the format attribute works in GCC, the implicit this argument
4261 // of member functions is counted. However, it doesn't appear in our own
4262 // lists, so decrement format_idx in that case.
4263 if (HasImplicitThisParam) {
4264 if(FSI->FormatIdx == 0)
4265 return false;
4266 --FSI->FormatIdx;
4267 if (FSI->FirstDataArg != 0)
4268 --FSI->FirstDataArg;
4269 }
4270 return true;
4271}
4272
4273/// Checks if a the given expression evaluates to null.
4274///
4275/// Returns true if the value evaluates to null.
4276static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4277 // Treat (smart) pointers constructed from nullptr as null, whether we can
4278 // const-evaluate them or not.
4279 // This must happen first: the smart pointer expr might have _Nonnull type!
4283 return true;
4284
4285 // If the expression has non-null type, it doesn't evaluate to null.
4286 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4287 if (*nullability == NullabilityKind::NonNull)
4288 return false;
4289 }
4290
4291 // As a special case, transparent unions initialized with zero are
4292 // considered null for the purposes of the nonnull attribute.
4293 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4294 UT &&
4295 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4296 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4297 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4298 Expr = ILE->getInit(0);
4299 }
4300
4301 bool Result;
4302 return (!Expr->isValueDependent() &&
4304 !Result);
4305}
4306
4308 const Expr *ArgExpr,
4309 SourceLocation CallSiteLoc) {
4310 if (CheckNonNullExpr(S, ArgExpr))
4311 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4312 S.PDiag(diag::warn_null_arg)
4313 << ArgExpr->getSourceRange());
4314}
4315
4316/// Determine whether the given type has a non-null nullability annotation.
4318 if (auto nullability = type->getNullability())
4319 return *nullability == NullabilityKind::NonNull;
4320
4321 return false;
4322}
4323
4325 const NamedDecl *FDecl,
4326 const FunctionProtoType *Proto,
4328 SourceLocation CallSiteLoc) {
4329 assert((FDecl || Proto) && "Need a function declaration or prototype");
4330
4331 // Already checked by constant evaluator.
4333 return;
4334 // Check the attributes attached to the method/function itself.
4335 llvm::SmallBitVector NonNullArgs;
4336 if (FDecl) {
4337 // Handle the nonnull attribute on the function/method declaration itself.
4338 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4339 if (!NonNull->args_size()) {
4340 // Easy case: all pointer arguments are nonnull.
4341 for (const auto *Arg : Args)
4342 if (S.isValidPointerAttrType(Arg->getType()))
4343 CheckNonNullArgument(S, Arg, CallSiteLoc);
4344 return;
4345 }
4346
4347 for (const ParamIdx &Idx : NonNull->args()) {
4348 unsigned IdxAST = Idx.getASTIndex();
4349 if (IdxAST >= Args.size())
4350 continue;
4351 if (NonNullArgs.empty())
4352 NonNullArgs.resize(Args.size());
4353 NonNullArgs.set(IdxAST);
4354 }
4355 }
4356 }
4357
4358 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4359 // Handle the nonnull attribute on the parameters of the
4360 // function/method.
4362 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4363 parms = FD->parameters();
4364 else
4365 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4366
4367 unsigned ParamIndex = 0;
4368 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4369 I != E; ++I, ++ParamIndex) {
4370 const ParmVarDecl *PVD = *I;
4371 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4372 if (NonNullArgs.empty())
4373 NonNullArgs.resize(Args.size());
4374
4375 NonNullArgs.set(ParamIndex);
4376 }
4377 }
4378 } else {
4379 // If we have a non-function, non-method declaration but no
4380 // function prototype, try to dig out the function prototype.
4381 if (!Proto) {
4382 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4383 QualType type = VD->getType().getNonReferenceType();
4384 if (auto pointerType = type->getAs<PointerType>())
4385 type = pointerType->getPointeeType();
4386 else if (auto blockType = type->getAs<BlockPointerType>())
4387 type = blockType->getPointeeType();
4388 // FIXME: data member pointers?
4389
4390 // Dig out the function prototype, if there is one.
4391 Proto = type->getAs<FunctionProtoType>();
4392 }
4393 }
4394
4395 // Fill in non-null argument information from the nullability
4396 // information on the parameter types (if we have them).
4397 if (Proto) {
4398 unsigned Index = 0;
4399 for (auto paramType : Proto->getParamTypes()) {
4400 if (isNonNullType(paramType)) {
4401 if (NonNullArgs.empty())
4402 NonNullArgs.resize(Args.size());
4403
4404 NonNullArgs.set(Index);
4405 }
4406
4407 ++Index;
4408 }
4409 }
4410 }
4411
4412 // Check for non-null arguments.
4413 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4414 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4415 if (NonNullArgs[ArgIndex])
4416 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4417 }
4418}
4419
4420void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4421 StringRef ParamName, QualType ArgTy,
4422 QualType ParamTy) {
4423
4424 // If a function accepts a pointer or reference type
4425 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4426 return;
4427
4428 // If the parameter is a pointer type, get the pointee type for the
4429 // argument too. If the parameter is a reference type, don't try to get
4430 // the pointee type for the argument.
4431 if (ParamTy->isPointerType())
4432 ArgTy = ArgTy->getPointeeType();
4433
4434 // Remove reference or pointer
4435 ParamTy = ParamTy->getPointeeType();
4436
4437 // Find expected alignment, and the actual alignment of the passed object.
4438 // getTypeAlignInChars requires complete types
4439 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4440 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4441 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4442 return;
4443
4444 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4445 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4446
4447 // If the argument is less aligned than the parameter, there is a
4448 // potential alignment issue.
4449 if (ArgAlign < ParamAlign)
4450 Diag(Loc, diag::warn_param_mismatched_alignment)
4451 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4452 << ParamName << (FDecl != nullptr) << FDecl;
4453}
4454
4455void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4456 const Expr *ThisArg,
4458 if (!FD || Args.empty())
4459 return;
4460 auto GetArgAt = [&](int Idx) -> const Expr * {
4461 if (Idx == LifetimeCaptureByAttr::Global ||
4462 Idx == LifetimeCaptureByAttr::Unknown)
4463 return nullptr;
4464 if (IsMemberFunction && Idx == 0)
4465 return ThisArg;
4466 return Args[Idx - IsMemberFunction];
4467 };
4468 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4469 unsigned ArgIdx) {
4470 if (!Attr)
4471 return;
4472
4473 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4474 for (int CapturingParamIdx : Attr->params()) {
4475 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4476 continue;
4477 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4478 // initialization codepath.
4479 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4481 continue;
4482 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4483 CapturingEntity CE{Capturing};
4484 // Ensure that 'Captured' outlives the 'Capturing' entity.
4485 checkCaptureByLifetime(*this, CE, Captured);
4486 }
4487 };
4488 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4489 for (const auto *A :
4490 FD->getParamDecl(I)->specific_attrs<LifetimeCaptureByAttr>())
4491 HandleCaptureByAttr(A, I + IsMemberFunction);
4492 // Check when the implicit object param is captured.
4493 if (IsMemberFunction) {
4494 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4495 if (!TSI)
4496 return;
4498 for (TypeLoc TL = TSI->getTypeLoc();
4499 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4500 TL = ATL.getModifiedLoc())
4501 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4502 }
4503}
4504
4506 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4507 bool IsMemberFunction, SourceLocation Loc,
4508 SourceRange Range, VariadicCallType CallType) {
4509
4510 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4511 llvm::any_of(Args, [](const Expr *E) {
4512 return E && E->isInstantiationDependent();
4513 }))
4514 return;
4515
4516 // Printf and scanf checking.
4517 llvm::SmallBitVector CheckedVarArgs;
4518 if (FDecl) {
4519 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4520 // Only create vector if there are format attributes.
4521 CheckedVarArgs.resize(Args.size());
4522 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4523 CheckedVarArgs);
4524 }
4525
4526 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4527 CheckedVarArgs.resize(Args.size());
4528 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4529 CheckedVarArgs);
4530 }
4531 }
4532
4533 // Refuse POD arguments that weren't caught by the format string
4534 // checks above.
4535 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4536 if (CallType != VariadicCallType::DoesNotApply &&
4537 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4538 unsigned NumParams = Proto ? Proto->getNumParams()
4539 : isa_and_nonnull<FunctionDecl>(FDecl)
4540 ? cast<FunctionDecl>(FDecl)->getNumParams()
4541 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4542 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4543 : 0;
4544
4545 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4546 // Args[ArgIdx] can be null in malformed code.
4547 if (const Expr *Arg = Args[ArgIdx]) {
4548 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4549 checkVariadicArgument(Arg, CallType);
4550 }
4551 }
4552 }
4553 if (FD)
4554 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4555 if (FDecl || Proto) {
4556 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4557
4558 // Type safety checking.
4559 if (FDecl) {
4560 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4561 CheckArgumentWithTypeTag(I, Args, Loc);
4562 }
4563 }
4564
4565 // Check that passed arguments match the alignment of original arguments.
4566 // Try to get the missing prototype from the declaration.
4567 if (!Proto && FDecl) {
4568 const auto *FT = FDecl->getFunctionType();
4569 if (isa_and_nonnull<FunctionProtoType>(FT))
4570 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4571 }
4572 if (Proto) {
4573 // For variadic functions, we may have more args than parameters.
4574 // For some K&R functions, we may have less args than parameters.
4575 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4576 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4577 bool IsScalableArg = false;
4578 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4579 // Args[ArgIdx] can be null in malformed code.
4580 if (const Expr *Arg = Args[ArgIdx]) {
4581 if (Arg->containsErrors())
4582 continue;
4583
4584 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4585 FDecl->hasLinkage() &&
4586 FDecl->getFormalLinkage() != Linkage::Internal &&
4588 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4589
4590 QualType ParamTy = Proto->getParamType(ArgIdx);
4591 if (ParamTy->isSizelessVectorType())
4592 IsScalableArg = true;
4593 QualType ArgTy = Arg->getType();
4594 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4595 ArgTy, ParamTy);
4596 }
4597 }
4598
4599 // If the callee has an AArch64 SME attribute to indicate that it is an
4600 // __arm_streaming function, then the caller requires SME to be available.
4603 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4604 llvm::StringMap<bool> CallerFeatureMap;
4605 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4606 if (!CallerFeatureMap.contains("sme"))
4607 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4608 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4609 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4610 }
4611 }
4612
4613 // If the call requires a streaming-mode change and has scalable vector
4614 // arguments or return values, then warn the user that the streaming and
4615 // non-streaming vector lengths may be different.
4616 // When both streaming and non-streaming vector lengths are defined and
4617 // mismatched, produce an error.
4618 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4619 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4620 (IsScalableArg || IsScalableRet)) {
4621 bool IsCalleeStreaming =
4623 bool IsCalleeStreamingCompatible =
4624 ExtInfo.AArch64SMEAttributes &
4626 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4627 if (!IsCalleeStreamingCompatible &&
4628 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4629 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4630 const LangOptions &LO = getLangOpts();
4631 unsigned VL = LO.VScaleMin * 128;
4632 unsigned SVL = LO.VScaleStreamingMin * 128;
4633 bool IsVLMismatch = VL && SVL && VL != SVL;
4634
4635 auto EmitDiag = [&](bool IsArg) {
4636 if (IsVLMismatch) {
4637 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4638 // Emit warning for streaming-compatible callers
4639 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4640 << IsArg << IsCalleeStreaming << SVL << VL;
4641 else
4642 // Emit error otherwise
4643 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4644 << IsArg << SVL << VL;
4645 } else
4646 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4647 << IsArg;
4648 };
4649
4650 if (IsScalableArg)
4651 EmitDiag(true);
4652 if (IsScalableRet)
4653 EmitDiag(false);
4654 }
4655 }
4656
4657 FunctionType::ArmStateValue CalleeArmZAState =
4659 FunctionType::ArmStateValue CalleeArmZT0State =
4661 if (CalleeArmZAState != FunctionType::ARM_None ||
4662 CalleeArmZT0State != FunctionType::ARM_None) {
4663 bool CallerHasZAState = false;
4664 bool CallerHasZT0State = false;
4665 if (CallerFD) {
4666 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4667 if (Attr && Attr->isNewZA())
4668 CallerHasZAState = true;
4669 if (Attr && Attr->isNewZT0())
4670 CallerHasZT0State = true;
4671 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4672 CallerHasZAState |=
4674 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4676 CallerHasZT0State |=
4678 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4680 }
4681 }
4682
4683 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4684 Diag(Loc, diag::err_sme_za_call_no_za_state);
4685
4686 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4687 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4688
4689 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4690 CalleeArmZT0State != FunctionType::ARM_None) {
4691 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4692 Diag(Loc, diag::note_sme_use_preserves_za);
4693 }
4694 }
4695 }
4696
4697 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4698 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4699 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4700 if (!Arg->isValueDependent()) {
4701 Expr::EvalResult Align;
4702 if (Arg->EvaluateAsInt(Align, Context)) {
4703 const llvm::APSInt &I = Align.Val.getInt();
4704 if (!I.isPowerOf2())
4705 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4706 << Arg->getSourceRange();
4707
4708 if (I > Sema::MaximumAlignment)
4709 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4710 << Arg->getSourceRange() << Sema::MaximumAlignment;
4711 }
4712 }
4713 }
4714
4715 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4717 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4718 << diag::OffloadLang::SYCL;
4719
4720 if (FD)
4721 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4722}
4723
4724void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4725 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4726 DiagnoseUseOfDecl(Decl, Loc);
4727 }
4728}
4729
4730void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4732 const FunctionProtoType *Proto,
4733 SourceLocation Loc) {
4734 VariadicCallType CallType = Proto->isVariadic()
4737
4738 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4739 CheckArgAlignment(
4740 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4741 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4742
4743 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4744 Loc, SourceRange(), CallType);
4745}
4746
4748 const FunctionProtoType *Proto) {
4749 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4750 isa<CXXMethodDecl>(FDecl);
4751 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4752 IsMemberOperatorCall;
4753 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4754 TheCall->getCallee());
4755 Expr** Args = TheCall->getArgs();
4756 unsigned NumArgs = TheCall->getNumArgs();
4757
4758 Expr *ImplicitThis = nullptr;
4759 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4760 // If this is a call to a member operator, hide the first
4761 // argument from checkCall.
4762 // FIXME: Our choice of AST representation here is less than ideal.
4763 ImplicitThis = Args[0];
4764 ++Args;
4765 --NumArgs;
4766 } else if (IsMemberFunction && !FDecl->isStatic() &&
4768 ImplicitThis =
4769 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4770
4771 if (ImplicitThis) {
4772 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4773 // used.
4774 QualType ThisType = ImplicitThis->getType();
4775 if (!ThisType->isPointerType()) {
4776 assert(!ThisType->isReferenceType());
4777 ThisType = Context.getPointerType(ThisType);
4778 }
4779
4780 QualType ThisTypeFromDecl = Context.getPointerType(
4781 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4782
4783 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4784 ThisTypeFromDecl);
4785 }
4786
4787 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4788 IsMemberFunction, TheCall->getRParenLoc(),
4789 TheCall->getCallee()->getSourceRange(), CallType);
4790
4791 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4792 // None of the checks below are needed for functions that don't have
4793 // simple names (e.g., C++ conversion functions).
4794 if (!FnInfo)
4795 return false;
4796
4797 // Enforce TCB except for builtin calls, which are always allowed.
4798 if (FDecl->getBuiltinID() == 0)
4799 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4800
4801 CheckAbsoluteValueFunction(TheCall, FDecl);
4802 CheckMaxUnsignedZero(TheCall, FDecl);
4803 CheckInfNaNFunction(TheCall, FDecl);
4804
4805 if (getLangOpts().ObjC)
4806 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4807
4808 unsigned CMId = FDecl->getMemoryFunctionKind();
4809
4810 // Handle memory setting and copying functions.
4811 switch (CMId) {
4812 case 0:
4813 return false;
4814 case Builtin::BIstrlcpy: // fallthrough
4815 case Builtin::BIstrlcat:
4816 CheckStrlcpycatArguments(TheCall, FnInfo);
4817 break;
4818 case Builtin::BIstrncat:
4819 CheckStrncatArguments(TheCall, FnInfo);
4820 break;
4821 case Builtin::BIfree:
4822 CheckFreeArguments(TheCall);
4823 break;
4824 default:
4825 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4826 }
4827
4828 return false;
4829}
4830
4831bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4832 const FunctionProtoType *Proto) {
4833 QualType Ty;
4834 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4835 Ty = V->getType().getNonReferenceType();
4836 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4837 Ty = F->getType().getNonReferenceType();
4838 else
4839 return false;
4840
4841 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4842 !Ty->isFunctionProtoType())
4843 return false;
4844
4845 VariadicCallType CallType;
4846 if (!Proto || !Proto->isVariadic()) {
4848 } else if (Ty->isBlockPointerType()) {
4849 CallType = VariadicCallType::Block;
4850 } else { // Ty->isFunctionPointerType()
4851 CallType = VariadicCallType::Function;
4852 }
4853
4854 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4855 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4856 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4857 TheCall->getCallee()->getSourceRange(), CallType);
4858
4859 return false;
4860}
4861
4862bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4863 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4864 TheCall->getCallee());
4865 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4866 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4867 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4868 TheCall->getCallee()->getSourceRange(), CallType);
4869
4870 return false;
4871}
4872
4873static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4874 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4875 return false;
4876
4877 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4878 switch (Op) {
4879 case AtomicExpr::AO__c11_atomic_init:
4880 case AtomicExpr::AO__opencl_atomic_init:
4881 llvm_unreachable("There is no ordering argument for an init");
4882
4883 case AtomicExpr::AO__c11_atomic_load:
4884 case AtomicExpr::AO__opencl_atomic_load:
4885 case AtomicExpr::AO__hip_atomic_load:
4886 case AtomicExpr::AO__atomic_load_n:
4887 case AtomicExpr::AO__atomic_load:
4888 case AtomicExpr::AO__scoped_atomic_load_n:
4889 case AtomicExpr::AO__scoped_atomic_load:
4890 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4891 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4892
4893 case AtomicExpr::AO__c11_atomic_store:
4894 case AtomicExpr::AO__opencl_atomic_store:
4895 case AtomicExpr::AO__hip_atomic_store:
4896 case AtomicExpr::AO__atomic_store:
4897 case AtomicExpr::AO__atomic_store_n:
4898 case AtomicExpr::AO__scoped_atomic_store:
4899 case AtomicExpr::AO__scoped_atomic_store_n:
4900 case AtomicExpr::AO__atomic_clear:
4901 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4902 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4903 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4904
4905 default:
4906 return true;
4907 }
4908}
4909
4910ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4912 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4913 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4914 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4915 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4916 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4917 Op);
4918}
4919
4920/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4921/// equivalents. Provide a fixit when the scope is a compile-time constant and
4922/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4923/// compare_exchange builtins differ in how they accept the desired value, so
4924/// only a warning (without a fixit) is emitted for those.
4926 MultiExprArg Args,
4928 StringRef OldName;
4929 StringRef NewName;
4930 bool CanFixIt;
4931
4932 switch (Op) {
4933#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4934 case AtomicExpr::AO__hip_atomic_##hip: \
4935 OldName = "__hip_atomic_" #hip; \
4936 NewName = "__scoped_atomic_" #scoped; \
4937 CanFixIt = true; \
4938 break;
4939 HIP_ATOMIC_FIXABLE(load, load_n)
4940 HIP_ATOMIC_FIXABLE(store, store_n)
4941 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4942 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4943 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4944 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4945 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4946 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4947 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4948 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4949#undef HIP_ATOMIC_FIXABLE
4950 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4951 OldName = "__hip_atomic_compare_exchange_weak";
4952 NewName = "__scoped_atomic_compare_exchange";
4953 CanFixIt = false;
4954 break;
4955 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4956 OldName = "__hip_atomic_compare_exchange_strong";
4957 NewName = "__scoped_atomic_compare_exchange";
4958 CanFixIt = false;
4959 break;
4960 default:
4961 llvm_unreachable("unhandled HIP atomic op");
4962 }
4963
4964 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4965 << OldName << NewName;
4966 if (!CanFixIt)
4967 return;
4968
4969 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4970
4971 Expr *Scope = Args[Args.size() - 1];
4972 std::optional<llvm::APSInt> ScopeVal =
4973 Scope->getIntegerConstantExpr(S.Context);
4974 if (!ScopeVal)
4975 return;
4976
4977 StringRef ScopeName;
4978 switch (ScopeVal->getZExtValue()) {
4980 ScopeName = "__MEMORY_SCOPE_SINGLE";
4981 break;
4983 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4984 break;
4986 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4987 break;
4989 ScopeName = "__MEMORY_SCOPE_DEVICE";
4990 break;
4992 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4993 break;
4995 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4996 break;
4997 default:
4998 return;
4999 }
5000
5002 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
5003}
5004
5006 SourceLocation RParenLoc, MultiExprArg Args,
5008 AtomicArgumentOrder ArgOrder) {
5009 // All the non-OpenCL operations take one of the following forms.
5010 // The OpenCL operations take the __c11 forms with one extra argument for
5011 // synchronization scope.
5012 enum {
5013 // C __c11_atomic_init(A *, C)
5014 Init,
5015
5016 // C __c11_atomic_load(A *, int)
5017 Load,
5018
5019 // void __atomic_load(A *, CP, int)
5020 LoadCopy,
5021
5022 // void __atomic_store(A *, CP, int)
5023 Copy,
5024
5025 // C __c11_atomic_add(A *, M, int)
5026 Arithmetic,
5027
5028 // C __atomic_exchange_n(A *, CP, int)
5029 Xchg,
5030
5031 // void __atomic_exchange(A *, C *, CP, int)
5032 GNUXchg,
5033
5034 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5035 C11CmpXchg,
5036
5037 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5038 GNUCmpXchg,
5039
5040 // bool __atomic_test_and_set(A *, int)
5041 TestAndSetByte,
5042
5043 // void __atomic_clear(A *, int)
5044 ClearByte,
5045 } Form = Init;
5046
5047 const unsigned NumForm = ClearByte + 1;
5048 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5049 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5050 // where:
5051 // C is an appropriate type,
5052 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5053 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5054 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5055 // the int parameters are for orderings.
5056
5057 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5058 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5059 "need to update code for modified forms");
5060 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5061 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5062 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5063 "need to update code for modified C11 atomics");
5064 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5065 Op <= AtomicExpr::AO__opencl_atomic_store;
5066 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5067 Op <= AtomicExpr::AO__hip_atomic_store;
5068 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5069 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5070 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5071 Op <= AtomicExpr::AO__c11_atomic_store) ||
5072 IsOpenCL;
5073 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5074 Op == AtomicExpr::AO__atomic_store_n ||
5075 Op == AtomicExpr::AO__atomic_exchange_n ||
5076 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5077 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5078 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5079 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5080 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5081 // Bit mask for extra allowed value types other than integers for atomic
5082 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5083 // allow floating point.
5084 enum ArithOpExtraValueType {
5085 AOEVT_None = 0,
5086 AOEVT_Pointer = 1,
5087 AOEVT_FP = 2,
5088 AOEVT_Int = 4,
5089 };
5090 unsigned ArithAllows = AOEVT_None;
5091
5092 switch (Op) {
5093 case AtomicExpr::AO__c11_atomic_init:
5094 case AtomicExpr::AO__opencl_atomic_init:
5095 Form = Init;
5096 break;
5097
5098 case AtomicExpr::AO__c11_atomic_load:
5099 case AtomicExpr::AO__opencl_atomic_load:
5100 case AtomicExpr::AO__hip_atomic_load:
5101 case AtomicExpr::AO__atomic_load_n:
5102 case AtomicExpr::AO__scoped_atomic_load_n:
5103 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5104 Form = Load;
5105 break;
5106
5107 case AtomicExpr::AO__atomic_load:
5108 case AtomicExpr::AO__scoped_atomic_load:
5109 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5110 Form = LoadCopy;
5111 break;
5112
5113 case AtomicExpr::AO__c11_atomic_store:
5114 case AtomicExpr::AO__opencl_atomic_store:
5115 case AtomicExpr::AO__hip_atomic_store:
5116 case AtomicExpr::AO__atomic_store:
5117 case AtomicExpr::AO__atomic_store_n:
5118 case AtomicExpr::AO__scoped_atomic_store:
5119 case AtomicExpr::AO__scoped_atomic_store_n:
5120 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5121 Form = Copy;
5122 break;
5123 case AtomicExpr::AO__atomic_fetch_add:
5124 case AtomicExpr::AO__atomic_fetch_sub:
5125 case AtomicExpr::AO__atomic_add_fetch:
5126 case AtomicExpr::AO__atomic_sub_fetch:
5127 case AtomicExpr::AO__scoped_atomic_fetch_add:
5128 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5129 case AtomicExpr::AO__scoped_atomic_add_fetch:
5130 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5131 case AtomicExpr::AO__c11_atomic_fetch_add:
5132 case AtomicExpr::AO__c11_atomic_fetch_sub:
5133 case AtomicExpr::AO__opencl_atomic_fetch_add:
5134 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5135 case AtomicExpr::AO__hip_atomic_fetch_add:
5136 case AtomicExpr::AO__hip_atomic_fetch_sub:
5137 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5138 Form = Arithmetic;
5139 break;
5140 case AtomicExpr::AO__atomic_fetch_fminimum:
5141 case AtomicExpr::AO__atomic_fetch_fmaximum:
5142 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5143 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5144 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5145 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5146 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5147 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5148 ArithAllows = AOEVT_FP;
5149 Form = Arithmetic;
5150 break;
5151 case AtomicExpr::AO__atomic_fetch_max:
5152 case AtomicExpr::AO__atomic_fetch_min:
5153 case AtomicExpr::AO__atomic_max_fetch:
5154 case AtomicExpr::AO__atomic_min_fetch:
5155 case AtomicExpr::AO__scoped_atomic_fetch_max:
5156 case AtomicExpr::AO__scoped_atomic_fetch_min:
5157 case AtomicExpr::AO__scoped_atomic_max_fetch:
5158 case AtomicExpr::AO__scoped_atomic_min_fetch:
5159 case AtomicExpr::AO__c11_atomic_fetch_max:
5160 case AtomicExpr::AO__c11_atomic_fetch_min:
5161 case AtomicExpr::AO__opencl_atomic_fetch_max:
5162 case AtomicExpr::AO__opencl_atomic_fetch_min:
5163 case AtomicExpr::AO__hip_atomic_fetch_max:
5164 case AtomicExpr::AO__hip_atomic_fetch_min:
5165 ArithAllows = AOEVT_Int | AOEVT_FP;
5166 Form = Arithmetic;
5167 break;
5168 case AtomicExpr::AO__c11_atomic_fetch_and:
5169 case AtomicExpr::AO__c11_atomic_fetch_or:
5170 case AtomicExpr::AO__c11_atomic_fetch_xor:
5171 case AtomicExpr::AO__hip_atomic_fetch_and:
5172 case AtomicExpr::AO__hip_atomic_fetch_or:
5173 case AtomicExpr::AO__hip_atomic_fetch_xor:
5174 case AtomicExpr::AO__c11_atomic_fetch_nand:
5175 case AtomicExpr::AO__opencl_atomic_fetch_and:
5176 case AtomicExpr::AO__opencl_atomic_fetch_or:
5177 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5178 case AtomicExpr::AO__atomic_fetch_and:
5179 case AtomicExpr::AO__atomic_fetch_or:
5180 case AtomicExpr::AO__atomic_fetch_xor:
5181 case AtomicExpr::AO__atomic_fetch_nand:
5182 case AtomicExpr::AO__atomic_and_fetch:
5183 case AtomicExpr::AO__atomic_or_fetch:
5184 case AtomicExpr::AO__atomic_xor_fetch:
5185 case AtomicExpr::AO__atomic_nand_fetch:
5186 case AtomicExpr::AO__atomic_fetch_uinc:
5187 case AtomicExpr::AO__atomic_fetch_udec:
5188 case AtomicExpr::AO__scoped_atomic_fetch_and:
5189 case AtomicExpr::AO__scoped_atomic_fetch_or:
5190 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5191 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5192 case AtomicExpr::AO__scoped_atomic_and_fetch:
5193 case AtomicExpr::AO__scoped_atomic_or_fetch:
5194 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5195 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5196 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5197 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5198 Form = Arithmetic;
5199 break;
5200
5201 case AtomicExpr::AO__c11_atomic_exchange:
5202 case AtomicExpr::AO__hip_atomic_exchange:
5203 case AtomicExpr::AO__opencl_atomic_exchange:
5204 case AtomicExpr::AO__atomic_exchange_n:
5205 case AtomicExpr::AO__scoped_atomic_exchange_n:
5206 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5207 Form = Xchg;
5208 break;
5209
5210 case AtomicExpr::AO__atomic_exchange:
5211 case AtomicExpr::AO__scoped_atomic_exchange:
5212 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5213 Form = GNUXchg;
5214 break;
5215
5216 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5217 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5218 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5219 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5220 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5221 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5222 Form = C11CmpXchg;
5223 break;
5224
5225 case AtomicExpr::AO__atomic_compare_exchange:
5226 case AtomicExpr::AO__atomic_compare_exchange_n:
5227 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5228 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5229 ArithAllows = AOEVT_Pointer;
5230 Form = GNUCmpXchg;
5231 break;
5232
5233 case AtomicExpr::AO__atomic_test_and_set:
5234 Form = TestAndSetByte;
5235 break;
5236
5237 case AtomicExpr::AO__atomic_clear:
5238 Form = ClearByte;
5239 break;
5240 }
5241
5242 unsigned AdjustedNumArgs = NumArgs[Form];
5243 if ((IsOpenCL || IsHIP || IsScoped) &&
5244 Op != AtomicExpr::AO__opencl_atomic_init)
5245 ++AdjustedNumArgs;
5246 // Check we have the right number of arguments.
5247 if (Args.size() < AdjustedNumArgs) {
5248 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5249 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5250 << /*is non object*/ 0 << ExprRange;
5251 return ExprError();
5252 } else if (Args.size() > AdjustedNumArgs) {
5253 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5254 diag::err_typecheck_call_too_many_args)
5255 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5256 << /*is non object*/ 0 << ExprRange;
5257 return ExprError();
5258 }
5259
5260 // Inspect the first argument of the atomic operation.
5261 Expr *Ptr = Args[0];
5263 if (ConvertedPtr.isInvalid())
5264 return ExprError();
5265
5266 Ptr = ConvertedPtr.get();
5267 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5268 if (!pointerType) {
5269 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5270 << Ptr->getType() << 0 << Ptr->getSourceRange();
5271 return ExprError();
5272 }
5273
5274 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5275 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5276 QualType ValType = AtomTy; // 'C'
5277 if (IsC11) {
5278 if (!AtomTy->isAtomicType()) {
5279 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5280 << Ptr->getType() << Ptr->getSourceRange();
5281 return ExprError();
5282 }
5283 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5285 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5286 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5287 << Ptr->getSourceRange();
5288 return ExprError();
5289 }
5290 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5291 } else if (Form != Load && Form != LoadCopy) {
5292 if (ValType.isConstQualified()) {
5293 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5294 << Ptr->getType() << Ptr->getSourceRange();
5295 return ExprError();
5296 }
5297 }
5298
5299 if (Form != TestAndSetByte && Form != ClearByte) {
5300 // Pointer to object of size zero is not allowed.
5301 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5302 diag::err_incomplete_type))
5303 return ExprError();
5304
5305 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5306 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5307 << Ptr->getType() << 1 << Ptr->getSourceRange();
5308 return ExprError();
5309 }
5310 } else {
5311 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5312 // non-const pointer type, including void* and pointers to incomplete
5313 // structs, but only access the first byte.
5314 AtomTy = Context.CharTy;
5315 AtomTy = AtomTy.withCVRQualifiers(
5316 pointerType->getPointeeType().getCVRQualifiers());
5317 QualType PointerQT = Context.getPointerType(AtomTy);
5318 pointerType = PointerQT->getAs<PointerType>();
5319 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5320 ValType = AtomTy;
5321 }
5322
5323 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5324 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5325 Diag(ExprRange.getBegin(),
5326 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5327 << 0 << Ptr->getType() << Ptr->getSourceRange();
5328 return ExprError();
5329 }
5330
5331 // For an arithmetic operation, the implied arithmetic must be well-formed.
5332 // For _n operations, the value type must also be a valid atomic type.
5333 if (Form == Arithmetic || IsN) {
5334 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5335 // trivial type errors.
5336 auto IsAllowedValueType = [&](QualType ValType,
5337 unsigned AllowedType) -> bool {
5338 bool IsX87LongDouble =
5339 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5340 &Context.getTargetInfo().getLongDoubleFormat() ==
5341 &llvm::APFloat::x87DoubleExtended();
5342 if (ValType->isIntegerType())
5343 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5344 // integers. Explicit AOEVT_Int or other combinations allow integers.
5345 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5346 if (ValType->isPointerType())
5347 return AllowedType & AOEVT_Pointer;
5348 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5349 return false;
5350 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5351 if (IsX87LongDouble)
5352 return false;
5353 return true;
5354 };
5355 if (!IsAllowedValueType(ValType, ArithAllows)) {
5356 auto DID =
5357 ArithAllows == AOEVT_FP
5358 ? diag::err_atomic_op_needs_atomic_fp
5359 : (ArithAllows & AOEVT_FP
5360 ? (ArithAllows & AOEVT_Pointer
5361 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5362 : diag::err_atomic_op_needs_atomic_int_or_fp)
5363 : (ArithAllows & AOEVT_Pointer
5364 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5365 : diag::err_atomic_op_needs_atomic_int));
5366 Diag(ExprRange.getBegin(), DID)
5367 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5368 return ExprError();
5369 }
5370 if (IsC11 && ValType->isPointerType() &&
5372 diag::err_incomplete_type)) {
5373 return ExprError();
5374 }
5375 }
5376
5377 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5378 !AtomTy->isScalarType()) {
5379 // For GNU atomics, require a trivially-copyable type. This is not part of
5380 // the GNU atomics specification but we enforce it for consistency with
5381 // other atomics which generally all require a trivially-copyable type. This
5382 // is because atomics just copy bits.
5383 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5384 << Ptr->getType() << Ptr->getSourceRange();
5385 return ExprError();
5386 }
5387
5388 switch (ValType.getObjCLifetime()) {
5391 // okay
5392 break;
5393
5397 // FIXME: Can this happen? By this point, ValType should be known
5398 // to be trivially copyable.
5399 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5400 << ValType << Ptr->getSourceRange();
5401 return ExprError();
5402 }
5403
5404 // All atomic operations have an overload which takes a pointer to a volatile
5405 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5406 // into the result or the other operands. Similarly atomic_load takes a
5407 // pointer to a const 'A'.
5408 ValType.removeLocalVolatile();
5409 ValType.removeLocalConst();
5410 QualType ResultType = ValType;
5411 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5412 Form == ClearByte)
5413 ResultType = Context.VoidTy;
5414 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5415 ResultType = Context.BoolTy;
5416
5417 // The type of a parameter passed 'by value'. In the GNU atomics, such
5418 // arguments are actually passed as pointers.
5419 QualType ByValType = ValType; // 'CP'
5420 bool IsPassedByAddress = false;
5421 if (!IsC11 && !IsHIP && !IsN) {
5422 ByValType = Ptr->getType();
5423 IsPassedByAddress = true;
5424 }
5425
5426 SmallVector<Expr *, 5> APIOrderedArgs;
5427 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5428 APIOrderedArgs.push_back(Args[0]);
5429 switch (Form) {
5430 case Init:
5431 case Load:
5432 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5433 break;
5434 case LoadCopy:
5435 case Copy:
5436 case Arithmetic:
5437 case Xchg:
5438 APIOrderedArgs.push_back(Args[2]); // Val1
5439 APIOrderedArgs.push_back(Args[1]); // Order
5440 break;
5441 case GNUXchg:
5442 APIOrderedArgs.push_back(Args[2]); // Val1
5443 APIOrderedArgs.push_back(Args[3]); // Val2
5444 APIOrderedArgs.push_back(Args[1]); // Order
5445 break;
5446 case C11CmpXchg:
5447 APIOrderedArgs.push_back(Args[2]); // Val1
5448 APIOrderedArgs.push_back(Args[4]); // Val2
5449 APIOrderedArgs.push_back(Args[1]); // Order
5450 APIOrderedArgs.push_back(Args[3]); // OrderFail
5451 break;
5452 case GNUCmpXchg:
5453 APIOrderedArgs.push_back(Args[2]); // Val1
5454 APIOrderedArgs.push_back(Args[4]); // Val2
5455 APIOrderedArgs.push_back(Args[5]); // Weak
5456 APIOrderedArgs.push_back(Args[1]); // Order
5457 APIOrderedArgs.push_back(Args[3]); // OrderFail
5458 break;
5459 case TestAndSetByte:
5460 case ClearByte:
5461 APIOrderedArgs.push_back(Args[1]); // Order
5462 break;
5463 }
5464 } else
5465 APIOrderedArgs.append(Args.begin(), Args.end());
5466
5467 // The first argument's non-CV pointer type is used to deduce the type of
5468 // subsequent arguments, except for:
5469 // - weak flag (always converted to bool)
5470 // - memory order (always converted to int)
5471 // - scope (always converted to int)
5472 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5473 QualType Ty;
5474 if (i < NumVals[Form] + 1) {
5475 switch (i) {
5476 case 0:
5477 // The first argument is always a pointer. It has a fixed type.
5478 // It is always dereferenced, a nullptr is undefined.
5479 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5480 // Nothing else to do: we already know all we want about this pointer.
5481 continue;
5482 case 1:
5483 // The second argument is the non-atomic operand. For arithmetic, this
5484 // is always passed by value, and for a compare_exchange it is always
5485 // passed by address. For the rest, GNU uses by-address and C11 uses
5486 // by-value.
5487 assert(Form != Load);
5488 if (Form == Arithmetic && ValType->isPointerType())
5489 Ty = Context.getPointerDiffType();
5490 else if (Form == Init || Form == Arithmetic)
5491 Ty = ValType;
5492 else if (Form == Copy || Form == Xchg) {
5493 if (IsPassedByAddress) {
5494 // The value pointer is always dereferenced, a nullptr is undefined.
5495 CheckNonNullArgument(*this, APIOrderedArgs[i],
5496 ExprRange.getBegin());
5497 }
5498 Ty = ByValType;
5499 } else {
5500 Expr *ValArg = APIOrderedArgs[i];
5501 // The value pointer is always dereferenced, a nullptr is undefined.
5502 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5504 // Keep address space of non-atomic pointer type.
5505 if (const PointerType *PtrTy =
5506 ValArg->getType()->getAs<PointerType>()) {
5507 AS = PtrTy->getPointeeType().getAddressSpace();
5508 }
5509 Ty = Context.getPointerType(
5510 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5511 }
5512 break;
5513 case 2:
5514 // The third argument to compare_exchange / GNU exchange is the desired
5515 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5516 if (IsPassedByAddress)
5517 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5518 Ty = ByValType;
5519 break;
5520 case 3:
5521 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5522 Ty = Context.BoolTy;
5523 break;
5524 }
5525 } else {
5526 // The order(s) and scope are always converted to int.
5527 Ty = Context.IntTy;
5528 }
5529
5530 InitializedEntity Entity =
5532 ExprResult Arg = APIOrderedArgs[i];
5533 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5534 if (Arg.isInvalid())
5535 return true;
5536 APIOrderedArgs[i] = Arg.get();
5537 }
5538
5539 // Permute the arguments into a 'consistent' order.
5540 SmallVector<Expr*, 5> SubExprs;
5541 SubExprs.push_back(Ptr);
5542 switch (Form) {
5543 case Init:
5544 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5545 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5546 break;
5547 case Load:
5548 case TestAndSetByte:
5549 case ClearByte:
5550 SubExprs.push_back(APIOrderedArgs[1]); // Order
5551 break;
5552 case LoadCopy:
5553 case Copy:
5554 case Arithmetic:
5555 case Xchg:
5556 SubExprs.push_back(APIOrderedArgs[2]); // Order
5557 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5558 break;
5559 case GNUXchg:
5560 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5561 SubExprs.push_back(APIOrderedArgs[3]); // Order
5562 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5563 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5564 break;
5565 case C11CmpXchg:
5566 SubExprs.push_back(APIOrderedArgs[3]); // Order
5567 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5568 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5569 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5570 break;
5571 case GNUCmpXchg:
5572 SubExprs.push_back(APIOrderedArgs[4]); // Order
5573 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5574 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5575 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5576 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5577 break;
5578 }
5579
5580 // If the memory orders are constants, check they are valid.
5581 if (SubExprs.size() >= 2 && Form != Init) {
5582 std::optional<llvm::APSInt> Success =
5583 SubExprs[1]->getIntegerConstantExpr(Context);
5584 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5585 Diag(SubExprs[1]->getBeginLoc(),
5586 diag::warn_atomic_op_has_invalid_memory_order)
5587 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5588 << SubExprs[1]->getSourceRange();
5589 }
5590 if (SubExprs.size() >= 5) {
5591 if (std::optional<llvm::APSInt> Failure =
5592 SubExprs[3]->getIntegerConstantExpr(Context)) {
5593 if (!llvm::is_contained(
5594 {llvm::AtomicOrderingCABI::relaxed,
5595 llvm::AtomicOrderingCABI::consume,
5596 llvm::AtomicOrderingCABI::acquire,
5597 llvm::AtomicOrderingCABI::seq_cst},
5598 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5599 Diag(SubExprs[3]->getBeginLoc(),
5600 diag::warn_atomic_op_has_invalid_memory_order)
5601 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5602 }
5603 }
5604 }
5605 }
5606
5607 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5608 auto *Scope = Args[Args.size() - 1];
5609 if (std::optional<llvm::APSInt> Result =
5610 Scope->getIntegerConstantExpr(Context)) {
5611 if (!ScopeModel->isValid(Result->getZExtValue()))
5612 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5613 << Scope->getSourceRange();
5614 }
5615 SubExprs.push_back(Scope);
5616 }
5617
5618 if (IsHIP)
5619 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5620
5621 AtomicExpr *AE = new (Context)
5622 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5623
5624 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5625 Op == AtomicExpr::AO__c11_atomic_store ||
5626 Op == AtomicExpr::AO__opencl_atomic_load ||
5627 Op == AtomicExpr::AO__hip_atomic_load ||
5628 Op == AtomicExpr::AO__opencl_atomic_store ||
5629 Op == AtomicExpr::AO__hip_atomic_store) &&
5630 Context.AtomicUsesUnsupportedLibcall(AE))
5631 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5632 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5633 Op == AtomicExpr::AO__opencl_atomic_load ||
5634 Op == AtomicExpr::AO__hip_atomic_load)
5635 ? 0
5636 : 1);
5637
5638 if (ValType->isBitIntType()) {
5639 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5640 return ExprError();
5641 }
5642
5643 return AE;
5644}
5645
5646/// checkBuiltinArgument - Given a call to a builtin function, perform
5647/// normal type-checking on the given argument, updating the call in
5648/// place. This is useful when a builtin function requires custom
5649/// type-checking for some of its arguments but not necessarily all of
5650/// them.
5651///
5652/// Returns true on error.
5653static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5654 FunctionDecl *Fn = E->getDirectCallee();
5655 assert(Fn && "builtin call without direct callee!");
5656
5657 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5658 InitializedEntity Entity =
5660
5661 ExprResult Arg = E->getArg(ArgIndex);
5662 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5663 if (Arg.isInvalid())
5664 return true;
5665
5666 E->setArg(ArgIndex, Arg.get());
5667 return false;
5668}
5669
5670ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5671 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5672 Expr *Callee = TheCall->getCallee();
5673 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5674 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5675
5676 // Ensure that we have at least one argument to do type inference from.
5677 if (TheCall->getNumArgs() < 1) {
5678 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5679 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5680 << Callee->getSourceRange();
5681 return ExprError();
5682 }
5683
5684 // Inspect the first argument of the atomic builtin. This should always be
5685 // a pointer type, whose element is an integral scalar or pointer type.
5686 // Because it is a pointer type, we don't have to worry about any implicit
5687 // casts here.
5688 // FIXME: We don't allow floating point scalars as input.
5689 Expr *FirstArg = TheCall->getArg(0);
5690 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5691 if (FirstArgResult.isInvalid())
5692 return ExprError();
5693 FirstArg = FirstArgResult.get();
5694 TheCall->setArg(0, FirstArg);
5695
5696 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5697 if (!pointerType) {
5698 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5699 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5700 return ExprError();
5701 }
5702
5703 QualType ValType = pointerType->getPointeeType();
5704 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5705 !ValType->isBlockPointerType()) {
5706 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5707 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5708 return ExprError();
5709 }
5710 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5711 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5712 Diag(FirstArg->getBeginLoc(),
5713 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5714 << 1 << ValType << FirstArg->getSourceRange();
5715 return ExprError();
5716 }
5717
5718 if (ValType.isConstQualified()) {
5719 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5720 << FirstArg->getType() << FirstArg->getSourceRange();
5721 return ExprError();
5722 }
5723
5724 switch (ValType.getObjCLifetime()) {
5727 // okay
5728 break;
5729
5733 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5734 << ValType << FirstArg->getSourceRange();
5735 return ExprError();
5736 }
5737
5738 // Strip any qualifiers off ValType.
5739 ValType = ValType.getUnqualifiedType();
5740
5741 // The majority of builtins return a value, but a few have special return
5742 // types, so allow them to override appropriately below.
5743 QualType ResultType = ValType;
5744
5745 // We need to figure out which concrete builtin this maps onto. For example,
5746 // __sync_fetch_and_add with a 2 byte object turns into
5747 // __sync_fetch_and_add_2.
5748#define BUILTIN_ROW(x) \
5749 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5750 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5751
5752 static const unsigned BuiltinIndices[][5] = {
5753 BUILTIN_ROW(__sync_fetch_and_add),
5754 BUILTIN_ROW(__sync_fetch_and_sub),
5755 BUILTIN_ROW(__sync_fetch_and_or),
5756 BUILTIN_ROW(__sync_fetch_and_and),
5757 BUILTIN_ROW(__sync_fetch_and_xor),
5758 BUILTIN_ROW(__sync_fetch_and_nand),
5759
5760 BUILTIN_ROW(__sync_add_and_fetch),
5761 BUILTIN_ROW(__sync_sub_and_fetch),
5762 BUILTIN_ROW(__sync_and_and_fetch),
5763 BUILTIN_ROW(__sync_or_and_fetch),
5764 BUILTIN_ROW(__sync_xor_and_fetch),
5765 BUILTIN_ROW(__sync_nand_and_fetch),
5766
5767 BUILTIN_ROW(__sync_val_compare_and_swap),
5768 BUILTIN_ROW(__sync_bool_compare_and_swap),
5769 BUILTIN_ROW(__sync_lock_test_and_set),
5770 BUILTIN_ROW(__sync_lock_release),
5771 BUILTIN_ROW(__sync_swap)
5772 };
5773#undef BUILTIN_ROW
5774
5775 // Determine the index of the size.
5776 unsigned SizeIndex;
5777 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5778 case 1: SizeIndex = 0; break;
5779 case 2: SizeIndex = 1; break;
5780 case 4: SizeIndex = 2; break;
5781 case 8: SizeIndex = 3; break;
5782 case 16: SizeIndex = 4; break;
5783 default:
5784 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5785 << FirstArg->getType() << FirstArg->getSourceRange();
5786 return ExprError();
5787 }
5788
5789 // Each of these builtins has one pointer argument, followed by some number of
5790 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5791 // that we ignore. Find out which row of BuiltinIndices to read from as well
5792 // as the number of fixed args.
5793 unsigned BuiltinID = FDecl->getBuiltinID();
5794 unsigned BuiltinIndex, NumFixed = 1;
5795 bool WarnAboutSemanticsChange = false;
5796 switch (BuiltinID) {
5797 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5798 case Builtin::BI__sync_fetch_and_add:
5799 case Builtin::BI__sync_fetch_and_add_1:
5800 case Builtin::BI__sync_fetch_and_add_2:
5801 case Builtin::BI__sync_fetch_and_add_4:
5802 case Builtin::BI__sync_fetch_and_add_8:
5803 case Builtin::BI__sync_fetch_and_add_16:
5804 BuiltinIndex = 0;
5805 break;
5806
5807 case Builtin::BI__sync_fetch_and_sub:
5808 case Builtin::BI__sync_fetch_and_sub_1:
5809 case Builtin::BI__sync_fetch_and_sub_2:
5810 case Builtin::BI__sync_fetch_and_sub_4:
5811 case Builtin::BI__sync_fetch_and_sub_8:
5812 case Builtin::BI__sync_fetch_and_sub_16:
5813 BuiltinIndex = 1;
5814 break;
5815
5816 case Builtin::BI__sync_fetch_and_or:
5817 case Builtin::BI__sync_fetch_and_or_1:
5818 case Builtin::BI__sync_fetch_and_or_2:
5819 case Builtin::BI__sync_fetch_and_or_4:
5820 case Builtin::BI__sync_fetch_and_or_8:
5821 case Builtin::BI__sync_fetch_and_or_16:
5822 BuiltinIndex = 2;
5823 break;
5824
5825 case Builtin::BI__sync_fetch_and_and:
5826 case Builtin::BI__sync_fetch_and_and_1:
5827 case Builtin::BI__sync_fetch_and_and_2:
5828 case Builtin::BI__sync_fetch_and_and_4:
5829 case Builtin::BI__sync_fetch_and_and_8:
5830 case Builtin::BI__sync_fetch_and_and_16:
5831 BuiltinIndex = 3;
5832 break;
5833
5834 case Builtin::BI__sync_fetch_and_xor:
5835 case Builtin::BI__sync_fetch_and_xor_1:
5836 case Builtin::BI__sync_fetch_and_xor_2:
5837 case Builtin::BI__sync_fetch_and_xor_4:
5838 case Builtin::BI__sync_fetch_and_xor_8:
5839 case Builtin::BI__sync_fetch_and_xor_16:
5840 BuiltinIndex = 4;
5841 break;
5842
5843 case Builtin::BI__sync_fetch_and_nand:
5844 case Builtin::BI__sync_fetch_and_nand_1:
5845 case Builtin::BI__sync_fetch_and_nand_2:
5846 case Builtin::BI__sync_fetch_and_nand_4:
5847 case Builtin::BI__sync_fetch_and_nand_8:
5848 case Builtin::BI__sync_fetch_and_nand_16:
5849 BuiltinIndex = 5;
5850 WarnAboutSemanticsChange = true;
5851 break;
5852
5853 case Builtin::BI__sync_add_and_fetch:
5854 case Builtin::BI__sync_add_and_fetch_1:
5855 case Builtin::BI__sync_add_and_fetch_2:
5856 case Builtin::BI__sync_add_and_fetch_4:
5857 case Builtin::BI__sync_add_and_fetch_8:
5858 case Builtin::BI__sync_add_and_fetch_16:
5859 BuiltinIndex = 6;
5860 break;
5861
5862 case Builtin::BI__sync_sub_and_fetch:
5863 case Builtin::BI__sync_sub_and_fetch_1:
5864 case Builtin::BI__sync_sub_and_fetch_2:
5865 case Builtin::BI__sync_sub_and_fetch_4:
5866 case Builtin::BI__sync_sub_and_fetch_8:
5867 case Builtin::BI__sync_sub_and_fetch_16:
5868 BuiltinIndex = 7;
5869 break;
5870
5871 case Builtin::BI__sync_and_and_fetch:
5872 case Builtin::BI__sync_and_and_fetch_1:
5873 case Builtin::BI__sync_and_and_fetch_2:
5874 case Builtin::BI__sync_and_and_fetch_4:
5875 case Builtin::BI__sync_and_and_fetch_8:
5876 case Builtin::BI__sync_and_and_fetch_16:
5877 BuiltinIndex = 8;
5878 break;
5879
5880 case Builtin::BI__sync_or_and_fetch:
5881 case Builtin::BI__sync_or_and_fetch_1:
5882 case Builtin::BI__sync_or_and_fetch_2:
5883 case Builtin::BI__sync_or_and_fetch_4:
5884 case Builtin::BI__sync_or_and_fetch_8:
5885 case Builtin::BI__sync_or_and_fetch_16:
5886 BuiltinIndex = 9;
5887 break;
5888
5889 case Builtin::BI__sync_xor_and_fetch:
5890 case Builtin::BI__sync_xor_and_fetch_1:
5891 case Builtin::BI__sync_xor_and_fetch_2:
5892 case Builtin::BI__sync_xor_and_fetch_4:
5893 case Builtin::BI__sync_xor_and_fetch_8:
5894 case Builtin::BI__sync_xor_and_fetch_16:
5895 BuiltinIndex = 10;
5896 break;
5897
5898 case Builtin::BI__sync_nand_and_fetch:
5899 case Builtin::BI__sync_nand_and_fetch_1:
5900 case Builtin::BI__sync_nand_and_fetch_2:
5901 case Builtin::BI__sync_nand_and_fetch_4:
5902 case Builtin::BI__sync_nand_and_fetch_8:
5903 case Builtin::BI__sync_nand_and_fetch_16:
5904 BuiltinIndex = 11;
5905 WarnAboutSemanticsChange = true;
5906 break;
5907
5908 case Builtin::BI__sync_val_compare_and_swap:
5909 case Builtin::BI__sync_val_compare_and_swap_1:
5910 case Builtin::BI__sync_val_compare_and_swap_2:
5911 case Builtin::BI__sync_val_compare_and_swap_4:
5912 case Builtin::BI__sync_val_compare_and_swap_8:
5913 case Builtin::BI__sync_val_compare_and_swap_16:
5914 BuiltinIndex = 12;
5915 NumFixed = 2;
5916 break;
5917
5918 case Builtin::BI__sync_bool_compare_and_swap:
5919 case Builtin::BI__sync_bool_compare_and_swap_1:
5920 case Builtin::BI__sync_bool_compare_and_swap_2:
5921 case Builtin::BI__sync_bool_compare_and_swap_4:
5922 case Builtin::BI__sync_bool_compare_and_swap_8:
5923 case Builtin::BI__sync_bool_compare_and_swap_16:
5924 BuiltinIndex = 13;
5925 NumFixed = 2;
5926 ResultType = Context.BoolTy;
5927 break;
5928
5929 case Builtin::BI__sync_lock_test_and_set:
5930 case Builtin::BI__sync_lock_test_and_set_1:
5931 case Builtin::BI__sync_lock_test_and_set_2:
5932 case Builtin::BI__sync_lock_test_and_set_4:
5933 case Builtin::BI__sync_lock_test_and_set_8:
5934 case Builtin::BI__sync_lock_test_and_set_16:
5935 BuiltinIndex = 14;
5936 break;
5937
5938 case Builtin::BI__sync_lock_release:
5939 case Builtin::BI__sync_lock_release_1:
5940 case Builtin::BI__sync_lock_release_2:
5941 case Builtin::BI__sync_lock_release_4:
5942 case Builtin::BI__sync_lock_release_8:
5943 case Builtin::BI__sync_lock_release_16:
5944 BuiltinIndex = 15;
5945 NumFixed = 0;
5946 ResultType = Context.VoidTy;
5947 break;
5948
5949 case Builtin::BI__sync_swap:
5950 case Builtin::BI__sync_swap_1:
5951 case Builtin::BI__sync_swap_2:
5952 case Builtin::BI__sync_swap_4:
5953 case Builtin::BI__sync_swap_8:
5954 case Builtin::BI__sync_swap_16:
5955 BuiltinIndex = 16;
5956 break;
5957 }
5958
5959 // Now that we know how many fixed arguments we expect, first check that we
5960 // have at least that many.
5961 if (TheCall->getNumArgs() < 1+NumFixed) {
5962 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5963 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5964 << Callee->getSourceRange();
5965 return ExprError();
5966 }
5967
5968 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5969 << Callee->getSourceRange();
5970
5971 if (WarnAboutSemanticsChange) {
5972 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5973 << Callee->getSourceRange();
5974 }
5975
5976 // Get the decl for the concrete builtin from this, we can tell what the
5977 // concrete integer type we should convert to is.
5978 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5979 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5980 FunctionDecl *NewBuiltinDecl;
5981 if (NewBuiltinID == BuiltinID)
5982 NewBuiltinDecl = FDecl;
5983 else {
5984 // Perform builtin lookup to avoid redeclaring it.
5985 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5986 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5987 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5988 assert(Res.getFoundDecl());
5989 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5990 if (!NewBuiltinDecl)
5991 return ExprError();
5992 }
5993
5994 // The first argument --- the pointer --- has a fixed type; we
5995 // deduce the types of the rest of the arguments accordingly. Walk
5996 // the remaining arguments, converting them to the deduced value type.
5997 for (unsigned i = 0; i != NumFixed; ++i) {
5998 ExprResult Arg = TheCall->getArg(i+1);
5999
6000 // GCC does an implicit conversion to the pointer or integer ValType. This
6001 // can fail in some cases (1i -> int**), check for this error case now.
6002 // Initialize the argument.
6003 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6004 ValType, /*consume*/ false);
6005 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6006 if (Arg.isInvalid())
6007 return ExprError();
6008
6009 // Okay, we have something that *can* be converted to the right type. Check
6010 // to see if there is a potentially weird extension going on here. This can
6011 // happen when you do an atomic operation on something like an char* and
6012 // pass in 42. The 42 gets converted to char. This is even more strange
6013 // for things like 45.123 -> char, etc.
6014 // FIXME: Do this check.
6015 TheCall->setArg(i+1, Arg.get());
6016 }
6017
6018 // Create a new DeclRefExpr to refer to the new decl.
6019 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6020 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6021 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6022 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6023
6024 // Set the callee in the CallExpr.
6025 // FIXME: This loses syntactic information.
6026 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6027 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6028 CK_BuiltinFnToFnPtr);
6029 TheCall->setCallee(PromotedCall.get());
6030
6031 // Change the result type of the call to match the original value type. This
6032 // is arbitrary, but the codegen for these builtins ins design to handle it
6033 // gracefully.
6034 TheCall->setType(ResultType);
6035
6036 // Prohibit problematic uses of bit-precise integer types with atomic
6037 // builtins. The arguments would have already been converted to the first
6038 // argument's type, so only need to check the first argument.
6039 const auto *BitIntValType = ValType->getAs<BitIntType>();
6040 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6041 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6042 return ExprError();
6043 }
6044
6045 return TheCallResult;
6046}
6047
6048ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6049 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6050 DeclRefExpr *DRE =
6052 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6053 unsigned BuiltinID = FDecl->getBuiltinID();
6054 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6055 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6056 "Unexpected nontemporal load/store builtin!");
6057 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6058 unsigned numArgs = isStore ? 2 : 1;
6059
6060 // Ensure that we have the proper number of arguments.
6061 if (checkArgCount(TheCall, numArgs))
6062 return ExprError();
6063
6064 // Inspect the last argument of the nontemporal builtin. This should always
6065 // be a pointer type, from which we imply the type of the memory access.
6066 // Because it is a pointer type, we don't have to worry about any implicit
6067 // casts here.
6068 Expr *PointerArg = TheCall->getArg(numArgs - 1);
6069 ExprResult PointerArgResult =
6071
6072 if (PointerArgResult.isInvalid())
6073 return ExprError();
6074 PointerArg = PointerArgResult.get();
6075 TheCall->setArg(numArgs - 1, PointerArg);
6076
6077 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6078 if (!pointerType) {
6079 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6080 << PointerArg->getType() << PointerArg->getSourceRange();
6081 return ExprError();
6082 }
6083
6084 QualType ValType = pointerType->getPointeeType();
6085
6086 // Strip any qualifiers off ValType.
6087 ValType = ValType.getUnqualifiedType();
6088 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6089 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6090 !ValType->isVectorType()) {
6091 Diag(DRE->getBeginLoc(),
6092 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6093 << PointerArg->getType() << PointerArg->getSourceRange();
6094 return ExprError();
6095 }
6096
6097 if (!isStore) {
6098 TheCall->setType(ValType);
6099 return TheCallResult;
6100 }
6101
6102 ExprResult ValArg = TheCall->getArg(0);
6103 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6104 Context, ValType, /*consume*/ false);
6105 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6106 if (ValArg.isInvalid())
6107 return ExprError();
6108
6109 TheCall->setArg(0, ValArg.get());
6110 TheCall->setType(Context.VoidTy);
6111 return TheCallResult;
6112}
6113
6114/// CheckObjCString - Checks that the format string argument to the os_log()
6115/// and os_trace() functions is correct, and converts it to const char *.
6116ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6117 Arg = Arg->IgnoreParenCasts();
6118 auto *Literal = dyn_cast<StringLiteral>(Arg);
6119 if (!Literal) {
6120 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6121 Literal = ObjcLiteral->getString();
6122 }
6123 }
6124
6125 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6126 return ExprError(
6127 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6128 << Arg->getSourceRange());
6129 }
6130
6131 ExprResult Result(Literal);
6132 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6133 InitializedEntity Entity =
6135 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6136 return Result;
6137}
6138
6139/// Check that the user is calling the appropriate va_start builtin for the
6140/// target and calling convention.
6141static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6142 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6143 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6144 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6145 TT.getArch() == llvm::Triple::aarch64_32);
6146 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6147 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6148 if (IsX64 || IsAArch64) {
6149 CallingConv CC = CC_C;
6150 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6151 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6152 if (IsMSVAStart) {
6153 // Don't allow this in System V ABI functions.
6154 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6155 return S.Diag(Fn->getBeginLoc(),
6156 diag::err_ms_va_start_used_in_sysv_function);
6157 } else {
6158 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6159 // On x64 Windows, don't allow this in System V ABI functions.
6160 // (Yes, that means there's no corresponding way to support variadic
6161 // System V ABI functions on Windows.)
6162 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6163 (!IsWindowsOrUEFI && CC == CC_Win64))
6164 return S.Diag(Fn->getBeginLoc(),
6165 diag::err_va_start_used_in_wrong_abi_function)
6166 << !IsWindowsOrUEFI;
6167 }
6168 return false;
6169 }
6170
6171 if (IsMSVAStart)
6172 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6173 return false;
6174}
6175
6177 ParmVarDecl **LastParam = nullptr) {
6178 // Determine whether the current function, block, or obj-c method is variadic
6179 // and get its parameter list.
6180 bool IsVariadic = false;
6182 DeclContext *Caller = S.CurContext;
6183 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6184 IsVariadic = Block->isVariadic();
6185 Params = Block->parameters();
6186 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6187 IsVariadic = FD->isVariadic();
6188 Params = FD->parameters();
6189 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6190 IsVariadic = MD->isVariadic();
6191 // FIXME: This isn't correct for methods (results in bogus warning).
6192 Params = MD->parameters();
6193 } else if (isa<CapturedDecl>(Caller)) {
6194 // We don't support va_start in a CapturedDecl.
6195 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6196 return true;
6197 } else {
6198 // This must be some other declcontext that parses exprs.
6199 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6200 return true;
6201 }
6202
6203 if (!IsVariadic) {
6204 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6205 return true;
6206 }
6207
6208 if (LastParam)
6209 *LastParam = Params.empty() ? nullptr : Params.back();
6210
6211 return false;
6212}
6213
6214bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6215 Expr *Fn = TheCall->getCallee();
6216 if (checkVAStartABI(*this, BuiltinID, Fn))
6217 return true;
6218
6219 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6220 // This builtin requires one argument (the va_list), allows two arguments,
6221 // but diagnoses more than two arguments. e.g.,
6222 // __builtin_c23_va_start(); // error
6223 // __builtin_c23_va_start(list); // ok
6224 // __builtin_c23_va_start(list, param); // ok
6225 // __builtin_c23_va_start(list, anything, anything); // error
6226 // This differs from the GCC behavior in that they accept the last case
6227 // with a warning, but it doesn't seem like a useful behavior to allow.
6228 if (checkArgCountRange(TheCall, 1, 2))
6229 return true;
6230 } else {
6231 // In C23 mode, va_start only needs one argument. However, the builtin still
6232 // requires two arguments (which matches the behavior of the GCC builtin),
6233 // <stdarg.h> passes `0` as the second argument in C23 mode.
6234 if (checkArgCount(TheCall, 2))
6235 return true;
6236 }
6237
6238 // Type-check the first argument normally.
6239 if (checkBuiltinArgument(*this, TheCall, 0))
6240 return true;
6241
6242 // Check that the current function is variadic, and get its last parameter.
6243 ParmVarDecl *LastParam;
6244 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6245 return true;
6246
6247 // Verify that the second argument to the builtin is the last non-variadic
6248 // argument of the current function or method. In C23 mode, if the call is
6249 // not to __builtin_c23_va_start, and the second argument is an integer
6250 // constant expression with value 0, then we don't bother with this check.
6251 // For __builtin_c23_va_start, we only perform the check for the second
6252 // argument being the last argument to the current function if there is a
6253 // second argument present.
6254 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6255 TheCall->getNumArgs() < 2) {
6256 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6257 return false;
6258 }
6259
6260 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6261 if (std::optional<llvm::APSInt> Val =
6263 Val && LangOpts.C23 && *Val == 0 &&
6264 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6265 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6266 return false;
6267 }
6268
6269 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6270 // next block.
6271 QualType Type;
6272 SourceLocation ParamLoc;
6273 bool IsCRegister = false;
6274 bool SecondArgIsLastNonVariadicArgument = false;
6275 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6276 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6277 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6278
6279 Type = PV->getType();
6280 ParamLoc = PV->getLocation();
6281 IsCRegister =
6282 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6283 }
6284 }
6285
6286 if (!SecondArgIsLastNonVariadicArgument)
6287 Diag(TheCall->getArg(1)->getBeginLoc(),
6288 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6289 else if (IsCRegister || Type->isReferenceType() ||
6290 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6291 // Promotable integers are UB, but enumerations need a bit of
6292 // extra checking to see what their promotable type actually is.
6293 if (!Context.isPromotableIntegerType(Type))
6294 return false;
6295 const auto *ED = Type->getAsEnumDecl();
6296 if (!ED)
6297 return true;
6298 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6299 }()) {
6300 unsigned Reason = 0;
6301 if (Type->isReferenceType()) Reason = 1;
6302 else if (IsCRegister) Reason = 2;
6303 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6304 Diag(ParamLoc, diag::note_parameter_type) << Type;
6305 }
6306
6307 return false;
6308}
6309
6310bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6311 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6312 const LangOptions &LO = getLangOpts();
6313
6314 if (LO.CPlusPlus)
6315 return Arg->getType()
6317 .getTypePtr()
6318 ->getPointeeType()
6320
6321 // In C, allow aliasing through `char *`, this is required for AArch64 at
6322 // least.
6323 return true;
6324 };
6325
6326 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6327 // const char *named_addr);
6328
6329 Expr *Func = Call->getCallee();
6330
6331 if (Call->getNumArgs() < 3)
6332 return Diag(Call->getEndLoc(),
6333 diag::err_typecheck_call_too_few_args_at_least)
6334 << 0 /*function call*/ << 3 << Call->getNumArgs()
6335 << /*is non object*/ 0;
6336
6337 // Type-check the first argument normally.
6338 if (checkBuiltinArgument(*this, Call, 0))
6339 return true;
6340
6341 // Check that the current function is variadic.
6343 return true;
6344
6345 // __va_start on Windows does not validate the parameter qualifiers
6346
6347 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6348 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6349
6350 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6351 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6352
6353 const QualType &ConstCharPtrTy =
6354 Context.getPointerType(Context.CharTy.withConst());
6355 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6356 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6357 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6358 << 0 /* qualifier difference */
6359 << 3 /* parameter mismatch */
6360 << 2 << Arg1->getType() << ConstCharPtrTy;
6361
6362 const QualType SizeTy = Context.getSizeType();
6363 if (!Context.hasSameType(
6365 SizeTy))
6366 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6367 << Arg2->getType() << SizeTy << 1 /* different class */
6368 << 0 /* qualifier difference */
6369 << 3 /* parameter mismatch */
6370 << 3 << Arg2->getType() << SizeTy;
6371
6372 return false;
6373}
6374
6375bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6376 if (checkArgCount(TheCall, 2))
6377 return true;
6378
6379 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6380 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6381 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6382 << 1 << 0 << TheCall->getSourceRange();
6383
6384 ExprResult OrigArg0 = TheCall->getArg(0);
6385 ExprResult OrigArg1 = TheCall->getArg(1);
6386
6387 // Do standard promotions between the two arguments, returning their common
6388 // type.
6389 QualType Res = UsualArithmeticConversions(
6390 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6391 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6392 return true;
6393
6394 // Make sure any conversions are pushed back into the call; this is
6395 // type safe since unordered compare builtins are declared as "_Bool
6396 // foo(...)".
6397 TheCall->setArg(0, OrigArg0.get());
6398 TheCall->setArg(1, OrigArg1.get());
6399
6400 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6401 return false;
6402
6403 // If the common type isn't a real floating type, then the arguments were
6404 // invalid for this operation.
6405 if (Res.isNull() || !Res->isRealFloatingType())
6406 return Diag(OrigArg0.get()->getBeginLoc(),
6407 diag::err_typecheck_call_invalid_ordered_compare)
6408 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6409 << SourceRange(OrigArg0.get()->getBeginLoc(),
6410 OrigArg1.get()->getEndLoc());
6411
6412 return false;
6413}
6414
6415bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6416 unsigned BuiltinID) {
6417 if (checkArgCount(TheCall, NumArgs))
6418 return true;
6419
6420 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6421 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6422 BuiltinID == Builtin::BI__builtin_isinf ||
6423 BuiltinID == Builtin::BI__builtin_isinf_sign))
6424 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6425 << 0 << 0 << TheCall->getSourceRange();
6426
6427 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6428 BuiltinID == Builtin::BI__builtin_isunordered))
6429 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6430 << 1 << 0 << TheCall->getSourceRange();
6431
6432 bool IsFPClass = NumArgs == 2;
6433
6434 // Find out position of floating-point argument.
6435 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6436
6437 // We can count on all parameters preceding the floating-point just being int.
6438 // Try all of those.
6439 for (unsigned i = 0; i < FPArgNo; ++i) {
6440 Expr *Arg = TheCall->getArg(i);
6441
6442 if (Arg->isTypeDependent())
6443 return false;
6444
6447
6448 if (Res.isInvalid())
6449 return true;
6450 TheCall->setArg(i, Res.get());
6451 }
6452
6453 Expr *OrigArg = TheCall->getArg(FPArgNo);
6454
6455 if (OrigArg->isTypeDependent())
6456 return false;
6457
6458 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6460 if (!Res.isUsable())
6461 return true;
6462 OrigArg = Res.get();
6463
6464 TheCall->setArg(FPArgNo, OrigArg);
6465
6466 QualType VectorResultTy;
6467 QualType ElementTy = OrigArg->getType();
6468 // TODO: When all classification function are implemented with is_fpclass,
6469 // vector argument can be supported in all of them.
6470 if (ElementTy->isVectorType() && IsFPClass) {
6471 VectorResultTy = GetSignedVectorType(ElementTy);
6472 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6473 }
6474
6475 // This operation requires a non-_Complex floating-point number.
6476 if (!ElementTy->isRealFloatingType())
6477 return Diag(OrigArg->getBeginLoc(),
6478 diag::err_typecheck_call_invalid_unary_fp)
6479 << OrigArg->getType() << OrigArg->getSourceRange();
6480
6481 // __builtin_isfpclass has integer parameter that specify test mask. It is
6482 // passed in (...), so it should be analyzed completely here.
6483 if (IsFPClass)
6484 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6485 return true;
6486
6487 // TODO: enable this code to all classification functions.
6488 if (IsFPClass) {
6489 QualType ResultTy;
6490 if (!VectorResultTy.isNull())
6491 ResultTy = VectorResultTy;
6492 else
6493 ResultTy = Context.IntTy;
6494 TheCall->setType(ResultTy);
6495 }
6496
6497 return false;
6498}
6499
6500bool Sema::BuiltinComplex(CallExpr *TheCall) {
6501 if (checkArgCount(TheCall, 2))
6502 return true;
6503
6504 bool Dependent = false;
6505 for (unsigned I = 0; I != 2; ++I) {
6506 Expr *Arg = TheCall->getArg(I);
6507 QualType T = Arg->getType();
6508 if (T->isDependentType()) {
6509 Dependent = true;
6510 continue;
6511 }
6512
6513 // Despite supporting _Complex int, GCC requires a real floating point type
6514 // for the operands of __builtin_complex.
6515 if (!T->isRealFloatingType()) {
6516 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6517 << Arg->getType() << Arg->getSourceRange();
6518 }
6519
6520 ExprResult Converted = DefaultLvalueConversion(Arg);
6521 if (Converted.isInvalid())
6522 return true;
6523 TheCall->setArg(I, Converted.get());
6524 }
6525
6526 if (Dependent) {
6527 TheCall->setType(Context.DependentTy);
6528 return false;
6529 }
6530
6531 Expr *Real = TheCall->getArg(0);
6532 Expr *Imag = TheCall->getArg(1);
6533 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6534 return Diag(Real->getBeginLoc(),
6535 diag::err_typecheck_call_different_arg_types)
6536 << Real->getType() << Imag->getType()
6537 << Real->getSourceRange() << Imag->getSourceRange();
6538 }
6539
6540 TheCall->setType(Context.getComplexType(Real->getType()));
6541 return false;
6542}
6543
6544/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6545// This is declared to take (...), so we have to check everything.
6547 unsigned NumArgs = TheCall->getNumArgs();
6548 if (NumArgs < 2)
6549 return ExprError(Diag(TheCall->getEndLoc(),
6550 diag::err_typecheck_call_too_few_args_at_least)
6551 << 0 /*function call*/ << 2 << NumArgs
6552 << /*is non object*/ 0 << TheCall->getSourceRange());
6553
6554 // Determine which of the following types of shufflevector we're checking:
6555 // 1) unary, vector mask: (lhs, mask)
6556 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6557 QualType ResType = TheCall->getArg(0)->getType();
6558 unsigned NumElements = 0;
6559
6560 if (!TheCall->getArg(0)->isTypeDependent() &&
6561 !TheCall->getArg(1)->isTypeDependent()) {
6562 QualType LHSType = TheCall->getArg(0)->getType();
6563 QualType RHSType = TheCall->getArg(1)->getType();
6564
6565 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6566 return ExprError(
6567 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6568 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6569 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6570 TheCall->getArg(1)->getEndLoc()));
6571
6572 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6573 unsigned NumResElements = NumArgs - 2;
6574
6575 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6576 // with mask. If so, verify that RHS is an integer vector type with the
6577 // same number of elts as lhs.
6578 if (NumArgs == 2) {
6579 if (!RHSType->hasIntegerRepresentation() ||
6580 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6581 return ExprError(Diag(TheCall->getBeginLoc(),
6582 diag::err_vec_builtin_incompatible_vector)
6583 << TheCall->getDirectCallee()
6584 << /*isMoreThanTwoArgs*/ false
6585 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6586 TheCall->getArg(1)->getEndLoc()));
6587 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6588 return ExprError(Diag(TheCall->getBeginLoc(),
6589 diag::err_vec_builtin_incompatible_vector)
6590 << TheCall->getDirectCallee()
6591 << /*isMoreThanTwoArgs*/ false
6592 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6593 TheCall->getArg(1)->getEndLoc()));
6594 } else if (NumElements != NumResElements) {
6595 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6596 ResType = ResType->isExtVectorType()
6597 ? Context.getExtVectorType(EltType, NumResElements)
6598 : Context.getVectorType(EltType, NumResElements,
6600 }
6601 }
6602
6603 for (unsigned I = 2; I != NumArgs; ++I) {
6604 Expr *Arg = TheCall->getArg(I);
6605 if (Arg->isTypeDependent() || Arg->isValueDependent())
6606 continue;
6607
6608 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6609 if (!Result)
6610 return ExprError(Diag(TheCall->getBeginLoc(),
6611 diag::err_shufflevector_nonconstant_argument)
6612 << Arg->getSourceRange());
6613
6614 // Allow -1 which will be translated to undef in the IR.
6615 if (Result->isSigned() && Result->isAllOnes())
6616 ;
6617 else if (Result->getActiveBits() > 64 ||
6618 Result->getZExtValue() >= NumElements * 2)
6619 return ExprError(Diag(TheCall->getBeginLoc(),
6620 diag::err_shufflevector_argument_too_large)
6621 << Arg->getSourceRange());
6622
6623 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6624 }
6625
6626 auto *Result = new (Context) ShuffleVectorExpr(
6627 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6628 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6629
6630 // All moved to Result.
6631 TheCall->shrinkNumArgs(0);
6632 return Result;
6633}
6634
6636 SourceLocation BuiltinLoc,
6637 SourceLocation RParenLoc) {
6640 QualType DstTy = TInfo->getType();
6641 QualType SrcTy = E->getType();
6642
6643 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6644 return ExprError(Diag(BuiltinLoc,
6645 diag::err_convertvector_non_vector)
6646 << E->getSourceRange());
6647 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6648 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6649 << "second"
6650 << "__builtin_convertvector");
6651
6652 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6653 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6654 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6655 if (SrcElts != DstElts)
6656 return ExprError(Diag(BuiltinLoc,
6657 diag::err_convertvector_incompatible_vector)
6658 << E->getSourceRange());
6659 }
6660
6661 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6662 RParenLoc, CurFPFeatureOverrides());
6663}
6664
6665bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6666 unsigned NumArgs = TheCall->getNumArgs();
6667
6668 if (NumArgs > 3)
6669 return Diag(TheCall->getEndLoc(),
6670 diag::err_typecheck_call_too_many_args_at_most)
6671 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6672 << TheCall->getSourceRange();
6673
6674 // Argument 0 is checked for us and the remaining arguments must be
6675 // constant integers.
6676 for (unsigned i = 1; i != NumArgs; ++i)
6677 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6678 return true;
6679
6680 return false;
6681}
6682
6683bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6684 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6685 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6686 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6687 if (checkArgCount(TheCall, 1))
6688 return true;
6689 Expr *Arg = TheCall->getArg(0);
6690 if (Arg->isInstantiationDependent())
6691 return false;
6692
6693 QualType ArgTy = Arg->getType();
6694 if (!ArgTy->hasFloatingRepresentation())
6695 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6696 << ArgTy;
6697 if (Arg->isLValue()) {
6698 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6699 TheCall->setArg(0, FirstArg.get());
6700 }
6701 TheCall->setType(TheCall->getArg(0)->getType());
6702 return false;
6703}
6704
6705bool Sema::BuiltinAssume(CallExpr *TheCall) {
6706 Expr *Arg = TheCall->getArg(0);
6707 if (Arg->isInstantiationDependent()) return false;
6708
6709 if (Arg->HasSideEffects(Context))
6710 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6711 << Arg->getSourceRange()
6712 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6713
6714 return false;
6715}
6716
6717bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6718 // The alignment must be a constant integer.
6719 Expr *Arg = TheCall->getArg(1);
6720
6721 // We can't check the value of a dependent argument.
6722 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6723 if (const auto *UE =
6724 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6725 if (UE->getKind() == UETT_AlignOf ||
6726 UE->getKind() == UETT_PreferredAlignOf)
6727 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6728 << Arg->getSourceRange();
6729
6730 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6731
6732 if (!Result.isPowerOf2())
6733 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6734 << Arg->getSourceRange();
6735
6736 if (Result < Context.getCharWidth())
6737 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6738 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6739
6740 if (Result > std::numeric_limits<int32_t>::max())
6741 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6742 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6743 }
6744
6745 return false;
6746}
6747
6748bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6749 if (checkArgCountRange(TheCall, 2, 3))
6750 return true;
6751
6752 unsigned NumArgs = TheCall->getNumArgs();
6753 Expr *FirstArg = TheCall->getArg(0);
6754
6755 {
6756 ExprResult FirstArgResult =
6758 if (!FirstArgResult.get()->getType()->isPointerType()) {
6759 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6760 << TheCall->getSourceRange();
6761 return true;
6762 }
6763 TheCall->setArg(0, FirstArgResult.get());
6764 }
6765
6766 // The alignment must be a constant integer.
6767 Expr *SecondArg = TheCall->getArg(1);
6768
6769 // We can't check the value of a dependent argument.
6770 if (!SecondArg->isValueDependent()) {
6771 llvm::APSInt Result;
6772 if (BuiltinConstantArg(TheCall, 1, Result))
6773 return true;
6774
6775 if (!Result.isPowerOf2())
6776 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6777 << SecondArg->getSourceRange();
6778
6780 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6781 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6782
6783 TheCall->setArg(1,
6785 }
6786
6787 if (NumArgs > 2) {
6788 Expr *ThirdArg = TheCall->getArg(2);
6789 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6790 return true;
6791 TheCall->setArg(2, ThirdArg);
6792 }
6793
6794 return false;
6795}
6796
6797bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6798 unsigned BuiltinID =
6799 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6800 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6801
6802 unsigned NumArgs = TheCall->getNumArgs();
6803 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6804 if (NumArgs < NumRequiredArgs) {
6805 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6806 << 0 /* function call */ << NumRequiredArgs << NumArgs
6807 << /*is non object*/ 0 << TheCall->getSourceRange();
6808 }
6809 if (NumArgs >= NumRequiredArgs + 0x100) {
6810 return Diag(TheCall->getEndLoc(),
6811 diag::err_typecheck_call_too_many_args_at_most)
6812 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6813 << /*is non object*/ 0 << TheCall->getSourceRange();
6814 }
6815 unsigned i = 0;
6816
6817 // For formatting call, check buffer arg.
6818 if (!IsSizeCall) {
6819 ExprResult Arg(TheCall->getArg(i));
6820 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6821 Context, Context.VoidPtrTy, false);
6822 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6823 if (Arg.isInvalid())
6824 return true;
6825 TheCall->setArg(i, Arg.get());
6826 i++;
6827 }
6828
6829 // Check string literal arg.
6830 unsigned FormatIdx = i;
6831 {
6832 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6833 if (Arg.isInvalid())
6834 return true;
6835 TheCall->setArg(i, Arg.get());
6836 i++;
6837 }
6838
6839 // Make sure variadic args are scalar.
6840 unsigned FirstDataArg = i;
6841 while (i < NumArgs) {
6843 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6844 if (Arg.isInvalid())
6845 return true;
6846 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6847 if (ArgSize.getQuantity() >= 0x100) {
6848 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6849 << i << (int)ArgSize.getQuantity() << 0xff
6850 << TheCall->getSourceRange();
6851 }
6852 TheCall->setArg(i, Arg.get());
6853 i++;
6854 }
6855
6856 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6857 // call to avoid duplicate diagnostics.
6858 if (!IsSizeCall) {
6859 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6860 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6861 bool Success = CheckFormatArguments(
6862 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6864 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6865 if (!Success)
6866 return true;
6867 }
6868
6869 if (IsSizeCall) {
6870 TheCall->setType(Context.getSizeType());
6871 } else {
6872 TheCall->setType(Context.VoidPtrTy);
6873 }
6874 return false;
6875}
6876
6877bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6878 llvm::APSInt &Result) {
6879 Expr *Arg = TheCall->getArg(ArgNum);
6880
6881 if (Arg->isTypeDependent() || Arg->isValueDependent())
6882 return false;
6883
6884 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6885 if (!R) {
6886 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6887 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6888 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6889 << FDecl->getDeclName() << Arg->getSourceRange();
6890 }
6891 Result = *R;
6892
6893 return false;
6894}
6895
6896bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6897 int High, bool RangeIsError) {
6899 return false;
6900 llvm::APSInt Result;
6901
6902 // We can't check the value of a dependent argument.
6903 Expr *Arg = TheCall->getArg(ArgNum);
6904 if (Arg->isTypeDependent() || Arg->isValueDependent())
6905 return false;
6906
6907 // Check constant-ness first.
6908 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6909 return true;
6910
6911 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6912 if (RangeIsError)
6913 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6914 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6915 else
6916 // Defer the warning until we know if the code will be emitted so that
6917 // dead code can ignore this.
6918 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6919 PDiag(diag::warn_argument_invalid_range)
6920 << toString(Result, 10) << Low << High
6921 << Arg->getSourceRange());
6922 }
6923
6924 return false;
6925}
6926
6927bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6928 unsigned Num) {
6929 llvm::APSInt Result;
6930
6931 // We can't check the value of a dependent argument.
6932 Expr *Arg = TheCall->getArg(ArgNum);
6933 if (Arg->isTypeDependent() || Arg->isValueDependent())
6934 return false;
6935
6936 // Check constant-ness first.
6937 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6938 return true;
6939
6940 if (Result.getSExtValue() % Num != 0)
6941 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6942 << Num << Arg->getSourceRange();
6943
6944 return false;
6945}
6946
6947bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6948 llvm::APSInt Result;
6949
6950 // We can't check the value of a dependent argument.
6951 Expr *Arg = TheCall->getArg(ArgNum);
6952 if (Arg->isTypeDependent() || Arg->isValueDependent())
6953 return false;
6954
6955 // Check constant-ness first.
6956 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6957 return true;
6958
6959 if (Result.isPowerOf2())
6960 return false;
6961
6962 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6963 << Arg->getSourceRange();
6964}
6965
6966static bool IsShiftedByte(llvm::APSInt Value) {
6967 if (Value.isNegative())
6968 return false;
6969
6970 // Check if it's a shifted byte, by shifting it down
6971 while (true) {
6972 // If the value fits in the bottom byte, the check passes.
6973 if (Value < 0x100)
6974 return true;
6975
6976 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6977 // fails.
6978 if ((Value & 0xFF) != 0)
6979 return false;
6980
6981 // If the bottom 8 bits are all 0, but something above that is nonzero,
6982 // then shifting the value right by 8 bits won't affect whether it's a
6983 // shifted byte or not. So do that, and go round again.
6984 Value >>= 8;
6985 }
6986}
6987
6988bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6989 unsigned ArgBits) {
6990 llvm::APSInt Result;
6991
6992 // We can't check the value of a dependent argument.
6993 Expr *Arg = TheCall->getArg(ArgNum);
6994 if (Arg->isTypeDependent() || Arg->isValueDependent())
6995 return false;
6996
6997 // Check constant-ness first.
6998 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6999 return true;
7000
7001 // Truncate to the given size.
7002 Result = Result.getLoBits(ArgBits);
7003 Result.setIsUnsigned(true);
7004
7005 if (IsShiftedByte(Result))
7006 return false;
7007
7008 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7009 << Arg->getSourceRange();
7010}
7011
7013 unsigned ArgNum,
7014 unsigned ArgBits) {
7015 llvm::APSInt Result;
7016
7017 // We can't check the value of a dependent argument.
7018 Expr *Arg = TheCall->getArg(ArgNum);
7019 if (Arg->isTypeDependent() || Arg->isValueDependent())
7020 return false;
7021
7022 // Check constant-ness first.
7023 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7024 return true;
7025
7026 // Truncate to the given size.
7027 Result = Result.getLoBits(ArgBits);
7028 Result.setIsUnsigned(true);
7029
7030 // Check to see if it's in either of the required forms.
7031 if (IsShiftedByte(Result) ||
7032 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7033 return false;
7034
7035 return Diag(TheCall->getBeginLoc(),
7036 diag::err_argument_not_shifted_byte_or_xxff)
7037 << Arg->getSourceRange();
7038}
7039
7040bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7041 if (!Context.getTargetInfo().hasSjLjLowering())
7042 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7043 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7044
7045 Expr *Arg = TheCall->getArg(1);
7046 llvm::APSInt Result;
7047
7048 // TODO: This is less than ideal. Overload this to take a value.
7049 if (BuiltinConstantArg(TheCall, 1, Result))
7050 return true;
7051
7052 if (Result != 1)
7053 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7054 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7055
7056 return false;
7057}
7058
7059bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7060 if (!Context.getTargetInfo().hasSjLjLowering())
7061 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7062 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7063 return false;
7064}
7065
7066bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7067 if (checkArgCount(TheCall, 1))
7068 return true;
7069
7070 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
7071 if (ArgRes.isInvalid())
7072 return true;
7073
7074 // For simplicity, we support only limited expressions for the argument.
7075 // Specifically a flexible array member or a pointer with counted_by:
7076 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7077 // complex casting, which really shouldn't be a huge problem.
7078 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7079 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7080 return Diag(Arg->getBeginLoc(),
7081 diag::err_builtin_counted_by_ref_invalid_arg)
7082 << Arg->getSourceRange();
7083
7084 if (Arg->HasSideEffects(Context))
7085 return Diag(Arg->getBeginLoc(),
7086 diag::err_builtin_counted_by_ref_has_side_effects)
7087 << Arg->getSourceRange();
7088
7089 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7090 const auto *CATy =
7091 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7092
7093 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7094 // Member has counted_by attribute - return pointer to count field
7095 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
7096 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7097 TheCall->setType(Context.getPointerType(CountFD->getType()));
7098 return false;
7099 }
7100 }
7101
7102 // FAMs and pointers without counted_by return void*
7103 QualType MemberTy = ME->getMemberDecl()->getType();
7104 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7105 return Diag(Arg->getBeginLoc(),
7106 diag::err_builtin_counted_by_ref_invalid_arg)
7107 << Arg->getSourceRange();
7108 } else {
7109 return Diag(Arg->getBeginLoc(),
7110 diag::err_builtin_counted_by_ref_invalid_arg)
7111 << Arg->getSourceRange();
7112 }
7113
7114 TheCall->setType(Context.getPointerType(Context.VoidTy));
7115 return false;
7116}
7117
7118/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7119/// It allows leaking and modification of bounds safety information.
7120bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7122 const CallExpr *CE =
7123 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7124 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7125 return false;
7126
7127 switch (K) {
7130 Diag(E->getExprLoc(),
7131 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7132 << 0 << E->getSourceRange();
7133 break;
7135 Diag(E->getExprLoc(),
7136 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7137 << 1 << E->getSourceRange();
7138 break;
7140 Diag(E->getExprLoc(),
7141 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7142 << 2 << E->getSourceRange();
7143 break;
7145 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7146 << 0 << E->getSourceRange();
7147 break;
7149 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7150 << 1 << E->getSourceRange();
7151 break;
7152 }
7153
7154 return true;
7155}
7156
7157namespace {
7158
7159class UncoveredArgHandler {
7160 enum { Unknown = -1, AllCovered = -2 };
7161
7162 signed FirstUncoveredArg = Unknown;
7163 SmallVector<const Expr *, 4> DiagnosticExprs;
7164
7165public:
7166 UncoveredArgHandler() = default;
7167
7168 bool hasUncoveredArg() const {
7169 return (FirstUncoveredArg >= 0);
7170 }
7171
7172 unsigned getUncoveredArg() const {
7173 assert(hasUncoveredArg() && "no uncovered argument");
7174 return FirstUncoveredArg;
7175 }
7176
7177 void setAllCovered() {
7178 // A string has been found with all arguments covered, so clear out
7179 // the diagnostics.
7180 DiagnosticExprs.clear();
7181 FirstUncoveredArg = AllCovered;
7182 }
7183
7184 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7185 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7186
7187 // Don't update if a previous string covers all arguments.
7188 if (FirstUncoveredArg == AllCovered)
7189 return;
7190
7191 // UncoveredArgHandler tracks the highest uncovered argument index
7192 // and with it all the strings that match this index.
7193 if (NewFirstUncoveredArg == FirstUncoveredArg)
7194 DiagnosticExprs.push_back(StrExpr);
7195 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7196 DiagnosticExprs.clear();
7197 DiagnosticExprs.push_back(StrExpr);
7198 FirstUncoveredArg = NewFirstUncoveredArg;
7199 }
7200 }
7201
7202 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7203};
7204
7205enum StringLiteralCheckType {
7206 SLCT_NotALiteral,
7207 SLCT_UncheckedLiteral,
7208 SLCT_CheckedLiteral
7209};
7210
7211} // namespace
7212
7213static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7214 BinaryOperatorKind BinOpKind,
7215 bool AddendIsRight) {
7216 unsigned BitWidth = Offset.getBitWidth();
7217 unsigned AddendBitWidth = Addend.getBitWidth();
7218 // There might be negative interim results.
7219 if (Addend.isUnsigned()) {
7220 Addend = Addend.zext(++AddendBitWidth);
7221 Addend.setIsSigned(true);
7222 }
7223 // Adjust the bit width of the APSInts.
7224 if (AddendBitWidth > BitWidth) {
7225 Offset = Offset.sext(AddendBitWidth);
7226 BitWidth = AddendBitWidth;
7227 } else if (BitWidth > AddendBitWidth) {
7228 Addend = Addend.sext(BitWidth);
7229 }
7230
7231 bool Ov = false;
7232 llvm::APSInt ResOffset = Offset;
7233 if (BinOpKind == BO_Add)
7234 ResOffset = Offset.sadd_ov(Addend, Ov);
7235 else {
7236 assert(AddendIsRight && BinOpKind == BO_Sub &&
7237 "operator must be add or sub with addend on the right");
7238 ResOffset = Offset.ssub_ov(Addend, Ov);
7239 }
7240
7241 // We add an offset to a pointer here so we should support an offset as big as
7242 // possible.
7243 if (Ov) {
7244 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7245 "index (intermediate) result too big");
7246 Offset = Offset.sext(2 * BitWidth);
7247 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7248 return;
7249 }
7250
7251 Offset = std::move(ResOffset);
7252}
7253
7254namespace {
7255
7256// This is a wrapper class around StringLiteral to support offsetted string
7257// literals as format strings. It takes the offset into account when returning
7258// the string and its length or the source locations to display notes correctly.
7259class FormatStringLiteral {
7260 const StringLiteral *FExpr;
7261 int64_t Offset;
7262
7263public:
7264 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7265 : FExpr(fexpr), Offset(Offset) {}
7266
7267 const StringLiteral *getFormatString() const { return FExpr; }
7268
7269 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7270
7271 unsigned getByteLength() const {
7272 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7273 }
7274
7275 unsigned getLength() const { return FExpr->getLength() - Offset; }
7276 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7277
7278 StringLiteralKind getKind() const { return FExpr->getKind(); }
7279
7280 QualType getType() const { return FExpr->getType(); }
7281
7282 bool isAscii() const { return FExpr->isOrdinary(); }
7283 bool isWide() const { return FExpr->isWide(); }
7284 bool isUTF8() const { return FExpr->isUTF8(); }
7285 bool isUTF16() const { return FExpr->isUTF16(); }
7286 bool isUTF32() const { return FExpr->isUTF32(); }
7287 bool isPascal() const { return FExpr->isPascal(); }
7288
7289 SourceLocation getLocationOfByte(
7290 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7291 const TargetInfo &Target, unsigned *StartToken = nullptr,
7292 unsigned *StartTokenByteOffset = nullptr) const {
7293 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7294 StartToken, StartTokenByteOffset);
7295 }
7296
7297 SourceLocation getBeginLoc() const LLVM_READONLY {
7298 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7299 }
7300
7301 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7302};
7303
7304} // namespace
7305
7306static void CheckFormatString(
7307 Sema &S, const FormatStringLiteral *FExpr,
7308 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7310 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7311 bool inFunctionCall, VariadicCallType CallType,
7312 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7313 bool IgnoreStringsWithoutSpecifiers);
7314
7315static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7316 const Expr *E);
7317
7318// Determine if an expression is a string literal or constant string.
7319// If this function returns false on the arguments to a function expecting a
7320// format string, we will usually need to emit a warning.
7321// True string literals are then checked by CheckFormatString.
7322static StringLiteralCheckType
7323checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7324 const Expr *E, ArrayRef<const Expr *> Args,
7325 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7326 unsigned firstDataArg, FormatStringType Type,
7327 VariadicCallType CallType, bool InFunctionCall,
7328 llvm::SmallBitVector &CheckedVarArgs,
7329 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7330 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7331 bool IgnoreStringsWithoutSpecifiers = false) {
7333 return SLCT_NotALiteral;
7334tryAgain:
7335 assert(Offset.isSigned() && "invalid offset");
7336
7337 if (E->isTypeDependent() || E->isValueDependent())
7338 return SLCT_NotALiteral;
7339
7340 E = E->IgnoreParenCasts();
7341
7343 // Technically -Wformat-nonliteral does not warn about this case.
7344 // The behavior of printf and friends in this case is implementation
7345 // dependent. Ideally if the format string cannot be null then
7346 // it should have a 'nonnull' attribute in the function prototype.
7347 return SLCT_UncheckedLiteral;
7348
7349 switch (E->getStmtClass()) {
7350 case Stmt::InitListExprClass:
7351 // Handle expressions like {"foobar"}.
7352 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7353 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7354 format_idx, firstDataArg, Type, CallType,
7355 /*InFunctionCall*/ false, CheckedVarArgs,
7356 UncoveredArg, Offset, CallerFormatParamIdx,
7357 IgnoreStringsWithoutSpecifiers);
7358 }
7359 return SLCT_NotALiteral;
7360 case Stmt::BinaryConditionalOperatorClass:
7361 case Stmt::ConditionalOperatorClass: {
7362 // The expression is a literal if both sub-expressions were, and it was
7363 // completely checked only if both sub-expressions were checked.
7366
7367 // Determine whether it is necessary to check both sub-expressions, for
7368 // example, because the condition expression is a constant that can be
7369 // evaluated at compile time.
7370 bool CheckLeft = true, CheckRight = true;
7371
7372 bool Cond;
7373 if (C->getCond()->EvaluateAsBooleanCondition(
7375 if (Cond)
7376 CheckRight = false;
7377 else
7378 CheckLeft = false;
7379 }
7380
7381 // We need to maintain the offsets for the right and the left hand side
7382 // separately to check if every possible indexed expression is a valid
7383 // string literal. They might have different offsets for different string
7384 // literals in the end.
7385 StringLiteralCheckType Left;
7386 if (!CheckLeft)
7387 Left = SLCT_UncheckedLiteral;
7388 else {
7389 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7390 Args, APK, format_idx, firstDataArg, Type,
7391 CallType, InFunctionCall, CheckedVarArgs,
7392 UncoveredArg, Offset, CallerFormatParamIdx,
7393 IgnoreStringsWithoutSpecifiers);
7394 if (Left == SLCT_NotALiteral || !CheckRight) {
7395 return Left;
7396 }
7397 }
7398
7399 StringLiteralCheckType Right = checkFormatStringExpr(
7400 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7401 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7402 UncoveredArg, Offset, CallerFormatParamIdx,
7403 IgnoreStringsWithoutSpecifiers);
7404
7405 return (CheckLeft && Left < Right) ? Left : Right;
7406 }
7407
7408 case Stmt::ImplicitCastExprClass:
7409 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7410 goto tryAgain;
7411
7412 case Stmt::OpaqueValueExprClass:
7413 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7414 E = src;
7415 goto tryAgain;
7416 }
7417 return SLCT_NotALiteral;
7418
7419 case Stmt::PredefinedExprClass:
7420 // While __func__, etc., are technically not string literals, they
7421 // cannot contain format specifiers and thus are not a security
7422 // liability.
7423 return SLCT_UncheckedLiteral;
7424
7425 case Stmt::DeclRefExprClass: {
7426 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7427
7428 // As an exception, do not flag errors for variables binding to
7429 // const string literals.
7430 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7431 bool isConstant = false;
7432 QualType T = DR->getType();
7433
7434 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7435 isConstant = AT->getElementType().isConstant(S.Context);
7436 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7437 isConstant = T.isConstant(S.Context) &&
7438 PT->getPointeeType().isConstant(S.Context);
7439 } else if (T->isObjCObjectPointerType()) {
7440 // In ObjC, there is usually no "const ObjectPointer" type,
7441 // so don't check if the pointee type is constant.
7442 isConstant = T.isConstant(S.Context);
7443 }
7444
7445 if (isConstant) {
7446 if (const Expr *Init = VD->getAnyInitializer()) {
7447 // Look through initializers like const char c[] = { "foo" }
7448 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7449 if (InitList->isStringLiteralInit())
7450 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7451 }
7452 return checkFormatStringExpr(
7453 S, ReferenceFormatString, Init, Args, APK, format_idx,
7454 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7455 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7456 }
7457 }
7458
7459 // When the format argument is an argument of this function, and this
7460 // function also has the format attribute, there are several interactions
7461 // for which there shouldn't be a warning. For instance, when calling
7462 // v*printf from a function that has the printf format attribute, we
7463 // should not emit a warning about using `fmt`, even though it's not
7464 // constant, because the arguments have already been checked for the
7465 // caller of `logmessage`:
7466 //
7467 // __attribute__((format(printf, 1, 2)))
7468 // void logmessage(char const *fmt, ...) {
7469 // va_list ap;
7470 // va_start(ap, fmt);
7471 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7472 // ...
7473 // }
7474 //
7475 // Another interaction that we need to support is using a format string
7476 // specified by the format_matches attribute:
7477 //
7478 // __attribute__((format_matches(printf, 1, "%s %d")))
7479 // void logmessage(char const *fmt, const char *a, int b) {
7480 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7481 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7482 // ...
7483 // }
7484 //
7485 // Yet another interaction that we need to support is calling a variadic
7486 // format function from a format function that has fixed arguments. For
7487 // instance:
7488 //
7489 // __attribute__((format(printf, 1, 2)))
7490 // void logstring(char const *fmt, char const *str) {
7491 // printf(fmt, str); /* do not emit a warning about "fmt" */
7492 // }
7493 //
7494 // Same (and perhaps more relatably) for the variadic template case:
7495 //
7496 // template<typename... Args>
7497 // __attribute__((format(printf, 1, 2)))
7498 // void log(const char *fmt, Args&&... args) {
7499 // printf(fmt, forward<Args>(args)...);
7500 // /* do not emit a warning about "fmt" */
7501 // }
7502 //
7503 // Due to implementation difficulty, we only check the format, not the
7504 // format arguments, in all cases.
7505 //
7506 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7507 if (CallerFormatParamIdx)
7508 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7509 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7510 for (const auto *PVFormatMatches :
7511 D->specific_attrs<FormatMatchesAttr>()) {
7512 Sema::FormatStringInfo CalleeFSI;
7513 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7514 0, &CalleeFSI))
7515 continue;
7516 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7517 // If using the wrong type of format string, emit a diagnostic
7518 // here and stop checking to avoid irrelevant diagnostics.
7519 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7520 S.Diag(Args[format_idx]->getBeginLoc(),
7521 diag::warn_format_string_type_incompatible)
7522 << PVFormatMatches->getType()->getName()
7524 if (!InFunctionCall) {
7525 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7526 diag::note_format_string_defined);
7527 }
7528 return SLCT_UncheckedLiteral;
7529 }
7530 return checkFormatStringExpr(
7531 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7532 Args, APK, format_idx, firstDataArg, Type, CallType,
7533 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7534 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7535 }
7536 }
7537
7538 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7539 Sema::FormatStringInfo CallerFSI;
7540 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7541 PVFormat->getFirstArg(), &CallerFSI))
7542 continue;
7543 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7544 // We also check if the formats are compatible.
7545 // We can't pass a 'scanf' string to a 'printf' function.
7546 if (Type != S.GetFormatStringType(PVFormat)) {
7547 S.Diag(Args[format_idx]->getBeginLoc(),
7548 diag::warn_format_string_type_incompatible)
7549 << PVFormat->getType()->getName()
7551 if (!InFunctionCall) {
7552 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7553 }
7554 return SLCT_UncheckedLiteral;
7555 }
7556 // Lastly, check that argument passing kinds transition in a
7557 // way that makes sense:
7558 // from a caller with FAPK_VAList, allow FAPK_VAList
7559 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7560 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7561 // from a caller with FAPK_Variadic, allow FAPK_VAList
7562 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7567 return SLCT_UncheckedLiteral;
7568 }
7569 }
7570 }
7571 }
7572 }
7573 }
7574
7575 return SLCT_NotALiteral;
7576 }
7577
7578 case Stmt::CallExprClass:
7579 case Stmt::CXXMemberCallExprClass: {
7580 const CallExpr *CE = cast<CallExpr>(E);
7581 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7582 bool IsFirst = true;
7583 StringLiteralCheckType CommonResult;
7584 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7585 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7586 StringLiteralCheckType Result = checkFormatStringExpr(
7587 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7588 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7589 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7590 if (IsFirst) {
7591 CommonResult = Result;
7592 IsFirst = false;
7593 }
7594 }
7595 if (!IsFirst)
7596 return CommonResult;
7597
7598 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7599 unsigned BuiltinID = FD->getBuiltinID();
7600 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7601 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7602 const Expr *Arg = CE->getArg(0);
7603 return checkFormatStringExpr(
7604 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7605 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7606 UncoveredArg, Offset, CallerFormatParamIdx,
7607 IgnoreStringsWithoutSpecifiers);
7608 }
7609 }
7610 }
7611 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7612 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7613 format_idx, firstDataArg, Type, CallType,
7614 /*InFunctionCall*/ false, CheckedVarArgs,
7615 UncoveredArg, Offset, CallerFormatParamIdx,
7616 IgnoreStringsWithoutSpecifiers);
7617 return SLCT_NotALiteral;
7618 }
7619 case Stmt::ObjCMessageExprClass: {
7620 const auto *ME = cast<ObjCMessageExpr>(E);
7621 if (const auto *MD = ME->getMethodDecl()) {
7622 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7623 // As a special case heuristic, if we're using the method -[NSBundle
7624 // localizedStringForKey:value:table:], ignore any key strings that lack
7625 // format specifiers. The idea is that if the key doesn't have any
7626 // format specifiers then its probably just a key to map to the
7627 // localized strings. If it does have format specifiers though, then its
7628 // likely that the text of the key is the format string in the
7629 // programmer's language, and should be checked.
7630 const ObjCInterfaceDecl *IFace;
7631 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7632 IFace->getIdentifier()->isStr("NSBundle") &&
7633 MD->getSelector().isKeywordSelector(
7634 {"localizedStringForKey", "value", "table"})) {
7635 IgnoreStringsWithoutSpecifiers = true;
7636 }
7637
7638 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7639 return checkFormatStringExpr(
7640 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7641 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7642 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7643 }
7644 }
7645
7646 return SLCT_NotALiteral;
7647 }
7648 case Stmt::ObjCStringLiteralClass:
7649 case Stmt::StringLiteralClass: {
7650 const StringLiteral *StrE = nullptr;
7651
7652 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7653 StrE = ObjCFExpr->getString();
7654 else
7655 StrE = cast<StringLiteral>(E);
7656
7657 if (StrE) {
7658 if (Offset.isNegative() || Offset > StrE->getLength()) {
7659 // TODO: It would be better to have an explicit warning for out of
7660 // bounds literals.
7661 return SLCT_NotALiteral;
7662 }
7663 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7664 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7665 format_idx, firstDataArg, Type, InFunctionCall,
7666 CallType, CheckedVarArgs, UncoveredArg,
7667 IgnoreStringsWithoutSpecifiers);
7668 return SLCT_CheckedLiteral;
7669 }
7670
7671 return SLCT_NotALiteral;
7672 }
7673 case Stmt::BinaryOperatorClass: {
7674 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7675
7676 // A string literal + an int offset is still a string literal.
7677 if (BinOp->isAdditiveOp()) {
7678 Expr::EvalResult LResult, RResult;
7679
7680 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7681 LResult, S.Context, Expr::SE_NoSideEffects,
7683 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7684 RResult, S.Context, Expr::SE_NoSideEffects,
7686
7687 if (LIsInt != RIsInt) {
7688 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7689
7690 if (LIsInt) {
7691 if (BinOpKind == BO_Add) {
7692 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7693 E = BinOp->getRHS();
7694 goto tryAgain;
7695 }
7696 } else {
7697 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7698 E = BinOp->getLHS();
7699 goto tryAgain;
7700 }
7701 }
7702 }
7703
7704 return SLCT_NotALiteral;
7705 }
7706 case Stmt::UnaryOperatorClass: {
7707 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7708 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7709 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7710 Expr::EvalResult IndexResult;
7711 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7714 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7715 /*RHS is int*/ true);
7716 E = ASE->getBase();
7717 goto tryAgain;
7718 }
7719 }
7720
7721 return SLCT_NotALiteral;
7722 }
7723
7724 default:
7725 return SLCT_NotALiteral;
7726 }
7727}
7728
7729// If this expression can be evaluated at compile-time,
7730// check if the result is a StringLiteral and return it
7731// otherwise return nullptr
7733 const Expr *E) {
7735 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7736 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7737 if (isa_and_nonnull<StringLiteral>(LVE))
7738 return LVE;
7739 }
7740 return nullptr;
7741}
7742
7744 switch (FST) {
7746 return "scanf";
7748 return "printf";
7750 return "NSString";
7752 return "strftime";
7754 return "strfmon";
7756 return "kprintf";
7758 return "freebsd_kprintf";
7760 return "os_log";
7761 default:
7762 return "<unknown>";
7763 }
7764}
7765
7767 return llvm::StringSwitch<FormatStringType>(Flavor)
7768 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7769 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7771 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7772 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7773 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7774 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7776 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7777 .Case("os_trace", FormatStringType::OSLog)
7778 .Case("os_log", FormatStringType::OSLog)
7779 .Default(FormatStringType::Unknown);
7780}
7781
7783 return GetFormatStringType(Format->getType()->getName());
7784}
7785
7786FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7787 return GetFormatStringType(Format->getType()->getName());
7788}
7789
7790bool Sema::CheckFormatArguments(const FormatAttr *Format,
7791 ArrayRef<const Expr *> Args, bool IsCXXMember,
7792 VariadicCallType CallType, SourceLocation Loc,
7793 SourceRange Range,
7794 llvm::SmallBitVector &CheckedVarArgs) {
7795 FormatStringInfo FSI;
7796 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7797 IsCXXMember,
7798 CallType != VariadicCallType::DoesNotApply, &FSI))
7799 return CheckFormatArguments(
7800 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7801 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7802 return false;
7803}
7804
7805bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7806 ArrayRef<const Expr *> Args, bool IsCXXMember,
7807 VariadicCallType CallType, SourceLocation Loc,
7808 SourceRange Range,
7809 llvm::SmallBitVector &CheckedVarArgs) {
7810 FormatStringInfo FSI;
7811 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7812 &FSI)) {
7813 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7814 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7815 Format->getFormatString(), FSI.FormatIdx,
7816 FSI.FirstDataArg, GetFormatStringType(Format),
7817 CallType, Loc, Range, CheckedVarArgs);
7818 }
7819 return false;
7820}
7821
7824 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7825 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7826 SourceLocation Loc) {
7827 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7828 return false;
7829
7830 DeclContext *DC = S->CurContext;
7831 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7832 return false;
7833 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7834
7835 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7836
7837 // Find the offset to convert between attribute and parameter indexes.
7838 unsigned CallerArgumentIndexOffset =
7839 hasImplicitObjectParameter(Caller) ? 2 : 1;
7840
7841 unsigned FirstArgumentIndex = -1;
7842 switch (APK) {
7845 // As an extension, clang allows the format attribute on non-variadic
7846 // functions.
7847 // Caller must have fixed arguments to pass them to a fixed or variadic
7848 // function. Try to match caller and callee arguments. If successful, then
7849 // emit a diag with the caller idx, otherwise we can't determine the callee
7850 // arguments.
7851 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7852 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7853 // There aren't enough arguments in the caller to pass to callee.
7854 return false;
7855 }
7856 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7857 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7858 const auto *Arg =
7859 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7860 if (!Arg)
7861 return false;
7862 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7863 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7864 return false;
7865 }
7866 FirstArgumentIndex =
7867 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7868 break;
7869 }
7871 // Caller arguments are either variadic or a va_list.
7872 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7873 ? (NumCallerParams + CallerArgumentIndexOffset)
7874 : 0;
7875 break;
7877 // The callee has a format_matches attribute. We will emit that instead.
7878 if (!ReferenceFormatString)
7879 return false;
7880 break;
7881 }
7882
7883 // Emit the diagnostic and fixit.
7884 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7885 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7886 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7887 do {
7888 std::string Attr, Fixit;
7889 llvm::raw_string_ostream AttrOS(Attr);
7891 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7892 << FirstArgumentIndex << ")";
7893 } else {
7894 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7895 << ", \"";
7896 AttrOS.write_escaped(ReferenceFormatString->getString());
7897 AttrOS << "\")";
7898 }
7899 AttrOS.flush();
7900 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7901 if (ND)
7902 DB << ND;
7903 else
7904 DB << "block";
7905
7906 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7907 if (isa<BlockDecl>(Caller))
7908 break;
7909
7910 SourceLocation SL;
7911 llvm::raw_string_ostream IS(Fixit);
7912 // The attribute goes at the start of the declaration in C/C++ functions
7913 // and methods, but after the declaration for Objective-C methods.
7914 if (isa<ObjCMethodDecl>(Caller)) {
7915 IS << ' ';
7916 SL = Caller->getEndLoc();
7917 }
7918 const LangOptions &LO = S->getLangOpts();
7919 if (LO.C23 || LO.CPlusPlus11)
7920 IS << "[[gnu::" << Attr << "]]";
7921 else if (LO.ObjC || LO.GNUMode)
7922 IS << "__attribute__((" << Attr << "))";
7923 else
7924 break;
7925 if (!isa<ObjCMethodDecl>(Caller)) {
7926 IS << ' ';
7927 SL = Caller->getBeginLoc();
7928 }
7929 IS.flush();
7930
7931 DB << FixItHint::CreateInsertion(SL, Fixit);
7932 } while (false);
7933
7934 // Add implicit format or format_matches attribute.
7936 Caller->addAttr(FormatAttr::CreateImplicit(
7937 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7938 FormatStringIndex, FirstArgumentIndex));
7939 } else {
7940 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7941 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7942 FormatStringIndex, ReferenceFormatString));
7943 }
7944
7945 {
7946 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7947 if (ND)
7948 DB << ND;
7949 else
7950 DB << "block";
7951 }
7952 return true;
7953}
7954
7955bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7957 StringLiteral *ReferenceFormatString,
7958 unsigned format_idx, unsigned firstDataArg,
7960 VariadicCallType CallType, SourceLocation Loc,
7961 SourceRange Range,
7962 llvm::SmallBitVector &CheckedVarArgs) {
7963 // CHECK: printf/scanf-like function is called with no format string.
7964 if (format_idx >= Args.size()) {
7965 Diag(Loc, diag::warn_missing_format_string) << Range;
7966 return false;
7967 }
7968
7969 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7970
7971 // CHECK: format string is not a string literal.
7972 //
7973 // Dynamically generated format strings are difficult to
7974 // automatically vet at compile time. Requiring that format strings
7975 // are string literals: (1) permits the checking of format strings by
7976 // the compiler and thereby (2) can practically remove the source of
7977 // many format string exploits.
7978
7979 // Format string can be either ObjC string (e.g. @"%d") or
7980 // C string (e.g. "%d")
7981 // ObjC string uses the same format specifiers as C string, so we can use
7982 // the same format string checking logic for both ObjC and C strings.
7983 UncoveredArgHandler UncoveredArg;
7984 std::optional<unsigned> CallerParamIdx;
7985 StringLiteralCheckType CT = checkFormatStringExpr(
7986 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7987 firstDataArg, Type, CallType,
7988 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7989 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7990
7991 // Generate a diagnostic where an uncovered argument is detected.
7992 if (UncoveredArg.hasUncoveredArg()) {
7993 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7994 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7995 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7996 }
7997
7998 if (CT != SLCT_NotALiteral)
7999 // Literal format string found, check done!
8000 return CT == SLCT_CheckedLiteral;
8001
8002 // Do not emit diag when the string param is a macro expansion and the
8003 // format is either NSString or CFString. This is a hack to prevent
8004 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8005 // which are usually used in place of NS and CF string literals.
8006 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8008 SourceMgr.isInSystemMacro(FormatLoc))
8009 return false;
8010
8011 if (CallerParamIdx && CheckMissingFormatAttribute(
8012 this, Args, APK, ReferenceFormatString, format_idx,
8013 firstDataArg, Type, *CallerParamIdx, Loc))
8014 return false;
8015
8016 // Strftime is particular as it always uses a single 'time' argument,
8017 // so it is safe to pass a non-literal string.
8019 return false;
8020
8021 // If there are no arguments specified, warn with -Wformat-security, otherwise
8022 // warn only with -Wformat-nonliteral.
8023 if (Args.size() == firstDataArg) {
8024 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8025 << OrigFormatExpr->getSourceRange();
8026 switch (Type) {
8027 default:
8028 break;
8032 Diag(FormatLoc, diag::note_format_security_fixit)
8033 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8034 break;
8036 Diag(FormatLoc, diag::note_format_security_fixit)
8037 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8038 break;
8039 }
8040 } else {
8041 Diag(FormatLoc, diag::warn_format_nonliteral)
8042 << OrigFormatExpr->getSourceRange();
8043 }
8044 return false;
8045}
8046
8047namespace {
8048
8049class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8050protected:
8051 Sema &S;
8052 const FormatStringLiteral *FExpr;
8053 const Expr *OrigFormatExpr;
8054 const FormatStringType FSType;
8055 const unsigned FirstDataArg;
8056 const unsigned NumDataArgs;
8057 const char *Beg; // Start of format string.
8058 const Sema::FormatArgumentPassingKind ArgPassingKind;
8059 ArrayRef<const Expr *> Args;
8060 unsigned FormatIdx;
8061 llvm::SmallBitVector CoveredArgs;
8062 bool usesPositionalArgs = false;
8063 bool atFirstArg = true;
8064 bool inFunctionCall;
8065 VariadicCallType CallType;
8066 llvm::SmallBitVector &CheckedVarArgs;
8067 UncoveredArgHandler &UncoveredArg;
8068
8069public:
8070 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8071 const Expr *origFormatExpr, const FormatStringType type,
8072 unsigned firstDataArg, unsigned numDataArgs,
8073 const char *beg, Sema::FormatArgumentPassingKind APK,
8074 ArrayRef<const Expr *> Args, unsigned formatIdx,
8075 bool inFunctionCall, VariadicCallType callType,
8076 llvm::SmallBitVector &CheckedVarArgs,
8077 UncoveredArgHandler &UncoveredArg)
8078 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8079 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8080 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8081 inFunctionCall(inFunctionCall), CallType(callType),
8082 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8083 CoveredArgs.resize(numDataArgs);
8084 CoveredArgs.reset();
8085 }
8086
8087 bool HasFormatArguments() const {
8088 return ArgPassingKind == Sema::FAPK_Fixed ||
8089 ArgPassingKind == Sema::FAPK_Variadic;
8090 }
8091
8092 void DoneProcessing();
8093
8094 void HandleIncompleteSpecifier(const char *startSpecifier,
8095 unsigned specifierLen) override;
8096
8097 void HandleInvalidLengthModifier(
8098 const analyze_format_string::FormatSpecifier &FS,
8099 const analyze_format_string::ConversionSpecifier &CS,
8100 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8101
8102 void HandleNonStandardLengthModifier(
8103 const analyze_format_string::FormatSpecifier &FS,
8104 const char *startSpecifier, unsigned specifierLen);
8105
8106 void HandleNonStandardConversionSpecifier(
8107 const analyze_format_string::ConversionSpecifier &CS,
8108 const char *startSpecifier, unsigned specifierLen);
8109
8110 void HandlePosition(const char *startPos, unsigned posLen) override;
8111
8112 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8114
8115 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8116
8117 void HandleNullChar(const char *nullCharacter) override;
8118
8119 template <typename Range>
8120 static void
8121 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8122 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8123 bool IsStringLocation, Range StringRange,
8124 ArrayRef<FixItHint> Fixit = {});
8125
8126protected:
8127 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8128 const char *startSpec,
8129 unsigned specifierLen,
8130 const char *csStart, unsigned csLen);
8131
8132 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8133 const char *startSpec,
8134 unsigned specifierLen);
8135
8136 SourceRange getFormatStringRange();
8137 CharSourceRange getSpecifierRange(const char *startSpecifier,
8138 unsigned specifierLen);
8139 SourceLocation getLocationOfByte(const char *x);
8140
8141 const Expr *getDataArg(unsigned i) const;
8142
8143 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8144 const analyze_format_string::ConversionSpecifier &CS,
8145 const char *startSpecifier, unsigned specifierLen,
8146 unsigned argIndex);
8147
8148 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8149 const Expr *E, const char *startSpecifier,
8150 unsigned specifierLen);
8151
8152 template <typename Range>
8153 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8154 bool IsStringLocation, Range StringRange,
8155 ArrayRef<FixItHint> Fixit = {});
8156};
8157
8158} // namespace
8159
8160SourceRange CheckFormatHandler::getFormatStringRange() {
8161 return OrigFormatExpr->getSourceRange();
8162}
8163
8165CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8166 unsigned specifierLen) {
8167 SourceLocation Start = getLocationOfByte(startSpecifier);
8168 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8169
8170 // Advance the end SourceLocation by one due to half-open ranges.
8171 End = End.getLocWithOffset(1);
8172
8173 return CharSourceRange::getCharRange(Start, End);
8174}
8175
8176SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8177 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8179}
8180
8181void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8182 unsigned specifierLen) {
8183 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8184 getLocationOfByte(startSpecifier),
8185 /*IsStringLocation*/ true,
8186 getSpecifierRange(startSpecifier, specifierLen));
8187}
8188
8189bool CheckFormatHandler::CheckUnsupportedType(
8190 const analyze_format_string::ArgType &AT, const Expr *E,
8191 const char *StartSpecifier, unsigned SpecifierLen) {
8192 if (!AT.isUnsupported())
8193 return false;
8194
8195 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8197 E->getExprLoc(), /*IsStringLocation=*/false,
8198 getSpecifierRange(StartSpecifier, SpecifierLen));
8199 return true;
8200}
8201
8202void CheckFormatHandler::HandleInvalidLengthModifier(
8205 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8206 using namespace analyze_format_string;
8207
8208 const LengthModifier &LM = FS.getLengthModifier();
8209 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8210
8211 // See if we know how to fix this length modifier.
8212 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8213 if (FixedLM) {
8214 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8215 getLocationOfByte(LM.getStart()),
8216 /*IsStringLocation*/ true,
8217 getSpecifierRange(startSpecifier, specifierLen));
8218
8219 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8220 << FixedLM->toString()
8221 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8222
8223 } else {
8224 FixItHint Hint;
8225 if (DiagID == diag::warn_format_nonsensical_length)
8226 Hint = FixItHint::CreateRemoval(LMRange);
8227
8228 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8229 getLocationOfByte(LM.getStart()),
8230 /*IsStringLocation*/ true,
8231 getSpecifierRange(startSpecifier, specifierLen), Hint);
8232 }
8233}
8234
8235void CheckFormatHandler::HandleNonStandardLengthModifier(
8237 const char *startSpecifier, unsigned specifierLen) {
8238 using namespace analyze_format_string;
8239
8240 const LengthModifier &LM = FS.getLengthModifier();
8241 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8242
8243 // See if we know how to fix this length modifier.
8244 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8245 if (FixedLM) {
8246 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8247 << LM.toString() << 0,
8248 getLocationOfByte(LM.getStart()),
8249 /*IsStringLocation*/ true,
8250 getSpecifierRange(startSpecifier, specifierLen));
8251
8252 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8253 << FixedLM->toString()
8254 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8255
8256 } else {
8257 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8258 << LM.toString() << 0,
8259 getLocationOfByte(LM.getStart()),
8260 /*IsStringLocation*/ true,
8261 getSpecifierRange(startSpecifier, specifierLen));
8262 }
8263}
8264
8265void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8267 const char *startSpecifier, unsigned specifierLen) {
8268 using namespace analyze_format_string;
8269
8270 // See if we know how to fix this conversion specifier.
8271 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8272 if (FixedCS) {
8273 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8274 << CS.toString() << /*conversion specifier*/ 1,
8275 getLocationOfByte(CS.getStart()),
8276 /*IsStringLocation*/ true,
8277 getSpecifierRange(startSpecifier, specifierLen));
8278
8279 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8280 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8281 << FixedCS->toString()
8282 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8283 } else {
8284 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8285 << CS.toString() << /*conversion specifier*/ 1,
8286 getLocationOfByte(CS.getStart()),
8287 /*IsStringLocation*/ true,
8288 getSpecifierRange(startSpecifier, specifierLen));
8289 }
8290}
8291
8292void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8293 if (!S.getDiagnostics().isIgnored(
8294 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8295 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8296 getLocationOfByte(startPos),
8297 /*IsStringLocation*/ true,
8298 getSpecifierRange(startPos, posLen));
8299}
8300
8301void CheckFormatHandler::HandleInvalidPosition(
8302 const char *startSpecifier, unsigned specifierLen,
8304 if (!S.getDiagnostics().isIgnored(
8305 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8306 EmitFormatDiagnostic(
8307 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8308 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8309 getSpecifierRange(startSpecifier, specifierLen));
8310}
8311
8312void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8313 unsigned posLen) {
8314 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8315 SourceLocation()))
8316 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8317 getLocationOfByte(startPos),
8318 /*IsStringLocation*/ true,
8319 getSpecifierRange(startPos, posLen));
8320}
8321
8322void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8323 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8324 // The presence of a null character is likely an error.
8325 EmitFormatDiagnostic(
8326 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8327 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8328 getFormatStringRange());
8329 }
8330}
8331
8332// Note that this may return NULL if there was an error parsing or building
8333// one of the argument expressions.
8334const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8335 return Args[FirstDataArg + i];
8336}
8337
8338void CheckFormatHandler::DoneProcessing() {
8339 // Does the number of data arguments exceed the number of
8340 // format conversions in the format string?
8341 if (HasFormatArguments()) {
8342 // Find any arguments that weren't covered.
8343 CoveredArgs.flip();
8344 signed notCoveredArg = CoveredArgs.find_first();
8345 if (notCoveredArg >= 0) {
8346 assert((unsigned)notCoveredArg < NumDataArgs);
8347 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8348 } else {
8349 UncoveredArg.setAllCovered();
8350 }
8351 }
8352}
8353
8354void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8355 const Expr *ArgExpr) {
8356 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8357
8358 if (!ArgExpr)
8359 return;
8360
8361 SourceLocation Loc = ArgExpr->getBeginLoc();
8362
8363 if (S.getSourceManager().isInSystemMacro(Loc))
8364 return;
8365
8366 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8367 for (auto E : DiagnosticExprs)
8368 PDiag << E->getSourceRange();
8369
8370 CheckFormatHandler::EmitFormatDiagnostic(
8371 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8372 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8373}
8374
8375bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8376 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8377 unsigned specifierLen, const char *csStart, unsigned csLen) {
8378 bool keepGoing = true;
8379 if (argIndex < NumDataArgs) {
8380 // Consider the argument coverered, even though the specifier doesn't
8381 // make sense.
8382 CoveredArgs.set(argIndex);
8383 } else {
8384 // If argIndex exceeds the number of data arguments we
8385 // don't issue a warning because that is just a cascade of warnings (and
8386 // they may have intended '%%' anyway). We don't want to continue processing
8387 // the format string after this point, however, as we will like just get
8388 // gibberish when trying to match arguments.
8389 keepGoing = false;
8390 }
8391
8392 StringRef Specifier(csStart, csLen);
8393
8394 // If the specifier in non-printable, it could be the first byte of a UTF-8
8395 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8396 // hex value.
8397 std::string CodePointStr;
8398 if (!llvm::sys::locale::isPrint(*csStart)) {
8399 llvm::UTF32 CodePoint;
8400 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8401 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8402 llvm::ConversionResult Result =
8403 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8404
8405 if (Result != llvm::conversionOK) {
8406 unsigned char FirstChar = *csStart;
8407 CodePoint = (llvm::UTF32)FirstChar;
8408 }
8409
8410 llvm::raw_string_ostream OS(CodePointStr);
8411 if (CodePoint < 256)
8412 OS << "\\x" << llvm::format("%02x", CodePoint);
8413 else if (CodePoint <= 0xFFFF)
8414 OS << "\\u" << llvm::format("%04x", CodePoint);
8415 else
8416 OS << "\\U" << llvm::format("%08x", CodePoint);
8417 Specifier = CodePointStr;
8418 }
8419
8420 EmitFormatDiagnostic(
8421 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8422 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8423
8424 return keepGoing;
8425}
8426
8427void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8428 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8429 EmitFormatDiagnostic(
8430 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8431 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8432}
8433
8434bool CheckFormatHandler::CheckNumArgs(
8437 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8438
8439 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8440 PartialDiagnostic PDiag =
8442 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8443 << (argIndex + 1) << NumDataArgs)
8444 : S.PDiag(diag::warn_printf_insufficient_data_args);
8445 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8446 /*IsStringLocation*/ true,
8447 getSpecifierRange(startSpecifier, specifierLen));
8448
8449 // Since more arguments than conversion tokens are given, by extension
8450 // all arguments are covered, so mark this as so.
8451 UncoveredArg.setAllCovered();
8452 return false;
8453 }
8454 return true;
8455}
8456
8457template <typename Range>
8458void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8459 SourceLocation Loc,
8460 bool IsStringLocation,
8461 Range StringRange,
8462 ArrayRef<FixItHint> FixIt) {
8463 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8464 IsStringLocation, StringRange, FixIt);
8465}
8466
8467/// If the format string is not within the function call, emit a note
8468/// so that the function call and string are in diagnostic messages.
8469///
8470/// \param InFunctionCall if true, the format string is within the function
8471/// call and only one diagnostic message will be produced. Otherwise, an
8472/// extra note will be emitted pointing to location of the format string.
8473///
8474/// \param ArgumentExpr the expression that is passed as the format string
8475/// argument in the function call. Used for getting locations when two
8476/// diagnostics are emitted.
8477///
8478/// \param PDiag the callee should already have provided any strings for the
8479/// diagnostic message. This function only adds locations and fixits
8480/// to diagnostics.
8481///
8482/// \param Loc primary location for diagnostic. If two diagnostics are
8483/// required, one will be at Loc and a new SourceLocation will be created for
8484/// the other one.
8485///
8486/// \param IsStringLocation if true, Loc points to the format string should be
8487/// used for the note. Otherwise, Loc points to the argument list and will
8488/// be used with PDiag.
8489///
8490/// \param StringRange some or all of the string to highlight. This is
8491/// templated so it can accept either a CharSourceRange or a SourceRange.
8492///
8493/// \param FixIt optional fix it hint for the format string.
8494template <typename Range>
8495void CheckFormatHandler::EmitFormatDiagnostic(
8496 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8497 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8498 Range StringRange, ArrayRef<FixItHint> FixIt) {
8499 if (InFunctionCall) {
8500 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8501 D << StringRange;
8502 D << FixIt;
8503 } else {
8504 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8505 << ArgumentExpr->getSourceRange();
8506
8508 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8509 diag::note_format_string_defined);
8510
8511 Note << StringRange;
8512 Note << FixIt;
8513 }
8514}
8515
8516//===--- CHECK: Printf format string checking -----------------------------===//
8517
8518namespace {
8519
8520class CheckPrintfHandler : public CheckFormatHandler {
8521public:
8522 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8523 const Expr *origFormatExpr, const FormatStringType type,
8524 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8525 const char *beg, Sema::FormatArgumentPassingKind APK,
8526 ArrayRef<const Expr *> Args, unsigned formatIdx,
8527 bool inFunctionCall, VariadicCallType CallType,
8528 llvm::SmallBitVector &CheckedVarArgs,
8529 UncoveredArgHandler &UncoveredArg)
8530 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8531 numDataArgs, beg, APK, Args, formatIdx,
8532 inFunctionCall, CallType, CheckedVarArgs,
8533 UncoveredArg) {}
8534
8535 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8536
8537 /// Returns true if '%@' specifiers are allowed in the format string.
8538 bool allowsObjCArg() const {
8539 return FSType == FormatStringType::NSString ||
8540 FSType == FormatStringType::OSLog ||
8541 FSType == FormatStringType::OSTrace;
8542 }
8543
8544 bool HandleInvalidPrintfConversionSpecifier(
8545 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8546 unsigned specifierLen) override;
8547
8548 void handleInvalidMaskType(StringRef MaskType) override;
8549
8550 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8551 const char *startSpecifier, unsigned specifierLen,
8552 const TargetInfo &Target) override;
8553 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8554 const char *StartSpecifier, unsigned SpecifierLen,
8555 const Expr *E);
8556
8557 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8558 unsigned k, const char *startSpecifier,
8559 unsigned specifierLen);
8560 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8561 const analyze_printf::OptionalAmount &Amt,
8562 unsigned type, const char *startSpecifier,
8563 unsigned specifierLen);
8564 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8565 const analyze_printf::OptionalFlag &flag,
8566 const char *startSpecifier, unsigned specifierLen);
8567 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8568 const analyze_printf::OptionalFlag &ignoredFlag,
8569 const analyze_printf::OptionalFlag &flag,
8570 const char *startSpecifier, unsigned specifierLen);
8571 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8572
8573 void HandleEmptyObjCModifierFlag(const char *startFlag,
8574 unsigned flagLen) override;
8575
8576 void HandleInvalidObjCModifierFlag(const char *startFlag,
8577 unsigned flagLen) override;
8578
8579 void
8580 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8581 const char *flagsEnd,
8582 const char *conversionPosition) override;
8583};
8584
8585/// Keeps around the information needed to verify that two specifiers are
8586/// compatible.
8587class EquatableFormatArgument {
8588public:
8589 enum SpecifierSensitivity : unsigned {
8590 SS_None,
8591 SS_Private,
8592 SS_Public,
8593 SS_Sensitive
8594 };
8595
8596 enum FormatArgumentRole : unsigned {
8597 FAR_Data,
8598 FAR_FieldWidth,
8599 FAR_Precision,
8600 FAR_Auxiliary, // FreeBSD kernel %b and %D
8601 };
8602
8603private:
8604 analyze_format_string::ArgType ArgType;
8605 analyze_format_string::LengthModifier LengthMod;
8606 StringRef SpecifierLetter;
8607 CharSourceRange Range;
8608 SourceLocation ElementLoc;
8609 FormatArgumentRole Role : 2;
8610 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8611 unsigned Position : 14;
8612 unsigned ModifierFor : 14; // not set for FAR_Data
8613
8614 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8615 bool InFunctionCall) const;
8616
8617public:
8618 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8619 analyze_format_string::LengthModifier LengthMod,
8620 StringRef SpecifierLetter,
8621 analyze_format_string::ArgType ArgType,
8622 FormatArgumentRole Role,
8623 SpecifierSensitivity Sensitivity, unsigned Position,
8624 unsigned ModifierFor)
8625 : ArgType(ArgType), LengthMod(LengthMod),
8626 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8627 Role(Role), Sensitivity(Sensitivity), Position(Position),
8628 ModifierFor(ModifierFor) {}
8629
8630 unsigned getPosition() const { return Position; }
8631 SourceLocation getSourceLocation() const { return ElementLoc; }
8632 CharSourceRange getSourceRange() const { return Range; }
8633 analyze_format_string::LengthModifier getLengthModifier() const {
8634 return LengthMod;
8635 }
8636 void setModifierFor(unsigned V) { ModifierFor = V; }
8637
8638 std::string buildFormatSpecifier() const {
8639 std::string result;
8640 llvm::raw_string_ostream(result)
8641 << getLengthModifier().toString() << SpecifierLetter;
8642 return result;
8643 }
8644
8645 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8646 const Expr *FmtExpr, bool InFunctionCall) const;
8647};
8648
8649/// Turns format strings into lists of EquatableSpecifier objects.
8650class DecomposePrintfHandler : public CheckPrintfHandler {
8651 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8652 bool HadError;
8653
8654 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8655 const Expr *origFormatExpr,
8656 const FormatStringType type, unsigned firstDataArg,
8657 unsigned numDataArgs, bool isObjC, const char *beg,
8659 ArrayRef<const Expr *> Args, unsigned formatIdx,
8660 bool inFunctionCall, VariadicCallType CallType,
8661 llvm::SmallBitVector &CheckedVarArgs,
8662 UncoveredArgHandler &UncoveredArg,
8663 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8664 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8665 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8666 inFunctionCall, CallType, CheckedVarArgs,
8667 UncoveredArg),
8668 Specs(Specs), HadError(false) {}
8669
8670public:
8671 static bool
8672 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8673 FormatStringType type, bool IsObjC, bool InFunctionCall,
8674 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8675
8676 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8677 const char *startSpecifier,
8678 unsigned specifierLen,
8679 const TargetInfo &Target) override;
8680};
8681
8682} // namespace
8683
8684bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8685 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8686 unsigned specifierLen) {
8689
8690 return HandleInvalidConversionSpecifier(
8691 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8692 specifierLen, CS.getStart(), CS.getLength());
8693}
8694
8695void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8696 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8697}
8698
8699// Error out if struct or complex type argments are passed to os_log.
8701 QualType T) {
8702 if (FSType != FormatStringType::OSLog)
8703 return false;
8704 return T->isRecordType() || T->isComplexType();
8705}
8706
8707bool CheckPrintfHandler::HandleAmount(
8708 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8709 const char *startSpecifier, unsigned specifierLen) {
8710 if (Amt.hasDataArgument()) {
8711 if (HasFormatArguments()) {
8712 unsigned argIndex = Amt.getArgIndex();
8713 if (argIndex >= NumDataArgs) {
8714 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8715 << k,
8716 getLocationOfByte(Amt.getStart()),
8717 /*IsStringLocation*/ true,
8718 getSpecifierRange(startSpecifier, specifierLen));
8719 // Don't do any more checking. We will just emit
8720 // spurious errors.
8721 return false;
8722 }
8723
8724 // Type check the data argument. It should be an 'int'.
8725 // Although not in conformance with C99, we also allow the argument to be
8726 // an 'unsigned int' as that is a reasonably safe case. GCC also
8727 // doesn't emit a warning for that case.
8728 CoveredArgs.set(argIndex);
8729 const Expr *Arg = getDataArg(argIndex);
8730 if (!Arg)
8731 return false;
8732
8733 QualType T = Arg->getType();
8734
8735 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8736 assert(AT.isValid());
8737
8738 if (!AT.matchesType(S.Context, T)) {
8739 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8740 ? diag::err_printf_asterisk_wrong_type
8741 : diag::warn_printf_asterisk_wrong_type;
8742 EmitFormatDiagnostic(S.PDiag(DiagID)
8744 << T << Arg->getSourceRange(),
8745 getLocationOfByte(Amt.getStart()),
8746 /*IsStringLocation*/ true,
8747 getSpecifierRange(startSpecifier, specifierLen));
8748 // Don't do any more checking. We will just emit
8749 // spurious errors.
8750 return false;
8751 }
8752 }
8753 }
8754 return true;
8755}
8756
8757void CheckPrintfHandler::HandleInvalidAmount(
8759 const analyze_printf::OptionalAmount &Amt, unsigned type,
8760 const char *startSpecifier, unsigned specifierLen) {
8763
8764 FixItHint fixit =
8767 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8768 : FixItHint();
8769
8770 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8771 << type << CS.toString(),
8772 getLocationOfByte(Amt.getStart()),
8773 /*IsStringLocation*/ true,
8774 getSpecifierRange(startSpecifier, specifierLen), fixit);
8775}
8776
8777void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8778 const analyze_printf::OptionalFlag &flag,
8779 const char *startSpecifier,
8780 unsigned specifierLen) {
8781 // Warn about pointless flag with a fixit removal.
8784 EmitFormatDiagnostic(
8785 S.PDiag(diag::warn_printf_nonsensical_flag)
8786 << flag.toString() << CS.toString(),
8787 getLocationOfByte(flag.getPosition()),
8788 /*IsStringLocation*/ true,
8789 getSpecifierRange(startSpecifier, specifierLen),
8790 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8791}
8792
8793void CheckPrintfHandler::HandleIgnoredFlag(
8795 const analyze_printf::OptionalFlag &ignoredFlag,
8796 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8797 unsigned specifierLen) {
8798 // Warn about ignored flag with a fixit removal.
8799 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8800 << ignoredFlag.toString() << flag.toString(),
8801 getLocationOfByte(ignoredFlag.getPosition()),
8802 /*IsStringLocation*/ true,
8803 getSpecifierRange(startSpecifier, specifierLen),
8805 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8806}
8807
8808void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8809 unsigned flagLen) {
8810 // Warn about an empty flag.
8811 EmitFormatDiagnostic(
8812 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8813 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8814}
8815
8816void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8817 unsigned flagLen) {
8818 // Warn about an invalid flag.
8819 auto Range = getSpecifierRange(startFlag, flagLen);
8820 StringRef flag(startFlag, flagLen);
8821 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8822 getLocationOfByte(startFlag),
8823 /*IsStringLocation*/ true, Range,
8825}
8826
8827void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8828 const char *flagsStart, const char *flagsEnd,
8829 const char *conversionPosition) {
8830 // Warn about using '[...]' without a '@' conversion.
8831 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8832 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8833 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8834 getLocationOfByte(conversionPosition),
8835 /*IsStringLocation*/ true, Range,
8837}
8838
8839void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8840 const Expr *FmtExpr,
8841 bool InFunctionCall) const {
8842 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8843 ElementLoc, true, Range);
8844}
8845
8846bool EquatableFormatArgument::VerifyCompatible(
8847 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8848 bool InFunctionCall) const {
8850 if (Role != Other.Role) {
8851 // diagnose and stop
8852 EmitDiagnostic(
8853 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8854 FmtExpr, InFunctionCall);
8855 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8856 return false;
8857 }
8858
8859 if (Role != FAR_Data) {
8860 if (ModifierFor != Other.ModifierFor) {
8861 // diagnose and stop
8862 EmitDiagnostic(S,
8863 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8864 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8865 FmtExpr, InFunctionCall);
8866 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8867 return false;
8868 }
8869 return true;
8870 }
8871
8872 bool HadError = false;
8873 if (Sensitivity != Other.Sensitivity) {
8874 // diagnose and continue
8875 EmitDiagnostic(S,
8876 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8877 << Sensitivity << Other.Sensitivity,
8878 FmtExpr, InFunctionCall);
8879 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8880 << 0 << Other.Range;
8881 }
8882
8883 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8884 case MK::Match:
8885 break;
8886
8887 case MK::MatchPromotion:
8888 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8889 // MatchPromotion is treated as a failure by format_matches.
8890 case MK::NoMatch:
8891 case MK::NoMatchTypeConfusion:
8892 case MK::NoMatchPromotionTypeConfusion:
8893 EmitDiagnostic(S,
8894 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8895 << buildFormatSpecifier()
8896 << Other.buildFormatSpecifier(),
8897 FmtExpr, InFunctionCall);
8898 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8899 << 0 << Other.Range;
8900 break;
8901
8902 case MK::NoMatchPedantic:
8903 EmitDiagnostic(S,
8904 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8905 << buildFormatSpecifier()
8906 << Other.buildFormatSpecifier(),
8907 FmtExpr, InFunctionCall);
8908 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8909 << 0 << Other.Range;
8910 break;
8911
8912 case MK::NoMatchSignedness:
8913 EmitDiagnostic(S,
8914 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8915 << buildFormatSpecifier()
8916 << Other.buildFormatSpecifier(),
8917 FmtExpr, InFunctionCall);
8918 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8919 << 0 << Other.Range;
8920 break;
8921 }
8922 return !HadError;
8923}
8924
8925bool DecomposePrintfHandler::GetSpecifiers(
8926 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8927 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8929 StringRef Data = FSL->getString();
8930 const char *Str = Data.data();
8931 llvm::SmallBitVector BV;
8932 UncoveredArgHandler UA;
8933 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8934 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8935 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8936 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8937 UA, Args);
8938
8940 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8942 H.DoneProcessing();
8943 if (H.HadError)
8944 return false;
8945
8946 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8947 const EquatableFormatArgument &B) {
8948 return A.getPosition() < B.getPosition();
8949 });
8950 return true;
8951}
8952
8953bool DecomposePrintfHandler::HandlePrintfSpecifier(
8954 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8955 unsigned specifierLen, const TargetInfo &Target) {
8956 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8957 specifierLen, Target)) {
8958 HadError = true;
8959 return false;
8960 }
8961
8962 // Do not add any specifiers to the list for %%. This is possibly incorrect
8963 // if using a precision/width with a data argument, but that combination is
8964 // meaningless and we wouldn't know which format to attach the
8965 // precision/width to.
8966 const auto &CS = FS.getConversionSpecifier();
8968 return true;
8969
8970 // have to patch these to have the right ModifierFor if they are used
8971 const unsigned Unset = ~0;
8972 unsigned FieldWidthIndex = Unset;
8973 unsigned PrecisionIndex = Unset;
8974
8975 // field width?
8976 const auto &FieldWidth = FS.getFieldWidth();
8977 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8978 FieldWidthIndex = Specs.size();
8979 Specs.emplace_back(
8980 getSpecifierRange(startSpecifier, specifierLen),
8981 getLocationOfByte(FieldWidth.getStart()),
8982 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
8983 FieldWidth.getArgType(S.Context),
8984 EquatableFormatArgument::FAR_FieldWidth,
8985 EquatableFormatArgument::SS_None,
8986 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8987 : FieldWidthIndex,
8988 0);
8989 }
8990 // precision?
8991 const auto &Precision = FS.getPrecision();
8992 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8993 PrecisionIndex = Specs.size();
8994 Specs.emplace_back(
8995 getSpecifierRange(startSpecifier, specifierLen),
8996 getLocationOfByte(Precision.getStart()),
8997 analyze_format_string::LengthModifier(), Precision.getCharacters(),
8998 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8999 EquatableFormatArgument::SS_None,
9000 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9001 : PrecisionIndex,
9002 0);
9003 }
9004
9005 // this specifier
9006 unsigned SpecIndex =
9007 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9008 if (FieldWidthIndex != Unset)
9009 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9010 if (PrecisionIndex != Unset)
9011 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9012
9013 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9014 if (FS.isPrivate())
9015 Sensitivity = EquatableFormatArgument::SS_Private;
9016 else if (FS.isPublic())
9017 Sensitivity = EquatableFormatArgument::SS_Public;
9018 else if (FS.isSensitive())
9019 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9020 else
9021 Sensitivity = EquatableFormatArgument::SS_None;
9022
9023 Specs.emplace_back(
9024 getSpecifierRange(startSpecifier, specifierLen),
9025 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
9026 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
9027 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9028
9029 // auxiliary argument?
9032 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9033 getLocationOfByte(CS.getStart()),
9035 CS.getCharacters(),
9037 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9038 SpecIndex + 1, SpecIndex);
9039 }
9040 return true;
9041}
9042
9043// Determines if the specified is a C++ class or struct containing
9044// a member with the specified name and kind (e.g. a CXXMethodDecl named
9045// "c_str()").
9046template<typename MemberKind>
9048CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9049 auto *RD = Ty->getAsCXXRecordDecl();
9051
9052 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9053 return Results;
9054
9055 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9057 R.suppressDiagnostics();
9058
9059 // We just need to include all members of the right kind turned up by the
9060 // filter, at this point.
9061 if (S.LookupQualifiedName(R, RD))
9062 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9063 NamedDecl *decl = (*I)->getUnderlyingDecl();
9064 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9065 Results.insert(FK);
9066 }
9067 return Results;
9068}
9069
9070/// Check if we could call '.c_str()' on an object.
9071///
9072/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9073/// allow the call, or if it would be ambiguous).
9075 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9076
9077 MethodSet Results =
9078 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9079 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9080 MI != ME; ++MI)
9081 if ((*MI)->getMinRequiredArguments() == 0)
9082 return true;
9083 return false;
9084}
9085
9086// Check if a (w)string was passed when a (w)char* was needed, and offer a
9087// better diagnostic if so. AT is assumed to be valid.
9088// Returns true when a c_str() conversion method is found.
9089bool CheckPrintfHandler::checkForCStrMembers(
9090 const analyze_printf::ArgType &AT, const Expr *E) {
9091 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9092
9093 MethodSet Results =
9095
9096 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9097 MI != ME; ++MI) {
9098 const CXXMethodDecl *Method = *MI;
9099 if (Method->getMinRequiredArguments() == 0 &&
9100 AT.matchesType(S.Context, Method->getReturnType())) {
9101 // FIXME: Suggest parens if the expression needs them.
9103 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9104 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9105 return true;
9106 }
9107 }
9108
9109 return false;
9110}
9111
9112bool CheckPrintfHandler::HandlePrintfSpecifier(
9113 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9114 unsigned specifierLen, const TargetInfo &Target) {
9115 using namespace analyze_format_string;
9116 using namespace analyze_printf;
9117
9118 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9119
9120 if (FS.consumesDataArgument()) {
9121 if (atFirstArg) {
9122 atFirstArg = false;
9123 usesPositionalArgs = FS.usesPositionalArg();
9124 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9125 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9126 startSpecifier, specifierLen);
9127 return false;
9128 }
9129 }
9130
9131 // First check if the field width, precision, and conversion specifier
9132 // have matching data arguments.
9133 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9134 specifierLen)) {
9135 return false;
9136 }
9137
9138 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9139 specifierLen)) {
9140 return false;
9141 }
9142
9143 if (!CS.consumesDataArgument()) {
9144 // FIXME: Technically specifying a precision or field width here
9145 // makes no sense. Worth issuing a warning at some point.
9146 return true;
9147 }
9148
9149 // Consume the argument.
9150 unsigned argIndex = FS.getArgIndex();
9151 if (argIndex < NumDataArgs) {
9152 // The check to see if the argIndex is valid will come later.
9153 // We set the bit here because we may exit early from this
9154 // function if we encounter some other error.
9155 CoveredArgs.set(argIndex);
9156 }
9157
9158 // FreeBSD kernel extensions.
9159 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9160 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9161 // We need at least two arguments.
9162 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9163 return false;
9164
9165 if (HasFormatArguments()) {
9166 // Claim the second argument.
9167 CoveredArgs.set(argIndex + 1);
9168
9169 // Type check the first argument (int for %b, pointer for %D)
9170 const Expr *Ex = getDataArg(argIndex);
9171 const analyze_printf::ArgType &AT =
9172 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9173 ? ArgType(S.Context.IntTy)
9174 : ArgType::CPointerTy;
9175 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9176 EmitFormatDiagnostic(
9177 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9178 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9179 << false << Ex->getSourceRange(),
9180 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9181 getSpecifierRange(startSpecifier, specifierLen));
9182
9183 // Type check the second argument (char * for both %b and %D)
9184 Ex = getDataArg(argIndex + 1);
9186 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9187 EmitFormatDiagnostic(
9188 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9189 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9190 << false << Ex->getSourceRange(),
9191 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9192 getSpecifierRange(startSpecifier, specifierLen));
9193 }
9194 return true;
9195 }
9196
9197 // Check for using an Objective-C specific conversion specifier
9198 // in a non-ObjC literal.
9199 if (!allowsObjCArg() && CS.isObjCArg()) {
9200 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9201 specifierLen);
9202 }
9203
9204 // %P can only be used with os_log.
9205 if (FSType != FormatStringType::OSLog &&
9206 CS.getKind() == ConversionSpecifier::PArg) {
9207 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9208 specifierLen);
9209 }
9210
9211 // %n is not allowed with os_log.
9212 if (FSType == FormatStringType::OSLog &&
9213 CS.getKind() == ConversionSpecifier::nArg) {
9214 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9215 getLocationOfByte(CS.getStart()),
9216 /*IsStringLocation*/ false,
9217 getSpecifierRange(startSpecifier, specifierLen));
9218
9219 return true;
9220 }
9221
9222 // Only scalars are allowed for os_trace.
9223 if (FSType == FormatStringType::OSTrace &&
9224 (CS.getKind() == ConversionSpecifier::PArg ||
9225 CS.getKind() == ConversionSpecifier::sArg ||
9226 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9227 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9228 specifierLen);
9229 }
9230
9231 // Check for use of public/private annotation outside of os_log().
9232 if (FSType != FormatStringType::OSLog) {
9233 if (FS.isPublic().isSet()) {
9234 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9235 << "public",
9236 getLocationOfByte(FS.isPublic().getPosition()),
9237 /*IsStringLocation*/ false,
9238 getSpecifierRange(startSpecifier, specifierLen));
9239 }
9240 if (FS.isPrivate().isSet()) {
9241 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9242 << "private",
9243 getLocationOfByte(FS.isPrivate().getPosition()),
9244 /*IsStringLocation*/ false,
9245 getSpecifierRange(startSpecifier, specifierLen));
9246 }
9247 }
9248
9249 const llvm::Triple &Triple = Target.getTriple();
9250 if (CS.getKind() == ConversionSpecifier::nArg &&
9251 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9252 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9253 getLocationOfByte(CS.getStart()),
9254 /*IsStringLocation*/ false,
9255 getSpecifierRange(startSpecifier, specifierLen));
9256 }
9257
9258 // Check for invalid use of field width
9259 if (!FS.hasValidFieldWidth()) {
9260 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9261 startSpecifier, specifierLen);
9262 }
9263
9264 // Check for invalid use of precision
9265 if (!FS.hasValidPrecision()) {
9266 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9267 startSpecifier, specifierLen);
9268 }
9269
9270 // Precision is mandatory for %P specifier.
9271 if (CS.getKind() == ConversionSpecifier::PArg &&
9273 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9274 getLocationOfByte(startSpecifier),
9275 /*IsStringLocation*/ false,
9276 getSpecifierRange(startSpecifier, specifierLen));
9277 }
9278
9279 // Check each flag does not conflict with any other component.
9281 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9282 if (!FS.hasValidLeadingZeros())
9283 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9284 if (!FS.hasValidPlusPrefix())
9285 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9286 if (!FS.hasValidSpacePrefix())
9287 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9288 if (!FS.hasValidAlternativeForm())
9289 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9290 if (!FS.hasValidLeftJustified())
9291 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9292
9293 // Check that flags are not ignored by another flag
9294 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9295 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9296 startSpecifier, specifierLen);
9297 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9298 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9299 startSpecifier, specifierLen);
9300
9301 // Check the length modifier is valid with the given conversion specifier.
9303 S.getLangOpts()))
9304 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9305 diag::warn_format_nonsensical_length);
9306 else if (!FS.hasStandardLengthModifier())
9307 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9309 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9310 diag::warn_format_non_standard_conversion_spec);
9311
9313 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9314
9315 // The remaining checks depend on the data arguments.
9316 if (!HasFormatArguments())
9317 return true;
9318
9319 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9320 return false;
9321
9322 const Expr *Arg = getDataArg(argIndex);
9323 if (!Arg)
9324 return true;
9325
9326 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9327}
9328
9329static bool requiresParensToAddCast(const Expr *E) {
9330 // FIXME: We should have a general way to reason about operator
9331 // precedence and whether parens are actually needed here.
9332 // Take care of a few common cases where they aren't.
9333 const Expr *Inside = E->IgnoreImpCasts();
9334 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9335 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9336
9337 switch (Inside->getStmtClass()) {
9338 case Stmt::ArraySubscriptExprClass:
9339 case Stmt::CallExprClass:
9340 case Stmt::CharacterLiteralClass:
9341 case Stmt::CXXBoolLiteralExprClass:
9342 case Stmt::DeclRefExprClass:
9343 case Stmt::FloatingLiteralClass:
9344 case Stmt::IntegerLiteralClass:
9345 case Stmt::MemberExprClass:
9346 case Stmt::ObjCArrayLiteralClass:
9347 case Stmt::ObjCBoolLiteralExprClass:
9348 case Stmt::ObjCBoxedExprClass:
9349 case Stmt::ObjCDictionaryLiteralClass:
9350 case Stmt::ObjCEncodeExprClass:
9351 case Stmt::ObjCIvarRefExprClass:
9352 case Stmt::ObjCMessageExprClass:
9353 case Stmt::ObjCPropertyRefExprClass:
9354 case Stmt::ObjCStringLiteralClass:
9355 case Stmt::ObjCSubscriptRefExprClass:
9356 case Stmt::ParenExprClass:
9357 case Stmt::StringLiteralClass:
9358 case Stmt::UnaryOperatorClass:
9359 return false;
9360 default:
9361 return true;
9362 }
9363}
9364
9365static std::pair<QualType, StringRef>
9366shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9367 const Expr *E) {
9368 // Use a 'while' to peel off layers of typedefs.
9369 QualType TyTy = IntendedTy;
9370 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9371 StringRef Name = UserTy->getDecl()->getName();
9372 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9373 .Case("CFIndex", Context.getNSIntegerType())
9374 .Case("NSInteger", Context.getNSIntegerType())
9375 .Case("NSUInteger", Context.getNSUIntegerType())
9376 .Case("SInt32", Context.IntTy)
9377 .Case("UInt32", Context.UnsignedIntTy)
9378 .Default(QualType());
9379
9380 if (!CastTy.isNull())
9381 return std::make_pair(CastTy, Name);
9382
9383 TyTy = UserTy->desugar();
9384 }
9385
9386 // Strip parens if necessary.
9387 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9388 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9389 PE->getSubExpr());
9390
9391 // If this is a conditional expression, then its result type is constructed
9392 // via usual arithmetic conversions and thus there might be no necessary
9393 // typedef sugar there. Recurse to operands to check for NSInteger &
9394 // Co. usage condition.
9395 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9396 QualType TrueTy, FalseTy;
9397 StringRef TrueName, FalseName;
9398
9399 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9400 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9401 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9402 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9403
9404 if (TrueTy == FalseTy)
9405 return std::make_pair(TrueTy, TrueName);
9406 else if (TrueTy.isNull())
9407 return std::make_pair(FalseTy, FalseName);
9408 else if (FalseTy.isNull())
9409 return std::make_pair(TrueTy, TrueName);
9410 }
9411
9412 return std::make_pair(QualType(), StringRef());
9413}
9414
9415/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9416/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9417/// type do not count.
9419 const ImplicitCastExpr *ICE) {
9420 QualType From = ICE->getSubExpr()->getType();
9421 QualType To = ICE->getType();
9422 // It's an integer promotion if the destination type is the promoted
9423 // source type.
9424 if (ICE->getCastKind() == CK_IntegralCast &&
9426 S.Context.getPromotedIntegerType(From) == To)
9427 return true;
9428 // Look through vector types, since we do default argument promotion for
9429 // those in OpenCL.
9430 if (const auto *VecTy = From->getAs<ExtVectorType>())
9431 From = VecTy->getElementType();
9432 if (const auto *VecTy = To->getAs<ExtVectorType>())
9433 To = VecTy->getElementType();
9434 // It's a floating promotion if the source type is a lower rank.
9435 return ICE->getCastKind() == CK_FloatingCast &&
9436 S.Context.getFloatingTypeOrder(From, To) < 0;
9437}
9438
9441 DiagnosticsEngine &Diags, SourceLocation Loc) {
9443 if (Diags.isIgnored(
9444 diag::warn_format_conversion_argument_type_mismatch_signedness,
9445 Loc) ||
9446 Diags.isIgnored(
9447 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9448 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9450 }
9451 }
9452 return Match;
9453}
9454
9455bool CheckPrintfHandler::checkFormatExpr(
9456 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9457 unsigned SpecifierLen, const Expr *E) {
9458 using namespace analyze_format_string;
9459 using namespace analyze_printf;
9460
9461 // Now type check the data expression that matches the
9462 // format specifier.
9463 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9464 if (!AT.isValid())
9465 return true;
9466
9467 QualType ExprTy = E->getType();
9468 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9469 ExprTy = TET->getUnderlyingExpr()->getType();
9470 }
9471
9472 if (const OverflowBehaviorType *OBT =
9473 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9474 ExprTy = OBT->getUnderlyingType();
9475
9476 // When using the format attribute in C++, you can receive a function or an
9477 // array that will necessarily decay to a pointer when passed to the final
9478 // format consumer. Apply decay before type comparison.
9479 if (ExprTy->canDecayToPointerType())
9480 ExprTy = S.Context.getDecayedType(ExprTy);
9481
9482 // Diagnose attempts to print a boolean value as a character. Unlike other
9483 // -Wformat diagnostics, this is fine from a type perspective, but it still
9484 // doesn't make sense.
9487 const CharSourceRange &CSR =
9488 getSpecifierRange(StartSpecifier, SpecifierLen);
9489 SmallString<4> FSString;
9490 llvm::raw_svector_ostream os(FSString);
9491 FS.toString(os);
9492 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9493 << FSString,
9494 E->getExprLoc(), false, CSR);
9495 return true;
9496 }
9497
9498 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9499 // dumping raw class data (like is-a pointer), not actual data.
9501 ExprTy->isObjCObjectPointerType()) {
9502 const CharSourceRange &CSR =
9503 getSpecifierRange(StartSpecifier, SpecifierLen);
9504 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9505 E->getExprLoc(), false, CSR);
9506 return true;
9507 }
9508
9509 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9510 return true;
9511
9512 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9514 ArgType::MatchKind OrigMatch = Match;
9515
9517 if (Match == ArgType::Match)
9518 return true;
9519
9520 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9521 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9522
9523 // Look through argument promotions for our error message's reported type.
9524 // This includes the integral and floating promotions, but excludes array
9525 // and function pointer decay (seeing that an argument intended to be a
9526 // string has type 'char [6]' is probably more confusing than 'char *') and
9527 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9528 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9529 if (isArithmeticArgumentPromotion(S, ICE)) {
9530 E = ICE->getSubExpr();
9531 ExprTy = E->getType();
9532
9533 // Check if we didn't match because of an implicit cast from a 'char'
9534 // or 'short' to an 'int'. This is done because printf is a varargs
9535 // function.
9536 if (ICE->getType() == S.Context.IntTy ||
9537 ICE->getType() == S.Context.UnsignedIntTy) {
9538 // All further checking is done on the subexpression
9539 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9540 if (OrigMatch == ArgType::NoMatchSignedness &&
9541 ImplicitMatch != ArgType::NoMatchSignedness)
9542 // If the original match was a signedness match this match on the
9543 // implicit cast type also need to be signedness match otherwise we
9544 // might introduce new unexpected warnings from -Wformat-signedness.
9545 return true;
9546 ImplicitMatch = handleFormatSignedness(
9547 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9548 if (ImplicitMatch == ArgType::Match)
9549 return true;
9550 }
9551 }
9552 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9553 // Special case for 'a', which has type 'int' in C.
9554 // Note, however, that we do /not/ want to treat multibyte constants like
9555 // 'MooV' as characters! This form is deprecated but still exists. In
9556 // addition, don't treat expressions as of type 'char' if one byte length
9557 // modifier is provided.
9558 if (ExprTy == S.Context.IntTy &&
9560 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9561 ExprTy = S.Context.CharTy;
9562 // To improve check results, we consider a character literal in C
9563 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9564 // more likely a type confusion situation, so we will suggest to
9565 // use '%hhd' instead by discarding the MatchPromotion.
9566 if (Match == ArgType::MatchPromotion)
9568 }
9569 }
9570 if (Match == ArgType::MatchPromotion) {
9571 // WG14 N2562 only clarified promotions in *printf
9572 // For NSLog in ObjC, just preserve -Wformat behavior
9573 if (!S.getLangOpts().ObjC &&
9574 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9575 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9576 return true;
9578 }
9579 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9580 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9581 Match = ImplicitMatch;
9582 assert(Match != ArgType::MatchPromotion);
9583
9584 // Look through unscoped enums to their underlying type.
9585 bool IsEnum = false;
9586 bool IsScopedEnum = false;
9587 QualType IntendedTy = ExprTy;
9588 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9589 IntendedTy = ED->getIntegerType();
9590 if (!ED->isScoped()) {
9591 ExprTy = IntendedTy;
9592 // This controls whether we're talking about the underlying type or not,
9593 // which we only want to do when it's an unscoped enum.
9594 IsEnum = true;
9595 } else {
9596 IsScopedEnum = true;
9597 }
9598 }
9599
9600 // %C in an Objective-C context prints a unichar, not a wchar_t.
9601 // If the argument is an integer of some kind, believe the %C and suggest
9602 // a cast instead of changing the conversion specifier.
9603 if (isObjCContext() &&
9606 !ExprTy->isCharType()) {
9607 // 'unichar' is defined as a typedef of unsigned short, but we should
9608 // prefer using the typedef if it is visible.
9609 IntendedTy = S.Context.UnsignedShortTy;
9610
9611 // While we are here, check if the value is an IntegerLiteral that happens
9612 // to be within the valid range.
9613 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9614 const llvm::APInt &V = IL->getValue();
9615 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9616 return true;
9617 }
9618
9619 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9621 if (S.LookupName(Result, S.getCurScope())) {
9622 NamedDecl *ND = Result.getFoundDecl();
9623 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9624 if (TD->getUnderlyingType() == IntendedTy)
9625 IntendedTy =
9627 /*Qualifier=*/std::nullopt, TD);
9628 }
9629 }
9630 }
9631
9632 // Special-case some of Darwin's platform-independence types by suggesting
9633 // casts to primitive types that are known to be large enough.
9634 bool ShouldNotPrintDirectly = false;
9635 StringRef CastTyName;
9636 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9637 QualType CastTy;
9638 std::tie(CastTy, CastTyName) =
9639 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9640 if (!CastTy.isNull()) {
9641 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9642 // (long in ASTContext). Only complain to pedants or when they're the
9643 // underlying type of a scoped enum (which always needs a cast).
9644 if (!IsScopedEnum &&
9645 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9646 (AT.isSizeT() || AT.isPtrdiffT()) &&
9647 AT.matchesType(S.Context, CastTy))
9649 IntendedTy = CastTy;
9650 ShouldNotPrintDirectly = true;
9651 }
9652 }
9653
9654 // We may be able to offer a FixItHint if it is a supported type.
9655 PrintfSpecifier fixedFS = FS;
9656 bool Success =
9657 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9658
9659 if (Success) {
9660 // Get the fix string from the fixed format specifier
9661 SmallString<16> buf;
9662 llvm::raw_svector_ostream os(buf);
9663 fixedFS.toString(os);
9664
9665 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9666
9667 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9668 unsigned Diag;
9669 switch (Match) {
9670 case ArgType::Match:
9673 llvm_unreachable("expected non-matching");
9675 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9676 break;
9678 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9679 break;
9681 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9682 break;
9683 case ArgType::NoMatch:
9684 Diag = diag::warn_format_conversion_argument_type_mismatch;
9685 break;
9686 }
9687
9688 // In this case, the specifier is wrong and should be changed to match
9689 // the argument.
9690 EmitFormatDiagnostic(S.PDiag(Diag)
9692 << IntendedTy << IsEnum << E->getSourceRange(),
9693 E->getBeginLoc(),
9694 /*IsStringLocation*/ false, SpecRange,
9695 FixItHint::CreateReplacement(SpecRange, os.str()));
9696 } else {
9697 // The canonical type for formatting this value is different from the
9698 // actual type of the expression. (This occurs, for example, with Darwin's
9699 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9700 // should be printed as 'long' for 64-bit compatibility.)
9701 // Rather than emitting a normal format/argument mismatch, we want to
9702 // add a cast to the recommended type (and correct the format string
9703 // if necessary). We should also do so for scoped enumerations.
9704 SmallString<16> CastBuf;
9705 llvm::raw_svector_ostream CastFix(CastBuf);
9706 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9707 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9708 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9709
9711 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9712 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9713 E->getExprLoc());
9714 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9715 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9716
9717 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9718 // If there's already a cast present, just replace it.
9719 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9720 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9721
9722 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9723 // If the expression has high enough precedence,
9724 // just write the C-style cast.
9725 Hints.push_back(
9726 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9727 } else {
9728 // Otherwise, add parens around the expression as well as the cast.
9729 CastFix << "(";
9730 Hints.push_back(
9731 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9732
9733 // We don't use getLocForEndOfToken because it returns invalid source
9734 // locations for macro expansions (by design).
9738 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9739 }
9740
9741 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9742 // The expression has a type that should not be printed directly.
9743 // We extract the name from the typedef because we don't want to show
9744 // the underlying type in the diagnostic.
9745 StringRef Name;
9746 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9747 Name = TypedefTy->getDecl()->getName();
9748 else
9749 Name = CastTyName;
9750 unsigned Diag = Match == ArgType::NoMatchPedantic
9751 ? diag::warn_format_argument_needs_cast_pedantic
9752 : diag::warn_format_argument_needs_cast;
9753 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9754 << E->getSourceRange(),
9755 E->getBeginLoc(), /*IsStringLocation=*/false,
9756 SpecRange, Hints);
9757 } else {
9758 // In this case, the expression could be printed using a different
9759 // specifier, but we've decided that the specifier is probably correct
9760 // and we should cast instead. Just use the normal warning message.
9761
9762 unsigned Diag =
9763 IsScopedEnum
9764 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9765 : diag::warn_format_conversion_argument_type_mismatch;
9766
9767 EmitFormatDiagnostic(
9768 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9769 << IsEnum << E->getSourceRange(),
9770 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9771 }
9772 }
9773 } else {
9774 const CharSourceRange &CSR =
9775 getSpecifierRange(StartSpecifier, SpecifierLen);
9776 // Since the warning for passing non-POD types to variadic functions
9777 // was deferred until now, we emit a warning for non-POD
9778 // arguments here.
9779 bool EmitTypeMismatch = false;
9780 // Record and complex type arguments cannot be code generated for os_log
9781 // and would crash CodeGen, so they are rejected with a hard error emitted
9782 // after the switch below.
9783 bool EmitOSLogError = false;
9784 switch (S.isValidVarArgType(ExprTy)) {
9785 case VarArgKind::Valid:
9787 unsigned Diag;
9788 switch (Match) {
9789 case ArgType::Match:
9792 llvm_unreachable("expected non-matching");
9794 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9795 break;
9797 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9798 break;
9800 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9801 break;
9802 case ArgType::NoMatch:
9803 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
9804 Diag = diag::warn_format_conversion_argument_type_mismatch;
9805 break;
9806 }
9807
9808 if (!EmitOSLogError)
9809 EmitFormatDiagnostic(
9810 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9811 << IsEnum << CSR << E->getSourceRange(),
9812 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9813 break;
9814 }
9817 if (CallType == VariadicCallType::DoesNotApply) {
9818 EmitTypeMismatch = true;
9819 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
9820 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9821 // does not stop compilation.
9822 EmitOSLogError = true;
9823 } else {
9824 EmitFormatDiagnostic(
9825 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9826 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9827 << AT.getRepresentativeTypeName(S.Context) << CSR
9828 << E->getSourceRange(),
9829 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9830 checkForCStrMembers(AT, E);
9831 }
9832 break;
9833
9835 if (CallType == VariadicCallType::DoesNotApply)
9836 EmitTypeMismatch = true;
9837 else if (ExprTy->isObjCObjectType())
9838 EmitFormatDiagnostic(
9839 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9840 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9841 << AT.getRepresentativeTypeName(S.Context) << CSR
9842 << E->getSourceRange(),
9843 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9844 else
9845 // FIXME: If this is an initializer list, suggest removing the braces
9846 // or inserting a cast to the target type.
9847 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9848 << isa<InitListExpr>(E) << ExprTy << CallType
9850 break;
9851 }
9852
9853 if (EmitOSLogError)
9854 EmitFormatDiagnostic(
9855 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
9856 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9857 << CSR << E->getSourceRange(),
9858 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9859
9860 if (EmitTypeMismatch) {
9861 // The function is not variadic, so we do not generate warnings about
9862 // being allowed to pass that object as a variadic argument. Instead,
9863 // since there are inherently no printf specifiers for types which cannot
9864 // be passed as variadic arguments, emit a plain old specifier mismatch
9865 // argument.
9866 EmitFormatDiagnostic(
9867 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9868 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9869 << E->getSourceRange(),
9870 E->getBeginLoc(), false, CSR);
9871 }
9872
9873 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9874 "format string specifier index out of range");
9875 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9876 }
9877
9878 return true;
9879}
9880
9881//===--- CHECK: Scanf format string checking ------------------------------===//
9882
9883namespace {
9884
9885class CheckScanfHandler : public CheckFormatHandler {
9886public:
9887 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9888 const Expr *origFormatExpr, FormatStringType type,
9889 unsigned firstDataArg, unsigned numDataArgs,
9890 const char *beg, Sema::FormatArgumentPassingKind APK,
9891 ArrayRef<const Expr *> Args, unsigned formatIdx,
9892 bool inFunctionCall, VariadicCallType CallType,
9893 llvm::SmallBitVector &CheckedVarArgs,
9894 UncoveredArgHandler &UncoveredArg)
9895 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9896 numDataArgs, beg, APK, Args, formatIdx,
9897 inFunctionCall, CallType, CheckedVarArgs,
9898 UncoveredArg) {}
9899
9900 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9901 const char *startSpecifier,
9902 unsigned specifierLen) override;
9903
9904 bool
9905 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9906 const char *startSpecifier,
9907 unsigned specifierLen) override;
9908
9909 void HandleIncompleteScanList(const char *start, const char *end) override;
9910};
9911
9912} // namespace
9913
9914void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9915 const char *end) {
9916 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9917 getLocationOfByte(end), /*IsStringLocation*/ true,
9918 getSpecifierRange(start, end - start));
9919}
9920
9921bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9922 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9923 unsigned specifierLen) {
9926
9927 return HandleInvalidConversionSpecifier(
9928 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9929 specifierLen, CS.getStart(), CS.getLength());
9930}
9931
9932bool CheckScanfHandler::HandleScanfSpecifier(
9933 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9934 unsigned specifierLen) {
9935 using namespace analyze_scanf;
9936 using namespace analyze_format_string;
9937
9938 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9939
9940 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9941 // be used to decide if we are using positional arguments consistently.
9942 if (FS.consumesDataArgument()) {
9943 if (atFirstArg) {
9944 atFirstArg = false;
9945 usesPositionalArgs = FS.usesPositionalArg();
9946 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9947 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9948 startSpecifier, specifierLen);
9949 return false;
9950 }
9951 }
9952
9953 // Check if the field with is non-zero.
9954 const OptionalAmount &Amt = FS.getFieldWidth();
9956 if (Amt.getConstantAmount() == 0) {
9957 const CharSourceRange &R =
9958 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9959 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9960 getLocationOfByte(Amt.getStart()),
9961 /*IsStringLocation*/ true, R,
9963 }
9964 }
9965
9966 if (!FS.consumesDataArgument()) {
9967 // FIXME: Technically specifying a precision or field width here
9968 // makes no sense. Worth issuing a warning at some point.
9969 return true;
9970 }
9971
9972 // Consume the argument.
9973 unsigned argIndex = FS.getArgIndex();
9974 if (argIndex < NumDataArgs) {
9975 // The check to see if the argIndex is valid will come later.
9976 // We set the bit here because we may exit early from this
9977 // function if we encounter some other error.
9978 CoveredArgs.set(argIndex);
9979 }
9980
9981 // Check the length modifier is valid with the given conversion specifier.
9983 S.getLangOpts()))
9984 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9985 diag::warn_format_nonsensical_length);
9986 else if (!FS.hasStandardLengthModifier())
9987 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9989 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9990 diag::warn_format_non_standard_conversion_spec);
9991
9993 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9994
9995 // The remaining checks depend on the data arguments.
9996 if (!HasFormatArguments())
9997 return true;
9998
9999 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10000 return false;
10001
10002 // Check that the argument type matches the format specifier.
10003 const Expr *Ex = getDataArg(argIndex);
10004 if (!Ex)
10005 return true;
10006
10008
10009 if (!AT.isValid()) {
10010 return true;
10011 }
10012
10013 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10014 return true;
10015
10017 AT.matchesType(S.Context, Ex->getType());
10020 return true;
10023
10024 ScanfSpecifier fixedFS = FS;
10025 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10026 S.getLangOpts(), S.Context);
10027
10028 unsigned Diag =
10029 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10030 : Signedness
10031 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10032 : diag::warn_format_conversion_argument_type_mismatch;
10033
10034 if (Success) {
10035 // Get the fix string from the fixed format specifier.
10036 SmallString<128> buf;
10037 llvm::raw_svector_ostream os(buf);
10038 fixedFS.toString(os);
10039
10040 EmitFormatDiagnostic(
10042 << Ex->getType() << false << Ex->getSourceRange(),
10043 Ex->getBeginLoc(),
10044 /*IsStringLocation*/ false,
10045 getSpecifierRange(startSpecifier, specifierLen),
10047 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10048 } else {
10049 EmitFormatDiagnostic(S.PDiag(Diag)
10051 << Ex->getType() << false << Ex->getSourceRange(),
10052 Ex->getBeginLoc(),
10053 /*IsStringLocation*/ false,
10054 getSpecifierRange(startSpecifier, specifierLen));
10055 }
10056
10057 return true;
10058}
10059
10060static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10062 const StringLiteral *Fmt,
10064 const Expr *FmtExpr, bool InFunctionCall) {
10065 bool HadError = false;
10066 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10067 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10068 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10069 // In positional-style format strings, the same specifier can appear
10070 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10071 // are sorted by getPosition(), and we process each range of equal
10072 // getPosition() values as one group.
10073 // RefArgs are taken from a string literal that was given to
10074 // attribute(format_matches), and if we got this far, we have already
10075 // verified that if it has positional specifiers that appear in multiple
10076 // locations, then they are all mutually compatible. What's left for us to
10077 // do is verify that all specifiers with the same position in FmtArgs are
10078 // compatible with the RefArgs specifiers. We check each specifier from
10079 // FmtArgs against the first member of the RefArgs group.
10080 for (; FmtIter < FmtEnd; ++FmtIter) {
10081 // Clang does not diagnose missing format specifiers in positional-style
10082 // strings (TODO: which it probably should do, as it is UB to skip over a
10083 // format argument). Skip specifiers if needed.
10084 if (FmtIter->getPosition() < RefIter->getPosition())
10085 continue;
10086
10087 // Delimits a new getPosition() value.
10088 if (FmtIter->getPosition() > RefIter->getPosition())
10089 break;
10090
10091 HadError |=
10092 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10093 }
10094
10095 // Jump RefIter to the start of the next group.
10096 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
10097 return Arg.getPosition() != RefIter->getPosition();
10098 });
10099 }
10100
10101 if (FmtIter < FmtEnd) {
10102 CheckFormatHandler::EmitFormatDiagnostic(
10103 S, InFunctionCall, FmtExpr,
10104 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10105 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
10106 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
10107 } else if (RefIter < RefEnd) {
10108 CheckFormatHandler::EmitFormatDiagnostic(
10109 S, InFunctionCall, FmtExpr,
10110 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10111 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
10112 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
10113 << 1 << RefIter->getSourceRange();
10114 }
10115 return !HadError;
10116}
10117
10119 Sema &S, const FormatStringLiteral *FExpr,
10120 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10122 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10123 bool inFunctionCall, VariadicCallType CallType,
10124 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10125 bool IgnoreStringsWithoutSpecifiers) {
10126 // CHECK: is the format string a wide literal?
10127 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10128 CheckFormatHandler::EmitFormatDiagnostic(
10129 S, inFunctionCall, Args[format_idx],
10130 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10131 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10132 return;
10133 }
10134
10135 // Str - The format string. NOTE: this is NOT null-terminated!
10136 StringRef StrRef = FExpr->getString();
10137 const char *Str = StrRef.data();
10138 // Account for cases where the string literal is truncated in a declaration.
10139 const ConstantArrayType *T =
10140 S.Context.getAsConstantArrayType(FExpr->getType());
10141 assert(T && "String literal not of constant array type!");
10142 size_t TypeSize = T->getZExtSize();
10143 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10144 const unsigned numDataArgs = Args.size() - firstDataArg;
10145
10146 if (IgnoreStringsWithoutSpecifiers &&
10148 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10149 return;
10150
10151 // Emit a warning if the string literal is truncated and does not contain an
10152 // embedded null character.
10153 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10154 CheckFormatHandler::EmitFormatDiagnostic(
10155 S, inFunctionCall, Args[format_idx],
10156 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10157 FExpr->getBeginLoc(),
10158 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10159 return;
10160 }
10161
10162 // CHECK: empty format string?
10163 if (StrLen == 0 && numDataArgs > 0) {
10164 CheckFormatHandler::EmitFormatDiagnostic(
10165 S, inFunctionCall, Args[format_idx],
10166 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10167 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10168 return;
10169 }
10170
10175 bool IsObjC =
10177 if (ReferenceFormatString == nullptr) {
10178 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10179 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10180 inFunctionCall, CallType, CheckedVarArgs,
10181 UncoveredArg);
10182
10184 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10187 H.DoneProcessing();
10188 } else {
10190 Type, ReferenceFormatString, FExpr->getFormatString(),
10191 inFunctionCall ? nullptr : Args[format_idx]);
10192 }
10193 } else if (Type == FormatStringType::Scanf) {
10194 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10195 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10196 CallType, CheckedVarArgs, UncoveredArg);
10197
10199 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10200 H.DoneProcessing();
10201 } // TODO: handle other formats
10202}
10203
10205 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10206 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10211 return true;
10212
10213 bool IsObjC =
10216 FormatStringLiteral RefLit = AuthoritativeFormatString;
10217 FormatStringLiteral TestLit = TestedFormatString;
10218 const Expr *Arg;
10219 bool DiagAtStringLiteral;
10220 if (FunctionCallArg) {
10221 Arg = FunctionCallArg;
10222 DiagAtStringLiteral = false;
10223 } else {
10224 Arg = TestedFormatString;
10225 DiagAtStringLiteral = true;
10226 }
10227 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10228 AuthoritativeFormatString, Type,
10229 IsObjC, true, RefArgs) &&
10230 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10231 DiagAtStringLiteral, FmtArgs)) {
10232 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10233 TestedFormatString, FmtArgs, Arg,
10234 DiagAtStringLiteral);
10235 }
10236 return false;
10237}
10238
10240 const StringLiteral *Str) {
10245 return true;
10246
10247 FormatStringLiteral RefLit = Str;
10249 bool IsObjC =
10251 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10252 true, Args))
10253 return false;
10254
10255 // Group arguments by getPosition() value, and check that each member of the
10256 // group is compatible with the first member. This verifies that when
10257 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10258 // are mutually compatible. As an optimization, don't test the first member
10259 // against itself.
10260 bool HadError = false;
10261 auto Iter = Args.begin();
10262 auto End = Args.end();
10263 while (Iter != End) {
10264 const auto &FirstInGroup = *Iter;
10265 for (++Iter;
10266 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10267 ++Iter) {
10268 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10269 }
10270 }
10271 return !HadError;
10272}
10273
10275 // Str - The format string. NOTE: this is NOT null-terminated!
10276 StringRef StrRef = FExpr->getString();
10277 const char *Str = StrRef.data();
10278 // Account for cases where the string literal is truncated in a declaration.
10279 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10280 assert(T && "String literal not of constant array type!");
10281 size_t TypeSize = T->getZExtSize();
10282 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10284 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10285}
10286
10287//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10288
10289// Returns the related absolute value function that is larger, of 0 if one
10290// does not exist.
10291static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10292 switch (AbsFunction) {
10293 default:
10294 return 0;
10295
10296 case Builtin::BI__builtin_abs:
10297 return Builtin::BI__builtin_labs;
10298 case Builtin::BI__builtin_labs:
10299 return Builtin::BI__builtin_llabs;
10300 case Builtin::BI__builtin_llabs:
10301 return 0;
10302
10303 case Builtin::BI__builtin_fabsf:
10304 return Builtin::BI__builtin_fabs;
10305 case Builtin::BI__builtin_fabs:
10306 return Builtin::BI__builtin_fabsl;
10307 case Builtin::BI__builtin_fabsl:
10308 return 0;
10309
10310 case Builtin::BI__builtin_cabsf:
10311 return Builtin::BI__builtin_cabs;
10312 case Builtin::BI__builtin_cabs:
10313 return Builtin::BI__builtin_cabsl;
10314 case Builtin::BI__builtin_cabsl:
10315 return 0;
10316
10317 case Builtin::BIabs:
10318 return Builtin::BIlabs;
10319 case Builtin::BIlabs:
10320 return Builtin::BIllabs;
10321 case Builtin::BIllabs:
10322 return 0;
10323
10324 case Builtin::BIfabsf:
10325 return Builtin::BIfabs;
10326 case Builtin::BIfabs:
10327 return Builtin::BIfabsl;
10328 case Builtin::BIfabsl:
10329 return 0;
10330
10331 case Builtin::BIcabsf:
10332 return Builtin::BIcabs;
10333 case Builtin::BIcabs:
10334 return Builtin::BIcabsl;
10335 case Builtin::BIcabsl:
10336 return 0;
10337 }
10338}
10339
10340// Returns the argument type of the absolute value function.
10342 unsigned AbsType) {
10343 if (AbsType == 0)
10344 return QualType();
10345
10347 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10349 return QualType();
10350
10352 if (!FT)
10353 return QualType();
10354
10355 if (FT->getNumParams() != 1)
10356 return QualType();
10357
10358 return FT->getParamType(0);
10359}
10360
10361// Returns the best absolute value function, or zero, based on type and
10362// current absolute value function.
10363static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10364 unsigned AbsFunctionKind) {
10365 unsigned BestKind = 0;
10366 uint64_t ArgSize = Context.getTypeSize(ArgType);
10367 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10368 Kind = getLargerAbsoluteValueFunction(Kind)) {
10369 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10370 if (Context.getTypeSize(ParamType) >= ArgSize) {
10371 if (BestKind == 0)
10372 BestKind = Kind;
10373 else if (Context.hasSameType(ParamType, ArgType)) {
10374 BestKind = Kind;
10375 break;
10376 }
10377 }
10378 }
10379 return BestKind;
10380}
10381
10387
10389 if (T->isIntegralOrEnumerationType())
10390 return AVK_Integer;
10391 if (T->isRealFloatingType())
10392 return AVK_Floating;
10393 if (T->isAnyComplexType())
10394 return AVK_Complex;
10395
10396 llvm_unreachable("Type not integer, floating, or complex");
10397}
10398
10399// Changes the absolute value function to a different type. Preserves whether
10400// the function is a builtin.
10401static unsigned changeAbsFunction(unsigned AbsKind,
10402 AbsoluteValueKind ValueKind) {
10403 switch (ValueKind) {
10404 case AVK_Integer:
10405 switch (AbsKind) {
10406 default:
10407 return 0;
10408 case Builtin::BI__builtin_fabsf:
10409 case Builtin::BI__builtin_fabs:
10410 case Builtin::BI__builtin_fabsl:
10411 case Builtin::BI__builtin_cabsf:
10412 case Builtin::BI__builtin_cabs:
10413 case Builtin::BI__builtin_cabsl:
10414 return Builtin::BI__builtin_abs;
10415 case Builtin::BIfabsf:
10416 case Builtin::BIfabs:
10417 case Builtin::BIfabsl:
10418 case Builtin::BIcabsf:
10419 case Builtin::BIcabs:
10420 case Builtin::BIcabsl:
10421 return Builtin::BIabs;
10422 }
10423 case AVK_Floating:
10424 switch (AbsKind) {
10425 default:
10426 return 0;
10427 case Builtin::BI__builtin_abs:
10428 case Builtin::BI__builtin_labs:
10429 case Builtin::BI__builtin_llabs:
10430 case Builtin::BI__builtin_cabsf:
10431 case Builtin::BI__builtin_cabs:
10432 case Builtin::BI__builtin_cabsl:
10433 return Builtin::BI__builtin_fabsf;
10434 case Builtin::BIabs:
10435 case Builtin::BIlabs:
10436 case Builtin::BIllabs:
10437 case Builtin::BIcabsf:
10438 case Builtin::BIcabs:
10439 case Builtin::BIcabsl:
10440 return Builtin::BIfabsf;
10441 }
10442 case AVK_Complex:
10443 switch (AbsKind) {
10444 default:
10445 return 0;
10446 case Builtin::BI__builtin_abs:
10447 case Builtin::BI__builtin_labs:
10448 case Builtin::BI__builtin_llabs:
10449 case Builtin::BI__builtin_fabsf:
10450 case Builtin::BI__builtin_fabs:
10451 case Builtin::BI__builtin_fabsl:
10452 return Builtin::BI__builtin_cabsf;
10453 case Builtin::BIabs:
10454 case Builtin::BIlabs:
10455 case Builtin::BIllabs:
10456 case Builtin::BIfabsf:
10457 case Builtin::BIfabs:
10458 case Builtin::BIfabsl:
10459 return Builtin::BIcabsf;
10460 }
10461 }
10462 llvm_unreachable("Unable to convert function");
10463}
10464
10465static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10466 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10467 if (!FnInfo)
10468 return 0;
10469
10470 switch (FDecl->getBuiltinID()) {
10471 default:
10472 return 0;
10473 case Builtin::BI__builtin_abs:
10474 case Builtin::BI__builtin_fabs:
10475 case Builtin::BI__builtin_fabsf:
10476 case Builtin::BI__builtin_fabsl:
10477 case Builtin::BI__builtin_labs:
10478 case Builtin::BI__builtin_llabs:
10479 case Builtin::BI__builtin_cabs:
10480 case Builtin::BI__builtin_cabsf:
10481 case Builtin::BI__builtin_cabsl:
10482 case Builtin::BIabs:
10483 case Builtin::BIlabs:
10484 case Builtin::BIllabs:
10485 case Builtin::BIfabs:
10486 case Builtin::BIfabsf:
10487 case Builtin::BIfabsl:
10488 case Builtin::BIcabs:
10489 case Builtin::BIcabsf:
10490 case Builtin::BIcabsl:
10491 return FDecl->getBuiltinID();
10492 }
10493 llvm_unreachable("Unknown Builtin type");
10494}
10495
10496// If the replacement is valid, emit a note with replacement function.
10497// Additionally, suggest including the proper header if not already included.
10499 unsigned AbsKind, QualType ArgType) {
10500 bool EmitHeaderHint = true;
10501 const char *HeaderName = nullptr;
10502 std::string FunctionName;
10503 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10504 FunctionName = "std::abs";
10505 if (ArgType->isIntegralOrEnumerationType()) {
10506 HeaderName = "cstdlib";
10507 } else if (ArgType->isRealFloatingType()) {
10508 HeaderName = "cmath";
10509 } else {
10510 llvm_unreachable("Invalid Type");
10511 }
10512
10513 // Lookup all std::abs
10514 if (NamespaceDecl *Std = S.getStdNamespace()) {
10515 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10516 R.suppressDiagnostics();
10517 S.LookupQualifiedName(R, Std);
10518
10519 for (const auto *I : R) {
10520 const FunctionDecl *FDecl = nullptr;
10521 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10522 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10523 } else {
10524 FDecl = dyn_cast<FunctionDecl>(I);
10525 }
10526 if (!FDecl)
10527 continue;
10528
10529 // Found std::abs(), check that they are the right ones.
10530 if (FDecl->getNumParams() != 1)
10531 continue;
10532
10533 // Check that the parameter type can handle the argument.
10534 QualType ParamType = FDecl->getParamDecl(0)->getType();
10535 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10536 S.Context.getTypeSize(ArgType) <=
10537 S.Context.getTypeSize(ParamType)) {
10538 // Found a function, don't need the header hint.
10539 EmitHeaderHint = false;
10540 break;
10541 }
10542 }
10543 }
10544 } else {
10545 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10546 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10547
10548 if (HeaderName) {
10549 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10550 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10551 R.suppressDiagnostics();
10552 S.LookupName(R, S.getCurScope());
10553
10554 if (R.isSingleResult()) {
10555 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10556 if (FD && FD->getBuiltinID() == AbsKind) {
10557 EmitHeaderHint = false;
10558 } else {
10559 return;
10560 }
10561 } else if (!R.empty()) {
10562 return;
10563 }
10564 }
10565 }
10566
10567 S.Diag(Loc, diag::note_replace_abs_function)
10568 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10569
10570 if (!HeaderName)
10571 return;
10572
10573 if (!EmitHeaderHint)
10574 return;
10575
10576 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10577 << FunctionName;
10578}
10579
10580template <std::size_t StrLen>
10581static bool IsStdFunction(const FunctionDecl *FDecl,
10582 const char (&Str)[StrLen]) {
10583 if (!FDecl)
10584 return false;
10585 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10586 return false;
10587 if (!FDecl->isInStdNamespace())
10588 return false;
10589
10590 return true;
10591}
10592
10593enum class MathCheck { NaN, Inf };
10594static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10595 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10596 return llvm::is_contained(names, calleeName);
10597 };
10598
10599 switch (Check) {
10600 case MathCheck::NaN:
10601 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10602 "__builtin_nanf16", "__builtin_nanf128"});
10603 case MathCheck::Inf:
10604 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10605 "__builtin_inff16", "__builtin_inff128"});
10606 }
10607 llvm_unreachable("unknown MathCheck");
10608}
10609
10610static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10611 if (FDecl->getName() != "infinity")
10612 return false;
10613
10614 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10615 const CXXRecordDecl *RDecl = MDecl->getParent();
10616 if (RDecl->getName() != "numeric_limits")
10617 return false;
10618
10619 if (const NamespaceDecl *NSDecl =
10620 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10621 return NSDecl->isStdNamespace();
10622 }
10623
10624 return false;
10625}
10626
10627void Sema::CheckInfNaNFunction(const CallExpr *Call,
10628 const FunctionDecl *FDecl) {
10629 if (!FDecl->getIdentifier())
10630 return;
10631
10632 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10633 if (FPO.getNoHonorNaNs() &&
10634 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10636 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10637 << 1 << 0 << Call->getSourceRange();
10638 return;
10639 }
10640
10641 if (FPO.getNoHonorInfs() &&
10642 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10643 IsInfinityFunction(FDecl) ||
10645 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10646 << 0 << 0 << Call->getSourceRange();
10647 }
10648}
10649
10650void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10651 const FunctionDecl *FDecl) {
10652 if (Call->getNumArgs() != 1)
10653 return;
10654
10655 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10656 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10657 if (AbsKind == 0 && !IsStdAbs)
10658 return;
10659
10660 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10661 QualType ParamType = Call->getArg(0)->getType();
10662
10663 // Unsigned types cannot be negative. Suggest removing the absolute value
10664 // function call.
10665 if (ArgType->isUnsignedIntegerType()) {
10666 std::string FunctionName =
10667 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10668 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10669 Diag(Call->getExprLoc(), diag::note_remove_abs)
10670 << FunctionName
10671 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10672 return;
10673 }
10674
10675 // Taking the absolute value of a pointer is very suspicious, they probably
10676 // wanted to index into an array, dereference a pointer, call a function, etc.
10677 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10678 unsigned DiagType = 0;
10679 if (ArgType->isFunctionType())
10680 DiagType = 1;
10681 else if (ArgType->isArrayType())
10682 DiagType = 2;
10683
10684 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10685 return;
10686 }
10687
10688 // std::abs has overloads which prevent most of the absolute value problems
10689 // from occurring.
10690 if (IsStdAbs)
10691 return;
10692
10693 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10694 // types.
10695 if (!ArgType->isIntegralOrEnumerationType() &&
10696 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10697 return;
10698
10699 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10700 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10701
10702 // The argument and parameter are the same kind. Check if they are the right
10703 // size.
10704 if (ArgValueKind == ParamValueKind) {
10705 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10706 return;
10707
10708 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10709 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10710 << FDecl << ArgType << ParamType;
10711
10712 if (NewAbsKind == 0)
10713 return;
10714
10715 emitReplacement(*this, Call->getExprLoc(),
10716 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10717 return;
10718 }
10719
10720 // ArgValueKind != ParamValueKind
10721 // The wrong type of absolute value function was used. Attempt to find the
10722 // proper one.
10723 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10724 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10725 if (NewAbsKind == 0)
10726 return;
10727
10728 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10729 << FDecl << ParamValueKind << ArgValueKind;
10730
10731 emitReplacement(*this, Call->getExprLoc(),
10732 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10733}
10734
10735//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10736void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10737 const FunctionDecl *FDecl) {
10738 if (!Call || !FDecl) return;
10739
10740 // Ignore template specializations and macros.
10741 if (inTemplateInstantiation()) return;
10742 if (Call->getExprLoc().isMacroID()) return;
10743
10744 // Only care about the one template argument, two function parameter std::max
10745 if (Call->getNumArgs() != 2) return;
10746 if (!IsStdFunction(FDecl, "max")) return;
10747 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10748 if (!ArgList) return;
10749 if (ArgList->size() != 1) return;
10750
10751 // Check that template type argument is unsigned integer.
10752 const auto& TA = ArgList->get(0);
10753 if (TA.getKind() != TemplateArgument::Type) return;
10754 QualType ArgType = TA.getAsType();
10755 if (!ArgType->isUnsignedIntegerType()) return;
10756
10757 // See if either argument is a literal zero.
10758 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10759 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10760 if (!MTE) return false;
10761 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10762 if (!Num) return false;
10763 if (Num->getValue() != 0) return false;
10764 return true;
10765 };
10766
10767 const Expr *FirstArg = Call->getArg(0);
10768 const Expr *SecondArg = Call->getArg(1);
10769 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10770 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10771
10772 // Only warn when exactly one argument is zero.
10773 if (IsFirstArgZero == IsSecondArgZero) return;
10774
10775 SourceRange FirstRange = FirstArg->getSourceRange();
10776 SourceRange SecondRange = SecondArg->getSourceRange();
10777
10778 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10779
10780 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10781 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10782
10783 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10784 SourceRange RemovalRange;
10785 if (IsFirstArgZero) {
10786 RemovalRange = SourceRange(FirstRange.getBegin(),
10787 SecondRange.getBegin().getLocWithOffset(-1));
10788 } else {
10789 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10790 SecondRange.getEnd());
10791 }
10792
10793 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10794 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10795 << FixItHint::CreateRemoval(RemovalRange);
10796}
10797
10798//===--- CHECK: Standard memory functions ---------------------------------===//
10799
10800/// Takes the expression passed to the size_t parameter of functions
10801/// such as memcmp, strncat, etc and warns if it's a comparison.
10802///
10803/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10805 const IdentifierInfo *FnName,
10806 SourceLocation FnLoc,
10807 SourceLocation RParenLoc) {
10808 const auto *Size = dyn_cast<BinaryOperator>(E);
10809 if (!Size)
10810 return false;
10811
10812 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10813 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10814 return false;
10815
10816 SourceRange SizeRange = Size->getSourceRange();
10817 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10818 << SizeRange << FnName;
10819 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10820 << FnName
10822 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10823 << FixItHint::CreateRemoval(RParenLoc);
10824 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10825 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10827 ")");
10828
10829 return true;
10830}
10831
10832/// Determine whether the given type is or contains a dynamic class type
10833/// (e.g., whether it has a vtable).
10835 bool &IsContained) {
10836 // Look through array types while ignoring qualifiers.
10837 const Type *Ty = T->getBaseElementTypeUnsafe();
10838 IsContained = false;
10839
10840 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10841 RD = RD ? RD->getDefinition() : nullptr;
10842 if (!RD || RD->isInvalidDecl())
10843 return nullptr;
10844
10845 if (RD->isDynamicClass())
10846 return RD;
10847
10848 // Check all the fields. If any bases were dynamic, the class is dynamic.
10849 // It's impossible for a class to transitively contain itself by value, so
10850 // infinite recursion is impossible.
10851 for (auto *FD : RD->fields()) {
10852 bool SubContained;
10853 if (const CXXRecordDecl *ContainedRD =
10854 getContainedDynamicClass(FD->getType(), SubContained)) {
10855 IsContained = true;
10856 return ContainedRD;
10857 }
10858 }
10859
10860 return nullptr;
10861}
10862
10864 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10865 if (Unary->getKind() == UETT_SizeOf)
10866 return Unary;
10867 return nullptr;
10868}
10869
10870/// If E is a sizeof expression, returns its argument expression,
10871/// otherwise returns NULL.
10872static const Expr *getSizeOfExprArg(const Expr *E) {
10874 if (!SizeOf->isArgumentType())
10875 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10876 return nullptr;
10877}
10878
10879/// If E is a sizeof expression, returns its argument type.
10882 return SizeOf->getTypeOfArgument();
10883 return QualType();
10884}
10885
10886namespace {
10887
10888struct SearchNonTrivialToInitializeField
10889 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10890 using Super =
10891 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10892
10893 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10894
10895 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10896 SourceLocation SL) {
10897 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10898 asDerived().visitArray(PDIK, AT, SL);
10899 return;
10900 }
10901
10902 Super::visitWithKind(PDIK, FT, SL);
10903 }
10904
10905 void visitARCStrong(QualType FT, SourceLocation SL) {
10906 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10907 }
10908 void visitARCWeak(QualType FT, SourceLocation SL) {
10909 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10910 }
10911 void visitStruct(QualType FT, SourceLocation SL) {
10912 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10913 visit(FD->getType(), FD->getLocation());
10914 }
10915 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10916 const ArrayType *AT, SourceLocation SL) {
10917 visit(getContext().getBaseElementType(AT), SL);
10918 }
10919 void visitTrivial(QualType FT, SourceLocation SL) {}
10920
10921 static void diag(QualType RT, const Expr *E, Sema &S) {
10922 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10923 }
10924
10925 ASTContext &getContext() { return S.getASTContext(); }
10926
10927 const Expr *E;
10928 Sema &S;
10929};
10930
10931struct SearchNonTrivialToCopyField
10932 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10933 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10934
10935 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10936
10937 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10938 SourceLocation SL) {
10939 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10940 asDerived().visitArray(PCK, AT, SL);
10941 return;
10942 }
10943
10944 Super::visitWithKind(PCK, FT, SL);
10945 }
10946
10947 void visitARCStrong(QualType FT, SourceLocation SL) {
10948 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10949 }
10950 void visitARCWeak(QualType FT, SourceLocation SL) {
10951 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10952 }
10953 void visitPtrAuth(QualType FT, SourceLocation SL) {
10954 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10955 }
10956 void visitStruct(QualType FT, SourceLocation SL) {
10957 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10958 visit(FD->getType(), FD->getLocation());
10959 }
10960 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10961 SourceLocation SL) {
10962 visit(getContext().getBaseElementType(AT), SL);
10963 }
10964 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10965 SourceLocation SL) {}
10966 void visitTrivial(QualType FT, SourceLocation SL) {}
10967 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10968
10969 static void diag(QualType RT, const Expr *E, Sema &S) {
10970 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10971 }
10972
10973 ASTContext &getContext() { return S.getASTContext(); }
10974
10975 const Expr *E;
10976 Sema &S;
10977};
10978
10979}
10980
10981/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10982static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10983 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10984
10985 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10986 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10987 return false;
10988
10989 return doesExprLikelyComputeSize(BO->getLHS()) ||
10990 doesExprLikelyComputeSize(BO->getRHS());
10991 }
10992
10993 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10994}
10995
10996/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10997///
10998/// \code
10999/// #define MACRO 0
11000/// foo(MACRO);
11001/// foo(0);
11002/// \endcode
11003///
11004/// This should return true for the first call to foo, but not for the second
11005/// (regardless of whether foo is a macro or function).
11007 SourceLocation CallLoc,
11008 SourceLocation ArgLoc) {
11009 if (!CallLoc.isMacroID())
11010 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11011
11012 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11013 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
11014}
11015
11016/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11017/// last two arguments transposed.
11018static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11019 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11020 return;
11021
11022 const Expr *SizeArg =
11023 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11024
11025 auto isLiteralZero = [](const Expr *E) {
11026 return (isa<IntegerLiteral>(E) &&
11027 cast<IntegerLiteral>(E)->getValue() == 0) ||
11029 cast<CharacterLiteral>(E)->getValue() == 0);
11030 };
11031
11032 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11033 SourceLocation CallLoc = Call->getRParenLoc();
11035 if (isLiteralZero(SizeArg) &&
11036 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11037
11038 SourceLocation DiagLoc = SizeArg->getExprLoc();
11039
11040 // Some platforms #define bzero to __builtin_memset. See if this is the
11041 // case, and if so, emit a better diagnostic.
11042 if (BId == Builtin::BIbzero ||
11044 CallLoc, SM, S.getLangOpts()) == "bzero")) {
11045 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11046 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11047 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11048 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11049 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11050 }
11051 return;
11052 }
11053
11054 // If the second argument to a memset is a sizeof expression and the third
11055 // isn't, this is also likely an error. This should catch
11056 // 'memset(buf, sizeof(buf), 0xff)'.
11057 if (BId == Builtin::BImemset &&
11058 doesExprLikelyComputeSize(Call->getArg(1)) &&
11059 !doesExprLikelyComputeSize(Call->getArg(2))) {
11060 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11061 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11062 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11063 return;
11064 }
11065}
11066
11067void Sema::CheckMemaccessArguments(const CallExpr *Call,
11068 unsigned BId,
11069 IdentifierInfo *FnName) {
11070 assert(BId != 0);
11071
11072 // It is possible to have a non-standard definition of memset. Validate
11073 // we have enough arguments, and if not, abort further checking.
11074 unsigned ExpectedNumArgs =
11075 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11076 if (Call->getNumArgs() < ExpectedNumArgs)
11077 return;
11078
11079 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11080 BId == Builtin::BIstrndup ? 1 : 2);
11081 unsigned LenArg =
11082 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11083 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11084
11085 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11086 Call->getBeginLoc(), Call->getRParenLoc()))
11087 return;
11088
11089 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11090 CheckMemaccessSize(*this, BId, Call);
11091
11092 // We have special checking when the length is a sizeof expression.
11093 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11094
11095 // Although widely used, 'bzero' is not a standard function. Be more strict
11096 // with the argument types before allowing diagnostics and only allow the
11097 // form bzero(ptr, sizeof(...)).
11098 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11099 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11100 return;
11101
11102 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11103 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11104 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11105
11106 QualType DestTy = Dest->getType();
11107 QualType PointeeTy;
11108 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11109 PointeeTy = DestPtrTy->getPointeeType();
11110
11111 // Never warn about void type pointers. This can be used to suppress
11112 // false positives.
11113 if (PointeeTy->isVoidType())
11114 continue;
11115
11116 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11117 // actually comparing the expressions for equality. Because computing the
11118 // expression IDs can be expensive, we only do this if the diagnostic is
11119 // enabled.
11120 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11121 break;
11122
11123 // Also check for cases where the sizeof argument is the exact same
11124 // type as the memory argument, and where it points to a user-defined
11125 // record type.
11126 if (SizeOfArgTy != QualType()) {
11127 if (PointeeTy->isRecordType() &&
11128 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11129 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11130 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11131 << FnName << SizeOfArgTy << ArgIdx
11132 << PointeeTy << Dest->getSourceRange()
11133 << LenExpr->getSourceRange());
11134 break;
11135 }
11136 }
11137 } else if (DestTy->isArrayType()) {
11138 PointeeTy = DestTy;
11139 }
11140
11141 if (PointeeTy == QualType())
11142 continue;
11143
11144 // Always complain about dynamic classes.
11145 bool IsContained;
11146 if (const CXXRecordDecl *ContainedRD =
11147 getContainedDynamicClass(PointeeTy, IsContained)) {
11148
11149 unsigned OperationType = 0;
11150 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11151 // "overwritten" if we're warning about the destination for any call
11152 // but memcmp; otherwise a verb appropriate to the call.
11153 if (ArgIdx != 0 || IsCmp) {
11154 if (BId == Builtin::BImemcpy)
11155 OperationType = 1;
11156 else if(BId == Builtin::BImemmove)
11157 OperationType = 2;
11158 else if (IsCmp)
11159 OperationType = 3;
11160 }
11161
11162 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11163 PDiag(diag::warn_dyn_class_memaccess)
11164 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11165 << IsContained << ContainedRD << OperationType
11166 << Call->getCallee()->getSourceRange());
11167 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11168 BId != Builtin::BImemset)
11170 Dest->getExprLoc(), Dest,
11171 PDiag(diag::warn_arc_object_memaccess)
11172 << ArgIdx << FnName << PointeeTy
11173 << Call->getCallee()->getSourceRange());
11174 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11175
11176 // FIXME: Do not consider incomplete types even though they may be
11177 // completed later. GCC does not diagnose such code, but we may want to
11178 // consider diagnosing it in the future, perhaps under a different, but
11179 // related, diagnostic group.
11180 bool NonTriviallyCopyableCXXRecord =
11181 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11182 !PointeeTy.isTriviallyCopyableType(Context);
11183
11184 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11186 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11187 PDiag(diag::warn_cstruct_memaccess)
11188 << ArgIdx << FnName << PointeeTy << 0);
11189 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11190 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11191 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11192 // FIXME: Limiting this warning to dest argument until we decide
11193 // whether it's valid for source argument too.
11194 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11195 PDiag(diag::warn_cxxstruct_memaccess)
11196 << FnName << PointeeTy);
11197 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11199 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11200 PDiag(diag::warn_cstruct_memaccess)
11201 << ArgIdx << FnName << PointeeTy << 1);
11202 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11203 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11204 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11205 // FIXME: Limiting this warning to dest argument until we decide
11206 // whether it's valid for source argument too.
11207 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11208 PDiag(diag::warn_cxxstruct_memaccess)
11209 << FnName << PointeeTy);
11210 } else {
11211 continue;
11212 }
11213 } else
11214 continue;
11215
11217 Dest->getExprLoc(), Dest,
11218 PDiag(diag::note_bad_memaccess_silence)
11219 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11220 break;
11221 }
11222}
11223
11224bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11225 IdentifierInfo *FnName) {
11226 llvm::FoldingSetNodeID SizeOfArgID;
11227 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11228 if (!SizeOfArg)
11229 return false;
11230 // Computing this warning is expensive, so we only do so if the warning is
11231 // enabled.
11232 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11233 SizeOfArg->getExprLoc()))
11234 return false;
11235 QualType DestTy = Dest->getType();
11236 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11237 if (!DestPtrTy)
11238 return false;
11239
11240 QualType PointeeTy = DestPtrTy->getPointeeType();
11241
11242 if (SizeOfArgID == llvm::FoldingSetNodeID())
11243 SizeOfArg->Profile(SizeOfArgID, Context, true);
11244
11245 llvm::FoldingSetNodeID DestID;
11246 Dest->Profile(DestID, Context, true);
11247 if (DestID == SizeOfArgID) {
11248 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11249 // over sizeof(src) as well.
11250 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11251 StringRef ReadableName = FnName->getName();
11252
11253 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11254 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11255 ActionIdx = 1; // If its an address-of operator, just remove it.
11256 if (!PointeeTy->isIncompleteType() &&
11257 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11258 ActionIdx = 2; // If the pointee's size is sizeof(char),
11259 // suggest an explicit length.
11260
11261 // If the function is defined as a builtin macro, do not show macro
11262 // expansion.
11263 SourceLocation SL = SizeOfArg->getExprLoc();
11264 SourceRange DSR = Dest->getSourceRange();
11265 SourceRange SSR = SizeOfArg->getSourceRange();
11266 SourceManager &SM = getSourceManager();
11267
11268 if (SM.isMacroArgExpansion(SL)) {
11269 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11270 SL = SM.getSpellingLoc(SL);
11271 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11272 SM.getSpellingLoc(DSR.getEnd()));
11273 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11274 SM.getSpellingLoc(SSR.getEnd()));
11275 }
11276
11277 DiagRuntimeBehavior(SL, SizeOfArg,
11278 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11279 << ReadableName << PointeeTy << DestTy << DSR
11280 << SSR);
11281 DiagRuntimeBehavior(SL, SizeOfArg,
11282 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11283 << ActionIdx << SSR);
11284 return true;
11285 }
11286 return false;
11287}
11288
11289// A little helper routine: ignore addition and subtraction of integer literals.
11290// This intentionally does not ignore all integer constant expressions because
11291// we don't want to remove sizeof().
11292static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11293 Ex = Ex->IgnoreParenCasts();
11294
11295 while (true) {
11296 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11297 if (!BO || !BO->isAdditiveOp())
11298 break;
11299
11300 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11301 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11302
11303 if (isa<IntegerLiteral>(RHS))
11304 Ex = LHS;
11305 else if (isa<IntegerLiteral>(LHS))
11306 Ex = RHS;
11307 else
11308 break;
11309 }
11310
11311 return Ex;
11312}
11313
11315 ASTContext &Context) {
11316 // Only handle constant-sized or VLAs, but not flexible members.
11317 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11318 // Only issue the FIXIT for arrays of size > 1.
11319 if (CAT->getZExtSize() <= 1)
11320 return false;
11321 } else if (!Ty->isVariableArrayType()) {
11322 return false;
11323 }
11324 return true;
11325}
11326
11327void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11328 IdentifierInfo *FnName) {
11329
11330 // Don't crash if the user has the wrong number of arguments
11331 unsigned NumArgs = Call->getNumArgs();
11332 if ((NumArgs != 3) && (NumArgs != 4))
11333 return;
11334
11335 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11336 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11337 const Expr *CompareWithSrc = nullptr;
11338
11339 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11340 Call->getBeginLoc(), Call->getRParenLoc()))
11341 return;
11342
11343 // Look for 'strlcpy(dst, x, sizeof(x))'
11344 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11345 CompareWithSrc = Ex;
11346 else {
11347 // Look for 'strlcpy(dst, x, strlen(x))'
11348 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11349 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11350 SizeCall->getNumArgs() == 1)
11351 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11352 }
11353 }
11354
11355 if (!CompareWithSrc)
11356 return;
11357
11358 // Determine if the argument to sizeof/strlen is equal to the source
11359 // argument. In principle there's all kinds of things you could do
11360 // here, for instance creating an == expression and evaluating it with
11361 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11362 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11363 if (!SrcArgDRE)
11364 return;
11365
11366 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11367 if (!CompareWithSrcDRE ||
11368 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11369 return;
11370
11371 const Expr *OriginalSizeArg = Call->getArg(2);
11372 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11373 << OriginalSizeArg->getSourceRange() << FnName;
11374
11375 // Output a FIXIT hint if the destination is an array (rather than a
11376 // pointer to an array). This could be enhanced to handle some
11377 // pointers if we know the actual size, like if DstArg is 'array+2'
11378 // we could say 'sizeof(array)-2'.
11379 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11381 return;
11382
11383 SmallString<128> sizeString;
11384 llvm::raw_svector_ostream OS(sizeString);
11385 OS << "sizeof(";
11386 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11387 OS << ")";
11388
11389 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11390 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11391 OS.str());
11392}
11393
11394/// Check if two expressions refer to the same declaration.
11395static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11396 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11397 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11398 return D1->getDecl() == D2->getDecl();
11399 return false;
11400}
11401
11402static const Expr *getStrlenExprArg(const Expr *E) {
11403 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11404 const FunctionDecl *FD = CE->getDirectCallee();
11405 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11406 return nullptr;
11407 return CE->getArg(0)->IgnoreParenCasts();
11408 }
11409 return nullptr;
11410}
11411
11412void Sema::CheckStrncatArguments(const CallExpr *CE,
11413 const IdentifierInfo *FnName) {
11414 // Don't crash if the user has the wrong number of arguments.
11415 if (CE->getNumArgs() < 3)
11416 return;
11417 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11418 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11419 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11420
11421 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11422 CE->getRParenLoc()))
11423 return;
11424
11425 // Identify common expressions, which are wrongly used as the size argument
11426 // to strncat and may lead to buffer overflows.
11427 unsigned PatternType = 0;
11428 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11429 // - sizeof(dst)
11430 if (referToTheSameDecl(SizeOfArg, DstArg))
11431 PatternType = 1;
11432 // - sizeof(src)
11433 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11434 PatternType = 2;
11435 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11436 if (BE->getOpcode() == BO_Sub) {
11437 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11438 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11439 // - sizeof(dst) - strlen(dst)
11440 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11442 PatternType = 1;
11443 // - sizeof(src) - (anything)
11444 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11445 PatternType = 2;
11446 }
11447 }
11448
11449 if (PatternType == 0)
11450 return;
11451
11452 // Generate the diagnostic.
11453 SourceLocation SL = LenArg->getBeginLoc();
11454 SourceRange SR = LenArg->getSourceRange();
11455 SourceManager &SM = getSourceManager();
11456
11457 // If the function is defined as a builtin macro, do not show macro expansion.
11458 if (SM.isMacroArgExpansion(SL)) {
11459 SL = SM.getSpellingLoc(SL);
11460 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11461 SM.getSpellingLoc(SR.getEnd()));
11462 }
11463
11464 // Check if the destination is an array (rather than a pointer to an array).
11465 QualType DstTy = DstArg->getType();
11466 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11467 Context);
11468 if (!isKnownSizeArray) {
11469 if (PatternType == 1)
11470 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11471 else
11472 Diag(SL, diag::warn_strncat_src_size) << SR;
11473 return;
11474 }
11475
11476 if (PatternType == 1)
11477 Diag(SL, diag::warn_strncat_large_size) << SR;
11478 else
11479 Diag(SL, diag::warn_strncat_src_size) << SR;
11480
11481 SmallString<128> sizeString;
11482 llvm::raw_svector_ostream OS(sizeString);
11483 OS << "sizeof(";
11484 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11485 OS << ") - ";
11486 OS << "strlen(";
11487 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11488 OS << ") - 1";
11489
11490 Diag(SL, diag::note_strncat_wrong_size)
11491 << FixItHint::CreateReplacement(SR, OS.str());
11492}
11493
11494namespace {
11495void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11496 const UnaryOperator *UnaryExpr, const Decl *D) {
11498 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11499 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11500 return;
11501 }
11502}
11503
11504void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11505 const UnaryOperator *UnaryExpr) {
11506 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11507 const Decl *D = Lvalue->getDecl();
11508 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11509 if (!DD->getType()->isReferenceType())
11510 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11511 }
11512 }
11513
11514 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11515 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11516 Lvalue->getMemberDecl());
11517}
11518
11519void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11520 const UnaryOperator *UnaryExpr) {
11521 const auto *Lambda = dyn_cast<LambdaExpr>(
11523 if (!Lambda)
11524 return;
11525
11526 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11527 << CalleeName << 2 /*object: lambda expression*/;
11528}
11529
11530void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11531 const DeclRefExpr *Lvalue) {
11532 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11533 if (Var == nullptr)
11534 return;
11535
11536 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11537 << CalleeName << 0 /*object: */ << Var;
11538}
11539
11540void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11541 const CastExpr *Cast) {
11542 SmallString<128> SizeString;
11543 llvm::raw_svector_ostream OS(SizeString);
11544
11545 clang::CastKind Kind = Cast->getCastKind();
11546 if (Kind == clang::CK_BitCast &&
11547 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11548 return;
11549 if (Kind == clang::CK_IntegralToPointer &&
11551 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11552 return;
11553
11554 switch (Cast->getCastKind()) {
11555 case clang::CK_BitCast:
11556 case clang::CK_IntegralToPointer:
11557 case clang::CK_FunctionToPointerDecay:
11558 OS << '\'';
11559 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11560 OS << '\'';
11561 break;
11562 default:
11563 return;
11564 }
11565
11566 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11567 << CalleeName << 0 /*object: */ << OS.str();
11568}
11569} // namespace
11570
11571void Sema::CheckFreeArguments(const CallExpr *E) {
11572 const std::string CalleeName =
11573 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11574
11575 { // Prefer something that doesn't involve a cast to make things simpler.
11576 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11577 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11578 switch (UnaryExpr->getOpcode()) {
11579 case UnaryOperator::Opcode::UO_AddrOf:
11580 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11581 case UnaryOperator::Opcode::UO_Plus:
11582 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11583 default:
11584 break;
11585 }
11586
11587 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11588 if (Lvalue->getType()->isArrayType())
11589 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11590
11591 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11592 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11593 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11594 return;
11595 }
11596
11597 if (isa<BlockExpr>(Arg)) {
11598 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11599 << CalleeName << 1 /*object: block*/;
11600 return;
11601 }
11602 }
11603 // Maybe the cast was important, check after the other cases.
11604 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11605 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11606}
11607
11608void
11609Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11610 SourceLocation ReturnLoc,
11611 bool isObjCMethod,
11612 const AttrVec *Attrs,
11613 const FunctionDecl *FD) {
11614 // Check if the return value is null but should not be.
11615 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11616 (!isObjCMethod && isNonNullType(lhsType))) &&
11617 CheckNonNullExpr(*this, RetValExp))
11618 Diag(ReturnLoc, diag::warn_null_ret)
11619 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11620
11621 // C++11 [basic.stc.dynamic.allocation]p4:
11622 // If an allocation function declared with a non-throwing
11623 // exception-specification fails to allocate storage, it shall return
11624 // a null pointer. Any other allocation function that fails to allocate
11625 // storage shall indicate failure only by throwing an exception [...]
11626 if (FD) {
11628 if (Op == OO_New || Op == OO_Array_New) {
11629 const FunctionProtoType *Proto
11630 = FD->getType()->castAs<FunctionProtoType>();
11631 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11632 CheckNonNullExpr(*this, RetValExp))
11633 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11634 << FD << getLangOpts().CPlusPlus11;
11635 }
11636 }
11637
11638 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11639 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11640 }
11641
11642 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11643 // here prevent the user from using a PPC MMA type as trailing return type.
11644 if (Context.getTargetInfo().getTriple().isPPC64())
11645 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11646}
11647
11649 const Expr *RHS, BinaryOperatorKind Opcode) {
11650 if (!BinaryOperator::isEqualityOp(Opcode))
11651 return;
11652
11653 // Match and capture subexpressions such as "(float) X == 0.1".
11654 const FloatingLiteral *FPLiteral;
11655 const CastExpr *FPCast;
11656 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11657 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11658 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11659 return FPLiteral && FPCast;
11660 };
11661
11662 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11663 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11664 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11665 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11666 TargetTy->isFloatingPoint()) {
11667 bool Lossy;
11668 llvm::APFloat TargetC = FPLiteral->getValue();
11669 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11670 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11671 if (Lossy) {
11672 // If the literal cannot be represented in the source type, then a
11673 // check for == is always false and check for != is always true.
11674 Diag(Loc, diag::warn_float_compare_literal)
11675 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11676 << LHS->getSourceRange() << RHS->getSourceRange();
11677 return;
11678 }
11679 }
11680 }
11681
11682 // Match a more general floating-point equality comparison (-Wfloat-equal).
11683 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11684 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11685
11686 // Special case: check for x == x (which is OK).
11687 // Do not emit warnings for such cases.
11688 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11689 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11690 if (DRL->getDecl() == DRR->getDecl())
11691 return;
11692
11693 // Special case: check for comparisons against literals that can be exactly
11694 // represented by APFloat. In such cases, do not emit a warning. This
11695 // is a heuristic: often comparison against such literals are used to
11696 // detect if a value in a variable has not changed. This clearly can
11697 // lead to false negatives.
11698 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11699 if (FLL->isExact())
11700 return;
11701 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11702 if (FLR->isExact())
11703 return;
11704
11705 // Check for comparisons with builtin types.
11706 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11707 CL && CL->getBuiltinCallee())
11708 return;
11709
11710 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11711 CR && CR->getBuiltinCallee())
11712 return;
11713
11714 // Emit the diagnostic.
11715 Diag(Loc, diag::warn_floatingpoint_eq)
11716 << LHS->getSourceRange() << RHS->getSourceRange();
11717}
11718
11719//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11720//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11721
11722namespace {
11723
11724/// Structure recording the 'active' range of an integer-valued
11725/// expression.
11726struct IntRange {
11727 /// The number of bits active in the int. Note that this includes exactly one
11728 /// sign bit if !NonNegative.
11729 unsigned Width;
11730
11731 /// True if the int is known not to have negative values. If so, all leading
11732 /// bits before Width are known zero, otherwise they are known to be the
11733 /// same as the MSB within Width.
11734 bool NonNegative;
11735
11736 IntRange(unsigned Width, bool NonNegative)
11737 : Width(Width), NonNegative(NonNegative) {}
11738
11739 /// Number of bits excluding the sign bit.
11740 unsigned valueBits() const {
11741 return NonNegative ? Width : Width - 1;
11742 }
11743
11744 /// Returns the range of the bool type.
11745 static IntRange forBoolType() {
11746 return IntRange(1, true);
11747 }
11748
11749 /// Returns the range of an opaque value of the given integral type.
11750 static IntRange forValueOfType(ASTContext &C, QualType T) {
11751 return forValueOfCanonicalType(C,
11753 }
11754
11755 /// Returns the range of an opaque value of a canonical integral type.
11756 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11757 assert(T->isCanonicalUnqualified());
11758
11759 if (const auto *VT = dyn_cast<VectorType>(T))
11760 T = VT->getElementType().getTypePtr();
11761 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11762 T = MT->getElementType().getTypePtr();
11763 if (const auto *CT = dyn_cast<ComplexType>(T))
11764 T = CT->getElementType().getTypePtr();
11765 if (const auto *AT = dyn_cast<AtomicType>(T))
11766 T = AT->getValueType().getTypePtr();
11767 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11768 T = OBT->getUnderlyingType().getTypePtr();
11769
11770 if (!C.getLangOpts().CPlusPlus) {
11771 // For enum types in C code, use the underlying datatype.
11772 if (const auto *ED = T->getAsEnumDecl())
11773 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11774 } else if (auto *Enum = T->getAsEnumDecl()) {
11775 // For enum types in C++, use the known bit width of the enumerators.
11776 // In C++11, enums can have a fixed underlying type. Use this type to
11777 // compute the range.
11778 if (Enum->isFixed()) {
11779 return IntRange(C.getIntWidth(QualType(T, 0)),
11780 !Enum->getIntegerType()->isSignedIntegerType());
11781 }
11782
11783 unsigned NumPositive = Enum->getNumPositiveBits();
11784 unsigned NumNegative = Enum->getNumNegativeBits();
11785
11786 if (NumNegative == 0)
11787 return IntRange(NumPositive, true/*NonNegative*/);
11788 else
11789 return IntRange(std::max(NumPositive + 1, NumNegative),
11790 false/*NonNegative*/);
11791 }
11792
11793 if (const auto *EIT = dyn_cast<BitIntType>(T))
11794 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11795
11796 const BuiltinType *BT = cast<BuiltinType>(T);
11797 assert(BT->isInteger());
11798
11799 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11800 }
11801
11802 /// Returns the "target" range of a canonical integral type, i.e.
11803 /// the range of values expressible in the type.
11804 ///
11805 /// This matches forValueOfCanonicalType except that enums have the
11806 /// full range of their type, not the range of their enumerators.
11807 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11808 assert(T->isCanonicalUnqualified());
11809
11810 if (const VectorType *VT = dyn_cast<VectorType>(T))
11811 T = VT->getElementType().getTypePtr();
11812 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11813 T = MT->getElementType().getTypePtr();
11814 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11815 T = CT->getElementType().getTypePtr();
11816 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11817 T = AT->getValueType().getTypePtr();
11818 if (const auto *ED = T->getAsEnumDecl())
11819 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11820 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11821 T = OBT->getUnderlyingType().getTypePtr();
11822
11823 if (const auto *EIT = dyn_cast<BitIntType>(T))
11824 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11825
11826 const BuiltinType *BT = cast<BuiltinType>(T);
11827 assert(BT->isInteger());
11828
11829 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11830 }
11831
11832 /// Returns the supremum of two ranges: i.e. their conservative merge.
11833 static IntRange join(IntRange L, IntRange R) {
11834 bool Unsigned = L.NonNegative && R.NonNegative;
11835 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11836 L.NonNegative && R.NonNegative);
11837 }
11838
11839 /// Return the range of a bitwise-AND of the two ranges.
11840 static IntRange bit_and(IntRange L, IntRange R) {
11841 unsigned Bits = std::max(L.Width, R.Width);
11842 bool NonNegative = false;
11843 if (L.NonNegative) {
11844 Bits = std::min(Bits, L.Width);
11845 NonNegative = true;
11846 }
11847 if (R.NonNegative) {
11848 Bits = std::min(Bits, R.Width);
11849 NonNegative = true;
11850 }
11851 return IntRange(Bits, NonNegative);
11852 }
11853
11854 /// Return the range of a sum of the two ranges.
11855 static IntRange sum(IntRange L, IntRange R) {
11856 bool Unsigned = L.NonNegative && R.NonNegative;
11857 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11858 Unsigned);
11859 }
11860
11861 /// Return the range of a difference of the two ranges.
11862 static IntRange difference(IntRange L, IntRange R) {
11863 // We need a 1-bit-wider range if:
11864 // 1) LHS can be negative: least value can be reduced.
11865 // 2) RHS can be negative: greatest value can be increased.
11866 bool CanWiden = !L.NonNegative || !R.NonNegative;
11867 bool Unsigned = L.NonNegative && R.Width == 0;
11868 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11869 !Unsigned,
11870 Unsigned);
11871 }
11872
11873 /// Return the range of a product of the two ranges.
11874 static IntRange product(IntRange L, IntRange R) {
11875 // If both LHS and RHS can be negative, we can form
11876 // -2^L * -2^R = 2^(L + R)
11877 // which requires L + R + 1 value bits to represent.
11878 bool CanWiden = !L.NonNegative && !R.NonNegative;
11879 bool Unsigned = L.NonNegative && R.NonNegative;
11880 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11881 Unsigned);
11882 }
11883
11884 /// Return the range of a remainder operation between the two ranges.
11885 static IntRange rem(IntRange L, IntRange R) {
11886 // The result of a remainder can't be larger than the result of
11887 // either side. The sign of the result is the sign of the LHS.
11888 bool Unsigned = L.NonNegative;
11889 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11890 Unsigned);
11891 }
11892};
11893
11894} // namespace
11895
11896static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11897 if (value.isSigned() && value.isNegative())
11898 return IntRange(value.getSignificantBits(), false);
11899
11900 if (value.getBitWidth() > MaxWidth)
11901 value = value.trunc(MaxWidth);
11902
11903 // isNonNegative() just checks the sign bit without considering
11904 // signedness.
11905 return IntRange(value.getActiveBits(), true);
11906}
11907
11908static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11909 if (result.isInt())
11910 return GetValueRange(result.getInt(), MaxWidth);
11911
11912 if (result.isVector()) {
11913 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11914 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11915 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11916 R = IntRange::join(R, El);
11917 }
11918 return R;
11919 }
11920
11921 if (result.isComplexInt()) {
11922 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11923 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11924 return IntRange::join(R, I);
11925 }
11926
11927 // This can happen with lossless casts to intptr_t of "based" lvalues.
11928 // Assume it might use arbitrary bits.
11929 // FIXME: The only reason we need to pass the type in here is to get
11930 // the sign right on this one case. It would be nice if APValue
11931 // preserved this.
11932 assert(result.isLValue() || result.isAddrLabelDiff());
11933 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11934}
11935
11936static QualType GetExprType(const Expr *E) {
11937 QualType Ty = E->getType();
11938 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11939 Ty = AtomicRHS->getValueType();
11940 return Ty;
11941}
11942
11943/// Attempts to estimate an approximate range for the given integer expression.
11944/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11945/// reliable estimation cannot be determined.
11946///
11947/// \param MaxWidth The width to which the value will be truncated.
11948/// \param InConstantContext If \c true, interpret the expression within a
11949/// constant context.
11950/// \param Approximate If \c true, provide a likely range of values by assuming
11951/// that arithmetic on narrower types remains within those types.
11952/// If \c false, return a range that includes all possible values
11953/// resulting from the expression.
11954/// \returns A range of values that the expression might take, or
11955/// std::nullopt if a reliable estimation cannot be determined.
11956static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11957 unsigned MaxWidth,
11958 bool InConstantContext,
11959 bool Approximate) {
11960 E = E->IgnoreParens();
11961
11962 // Try a full evaluation first.
11963 Expr::EvalResult result;
11964 if (E->EvaluateAsRValue(result, C, InConstantContext))
11965 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11966
11967 // I think we only want to look through implicit casts here; if the
11968 // user has an explicit widening cast, we should treat the value as
11969 // being of the new, wider type.
11970 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11971 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11972 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11973 Approximate);
11974
11975 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11976
11977 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11978 CE->getCastKind() == CK_BooleanToSignedIntegral;
11979
11980 // Assume that non-integer casts can span the full range of the type.
11981 if (!isIntegerCast)
11982 return OutputTypeRange;
11983
11984 std::optional<IntRange> SubRange = TryGetExprRange(
11985 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11986 InConstantContext, Approximate);
11987 if (!SubRange)
11988 return std::nullopt;
11989
11990 // Bail out if the subexpr's range is as wide as the cast type.
11991 if (SubRange->Width >= OutputTypeRange.Width)
11992 return OutputTypeRange;
11993
11994 // Otherwise, we take the smaller width, and we're non-negative if
11995 // either the output type or the subexpr is.
11996 return IntRange(SubRange->Width,
11997 SubRange->NonNegative || OutputTypeRange.NonNegative);
11998 }
11999
12000 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12001 // If we can fold the condition, just take that operand.
12002 bool CondResult;
12003 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12004 return TryGetExprRange(
12005 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12006 InConstantContext, Approximate);
12007
12008 // Otherwise, conservatively merge.
12009 // TryGetExprRange requires an integer expression, but a throw expression
12010 // results in a void type.
12011 Expr *TrueExpr = CO->getTrueExpr();
12012 if (TrueExpr->getType()->isVoidType())
12013 return std::nullopt;
12014
12015 std::optional<IntRange> L =
12016 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
12017 if (!L)
12018 return std::nullopt;
12019
12020 Expr *FalseExpr = CO->getFalseExpr();
12021 if (FalseExpr->getType()->isVoidType())
12022 return std::nullopt;
12023
12024 std::optional<IntRange> R =
12025 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
12026 if (!R)
12027 return std::nullopt;
12028
12029 return IntRange::join(*L, *R);
12030 }
12031
12032 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12033 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12034
12035 switch (BO->getOpcode()) {
12036 case BO_Cmp:
12037 llvm_unreachable("builtin <=> should have class type");
12038
12039 // Boolean-valued operations are single-bit and positive.
12040 case BO_LAnd:
12041 case BO_LOr:
12042 case BO_LT:
12043 case BO_GT:
12044 case BO_LE:
12045 case BO_GE:
12046 case BO_EQ:
12047 case BO_NE:
12048 return IntRange::forBoolType();
12049
12050 // The type of the assignments is the type of the LHS, so the RHS
12051 // is not necessarily the same type.
12052 case BO_MulAssign:
12053 case BO_DivAssign:
12054 case BO_RemAssign:
12055 case BO_AddAssign:
12056 case BO_SubAssign:
12057 case BO_XorAssign:
12058 case BO_OrAssign:
12059 // TODO: bitfields?
12060 return IntRange::forValueOfType(C, GetExprType(E));
12061
12062 // Simple assignments just pass through the RHS, which will have
12063 // been coerced to the LHS type.
12064 case BO_Assign:
12065 // TODO: bitfields?
12066 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12067 Approximate);
12068
12069 // Operations with opaque sources are black-listed.
12070 case BO_PtrMemD:
12071 case BO_PtrMemI:
12072 return IntRange::forValueOfType(C, GetExprType(E));
12073
12074 // Bitwise-and uses the *infinum* of the two source ranges.
12075 case BO_And:
12076 case BO_AndAssign:
12077 Combine = IntRange::bit_and;
12078 break;
12079
12080 // Left shift gets black-listed based on a judgement call.
12081 case BO_Shl:
12082 // ...except that we want to treat '1 << (blah)' as logically
12083 // positive. It's an important idiom.
12084 if (IntegerLiteral *I
12085 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12086 if (I->getValue() == 1) {
12087 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12088 return IntRange(R.Width, /*NonNegative*/ true);
12089 }
12090 }
12091 [[fallthrough]];
12092
12093 case BO_ShlAssign:
12094 return IntRange::forValueOfType(C, GetExprType(E));
12095
12096 // Right shift by a constant can narrow its left argument.
12097 case BO_Shr:
12098 case BO_ShrAssign: {
12099 std::optional<IntRange> L = TryGetExprRange(
12100 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12101 if (!L)
12102 return std::nullopt;
12103
12104 // If the shift amount is a positive constant, drop the width by
12105 // that much.
12106 if (std::optional<llvm::APSInt> shift =
12107 BO->getRHS()->getIntegerConstantExpr(C)) {
12108 if (shift->isNonNegative()) {
12109 if (shift->uge(L->Width))
12110 L->Width = (L->NonNegative ? 0 : 1);
12111 else
12112 L->Width -= shift->getZExtValue();
12113 }
12114 }
12115
12116 return L;
12117 }
12118
12119 // Comma acts as its right operand.
12120 case BO_Comma:
12121 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12122 Approximate);
12123
12124 case BO_Add:
12125 if (!Approximate)
12126 Combine = IntRange::sum;
12127 break;
12128
12129 case BO_Sub:
12130 if (BO->getLHS()->getType()->isPointerType())
12131 return IntRange::forValueOfType(C, GetExprType(E));
12132 if (!Approximate)
12133 Combine = IntRange::difference;
12134 break;
12135
12136 case BO_Mul:
12137 if (!Approximate)
12138 Combine = IntRange::product;
12139 break;
12140
12141 // The width of a division result is mostly determined by the size
12142 // of the LHS.
12143 case BO_Div: {
12144 // Don't 'pre-truncate' the operands.
12145 unsigned opWidth = C.getIntWidth(GetExprType(E));
12146 std::optional<IntRange> L = TryGetExprRange(
12147 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12148 if (!L)
12149 return std::nullopt;
12150
12151 // If the divisor is constant, use that.
12152 if (std::optional<llvm::APSInt> divisor =
12153 BO->getRHS()->getIntegerConstantExpr(C)) {
12154 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12155 if (log2 >= L->Width)
12156 L->Width = (L->NonNegative ? 0 : 1);
12157 else
12158 L->Width = std::min(L->Width - log2, MaxWidth);
12159 return L;
12160 }
12161
12162 // Otherwise, just use the LHS's width.
12163 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12164 // could be -1.
12165 std::optional<IntRange> R = TryGetExprRange(
12166 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12167 if (!R)
12168 return std::nullopt;
12169
12170 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12171 }
12172
12173 case BO_Rem:
12174 Combine = IntRange::rem;
12175 break;
12176
12177 // The default behavior is okay for these.
12178 case BO_Xor:
12179 case BO_Or:
12180 break;
12181 }
12182
12183 // Combine the two ranges, but limit the result to the type in which we
12184 // performed the computation.
12185 QualType T = GetExprType(E);
12186 unsigned opWidth = C.getIntWidth(T);
12187 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12188 InConstantContext, Approximate);
12189 if (!L)
12190 return std::nullopt;
12191
12192 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12193 InConstantContext, Approximate);
12194 if (!R)
12195 return std::nullopt;
12196
12197 IntRange C = Combine(*L, *R);
12198 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12199 C.Width = std::min(C.Width, MaxWidth);
12200 return C;
12201 }
12202
12203 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12204 switch (UO->getOpcode()) {
12205 // Boolean-valued operations are white-listed.
12206 case UO_LNot:
12207 return IntRange::forBoolType();
12208
12209 // Operations with opaque sources are black-listed.
12210 case UO_Deref:
12211 case UO_AddrOf: // should be impossible
12212 return IntRange::forValueOfType(C, GetExprType(E));
12213
12214 case UO_Minus: {
12215 if (E->getType()->isUnsignedIntegerType()) {
12216 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12217 Approximate);
12218 }
12219
12220 std::optional<IntRange> SubRange = TryGetExprRange(
12221 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12222
12223 if (!SubRange)
12224 return std::nullopt;
12225
12226 // If the range was previously non-negative, we need an extra bit for the
12227 // sign bit. Otherwise, we need an extra bit because the negation of the
12228 // most-negative value is one bit wider than that value.
12229 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12230 }
12231
12232 case UO_Not: {
12233 if (E->getType()->isUnsignedIntegerType()) {
12234 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12235 Approximate);
12236 }
12237
12238 std::optional<IntRange> SubRange = TryGetExprRange(
12239 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12240
12241 if (!SubRange)
12242 return std::nullopt;
12243
12244 // The width increments by 1 if the sub-expression cannot be negative
12245 // since it now can be.
12246 return IntRange(
12247 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12248 false);
12249 }
12250
12251 default:
12252 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12253 Approximate);
12254 }
12255 }
12256
12257 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12258 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12259 Approximate);
12260
12261 if (const auto *BitField = E->getSourceBitField())
12262 return IntRange(BitField->getBitWidthValue(),
12263 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12264
12265 if (GetExprType(E)->isVoidType())
12266 return std::nullopt;
12267
12268 return IntRange::forValueOfType(C, GetExprType(E));
12269}
12270
12271static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12272 bool InConstantContext,
12273 bool Approximate) {
12274 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12275 Approximate);
12276}
12277
12278/// Checks whether the given value, which currently has the given
12279/// source semantics, has the same value when coerced through the
12280/// target semantics.
12281static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12282 const llvm::fltSemantics &Src,
12283 const llvm::fltSemantics &Tgt) {
12284 llvm::APFloat truncated = value;
12285
12286 bool ignored;
12287 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12288 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12289
12290 return truncated.bitwiseIsEqual(value);
12291}
12292
12293/// Checks whether the given value, which currently has the given
12294/// source semantics, has the same value when coerced through the
12295/// target semantics.
12296///
12297/// The value might be a vector of floats (or a complex number).
12298static bool IsSameFloatAfterCast(const APValue &value,
12299 const llvm::fltSemantics &Src,
12300 const llvm::fltSemantics &Tgt) {
12301 if (value.isFloat())
12302 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12303
12304 if (value.isVector()) {
12305 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12306 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12307 return false;
12308 return true;
12309 }
12310
12311 if (value.isMatrix()) {
12312 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12313 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12314 return false;
12315 return true;
12316 }
12317
12318 assert(value.isComplexFloat());
12319 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12320 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12321}
12322
12323static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12324 bool IsListInit = false);
12325
12326static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12327 // Suppress cases where we are comparing against an enum constant.
12328 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12329 if (isa<EnumConstantDecl>(DR->getDecl()))
12330 return true;
12331
12332 // Suppress cases where the value is expanded from a macro, unless that macro
12333 // is how a language represents a boolean literal. This is the case in both C
12334 // and Objective-C.
12335 SourceLocation BeginLoc = E->getBeginLoc();
12336 if (BeginLoc.isMacroID()) {
12337 StringRef MacroName = Lexer::getImmediateMacroName(
12338 BeginLoc, S.getSourceManager(), S.getLangOpts());
12339 return MacroName != "YES" && MacroName != "NO" &&
12340 MacroName != "true" && MacroName != "false";
12341 }
12342
12343 return false;
12344}
12345
12346static bool isKnownToHaveUnsignedValue(const Expr *E) {
12347 return E->getType()->isIntegerType() &&
12348 (!E->getType()->isSignedIntegerType() ||
12350}
12351
12352namespace {
12353/// The promoted range of values of a type. In general this has the
12354/// following structure:
12355///
12356/// |-----------| . . . |-----------|
12357/// ^ ^ ^ ^
12358/// Min HoleMin HoleMax Max
12359///
12360/// ... where there is only a hole if a signed type is promoted to unsigned
12361/// (in which case Min and Max are the smallest and largest representable
12362/// values).
12363struct PromotedRange {
12364 // Min, or HoleMax if there is a hole.
12365 llvm::APSInt PromotedMin;
12366 // Max, or HoleMin if there is a hole.
12367 llvm::APSInt PromotedMax;
12368
12369 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12370 if (R.Width == 0)
12371 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12372 else if (R.Width >= BitWidth && !Unsigned) {
12373 // Promotion made the type *narrower*. This happens when promoting
12374 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12375 // Treat all values of 'signed int' as being in range for now.
12376 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12377 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12378 } else {
12379 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12380 .extOrTrunc(BitWidth);
12381 PromotedMin.setIsUnsigned(Unsigned);
12382
12383 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12384 .extOrTrunc(BitWidth);
12385 PromotedMax.setIsUnsigned(Unsigned);
12386 }
12387 }
12388
12389 // Determine whether this range is contiguous (has no hole).
12390 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12391
12392 // Where a constant value is within the range.
12393 enum ComparisonResult {
12394 LT = 0x1,
12395 LE = 0x2,
12396 GT = 0x4,
12397 GE = 0x8,
12398 EQ = 0x10,
12399 NE = 0x20,
12400 InRangeFlag = 0x40,
12401
12402 Less = LE | LT | NE,
12403 Min = LE | InRangeFlag,
12404 InRange = InRangeFlag,
12405 Max = GE | InRangeFlag,
12406 Greater = GE | GT | NE,
12407
12408 OnlyValue = LE | GE | EQ | InRangeFlag,
12409 InHole = NE
12410 };
12411
12412 ComparisonResult compare(const llvm::APSInt &Value) const {
12413 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12414 Value.isUnsigned() == PromotedMin.isUnsigned());
12415 if (!isContiguous()) {
12416 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12417 if (Value.isMinValue()) return Min;
12418 if (Value.isMaxValue()) return Max;
12419 if (Value >= PromotedMin) return InRange;
12420 if (Value <= PromotedMax) return InRange;
12421 return InHole;
12422 }
12423
12424 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12425 case -1: return Less;
12426 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12427 case 1:
12428 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12429 case -1: return InRange;
12430 case 0: return Max;
12431 case 1: return Greater;
12432 }
12433 }
12434
12435 llvm_unreachable("impossible compare result");
12436 }
12437
12438 static std::optional<StringRef>
12439 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12440 if (Op == BO_Cmp) {
12441 ComparisonResult LTFlag = LT, GTFlag = GT;
12442 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12443
12444 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12445 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12446 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12447 return std::nullopt;
12448 }
12449
12450 ComparisonResult TrueFlag, FalseFlag;
12451 if (Op == BO_EQ) {
12452 TrueFlag = EQ;
12453 FalseFlag = NE;
12454 } else if (Op == BO_NE) {
12455 TrueFlag = NE;
12456 FalseFlag = EQ;
12457 } else {
12458 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12459 TrueFlag = LT;
12460 FalseFlag = GE;
12461 } else {
12462 TrueFlag = GT;
12463 FalseFlag = LE;
12464 }
12465 if (Op == BO_GE || Op == BO_LE)
12466 std::swap(TrueFlag, FalseFlag);
12467 }
12468 if (R & TrueFlag)
12469 return StringRef("true");
12470 if (R & FalseFlag)
12471 return StringRef("false");
12472 return std::nullopt;
12473 }
12474};
12475}
12476
12477static bool HasEnumType(const Expr *E) {
12478 // Strip off implicit integral promotions.
12479 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12480 if (ICE->getCastKind() != CK_IntegralCast &&
12481 ICE->getCastKind() != CK_NoOp)
12482 break;
12483 E = ICE->getSubExpr();
12484 }
12485
12486 return E->getType()->isEnumeralType();
12487}
12488
12490 // The values of this enumeration are used in the diagnostics
12491 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12492 enum ConstantValueKind {
12493 Miscellaneous = 0,
12494 LiteralTrue,
12495 LiteralFalse
12496 };
12497 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12498 return BL->getValue() ? ConstantValueKind::LiteralTrue
12499 : ConstantValueKind::LiteralFalse;
12500 return ConstantValueKind::Miscellaneous;
12501}
12502
12505 const llvm::APSInt &Value,
12506 bool RhsConstant) {
12508 return false;
12509
12510 Expr *OriginalOther = Other;
12511
12512 Constant = Constant->IgnoreParenImpCasts();
12513 Other = Other->IgnoreParenImpCasts();
12514
12515 // Suppress warnings on tautological comparisons between values of the same
12516 // enumeration type. There are only two ways we could warn on this:
12517 // - If the constant is outside the range of representable values of
12518 // the enumeration. In such a case, we should warn about the cast
12519 // to enumeration type, not about the comparison.
12520 // - If the constant is the maximum / minimum in-range value. For an
12521 // enumeratin type, such comparisons can be meaningful and useful.
12522 if (Constant->getType()->isEnumeralType() &&
12523 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12524 return false;
12525
12526 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12527 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12528 if (!OtherValueRange)
12529 return false;
12530
12531 QualType OtherT = Other->getType();
12532 if (const auto *AT = OtherT->getAs<AtomicType>())
12533 OtherT = AT->getValueType();
12534 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12535
12536 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12537 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12538 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12539 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12540 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12541
12542 // Whether we're treating Other as being a bool because of the form of
12543 // expression despite it having another type (typically 'int' in C).
12544 bool OtherIsBooleanDespiteType =
12545 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12546 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12547 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12548
12549 // Check if all values in the range of possible values of this expression
12550 // lead to the same comparison outcome.
12551 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12552 Value.isUnsigned());
12553 auto Cmp = OtherPromotedValueRange.compare(Value);
12554 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12555 if (!Result)
12556 return false;
12557
12558 // Also consider the range determined by the type alone. This allows us to
12559 // classify the warning under the proper diagnostic group.
12560 bool TautologicalTypeCompare = false;
12561 {
12562 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12563 Value.isUnsigned());
12564 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12565 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12566 RhsConstant)) {
12567 TautologicalTypeCompare = true;
12568 Cmp = TypeCmp;
12570 }
12571 }
12572
12573 // Don't warn if the non-constant operand actually always evaluates to the
12574 // same value.
12575 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12576 return false;
12577
12578 // Suppress the diagnostic for an in-range comparison if the constant comes
12579 // from a macro or enumerator. We don't want to diagnose
12580 //
12581 // some_long_value <= INT_MAX
12582 //
12583 // when sizeof(int) == sizeof(long).
12584 bool InRange = Cmp & PromotedRange::InRangeFlag;
12585 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12586 return false;
12587
12588 // A comparison of an unsigned bit-field against 0 is really a type problem,
12589 // even though at the type level the bit-field might promote to 'signed int'.
12590 if (Other->refersToBitField() && InRange && Value == 0 &&
12591 Other->getType()->isUnsignedIntegerOrEnumerationType())
12592 TautologicalTypeCompare = true;
12593
12594 // If this is a comparison to an enum constant, include that
12595 // constant in the diagnostic.
12596 const EnumConstantDecl *ED = nullptr;
12597 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12598 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12599
12600 // Should be enough for uint128 (39 decimal digits)
12601 SmallString<64> PrettySourceValue;
12602 llvm::raw_svector_ostream OS(PrettySourceValue);
12603 if (ED) {
12604 OS << '\'' << *ED << "' (" << Value << ")";
12605 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12606 Constant->IgnoreParenImpCasts())) {
12607 OS << (BL->getValue() ? "YES" : "NO");
12608 } else {
12609 OS << Value;
12610 }
12611
12612 if (!TautologicalTypeCompare) {
12613 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12614 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12615 << E->getOpcodeStr() << OS.str() << *Result
12616 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12617 return true;
12618 }
12619
12620 if (IsObjCSignedCharBool) {
12622 S.PDiag(diag::warn_tautological_compare_objc_bool)
12623 << OS.str() << *Result);
12624 return true;
12625 }
12626
12627 // FIXME: We use a somewhat different formatting for the in-range cases and
12628 // cases involving boolean values for historical reasons. We should pick a
12629 // consistent way of presenting these diagnostics.
12630 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12631
12633 E->getOperatorLoc(), E,
12634 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12635 : diag::warn_tautological_bool_compare)
12636 << OS.str() << classifyConstantValue(Constant) << OtherT
12637 << OtherIsBooleanDespiteType << *Result
12638 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12639 } else {
12640 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12641 unsigned Diag =
12642 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12643 ? (HasEnumType(OriginalOther)
12644 ? diag::warn_unsigned_enum_always_true_comparison
12645 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12646 : diag::warn_unsigned_always_true_comparison)
12647 : diag::warn_tautological_constant_compare;
12648
12649 S.Diag(E->getOperatorLoc(), Diag)
12650 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12651 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12652 }
12653
12654 return true;
12655}
12656
12657/// Analyze the operands of the given comparison. Implements the
12658/// fallback case from AnalyzeComparison.
12663
12664/// Implements -Wsign-compare.
12665///
12666/// \param E the binary operator to check for warnings
12668 // The type the comparison is being performed in.
12669 QualType T = E->getLHS()->getType();
12670
12671 // Only analyze comparison operators where both sides have been converted to
12672 // the same type.
12674 return AnalyzeImpConvsInComparison(S, E);
12675
12676 // Don't analyze value-dependent comparisons directly.
12677 if (E->isValueDependent())
12678 return AnalyzeImpConvsInComparison(S, E);
12679
12680 Expr *LHS = E->getLHS();
12681 Expr *RHS = E->getRHS();
12682
12683 if (T->isIntegralType(S.Context)) {
12684 std::optional<llvm::APSInt> RHSValue =
12686 std::optional<llvm::APSInt> LHSValue =
12688
12689 // We don't care about expressions whose result is a constant.
12690 if (RHSValue && LHSValue)
12691 return AnalyzeImpConvsInComparison(S, E);
12692
12693 // We only care about expressions where just one side is literal
12694 if ((bool)RHSValue ^ (bool)LHSValue) {
12695 // Is the constant on the RHS or LHS?
12696 const bool RhsConstant = (bool)RHSValue;
12697 Expr *Const = RhsConstant ? RHS : LHS;
12698 Expr *Other = RhsConstant ? LHS : RHS;
12699 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12700
12701 // Check whether an integer constant comparison results in a value
12702 // of 'true' or 'false'.
12703 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12704 return AnalyzeImpConvsInComparison(S, E);
12705 }
12706 }
12707
12708 if (!T->hasUnsignedIntegerRepresentation()) {
12709 // We don't do anything special if this isn't an unsigned integral
12710 // comparison: we're only interested in integral comparisons, and
12711 // signed comparisons only happen in cases we don't care to warn about.
12712 return AnalyzeImpConvsInComparison(S, E);
12713 }
12714
12715 LHS = LHS->IgnoreParenImpCasts();
12716 RHS = RHS->IgnoreParenImpCasts();
12717
12718 if (!S.getLangOpts().CPlusPlus) {
12719 // Avoid warning about comparison of integers with different signs when
12720 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12721 // the type of `E`.
12722 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12723 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12724 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12725 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12726 }
12727
12728 // Check to see if one of the (unmodified) operands is of different
12729 // signedness.
12730 Expr *signedOperand, *unsignedOperand;
12732 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12733 "unsigned comparison between two signed integer expressions?");
12734 signedOperand = LHS;
12735 unsignedOperand = RHS;
12736 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12737 signedOperand = RHS;
12738 unsignedOperand = LHS;
12739 } else {
12740 return AnalyzeImpConvsInComparison(S, E);
12741 }
12742
12743 // Otherwise, calculate the effective range of the signed operand.
12744 std::optional<IntRange> signedRange =
12746 /*Approximate=*/true);
12747 if (!signedRange)
12748 return;
12749
12750 // Go ahead and analyze implicit conversions in the operands. Note
12751 // that we skip the implicit conversions on both sides.
12754
12755 // If the signed range is non-negative, -Wsign-compare won't fire.
12756 if (signedRange->NonNegative)
12757 return;
12758
12759 // For (in)equality comparisons, if the unsigned operand is a
12760 // constant which cannot collide with a overflowed signed operand,
12761 // then reinterpreting the signed operand as unsigned will not
12762 // change the result of the comparison.
12763 if (E->isEqualityOp()) {
12764 unsigned comparisonWidth = S.Context.getIntWidth(T);
12765 std::optional<IntRange> unsignedRange = TryGetExprRange(
12766 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12767 /*Approximate=*/true);
12768 if (!unsignedRange)
12769 return;
12770
12771 // We should never be unable to prove that the unsigned operand is
12772 // non-negative.
12773 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12774
12775 if (unsignedRange->Width < comparisonWidth)
12776 return;
12777 }
12778
12780 S.PDiag(diag::warn_mixed_sign_comparison)
12781 << LHS->getType() << RHS->getType()
12782 << LHS->getSourceRange() << RHS->getSourceRange());
12783}
12784
12785/// Analyzes an attempt to assign the given value to a bitfield.
12786///
12787/// Returns true if there was something fishy about the attempt.
12789 SourceLocation InitLoc) {
12790 assert(Bitfield->isBitField());
12791 if (Bitfield->isInvalidDecl())
12792 return false;
12793
12794 // White-list bool bitfields.
12795 QualType BitfieldType = Bitfield->getType();
12796 if (BitfieldType->isBooleanType())
12797 return false;
12798
12799 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12800 // If the underlying enum type was not explicitly specified as an unsigned
12801 // type and the enum contain only positive values, MSVC++ will cause an
12802 // inconsistency by storing this as a signed type.
12803 if (S.getLangOpts().CPlusPlus11 &&
12804 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12805 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12806 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12807 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12808 << BitfieldEnumDecl;
12809 }
12810 }
12811
12812 // Ignore value- or type-dependent expressions.
12813 if (Bitfield->getBitWidth()->isValueDependent() ||
12814 Bitfield->getBitWidth()->isTypeDependent() ||
12815 Init->isValueDependent() ||
12816 Init->isTypeDependent())
12817 return false;
12818
12819 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12820 unsigned FieldWidth = Bitfield->getBitWidthValue();
12821
12823 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12825 // The RHS is not constant. If the RHS has an enum type, make sure the
12826 // bitfield is wide enough to hold all the values of the enum without
12827 // truncation.
12828 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12829 const PreferredTypeAttr *PTAttr = nullptr;
12830 if (!ED) {
12831 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12832 if (PTAttr)
12833 ED = PTAttr->getType()->getAsEnumDecl();
12834 }
12835 if (ED) {
12836 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12837
12838 // Enum types are implicitly signed on Windows, so check if there are any
12839 // negative enumerators to see if the enum was intended to be signed or
12840 // not.
12841 bool SignedEnum = ED->getNumNegativeBits() > 0;
12842
12843 // Check for surprising sign changes when assigning enum values to a
12844 // bitfield of different signedness. If the bitfield is signed and we
12845 // have exactly the right number of bits to store this unsigned enum,
12846 // suggest changing the enum to an unsigned type. This typically happens
12847 // on Windows where unfixed enums always use an underlying type of 'int'.
12848 unsigned DiagID = 0;
12849 if (SignedEnum && !SignedBitfield) {
12850 DiagID =
12851 PTAttr == nullptr
12852 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12853 : diag::
12854 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12855 } else if (SignedBitfield && !SignedEnum &&
12856 ED->getNumPositiveBits() == FieldWidth) {
12857 DiagID =
12858 PTAttr == nullptr
12859 ? diag::warn_signed_bitfield_enum_conversion
12860 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12861 }
12862 if (DiagID) {
12863 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12864 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12865 SourceRange TypeRange =
12866 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12867 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12868 << SignedEnum << TypeRange;
12869 if (PTAttr)
12870 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12871 << ED;
12872 }
12873
12874 // Compute the required bitwidth. If the enum has negative values, we need
12875 // one more bit than the normal number of positive bits to represent the
12876 // sign bit.
12877 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12878 ED->getNumNegativeBits())
12879 : ED->getNumPositiveBits();
12880
12881 // Check the bitwidth.
12882 if (BitsNeeded > FieldWidth) {
12883 Expr *WidthExpr = Bitfield->getBitWidth();
12884 auto DiagID =
12885 PTAttr == nullptr
12886 ? diag::warn_bitfield_too_small_for_enum
12887 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12888 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12889 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12890 << BitsNeeded << ED << WidthExpr->getSourceRange();
12891 if (PTAttr)
12892 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12893 << ED;
12894 }
12895 }
12896
12897 return false;
12898 }
12899
12900 llvm::APSInt Value = Result.Val.getInt();
12901
12902 unsigned OriginalWidth = Value.getBitWidth();
12903
12904 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12905 // false positives where the user is demonstrating they intend to use the
12906 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12907 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12908 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12909 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12910 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12911 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12912 S.findMacroSpelling(MaybeMacroLoc, "true"))
12913 return false;
12914 }
12915
12916 if (!Value.isSigned() || Value.isNegative())
12917 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12918 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12919 OriginalWidth = Value.getSignificantBits();
12920
12921 if (OriginalWidth <= FieldWidth)
12922 return false;
12923
12924 // Compute the value which the bitfield will contain.
12925 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12926 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12927
12928 // Check whether the stored value is equal to the original value.
12929 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12930 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12931 return false;
12932
12933 std::string PrettyValue = toString(Value, 10);
12934 std::string PrettyTrunc = toString(TruncatedValue, 10);
12935
12936 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12937 ? diag::warn_impcast_single_bit_bitield_precision_constant
12938 : diag::warn_impcast_bitfield_precision_constant)
12939 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12940 << Init->getSourceRange();
12941
12942 return true;
12943}
12944
12945/// Analyze the given simple or compound assignment for warning-worthy
12946/// operations.
12948 // Just recurse on the LHS.
12950
12951 // We want to recurse on the RHS as normal unless we're assigning to
12952 // a bitfield.
12953 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12954 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12955 E->getOperatorLoc())) {
12956 // Recurse, ignoring any implicit conversions on the RHS.
12958 E->getOperatorLoc());
12959 }
12960 }
12961
12962 // Set context flag for overflow behavior type assignment analysis, use RAII
12963 // pattern to handle nested assignments.
12964 llvm::SaveAndRestore OBTAssignmentContext(
12966
12968
12969 // Diagnose implicitly sequentially-consistent atomic assignment.
12970 if (E->getLHS()->getType()->isAtomicType())
12971 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12972}
12973
12974/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12975static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12976 QualType T, SourceLocation CContext, unsigned diag,
12977 bool PruneControlFlow = false) {
12978 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12979 // address space annotations isn't really useful. The warnings aren't because
12980 // you're converting a `private int` to `unsigned int`, it is because you're
12981 // conerting `int` to `unsigned int`.
12982 if (SourceType.hasAddressSpace())
12983 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12984 if (T.hasAddressSpace())
12986 if (PruneControlFlow) {
12988 S.PDiag(diag)
12989 << SourceType << T << E->getSourceRange()
12990 << SourceRange(CContext));
12991 return;
12992 }
12993 S.Diag(E->getExprLoc(), diag)
12994 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12995}
12996
12997/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12998static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12999 SourceLocation CContext, unsigned diag,
13000 bool PruneControlFlow = false) {
13001 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
13002}
13003
13004/// Diagnose an implicit cast from a floating point value to an integer value.
13005static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13006 SourceLocation CContext) {
13007 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13008 bool PruneWarnings = S.inTemplateInstantiation();
13009
13010 const Expr *InnerE = E->IgnoreParenImpCasts();
13011 // We also want to warn on, e.g., "int i = -1.234"
13012 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13013 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13014 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13015
13016 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13017
13018 llvm::APFloat Value(0.0);
13019 bool IsConstant =
13021 if (!IsConstant) {
13022 if (S.ObjC().isSignedCharBool(T)) {
13024 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13025 << E->getType());
13026 }
13027
13028 return DiagnoseImpCast(S, E, T, CContext,
13029 diag::warn_impcast_float_integer, PruneWarnings);
13030 }
13031
13032 bool isExact = false;
13033
13034 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13035 T->hasUnsignedIntegerRepresentation());
13036 llvm::APFloat::opStatus Result = Value.convertToInteger(
13037 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13038
13039 // FIXME: Force the precision of the source value down so we don't print
13040 // digits which are usually useless (we don't really care here if we
13041 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13042 // would automatically print the shortest representation, but it's a bit
13043 // tricky to implement.
13044 SmallString<16> PrettySourceValue;
13045 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13046 precision = (precision * 59 + 195) / 196;
13047 Value.toString(PrettySourceValue, precision);
13048
13049 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
13051 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13052 << PrettySourceValue);
13053 }
13054
13055 if (Result == llvm::APFloat::opOK && isExact) {
13056 if (IsLiteral) return;
13057 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13058 PruneWarnings);
13059 }
13060
13061 // Conversion of a floating-point value to a non-bool integer where the
13062 // integral part cannot be represented by the integer type is undefined.
13063 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13064 return DiagnoseImpCast(
13065 S, E, T, CContext,
13066 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13067 : diag::warn_impcast_float_to_integer_out_of_range,
13068 PruneWarnings);
13069
13070 unsigned DiagID = 0;
13071 if (IsLiteral) {
13072 // Warn on floating point literal to integer.
13073 DiagID = diag::warn_impcast_literal_float_to_integer;
13074 } else if (IntegerValue == 0) {
13075 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13076 return DiagnoseImpCast(S, E, T, CContext,
13077 diag::warn_impcast_float_integer, PruneWarnings);
13078 }
13079 // Warn on non-zero to zero conversion.
13080 DiagID = diag::warn_impcast_float_to_integer_zero;
13081 } else {
13082 if (IntegerValue.isUnsigned()) {
13083 if (!IntegerValue.isMaxValue()) {
13084 return DiagnoseImpCast(S, E, T, CContext,
13085 diag::warn_impcast_float_integer, PruneWarnings);
13086 }
13087 } else { // IntegerValue.isSigned()
13088 if (!IntegerValue.isMaxSignedValue() &&
13089 !IntegerValue.isMinSignedValue()) {
13090 return DiagnoseImpCast(S, E, T, CContext,
13091 diag::warn_impcast_float_integer, PruneWarnings);
13092 }
13093 }
13094 // Warn on evaluatable floating point expression to integer conversion.
13095 DiagID = diag::warn_impcast_float_to_integer;
13096 }
13097
13098 SmallString<16> PrettyTargetValue;
13099 if (IsBool)
13100 PrettyTargetValue = Value.isZero() ? "false" : "true";
13101 else
13102 IntegerValue.toString(PrettyTargetValue);
13103
13104 if (PruneWarnings) {
13106 S.PDiag(DiagID)
13107 << E->getType() << T.getUnqualifiedType()
13108 << PrettySourceValue << PrettyTargetValue
13109 << E->getSourceRange() << SourceRange(CContext));
13110 } else {
13111 S.Diag(E->getExprLoc(), DiagID)
13112 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13113 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13114 }
13115}
13116
13117/// Analyze the given compound assignment for the possible losing of
13118/// floating-point precision.
13120 assert(isa<CompoundAssignOperator>(E) &&
13121 "Must be compound assignment operation");
13122 // Recurse on the LHS and RHS in here
13125
13126 if (E->getLHS()->getType()->isAtomicType())
13127 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13128
13129 // Now check the outermost expression
13130 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13131 const auto *RBT = cast<CompoundAssignOperator>(E)
13132 ->getComputationResultType()
13133 ->getAs<BuiltinType>();
13134
13135 // The below checks assume source is floating point.
13136 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13137
13138 // If source is floating point but target is an integer.
13139 if (ResultBT->isInteger())
13140 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13141 E->getExprLoc(), diag::warn_impcast_float_integer);
13142
13143 if (!ResultBT->isFloatingPoint())
13144 return;
13145
13146 // If both source and target are floating points, warn about losing precision.
13148 QualType(ResultBT, 0), QualType(RBT, 0));
13149 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13150 // warn about dropping FP rank.
13151 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13152 diag::warn_impcast_float_result_precision);
13153}
13154
13155static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13156 IntRange Range) {
13157 if (!Range.Width) return "0";
13158
13159 llvm::APSInt ValueInRange = Value;
13160 ValueInRange.setIsSigned(!Range.NonNegative);
13161 ValueInRange = ValueInRange.trunc(Range.Width);
13162 return toString(ValueInRange, 10);
13163}
13164
13165static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13166 bool ToBool) {
13167 if (!isa<ImplicitCastExpr>(Ex))
13168 return false;
13169
13170 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13172 const Type *Source =
13174 if (Target->isDependentType())
13175 return false;
13176
13177 const auto *FloatCandidateBT =
13178 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13179 const Type *BoolCandidateType = ToBool ? Target : Source;
13180
13181 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13182 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13183}
13184
13185static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13186 SourceLocation CC) {
13187 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13188 const Expr *CurrA = TheCall->getArg(I);
13189 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13190 continue;
13191
13192 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13193 S, TheCall->getArg(I - 1), false));
13194 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13195 S, TheCall->getArg(I + 1), false));
13196 if (IsSwapped) {
13197 // Warn on this floating-point to bool conversion.
13199 CurrA->getType(), CC,
13200 diag::warn_impcast_floating_point_to_bool);
13201 }
13202 }
13203}
13204
13206 SourceLocation CC) {
13207 // Don't warn on functions which have return type nullptr_t.
13208 if (isa<CallExpr>(E))
13209 return;
13210
13211 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13212 const Expr *NewE = E->IgnoreParenImpCasts();
13213 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13214 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13215 if (!IsGNUNullExpr && !HasNullPtrType)
13216 return;
13217
13218 // Return if target type is a safe conversion.
13219 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13220 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13221 return;
13222
13223 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13224 E->getExprLoc()))
13225 return;
13226
13228
13229 // Venture through the macro stacks to get to the source of macro arguments.
13230 // The new location is a better location than the complete location that was
13231 // passed in.
13232 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13234
13235 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13236 if (IsGNUNullExpr && Loc.isMacroID()) {
13237 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13238 Loc, S.SourceMgr, S.getLangOpts());
13239 if (MacroName == "NULL")
13241 }
13242
13243 // Only warn if the null and context location are in the same macro expansion.
13244 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13245 return;
13246
13247 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13248 << HasNullPtrType << T << SourceRange(CC)
13251}
13252
13253// Helper function to filter out cases for constant width constant conversion.
13254// Don't warn on char array initialization or for non-decimal values.
13256 SourceLocation CC) {
13257 // If initializing from a constant, and the constant starts with '0',
13258 // then it is a binary, octal, or hexadecimal. Allow these constants
13259 // to fill all the bits, even if there is a sign change.
13260 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13261 const char FirstLiteralCharacter =
13262 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13263 if (FirstLiteralCharacter == '0')
13264 return false;
13265 }
13266
13267 // If the CC location points to a '{', and the type is char, then assume
13268 // assume it is an array initialization.
13269 if (CC.isValid() && T->isCharType()) {
13270 const char FirstContextCharacter =
13272 if (FirstContextCharacter == '{')
13273 return false;
13274 }
13275
13276 return true;
13277}
13278
13280 const auto *IL = dyn_cast<IntegerLiteral>(E);
13281 if (!IL) {
13282 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13283 if (UO->getOpcode() == UO_Minus)
13284 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13285 }
13286 }
13287
13288 return IL;
13289}
13290
13292 E = E->IgnoreParenImpCasts();
13293 SourceLocation ExprLoc = E->getExprLoc();
13294
13295 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13296 BinaryOperator::Opcode Opc = BO->getOpcode();
13298 // Do not diagnose unsigned shifts.
13299 if (Opc == BO_Shl) {
13300 const auto *LHS = getIntegerLiteral(BO->getLHS());
13301 const auto *RHS = getIntegerLiteral(BO->getRHS());
13302 if (LHS && LHS->getValue() == 0)
13303 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13304 else if (!E->isValueDependent() && LHS && RHS &&
13305 RHS->getValue().isNonNegative() &&
13307 S.Diag(ExprLoc, diag::warn_left_shift_always)
13308 << (Result.Val.getInt() != 0);
13309 else if (E->getType()->isSignedIntegerType())
13310 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13313 ") != 0");
13314 }
13315 }
13316
13317 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13318 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13319 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13320 if (!LHS || !RHS)
13321 return;
13322 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13323 (RHS->getValue() == 0 || RHS->getValue() == 1))
13324 // Do not diagnose common idioms.
13325 return;
13326 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13327 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13328 }
13329}
13330
13332 const Type *Target, Expr *E,
13333 QualType T,
13334 SourceLocation CC) {
13335 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13336 Source != Target);
13337
13338 // Lone surrogates have a distinct representation in UTF-32.
13339 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13340 // so don't warn on such conversion.
13341 if (Source->isChar16Type() && Target->isChar32Type())
13342 return;
13343
13347 llvm::APSInt Value(32);
13348 Value = Result.Val.getInt();
13349 bool IsASCII = Value <= 0x7F;
13350 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13351 bool ConversionPreservesSemantics =
13352 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13353
13354 if (!ConversionPreservesSemantics) {
13355 auto IsSingleCodeUnitCP = [](const QualType &T,
13356 const llvm::APSInt &Value) {
13357 if (T->isChar8Type())
13358 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13359 if (T->isChar16Type())
13360 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13361 assert(T->isChar32Type());
13362 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13363 };
13364
13365 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13366 << E->getType() << T
13367 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13368 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13369 }
13370 } else {
13371 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13373 DiagnoseImpCast(S, E, T, CC,
13374 LosesPrecision ? diag::warn_impcast_unicode_precision
13375 : diag::warn_impcast_unicode_char_type);
13376 }
13377}
13378
13380 From = Context.getCanonicalType(From);
13381 To = Context.getCanonicalType(To);
13382 QualType MaybePointee = From->getPointeeType();
13383 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13384 From = MaybePointee;
13385 MaybePointee = To->getPointeeType();
13386 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13387 To = MaybePointee;
13388
13389 if (const auto *FromFn = From->getAs<FunctionType>()) {
13390 if (const auto *ToFn = To->getAs<FunctionType>()) {
13391 if (FromFn->getCFIUncheckedCalleeAttr() &&
13392 !ToFn->getCFIUncheckedCalleeAttr())
13393 return true;
13394 }
13395 }
13396 return false;
13397}
13398
13400 bool *ICContext, bool IsListInit) {
13401 if (E->isTypeDependent() || E->isValueDependent()) return;
13402
13403 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13404 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13405 if (Source == Target) return;
13406 if (Target->isDependentType()) return;
13407
13408 // If the conversion context location is invalid don't complain. We also
13409 // don't want to emit a warning if the issue occurs from the expansion of
13410 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13411 // delay this check as long as possible. Once we detect we are in that
13412 // scenario, we just return.
13413 if (CC.isInvalid())
13414 return;
13415
13416 if (Source->isAtomicType())
13417 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13418
13419 // Diagnose implicit casts to bool.
13420 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13421 if (isa<StringLiteral>(E))
13422 // Warn on string literal to bool. Checks for string literals in logical
13423 // and expressions, for instance, assert(0 && "error here"), are
13424 // prevented by a check in AnalyzeImplicitConversions().
13425 return DiagnoseImpCast(*this, E, T, CC,
13426 diag::warn_impcast_string_literal_to_bool);
13429 // This covers the literal expressions that evaluate to Objective-C
13430 // objects.
13431 return DiagnoseImpCast(*this, E, T, CC,
13432 diag::warn_impcast_objective_c_literal_to_bool);
13433 }
13434 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13435 // Warn on pointer to bool conversion that is always true.
13437 SourceRange(CC));
13438 }
13439 }
13440
13442
13443 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13444 // is a typedef for signed char (macOS), then that constant value has to be 1
13445 // or 0.
13446 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13449 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13451 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13452 << toString(Result.Val.getInt(), 10));
13453 }
13454 return;
13455 }
13456 }
13457
13458 // Check implicit casts from Objective-C collection literals to specialized
13459 // collection types, e.g., NSArray<NSString *> *.
13460 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13461 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13462 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13463 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13464
13465 // Strip complex types.
13466 if (isa<ComplexType>(Source)) {
13467 if (!isa<ComplexType>(Target)) {
13468 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13469 return;
13470
13471 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13472 return DiagnoseImpCast(*this, E, T, CC,
13473 diag::err_impcast_incompatible_type);
13474 }
13475
13476 return DiagnoseImpCast(*this, E, T, CC,
13478 ? diag::err_impcast_complex_scalar
13479 : diag::warn_impcast_complex_scalar);
13480 }
13481
13482 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13483 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13484 }
13485
13486 // Strip vector types.
13487 if (isa<VectorType>(Source)) {
13488 if (Target->isSveVLSBuiltinType() &&
13489 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13490 QualType(Source, 0)) ||
13491 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13492 QualType(Source, 0))))
13493 return;
13494
13495 if (Target->isRVVVLSBuiltinType() &&
13496 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13497 QualType(Source, 0)) ||
13498 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13499 QualType(Source, 0))))
13500 return;
13501
13502 if (!isa<VectorType>(Target)) {
13503 if (SourceMgr.isInSystemMacro(CC))
13504 return;
13505 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13506 }
13507 if (getLangOpts().HLSL &&
13508 Target->castAs<VectorType>()->getNumElements() <
13509 Source->castAs<VectorType>()->getNumElements()) {
13510 // Diagnose vector truncation but don't return. We may also want to
13511 // diagnose an element conversion.
13512 DiagnoseImpCast(*this, E, T, CC,
13513 diag::warn_hlsl_impcast_vector_truncation);
13514 }
13515
13516 // If the vector cast is cast between two vectors of the same size, it is
13517 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13518 if (!getLangOpts().HLSL &&
13519 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13520 return;
13521
13522 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13523 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13524 }
13525 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13526 Target = VecTy->getElementType().getTypePtr();
13527
13528 // Strip matrix types.
13529 if (isa<ConstantMatrixType>(Source)) {
13530 if (Target->isScalarType())
13531 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13532
13535 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13536 // Diagnose Matrix truncation but don't return. We may also want to
13537 // diagnose an element conversion.
13538 DiagnoseImpCast(*this, E, T, CC,
13539 diag::warn_hlsl_impcast_matrix_truncation);
13540 }
13541
13542 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13543 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13544 }
13545 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13546 Target = MatTy->getElementType().getTypePtr();
13547
13548 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13549 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13550
13551 // Strip SVE vector types
13552 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13553 // Need the original target type for vector type checks
13554 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13555 // Handle conversion from scalable to fixed when msve-vector-bits is
13556 // specified
13557 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13558 QualType(Source, 0)) ||
13559 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13560 QualType(Source, 0)))
13561 return;
13562
13563 // If the vector cast is cast between two vectors of the same size, it is
13564 // a bitcast, not a conversion.
13565 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13566 return;
13567
13568 Source = SourceBT->getSveEltType(Context).getTypePtr();
13569 }
13570
13571 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13572 Target = TargetBT->getSveEltType(Context).getTypePtr();
13573
13574 // If the source is floating point...
13575 if (SourceBT && SourceBT->isFloatingPoint()) {
13576 // ...and the target is floating point...
13577 if (TargetBT && TargetBT->isFloatingPoint()) {
13578 // ...then warn if we're dropping FP rank.
13579
13581 QualType(SourceBT, 0), QualType(TargetBT, 0));
13582 if (Order > 0) {
13583 // Don't warn about float constants that are precisely
13584 // representable in the target type.
13585 Expr::EvalResult result;
13586 if (E->EvaluateAsRValue(result, Context)) {
13587 // Value might be a float, a float vector, or a float complex.
13589 result.Val,
13590 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13591 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13592 return;
13593 }
13594
13595 if (SourceMgr.isInSystemMacro(CC))
13596 return;
13597
13598 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13599 }
13600 // ... or possibly if we're increasing rank, too
13601 else if (Order < 0) {
13602 if (SourceMgr.isInSystemMacro(CC))
13603 return;
13604
13605 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13606 }
13607 return;
13608 }
13609
13610 // If the target is integral, always warn.
13611 if (TargetBT && TargetBT->isInteger()) {
13612 if (SourceMgr.isInSystemMacro(CC))
13613 return;
13614
13615 DiagnoseFloatingImpCast(*this, E, T, CC);
13616 }
13617
13618 // Detect the case where a call result is converted from floating-point to
13619 // to bool, and the final argument to the call is converted from bool, to
13620 // discover this typo:
13621 //
13622 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13623 //
13624 // FIXME: This is an incredibly special case; is there some more general
13625 // way to detect this class of misplaced-parentheses bug?
13626 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13627 // Check last argument of function call to see if it is an
13628 // implicit cast from a type matching the type the result
13629 // is being cast to.
13630 CallExpr *CEx = cast<CallExpr>(E);
13631 if (unsigned NumArgs = CEx->getNumArgs()) {
13632 Expr *LastA = CEx->getArg(NumArgs - 1);
13633 Expr *InnerE = LastA->IgnoreParenImpCasts();
13634 if (isa<ImplicitCastExpr>(LastA) &&
13635 InnerE->getType()->isBooleanType()) {
13636 // Warn on this floating-point to bool conversion
13637 DiagnoseImpCast(*this, E, T, CC,
13638 diag::warn_impcast_floating_point_to_bool);
13639 }
13640 }
13641 }
13642 return;
13643 }
13644
13645 // Valid casts involving fixed point types should be accounted for here.
13646 if (Source->isFixedPointType()) {
13647 if (Target->isUnsaturatedFixedPointType()) {
13651 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13652 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13653 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13654 if (Value > MaxVal || Value < MinVal) {
13656 PDiag(diag::warn_impcast_fixed_point_range)
13657 << Value.toString() << T
13658 << E->getSourceRange()
13659 << clang::SourceRange(CC));
13660 return;
13661 }
13662 }
13663 } else if (Target->isIntegerType()) {
13667 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13668
13669 bool Overflowed;
13670 llvm::APSInt IntResult = FXResult.convertToInt(
13671 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13672 &Overflowed);
13673
13674 if (Overflowed) {
13676 PDiag(diag::warn_impcast_fixed_point_range)
13677 << FXResult.toString() << T
13678 << E->getSourceRange()
13679 << clang::SourceRange(CC));
13680 return;
13681 }
13682 }
13683 }
13684 } else if (Target->isUnsaturatedFixedPointType()) {
13685 if (Source->isIntegerType()) {
13689 llvm::APSInt Value = Result.Val.getInt();
13690
13691 bool Overflowed;
13692 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13693 Value, Context.getFixedPointSemantics(T), &Overflowed);
13694
13695 if (Overflowed) {
13697 PDiag(diag::warn_impcast_fixed_point_range)
13698 << toString(Value, /*Radix=*/10) << T
13699 << E->getSourceRange()
13700 << clang::SourceRange(CC));
13701 return;
13702 }
13703 }
13704 }
13705 }
13706
13707 // If we are casting an integer type to a floating point type without
13708 // initialization-list syntax, we might lose accuracy if the floating
13709 // point type has a narrower significand than the integer type.
13710 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13711 TargetBT->isFloatingType() && !IsListInit) {
13712 // Determine the number of precision bits in the source integer type.
13713 std::optional<IntRange> SourceRange =
13715 /*Approximate=*/true);
13716 if (!SourceRange)
13717 return;
13718 unsigned int SourcePrecision = SourceRange->Width;
13719
13720 // Determine the number of precision bits in the
13721 // target floating point type.
13722 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13723 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13724
13725 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13726 SourcePrecision > TargetPrecision) {
13727
13728 if (std::optional<llvm::APSInt> SourceInt =
13730 // If the source integer is a constant, convert it to the target
13731 // floating point type. Issue a warning if the value changes
13732 // during the whole conversion.
13733 llvm::APFloat TargetFloatValue(
13734 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13735 llvm::APFloat::opStatus ConversionStatus =
13736 TargetFloatValue.convertFromAPInt(
13737 *SourceInt, SourceBT->isSignedInteger(),
13738 llvm::APFloat::rmNearestTiesToEven);
13739
13740 if (ConversionStatus != llvm::APFloat::opOK) {
13741 SmallString<32> PrettySourceValue;
13742 SourceInt->toString(PrettySourceValue, 10);
13743 SmallString<32> PrettyTargetValue;
13744 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13745
13747 E->getExprLoc(), E,
13748 PDiag(diag::warn_impcast_integer_float_precision_constant)
13749 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13750 << E->getSourceRange() << clang::SourceRange(CC));
13751 }
13752 } else {
13753 // Otherwise, the implicit conversion may lose precision.
13754 DiagnoseImpCast(*this, E, T, CC,
13755 diag::warn_impcast_integer_float_precision);
13756 }
13757 }
13758 }
13759
13760 DiagnoseNullConversion(*this, E, T, CC);
13761
13763
13764 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13765 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13766 return;
13767 }
13768
13769 if (Target->isBooleanType())
13770 DiagnoseIntInBoolContext(*this, E);
13771
13773 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13774 << QualType(Source, 0) << QualType(Target, 0);
13775 }
13776
13777 if (!Source->isIntegerType() || !Target->isIntegerType())
13778 return;
13779
13780 // TODO: remove this early return once the false positives for constant->bool
13781 // in templates, macros, etc, are reduced or removed.
13782 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13783 return;
13784
13785 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13786 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13788 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13789 << E->getType());
13790 }
13791 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13792 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13793 if (!LikelySourceRange)
13794 return;
13795
13796 IntRange SourceTypeRange =
13797 IntRange::forTargetOfCanonicalType(Context, Source);
13798 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13799
13800 if (LikelySourceRange->Width > TargetRange.Width) {
13801 // Check if target is a wrapping OBT - if so, don't warn about constant
13802 // conversion as this type may be used intentionally with implicit
13803 // truncation, especially during assignments.
13804 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13805 if (TargetOBT->isWrapKind()) {
13806 return;
13807 }
13808 }
13809
13810 // Check if source expression has an explicit __ob_wrap cast because if so,
13811 // wrapping was explicitly requested and we shouldn't warn
13812 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13813 if (SourceOBT->isWrapKind()) {
13814 return;
13815 }
13816 }
13817
13818 // If the source is a constant, use a default-on diagnostic.
13819 // TODO: this should happen for bitfield stores, too.
13823 llvm::APSInt Value(32);
13824 Value = Result.Val.getInt();
13825
13826 if (SourceMgr.isInSystemMacro(CC))
13827 return;
13828
13829 std::string PrettySourceValue = toString(Value, 10);
13830 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13831
13833 PDiag(diag::warn_impcast_integer_precision_constant)
13834 << PrettySourceValue << PrettyTargetValue
13835 << E->getType() << T << E->getSourceRange()
13836 << SourceRange(CC));
13837 return;
13838 }
13839
13840 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13841 if (SourceMgr.isInSystemMacro(CC))
13842 return;
13843
13844 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13845 if (UO->getOpcode() == UO_Minus)
13846 return DiagnoseImpCast(
13847 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13848 }
13849
13850 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13851 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13852 /* pruneControlFlow */ true);
13853 return DiagnoseImpCast(*this, E, T, CC,
13854 diag::warn_impcast_integer_precision);
13855 }
13856
13857 if (TargetRange.Width > SourceTypeRange.Width) {
13858 if (auto *UO = dyn_cast<UnaryOperator>(E))
13859 if (UO->getOpcode() == UO_Minus)
13860 if (Source->isUnsignedIntegerType()) {
13861 if (Target->isUnsignedIntegerType())
13862 return DiagnoseImpCast(*this, E, T, CC,
13863 diag::warn_impcast_high_order_zero_bits);
13864 if (Target->isSignedIntegerType())
13865 return DiagnoseImpCast(*this, E, T, CC,
13866 diag::warn_impcast_nonnegative_result);
13867 }
13868 }
13869
13870 if (TargetRange.Width == LikelySourceRange->Width &&
13871 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13872 Source->isSignedIntegerType()) {
13873 // Warn when doing a signed to signed conversion, warn if the positive
13874 // source value is exactly the width of the target type, which will
13875 // cause a negative value to be stored.
13876
13879 !SourceMgr.isInSystemMacro(CC)) {
13880 llvm::APSInt Value = Result.Val.getInt();
13881 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13882 std::string PrettySourceValue = toString(Value, 10);
13883 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13884
13885 Diag(E->getExprLoc(),
13886 PDiag(diag::warn_impcast_integer_precision_constant)
13887 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13888 << E->getSourceRange() << SourceRange(CC));
13889 return;
13890 }
13891 }
13892
13893 // Fall through for non-constants to give a sign conversion warning.
13894 }
13895
13896 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13897 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13898 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13899 LikelySourceRange->Width == TargetRange.Width))) {
13900 if (SourceMgr.isInSystemMacro(CC))
13901 return;
13902
13903 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13904 TargetBT->isInteger() &&
13905 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13906 return;
13907 }
13908
13909 unsigned DiagID = diag::warn_impcast_integer_sign;
13910
13911 // Traditionally, gcc has warned about this under -Wsign-compare.
13912 // We also want to warn about it in -Wconversion.
13913 // So if -Wconversion is off, use a completely identical diagnostic
13914 // in the sign-compare group.
13915 // The conditional-checking code will
13916 if (ICContext) {
13917 DiagID = diag::warn_impcast_integer_sign_conditional;
13918 *ICContext = true;
13919 }
13920
13921 DiagnoseImpCast(*this, E, T, CC, DiagID);
13922 }
13923
13924 // If we're implicitly converting from an integer into an enumeration, that
13925 // is valid in C but invalid in C++.
13926 QualType SourceType = E->getEnumCoercedType(Context);
13927 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13928 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13929 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13930
13931 // Diagnose conversions between different enumeration types.
13932 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13933 // type, to give us better diagnostics.
13934 Source = Context.getCanonicalType(SourceType).getTypePtr();
13935
13936 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13937 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13938 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13939 TargetEnum->getDecl()->hasNameForLinkage() &&
13940 SourceEnum != TargetEnum) {
13941 if (SourceMgr.isInSystemMacro(CC))
13942 return;
13943
13944 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13945 diag::warn_impcast_different_enum_types);
13946 }
13947}
13948
13951
13953 SourceLocation CC, bool &ICContext) {
13954 E = E->IgnoreParenImpCasts();
13955 // Diagnose incomplete type for second or third operand in C.
13956 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13957 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13958
13959 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13960 return CheckConditionalOperator(S, CO, CC, T);
13961
13963 if (E->getType() != T)
13964 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13965}
13966
13970
13971 Expr *TrueExpr = E->getTrueExpr();
13972 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13973 TrueExpr = BCO->getCommon();
13974
13975 bool Suspicious = false;
13976 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13977 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13978
13979 if (T->isBooleanType())
13981
13982 // If -Wconversion would have warned about either of the candidates
13983 // for a signedness conversion to the context type...
13984 if (!Suspicious) return;
13985
13986 // ...but it's currently ignored...
13987 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13988 return;
13989
13990 // ...then check whether it would have warned about either of the
13991 // candidates for a signedness conversion to the condition type.
13992 if (E->getType() == T) return;
13993
13994 Suspicious = false;
13995 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13996 &Suspicious);
13997 if (!Suspicious)
13999 E->getType(), CC, &Suspicious);
14000}
14001
14002/// Check conversion of given expression to boolean.
14003/// Input argument E is a logical expression.
14005 // Run the bool-like conversion checks only for C since there bools are
14006 // still not used as the return type from "boolean" operators or as the input
14007 // type for conditional operators.
14008 if (S.getLangOpts().CPlusPlus)
14009 return;
14011 return;
14013}
14014
14015namespace {
14016struct AnalyzeImplicitConversionsWorkItem {
14017 Expr *E;
14018 SourceLocation CC;
14019 bool IsListInit;
14020};
14021}
14022
14024 Sema &S, Expr *E, QualType T, SourceLocation CC,
14025 bool ExtraCheckForImplicitConversion,
14027 E = E->IgnoreParenImpCasts();
14028 WorkList.push_back({E, CC, false});
14029
14030 if (ExtraCheckForImplicitConversion && E->getType() != T)
14031 S.CheckImplicitConversion(E, T, CC);
14032}
14033
14034/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14035/// that should be visited are added to WorkList.
14037 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14039 Expr *OrigE = Item.E;
14040 SourceLocation CC = Item.CC;
14041
14042 QualType T = OrigE->getType();
14043 Expr *E = OrigE->IgnoreParenImpCasts();
14044
14045 // Propagate whether we are in a C++ list initialization expression.
14046 // If so, we do not issue warnings for implicit int-float conversion
14047 // precision loss, because C++11 narrowing already handles it.
14048 //
14049 // HLSL's initialization lists are special, so they shouldn't observe the C++
14050 // behavior here.
14051 bool IsListInit =
14052 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
14053 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14054
14055 if (E->isTypeDependent() || E->isValueDependent())
14056 return;
14057
14058 Expr *SourceExpr = E;
14059 // Examine, but don't traverse into the source expression of an
14060 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14061 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14062 // evaluate it in the context of checking the specific conversion to T though.
14063 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14064 if (auto *Src = OVE->getSourceExpr())
14065 SourceExpr = Src;
14066
14067 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14068 if (UO->getOpcode() == UO_Not &&
14069 UO->getSubExpr()->isKnownToHaveBooleanValue())
14070 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14071 << OrigE->getSourceRange() << T->isBooleanType()
14072 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14073
14074 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14075 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14076 BO->getLHS()->isKnownToHaveBooleanValue() &&
14077 BO->getRHS()->isKnownToHaveBooleanValue() &&
14078 BO->getLHS()->HasSideEffects(S.Context) &&
14079 BO->getRHS()->HasSideEffects(S.Context)) {
14081 const LangOptions &LO = S.getLangOpts();
14082 SourceLocation BLoc = BO->getOperatorLoc();
14083 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
14084 StringRef SR = clang::Lexer::getSourceText(
14085 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
14086 // To reduce false positives, only issue the diagnostic if the operator
14087 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14088 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14089 // in C, along with other macro spellings the user might invent.
14090 if (SR.str() == "&" || SR.str() == "|") {
14091
14092 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14093 << (BO->getOpcode() == BO_And ? "&" : "|")
14094 << OrigE->getSourceRange()
14096 BO->getOperatorLoc(),
14097 (BO->getOpcode() == BO_And ? "&&" : "||"));
14098 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14099 }
14100 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14101 /// Analyze the given comma operator. The basic idea behind the analysis
14102 /// is to analyze the left and right operands slightly differently. The
14103 /// left operand needs to check whether the operand itself has an implicit
14104 /// conversion, but not whether the left operand induces an implicit
14105 /// conversion for the entire comma expression itself. This is similar to
14106 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14107 /// were directly used for the implicit conversion check.
14108 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
14109 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14110 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
14111 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14112 return;
14113 }
14114 }
14115
14116 // For conditional operators, we analyze the arguments as if they
14117 // were being fed directly into the output.
14118 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14119 CheckConditionalOperator(S, CO, CC, T);
14120 return;
14121 }
14122
14123 // Check implicit argument conversions for function calls.
14124 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14126
14127 // Go ahead and check any implicit conversions we might have skipped.
14128 // The non-canonical typecheck is just an optimization;
14129 // CheckImplicitConversion will filter out dead implicit conversions.
14130 if (SourceExpr->getType() != T)
14131 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14132
14133 // Now continue drilling into this expression.
14134
14135 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14136 // The bound subexpressions in a PseudoObjectExpr are not reachable
14137 // as transitive children.
14138 // FIXME: Use a more uniform representation for this.
14139 for (auto *SE : POE->semantics())
14140 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14141 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14142 }
14143
14144 // Skip past explicit casts.
14145 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14146 E = CE->getSubExpr();
14147 // In the special case of a C++ function-style cast with braces,
14148 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14149 // initializer. This InitListExpr basically belongs to the cast itself, so
14150 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14152 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14153 if (InitListE->getNumInits() == 1) {
14154 E = InitListE->getInit(0);
14155 }
14156 }
14157 }
14158 E = E->IgnoreParenImpCasts();
14159 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14160 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14161 WorkList.push_back({E, CC, IsListInit});
14162 return;
14163 }
14164
14165 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14166 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14167 // The base expression is only used to initialize the parameter for
14168 // arguments to `inout` parameters, so we only traverse down the base
14169 // expression for `inout` cases.
14170 if (OutArgE->isInOut())
14171 WorkList.push_back(
14172 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14173 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14174 return;
14175 }
14176
14177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14178 // Do a somewhat different check with comparison operators.
14179 if (BO->isComparisonOp())
14180 return AnalyzeComparison(S, BO);
14181
14182 // And with simple assignments.
14183 if (BO->getOpcode() == BO_Assign)
14184 return AnalyzeAssignment(S, BO);
14185 // And with compound assignments.
14186 if (BO->isAssignmentOp())
14187 return AnalyzeCompoundAssignment(S, BO);
14188 }
14189
14190 // These break the otherwise-useful invariant below. Fortunately,
14191 // we don't really need to recurse into them, because any internal
14192 // expressions should have been analyzed already when they were
14193 // built into statements.
14194 if (isa<StmtExpr>(E)) return;
14195
14196 // Don't descend into unevaluated contexts.
14197 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14198
14199 // Now just recurse over the expression's children.
14200 CC = E->getExprLoc();
14201 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14202 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14203 for (Stmt *SubStmt : E->children()) {
14204 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14205 if (!ChildExpr)
14206 continue;
14207
14208 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14209 if (ChildExpr == CSE->getOperand())
14210 // Do not recurse over a CoroutineSuspendExpr's operand.
14211 // The operand is also a subexpression of getCommonExpr(), and
14212 // recursing into it directly would produce duplicate diagnostics.
14213 continue;
14214
14215 if (IsLogicalAndOperator &&
14217 // Ignore checking string literals that are in logical and operators.
14218 // This is a common pattern for asserts.
14219 continue;
14220 WorkList.push_back({ChildExpr, CC, IsListInit});
14221 }
14222
14223 if (BO && BO->isLogicalOp()) {
14224 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14225 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14226 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14227
14228 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14229 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14230 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14231 }
14232
14233 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14234 if (U->getOpcode() == UO_LNot) {
14235 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14236 } else if (U->getOpcode() != UO_AddrOf) {
14237 if (U->getSubExpr()->getType()->isAtomicType())
14238 S.Diag(U->getSubExpr()->getBeginLoc(),
14239 diag::warn_atomic_implicit_seq_cst);
14240 }
14241 }
14242}
14243
14244/// AnalyzeImplicitConversions - Find and report any interesting
14245/// implicit conversions in the given expression. There are a couple
14246/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14248 bool IsListInit/*= false*/) {
14250 WorkList.push_back({OrigE, CC, IsListInit});
14251 while (!WorkList.empty())
14252 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14253}
14254
14255// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14256// Returns true when emitting a warning about taking the address of a reference.
14257static bool CheckForReference(Sema &SemaRef, const Expr *E,
14258 const PartialDiagnostic &PD) {
14259 E = E->IgnoreParenImpCasts();
14260
14261 const FunctionDecl *FD = nullptr;
14262
14263 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14264 if (!DRE->getDecl()->getType()->isReferenceType())
14265 return false;
14266 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14267 if (!M->getMemberDecl()->getType()->isReferenceType())
14268 return false;
14269 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14270 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14271 return false;
14272 FD = Call->getDirectCallee();
14273 } else {
14274 return false;
14275 }
14276
14277 SemaRef.Diag(E->getExprLoc(), PD);
14278
14279 // If possible, point to location of function.
14280 if (FD) {
14281 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14282 }
14283
14284 return true;
14285}
14286
14287// Returns true if the SourceLocation is expanded from any macro body.
14288// Returns false if the SourceLocation is invalid, is from not in a macro
14289// expansion, or is from expanded from a top-level macro argument.
14291 if (Loc.isInvalid())
14292 return false;
14293
14294 while (Loc.isMacroID()) {
14295 if (SM.isMacroBodyExpansion(Loc))
14296 return true;
14297 Loc = SM.getImmediateMacroCallerLoc(Loc);
14298 }
14299
14300 return false;
14301}
14302
14305 bool IsEqual, SourceRange Range) {
14306 if (!E)
14307 return;
14308
14309 // Don't warn inside macros.
14310 if (E->getExprLoc().isMacroID()) {
14312 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14313 IsInAnyMacroBody(SM, Range.getBegin()))
14314 return;
14315 }
14316 E = E->IgnoreImpCasts();
14317
14318 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14319
14320 if (isa<CXXThisExpr>(E)) {
14321 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14322 : diag::warn_this_bool_conversion;
14323 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14324 return;
14325 }
14326
14327 bool IsAddressOf = false;
14328
14329 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14330 if (UO->getOpcode() != UO_AddrOf)
14331 return;
14332 IsAddressOf = true;
14333 E = UO->getSubExpr();
14334 }
14335
14336 if (IsAddressOf) {
14337 unsigned DiagID = IsCompare
14338 ? diag::warn_address_of_reference_null_compare
14339 : diag::warn_address_of_reference_bool_conversion;
14340 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14341 << IsEqual;
14342 if (CheckForReference(*this, E, PD)) {
14343 return;
14344 }
14345 }
14346
14347 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14348 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14349 std::string Str;
14350 llvm::raw_string_ostream S(Str);
14351 E->printPretty(S, nullptr, getPrintingPolicy());
14352 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14353 : diag::warn_cast_nonnull_to_bool;
14354 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14355 << E->getSourceRange() << Range << IsEqual;
14356 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14357 };
14358
14359 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14360 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14361 if (auto *Callee = Call->getDirectCallee()) {
14362 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14363 ComplainAboutNonnullParamOrCall(A);
14364 return;
14365 }
14366 }
14367 }
14368
14369 // Complain if we are converting a lambda expression to a boolean value
14370 // outside of instantiation.
14371 if (!inTemplateInstantiation()) {
14372 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14373 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14374 MRecordDecl && MRecordDecl->isLambda()) {
14375 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14376 << /*LambdaPointerConversionOperatorType=*/3
14377 << MRecordDecl->getSourceRange() << Range << IsEqual;
14378 return;
14379 }
14380 }
14381 }
14382
14383 // Expect to find a single Decl. Skip anything more complicated.
14384 ValueDecl *D = nullptr;
14385 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14386 D = R->getDecl();
14387 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14388 D = M->getMemberDecl();
14389 }
14390
14391 // Weak Decls can be null.
14392 if (!D || D->isWeak())
14393 return;
14394
14395 // Check for parameter decl with nonnull attribute
14396 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14397 if (getCurFunction() &&
14398 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14399 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14400 ComplainAboutNonnullParamOrCall(A);
14401 return;
14402 }
14403
14404 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14405 // Skip function template not specialized yet.
14407 return;
14408 auto ParamIter = llvm::find(FD->parameters(), PV);
14409 assert(ParamIter != FD->param_end());
14410 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14411
14412 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14413 if (!NonNull->args_size()) {
14414 ComplainAboutNonnullParamOrCall(NonNull);
14415 return;
14416 }
14417
14418 for (const ParamIdx &ArgNo : NonNull->args()) {
14419 if (ArgNo.getASTIndex() == ParamNo) {
14420 ComplainAboutNonnullParamOrCall(NonNull);
14421 return;
14422 }
14423 }
14424 }
14425 }
14426 }
14427 }
14428
14429 QualType T = D->getType();
14430 // A reference to a function is never null either; look through it.
14431 const bool IsFunctionReference =
14432 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14433 if (IsFunctionReference)
14434 T = T->getPointeeType();
14435 const bool IsArray = T->isArrayType();
14436 const bool IsFunction = T->isFunctionType();
14437
14438 // Address of function is used to silence the function warning.
14439 if (IsAddressOf && IsFunction) {
14440 return;
14441 }
14442
14443 // Found nothing.
14444 if (!IsAddressOf && !IsFunction && !IsArray)
14445 return;
14446
14447 // Pretty print the expression for the diagnostic.
14448 std::string Str;
14449 llvm::raw_string_ostream S(Str);
14450 E->printPretty(S, nullptr, getPrintingPolicy());
14451
14452 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14453 : diag::warn_impcast_pointer_to_bool;
14454 enum {
14455 AddressOf,
14456 FunctionPointer,
14457 ArrayPointer
14458 } DiagType;
14459 if (IsAddressOf)
14460 DiagType = AddressOf;
14461 else if (IsFunction)
14462 DiagType = FunctionPointer;
14463 else if (IsArray)
14464 DiagType = ArrayPointer;
14465 else
14466 llvm_unreachable("Could not determine diagnostic.");
14467 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14468 << Range << IsEqual;
14469
14470 // The fix-it notes below only apply to a bare function name, not a reference.
14471 if (!IsFunction || IsFunctionReference)
14472 return;
14473
14474 // Suggest '&' to silence the function warning.
14475 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14477
14478 // Check to see if '()' fixit should be emitted.
14479 QualType ReturnType;
14480 UnresolvedSet<4> NonTemplateOverloads;
14481 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14482 if (ReturnType.isNull())
14483 return;
14484
14485 if (IsCompare) {
14486 // There are two cases here. If there is null constant, the only suggest
14487 // for a pointer return type. If the null is 0, then suggest if the return
14488 // type is a pointer or an integer type.
14489 if (!ReturnType->isPointerType()) {
14490 if (NullKind == Expr::NPCK_ZeroExpression ||
14491 NullKind == Expr::NPCK_ZeroLiteral) {
14492 if (!ReturnType->isIntegerType())
14493 return;
14494 } else {
14495 return;
14496 }
14497 }
14498 } else { // !IsCompare
14499 // For function to bool, only suggest if the function pointer has bool
14500 // return type.
14501 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14502 return;
14503 }
14504 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14506}
14507
14509 SourceLocation CC) {
14510 QualType Source = E->getType();
14511 QualType Target = T;
14512
14513 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14514 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14515 // Overflow behavior type is being stripped - issue warning
14516 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14517 Target->isUnsignedIntegerType()) {
14518 // For unsigned wrap to unsigned conversions, use pedantic version
14519 unsigned DiagId =
14521 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14522 : diag::warn_impcast_overflow_behavior_pedantic;
14523 DiagnoseImpCast(*this, E, T, CC, DiagId);
14524 } else {
14525 unsigned DiagId = InOverflowBehaviorAssignmentContext
14526 ? diag::warn_impcast_overflow_behavior_assignment
14527 : diag::warn_impcast_overflow_behavior;
14528 DiagnoseImpCast(*this, E, T, CC, DiagId);
14529 }
14530 }
14531 }
14532
14533 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14534 if (TargetOBT->isWrapKind()) {
14535 return true;
14536 }
14537 }
14538
14539 return false;
14540}
14541
14542void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14543 // Don't diagnose in unevaluated contexts.
14545 return;
14546
14547 // Don't diagnose for value- or type-dependent expressions.
14548 if (E->isTypeDependent() || E->isValueDependent())
14549 return;
14550
14551 // Check for array bounds violations in cases where the check isn't triggered
14552 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14553 // ArraySubscriptExpr is on the RHS of a variable initialization.
14554 CheckArrayAccess(E);
14555
14556 // This is not the right CC for (e.g.) a variable initialization.
14557 AnalyzeImplicitConversions(*this, E, CC);
14558}
14559
14560void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14561 ::CheckBoolLikeConversion(*this, E, CC);
14562}
14563
14564void Sema::CheckForIntOverflow (const Expr *E) {
14565 // Use a work list to deal with nested struct initializers.
14566 SmallVector<const Expr *, 2> Exprs(1, E);
14567
14568 do {
14569 const Expr *OriginalE = Exprs.pop_back_val();
14570 const Expr *E = OriginalE->IgnoreParenCasts();
14571
14572 if (isa<BinaryOperator>(E) ||
14573 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14575 continue;
14576 }
14577
14578 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14579 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14580 else if (isa<ObjCBoxedExpr>(OriginalE))
14582 else if (const auto *Call = dyn_cast<CallExpr>(E))
14583 Exprs.append(Call->arg_begin(), Call->arg_end());
14584 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14585 Exprs.append(Message->arg_begin(), Message->arg_end());
14586 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14587 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14588 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14589 Exprs.push_back(Temporary->getSubExpr());
14590 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14591 Exprs.push_back(Array->getIdx());
14592 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14593 Exprs.push_back(Compound->getInitializer());
14594 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14595 New && New->isArray()) {
14596 if (auto ArraySize = New->getArraySize())
14597 Exprs.push_back(*ArraySize);
14598 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14599 Exprs.push_back(MTE->getSubExpr());
14600 } while (!Exprs.empty());
14601}
14602
14603namespace {
14604
14605/// Visitor for expressions which looks for unsequenced operations on the
14606/// same object.
14607class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14608 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14609
14610 /// A tree of sequenced regions within an expression. Two regions are
14611 /// unsequenced if one is an ancestor or a descendent of the other. When we
14612 /// finish processing an expression with sequencing, such as a comma
14613 /// expression, we fold its tree nodes into its parent, since they are
14614 /// unsequenced with respect to nodes we will visit later.
14615 class SequenceTree {
14616 struct Value {
14617 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14618 unsigned Parent : 31;
14619 LLVM_PREFERRED_TYPE(bool)
14620 unsigned Merged : 1;
14621 };
14622 SmallVector<Value, 8> Values;
14623
14624 public:
14625 /// A region within an expression which may be sequenced with respect
14626 /// to some other region.
14627 class Seq {
14628 friend class SequenceTree;
14629
14630 unsigned Index;
14631
14632 explicit Seq(unsigned N) : Index(N) {}
14633
14634 public:
14635 Seq() : Index(0) {}
14636 };
14637
14638 SequenceTree() { Values.push_back(Value(0)); }
14639 Seq root() const { return Seq(0); }
14640
14641 /// Create a new sequence of operations, which is an unsequenced
14642 /// subset of \p Parent. This sequence of operations is sequenced with
14643 /// respect to other children of \p Parent.
14644 Seq allocate(Seq Parent) {
14645 Values.push_back(Value(Parent.Index));
14646 return Seq(Values.size() - 1);
14647 }
14648
14649 /// Merge a sequence of operations into its parent.
14650 void merge(Seq S) {
14651 Values[S.Index].Merged = true;
14652 }
14653
14654 /// Determine whether two operations are unsequenced. This operation
14655 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14656 /// should have been merged into its parent as appropriate.
14657 bool isUnsequenced(Seq Cur, Seq Old) {
14658 unsigned C = representative(Cur.Index);
14659 unsigned Target = representative(Old.Index);
14660 while (C >= Target) {
14661 if (C == Target)
14662 return true;
14663 C = Values[C].Parent;
14664 }
14665 return false;
14666 }
14667
14668 private:
14669 /// Pick a representative for a sequence.
14670 unsigned representative(unsigned K) {
14671 if (Values[K].Merged)
14672 // Perform path compression as we go.
14673 return Values[K].Parent = representative(Values[K].Parent);
14674 return K;
14675 }
14676 };
14677
14678 /// An object for which we can track unsequenced uses.
14679 using Object = const NamedDecl *;
14680
14681 /// Different flavors of object usage which we track. We only track the
14682 /// least-sequenced usage of each kind.
14683 enum UsageKind {
14684 /// A read of an object. Multiple unsequenced reads are OK.
14685 UK_Use,
14686
14687 /// A modification of an object which is sequenced before the value
14688 /// computation of the expression, such as ++n in C++.
14689 UK_ModAsValue,
14690
14691 /// A modification of an object which is not sequenced before the value
14692 /// computation of the expression, such as n++.
14693 UK_ModAsSideEffect,
14694
14695 UK_Count = UK_ModAsSideEffect + 1
14696 };
14697
14698 /// Bundle together a sequencing region and the expression corresponding
14699 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14700 struct Usage {
14701 const Expr *UsageExpr = nullptr;
14702 SequenceTree::Seq Seq;
14703
14704 Usage() = default;
14705 };
14706
14707 struct UsageInfo {
14708 Usage Uses[UK_Count];
14709
14710 /// Have we issued a diagnostic for this object already?
14711 bool Diagnosed = false;
14712
14713 UsageInfo();
14714 };
14715 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14716
14717 Sema &SemaRef;
14718
14719 /// Sequenced regions within the expression.
14720 SequenceTree Tree;
14721
14722 /// Declaration modifications and references which we have seen.
14723 UsageInfoMap UsageMap;
14724
14725 /// The region we are currently within.
14726 SequenceTree::Seq Region;
14727
14728 /// Filled in with declarations which were modified as a side-effect
14729 /// (that is, post-increment operations).
14730 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14731
14732 /// Expressions to check later. We defer checking these to reduce
14733 /// stack usage.
14734 SmallVectorImpl<const Expr *> &WorkList;
14735
14736 /// RAII object wrapping the visitation of a sequenced subexpression of an
14737 /// expression. At the end of this process, the side-effects of the evaluation
14738 /// become sequenced with respect to the value computation of the result, so
14739 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14740 /// UK_ModAsValue.
14741 struct SequencedSubexpression {
14742 SequencedSubexpression(SequenceChecker &Self)
14743 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14744 Self.ModAsSideEffect = &ModAsSideEffect;
14745 }
14746
14747 ~SequencedSubexpression() {
14748 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14749 // Add a new usage with usage kind UK_ModAsValue, and then restore
14750 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14751 // the previous one was empty).
14752 UsageInfo &UI = Self.UsageMap[M.first];
14753 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14754 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14755 SideEffectUsage = M.second;
14756 }
14757 Self.ModAsSideEffect = OldModAsSideEffect;
14758 }
14759
14760 SequenceChecker &Self;
14761 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14762 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14763 };
14764
14765 /// RAII object wrapping the visitation of a subexpression which we might
14766 /// choose to evaluate as a constant. If any subexpression is evaluated and
14767 /// found to be non-constant, this allows us to suppress the evaluation of
14768 /// the outer expression.
14769 class EvaluationTracker {
14770 public:
14771 EvaluationTracker(SequenceChecker &Self)
14772 : Self(Self), Prev(Self.EvalTracker) {
14773 Self.EvalTracker = this;
14774 }
14775
14776 ~EvaluationTracker() {
14777 Self.EvalTracker = Prev;
14778 if (Prev)
14779 Prev->EvalOK &= EvalOK;
14780 }
14781
14782 bool evaluate(const Expr *E, bool &Result) {
14783 if (!EvalOK || E->isValueDependent())
14784 return false;
14785 EvalOK = E->EvaluateAsBooleanCondition(
14786 Result, Self.SemaRef.Context,
14787 Self.SemaRef.isConstantEvaluatedContext());
14788 return EvalOK;
14789 }
14790
14791 private:
14792 SequenceChecker &Self;
14793 EvaluationTracker *Prev;
14794 bool EvalOK = true;
14795 } *EvalTracker = nullptr;
14796
14797 /// Find the object which is produced by the specified expression,
14798 /// if any.
14799 Object getObject(const Expr *E, bool Mod) const {
14800 E = E->IgnoreParenCasts();
14801 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14802 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14803 return getObject(UO->getSubExpr(), Mod);
14804 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14805 if (BO->getOpcode() == BO_Comma)
14806 return getObject(BO->getRHS(), Mod);
14807 if (Mod && BO->isAssignmentOp())
14808 return getObject(BO->getLHS(), Mod);
14809 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14810 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14811 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14812 return ME->getMemberDecl();
14813 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14814 // FIXME: If this is a reference, map through to its value.
14815 return DRE->getDecl();
14816 return nullptr;
14817 }
14818
14819 /// Note that an object \p O was modified or used by an expression
14820 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14821 /// the object \p O as obtained via the \p UsageMap.
14822 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14823 // Get the old usage for the given object and usage kind.
14824 Usage &U = UI.Uses[UK];
14825 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14826 // If we have a modification as side effect and are in a sequenced
14827 // subexpression, save the old Usage so that we can restore it later
14828 // in SequencedSubexpression::~SequencedSubexpression.
14829 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14830 ModAsSideEffect->push_back(std::make_pair(O, U));
14831 // Then record the new usage with the current sequencing region.
14832 U.UsageExpr = UsageExpr;
14833 U.Seq = Region;
14834 }
14835 }
14836
14837 /// Check whether a modification or use of an object \p O in an expression
14838 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14839 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14840 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14841 /// usage and false we are checking for a mod-use unsequenced usage.
14842 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14843 UsageKind OtherKind, bool IsModMod) {
14844 if (UI.Diagnosed)
14845 return;
14846
14847 const Usage &U = UI.Uses[OtherKind];
14848 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14849 return;
14850
14851 const Expr *Mod = U.UsageExpr;
14852 const Expr *ModOrUse = UsageExpr;
14853 if (OtherKind == UK_Use)
14854 std::swap(Mod, ModOrUse);
14855
14856 SemaRef.DiagRuntimeBehavior(
14857 Mod->getExprLoc(), {Mod, ModOrUse},
14858 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14859 : diag::warn_unsequenced_mod_use)
14860 << O << SourceRange(ModOrUse->getExprLoc()));
14861 UI.Diagnosed = true;
14862 }
14863
14864 // A note on note{Pre, Post}{Use, Mod}:
14865 //
14866 // (It helps to follow the algorithm with an expression such as
14867 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14868 // operations before C++17 and both are well-defined in C++17).
14869 //
14870 // When visiting a node which uses/modify an object we first call notePreUse
14871 // or notePreMod before visiting its sub-expression(s). At this point the
14872 // children of the current node have not yet been visited and so the eventual
14873 // uses/modifications resulting from the children of the current node have not
14874 // been recorded yet.
14875 //
14876 // We then visit the children of the current node. After that notePostUse or
14877 // notePostMod is called. These will 1) detect an unsequenced modification
14878 // as side effect (as in "k++ + k") and 2) add a new usage with the
14879 // appropriate usage kind.
14880 //
14881 // We also have to be careful that some operation sequences modification as
14882 // side effect as well (for example: || or ,). To account for this we wrap
14883 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14884 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14885 // which record usages which are modifications as side effect, and then
14886 // downgrade them (or more accurately restore the previous usage which was a
14887 // modification as side effect) when exiting the scope of the sequenced
14888 // subexpression.
14889
14890 void notePreUse(Object O, const Expr *UseExpr) {
14891 UsageInfo &UI = UsageMap[O];
14892 // Uses conflict with other modifications.
14893 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14894 }
14895
14896 void notePostUse(Object O, const Expr *UseExpr) {
14897 UsageInfo &UI = UsageMap[O];
14898 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14899 /*IsModMod=*/false);
14900 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14901 }
14902
14903 void notePreMod(Object O, const Expr *ModExpr) {
14904 UsageInfo &UI = UsageMap[O];
14905 // Modifications conflict with other modifications and with uses.
14906 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14907 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14908 }
14909
14910 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14911 UsageInfo &UI = UsageMap[O];
14912 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14913 /*IsModMod=*/true);
14914 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14915 }
14916
14917public:
14918 SequenceChecker(Sema &S, const Expr *E,
14919 SmallVectorImpl<const Expr *> &WorkList)
14920 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14921 Visit(E);
14922 // Silence a -Wunused-private-field since WorkList is now unused.
14923 // TODO: Evaluate if it can be used, and if not remove it.
14924 (void)this->WorkList;
14925 }
14926
14927 void VisitStmt(const Stmt *S) {
14928 // Skip all statements which aren't expressions for now.
14929 }
14930
14931 void VisitExpr(const Expr *E) {
14932 // By default, just recurse to evaluated subexpressions.
14933 Base::VisitStmt(E);
14934 }
14935
14936 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14937 for (auto *Sub : CSE->children()) {
14938 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14939 if (!ChildExpr)
14940 continue;
14941
14942 if (ChildExpr == CSE->getOperand())
14943 // Do not recurse over a CoroutineSuspendExpr's operand.
14944 // The operand is also a subexpression of getCommonExpr(), and
14945 // recursing into it directly could confuse object management
14946 // for the sake of sequence tracking.
14947 continue;
14948
14949 Visit(Sub);
14950 }
14951 }
14952
14953 void VisitCastExpr(const CastExpr *E) {
14954 Object O = Object();
14955 if (E->getCastKind() == CK_LValueToRValue)
14956 O = getObject(E->getSubExpr(), false);
14957
14958 if (O)
14959 notePreUse(O, E);
14960 VisitExpr(E);
14961 if (O)
14962 notePostUse(O, E);
14963 }
14964
14965 void VisitSequencedExpressions(const Expr *SequencedBefore,
14966 const Expr *SequencedAfter) {
14967 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14968 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14969 SequenceTree::Seq OldRegion = Region;
14970
14971 {
14972 SequencedSubexpression SeqBefore(*this);
14973 Region = BeforeRegion;
14974 Visit(SequencedBefore);
14975 }
14976
14977 Region = AfterRegion;
14978 Visit(SequencedAfter);
14979
14980 Region = OldRegion;
14981
14982 Tree.merge(BeforeRegion);
14983 Tree.merge(AfterRegion);
14984 }
14985
14986 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14987 // C++17 [expr.sub]p1:
14988 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14989 // expression E1 is sequenced before the expression E2.
14990 if (SemaRef.getLangOpts().CPlusPlus17)
14991 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14992 else {
14993 Visit(ASE->getLHS());
14994 Visit(ASE->getRHS());
14995 }
14996 }
14997
14998 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14999 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15000 void VisitBinPtrMem(const BinaryOperator *BO) {
15001 // C++17 [expr.mptr.oper]p4:
15002 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15003 // the expression E1 is sequenced before the expression E2.
15004 if (SemaRef.getLangOpts().CPlusPlus17)
15005 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15006 else {
15007 Visit(BO->getLHS());
15008 Visit(BO->getRHS());
15009 }
15010 }
15011
15012 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15013 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15014 void VisitBinShlShr(const BinaryOperator *BO) {
15015 // C++17 [expr.shift]p4:
15016 // The expression E1 is sequenced before the expression E2.
15017 if (SemaRef.getLangOpts().CPlusPlus17)
15018 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15019 else {
15020 Visit(BO->getLHS());
15021 Visit(BO->getRHS());
15022 }
15023 }
15024
15025 void VisitBinComma(const BinaryOperator *BO) {
15026 // C++11 [expr.comma]p1:
15027 // Every value computation and side effect associated with the left
15028 // expression is sequenced before every value computation and side
15029 // effect associated with the right expression.
15030 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15031 }
15032
15033 void VisitBinAssign(const BinaryOperator *BO) {
15034 SequenceTree::Seq RHSRegion;
15035 SequenceTree::Seq LHSRegion;
15036 if (SemaRef.getLangOpts().CPlusPlus17) {
15037 RHSRegion = Tree.allocate(Region);
15038 LHSRegion = Tree.allocate(Region);
15039 } else {
15040 RHSRegion = Region;
15041 LHSRegion = Region;
15042 }
15043 SequenceTree::Seq OldRegion = Region;
15044
15045 // C++11 [expr.ass]p1:
15046 // [...] the assignment is sequenced after the value computation
15047 // of the right and left operands, [...]
15048 //
15049 // so check it before inspecting the operands and update the
15050 // map afterwards.
15051 Object O = getObject(BO->getLHS(), /*Mod=*/true);
15052 if (O)
15053 notePreMod(O, BO);
15054
15055 if (SemaRef.getLangOpts().CPlusPlus17) {
15056 // C++17 [expr.ass]p1:
15057 // [...] The right operand is sequenced before the left operand. [...]
15058 {
15059 SequencedSubexpression SeqBefore(*this);
15060 Region = RHSRegion;
15061 Visit(BO->getRHS());
15062 }
15063
15064 Region = LHSRegion;
15065 Visit(BO->getLHS());
15066
15067 if (O && isa<CompoundAssignOperator>(BO))
15068 notePostUse(O, BO);
15069
15070 } else {
15071 // C++11 does not specify any sequencing between the LHS and RHS.
15072 Region = LHSRegion;
15073 Visit(BO->getLHS());
15074
15075 if (O && isa<CompoundAssignOperator>(BO))
15076 notePostUse(O, BO);
15077
15078 Region = RHSRegion;
15079 Visit(BO->getRHS());
15080 }
15081
15082 // C++11 [expr.ass]p1:
15083 // the assignment is sequenced [...] before the value computation of the
15084 // assignment expression.
15085 // C11 6.5.16/3 has no such rule.
15086 Region = OldRegion;
15087 if (O)
15088 notePostMod(O, BO,
15089 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15090 : UK_ModAsSideEffect);
15091 if (SemaRef.getLangOpts().CPlusPlus17) {
15092 Tree.merge(RHSRegion);
15093 Tree.merge(LHSRegion);
15094 }
15095 }
15096
15097 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15098 VisitBinAssign(CAO);
15099 }
15100
15101 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15102 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15103 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15104 Object O = getObject(UO->getSubExpr(), true);
15105 if (!O)
15106 return VisitExpr(UO);
15107
15108 notePreMod(O, UO);
15109 Visit(UO->getSubExpr());
15110 // C++11 [expr.pre.incr]p1:
15111 // the expression ++x is equivalent to x+=1
15112 notePostMod(O, UO,
15113 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15114 : UK_ModAsSideEffect);
15115 }
15116
15117 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15118 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15119 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15120 Object O = getObject(UO->getSubExpr(), true);
15121 if (!O)
15122 return VisitExpr(UO);
15123
15124 notePreMod(O, UO);
15125 Visit(UO->getSubExpr());
15126 notePostMod(O, UO, UK_ModAsSideEffect);
15127 }
15128
15129 void VisitBinLOr(const BinaryOperator *BO) {
15130 // C++11 [expr.log.or]p2:
15131 // If the second expression is evaluated, every value computation and
15132 // side effect associated with the first expression is sequenced before
15133 // every value computation and side effect associated with the
15134 // second expression.
15135 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15136 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15137 SequenceTree::Seq OldRegion = Region;
15138
15139 EvaluationTracker Eval(*this);
15140 {
15141 SequencedSubexpression Sequenced(*this);
15142 Region = LHSRegion;
15143 Visit(BO->getLHS());
15144 }
15145
15146 // C++11 [expr.log.or]p1:
15147 // [...] the second operand is not evaluated if the first operand
15148 // evaluates to true.
15149 bool EvalResult = false;
15150 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15151 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15152 if (ShouldVisitRHS) {
15153 Region = RHSRegion;
15154 Visit(BO->getRHS());
15155 }
15156
15157 Region = OldRegion;
15158 Tree.merge(LHSRegion);
15159 Tree.merge(RHSRegion);
15160 }
15161
15162 void VisitBinLAnd(const BinaryOperator *BO) {
15163 // C++11 [expr.log.and]p2:
15164 // If the second expression is evaluated, every value computation and
15165 // side effect associated with the first expression is sequenced before
15166 // every value computation and side effect associated with the
15167 // second expression.
15168 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15169 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15170 SequenceTree::Seq OldRegion = Region;
15171
15172 EvaluationTracker Eval(*this);
15173 {
15174 SequencedSubexpression Sequenced(*this);
15175 Region = LHSRegion;
15176 Visit(BO->getLHS());
15177 }
15178
15179 // C++11 [expr.log.and]p1:
15180 // [...] the second operand is not evaluated if the first operand is false.
15181 bool EvalResult = false;
15182 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15183 bool ShouldVisitRHS = !EvalOK || EvalResult;
15184 if (ShouldVisitRHS) {
15185 Region = RHSRegion;
15186 Visit(BO->getRHS());
15187 }
15188
15189 Region = OldRegion;
15190 Tree.merge(LHSRegion);
15191 Tree.merge(RHSRegion);
15192 }
15193
15194 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15195 // C++11 [expr.cond]p1:
15196 // [...] Every value computation and side effect associated with the first
15197 // expression is sequenced before every value computation and side effect
15198 // associated with the second or third expression.
15199 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15200
15201 // No sequencing is specified between the true and false expression.
15202 // However since exactly one of both is going to be evaluated we can
15203 // consider them to be sequenced. This is needed to avoid warning on
15204 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15205 // both the true and false expressions because we can't evaluate x.
15206 // This will still allow us to detect an expression like (pre C++17)
15207 // "(x ? y += 1 : y += 2) = y".
15208 //
15209 // We don't wrap the visitation of the true and false expression with
15210 // SequencedSubexpression because we don't want to downgrade modifications
15211 // as side effect in the true and false expressions after the visition
15212 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15213 // not warn between the two "y++", but we should warn between the "y++"
15214 // and the "y".
15215 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15216 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15217 SequenceTree::Seq OldRegion = Region;
15218
15219 EvaluationTracker Eval(*this);
15220 {
15221 SequencedSubexpression Sequenced(*this);
15222 Region = ConditionRegion;
15223 Visit(CO->getCond());
15224 }
15225
15226 // C++11 [expr.cond]p1:
15227 // [...] The first expression is contextually converted to bool (Clause 4).
15228 // It is evaluated and if it is true, the result of the conditional
15229 // expression is the value of the second expression, otherwise that of the
15230 // third expression. Only one of the second and third expressions is
15231 // evaluated. [...]
15232 bool EvalResult = false;
15233 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15234 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15235 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15236 if (ShouldVisitTrueExpr) {
15237 Region = TrueRegion;
15238 Visit(CO->getTrueExpr());
15239 }
15240 if (ShouldVisitFalseExpr) {
15241 Region = FalseRegion;
15242 Visit(CO->getFalseExpr());
15243 }
15244
15245 Region = OldRegion;
15246 Tree.merge(ConditionRegion);
15247 Tree.merge(TrueRegion);
15248 Tree.merge(FalseRegion);
15249 }
15250
15251 void VisitCallExpr(const CallExpr *CE) {
15252 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15253
15254 if (CE->isUnevaluatedBuiltinCall(Context))
15255 return;
15256
15257 // C++11 [intro.execution]p15:
15258 // When calling a function [...], every value computation and side effect
15259 // associated with any argument expression, or with the postfix expression
15260 // designating the called function, is sequenced before execution of every
15261 // expression or statement in the body of the function [and thus before
15262 // the value computation of its result].
15263 SequencedSubexpression Sequenced(*this);
15264 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15265 // C++17 [expr.call]p5
15266 // The postfix-expression is sequenced before each expression in the
15267 // expression-list and any default argument. [...]
15268 SequenceTree::Seq CalleeRegion;
15269 SequenceTree::Seq OtherRegion;
15270 if (SemaRef.getLangOpts().CPlusPlus17) {
15271 CalleeRegion = Tree.allocate(Region);
15272 OtherRegion = Tree.allocate(Region);
15273 } else {
15274 CalleeRegion = Region;
15275 OtherRegion = Region;
15276 }
15277 SequenceTree::Seq OldRegion = Region;
15278
15279 // Visit the callee expression first.
15280 Region = CalleeRegion;
15281 if (SemaRef.getLangOpts().CPlusPlus17) {
15282 SequencedSubexpression Sequenced(*this);
15283 Visit(CE->getCallee());
15284 } else {
15285 Visit(CE->getCallee());
15286 }
15287
15288 // Then visit the argument expressions.
15289 Region = OtherRegion;
15290 for (const Expr *Argument : CE->arguments())
15291 Visit(Argument);
15292
15293 Region = OldRegion;
15294 if (SemaRef.getLangOpts().CPlusPlus17) {
15295 Tree.merge(CalleeRegion);
15296 Tree.merge(OtherRegion);
15297 }
15298 });
15299 }
15300
15301 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15302 // C++17 [over.match.oper]p2:
15303 // [...] the operator notation is first transformed to the equivalent
15304 // function-call notation as summarized in Table 12 (where @ denotes one
15305 // of the operators covered in the specified subclause). However, the
15306 // operands are sequenced in the order prescribed for the built-in
15307 // operator (Clause 8).
15308 //
15309 // From the above only overloaded binary operators and overloaded call
15310 // operators have sequencing rules in C++17 that we need to handle
15311 // separately.
15312 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15313 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15314 return VisitCallExpr(CXXOCE);
15315
15316 enum {
15317 NoSequencing,
15318 LHSBeforeRHS,
15319 RHSBeforeLHS,
15320 LHSBeforeRest
15321 } SequencingKind;
15322 switch (CXXOCE->getOperator()) {
15323 case OO_Equal:
15324 case OO_PlusEqual:
15325 case OO_MinusEqual:
15326 case OO_StarEqual:
15327 case OO_SlashEqual:
15328 case OO_PercentEqual:
15329 case OO_CaretEqual:
15330 case OO_AmpEqual:
15331 case OO_PipeEqual:
15332 case OO_LessLessEqual:
15333 case OO_GreaterGreaterEqual:
15334 SequencingKind = RHSBeforeLHS;
15335 break;
15336
15337 case OO_LessLess:
15338 case OO_GreaterGreater:
15339 case OO_AmpAmp:
15340 case OO_PipePipe:
15341 case OO_Comma:
15342 case OO_ArrowStar:
15343 case OO_Subscript:
15344 SequencingKind = LHSBeforeRHS;
15345 break;
15346
15347 case OO_Call:
15348 SequencingKind = LHSBeforeRest;
15349 break;
15350
15351 default:
15352 SequencingKind = NoSequencing;
15353 break;
15354 }
15355
15356 if (SequencingKind == NoSequencing)
15357 return VisitCallExpr(CXXOCE);
15358
15359 // This is a call, so all subexpressions are sequenced before the result.
15360 SequencedSubexpression Sequenced(*this);
15361
15362 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15363 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15364 "Should only get there with C++17 and above!");
15365 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15366 "Should only get there with an overloaded binary operator"
15367 " or an overloaded call operator!");
15368
15369 if (SequencingKind == LHSBeforeRest) {
15370 assert(CXXOCE->getOperator() == OO_Call &&
15371 "We should only have an overloaded call operator here!");
15372
15373 // This is very similar to VisitCallExpr, except that we only have the
15374 // C++17 case. The postfix-expression is the first argument of the
15375 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15376 // are in the following arguments.
15377 //
15378 // Note that we intentionally do not visit the callee expression since
15379 // it is just a decayed reference to a function.
15380 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15381 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15382 SequenceTree::Seq OldRegion = Region;
15383
15384 assert(CXXOCE->getNumArgs() >= 1 &&
15385 "An overloaded call operator must have at least one argument"
15386 " for the postfix-expression!");
15387 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15388 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15389 CXXOCE->getNumArgs() - 1);
15390
15391 // Visit the postfix-expression first.
15392 {
15393 Region = PostfixExprRegion;
15394 SequencedSubexpression Sequenced(*this);
15395 Visit(PostfixExpr);
15396 }
15397
15398 // Then visit the argument expressions.
15399 Region = ArgsRegion;
15400 for (const Expr *Arg : Args)
15401 Visit(Arg);
15402
15403 Region = OldRegion;
15404 Tree.merge(PostfixExprRegion);
15405 Tree.merge(ArgsRegion);
15406 } else {
15407 assert(CXXOCE->getNumArgs() == 2 &&
15408 "Should only have two arguments here!");
15409 assert((SequencingKind == LHSBeforeRHS ||
15410 SequencingKind == RHSBeforeLHS) &&
15411 "Unexpected sequencing kind!");
15412
15413 // We do not visit the callee expression since it is just a decayed
15414 // reference to a function.
15415 const Expr *E1 = CXXOCE->getArg(0);
15416 const Expr *E2 = CXXOCE->getArg(1);
15417 if (SequencingKind == RHSBeforeLHS)
15418 std::swap(E1, E2);
15419
15420 return VisitSequencedExpressions(E1, E2);
15421 }
15422 });
15423 }
15424
15425 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15426 // This is a call, so all subexpressions are sequenced before the result.
15427 SequencedSubexpression Sequenced(*this);
15428
15429 if (!CCE->isListInitialization())
15430 return VisitExpr(CCE);
15431
15432 // In C++11, list initializations are sequenced.
15433 SequenceExpressionsInOrder(
15434 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15435 }
15436
15437 void VisitInitListExpr(const InitListExpr *ILE) {
15438 if (!SemaRef.getLangOpts().CPlusPlus11)
15439 return VisitExpr(ILE);
15440
15441 // In C++11, list initializations are sequenced.
15442 SequenceExpressionsInOrder(ILE->inits());
15443 }
15444
15445 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15446 // C++20 parenthesized list initializations are sequenced. See C++20
15447 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15448 SequenceExpressionsInOrder(PLIE->getInitExprs());
15449 }
15450
15451private:
15452 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15454 SequenceTree::Seq Parent = Region;
15455 for (const Expr *E : ExpressionList) {
15456 if (!E)
15457 continue;
15458 Region = Tree.allocate(Parent);
15459 Elts.push_back(Region);
15460 Visit(E);
15461 }
15462
15463 // Forget that the initializers are sequenced.
15464 Region = Parent;
15465 for (unsigned I = 0; I < Elts.size(); ++I)
15466 Tree.merge(Elts[I]);
15467 }
15468};
15469
15470SequenceChecker::UsageInfo::UsageInfo() = default;
15471
15472} // namespace
15473
15474void Sema::CheckUnsequencedOperations(const Expr *E) {
15475 SmallVector<const Expr *, 8> WorkList;
15476 WorkList.push_back(E);
15477 while (!WorkList.empty()) {
15478 const Expr *Item = WorkList.pop_back_val();
15479 SequenceChecker(*this, Item, WorkList);
15480 }
15481}
15482
15483void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15484 bool IsConstexpr) {
15485 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15486 IsConstexpr || isa<ConstantExpr>(E));
15487 CheckImplicitConversions(E, CheckLoc);
15488 if (!E->isInstantiationDependent())
15489 CheckUnsequencedOperations(E);
15490 if (!IsConstexpr && !E->isValueDependent())
15491 CheckForIntOverflow(E);
15492}
15493
15494void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15495 FieldDecl *BitField,
15496 Expr *Init) {
15497 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15498}
15499
15501 SourceLocation Loc) {
15502 if (!PType->isVariablyModifiedType())
15503 return;
15504 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15505 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15506 return;
15507 }
15508 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15509 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15510 return;
15511 }
15512 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15513 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15514 return;
15515 }
15516
15517 const ArrayType *AT = S.Context.getAsArrayType(PType);
15518 if (!AT)
15519 return;
15520
15523 return;
15524 }
15525
15526 S.Diag(Loc, diag::err_array_star_in_function_definition);
15527}
15528
15530 bool CheckParameterNames) {
15531 bool HasInvalidParm = false;
15532 for (ParmVarDecl *Param : Parameters) {
15533 assert(Param && "null in a parameter list");
15534 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15535 // function declarator that is part of a function definition of
15536 // that function shall not have incomplete type.
15537 //
15538 // C++23 [dcl.fct.def.general]/p2
15539 // The type of a parameter [...] for a function definition
15540 // shall not be a (possibly cv-qualified) class type that is incomplete
15541 // or abstract within the function body unless the function is deleted.
15542 if (!Param->isInvalidDecl() &&
15543 (RequireCompleteType(Param->getLocation(), Param->getType(),
15544 diag::err_typecheck_decl_incomplete_type) ||
15545 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15546 diag::err_abstract_type_in_decl,
15548 Param->setInvalidDecl();
15549 HasInvalidParm = true;
15550 }
15551
15552 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15553 // declaration of each parameter shall include an identifier.
15554 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15555 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15556 // Diagnose this as an extension in C17 and earlier.
15557 if (!getLangOpts().C23)
15558 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15559 }
15560
15561 // C99 6.7.5.3p12:
15562 // If the function declarator is not part of a definition of that
15563 // function, parameters may have incomplete type and may use the [*]
15564 // notation in their sequences of declarator specifiers to specify
15565 // variable length array types.
15566 QualType PType = Param->getOriginalType();
15567 // FIXME: This diagnostic should point the '[*]' if source-location
15568 // information is added for it.
15569 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15570
15571 // If the parameter is a c++ class type and it has to be destructed in the
15572 // callee function, declare the destructor so that it can be called by the
15573 // callee function. Do not perform any direct access check on the dtor here.
15574 if (!Param->isInvalidDecl()) {
15575 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15576 if (!ClassDecl->isInvalidDecl() &&
15577 !ClassDecl->hasIrrelevantDestructor() &&
15578 !ClassDecl->isDependentContext() &&
15579 ClassDecl->isParamDestroyedInCallee()) {
15581 MarkFunctionReferenced(Param->getLocation(), Destructor);
15582 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15583 }
15584 }
15585 }
15586
15587 // Parameters with the pass_object_size attribute only need to be marked
15588 // constant at function definitions. Because we lack information about
15589 // whether we're on a declaration or definition when we're instantiating the
15590 // attribute, we need to check for constness here.
15591 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15592 if (!Param->getType().isConstQualified())
15593 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15594 << Attr->getSpelling() << 1;
15595
15596 // Check for parameter names shadowing fields from the class.
15597 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15598 // The owning context for the parameter should be the function, but we
15599 // want to see if this function's declaration context is a record.
15600 DeclContext *DC = Param->getDeclContext();
15601 if (DC && DC->isFunctionOrMethod()) {
15602 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15603 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15604 RD, /*DeclIsField*/ false);
15605 }
15606 }
15607
15608 if (!Param->isInvalidDecl() &&
15609 Param->getOriginalType()->isWebAssemblyTableType()) {
15610 Param->setInvalidDecl();
15611 HasInvalidParm = true;
15612 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15613 }
15614 }
15615
15616 return HasInvalidParm;
15617}
15618
15619std::optional<std::pair<
15621 *E,
15623 &Ctx);
15624
15625/// Compute the alignment and offset of the base class object given the
15626/// derived-to-base cast expression and the alignment and offset of the derived
15627/// class object.
15628static std::pair<CharUnits, CharUnits>
15630 CharUnits BaseAlignment, CharUnits Offset,
15631 ASTContext &Ctx) {
15632 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15633 ++PathI) {
15634 const CXXBaseSpecifier *Base = *PathI;
15635 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15636 if (Base->isVirtual()) {
15637 // The complete object may have a lower alignment than the non-virtual
15638 // alignment of the base, in which case the base may be misaligned. Choose
15639 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15640 // conservative lower bound of the complete object alignment.
15641 CharUnits NonVirtualAlignment =
15643 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15644 Offset = CharUnits::Zero();
15645 } else {
15646 const ASTRecordLayout &RL =
15647 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15648 Offset += RL.getBaseClassOffset(BaseDecl);
15649 }
15650 DerivedType = Base->getType();
15651 }
15652
15653 return std::make_pair(BaseAlignment, Offset);
15654}
15655
15656/// Compute the alignment and offset of a binary additive operator.
15657static std::optional<std::pair<CharUnits, CharUnits>>
15659 bool IsSub, ASTContext &Ctx) {
15660 QualType PointeeType = PtrE->getType()->getPointeeType();
15661
15662 if (!PointeeType->isConstantSizeType())
15663 return std::nullopt;
15664
15665 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15666
15667 if (!P)
15668 return std::nullopt;
15669
15670 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15671 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15672 CharUnits Offset = EltSize * IdxRes->getExtValue();
15673 if (IsSub)
15674 Offset = -Offset;
15675 return std::make_pair(P->first, P->second + Offset);
15676 }
15677
15678 // If the integer expression isn't a constant expression, compute the lower
15679 // bound of the alignment using the alignment and offset of the pointer
15680 // expression and the element size.
15681 return std::make_pair(
15682 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15683 CharUnits::Zero());
15684}
15685
15686/// This helper function takes an lvalue expression and returns the alignment of
15687/// a VarDecl and a constant offset from the VarDecl.
15688std::optional<std::pair<
15689 CharUnits,
15691 ASTContext &Ctx) {
15692 E = E->IgnoreParens();
15693 switch (E->getStmtClass()) {
15694 default:
15695 break;
15696 case Stmt::CStyleCastExprClass:
15697 case Stmt::CXXStaticCastExprClass:
15698 case Stmt::ImplicitCastExprClass: {
15699 auto *CE = cast<CastExpr>(E);
15700 const Expr *From = CE->getSubExpr();
15701 switch (CE->getCastKind()) {
15702 default:
15703 break;
15704 case CK_NoOp:
15705 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15706 case CK_UncheckedDerivedToBase:
15707 case CK_DerivedToBase: {
15708 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15709 if (!P)
15710 break;
15711 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15712 P->second, Ctx);
15713 }
15714 }
15715 break;
15716 }
15717 case Stmt::ArraySubscriptExprClass: {
15718 auto *ASE = cast<ArraySubscriptExpr>(E);
15720 false, Ctx);
15721 }
15722 case Stmt::DeclRefExprClass: {
15723 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15724 // FIXME: If VD is captured by copy or is an escaping __block variable,
15725 // use the alignment of VD's type.
15726 if (!VD->getType()->isReferenceType()) {
15727 // Dependent alignment cannot be resolved -> bail out.
15728 if (VD->hasDependentAlignment())
15729 break;
15730 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15731 }
15732 if (VD->hasInit())
15733 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15734 }
15735 break;
15736 }
15737 case Stmt::MemberExprClass: {
15738 auto *ME = cast<MemberExpr>(E);
15739 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15740 if (!FD || FD->getType()->isReferenceType() ||
15741 FD->getParent()->isInvalidDecl())
15742 break;
15743 std::optional<std::pair<CharUnits, CharUnits>> P;
15744 if (ME->isArrow())
15745 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15746 else
15747 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15748 if (!P)
15749 break;
15750 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15751 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15752 return std::make_pair(P->first,
15753 P->second + CharUnits::fromQuantity(Offset));
15754 }
15755 case Stmt::UnaryOperatorClass: {
15756 auto *UO = cast<UnaryOperator>(E);
15757 switch (UO->getOpcode()) {
15758 default:
15759 break;
15760 case UO_Deref:
15762 }
15763 break;
15764 }
15765 case Stmt::BinaryOperatorClass: {
15766 auto *BO = cast<BinaryOperator>(E);
15767 auto Opcode = BO->getOpcode();
15768 switch (Opcode) {
15769 default:
15770 break;
15771 case BO_Comma:
15773 }
15774 break;
15775 }
15776 }
15777 return std::nullopt;
15778}
15779
15780/// This helper function takes a pointer expression and returns the alignment of
15781/// a VarDecl and a constant offset from the VarDecl.
15782std::optional<std::pair<
15784 *E,
15786 &Ctx) {
15787 E = E->IgnoreParens();
15788 switch (E->getStmtClass()) {
15789 default:
15790 break;
15791 case Stmt::CStyleCastExprClass:
15792 case Stmt::CXXStaticCastExprClass:
15793 case Stmt::ImplicitCastExprClass: {
15794 auto *CE = cast<CastExpr>(E);
15795 const Expr *From = CE->getSubExpr();
15796 switch (CE->getCastKind()) {
15797 default:
15798 break;
15799 case CK_NoOp:
15800 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15801 case CK_ArrayToPointerDecay:
15802 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15803 case CK_UncheckedDerivedToBase:
15804 case CK_DerivedToBase: {
15805 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15806 if (!P)
15807 break;
15809 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15810 }
15811 }
15812 break;
15813 }
15814 case Stmt::CXXThisExprClass: {
15815 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15817 return std::make_pair(Alignment, CharUnits::Zero());
15818 }
15819 case Stmt::UnaryOperatorClass: {
15820 auto *UO = cast<UnaryOperator>(E);
15821 if (UO->getOpcode() == UO_AddrOf)
15823 break;
15824 }
15825 case Stmt::BinaryOperatorClass: {
15826 auto *BO = cast<BinaryOperator>(E);
15827 auto Opcode = BO->getOpcode();
15828 switch (Opcode) {
15829 default:
15830 break;
15831 case BO_Add:
15832 case BO_Sub: {
15833 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15834 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15835 std::swap(LHS, RHS);
15836 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15837 Ctx);
15838 }
15839 case BO_Comma:
15840 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15841 }
15842 break;
15843 }
15844 }
15845 return std::nullopt;
15846}
15847
15849 // See if we can compute the alignment of a VarDecl and an offset from it.
15850 std::optional<std::pair<CharUnits, CharUnits>> P =
15852
15853 if (P)
15854 return P->first.alignmentAtOffset(P->second);
15855
15856 // If that failed, return the type's alignment.
15858}
15859
15861 // This is actually a lot of work to potentially be doing on every
15862 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15863 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15864 return;
15865
15866 // Ignore dependent types.
15867 if (T->isDependentType() || Op->getType()->isDependentType())
15868 return;
15869
15870 // Require that the destination be a pointer type.
15871 const PointerType *DestPtr = T->getAs<PointerType>();
15872 if (!DestPtr) return;
15873
15874 // If the destination has alignment 1, we're done.
15875 QualType DestPointee = DestPtr->getPointeeType();
15876 if (DestPointee->isIncompleteType()) return;
15877 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15878 if (DestAlign.isOne()) return;
15879
15880 // Require that the source be a pointer type.
15881 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15882 if (!SrcPtr) return;
15883 QualType SrcPointee = SrcPtr->getPointeeType();
15884
15885 // Explicitly allow casts from cv void*. We already implicitly
15886 // allowed casts to cv void*, since they have alignment 1.
15887 // Also allow casts involving incomplete types, which implicitly
15888 // includes 'void'.
15889 if (SrcPointee->isIncompleteType()) return;
15890
15891 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15892
15893 if (SrcAlign >= DestAlign) return;
15894
15895 Diag(TRange.getBegin(), diag::warn_cast_align)
15896 << Op->getType() << T
15897 << static_cast<unsigned>(SrcAlign.getQuantity())
15898 << static_cast<unsigned>(DestAlign.getQuantity())
15899 << TRange << Op->getSourceRange();
15900}
15901
15902void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15903 const ArraySubscriptExpr *ASE,
15904 bool AllowOnePastEnd, bool IndexNegated) {
15905 // Already diagnosed by the constant evaluator.
15907 return;
15908
15909 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15910 if (IndexExpr->isValueDependent())
15911 return;
15912
15913 const Type *EffectiveType =
15915 BaseExpr = BaseExpr->IgnoreParenCasts();
15916 const ConstantArrayType *ArrayTy =
15917 Context.getAsConstantArrayType(BaseExpr->getType());
15918
15920 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15921
15922 const Type *BaseType =
15923 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15924 bool IsUnboundedArray =
15925 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15926 Context, StrictFlexArraysLevel,
15927 /*IgnoreTemplateOrMacroSubstitution=*/true);
15928 if (EffectiveType->isDependentType() ||
15929 (!IsUnboundedArray && BaseType->isDependentType()))
15930 return;
15931
15933 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15934 return;
15935
15936 llvm::APSInt index = Result.Val.getInt();
15937 if (IndexNegated) {
15938 index.setIsUnsigned(false);
15939 index = -index;
15940 }
15941
15942 if (IsUnboundedArray) {
15943 if (EffectiveType->isFunctionType())
15944 return;
15945 if (index.isUnsigned() || !index.isNegative()) {
15946 const auto &ASTC = getASTContext();
15947 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15948 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15949 if (index.getBitWidth() < AddrBits)
15950 index = index.zext(AddrBits);
15951 std::optional<CharUnits> ElemCharUnits =
15952 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15953 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15954 // pointer) bounds-checking isn't meaningful.
15955 if (!ElemCharUnits || ElemCharUnits->isZero())
15956 return;
15957 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15958 // If index has more active bits than address space, we already know
15959 // we have a bounds violation to warn about. Otherwise, compute
15960 // address of (index + 1)th element, and warn about bounds violation
15961 // only if that address exceeds address space.
15962 if (index.getActiveBits() <= AddrBits) {
15963 bool Overflow;
15964 llvm::APInt Product(index);
15965 Product += 1;
15966 Product = Product.umul_ov(ElemBytes, Overflow);
15967 if (!Overflow && Product.getActiveBits() <= AddrBits)
15968 return;
15969 }
15970
15971 // Need to compute max possible elements in address space, since that
15972 // is included in diag message.
15973 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15974 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15975 MaxElems += 1;
15976 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15977 MaxElems = MaxElems.udiv(ElemBytes);
15978
15979 unsigned DiagID =
15980 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15981 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15982
15983 // Diag message shows element size in bits and in "bytes" (platform-
15984 // dependent CharUnits)
15985 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15986 PDiag(DiagID) << index << AddrBits
15987 << (unsigned)ASTC.toBits(*ElemCharUnits)
15988 << ElemBytes << MaxElems
15989 << MaxElems.getZExtValue()
15990 << IndexExpr->getSourceRange());
15991
15992 const NamedDecl *ND = nullptr;
15993 // Try harder to find a NamedDecl to point at in the note.
15994 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15995 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15996 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15997 ND = DRE->getDecl();
15998 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15999 ND = ME->getMemberDecl();
16000
16001 if (ND)
16002 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16003 PDiag(diag::note_array_declared_here) << ND);
16004 }
16005 return;
16006 }
16007
16008 if (index.isUnsigned() || !index.isNegative()) {
16009 // It is possible that the type of the base expression after
16010 // IgnoreParenCasts is incomplete, even though the type of the base
16011 // expression before IgnoreParenCasts is complete (see PR39746 for an
16012 // example). In this case we have no information about whether the array
16013 // access exceeds the array bounds. However we can still diagnose an array
16014 // access which precedes the array bounds.
16015 if (BaseType->isIncompleteType())
16016 return;
16017
16018 llvm::APInt size = ArrayTy->getSize();
16019
16020 if (BaseType != EffectiveType) {
16021 // Make sure we're comparing apples to apples when comparing index to
16022 // size.
16023 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
16024 uint64_t array_typesize = Context.getTypeSize(BaseType);
16025
16026 // Handle ptrarith_typesize being zero, such as when casting to void*.
16027 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16028 if (!ptrarith_typesize)
16029 ptrarith_typesize = Context.getCharWidth();
16030
16031 if (ptrarith_typesize != array_typesize) {
16032 // There's a cast to a different size type involved.
16033 uint64_t ratio = array_typesize / ptrarith_typesize;
16034
16035 // TODO: Be smarter about handling cases where array_typesize is not a
16036 // multiple of ptrarith_typesize.
16037 if (ptrarith_typesize * ratio == array_typesize)
16038 size *= llvm::APInt(size.getBitWidth(), ratio);
16039 }
16040 }
16041
16042 if (size.getBitWidth() > index.getBitWidth())
16043 index = index.zext(size.getBitWidth());
16044 else if (size.getBitWidth() < index.getBitWidth())
16045 size = size.zext(index.getBitWidth());
16046
16047 // For array subscripting the index must be less than size, but for pointer
16048 // arithmetic also allow the index (offset) to be equal to size since
16049 // computing the next address after the end of the array is legal and
16050 // commonly done e.g. in C++ iterators and range-based for loops.
16051 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16052 return;
16053
16054 // Suppress the warning if the subscript expression (as identified by the
16055 // ']' location) and the index expression are both from macro expansions
16056 // within a system header.
16057 if (ASE) {
16058 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16059 ASE->getRBracketLoc());
16060 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
16061 SourceLocation IndexLoc =
16062 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
16063 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16064 return;
16065 }
16066 }
16067
16068 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16069 : diag::warn_ptr_arith_exceeds_bounds;
16070 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16071 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16072
16073 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16074 PDiag(DiagID)
16075 << index << ArrayTy->desugar() << CastMsg
16076 << CastMsgTy << IndexExpr->getSourceRange());
16077 } else {
16078 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16079 if (!ASE) {
16080 DiagID = diag::warn_ptr_arith_precedes_bounds;
16081 if (index.isNegative()) index = -index;
16082 }
16083
16084 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16085 PDiag(DiagID) << index << IndexExpr->getSourceRange());
16086 }
16087
16088 const NamedDecl *ND = nullptr;
16089 // Try harder to find a NamedDecl to point at in the note.
16090 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16091 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16092 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16093 ND = DRE->getDecl();
16094 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16095 ND = ME->getMemberDecl();
16096
16097 if (ND)
16098 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16099 PDiag(diag::note_array_declared_here) << ND);
16100}
16101
16102void Sema::CheckArrayAccess(const Expr *expr) {
16103 int AllowOnePastEnd = 0;
16104 while (expr) {
16105 expr = expr->IgnoreParenImpCasts();
16106 switch (expr->getStmtClass()) {
16107 case Stmt::ArraySubscriptExprClass: {
16108 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16109 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16110 AllowOnePastEnd > 0);
16111 expr = ASE->getBase();
16112 break;
16113 }
16114 case Stmt::MemberExprClass: {
16115 expr = cast<MemberExpr>(expr)->getBase();
16116 break;
16117 }
16118 case Stmt::CXXMemberCallExprClass: {
16119 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16120 break;
16121 }
16122 case Stmt::ArraySectionExprClass: {
16123 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16124 // FIXME: We should probably be checking all of the elements to the
16125 // 'length' here as well.
16126 if (ASE->getLowerBound())
16127 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16128 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16129 return;
16130 }
16131 case Stmt::UnaryOperatorClass: {
16132 // Only unwrap the * and & unary operators
16133 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16134 expr = UO->getSubExpr();
16135 switch (UO->getOpcode()) {
16136 case UO_AddrOf:
16137 AllowOnePastEnd++;
16138 break;
16139 case UO_Deref:
16140 AllowOnePastEnd--;
16141 break;
16142 default:
16143 return;
16144 }
16145 break;
16146 }
16147 case Stmt::ConditionalOperatorClass: {
16148 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16149 if (const Expr *lhs = cond->getLHS())
16150 CheckArrayAccess(lhs);
16151 if (const Expr *rhs = cond->getRHS())
16152 CheckArrayAccess(rhs);
16153 return;
16154 }
16155 case Stmt::CXXOperatorCallExprClass: {
16156 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16157 for (const auto *Arg : OCE->arguments())
16158 CheckArrayAccess(Arg);
16159 return;
16160 }
16161 default:
16162 return;
16163 }
16164 }
16165}
16166
16168 Expr *RHS, bool isProperty) {
16169 // Check if RHS is an Objective-C object literal, which also can get
16170 // immediately zapped in a weak reference. Note that we explicitly
16171 // allow ObjCStringLiterals, since those are designed to never really die.
16172 RHS = RHS->IgnoreParenImpCasts();
16173
16174 // This enum needs to match with the 'select' in
16175 // warn_objc_arc_literal_assign (off-by-1).
16177 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16178 return false;
16179
16180 S.Diag(Loc, diag::warn_arc_literal_assign)
16181 << (unsigned) Kind
16182 << (isProperty ? 0 : 1)
16183 << RHS->getSourceRange();
16184
16185 return true;
16186}
16187
16190 Expr *RHS, bool isProperty) {
16191 // Strip off any implicit cast added to get to the one ARC-specific.
16192 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16193 if (cast->getCastKind() == CK_ARCConsumeObject) {
16194 S.Diag(Loc, diag::warn_arc_retained_assign)
16196 << (isProperty ? 0 : 1)
16197 << RHS->getSourceRange();
16198 return true;
16199 }
16200 RHS = cast->getSubExpr();
16201 }
16202
16203 if (LT == Qualifiers::OCL_Weak &&
16204 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16205 return true;
16206
16207 return false;
16208}
16209
16211 QualType LHS, Expr *RHS) {
16213
16215 return false;
16216
16217 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16218 return true;
16219
16220 return false;
16221}
16222
16224 Expr *LHS, Expr *RHS) {
16225 QualType LHSType;
16226 // PropertyRef on LHS type need be directly obtained from
16227 // its declaration as it has a PseudoType.
16229 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16230 if (PRE && !PRE->isImplicitProperty()) {
16231 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16232 if (PD)
16233 LHSType = PD->getType();
16234 }
16235
16236 if (LHSType.isNull())
16237 LHSType = LHS->getType();
16238
16240
16241 if (LT == Qualifiers::OCL_Weak) {
16242 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16244 }
16245
16246 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16247 return;
16248
16249 // FIXME. Check for other life times.
16250 if (LT != Qualifiers::OCL_None)
16251 return;
16252
16253 if (PRE) {
16254 if (PRE->isImplicitProperty())
16255 return;
16256 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16257 if (!PD)
16258 return;
16259
16260 unsigned Attributes = PD->getPropertyAttributes();
16261 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16262 // when 'assign' attribute was not explicitly specified
16263 // by user, ignore it and rely on property type itself
16264 // for lifetime info.
16265 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16266 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16267 LHSType->isObjCRetainableType())
16268 return;
16269
16270 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16271 if (cast->getCastKind() == CK_ARCConsumeObject) {
16272 Diag(Loc, diag::warn_arc_retained_property_assign)
16273 << RHS->getSourceRange();
16274 return;
16275 }
16276 RHS = cast->getSubExpr();
16277 }
16278 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16279 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16280 return;
16281 }
16282 }
16283}
16284
16285//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16286
16287static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16288 SourceLocation StmtLoc,
16289 const NullStmt *Body) {
16290 // Do not warn if the body is a macro that expands to nothing, e.g:
16291 //
16292 // #define CALL(x)
16293 // if (condition)
16294 // CALL(0);
16295 if (Body->hasLeadingEmptyMacro())
16296 return false;
16297
16298 // Get line numbers of statement and body.
16299 bool StmtLineInvalid;
16300 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16301 &StmtLineInvalid);
16302 if (StmtLineInvalid)
16303 return false;
16304
16305 bool BodyLineInvalid;
16306 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16307 &BodyLineInvalid);
16308 if (BodyLineInvalid)
16309 return false;
16310
16311 // Warn if null statement and body are on the same line.
16312 if (StmtLine != BodyLine)
16313 return false;
16314
16315 return true;
16316}
16317
16319 const Stmt *Body,
16320 unsigned DiagID) {
16321 // Since this is a syntactic check, don't emit diagnostic for template
16322 // instantiations, this just adds noise.
16324 return;
16325
16326 // The body should be a null statement.
16327 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16328 if (!NBody)
16329 return;
16330
16331 // Do the usual checks.
16332 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16333 return;
16334
16335 Diag(NBody->getSemiLoc(), DiagID);
16336 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16337}
16338
16340 const Stmt *PossibleBody) {
16341 assert(!CurrentInstantiationScope); // Ensured by caller
16342
16343 SourceLocation StmtLoc;
16344 const Stmt *Body;
16345 unsigned DiagID;
16346 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16347 StmtLoc = FS->getRParenLoc();
16348 Body = FS->getBody();
16349 DiagID = diag::warn_empty_for_body;
16350 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16351 StmtLoc = WS->getRParenLoc();
16352 Body = WS->getBody();
16353 DiagID = diag::warn_empty_while_body;
16354 } else
16355 return; // Neither `for' nor `while'.
16356
16357 // The body should be a null statement.
16358 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16359 if (!NBody)
16360 return;
16361
16362 // Skip expensive checks if diagnostic is disabled.
16363 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16364 return;
16365
16366 // Do the usual checks.
16367 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16368 return;
16369
16370 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16371 // noise level low, emit diagnostics only if for/while is followed by a
16372 // CompoundStmt, e.g.:
16373 // for (int i = 0; i < n; i++);
16374 // {
16375 // a(i);
16376 // }
16377 // or if for/while is followed by a statement with more indentation
16378 // than for/while itself:
16379 // for (int i = 0; i < n; i++);
16380 // a(i);
16381 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16382 if (!ProbableTypo) {
16383 bool BodyColInvalid;
16384 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16385 PossibleBody->getBeginLoc(), &BodyColInvalid);
16386 if (BodyColInvalid)
16387 return;
16388
16389 bool StmtColInvalid;
16390 unsigned StmtCol =
16391 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16392 if (StmtColInvalid)
16393 return;
16394
16395 if (BodyCol > StmtCol)
16396 ProbableTypo = true;
16397 }
16398
16399 if (ProbableTypo) {
16400 Diag(NBody->getSemiLoc(), DiagID);
16401 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16402 }
16403}
16404
16405//===--- CHECK: Warn on self move with std::move. -------------------------===//
16406
16407void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16408 SourceLocation OpLoc) {
16409 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16410 return;
16411
16413 return;
16414
16415 // Strip parens and casts away.
16416 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16417 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16418
16419 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16420 // which we can treat as an inlined std::move
16421 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16422 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16423 RHSExpr = CE->getArg(0);
16424 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16425 CXXSCE && CXXSCE->isXValue())
16426 RHSExpr = CXXSCE->getSubExpr();
16427 else
16428 return;
16429
16430 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16431 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16432
16433 // Two DeclRefExpr's, check that the decls are the same.
16434 if (LHSDeclRef && RHSDeclRef) {
16435 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16436 return;
16437 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16438 RHSDeclRef->getDecl()->getCanonicalDecl())
16439 return;
16440
16441 auto D = Diag(OpLoc, diag::warn_self_move)
16442 << LHSExpr->getType() << LHSExpr->getSourceRange()
16443 << RHSExpr->getSourceRange();
16444 if (const FieldDecl *F =
16446 D << 1 << F
16447 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16448 else
16449 D << 0;
16450 return;
16451 }
16452
16453 // Member variables require a different approach to check for self moves.
16454 // MemberExpr's are the same if every nested MemberExpr refers to the same
16455 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16456 // the base Expr's are CXXThisExpr's.
16457 const Expr *LHSBase = LHSExpr;
16458 const Expr *RHSBase = RHSExpr;
16459 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16460 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16461 if (!LHSME || !RHSME)
16462 return;
16463
16464 while (LHSME && RHSME) {
16465 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16466 RHSME->getMemberDecl()->getCanonicalDecl())
16467 return;
16468
16469 LHSBase = LHSME->getBase();
16470 RHSBase = RHSME->getBase();
16471 LHSME = dyn_cast<MemberExpr>(LHSBase);
16472 RHSME = dyn_cast<MemberExpr>(RHSBase);
16473 }
16474
16475 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16476 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16477 if (LHSDeclRef && RHSDeclRef) {
16478 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16479 return;
16480 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16481 RHSDeclRef->getDecl()->getCanonicalDecl())
16482 return;
16483
16484 Diag(OpLoc, diag::warn_self_move)
16485 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16486 << RHSExpr->getSourceRange();
16487 return;
16488 }
16489
16490 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16491 Diag(OpLoc, diag::warn_self_move)
16492 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16493 << RHSExpr->getSourceRange();
16494}
16495
16496//===--- Layout compatibility ----------------------------------------------//
16497
16498static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16499
16500/// Check if two enumeration types are layout-compatible.
16501static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16502 const EnumDecl *ED2) {
16503 // C++11 [dcl.enum] p8:
16504 // Two enumeration types are layout-compatible if they have the same
16505 // underlying type.
16506 return ED1->isComplete() && ED2->isComplete() &&
16507 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16508}
16509
16510/// Check if two fields are layout-compatible.
16511/// Can be used on union members, which are exempt from alignment requirement
16512/// of common initial sequence.
16513static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16514 const FieldDecl *Field2,
16515 bool AreUnionMembers = false) {
16516#ifndef NDEBUG
16517 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16518 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16519 assert(((Field1Parent->isStructureOrClassType() &&
16520 Field2Parent->isStructureOrClassType()) ||
16521 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16522 "Can't evaluate layout compatibility between a struct field and a "
16523 "union field.");
16524 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16525 (AreUnionMembers && Field1Parent->isUnionType())) &&
16526 "AreUnionMembers should be 'true' for union fields (only).");
16527#endif
16528
16529 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16530 return false;
16531
16532 if (Field1->isBitField() != Field2->isBitField())
16533 return false;
16534
16535 if (Field1->isBitField()) {
16536 // Make sure that the bit-fields are the same length.
16537 unsigned Bits1 = Field1->getBitWidthValue();
16538 unsigned Bits2 = Field2->getBitWidthValue();
16539
16540 if (Bits1 != Bits2)
16541 return false;
16542 }
16543
16544 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16545 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16546 return false;
16547
16548 if (!AreUnionMembers &&
16549 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16550 return false;
16551
16552 return true;
16553}
16554
16555/// Check if two standard-layout structs are layout-compatible.
16556/// (C++11 [class.mem] p17)
16557static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16558 const RecordDecl *RD2) {
16559 // Get to the class where the fields are declared
16560 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16561 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16562
16563 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16564 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16565
16566 // Check the fields.
16567 return llvm::equal(RD1->fields(), RD2->fields(),
16568 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16569 return isLayoutCompatible(C, F1, F2);
16570 });
16571}
16572
16573/// Check if two standard-layout unions are layout-compatible.
16574/// (C++11 [class.mem] p18)
16575static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16576 const RecordDecl *RD2) {
16577 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16578 RD2->fields());
16579
16580 for (auto *Field1 : RD1->fields()) {
16581 auto I = UnmatchedFields.begin();
16582 auto E = UnmatchedFields.end();
16583
16584 for ( ; I != E; ++I) {
16585 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16586 bool Result = UnmatchedFields.erase(*I);
16587 (void) Result;
16588 assert(Result);
16589 break;
16590 }
16591 }
16592 if (I == E)
16593 return false;
16594 }
16595
16596 return UnmatchedFields.empty();
16597}
16598
16599static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16600 const RecordDecl *RD2) {
16601 if (RD1->isUnion() != RD2->isUnion())
16602 return false;
16603
16604 if (RD1->isUnion())
16605 return isLayoutCompatibleUnion(C, RD1, RD2);
16606 else
16607 return isLayoutCompatibleStruct(C, RD1, RD2);
16608}
16609
16610/// Check if two types are layout-compatible in C++11 sense.
16611static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16612 if (T1.isNull() || T2.isNull())
16613 return false;
16614
16615 // C++20 [basic.types] p11:
16616 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16617 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16618 // or layout-compatible standard-layout class types (11.4).
16621
16622 if (C.hasSameType(T1, T2))
16623 return true;
16624
16625 const Type::TypeClass TC1 = T1->getTypeClass();
16626 const Type::TypeClass TC2 = T2->getTypeClass();
16627
16628 if (TC1 != TC2)
16629 return false;
16630
16631 if (TC1 == Type::Enum)
16632 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16633 if (TC1 == Type::Record) {
16634 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16635 return false;
16636
16638 T2->castAsRecordDecl());
16639 }
16640
16641 return false;
16642}
16643
16645 return isLayoutCompatible(getASTContext(), T1, T2);
16646}
16647
16648//===-------------- Pointer interconvertibility ----------------------------//
16649
16651 const TypeSourceInfo *Derived) {
16652 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16653 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16654
16655 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16656 getASTContext().hasSameType(BaseT, DerivedT))
16657 return true;
16658
16659 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16660 return false;
16661
16662 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16663 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16664 return true;
16665
16666 return false;
16667}
16668
16669//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16670
16671/// Given a type tag expression find the type tag itself.
16672///
16673/// \param TypeExpr Type tag expression, as it appears in user's code.
16674///
16675/// \param VD Declaration of an identifier that appears in a type tag.
16676///
16677/// \param MagicValue Type tag magic value.
16678///
16679/// \param isConstantEvaluated whether the evalaution should be performed in
16680
16681/// constant context.
16682static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16683 const ValueDecl **VD, uint64_t *MagicValue,
16684 bool isConstantEvaluated) {
16685 while(true) {
16686 if (!TypeExpr)
16687 return false;
16688
16689 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16690
16691 switch (TypeExpr->getStmtClass()) {
16692 case Stmt::UnaryOperatorClass: {
16693 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16694 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16695 TypeExpr = UO->getSubExpr();
16696 continue;
16697 }
16698 return false;
16699 }
16700
16701 case Stmt::DeclRefExprClass: {
16702 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16703 *VD = DRE->getDecl();
16704 return true;
16705 }
16706
16707 case Stmt::IntegerLiteralClass: {
16708 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16709 llvm::APInt MagicValueAPInt = IL->getValue();
16710 if (MagicValueAPInt.getActiveBits() <= 64) {
16711 *MagicValue = MagicValueAPInt.getZExtValue();
16712 return true;
16713 } else
16714 return false;
16715 }
16716
16717 case Stmt::BinaryConditionalOperatorClass:
16718 case Stmt::ConditionalOperatorClass: {
16719 const AbstractConditionalOperator *ACO =
16721 bool Result;
16722 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16723 isConstantEvaluated)) {
16724 if (Result)
16725 TypeExpr = ACO->getTrueExpr();
16726 else
16727 TypeExpr = ACO->getFalseExpr();
16728 continue;
16729 }
16730 return false;
16731 }
16732
16733 case Stmt::BinaryOperatorClass: {
16734 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16735 if (BO->getOpcode() == BO_Comma) {
16736 TypeExpr = BO->getRHS();
16737 continue;
16738 }
16739 return false;
16740 }
16741
16742 default:
16743 return false;
16744 }
16745 }
16746}
16747
16748/// Retrieve the C type corresponding to type tag TypeExpr.
16749///
16750/// \param TypeExpr Expression that specifies a type tag.
16751///
16752/// \param MagicValues Registered magic values.
16753///
16754/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16755/// kind.
16756///
16757/// \param TypeInfo Information about the corresponding C type.
16758///
16759/// \param isConstantEvaluated whether the evalaution should be performed in
16760/// constant context.
16761///
16762/// \returns true if the corresponding C type was found.
16764 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16765 const ASTContext &Ctx,
16766 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16767 *MagicValues,
16768 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16769 bool isConstantEvaluated) {
16770 FoundWrongKind = false;
16771
16772 // Variable declaration that has type_tag_for_datatype attribute.
16773 const ValueDecl *VD = nullptr;
16774
16775 uint64_t MagicValue;
16776
16777 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16778 return false;
16779
16780 if (VD) {
16781 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16782 if (I->getArgumentKind() != ArgumentKind) {
16783 FoundWrongKind = true;
16784 return false;
16785 }
16786 TypeInfo.Type = I->getMatchingCType();
16787 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16788 TypeInfo.MustBeNull = I->getMustBeNull();
16789 return true;
16790 }
16791 return false;
16792 }
16793
16794 if (!MagicValues)
16795 return false;
16796
16797 llvm::DenseMap<Sema::TypeTagMagicValue,
16799 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16800 if (I == MagicValues->end())
16801 return false;
16802
16803 TypeInfo = I->second;
16804 return true;
16805}
16806
16808 uint64_t MagicValue, QualType Type,
16809 bool LayoutCompatible,
16810 bool MustBeNull) {
16811 if (!TypeTagForDatatypeMagicValues)
16812 TypeTagForDatatypeMagicValues.reset(
16813 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16814
16815 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16816 (*TypeTagForDatatypeMagicValues)[Magic] =
16817 TypeTagData(Type, LayoutCompatible, MustBeNull);
16818}
16819
16820static bool IsSameCharType(QualType T1, QualType T2) {
16821 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16822 if (!BT1)
16823 return false;
16824
16825 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16826 if (!BT2)
16827 return false;
16828
16829 BuiltinType::Kind T1Kind = BT1->getKind();
16830 BuiltinType::Kind T2Kind = BT2->getKind();
16831
16832 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16833 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16834 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16835 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16836}
16837
16838void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16839 const ArrayRef<const Expr *> ExprArgs,
16840 SourceLocation CallSiteLoc) {
16841 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16842 bool IsPointerAttr = Attr->getIsPointer();
16843
16844 // Retrieve the argument representing the 'type_tag'.
16845 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16846 if (TypeTagIdxAST >= ExprArgs.size()) {
16847 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16848 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16849 return;
16850 }
16851 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16852 bool FoundWrongKind;
16853 TypeTagData TypeInfo;
16854 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16855 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16856 TypeInfo, isConstantEvaluatedContext())) {
16857 if (FoundWrongKind)
16858 Diag(TypeTagExpr->getExprLoc(),
16859 diag::warn_type_tag_for_datatype_wrong_kind)
16860 << TypeTagExpr->getSourceRange();
16861 return;
16862 }
16863
16864 // Retrieve the argument representing the 'arg_idx'.
16865 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16866 if (ArgumentIdxAST >= ExprArgs.size()) {
16867 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16868 << 1 << Attr->getArgumentIdx().getSourceIndex();
16869 return;
16870 }
16871 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16872 if (IsPointerAttr) {
16873 // Skip implicit cast of pointer to `void *' (as a function argument).
16874 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16875 if (ICE->getType()->isVoidPointerType() &&
16876 ICE->getCastKind() == CK_BitCast)
16877 ArgumentExpr = ICE->getSubExpr();
16878 }
16879 QualType ArgumentType = ArgumentExpr->getType();
16880
16881 // Passing a `void*' pointer shouldn't trigger a warning.
16882 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16883 return;
16884
16885 if (TypeInfo.MustBeNull) {
16886 // Type tag with matching void type requires a null pointer.
16887 if (!ArgumentExpr->isNullPointerConstant(Context,
16889 Diag(ArgumentExpr->getExprLoc(),
16890 diag::warn_type_safety_null_pointer_required)
16891 << ArgumentKind->getName()
16892 << ArgumentExpr->getSourceRange()
16893 << TypeTagExpr->getSourceRange();
16894 }
16895 return;
16896 }
16897
16898 QualType RequiredType = TypeInfo.Type;
16899 if (IsPointerAttr)
16900 RequiredType = Context.getPointerType(RequiredType);
16901
16902 bool mismatch = false;
16903 if (!TypeInfo.LayoutCompatible) {
16904 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16905
16906 // C++11 [basic.fundamental] p1:
16907 // Plain char, signed char, and unsigned char are three distinct types.
16908 //
16909 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16910 // char' depending on the current char signedness mode.
16911 if (mismatch)
16912 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16913 RequiredType->getPointeeType())) ||
16914 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16915 mismatch = false;
16916 } else
16917 if (IsPointerAttr)
16918 mismatch = !isLayoutCompatible(Context,
16919 ArgumentType->getPointeeType(),
16920 RequiredType->getPointeeType());
16921 else
16922 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16923
16924 if (mismatch)
16925 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16926 << ArgumentType << ArgumentKind
16927 << TypeInfo.LayoutCompatible << RequiredType
16928 << ArgumentExpr->getSourceRange()
16929 << TypeTagExpr->getSourceRange();
16930}
16931
16932void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16933 CharUnits Alignment) {
16934 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16935 Alignment);
16936}
16937
16939 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16940 const NamedDecl *ND = m.RD;
16941 if (ND->getName().empty()) {
16942 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16943 ND = TD;
16944 }
16945 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16946 << m.MD << ND << m.E->getSourceRange();
16947 }
16949}
16950
16952 E = E->IgnoreParens();
16953 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16954 return;
16955 if (isa<UnaryOperator>(E) &&
16956 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16957 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16958 if (isa<MemberExpr>(Op)) {
16959 auto &MisalignedMembersForExpr =
16961 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16962 if (MA != MisalignedMembersForExpr.end() &&
16963 (T->isDependentType() || T->isIntegerType() ||
16964 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16965 Context.getTypeAlignInChars(
16966 T->getPointeeType()) <= MA->Alignment))))
16967 MisalignedMembersForExpr.erase(MA);
16968 }
16969 }
16970}
16971
16973 Expr *E,
16974 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16975 Action) {
16976 const auto *ME = dyn_cast<MemberExpr>(E);
16977 if (!ME)
16978 return;
16979
16980 // No need to check expressions with an __unaligned-qualified type.
16981 if (E->getType().getQualifiers().hasUnaligned())
16982 return;
16983
16984 // For a chain of MemberExpr like "a.b.c.d" this list
16985 // will keep FieldDecl's like [d, c, b].
16986 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16987 const MemberExpr *TopME = nullptr;
16988 bool AnyIsPacked = false;
16989 do {
16990 QualType BaseType = ME->getBase()->getType();
16991 if (BaseType->isDependentType())
16992 return;
16993 if (ME->isArrow())
16994 BaseType = BaseType->getPointeeType();
16995 auto *RD = BaseType->castAsRecordDecl();
16996 if (RD->isInvalidDecl())
16997 return;
16998
16999 ValueDecl *MD = ME->getMemberDecl();
17000 auto *FD = dyn_cast<FieldDecl>(MD);
17001 // We do not care about non-data members.
17002 if (!FD || FD->isInvalidDecl())
17003 return;
17004
17005 AnyIsPacked =
17006 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17007 ReverseMemberChain.push_back(FD);
17008
17009 TopME = ME;
17010 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17011 } while (ME);
17012 assert(TopME && "We did not compute a topmost MemberExpr!");
17013
17014 // Not the scope of this diagnostic.
17015 if (!AnyIsPacked)
17016 return;
17017
17018 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17019 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17020 // TODO: The innermost base of the member expression may be too complicated.
17021 // For now, just disregard these cases. This is left for future
17022 // improvement.
17023 if (!DRE && !isa<CXXThisExpr>(TopBase))
17024 return;
17025
17026 // Alignment expected by the whole expression.
17027 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17028
17029 // No need to do anything else with this case.
17030 if (ExpectedAlignment.isOne())
17031 return;
17032
17033 // Synthesize offset of the whole access.
17034 CharUnits Offset;
17035 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17036 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17037
17038 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17039 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17040 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17041
17042 // The base expression of the innermost MemberExpr may give
17043 // stronger guarantees than the class containing the member.
17044 if (DRE && !TopME->isArrow()) {
17045 const ValueDecl *VD = DRE->getDecl();
17046 if (!VD->getType()->isReferenceType())
17047 CompleteObjectAlignment =
17048 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17049 }
17050
17051 // Check if the synthesized offset fulfills the alignment.
17052 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17053 // It may fulfill the offset it but the effective alignment may still be
17054 // lower than the expected expression alignment.
17055 CompleteObjectAlignment < ExpectedAlignment) {
17056 // If this happens, we want to determine a sensible culprit of this.
17057 // Intuitively, watching the chain of member expressions from right to
17058 // left, we start with the required alignment (as required by the field
17059 // type) but some packed attribute in that chain has reduced the alignment.
17060 // It may happen that another packed structure increases it again. But if
17061 // we are here such increase has not been enough. So pointing the first
17062 // FieldDecl that either is packed or else its RecordDecl is,
17063 // seems reasonable.
17064 FieldDecl *FD = nullptr;
17065 CharUnits Alignment;
17066 for (FieldDecl *FDI : ReverseMemberChain) {
17067 if (FDI->hasAttr<PackedAttr>() ||
17068 FDI->getParent()->hasAttr<PackedAttr>()) {
17069 FD = FDI;
17070 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
17071 Context.getTypeAlignInChars(
17072 Context.getCanonicalTagType(FD->getParent())));
17073 break;
17074 }
17075 }
17076 assert(FD && "We did not find a packed FieldDecl!");
17077 Action(E, FD->getParent(), FD, Alignment);
17078 }
17079}
17080
17081void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17082 using namespace std::placeholders;
17083
17085 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17086 _2, _3, _4));
17087}
17088
17090 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17091 if (checkArgCount(TheCall, 1))
17092 return true;
17093
17094 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
17095 if (A.isInvalid())
17096 return true;
17097
17098 TheCall->setArg(0, A.get());
17099 QualType TyA = A.get()->getType();
17100
17101 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
17102 ArgTyRestr, 1))
17103 return true;
17104
17105 TheCall->setType(TyA);
17106 return false;
17107}
17108
17109bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17110 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17111 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17112 TheCall->setType(*Res);
17113 return false;
17114 }
17115 return true;
17116}
17117
17119 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17120 if (!Res)
17121 return true;
17122
17123 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17124 TheCall->setType(VecTy0->getElementType());
17125 else
17126 TheCall->setType(*Res);
17127
17128 return false;
17129}
17130
17132 SourceLocation Loc) {
17134 R = RHS->getEnumCoercedType(S.Context);
17135 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17137 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17138 << LHS->getSourceRange() << RHS->getSourceRange()
17139 << /*Arithmetic Between*/ 0 << L << R;
17140 }
17141 return false;
17142}
17143
17144/// Check if all arguments have the same type. If the types don't match, emit an
17145/// error message and return true. Otherwise return false.
17146///
17147/// For scalars we directly compare their unqualified types. But even if we
17148/// compare unqualified vector types, a difference in qualifiers in the element
17149/// types can make the vector types be considered not equal. For example,
17150/// vector of 4 'const float' values vs vector of 4 'float' values.
17151/// So we compare unqualified types of their elements and number of elements.
17153 ArrayRef<Expr *> Args) {
17154 assert(!Args.empty() && "Should have at least one argument.");
17155
17156 Expr *Arg0 = Args.front();
17157 QualType Ty0 = Arg0->getType();
17158
17159 auto EmitError = [&](Expr *ArgI) {
17160 SemaRef.Diag(Arg0->getBeginLoc(),
17161 diag::err_typecheck_call_different_arg_types)
17162 << Arg0->getType() << ArgI->getType();
17163 };
17164
17165 // Compare scalar types.
17166 if (!Ty0->isVectorType()) {
17167 for (Expr *ArgI : Args.drop_front())
17168 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17169 EmitError(ArgI);
17170 return true;
17171 }
17172
17173 return false;
17174 }
17175
17176 // Compare vector types.
17177 const auto *Vec0 = Ty0->castAs<VectorType>();
17178 for (Expr *ArgI : Args.drop_front()) {
17179 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17180 if (!VecI ||
17181 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17182 VecI->getElementType()) ||
17183 Vec0->getNumElements() != VecI->getNumElements()) {
17184 EmitError(ArgI);
17185 return true;
17186 }
17187 }
17188
17189 return false;
17190}
17191
17192std::optional<QualType>
17194 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17195 if (checkArgCount(TheCall, 2))
17196 return std::nullopt;
17197
17199 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17200 return std::nullopt;
17201
17202 Expr *Args[2];
17203 for (int I = 0; I < 2; ++I) {
17204 ExprResult Converted =
17205 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17206 if (Converted.isInvalid())
17207 return std::nullopt;
17208 Args[I] = Converted.get();
17209 }
17210
17211 SourceLocation LocA = Args[0]->getBeginLoc();
17212 QualType TyA = Args[0]->getType();
17213
17214 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17215 return std::nullopt;
17216
17217 if (checkBuiltinVectorMathArgTypes(*this, Args))
17218 return std::nullopt;
17219
17220 TheCall->setArg(0, Args[0]);
17221 TheCall->setArg(1, Args[1]);
17222 return TyA;
17223}
17224
17226 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17227 if (checkArgCount(TheCall, 3))
17228 return true;
17229
17230 SourceLocation Loc = TheCall->getExprLoc();
17231 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17232 TheCall->getArg(1), Loc) ||
17233 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17234 TheCall->getArg(2), Loc))
17235 return true;
17236
17237 Expr *Args[3];
17238 for (int I = 0; I < 3; ++I) {
17239 ExprResult Converted =
17240 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17241 if (Converted.isInvalid())
17242 return true;
17243 Args[I] = Converted.get();
17244 }
17245
17246 int ArgOrdinal = 1;
17247 for (Expr *Arg : Args) {
17248 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17249 ArgTyRestr, ArgOrdinal++))
17250 return true;
17251 }
17252
17253 if (checkBuiltinVectorMathArgTypes(*this, Args))
17254 return true;
17255
17256 for (int I = 0; I < 3; ++I)
17257 TheCall->setArg(I, Args[I]);
17258
17259 TheCall->setType(Args[0]->getType());
17260 return false;
17261}
17262
17263bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17264 if (checkArgCount(TheCall, 1))
17265 return true;
17266
17267 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17268 if (A.isInvalid())
17269 return true;
17270
17271 TheCall->setArg(0, A.get());
17272 return false;
17273}
17274
17275bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17276 if (checkArgCount(TheCall, 1))
17277 return true;
17278
17279 ExprResult Arg = TheCall->getArg(0);
17280 QualType TyArg = Arg.get()->getType();
17281
17282 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17283 return Diag(TheCall->getArg(0)->getBeginLoc(),
17284 diag::err_builtin_invalid_arg_type)
17285 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17286
17287 TheCall->setType(TyArg);
17288 return false;
17289}
17290
17291ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17292 ExprResult CallResult) {
17293 if (checkArgCount(TheCall, 1))
17294 return ExprError();
17295
17296 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17297 if (MatrixArg.isInvalid())
17298 return MatrixArg;
17299 Expr *Matrix = MatrixArg.get();
17300
17301 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17302 if (!MType) {
17303 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17304 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17305 << Matrix->getType();
17306 return ExprError();
17307 }
17308
17309 // Create returned matrix type by swapping rows and columns of the argument
17310 // matrix type.
17311 QualType ResultType = Context.getConstantMatrixType(
17312 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17313
17314 // Change the return type to the type of the returned matrix.
17315 TheCall->setType(ResultType);
17316
17317 // Update call argument to use the possibly converted matrix argument.
17318 TheCall->setArg(0, Matrix);
17319 return CallResult;
17320}
17321
17322// Get and verify the matrix dimensions.
17323static std::optional<unsigned>
17325 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17326 if (!Value) {
17327 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17328 << Name;
17329 return {};
17330 }
17331 uint64_t Dim = Value->getZExtValue();
17332 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17333 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17334 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17335 return {};
17336 }
17337 return Dim;
17338}
17339
17340ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17341 ExprResult CallResult) {
17342 if (!getLangOpts().MatrixTypes) {
17343 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17344 return ExprError();
17345 }
17346
17347 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17349 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17350 << /*column*/ 1 << /*load*/ 0;
17351 return ExprError();
17352 }
17353
17354 if (checkArgCount(TheCall, 4))
17355 return ExprError();
17356
17357 unsigned PtrArgIdx = 0;
17358 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17359 Expr *RowsExpr = TheCall->getArg(1);
17360 Expr *ColumnsExpr = TheCall->getArg(2);
17361 Expr *StrideExpr = TheCall->getArg(3);
17362
17363 bool ArgError = false;
17364
17365 // Check pointer argument.
17366 {
17368 if (PtrConv.isInvalid())
17369 return PtrConv;
17370 PtrExpr = PtrConv.get();
17371 TheCall->setArg(0, PtrExpr);
17372 if (PtrExpr->isTypeDependent()) {
17373 TheCall->setType(Context.DependentTy);
17374 return TheCall;
17375 }
17376 }
17377
17378 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17379 QualType ElementTy;
17380 if (!PtrTy) {
17381 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17382 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17383 << PtrExpr->getType();
17384 ArgError = true;
17385 } else {
17386 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17387
17389 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17390 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17391 << /* no fp */ 0 << PtrExpr->getType();
17392 ArgError = true;
17393 }
17394 }
17395
17396 // Apply default Lvalue conversions and convert the expression to size_t.
17397 auto ApplyArgumentConversions = [this](Expr *E) {
17399 if (Conv.isInvalid())
17400 return Conv;
17401
17402 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17403 };
17404
17405 // Apply conversion to row and column expressions.
17406 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17407 if (!RowsConv.isInvalid()) {
17408 RowsExpr = RowsConv.get();
17409 TheCall->setArg(1, RowsExpr);
17410 } else
17411 RowsExpr = nullptr;
17412
17413 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17414 if (!ColumnsConv.isInvalid()) {
17415 ColumnsExpr = ColumnsConv.get();
17416 TheCall->setArg(2, ColumnsExpr);
17417 } else
17418 ColumnsExpr = nullptr;
17419
17420 // If any part of the result matrix type is still pending, just use
17421 // Context.DependentTy, until all parts are resolved.
17422 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17423 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17424 TheCall->setType(Context.DependentTy);
17425 return CallResult;
17426 }
17427
17428 // Check row and column dimensions.
17429 std::optional<unsigned> MaybeRows;
17430 if (RowsExpr)
17431 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17432
17433 std::optional<unsigned> MaybeColumns;
17434 if (ColumnsExpr)
17435 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17436
17437 // Check stride argument.
17438 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17439 if (StrideConv.isInvalid())
17440 return ExprError();
17441 StrideExpr = StrideConv.get();
17442 TheCall->setArg(3, StrideExpr);
17443
17444 if (MaybeRows) {
17445 if (std::optional<llvm::APSInt> Value =
17446 StrideExpr->getIntegerConstantExpr(Context)) {
17447 uint64_t Stride = Value->getZExtValue();
17448 if (Stride < *MaybeRows) {
17449 Diag(StrideExpr->getBeginLoc(),
17450 diag::err_builtin_matrix_stride_too_small);
17451 ArgError = true;
17452 }
17453 }
17454 }
17455
17456 if (ArgError || !MaybeRows || !MaybeColumns)
17457 return ExprError();
17458
17459 TheCall->setType(
17460 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17461 return CallResult;
17462}
17463
17464ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17465 ExprResult CallResult) {
17466 if (!getLangOpts().MatrixTypes) {
17467 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17468 return ExprError();
17469 }
17470
17471 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17473 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17474 << /*column*/ 1 << /*store*/ 1;
17475 return ExprError();
17476 }
17477
17478 if (checkArgCount(TheCall, 3))
17479 return ExprError();
17480
17481 unsigned PtrArgIdx = 1;
17482 Expr *MatrixExpr = TheCall->getArg(0);
17483 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17484 Expr *StrideExpr = TheCall->getArg(2);
17485
17486 bool ArgError = false;
17487
17488 {
17489 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17490 if (MatrixConv.isInvalid())
17491 return MatrixConv;
17492 MatrixExpr = MatrixConv.get();
17493 TheCall->setArg(0, MatrixExpr);
17494 }
17495 if (MatrixExpr->isTypeDependent()) {
17496 TheCall->setType(Context.DependentTy);
17497 return TheCall;
17498 }
17499
17500 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17501 if (!MatrixTy) {
17502 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17503 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17504 ArgError = true;
17505 }
17506
17507 {
17509 if (PtrConv.isInvalid())
17510 return PtrConv;
17511 PtrExpr = PtrConv.get();
17512 TheCall->setArg(1, PtrExpr);
17513 if (PtrExpr->isTypeDependent()) {
17514 TheCall->setType(Context.DependentTy);
17515 return TheCall;
17516 }
17517 }
17518
17519 // Check pointer argument.
17520 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17521 if (!PtrTy) {
17522 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17523 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17524 << PtrExpr->getType();
17525 ArgError = true;
17526 } else {
17527 QualType ElementTy = PtrTy->getPointeeType();
17528 if (ElementTy.isConstQualified()) {
17529 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17530 ArgError = true;
17531 }
17532 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17533 if (MatrixTy &&
17534 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17535 Diag(PtrExpr->getBeginLoc(),
17536 diag::err_builtin_matrix_pointer_arg_mismatch)
17537 << ElementTy << MatrixTy->getElementType();
17538 ArgError = true;
17539 }
17540 }
17541
17542 // Apply default Lvalue conversions and convert the stride expression to
17543 // size_t.
17544 {
17545 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17546 if (StrideConv.isInvalid())
17547 return StrideConv;
17548
17549 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17550 if (StrideConv.isInvalid())
17551 return StrideConv;
17552 StrideExpr = StrideConv.get();
17553 TheCall->setArg(2, StrideExpr);
17554 }
17555
17556 // Check stride argument.
17557 if (MatrixTy) {
17558 if (std::optional<llvm::APSInt> Value =
17559 StrideExpr->getIntegerConstantExpr(Context)) {
17560 uint64_t Stride = Value->getZExtValue();
17561 if (Stride < MatrixTy->getNumRows()) {
17562 Diag(StrideExpr->getBeginLoc(),
17563 diag::err_builtin_matrix_stride_too_small);
17564 ArgError = true;
17565 }
17566 }
17567 }
17568
17569 if (ArgError)
17570 return ExprError();
17571
17572 return CallResult;
17573}
17574
17576 const NamedDecl *Callee) {
17577 // This warning does not make sense in code that has no runtime behavior.
17579 return;
17580
17581 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17582
17583 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17584 return;
17585
17586 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17587 // all TCBs the callee is a part of.
17588 llvm::StringSet<> CalleeTCBs;
17589 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17590 CalleeTCBs.insert(A->getTCBName());
17591 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17592 CalleeTCBs.insert(A->getTCBName());
17593
17594 // Go through the TCBs the caller is a part of and emit warnings if Caller
17595 // is in a TCB that the Callee is not.
17596 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17597 StringRef CallerTCB = A->getTCBName();
17598 if (CalleeTCBs.count(CallerTCB) == 0) {
17599 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17600 << Callee << CallerTCB;
17601 }
17602 }
17603}
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
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
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:808
Builtin::Context & BuiltinInfo
Definition ASTContext.h:810
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
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:861
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:927
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:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
SourceLocation getQuestionLoc() const
Definition Expr.h:4386
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
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:7309
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7313
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
SourceLocation getRBracketLoc() const
Definition Expr.h:2775
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3835
QualType getElementType() const
Definition TypeBase.h:3833
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6940
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7089
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7071
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:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
SourceLocation getOperatorLoc() const
Definition Expr.h:4086
SourceLocation getExprLoc() const
Definition Expr.h:4085
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:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
Opcode getOpcode() const
Definition Expr.h:4089
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
BinaryOperatorKind Opcode
Definition Expr.h:4049
Pointer to a block type.
Definition TypeBase.h:3641
This class is used for builtin types like 'int'.
Definition TypeBase.h:3229
bool isInteger() const
Definition TypeBase.h:3290
bool isFloatingPoint() const
Definition TypeBase.h:3302
bool isSignedInteger() const
Definition TypeBase.h:3294
bool isUnsignedInteger() const
Definition TypeBase.h:3298
Kind getKind() const
Definition TypeBase.h:3277
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:3975
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:2968
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
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:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3166
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:3206
arg_iterator arg_end()
Definition Expr.h:3209
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
bool isCallToStdMove() const
Definition Expr.cpp:3653
Expr * getCallee()
Definition Expr.h:3096
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3242
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3143
arg_range arguments()
Definition Expr.h:3201
SourceLocation getEndLoc() const
Definition Expr.h:3302
SourceLocation getRParenLoc() const
Definition Expr.h:3280
Decl * getCalleeDecl()
Definition Expr.h:3126
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:3098
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3185
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:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
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:4397
Expr * getLHS() const
Definition Expr.h:4431
Expr * getRHS() const
Definition Expr.h:4432
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3859
QualType desugar() const
Definition TypeBase.h:3960
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3915
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:4486
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4508
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:5694
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:1276
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:1369
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getBeginLoc() const
Definition Expr.h:1355
SourceLocation getLocation() const
Definition Expr.h:1352
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 hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:961
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3467
Represents an enum.
Definition Decl.h:4055
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4287
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4228
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:681
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:678
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...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4241
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
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:3699
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:808
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:820
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:810
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:4080
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:4366
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3307
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4752
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3320
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:1672
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2897
Represents a function declaration or definition.
Definition Decl.h:2029
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4553
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3742
param_iterator param_end()
Definition Decl.h:2827
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3845
QualType getReturnType() const
Definition Decl.h:2885
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2814
param_iterator param_begin()
Definition Decl.h:2826
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3112
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4309
bool isStatic() const
Definition Decl.h:2969
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4124
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4110
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3806
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
unsigned getNumParams() const
Definition TypeBase.h:5684
QualType getParamType(unsigned i) const
Definition TypeBase.h:5686
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5810
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5695
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5805
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5691
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4911
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4907
QualType getReturnType() const
Definition TypeBase.h:4942
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:3859
Describes an C or C++ initializer list.
Definition Expr.h:5314
ArrayRef< Expr * > inits() const
Definition Expr.h:5367
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:4436
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4457
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
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:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h: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:2188
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:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6816
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5201
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8573
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2970
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:8489
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8615
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8529
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:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
void removeLocalVolatile()
Definition TypeBase.h:8605
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
void removeLocalConst()
Definition TypeBase.h:8597
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8562
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8610
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8535
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:4369
bool hasFlexibleArrayMember() const
Definition Decl.h:4402
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4455
field_range fields() const
Definition Decl.h:4572
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4447
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:1034
@ 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:1117
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:10411
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10416
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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:1449
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:13196
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1142
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:2778
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9465
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:7022
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:2078
SemaHexagon & Hexagon()
Definition Sema.h:1489
SemaSYCL & SYCL()
Definition Sema.h:1559
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:1748
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:1579
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:1309
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:937
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:1519
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1374
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:940
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:769
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2638
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:1213
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:2745
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:933
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:1464
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:1479
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:1307
static const uint64_t MaximumAlignment
Definition Sema.h:1236
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:961
SemaHLSL & HLSL()
Definition Sema.h:1484
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1504
SemaRISCV & RISCV()
Definition Sema.h:1549
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:2811
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7058
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1760
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:1342
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:2718
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15562
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:2433
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:1447
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:1529
FormatArgumentPassingKind
Definition Sema.h:2648
@ FAPK_Elsewhere
Definition Sema.h:2652
@ FAPK_Fixed
Definition Sema.h:2649
@ FAPK_Variadic
Definition Sema.h:2650
@ FAPK_VAList
Definition Sema.h:2651
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:8263
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:14088
SourceManager & getSourceManager() const
Definition Sema.h:938
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:2640
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:1539
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:1268
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:1569
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:1312
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:792
DiagnosticsEngine & Diags
Definition Sema.h:1311
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:1514
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:638
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:6322
SemaSPIRV & SPIRV()
Definition Sema.h:1554
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:1494
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6510
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:1574
SemaARM & ARM()
Definition Sema.h:1454
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:4649
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp: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:1805
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1979
bool isUTF8() const
Definition Expr.h:1924
bool isWide() const
Definition Expr.h:1923
bool isPascal() const
Definition Expr.h:1928
unsigned getLength() const
Definition Expr.h:1915
StringLiteralKind getKind() const
Definition Expr.h:1918
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:1926
unsigned getByteLength() const
Definition Expr.h:1914
StringRef getString() const
Definition Expr.h:1873
bool isUTF16() const
Definition Expr.h:1925
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1980
bool isOrdinary() const
Definition Expr.h:1922
unsigned getCharByteWidth() const
Definition Expr.h:1916
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3882
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3862
bool isUnion() const
Definition Decl.h:3972
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:392
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:6317
A container of type source information.
Definition TypeBase.h:8460
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:8471
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isBlockPointerType() const
Definition TypeBase.h:8746
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9279
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:2270
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2359
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
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:9259
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:2123
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:2521
bool isArrayType() const
Definition TypeBase.h:8825
bool isCharType() const
Definition Type.cpp:2197
bool isFunctionPointerType() const
Definition TypeBase.h:8793
bool isPointerType() const
Definition TypeBase.h:8726
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9136
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isEnumeralType() const
Definition TypeBase.h:8857
bool isScalarType() const
Definition TypeBase.h:9198
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:1958
bool isVariableArrayType() const
Definition TypeBase.h:8837
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2705
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:9214
bool isExtVectorType() const
Definition TypeBase.h:8869
bool isExtVectorBoolType() const
Definition TypeBase.h:8873
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2744
bool isBitIntType() const
Definition TypeBase.h:9001
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9061
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8849
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8861
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2314
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3184
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2655
bool isMemberPointerType() const
Definition TypeBase.h:8807
bool isAtomicType() const
Definition TypeBase.h:8918
bool isFunctionProtoType() const
Definition TypeBase.h:2662
bool isMatrixType() const
Definition TypeBase.h:8889
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3205
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:2865
bool isUnscopedEnumerationType() const
Definition Type.cpp:2190
bool isObjCObjectType() const
Definition TypeBase.h:8909
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9372
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9235
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2571
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:2531
bool isFunctionType() const
Definition TypeBase.h:8722
bool isObjCObjectPointerType() const
Definition TypeBase.h:8905
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2401
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isVectorType() const
Definition TypeBase.h:8865
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
bool isFloatingType() const
Definition Type.cpp:2393
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:2336
bool isAnyPointerType() const
Definition TypeBase.h:8734
TypeClass getTypeClass() const
Definition TypeBase.h:2446
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2472
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
bool isNullPtrType() const
Definition TypeBase.h:9129
bool isRecordType() const
Definition TypeBase.h:8853
bool isObjCRetainableType() const
Definition Type.cpp:5435
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2667
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5156
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2732
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3606
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2368
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1088
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1176
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
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:5581
Represents a variable declaration or definition.
Definition Decl.h:932
Represents a GCC generic vector type.
Definition TypeBase.h:4274
unsigned getNumElements() const
Definition TypeBase.h:4289
QualType getElementType() const
Definition TypeBase.h:4288
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:1533
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1518
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1511
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1525
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2820
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1479
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1540
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.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:829
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:512
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:662
@ Comparison
A comparison.
Definition Sema.h:666
@ NonNull
Values of this type can never be null.
Definition Specifiers.h: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:593
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h: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:552
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:112
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:563
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:498
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:520
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h: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:64
StringLiteralKind
Definition Expr.h:1769
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:4235
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6026
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6019
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:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
Extra information about a function prototype.
Definition TypeBase.h:5491
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:13378
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13404
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13394
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13342
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6916
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2660
#define log2(__x)
Definition tgmath.h:970