clang 24.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
48#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any unrecoverable errors, even if we managed
545 // to build the call.
546 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150namespace {
1151/// Helper class for buffer overflow/overread checking in fortified functions.
1152class FortifiedBufferChecker {
1153public:
1154 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1155 : S(S), TheCall(TheCall), FD(FD),
1156 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1157 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1158 SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1159 }
1160
1161 std::optional<unsigned> TranslateIndex(unsigned Index) {
1162 // If we refer to a diagnose_as_builtin attribute, we need to change the
1163 // argument index to refer to the arguments of the called function. Unless
1164 // the index is out of bounds, which presumably means it's a variadic
1165 // function.
1166 if (!DABAttr)
1167 return Index;
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 unsigned NewIndex = Index < DABIndices
1170 ? DABAttr->argIndices_begin()[Index]
1171 : Index - DABIndices + FD->getNumParams();
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 std::optional<llvm::APSInt>
1178 ComputeExplicitObjectSizeArgument(unsigned Index) {
1179 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1180 if (!IndexOptional)
1181 return std::nullopt;
1182 unsigned NewIndex = *IndexOptional;
1183 Expr::EvalResult Result;
1184 Expr *SizeArg = TheCall->getArg(NewIndex);
1185 if (!SizeArg->EvaluateAsInt(Result, S.getASTContext()))
1186 return std::nullopt;
1187 llvm::APSInt Integer = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
1188 Integer.setIsUnsigned(true);
1189 return Integer;
1190 }
1191
1192 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1193 // If the parameter has a pass_object_size attribute, then we should use its
1194 // (potentially) more strict checking mode. Otherwise, conservatively assume
1195 // type 0.
1196 int BOSType = 0;
1197 // This check can fail for variadic functions.
1198 if (Index < FD->getNumParams()) {
1199 if (const auto *POS =
1200 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1201 BOSType = POS->getType();
1202 }
1203
1204 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1205 if (!IndexOptional)
1206 return std::nullopt;
1207 unsigned NewIndex = *IndexOptional;
1208
1209 if (NewIndex >= TheCall->getNumArgs())
1210 return std::nullopt;
1211
1212 const Expr *ObjArg = TheCall->getArg(NewIndex);
1213 if (std::optional<uint64_t> ObjSize =
1214 ObjArg->tryEvaluateObjectSize(S.getASTContext(), BOSType)) {
1215 // Get the object size in the target's size_t width.
1216 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1217 }
1218 return std::nullopt;
1219 }
1220
1221 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1222 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1223 if (!IndexOptional)
1224 return std::nullopt;
1225 unsigned NewIndex = *IndexOptional;
1226
1227 const Expr *ObjArg = TheCall->getArg(NewIndex);
1228
1229 if (std::optional<uint64_t> Result =
1230 ObjArg->tryEvaluateStrLen(S.getASTContext())) {
1231 // Add 1 for null byte.
1232 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1233 }
1234 return std::nullopt;
1235 }
1236
1237 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1238
1239 unsigned getBuiltinID() const {
1240 const FunctionDecl *UseDecl = FD;
1241 if (DABAttr) {
1242 UseDecl = DABAttr->getFunction();
1243 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1244 }
1245 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1246 }
1247
1248 /// Return function name after stripping __builtin_ and _chk affixes.
1249 std::string getFunctionName() const {
1250 unsigned ID = getBuiltinID();
1251 if (!ID) {
1252 // Use callee name directly if not a builtin.
1253 const FunctionDecl *Callee = TheCall->getDirectCallee();
1254 assert(Callee && "expected callee");
1255 return Callee->getName().str();
1256 }
1257 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1258 StringRef Ref = Name;
1259 // Strip __builtin___*_chk or __builtin_ prefix.
1260 if (!(Ref.consume_front("__builtin___") && Ref.consume_back("_chk")))
1261 Ref.consume_front("__builtin_");
1262 assert(!Ref.empty() && "expected non-empty function name");
1263 return Ref.str();
1264 }
1265
1266 /// Check for source buffer overread in memory functions.
1267 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1269 return;
1270
1271 const Expr *SrcArg = TheCall->getArg(SrcArgIdx);
1272 const Expr *SizeArg = TheCall->getArg(SizeArgIdx);
1273 if (SrcArg->isInstantiationDependent() ||
1274 SizeArg->isInstantiationDependent())
1275 return;
1276
1277 std::optional<llvm::APSInt> CopyLen =
1278 ComputeExplicitObjectSizeArgument(SizeArgIdx);
1279 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(SrcArgIdx);
1280
1281 if (!CopyLen || !SrcBufSize)
1282 return;
1283
1284 // Warn only if copy length exceeds source buffer size.
1285 if (llvm::APSInt::compareValues(*CopyLen, *SrcBufSize) <= 0)
1286 return;
1287
1288 S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1289 S.PDiag(diag::warn_stringop_overread)
1290 << getFunctionName() << CopyLen->getZExtValue()
1291 << SrcBufSize->getZExtValue());
1292 }
1293
1294private:
1295 Sema &S;
1296 CallExpr *TheCall;
1297 FunctionDecl *FD;
1298 const DiagnoseAsBuiltinAttr *DABAttr;
1299 unsigned SizeTypeWidth;
1300};
1301} // anonymous namespace
1302
1303void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1304 CallExpr *TheCall) {
1306 return;
1307
1308 FortifiedBufferChecker Checker(*this, FD, TheCall);
1309
1310 unsigned BuiltinID = Checker.getBuiltinID();
1311 if (!BuiltinID)
1312 return;
1313
1314 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1315
1316 std::optional<llvm::APSInt> SourceSize;
1317 std::optional<llvm::APSInt> DestinationSize;
1318 unsigned DiagID = 0;
1319
1320 switch (BuiltinID) {
1321 default:
1322 return;
1323 case Builtin::BI__builtin_strcat:
1324 case Builtin::BIstrcat:
1325 case Builtin::BI__builtin_stpcpy:
1326 case Builtin::BIstpcpy:
1327 case Builtin::BI__builtin_strcpy:
1328 case Builtin::BIstrcpy: {
1329 DiagID = diag::warn_fortify_strlen_overflow;
1330 SourceSize = Checker.ComputeStrLenArgument(1);
1331 DestinationSize = Checker.ComputeSizeArgument(0);
1332 break;
1333 }
1334
1335 case Builtin::BI__builtin___strcat_chk:
1336 case Builtin::BI__builtin___stpcpy_chk:
1337 case Builtin::BI__builtin___strcpy_chk: {
1338 DiagID = diag::warn_fortify_strlen_overflow;
1339 SourceSize = Checker.ComputeStrLenArgument(1);
1340 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(2);
1341 break;
1342 }
1343
1344 case Builtin::BIscanf:
1345 case Builtin::BIfscanf:
1346 case Builtin::BIsscanf: {
1347 unsigned FormatIndex = 1;
1348 unsigned DataIndex = 2;
1349 if (BuiltinID == Builtin::BIscanf) {
1350 FormatIndex = 0;
1351 DataIndex = 1;
1352 }
1353
1354 const auto *FormatExpr =
1355 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1356
1357 StringRef FormatStrRef;
1358 size_t StrLen;
1359 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1360 return;
1361
1362 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1363 unsigned SourceSize) {
1364 DiagID = diag::warn_fortify_scanf_overflow;
1365 unsigned Index = ArgIndex + DataIndex;
1366 std::string FunctionName = Checker.getFunctionName();
1367 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1368 PDiag(DiagID) << FunctionName << (Index + 1)
1369 << DestSize << SourceSize);
1370 };
1371
1372 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1373 return Checker.ComputeSizeArgument(Index + DataIndex);
1374 };
1375 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1376 const char *FormatBytes = FormatStrRef.data();
1378 FormatBytes + StrLen, getLangOpts(),
1379 Context.getTargetInfo());
1380
1381 // Unlike the other cases, in this one we have already issued the diagnostic
1382 // here, so no need to continue (because unlike the other cases, here the
1383 // diagnostic refers to the argument number).
1384 return;
1385 }
1386
1387 case Builtin::BIsprintf:
1388 case Builtin::BI__builtin___sprintf_chk: {
1389 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1390 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1391
1392 StringRef FormatStrRef;
1393 size_t StrLen;
1394 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1395 EstimateSizeFormatHandler H(FormatStrRef);
1396 const char *FormatBytes = FormatStrRef.data();
1398 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1399 Context.getTargetInfo(), false)) {
1400 DiagID = H.isKernelCompatible()
1401 ? diag::warn_format_overflow
1402 : diag::warn_format_overflow_non_kprintf;
1403 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1404 .extOrTrunc(SizeTypeWidth);
1405 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1406 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(2);
1407 } else {
1408 DestinationSize = Checker.ComputeSizeArgument(0);
1409 }
1410 break;
1411 }
1412 }
1413 return;
1414 }
1415 case Builtin::BI__builtin___memcpy_chk:
1416 case Builtin::BI__builtin___memmove_chk:
1417 case Builtin::BI__builtin___memset_chk:
1418 case Builtin::BI__builtin___strlcat_chk:
1419 case Builtin::BI__builtin___strlcpy_chk:
1420 case Builtin::BI__builtin___strncat_chk:
1421 case Builtin::BI__builtin___strncpy_chk:
1422 case Builtin::BI__builtin___stpncpy_chk:
1423 case Builtin::BI__builtin___memccpy_chk:
1424 case Builtin::BI__builtin___mempcpy_chk: {
1425 DiagID = diag::warn_builtin_chk_overflow;
1426 SourceSize =
1427 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1428 DestinationSize =
1429 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1430
1431 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1432 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1433 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1434 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1435 }
1436 break;
1437 }
1438
1439 case Builtin::BI__builtin___snprintf_chk:
1440 case Builtin::BI__builtin___vsnprintf_chk: {
1441 DiagID = diag::warn_builtin_chk_overflow;
1442 SourceSize = Checker.ComputeExplicitObjectSizeArgument(1);
1443 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(3);
1444 break;
1445 }
1446
1447 case Builtin::BIstrncat:
1448 case Builtin::BI__builtin_strncat:
1449 case Builtin::BIstrncpy:
1450 case Builtin::BI__builtin_strncpy:
1451 case Builtin::BIstpncpy:
1452 case Builtin::BI__builtin_stpncpy:
1453 case Builtin::BIstrlcat:
1454 case Builtin::BI__builtin_strlcat:
1455 case Builtin::BIstrlcpy:
1456 case Builtin::BI__builtin_strlcpy: {
1457 // Whether these functions overflow depends on the runtime strlen of the
1458 // string, not just the buffer size, so emitting the "always overflow"
1459 // diagnostic isn't quite right. We should still diagnose passing a buffer
1460 // size larger than the destination buffer though; this is a runtime abort
1461 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1462 DiagID = diag::warn_fortify_source_size_mismatch;
1463 SourceSize =
1464 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1465 DestinationSize = Checker.ComputeSizeArgument(0);
1466 break;
1467 }
1468
1469 case Builtin::BIrecv:
1470 case Builtin::BIrecvfrom: {
1471 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1472 if (TheCall->getNumArgs() != ExpectedArgs ||
1473 !TheCall->getArg(1)->getType()->isPointerType() ||
1474 !TheCall->getArg(2)->getType()->isIntegerType())
1475 return;
1476 DiagID = diag::warn_fortify_source_size_mismatch;
1477 SourceSize = Checker.ComputeExplicitObjectSizeArgument(2);
1478 DestinationSize = Checker.ComputeSizeArgument(1);
1479 break;
1480 }
1481
1482 case Builtin::BIbzero:
1483 case Builtin::BI__builtin_bzero:
1484 case Builtin::BImemcpy:
1485 case Builtin::BI__builtin_memcpy:
1486 case Builtin::BImemmove:
1487 case Builtin::BI__builtin_memmove:
1488 case Builtin::BImemset:
1489 case Builtin::BI__builtin_memset:
1490 case Builtin::BImempcpy:
1491 case Builtin::BI__builtin_mempcpy: {
1492 DiagID = diag::warn_fortify_source_overflow;
1493 SourceSize =
1494 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1495 DestinationSize = Checker.ComputeSizeArgument(0);
1496
1497 // Buffer overread doesn't make sense for memset/bzero.
1498 if (BuiltinID != Builtin::BImemset &&
1499 BuiltinID != Builtin::BI__builtin_memset &&
1500 BuiltinID != Builtin::BIbzero &&
1501 BuiltinID != Builtin::BI__builtin_bzero) {
1502 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1503 }
1504 break;
1505 }
1506 case Builtin::BIbcopy:
1507 case Builtin::BI__builtin_bcopy: {
1508 DiagID = diag::warn_fortify_source_overflow;
1509 SourceSize =
1510 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1511 DestinationSize = Checker.ComputeSizeArgument(1);
1512 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1513 break;
1514 }
1515
1516 // memchr(buf, val, size)
1517 case Builtin::BImemchr:
1518 case Builtin::BI__builtin_memchr: {
1519 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1520 return;
1521 }
1522
1523 // memcmp/bcmp(buf0, buf1, size)
1524 // Two checks since each buffer is read
1525 case Builtin::BImemcmp:
1526 case Builtin::BI__builtin_memcmp:
1527 case Builtin::BIbcmp:
1528 case Builtin::BI__builtin_bcmp: {
1529 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1530 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1531 return;
1532 }
1533 case Builtin::BIsnprintf:
1534 case Builtin::BI__builtin_snprintf:
1535 case Builtin::BIvsnprintf:
1536 case Builtin::BI__builtin_vsnprintf: {
1537 DiagID = diag::warn_fortify_source_size_mismatch;
1538 SourceSize = Checker.ComputeExplicitObjectSizeArgument(1);
1539 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1540 StringRef FormatStrRef;
1541 size_t StrLen;
1542 if (SourceSize &&
1543 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1544 EstimateSizeFormatHandler H(FormatStrRef);
1545 const char *FormatBytes = FormatStrRef.data();
1547 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1548 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1549 llvm::APSInt FormatSize =
1550 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1551 .extOrTrunc(SizeTypeWidth);
1552 if (FormatSize > *SourceSize && *SourceSize != 0) {
1553 unsigned TruncationDiagID =
1554 H.isKernelCompatible() ? diag::warn_format_truncation
1555 : diag::warn_format_truncation_non_kprintf;
1556 SmallString<16> SpecifiedSizeStr;
1557 SmallString<16> FormatSizeStr;
1558 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1559 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1560 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1561 PDiag(TruncationDiagID)
1562 << Checker.getFunctionName()
1563 << SpecifiedSizeStr << FormatSizeStr);
1564 }
1565 }
1566 }
1567 DestinationSize = Checker.ComputeSizeArgument(0);
1568 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1569 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1570 IdentifierInfo *FnInfo = FD->getIdentifier();
1571 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1572 }
1573 }
1574
1575 if (!SourceSize || !DestinationSize ||
1576 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1577 return;
1578
1579 std::string FunctionName = Checker.getFunctionName();
1580
1581 SmallString<16> DestinationStr;
1582 SmallString<16> SourceStr;
1583 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1584 SourceSize->toString(SourceStr, /*Radix=*/10);
1585 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1586 PDiag(DiagID)
1587 << FunctionName << DestinationStr << SourceStr);
1588}
1589
1590void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1591 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1592 return;
1593
1594 // Recognize the libc function by builtin identity rather than by name and
1595 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1596 // builtin id is attached to any file-scope, C-linkage declaration of umask
1597 // regardless of the libc's mode_t spelling -- including a hand-written
1598 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1599 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1600 if (FD->getBuiltinID() != Builtin::BIumask)
1601 return;
1602
1603 // umask(mode_t): warn when the constant-evaluated argument has bits set
1604 // outside the file-permission mask (0777). Those bits are ignored.
1605 if (TheCall->getNumArgs() != 1)
1606 return;
1607 Expr *Arg = TheCall->getArg(0);
1608 if (!Arg->getType()->isIntegerType())
1609 return;
1610 Expr::EvalResult R;
1611 if (!Arg->EvaluateAsInt(R, getASTContext()))
1612 return;
1613 // Operate on the raw two's-complement bit pattern so that negative literals
1614 // (which convert to large unsigned mode_t values) are caught.
1615 llvm::APInt RawValue = R.Val.getInt();
1616 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1617 llvm::APInt Extra = RawValue & ~Mask;
1618 if (Extra == 0)
1619 return;
1620 SmallString<16> ExtraStr;
1621 Extra.toString(ExtraStr, /*Radix=*/8, /*Signed=*/false);
1622 Diag(TheCall->getBeginLoc(), diag::warn_fortify_umask_unused_bits)
1623 << ExtraStr;
1624}
1625
1626static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1627 Scope::ScopeFlags NeededScopeFlags,
1628 unsigned DiagID) {
1629 // Scopes aren't available during instantiation. Fortunately, builtin
1630 // functions cannot be template args so they cannot be formed through template
1631 // instantiation. Therefore checking once during the parse is sufficient.
1632 if (SemaRef.inTemplateInstantiation())
1633 return false;
1634
1635 Scope *S = SemaRef.getCurScope();
1636 while (S && !S->isSEHExceptScope())
1637 S = S->getParent();
1638 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1639 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1640 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1641 << DRE->getDecl()->getIdentifier();
1642 return true;
1643 }
1644
1645 return false;
1646}
1647
1648// In OpenCL, __builtin_alloca_* should return a pointer to address space
1649// that corresponds to the stack address space i.e private address space.
1650static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1651 QualType RT = TheCall->getType();
1652 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1653 "__builtin_alloca has invalid address space");
1654
1655 RT = RT->getPointeeType();
1657 TheCall->setType(S.Context.getPointerType(RT));
1658}
1659
1660static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1661 if (S.checkArgCountAtLeast(TheCall, 1))
1662 return true;
1663
1664 for (Expr *Arg : TheCall->arguments()) {
1665 // If argument is dependent on a template parameter, we can't resolve now.
1666 if (Arg->isTypeDependent() || Arg->isValueDependent())
1667 continue;
1668 // Reject void types.
1669 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1670 if (ArgTy->isVoidType())
1671 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1672 }
1673
1674 TheCall->setType(S.Context.getSizeType());
1675 return false;
1676}
1677
1678namespace {
1679enum PointerAuthOpKind {
1680 PAO_Strip,
1681 PAO_Sign,
1682 PAO_Auth,
1683 PAO_SignGeneric,
1684 PAO_Discriminator,
1685 PAO_BlendPointer,
1686 PAO_BlendInteger,
1687 PAO_BlendPC
1688};
1689}
1690
1692 if (getLangOpts().PointerAuthIntrinsics)
1693 return false;
1694
1695 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1696 return true;
1697}
1698
1699static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1701}
1702
1703static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1704 // Convert it to type 'int'.
1705 if (S.convertArgumentToType(Arg, S.Context.IntTy))
1706 return true;
1707
1708 // Value-dependent expressions are okay; wait for template instantiation.
1709 if (Arg->isValueDependent())
1710 return false;
1711
1712 unsigned KeyValue;
1713 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1714}
1715
1717 // Attempt to constant-evaluate the expression.
1718 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1719 if (!KeyValue) {
1720 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1721 << 0 << Arg->getSourceRange();
1722 return true;
1723 }
1724
1725 // Ask the target to validate the key parameter.
1726 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1728 {
1729 llvm::raw_svector_ostream Str(Value);
1730 Str << *KeyValue;
1731 }
1732
1733 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1734 << Value << Arg->getSourceRange();
1735 return true;
1736 }
1737
1738 Result = KeyValue->getZExtValue();
1739 return false;
1740}
1741
1744 unsigned &IntVal) {
1745 if (!Arg) {
1746 IntVal = 0;
1747 return true;
1748 }
1749
1750 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1751 if (!Result) {
1752 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1753 return false;
1754 }
1755
1756 unsigned Max;
1757 bool IsAddrDiscArg = false;
1758
1759 switch (Kind) {
1761 Max = 1;
1762 IsAddrDiscArg = true;
1763 break;
1766 break;
1767 };
1768
1770 if (IsAddrDiscArg)
1771 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1772 << Result->getExtValue();
1773 else
1774 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1775 << Result->getExtValue() << Max;
1776
1777 return false;
1778 };
1779
1780 IntVal = Result->getZExtValue();
1781 return true;
1782}
1783
1784static std::pair<const ValueDecl *, CharUnits>
1786 // Must evaluate as a pointer.
1788 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1789 return {nullptr, CharUnits()};
1790
1791 const auto *BaseDecl =
1792 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1793 if (!BaseDecl)
1794 return {nullptr, CharUnits()};
1795
1796 return {BaseDecl, Result.Val.getLValueOffset()};
1797}
1798
1799static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1800 bool RequireConstant = false) {
1801 if (Arg->hasPlaceholderType()) {
1803 if (R.isInvalid())
1804 return true;
1805 Arg = R.get();
1806 }
1807
1808 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1809 return OpKind != PAO_BlendInteger;
1810 };
1811 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1812 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1813 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1814 };
1815
1816 // Require the value to have the right range of type.
1817 QualType ExpectedTy;
1818 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1819 ExpectedTy = Arg->getType().getUnqualifiedType();
1820 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1821 ExpectedTy = S.Context.VoidPtrTy;
1822 } else if (AllowsInteger(OpKind) &&
1824 ExpectedTy = S.Context.getUIntPtrType();
1825
1826 } else {
1827 // Diagnose the failures.
1828 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1829 << unsigned(OpKind == PAO_Discriminator ? 1
1830 : OpKind == PAO_BlendPointer ? 2
1831 : OpKind == PAO_BlendInteger ? 3
1832 : OpKind == PAO_BlendPC ? 4
1833 : 0)
1834 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1835 << Arg->getType() << Arg->getSourceRange();
1836 return true;
1837 }
1838
1839 // Convert to that type. This should just be an lvalue-to-rvalue
1840 // conversion.
1841 if (S.convertArgumentToType(Arg, ExpectedTy))
1842 return true;
1843
1844 if (!RequireConstant) {
1845 // Warn about null pointers for non-generic sign and auth operations.
1846 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1848 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1849 ? diag::warn_ptrauth_sign_null_pointer
1850 : diag::warn_ptrauth_auth_null_pointer)
1851 << Arg->getSourceRange();
1852 }
1853
1854 return false;
1855 }
1856
1857 // Perform special checking on the arguments to ptrauth_sign_constant.
1858
1859 // The main argument.
1860 if (OpKind == PAO_Sign) {
1861 // Require the value we're signing to have a special form.
1862 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1863 bool Invalid;
1864
1865 // Must be rooted in a declaration reference.
1866 if (!BaseDecl)
1867 Invalid = true;
1868
1869 // If it's a function declaration, we can't have an offset.
1870 else if (isa<FunctionDecl>(BaseDecl))
1871 Invalid = !Offset.isZero();
1872
1873 // Otherwise we're fine.
1874 else
1875 Invalid = false;
1876
1877 if (Invalid)
1878 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1879 return Invalid;
1880 }
1881
1882 // The discriminator argument.
1883 assert(OpKind == PAO_Discriminator);
1884
1885 // Must be a pointer or integer or blend thereof.
1886 Expr *Pointer = nullptr;
1887 Expr *Integer = nullptr;
1888 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1889 if (Call->getBuiltinCallee() ==
1890 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1891 Pointer = Call->getArg(0);
1892 Integer = Call->getArg(1);
1893 }
1894 }
1895 if (!Pointer && !Integer) {
1896 if (Arg->getType()->isPointerType())
1897 Pointer = Arg;
1898 else
1899 Integer = Arg;
1900 }
1901
1902 // Check the pointer.
1903 bool Invalid = false;
1904 if (Pointer) {
1905 assert(Pointer->getType()->isPointerType());
1906
1907 // TODO: if we're initializing a global, check that the address is
1908 // somehow related to what we're initializing. This probably will
1909 // never really be feasible and we'll have to catch it at link-time.
1910 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1911 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1912 Invalid = true;
1913 }
1914
1915 // Check the integer.
1916 if (Integer) {
1917 assert(Integer->getType()->isIntegerType());
1918 if (!Integer->isEvaluatable(S.Context))
1919 Invalid = true;
1920 }
1921
1922 if (Invalid)
1923 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1924 return Invalid;
1925}
1926
1928 if (S.checkArgCount(Call, 2))
1929 return ExprError();
1931 return ExprError();
1932 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1933 checkPointerAuthKey(S, Call->getArgs()[1]))
1934 return ExprError();
1935
1936 Call->setType(Call->getArgs()[0]->getType());
1937 return Call;
1938}
1939
1941 if (S.checkArgCount(Call, 2))
1942 return ExprError();
1944 return ExprError();
1945 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1946 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1947 return ExprError();
1948
1949 Call->setType(S.Context.getUIntPtrType());
1950 return Call;
1951}
1952
1954 if (S.checkArgCount(Call, 2))
1955 return ExprError();
1957 return ExprError();
1958 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1959 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1960 return ExprError();
1961
1962 Call->setType(S.Context.getUIntPtrType());
1963 return Call;
1964}
1965
1967 PointerAuthOpKind OpKind,
1968 bool RequireConstant) {
1969 if (S.checkArgCount(Call, 3))
1970 return ExprError();
1972 return ExprError();
1973 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1974 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1975 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1976 RequireConstant))
1977 return ExprError();
1978
1979 Call->setType(Call->getArgs()[0]->getType());
1980 return Call;
1981}
1982
1984 if (S.checkArgCount(Call, 5))
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 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1992 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1993 return ExprError();
1994
1995 Call->setType(Call->getArgs()[0]->getType());
1996 return Call;
1997}
1998
2000 if (S.checkArgCount(Call, 6))
2001 return ExprError();
2003 return ExprError();
2004 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2005 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2006 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2007 checkPointerAuthValue(S, Call->getArgs()[3], PAO_BlendPC) ||
2008 checkPointerAuthKey(S, Call->getArgs()[4]) ||
2009 checkPointerAuthValue(S, Call->getArgs()[5], PAO_Discriminator))
2010 return ExprError();
2011
2012 // Validate that the oldKey is IA or IB, not DA or DB.
2013 // This enforces the constraint that auth_with_pc_and_resign only supports
2014 // IA/IB keys for authentication, as only those keys support the PC-based
2015 // signing instructions (paciasppc/pacibsppc).
2016 unsigned OldKey = 0;
2017 if (!S.checkConstantPointerAuthKey(Call->getArgs()[1], OldKey)) {
2019 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2020 OldKey != static_cast<unsigned>(AK::ASIB)) {
2021 S.Diag(Call->getArgs()[1]->getExprLoc(),
2022 diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2023 << OldKey << Call->getArgs()[1]->getSourceRange();
2024 return ExprError();
2025 }
2026 }
2027
2028 Call->setType(Call->getArgs()[0]->getType());
2029 return Call;
2030}
2031
2033 if (S.checkArgCount(Call, 6))
2034 return ExprError();
2036 return ExprError();
2037 const Expr *AddendExpr = Call->getArg(5);
2038 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
2039 if (!AddendIsConstInt) {
2040 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
2041 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
2042 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2043 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
2044 << FDecl->getDeclName() << Arg->getSourceRange();
2045 }
2046 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2047 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2048 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2049 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2050 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
2051 !AddendIsConstInt)
2052 return ExprError();
2053
2054 Call->setType(Call->getArgs()[0]->getType());
2055 return Call;
2056}
2057
2060 return ExprError();
2061
2062 // We've already performed normal call type-checking.
2063 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
2064
2065 // Operand must be an ordinary or UTF-8 string literal.
2066 const auto *Literal = dyn_cast<StringLiteral>(Arg);
2067 if (!Literal || Literal->getCharByteWidth() != 1) {
2068 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
2069 << (Literal ? 1 : 0) << Arg->getSourceRange();
2070 return ExprError();
2071 }
2072
2073 return Call;
2074}
2075
2077 if (S.checkArgCount(Call, 1))
2078 return ExprError();
2079 Expr *FirstArg = Call->getArg(0);
2080 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
2081 if (FirstValue.isInvalid())
2082 return ExprError();
2083 Call->setArg(0, FirstValue.get());
2084 QualType FirstArgType = FirstArg->getType();
2085 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2086 FirstArgType = S.Context.getDecayedType(FirstArgType);
2087
2088 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2089 if (!FirstArgRecord) {
2090 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2091 << /*isPolymorphic=*/0 << FirstArgType;
2092 return ExprError();
2093 }
2094 if (S.RequireCompleteType(
2095 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
2096 diag::err_get_vtable_pointer_requires_complete_type)) {
2097 return ExprError();
2098 }
2099
2100 if (!FirstArgRecord->isPolymorphic()) {
2101 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2102 << /*isPolymorphic=*/1 << FirstArgRecord;
2103 return ExprError();
2104 }
2106 Call->setType(ReturnType);
2107 return Call;
2108}
2109
2111 if (S.checkArgCount(TheCall, 1))
2112 return ExprError();
2113
2114 // Compute __builtin_launder's parameter type from the argument.
2115 // The parameter type is:
2116 // * The type of the argument if it's not an array or function type,
2117 // Otherwise,
2118 // * The decayed argument type.
2119 QualType ParamTy = [&]() {
2120 QualType ArgTy = TheCall->getArg(0)->getType();
2121 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2122 return S.Context.getPointerType(Ty->getElementType());
2123 if (ArgTy->isFunctionType()) {
2124 return S.Context.getPointerType(ArgTy);
2125 }
2126 return ArgTy;
2127 }();
2128
2129 TheCall->setType(ParamTy);
2130
2131 auto DiagSelect = [&]() -> std::optional<unsigned> {
2132 if (!ParamTy->isPointerType())
2133 return 0;
2134 if (ParamTy->isFunctionPointerType())
2135 return 1;
2136 if (ParamTy->isVoidPointerType())
2137 return 2;
2138 return std::optional<unsigned>{};
2139 }();
2140 if (DiagSelect) {
2141 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2142 << *DiagSelect << TheCall->getSourceRange();
2143 return ExprError();
2144 }
2145
2146 // We either have an incomplete class type, or we have a class template
2147 // whose instantiation has not been forced. Example:
2148 //
2149 // template <class T> struct Foo { T value; };
2150 // Foo<int> *p = nullptr;
2151 // auto *d = __builtin_launder(p);
2152 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2153 diag::err_incomplete_type))
2154 return ExprError();
2155
2156 assert(ParamTy->getPointeeType()->isObjectType() &&
2157 "Unhandled non-object pointer case");
2158
2159 InitializedEntity Entity =
2161 ExprResult Arg =
2162 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2163 if (Arg.isInvalid())
2164 return ExprError();
2165 TheCall->setArg(0, Arg.get());
2166
2167 return TheCall;
2168}
2169
2171 if (S.checkArgCount(TheCall, 1))
2172 return ExprError();
2173
2175 if (Arg.isInvalid())
2176 return ExprError();
2177 QualType ParamTy = Arg.get()->getType();
2178 TheCall->setArg(0, Arg.get());
2179 TheCall->setType(S.Context.BoolTy);
2180
2181 // Only accept pointers to objects as arguments, which should have object
2182 // pointer or void pointer types.
2183 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2184 // LWG4138: Function pointer types not allowed
2185 if (PT->getPointeeType()->isFunctionType()) {
2186 S.Diag(TheCall->getArg(0)->getExprLoc(),
2187 diag::err_builtin_is_within_lifetime_invalid_arg)
2188 << 1;
2189 return ExprError();
2190 }
2191 // Disallow VLAs too since those shouldn't be able to
2192 // be a template parameter for `std::is_within_lifetime`
2193 if (PT->getPointeeType()->isVariableArrayType()) {
2194 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2195 << 1 << "__builtin_is_within_lifetime";
2196 return ExprError();
2197 }
2198 } else {
2199 S.Diag(TheCall->getArg(0)->getExprLoc(),
2200 diag::err_builtin_is_within_lifetime_invalid_arg)
2201 << 0;
2202 return ExprError();
2203 }
2204 return TheCall;
2205}
2206
2208 if (S.checkArgCount(TheCall, 3))
2209 return ExprError();
2210
2211 QualType Dest = TheCall->getArg(0)->getType();
2212 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2213 S.Diag(TheCall->getArg(0)->getExprLoc(),
2214 diag::err_builtin_trivially_relocate_invalid_arg_type)
2215 << /*a pointer*/ 0;
2216 return ExprError();
2217 }
2218
2219 QualType T = Dest->getPointeeType();
2220 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2221 diag::err_incomplete_type))
2222 return ExprError();
2223
2224 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2225 T->isIncompleteArrayType()) {
2226 S.Diag(TheCall->getArg(0)->getExprLoc(),
2227 diag::err_builtin_trivially_relocate_invalid_arg_type)
2228 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2229 return ExprError();
2230 }
2231
2232 TheCall->setType(Dest);
2233
2234 QualType Src = TheCall->getArg(1)->getType();
2235 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2236 S.Diag(TheCall->getArg(1)->getExprLoc(),
2237 diag::err_builtin_trivially_relocate_invalid_arg_type)
2238 << /*the same*/ 3;
2239 return ExprError();
2240 }
2241
2242 Expr *SizeExpr = TheCall->getArg(2);
2243 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2244 if (Size.isInvalid())
2245 return ExprError();
2246
2247 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2248 if (Size.isInvalid())
2249 return ExprError();
2250 SizeExpr = Size.get();
2251 TheCall->setArg(2, SizeExpr);
2252
2253 return TheCall;
2254}
2255
2256// Emit an error and return true if the current object format type is in the
2257// list of unsupported types.
2259 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2260 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2261 llvm::Triple::ObjectFormatType CurObjFormat =
2262 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2263 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2264 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2265 << TheCall->getSourceRange();
2266 return true;
2267 }
2268 return false;
2269}
2270
2271// Emit an error and return true if the current architecture is not in the list
2272// of supported architectures.
2273static bool
2275 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2276 llvm::Triple::ArchType CurArch =
2277 S.getASTContext().getTargetInfo().getTriple().getArch();
2278 if (llvm::is_contained(SupportedArchs, CurArch))
2279 return false;
2280 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2281 << TheCall->getSourceRange();
2282 return true;
2283}
2284
2285static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2286 SourceLocation CallSiteLoc);
2287
2288bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2289 CallExpr *TheCall) {
2290 switch (TI.getTriple().getArch()) {
2291 default:
2292 // Some builtins don't require additional checking, so just consider these
2293 // acceptable.
2294 return false;
2295 case llvm::Triple::arm:
2296 case llvm::Triple::armeb:
2297 case llvm::Triple::thumb:
2298 case llvm::Triple::thumbeb:
2299 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2300 case llvm::Triple::aarch64:
2301 case llvm::Triple::aarch64_32:
2302 case llvm::Triple::aarch64_be:
2303 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2304 case llvm::Triple::bpfeb:
2305 case llvm::Triple::bpfel:
2306 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2307 case llvm::Triple::dxil:
2308 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2309 case llvm::Triple::hexagon:
2310 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2311 case llvm::Triple::mips:
2312 case llvm::Triple::mipsel:
2313 case llvm::Triple::mips64:
2314 case llvm::Triple::mips64el:
2315 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2316 case llvm::Triple::spirv:
2317 case llvm::Triple::spirv32:
2318 case llvm::Triple::spirv64:
2319 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2320 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2321 return false;
2322 case llvm::Triple::systemz:
2323 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2324 case llvm::Triple::x86:
2325 case llvm::Triple::x86_64:
2326 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2327 case llvm::Triple::ppc:
2328 case llvm::Triple::ppcle:
2329 case llvm::Triple::ppc64:
2330 case llvm::Triple::ppc64le:
2331 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2332 case llvm::Triple::amdgpu:
2333 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2334 case llvm::Triple::riscv32:
2335 case llvm::Triple::riscv64:
2336 case llvm::Triple::riscv32be:
2337 case llvm::Triple::riscv64be:
2338 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2339 case llvm::Triple::loongarch32:
2340 case llvm::Triple::loongarch64:
2341 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2342 TheCall);
2343 case llvm::Triple::wasm32:
2344 case llvm::Triple::wasm64:
2345 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2346 case llvm::Triple::nvptx:
2347 case llvm::Triple::nvptx64:
2348 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2349 }
2350}
2351
2353 return T->isDependentType() ||
2354 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2355}
2356
2357// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2358// not a valid type, emit an error message and return true. Otherwise return
2359// false.
2360static bool
2363 int ArgOrdinal) {
2364 clang::QualType EltTy =
2365 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2366 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2367 : ArgTy;
2368
2369 switch (ArgTyRestr) {
2371 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2372 !isValidMathElementType(ArgTy)) {
2373 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2374 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2375 << ArgTy;
2376 }
2377 break;
2379 if (!EltTy->isRealFloatingType()) {
2380 // FIXME: make diagnostic's wording correct for matrices
2381 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2382 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2383 << /* floating-point */ 1 << ArgTy;
2384 }
2385 break;
2387 if (!EltTy->isIntegerType()) {
2388 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2389 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2390 << /* no fp */ 0 << ArgTy;
2391 }
2392 break;
2394 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2395 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2396 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2397 << /* or fp */ 1 << ArgTy;
2398 }
2399 break;
2400 }
2401
2402 return false;
2403}
2404
2405/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2406/// This checks that the target supports the builtin and that the string
2407/// argument is constant and valid.
2408static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2409 const TargetInfo *AuxTI, unsigned BuiltinID) {
2410 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2411 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2412 "Expecting __builtin_cpu_...");
2413
2414 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2415 const TargetInfo *TheTI = &TI;
2416 auto SupportsBI = [=](const TargetInfo *TInfo) {
2417 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2418 (!IsCPUSupports && TInfo->supportsCpuIs()));
2419 };
2420 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2421 TheTI = AuxTI;
2422
2423 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2424 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2425 return S.Diag(TheCall->getBeginLoc(),
2426 TI.getTriple().isOSAIX()
2427 ? diag::err_builtin_aix_os_unsupported
2428 : diag::err_builtin_target_unsupported)
2429 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2430
2431 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2432 // Check if the argument is a string literal.
2433 if (!isa<StringLiteral>(Arg))
2434 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2435 << Arg->getSourceRange();
2436
2437 // Check the contents of the string.
2438 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2439 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2440 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2441 << Arg->getSourceRange();
2442 return false;
2443 }
2444 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2445 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2446 << Arg->getSourceRange();
2447 return false;
2448}
2449
2450/// Checks that __builtin_bswapg was called with a single argument, which is an
2451/// unsigned integer, and overrides the return value type to the integer type.
2452static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2453 if (S.checkArgCount(TheCall, 1))
2454 return true;
2455 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2456 if (ArgRes.isInvalid())
2457 return true;
2458
2459 Expr *Arg = ArgRes.get();
2460 TheCall->setArg(0, Arg);
2461 if (Arg->isTypeDependent())
2462 return false;
2463
2464 QualType ArgTy = Arg->getType();
2465
2466 if (!ArgTy->isIntegerType()) {
2467 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2468 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2469 << ArgTy;
2470 return true;
2471 }
2472 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2473 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2474 BT->getNumBits() != 1) {
2475 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2476 << ArgTy << BT->getNumBits();
2477 return true;
2478 }
2479 }
2480 TheCall->setType(ArgTy);
2481 return false;
2482}
2483
2484/// Checks that __builtin_bitreverseg was called with a single argument, which
2485/// is an integer
2486static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2487 if (S.checkArgCount(TheCall, 1))
2488 return true;
2489 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2490 if (ArgRes.isInvalid())
2491 return true;
2492
2493 Expr *Arg = ArgRes.get();
2494 TheCall->setArg(0, Arg);
2495 if (Arg->isTypeDependent())
2496 return false;
2497
2498 QualType ArgTy = Arg->getType();
2499
2500 if (!ArgTy->isIntegerType()) {
2501 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2502 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2503 << ArgTy;
2504 return true;
2505 }
2506 TheCall->setType(ArgTy);
2507 return false;
2508}
2509
2510/// Checks that __builtin_popcountg was called with a single argument, which is
2511/// an unsigned integer.
2512static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2513 if (S.checkArgCount(TheCall, 1))
2514 return true;
2515
2516 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2517 if (ArgRes.isInvalid())
2518 return true;
2519
2520 Expr *Arg = ArgRes.get();
2521 TheCall->setArg(0, Arg);
2522
2523 QualType ArgTy = Arg->getType();
2524
2525 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2526 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2527 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2528 << ArgTy;
2529 return true;
2530 }
2531 return false;
2532}
2533
2534/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2535/// argument and return either int, bool, or the argument type.
2536static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2537 QualType ReturnType) {
2538 if (S.checkArgCount(TheCall, 1))
2539 return true;
2540
2541 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2542 if (ArgRes.isInvalid())
2543 return true;
2544
2545 Expr *Arg = ArgRes.get();
2546 TheCall->setArg(0, Arg);
2547
2548 QualType ArgTy = Arg->getType();
2549 // C23 stdbit.h functions do not permit bool or enumeration types.
2550 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2551 return S.Diag(Arg->getBeginLoc(),
2552 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2553 << 1 /*1st argument*/ << ArgTy;
2554 if (!ArgTy->isUnsignedIntegerType())
2555 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2556 << 1 /*1st argument*/ << ArgTy;
2557
2558 // For builtins returning unsigned int, verify the argument's bit width fits.
2559 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2560 // produce a count that overflows the return type.
2561 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2562 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2563 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2564 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2565 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2566 << ArgTy;
2567 }
2568
2569 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2570 return false;
2571}
2572
2573/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2574/// an unsigned integer, and an optional second argument, which is promoted to
2575/// an 'int'.
2576static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2577 if (S.checkArgCountRange(TheCall, 1, 2))
2578 return true;
2579
2580 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2581 if (Arg0Res.isInvalid())
2582 return true;
2583
2584 Expr *Arg0 = Arg0Res.get();
2585 TheCall->setArg(0, Arg0);
2586
2587 QualType Arg0Ty = Arg0->getType();
2588
2589 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2590 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2591 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2592 << Arg0Ty;
2593 return true;
2594 }
2595
2596 if (TheCall->getNumArgs() > 1) {
2597 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2598 if (Arg1Res.isInvalid())
2599 return true;
2600
2601 Expr *Arg1 = Arg1Res.get();
2602 TheCall->setArg(1, Arg1);
2603
2604 QualType Arg1Ty = Arg1->getType();
2605
2606 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2607 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2608 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2609 return true;
2610 }
2611 }
2612
2613 return false;
2614}
2615
2617 unsigned ArgIndex;
2618 bool OnlyUnsigned;
2619
2621 QualType T) {
2622 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2623 << ArgIndex << /*scalar*/ 1
2624 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2625 << /*no fp*/ 0 << T;
2626 }
2627
2628public:
2629 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2630 : ContextualImplicitConverter(/*Suppress=*/false,
2631 /*SuppressConversion=*/true),
2632 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2633
2634 bool match(QualType T) override {
2635 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2636 }
2637
2639 QualType T) override {
2640 return emitError(S, Loc, T);
2641 }
2642
2644 QualType T) override {
2645 return emitError(S, Loc, T);
2646 }
2647
2649 QualType T,
2650 QualType ConvTy) override {
2651 return emitError(S, Loc, T);
2652 }
2653
2655 QualType ConvTy) override {
2656 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2657 }
2658
2660 QualType T) override {
2661 return emitError(S, Loc, T);
2662 }
2663
2665 QualType ConvTy) override {
2666 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2667 }
2668
2670 QualType T,
2671 QualType ConvTy) override {
2672 llvm_unreachable("conversion functions are permitted");
2673 }
2674};
2675
2676/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2677/// arguments, that the first argument is an unsigned integer type, and that
2678/// the second argument is an integer type.
2679static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2680 if (S.checkArgCount(TheCall, 2))
2681 return true;
2682
2683 // First argument (value to rotate) must be unsigned integer type.
2684 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2686 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2687 if (Arg0Res.isInvalid())
2688 return true;
2689
2690 Expr *Arg0 = Arg0Res.get();
2691 TheCall->setArg(0, Arg0);
2692
2693 QualType Arg0Ty = Arg0->getType();
2694 if (!Arg0Ty->isUnsignedIntegerType())
2695 return true;
2696
2697 // Second argument (rotation count) must be integer type.
2698 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2700 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2701 if (Arg1Res.isInvalid())
2702 return true;
2703
2704 Expr *Arg1 = Arg1Res.get();
2705 TheCall->setArg(1, Arg1);
2706
2707 QualType Arg1Ty = Arg1->getType();
2708 if (!Arg1Ty->isIntegerType())
2709 return true;
2710
2711 TheCall->setType(Arg0Ty);
2712 return false;
2713}
2714
2715static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2716 unsigned Pos, bool AllowConst,
2717 bool AllowAS) {
2718 QualType MaskTy = MaskArg->getType();
2719 if (!MaskTy->isExtVectorBoolType())
2720 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2721 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2722 << MaskTy;
2723
2724 QualType PtrTy = PtrArg->getType();
2725 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2726 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2727 << Pos << "scalar pointer";
2728
2729 QualType PointeeTy = PtrTy->getPointeeType();
2730 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2731 (!AllowConst && PointeeTy.isConstQualified()) ||
2732 (!AllowAS && PointeeTy.hasAddressSpace())) {
2735 return S.Diag(PtrArg->getExprLoc(),
2736 diag::err_typecheck_convert_incompatible)
2737 << PtrTy << Target << /*different qualifiers=*/5
2738 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2739 << PtrTy << Target;
2740 }
2741 return false;
2742}
2743
2744static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2745 bool TypeDependent = false;
2746 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2747 ExprResult Converted =
2749 if (Converted.isInvalid())
2750 return true;
2751 TheCall->setArg(Arg, Converted.get());
2752 TypeDependent |= Converted.get()->isTypeDependent();
2753 }
2754
2755 if (TypeDependent)
2756 TheCall->setType(S.Context.DependentTy);
2757 return false;
2758}
2759
2761 if (S.checkArgCountRange(TheCall, 2, 3))
2762 return ExprError();
2763
2764 if (ConvertMaskedBuiltinArgs(S, TheCall))
2765 return ExprError();
2766
2767 Expr *MaskArg = TheCall->getArg(0);
2768 Expr *PtrArg = TheCall->getArg(1);
2769 if (TheCall->isTypeDependent())
2770 return TheCall;
2771
2772 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2773 TheCall->getBuiltinCallee() ==
2774 Builtin::BI__builtin_masked_load))
2775 return ExprError();
2776
2777 QualType MaskTy = MaskArg->getType();
2778 QualType PtrTy = PtrArg->getType();
2779 QualType PointeeTy = PtrTy->getPointeeType();
2780 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2781
2783 MaskVecTy->getNumElements());
2784 if (TheCall->getNumArgs() == 3) {
2785 Expr *PassThruArg = TheCall->getArg(2);
2786 QualType PassThruTy = PassThruArg->getType();
2787 if (!S.Context.hasSameType(PassThruTy, RetTy))
2788 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2789 << /* third argument */ 3 << RetTy;
2790 }
2791
2792 TheCall->setType(RetTy);
2793 return TheCall;
2794}
2795
2797 if (S.checkArgCount(TheCall, 3))
2798 return ExprError();
2799
2800 if (ConvertMaskedBuiltinArgs(S, TheCall))
2801 return ExprError();
2802
2803 Expr *MaskArg = TheCall->getArg(0);
2804 Expr *ValArg = TheCall->getArg(1);
2805 Expr *PtrArg = TheCall->getArg(2);
2806 if (TheCall->isTypeDependent())
2807 return TheCall;
2808
2809 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2810 TheCall->getBuiltinCallee() ==
2811 Builtin::BI__builtin_masked_store))
2812 return ExprError();
2813
2814 QualType MaskTy = MaskArg->getType();
2815 QualType PtrTy = PtrArg->getType();
2816 QualType ValTy = ValArg->getType();
2817 if (!ValTy->isVectorType())
2818 return ExprError(
2819 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2820 << 2 << "vector");
2821
2822 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2823 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2824
2825 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2826 return ExprError(
2827 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2829 TheCall->getBuiltinCallee())
2830 << MaskTy << ValTy);
2831 }
2832
2833 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2834 PtrTy->getPointeeType().getUnqualifiedType()))
2835 return ExprError(S.Diag(TheCall->getBeginLoc(),
2836 diag::err_vec_builtin_incompatible_vector)
2837 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2838 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2839 TheCall->getArg(1)->getEndLoc()));
2840
2841 TheCall->setType(S.Context.VoidTy);
2842 return TheCall;
2843}
2844
2846 if (S.checkArgCountRange(TheCall, 3, 4))
2847 return ExprError();
2848
2849 if (ConvertMaskedBuiltinArgs(S, TheCall))
2850 return ExprError();
2851
2852 Expr *MaskArg = TheCall->getArg(0);
2853 Expr *IdxArg = TheCall->getArg(1);
2854 Expr *PtrArg = TheCall->getArg(2);
2855 if (TheCall->isTypeDependent())
2856 return TheCall;
2857
2858 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2859 /*AllowAS=*/true))
2860 return ExprError();
2861
2862 QualType IdxTy = IdxArg->getType();
2863 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2864 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2865 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2866 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2867 << IdxTy;
2868
2869 QualType MaskTy = MaskArg->getType();
2870 QualType PtrTy = PtrArg->getType();
2871 QualType PointeeTy = PtrTy->getPointeeType();
2872 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2873 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2874 return ExprError(
2875 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2877 TheCall->getBuiltinCallee())
2878 << MaskTy << IdxTy);
2879
2881 MaskVecTy->getNumElements());
2882 if (TheCall->getNumArgs() == 4) {
2883 Expr *PassThruArg = TheCall->getArg(3);
2884 QualType PassThruTy = PassThruArg->getType();
2885 if (!S.Context.hasSameType(PassThruTy, RetTy))
2886 return S.Diag(PassThruArg->getExprLoc(),
2887 diag::err_vec_masked_load_store_ptr)
2888 << /* fourth argument */ 4 << RetTy;
2889 }
2890
2891 TheCall->setType(RetTy);
2892 return TheCall;
2893}
2894
2896 if (S.checkArgCount(TheCall, 4))
2897 return ExprError();
2898
2899 if (ConvertMaskedBuiltinArgs(S, TheCall))
2900 return ExprError();
2901
2902 Expr *MaskArg = TheCall->getArg(0);
2903 Expr *IdxArg = TheCall->getArg(1);
2904 Expr *ValArg = TheCall->getArg(2);
2905 Expr *PtrArg = TheCall->getArg(3);
2906 if (TheCall->isTypeDependent())
2907 return TheCall;
2908
2909 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2910 /*AllowAS=*/true))
2911 return ExprError();
2912
2913 QualType IdxTy = IdxArg->getType();
2914 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2915 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2916 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2917 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2918 << IdxTy;
2919
2920 QualType ValTy = ValArg->getType();
2921 QualType MaskTy = MaskArg->getType();
2922 QualType PtrTy = PtrArg->getType();
2923
2924 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2925 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2926 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2927 return ExprError(
2928 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2930 TheCall->getBuiltinCallee())
2931 << MaskTy << IdxTy);
2932 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2933 return ExprError(
2934 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2936 TheCall->getBuiltinCallee())
2937 << MaskTy << ValTy);
2938
2939 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2940 PtrTy->getPointeeType().getUnqualifiedType()))
2941 return ExprError(S.Diag(TheCall->getBeginLoc(),
2942 diag::err_vec_builtin_incompatible_vector)
2943 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2944 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2945 TheCall->getArg(1)->getEndLoc()));
2946
2947 TheCall->setType(S.Context.VoidTy);
2948 return TheCall;
2949}
2950
2952 SourceLocation Loc = TheCall->getBeginLoc();
2953 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2954 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2955
2956 if (Args.size() == 0) {
2957 S.Diag(TheCall->getBeginLoc(),
2958 diag::err_typecheck_call_too_few_args_at_least)
2959 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2960 << /*is_non_object=*/0 << TheCall->getSourceRange();
2961 return ExprError();
2962 }
2963
2964 QualType FuncT = Args[0]->getType();
2965
2966 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2967 if (Args.size() < 2) {
2968 S.Diag(TheCall->getBeginLoc(),
2969 diag::err_typecheck_call_too_few_args_at_least)
2970 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2971 << /*is_non_object=*/0 << TheCall->getSourceRange();
2972 return ExprError();
2973 }
2974
2975 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2976 QualType ObjectT = Args[1]->getType();
2977
2978 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2979 return ExprError();
2980
2981 ExprResult ObjectArg = [&]() -> ExprResult {
2982 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2983 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2984 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2985 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2986 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2987 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2988 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2989 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2990 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2991 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2992 return Args[1];
2993 }
2994
2995 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2996 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2997 // reference_wrapper;
2998 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2999 if (RD->isInStdNamespace() &&
3000 RD->getDeclName().getAsString() == "reference_wrapper") {
3001 CXXScopeSpec SS;
3002 IdentifierInfo *GetName = &S.Context.Idents.get("get");
3003 UnqualifiedId GetID;
3004 GetID.setIdentifier(GetName, Loc);
3005
3007 S.getCurScope(), Args[1], Loc, tok::period, SS,
3008 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
3009
3010 if (MemExpr.isInvalid())
3011 return ExprError();
3012
3013 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
3014 }
3015 }
3016
3017 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3018 // class T and t1 does not satisfy the previous two items;
3019
3020 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
3021 }();
3022
3023 if (ObjectArg.isInvalid())
3024 return ExprError();
3025
3026 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
3027 tok::periodstar, ObjectArg.get(), Args[0]);
3028 if (BinOp.isInvalid())
3029 return ExprError();
3030
3031 if (MPT->isMemberDataPointer())
3032 return BinOp;
3033
3034 // Give the synthesized expression a valid source range for diagnostics.
3035 auto *MemCall = new (S.Context)
3036 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3037
3038 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
3039 Args.drop_front(2), TheCall->getRParenLoc());
3040 }
3041 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
3042 Args.drop_front(), TheCall->getRParenLoc());
3043}
3044
3045// Performs a similar job to Sema::UsualUnaryConversions, but without any
3046// implicit promotion of integral/enumeration types.
3048 // First, convert to an r-value.
3050 if (Res.isInvalid())
3051 return ExprError();
3052
3053 // Promote floating-point types.
3054 return S.UsualUnaryFPConversions(Res.get());
3055}
3056
3058 if (const auto *TyA = VecTy->getAs<VectorType>())
3059 return TyA->getElementType();
3060 if (VecTy->isSizelessVectorType())
3061 return VecTy->getSizelessVectorEltType(Context);
3062 return QualType();
3063}
3064
3066Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3067 CallExpr *TheCall) {
3068 ExprResult TheCallResult(TheCall);
3069
3070 // Find out if any arguments are required to be integer constant expressions.
3071 unsigned ICEArguments = 0;
3073 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
3075 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3076
3077 // If any arguments are required to be ICE's, check and diagnose.
3078 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3079 // Skip arguments not required to be ICE's.
3080 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3081
3082 llvm::APSInt Result;
3083 // If we don't have enough arguments, continue so we can issue better
3084 // diagnostic in checkArgCount(...)
3085 if (ArgNo < TheCall->getNumArgs() &&
3086 BuiltinConstantArg(TheCall, ArgNo, Result))
3087 return true;
3088 ICEArguments &= ~(1 << ArgNo);
3089 }
3090
3091 FPOptions FPO;
3092 switch (BuiltinID) {
3093 case Builtin::BI__builtin___get_unsafe_stack_start:
3094 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3095 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3096 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3097 << "__safestack_get_unsafe_stack_bottom";
3098 break;
3099 case Builtin::BI__builtin___get_unsafe_stack_top:
3100 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3101 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3102 << "__safestack_get_unsafe_stack_top";
3103 break;
3104 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3105 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3106 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3107 << "__safestack_get_unsafe_stack_ptr";
3108 break;
3109 case Builtin::BI__builtin_cpu_supports:
3110 case Builtin::BI__builtin_cpu_is:
3111 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
3112 Context.getAuxTargetInfo(), BuiltinID))
3113 return ExprError();
3114 break;
3115 case Builtin::BI__builtin_cpu_init:
3116 if (!Context.getTargetInfo().supportsCpuInit()) {
3117 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3118 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3119 return ExprError();
3120 }
3121 break;
3122 case Builtin::BI__builtin___CFStringMakeConstantString:
3123 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3124 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3126 *this, BuiltinID, TheCall,
3127 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3128 return ExprError();
3129 assert(TheCall->getNumArgs() == 1 &&
3130 "Wrong # arguments to builtin CFStringMakeConstantString");
3131 if (ObjC().CheckObjCString(TheCall->getArg(0)))
3132 return ExprError();
3133 break;
3134 case Builtin::BI__builtin_ms_va_start:
3135 case Builtin::BI__builtin_zos_va_start:
3136 case Builtin::BI__builtin_stdarg_start:
3137 case Builtin::BI__builtin_va_start:
3138 case Builtin::BI__builtin_c23_va_start:
3139 if (BuiltinVAStart(BuiltinID, TheCall))
3140 return ExprError();
3141 break;
3142 case Builtin::BI__va_start: {
3143 switch (Context.getTargetInfo().getTriple().getArch()) {
3144 case llvm::Triple::aarch64:
3145 case llvm::Triple::arm:
3146 case llvm::Triple::thumb:
3147 if (BuiltinVAStartARMMicrosoft(TheCall))
3148 return ExprError();
3149 break;
3150 default:
3151 if (BuiltinVAStart(BuiltinID, TheCall))
3152 return ExprError();
3153 break;
3154 }
3155 break;
3156 }
3157
3158 // The acquire, release, and no fence variants are ARM and AArch64 only.
3159 case Builtin::BI_interlockedbittestandset_acq:
3160 case Builtin::BI_interlockedbittestandset_rel:
3161 case Builtin::BI_interlockedbittestandset_nf:
3162 case Builtin::BI_interlockedbittestandreset_acq:
3163 case Builtin::BI_interlockedbittestandreset_rel:
3164 case Builtin::BI_interlockedbittestandreset_nf:
3166 *this, TheCall,
3167 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3168 return ExprError();
3169 break;
3170
3171 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3172 case Builtin::BI_bittest64:
3173 case Builtin::BI_bittestandcomplement64:
3174 case Builtin::BI_bittestandreset64:
3175 case Builtin::BI_bittestandset64:
3176 case Builtin::BI_interlockedbittestandreset64:
3177 case Builtin::BI_interlockedbittestandset64:
3179 *this, TheCall,
3180 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3181 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3182 return ExprError();
3183 break;
3184
3185 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3186 case Builtin::BI_interlockedbittestandreset64_acq:
3187 case Builtin::BI_interlockedbittestandreset64_rel:
3188 case Builtin::BI_interlockedbittestandreset64_nf:
3189 case Builtin::BI_interlockedbittestandset64_acq:
3190 case Builtin::BI_interlockedbittestandset64_rel:
3191 case Builtin::BI_interlockedbittestandset64_nf:
3192 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3193 return ExprError();
3194 break;
3195
3196 case Builtin::BI__builtin_set_flt_rounds:
3198 *this, TheCall,
3199 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3200 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3201 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3202 llvm::Triple::ppc64le}))
3203 return ExprError();
3204 break;
3205
3206 case Builtin::BI__builtin_isgreater:
3207 case Builtin::BI__builtin_isgreaterequal:
3208 case Builtin::BI__builtin_isless:
3209 case Builtin::BI__builtin_islessequal:
3210 case Builtin::BI__builtin_islessgreater:
3211 case Builtin::BI__builtin_isunordered:
3212 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3213 return ExprError();
3214 break;
3215 case Builtin::BI__builtin_fpclassify:
3216 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3217 return ExprError();
3218 break;
3219 case Builtin::BI__builtin_isfpclass:
3220 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3221 return ExprError();
3222 break;
3223 case Builtin::BI__builtin_isfinite:
3224 case Builtin::BI__builtin_isinf:
3225 case Builtin::BI__builtin_isinf_sign:
3226 case Builtin::BI__builtin_isnan:
3227 case Builtin::BI__builtin_issignaling:
3228 case Builtin::BI__builtin_isnormal:
3229 case Builtin::BI__builtin_issubnormal:
3230 case Builtin::BI__builtin_iszero:
3231 case Builtin::BI__builtin_signbit:
3232 case Builtin::BI__builtin_signbitf:
3233 case Builtin::BI__builtin_signbitl:
3234 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3235 return ExprError();
3236 break;
3237 case Builtin::BI__builtin_shufflevector:
3238 return BuiltinShuffleVector(TheCall);
3239 // TheCall will be freed by the smart pointer here, but that's fine, since
3240 // BuiltinShuffleVector guts it, but then doesn't release it.
3241 case Builtin::BI__builtin_masked_load:
3242 case Builtin::BI__builtin_masked_expand_load:
3243 return BuiltinMaskedLoad(*this, TheCall);
3244 case Builtin::BI__builtin_masked_store:
3245 case Builtin::BI__builtin_masked_compress_store:
3246 return BuiltinMaskedStore(*this, TheCall);
3247 case Builtin::BI__builtin_masked_gather:
3248 return BuiltinMaskedGather(*this, TheCall);
3249 case Builtin::BI__builtin_masked_scatter:
3250 return BuiltinMaskedScatter(*this, TheCall);
3251 case Builtin::BI__builtin_invoke:
3252 return BuiltinInvoke(*this, TheCall);
3253 case Builtin::BI__builtin_prefetch:
3254 if (BuiltinPrefetch(TheCall))
3255 return ExprError();
3256 break;
3257 case Builtin::BI__builtin_alloca_with_align:
3258 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3259 if (BuiltinAllocaWithAlign(TheCall))
3260 return ExprError();
3261 [[fallthrough]];
3262 case Builtin::BI__builtin_alloca:
3263 case Builtin::BI__builtin_alloca_uninitialized:
3264 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3265 << TheCall->getDirectCallee();
3266 if (getLangOpts().OpenCL) {
3267 builtinAllocaAddrSpace(*this, TheCall);
3268 }
3269 break;
3270 case Builtin::BI__builtin_infer_alloc_token:
3271 if (checkBuiltinInferAllocToken(*this, TheCall))
3272 return ExprError();
3273 break;
3274 case Builtin::BI__arithmetic_fence:
3275 if (BuiltinArithmeticFence(TheCall))
3276 return ExprError();
3277 break;
3278 case Builtin::BI__assume:
3279 case Builtin::BI__builtin_assume:
3280 if (BuiltinAssume(TheCall))
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_assume_aligned:
3284 if (BuiltinAssumeAligned(TheCall))
3285 return ExprError();
3286 break;
3287 case Builtin::BI__builtin_dynamic_object_size:
3288 case Builtin::BI__builtin_object_size:
3289 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3290 return ExprError();
3291 break;
3292 case Builtin::BI__builtin_longjmp:
3293 if (BuiltinLongjmp(TheCall))
3294 return ExprError();
3295 break;
3296 case Builtin::BI__builtin_setjmp:
3297 if (BuiltinSetjmp(TheCall))
3298 return ExprError();
3299 break;
3300 case Builtin::BI__builtin_complex:
3301 if (BuiltinComplex(TheCall))
3302 return ExprError();
3303 break;
3304 case Builtin::BI__builtin_classify_type:
3305 case Builtin::BI__builtin_constant_p: {
3306 if (checkArgCount(TheCall, 1))
3307 return true;
3309 if (Arg.isInvalid()) return true;
3310 TheCall->setArg(0, Arg.get());
3311 TheCall->setType(Context.IntTy);
3312 break;
3313 }
3314 case Builtin::BI__builtin_launder:
3315 return BuiltinLaunder(*this, TheCall);
3316 case Builtin::BI__builtin_is_within_lifetime:
3317 return BuiltinIsWithinLifetime(*this, TheCall);
3318 case Builtin::BI__builtin_trivially_relocate:
3319 return BuiltinTriviallyRelocate(*this, TheCall);
3320 case Builtin::BI__builtin_clear_padding: {
3321 if (checkArgCount(TheCall, 1))
3322 return ExprError();
3323
3324 const Expr *PtrArg = TheCall->getArg(0);
3325 const QualType PtrArgType = PtrArg->getType();
3326 if (!PtrArgType->isPointerType()) {
3327 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3328 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3329 << "pointer";
3330 return ExprError();
3331 }
3332 QualType PointeeType = PtrArgType->getPointeeType();
3333 if (PointeeType.isConstQualified()) {
3334 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3335 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3336 return ExprError();
3337 }
3338 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3339 diag::err_typecheck_decl_incomplete_type))
3340 return ExprError();
3341
3342 // For non trivially copyable types, we try to match gcc's behaviour.
3343 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3344 // object, either a local variable or a function parameter passed by value
3345 auto IsAddrOfDeclExpr = [&]() {
3346 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3347 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3348 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3349 return false;
3350
3351 const Expr *Operand =
3352 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3353 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3354 if (!DeclRef)
3355 return false;
3356
3357 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3358 if (!VarDecl || VarDecl->getType()->isReferenceType())
3359 return false;
3360
3361 // matching GCC behaviour
3362 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3363 QualType VarQType = VarDecl->getType();
3364 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3365 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3366 };
3367
3368 if (!PointeeType.isTriviallyCopyableType(Context) &&
3369 !PointeeType->isAtomicType() // _Atomic is not copyable
3370 && !IsAddrOfDeclExpr()) {
3371 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3372 << PtrArg->getType() << PtrArg->getSourceRange();
3373 return ExprError();
3374 }
3375
3376 if (auto *Record = PointeeType->getAsRecordDecl();
3378 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3379 << PointeeType << PtrArg->getSourceRange();
3380 return ExprError();
3381 }
3382
3383 break;
3384 }
3385 case Builtin::BI__sync_fetch_and_add:
3386 case Builtin::BI__sync_fetch_and_add_1:
3387 case Builtin::BI__sync_fetch_and_add_2:
3388 case Builtin::BI__sync_fetch_and_add_4:
3389 case Builtin::BI__sync_fetch_and_add_8:
3390 case Builtin::BI__sync_fetch_and_add_16:
3391 case Builtin::BI__sync_fetch_and_sub:
3392 case Builtin::BI__sync_fetch_and_sub_1:
3393 case Builtin::BI__sync_fetch_and_sub_2:
3394 case Builtin::BI__sync_fetch_and_sub_4:
3395 case Builtin::BI__sync_fetch_and_sub_8:
3396 case Builtin::BI__sync_fetch_and_sub_16:
3397 case Builtin::BI__sync_fetch_and_or:
3398 case Builtin::BI__sync_fetch_and_or_1:
3399 case Builtin::BI__sync_fetch_and_or_2:
3400 case Builtin::BI__sync_fetch_and_or_4:
3401 case Builtin::BI__sync_fetch_and_or_8:
3402 case Builtin::BI__sync_fetch_and_or_16:
3403 case Builtin::BI__sync_fetch_and_and:
3404 case Builtin::BI__sync_fetch_and_and_1:
3405 case Builtin::BI__sync_fetch_and_and_2:
3406 case Builtin::BI__sync_fetch_and_and_4:
3407 case Builtin::BI__sync_fetch_and_and_8:
3408 case Builtin::BI__sync_fetch_and_and_16:
3409 case Builtin::BI__sync_fetch_and_xor:
3410 case Builtin::BI__sync_fetch_and_xor_1:
3411 case Builtin::BI__sync_fetch_and_xor_2:
3412 case Builtin::BI__sync_fetch_and_xor_4:
3413 case Builtin::BI__sync_fetch_and_xor_8:
3414 case Builtin::BI__sync_fetch_and_xor_16:
3415 case Builtin::BI__sync_fetch_and_nand:
3416 case Builtin::BI__sync_fetch_and_nand_1:
3417 case Builtin::BI__sync_fetch_and_nand_2:
3418 case Builtin::BI__sync_fetch_and_nand_4:
3419 case Builtin::BI__sync_fetch_and_nand_8:
3420 case Builtin::BI__sync_fetch_and_nand_16:
3421 case Builtin::BI__sync_add_and_fetch:
3422 case Builtin::BI__sync_add_and_fetch_1:
3423 case Builtin::BI__sync_add_and_fetch_2:
3424 case Builtin::BI__sync_add_and_fetch_4:
3425 case Builtin::BI__sync_add_and_fetch_8:
3426 case Builtin::BI__sync_add_and_fetch_16:
3427 case Builtin::BI__sync_sub_and_fetch:
3428 case Builtin::BI__sync_sub_and_fetch_1:
3429 case Builtin::BI__sync_sub_and_fetch_2:
3430 case Builtin::BI__sync_sub_and_fetch_4:
3431 case Builtin::BI__sync_sub_and_fetch_8:
3432 case Builtin::BI__sync_sub_and_fetch_16:
3433 case Builtin::BI__sync_and_and_fetch:
3434 case Builtin::BI__sync_and_and_fetch_1:
3435 case Builtin::BI__sync_and_and_fetch_2:
3436 case Builtin::BI__sync_and_and_fetch_4:
3437 case Builtin::BI__sync_and_and_fetch_8:
3438 case Builtin::BI__sync_and_and_fetch_16:
3439 case Builtin::BI__sync_or_and_fetch:
3440 case Builtin::BI__sync_or_and_fetch_1:
3441 case Builtin::BI__sync_or_and_fetch_2:
3442 case Builtin::BI__sync_or_and_fetch_4:
3443 case Builtin::BI__sync_or_and_fetch_8:
3444 case Builtin::BI__sync_or_and_fetch_16:
3445 case Builtin::BI__sync_xor_and_fetch:
3446 case Builtin::BI__sync_xor_and_fetch_1:
3447 case Builtin::BI__sync_xor_and_fetch_2:
3448 case Builtin::BI__sync_xor_and_fetch_4:
3449 case Builtin::BI__sync_xor_and_fetch_8:
3450 case Builtin::BI__sync_xor_and_fetch_16:
3451 case Builtin::BI__sync_nand_and_fetch:
3452 case Builtin::BI__sync_nand_and_fetch_1:
3453 case Builtin::BI__sync_nand_and_fetch_2:
3454 case Builtin::BI__sync_nand_and_fetch_4:
3455 case Builtin::BI__sync_nand_and_fetch_8:
3456 case Builtin::BI__sync_nand_and_fetch_16:
3457 case Builtin::BI__sync_val_compare_and_swap:
3458 case Builtin::BI__sync_val_compare_and_swap_1:
3459 case Builtin::BI__sync_val_compare_and_swap_2:
3460 case Builtin::BI__sync_val_compare_and_swap_4:
3461 case Builtin::BI__sync_val_compare_and_swap_8:
3462 case Builtin::BI__sync_val_compare_and_swap_16:
3463 case Builtin::BI__sync_bool_compare_and_swap:
3464 case Builtin::BI__sync_bool_compare_and_swap_1:
3465 case Builtin::BI__sync_bool_compare_and_swap_2:
3466 case Builtin::BI__sync_bool_compare_and_swap_4:
3467 case Builtin::BI__sync_bool_compare_and_swap_8:
3468 case Builtin::BI__sync_bool_compare_and_swap_16:
3469 case Builtin::BI__sync_lock_test_and_set:
3470 case Builtin::BI__sync_lock_test_and_set_1:
3471 case Builtin::BI__sync_lock_test_and_set_2:
3472 case Builtin::BI__sync_lock_test_and_set_4:
3473 case Builtin::BI__sync_lock_test_and_set_8:
3474 case Builtin::BI__sync_lock_test_and_set_16:
3475 case Builtin::BI__sync_lock_release:
3476 case Builtin::BI__sync_lock_release_1:
3477 case Builtin::BI__sync_lock_release_2:
3478 case Builtin::BI__sync_lock_release_4:
3479 case Builtin::BI__sync_lock_release_8:
3480 case Builtin::BI__sync_lock_release_16:
3481 case Builtin::BI__sync_swap:
3482 case Builtin::BI__sync_swap_1:
3483 case Builtin::BI__sync_swap_2:
3484 case Builtin::BI__sync_swap_4:
3485 case Builtin::BI__sync_swap_8:
3486 case Builtin::BI__sync_swap_16:
3487 return BuiltinAtomicOverloaded(TheCallResult);
3488 case Builtin::BI__sync_synchronize:
3489 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3490 << TheCall->getCallee()->getSourceRange();
3491 break;
3492 case Builtin::BI__builtin_nontemporal_load:
3493 case Builtin::BI__builtin_nontemporal_store:
3494 return BuiltinNontemporalOverloaded(TheCallResult);
3495 case Builtin::BI__builtin_memcpy_inline: {
3496 clang::Expr *SizeOp = TheCall->getArg(2);
3497 // We warn about copying to or from `nullptr` pointers when `size` is
3498 // greater than 0. When `size` is value dependent we cannot evaluate its
3499 // value so we bail out.
3500 if (SizeOp->isValueDependent())
3501 break;
3502 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3503 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3504 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3505 }
3506 break;
3507 }
3508 case Builtin::BI__builtin_memset_inline: {
3509 clang::Expr *SizeOp = TheCall->getArg(2);
3510 // We warn about filling to `nullptr` pointers when `size` is greater than
3511 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3512 // out.
3513 if (SizeOp->isValueDependent())
3514 break;
3515 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3516 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3517 break;
3518 }
3519#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3520 case Builtin::BI##ID: \
3521 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3522#include "clang/Basic/Builtins.inc"
3523 case Builtin::BI__annotation: {
3524 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3525 if (!TT.isOSWindows() && !TT.isUEFI()) {
3526 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3527 << TheCall->getSourceRange();
3528 return ExprError();
3529 }
3530 if (BuiltinMSVCAnnotation(*this, TheCall))
3531 return ExprError();
3532 break;
3533 }
3534 case Builtin::BI__builtin_annotation:
3535 if (BuiltinAnnotation(*this, TheCall))
3536 return ExprError();
3537 break;
3538 case Builtin::BI__builtin_addressof:
3539 if (BuiltinAddressof(*this, TheCall))
3540 return ExprError();
3541 break;
3542 case Builtin::BI__builtin_function_start:
3543 if (BuiltinFunctionStart(*this, TheCall))
3544 return ExprError();
3545 break;
3546 case Builtin::BI__builtin_is_aligned:
3547 case Builtin::BI__builtin_align_up:
3548 case Builtin::BI__builtin_align_down:
3549 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3550 return ExprError();
3551 break;
3552 case Builtin::BI__builtin_add_overflow:
3553 case Builtin::BI__builtin_sub_overflow:
3554 case Builtin::BI__builtin_mul_overflow:
3555 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3556 return ExprError();
3557 break;
3558 case Builtin::BI__builtin_operator_new:
3559 case Builtin::BI__builtin_operator_delete: {
3560 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3561 ExprResult Res =
3562 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3563 return Res;
3564 }
3565 case Builtin::BI__builtin_dump_struct:
3566 return BuiltinDumpStruct(*this, TheCall);
3567 case Builtin::BI__builtin_expect_with_probability: {
3568 // We first want to ensure we are called with 3 arguments
3569 if (checkArgCount(TheCall, 3))
3570 return ExprError();
3571 // then check probability is constant float in range [0.0, 1.0]
3572 const Expr *ProbArg = TheCall->getArg(2);
3573 SmallVector<PartialDiagnosticAt, 8> Notes;
3574 Expr::EvalResult Eval;
3575 Eval.Diag = &Notes;
3576 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3577 !Eval.Val.isFloat()) {
3578 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3579 << ProbArg->getSourceRange();
3580 for (const PartialDiagnosticAt &PDiag : Notes)
3581 Diag(PDiag.first, PDiag.second);
3582 return ExprError();
3583 }
3584 llvm::APFloat Probability = Eval.Val.getFloat();
3585 bool LoseInfo = false;
3586 Probability.convert(llvm::APFloat::IEEEdouble(),
3587 llvm::RoundingMode::Dynamic, &LoseInfo);
3588 if (!(Probability >= llvm::APFloat(0.0) &&
3589 Probability <= llvm::APFloat(1.0))) {
3590 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3591 << ProbArg->getSourceRange();
3592 return ExprError();
3593 }
3594 break;
3595 }
3596 case Builtin::BI__builtin_preserve_access_index:
3597 if (BuiltinPreserveAI(*this, TheCall))
3598 return ExprError();
3599 break;
3600 case Builtin::BI__builtin_call_with_static_chain:
3601 if (BuiltinCallWithStaticChain(*this, TheCall))
3602 return ExprError();
3603 break;
3604 case Builtin::BI__exception_code:
3605 case Builtin::BI_exception_code:
3606 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3607 diag::err_seh___except_block))
3608 return ExprError();
3609 break;
3610 case Builtin::BI__exception_info:
3611 case Builtin::BI_exception_info:
3612 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3613 diag::err_seh___except_filter))
3614 return ExprError();
3615 break;
3616 case Builtin::BI__GetExceptionInfo:
3617 if (checkArgCount(TheCall, 1))
3618 return ExprError();
3619
3621 TheCall->getBeginLoc(),
3622 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3623 TheCall))
3624 return ExprError();
3625
3626 TheCall->setType(Context.VoidPtrTy);
3627 break;
3628 case Builtin::BIaddressof:
3629 case Builtin::BI__addressof:
3630 case Builtin::BIforward:
3631 case Builtin::BIforward_like:
3632 case Builtin::BImove:
3633 case Builtin::BImove_if_noexcept:
3634 case Builtin::BIas_const: {
3635 // These are all expected to be of the form
3636 // T &/&&/* f(U &/&&)
3637 // where T and U only differ in qualification.
3638 if (checkArgCount(TheCall, 1))
3639 return ExprError();
3640 QualType Param = FDecl->getParamDecl(0)->getType();
3641 QualType Result = FDecl->getReturnType();
3642 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3643 BuiltinID == Builtin::BI__addressof;
3644 if (!(Param->isReferenceType() &&
3645 (ReturnsPointer ? Result->isAnyPointerType()
3646 : Result->isReferenceType()) &&
3647 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3648 Result->getPointeeType()))) {
3649 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3650 << FDecl;
3651 return ExprError();
3652 }
3653 break;
3654 }
3655 case Builtin::BI__builtin_ptrauth_strip:
3656 return PointerAuthStrip(*this, TheCall);
3657 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3658 return PointerAuthBlendDiscriminator(*this, TheCall);
3659 case Builtin::BI__builtin_ptrauth_sign_constant:
3660 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3661 /*RequireConstant=*/true);
3662 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3663 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3664 /*RequireConstant=*/false);
3665 case Builtin::BI__builtin_ptrauth_auth:
3666 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3667 /*RequireConstant=*/false);
3668 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3669 return PointerAuthSignGenericData(*this, TheCall);
3670 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3671 return PointerAuthAuthAndResign(*this, TheCall);
3672 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3673 return PointerAuthAuthWithPCAndResign(*this, TheCall);
3674 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3675 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3676 case Builtin::BI__builtin_ptrauth_string_discriminator:
3677 return PointerAuthStringDiscriminator(*this, TheCall);
3678
3679 case Builtin::BI__builtin_get_vtable_pointer:
3680 return GetVTablePointer(*this, TheCall);
3681
3682 // OpenCL v2.0, s6.13.16 - Pipe functions
3683 case Builtin::BIread_pipe:
3684 case Builtin::BIwrite_pipe:
3685 // Since those two functions are declared with var args, we need a semantic
3686 // check for the argument.
3687 if (OpenCL().checkBuiltinRWPipe(TheCall))
3688 return ExprError();
3689 break;
3690 case Builtin::BIreserve_read_pipe:
3691 case Builtin::BIreserve_write_pipe:
3692 case Builtin::BIwork_group_reserve_read_pipe:
3693 case Builtin::BIwork_group_reserve_write_pipe:
3694 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3695 return ExprError();
3696 break;
3697 case Builtin::BIsub_group_reserve_read_pipe:
3698 case Builtin::BIsub_group_reserve_write_pipe:
3699 if (OpenCL().checkSubgroupExt(TheCall) ||
3700 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3701 return ExprError();
3702 break;
3703 case Builtin::BIcommit_read_pipe:
3704 case Builtin::BIcommit_write_pipe:
3705 case Builtin::BIwork_group_commit_read_pipe:
3706 case Builtin::BIwork_group_commit_write_pipe:
3707 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3708 return ExprError();
3709 break;
3710 case Builtin::BIsub_group_commit_read_pipe:
3711 case Builtin::BIsub_group_commit_write_pipe:
3712 if (OpenCL().checkSubgroupExt(TheCall) ||
3713 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3714 return ExprError();
3715 break;
3716 case Builtin::BIget_pipe_num_packets:
3717 case Builtin::BIget_pipe_max_packets:
3718 if (OpenCL().checkBuiltinPipePackets(TheCall))
3719 return ExprError();
3720 break;
3721 case Builtin::BIto_global:
3722 case Builtin::BIto_local:
3723 case Builtin::BIto_private:
3724 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3725 return ExprError();
3726 break;
3727 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3728 case Builtin::BIenqueue_kernel:
3729 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3730 return ExprError();
3731 break;
3732 case Builtin::BIget_kernel_work_group_size:
3733 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3734 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3735 return ExprError();
3736 break;
3737 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3738 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3739 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3740 return ExprError();
3741 break;
3742 case Builtin::BI__builtin_os_log_format:
3743 Cleanup.setExprNeedsCleanups(true);
3744 [[fallthrough]];
3745 case Builtin::BI__builtin_os_log_format_buffer_size:
3746 if (BuiltinOSLogFormat(TheCall))
3747 return ExprError();
3748 break;
3749 case Builtin::BI__builtin_frame_address:
3750 case Builtin::BI__builtin_return_address: {
3751 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3752 return ExprError();
3753
3754 // -Wframe-address warning if non-zero passed to builtin
3755 // return/frame address.
3756 Expr::EvalResult Result;
3757 if (!TheCall->getArg(0)->isValueDependent() &&
3758 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3759 Result.Val.getInt() != 0)
3760 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3761 << ((BuiltinID == Builtin::BI__builtin_return_address)
3762 ? "__builtin_return_address"
3763 : "__builtin_frame_address")
3764 << TheCall->getSourceRange();
3765 break;
3766 }
3767
3768 case Builtin::BI__builtin_nondeterministic_value: {
3769 if (BuiltinNonDeterministicValue(TheCall))
3770 return ExprError();
3771 break;
3772 }
3773
3774 // __builtin_elementwise_abs restricts the element type to signed integers or
3775 // floating point types only.
3776 case Builtin::BI__builtin_elementwise_abs:
3779 return ExprError();
3780 break;
3781
3782 // These builtins restrict the element type to floating point
3783 // types only.
3784 case Builtin::BI__builtin_elementwise_acos:
3785 case Builtin::BI__builtin_elementwise_asin:
3786 case Builtin::BI__builtin_elementwise_atan:
3787 case Builtin::BI__builtin_elementwise_ceil:
3788 case Builtin::BI__builtin_elementwise_cos:
3789 case Builtin::BI__builtin_elementwise_cosh:
3790 case Builtin::BI__builtin_elementwise_exp:
3791 case Builtin::BI__builtin_elementwise_exp2:
3792 case Builtin::BI__builtin_elementwise_exp10:
3793 case Builtin::BI__builtin_elementwise_floor:
3794 case Builtin::BI__builtin_elementwise_log:
3795 case Builtin::BI__builtin_elementwise_log2:
3796 case Builtin::BI__builtin_elementwise_log10:
3797 case Builtin::BI__builtin_elementwise_roundeven:
3798 case Builtin::BI__builtin_elementwise_round:
3799 case Builtin::BI__builtin_elementwise_rint:
3800 case Builtin::BI__builtin_elementwise_nearbyint:
3801 case Builtin::BI__builtin_elementwise_sin:
3802 case Builtin::BI__builtin_elementwise_sinh:
3803 case Builtin::BI__builtin_elementwise_sqrt:
3804 case Builtin::BI__builtin_elementwise_tan:
3805 case Builtin::BI__builtin_elementwise_tanh:
3806 case Builtin::BI__builtin_elementwise_trunc:
3807 case Builtin::BI__builtin_elementwise_canonicalize:
3810 return ExprError();
3811 break;
3812 case Builtin::BI__builtin_elementwise_fma:
3813 if (BuiltinElementwiseTernaryMath(TheCall))
3814 return ExprError();
3815 break;
3816
3817 case Builtin::BI__builtin_elementwise_ldexp: {
3818 if (checkArgCount(TheCall, 2))
3819 return ExprError();
3820
3821 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3822 if (A.isInvalid())
3823 return ExprError();
3824 QualType TyA = A.get()->getType();
3825 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3827 return ExprError();
3828
3829 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3830 if (Exp.isInvalid())
3831 return ExprError();
3832 QualType TyExp = Exp.get()->getType();
3833 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3835 2))
3836 return ExprError();
3837
3838 // Check the two arguments are either scalars or vectors of equal length.
3839 const auto *Vec0 = TyA->getAs<VectorType>();
3840 const auto *Vec1 = TyExp->getAs<VectorType>();
3841 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3842 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3843 if (Arg0Length != Arg1Length) {
3844 Diag(Exp.get()->getBeginLoc(),
3845 diag::err_typecheck_vector_lengths_not_equal)
3846 << TyA << TyExp << A.get()->getSourceRange()
3847 << Exp.get()->getSourceRange();
3848 return ExprError();
3849 }
3850
3851 TheCall->setArg(0, A.get());
3852 TheCall->setArg(1, Exp.get());
3853 TheCall->setType(TyA);
3854 break;
3855 }
3856
3857 // These builtins restrict the element type to floating point
3858 // types only, and take in two arguments.
3859 case Builtin::BI__builtin_elementwise_minnum:
3860 case Builtin::BI__builtin_elementwise_maxnum:
3861 case Builtin::BI__builtin_elementwise_minimum:
3862 case Builtin::BI__builtin_elementwise_maximum:
3863 case Builtin::BI__builtin_elementwise_minimumnum:
3864 case Builtin::BI__builtin_elementwise_maximumnum:
3865 case Builtin::BI__builtin_elementwise_atan2:
3866 case Builtin::BI__builtin_elementwise_fmod:
3867 case Builtin::BI__builtin_elementwise_pow:
3868 if (BuiltinElementwiseMath(TheCall,
3870 return ExprError();
3871 break;
3872 // These builtins restrict the element type to integer
3873 // types only.
3874 case Builtin::BI__builtin_elementwise_add_sat:
3875 case Builtin::BI__builtin_elementwise_sub_sat:
3876 case Builtin::BI__builtin_elementwise_clmul:
3877 case Builtin::BI__builtin_elementwise_pext:
3878 case Builtin::BI__builtin_elementwise_pdep:
3879 if (BuiltinElementwiseMath(TheCall,
3881 return ExprError();
3882 break;
3883 case Builtin::BI__builtin_elementwise_fshl:
3884 case Builtin::BI__builtin_elementwise_fshr:
3887 return ExprError();
3888 break;
3889 case Builtin::BI__builtin_elementwise_min:
3890 case Builtin::BI__builtin_elementwise_max: {
3891 if (BuiltinElementwiseMath(TheCall))
3892 return ExprError();
3893 Expr *Arg0 = TheCall->getArg(0);
3894 Expr *Arg1 = TheCall->getArg(1);
3895 QualType Ty0 = Arg0->getType();
3896 QualType Ty1 = Arg1->getType();
3897 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3898 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3899 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3900 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3901 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3902 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3903 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3904 break;
3905 }
3906 case Builtin::BI__builtin_elementwise_popcount:
3907 case Builtin::BI__builtin_elementwise_bitreverse:
3910 return ExprError();
3911 break;
3912 case Builtin::BI__builtin_elementwise_copysign: {
3913 if (checkArgCount(TheCall, 2))
3914 return ExprError();
3915
3916 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3917 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3918 if (Magnitude.isInvalid() || Sign.isInvalid())
3919 return ExprError();
3920
3921 QualType MagnitudeTy = Magnitude.get()->getType();
3922 QualType SignTy = Sign.get()->getType();
3924 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3927 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3929 return ExprError();
3930 }
3931
3932 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3933 return Diag(Sign.get()->getBeginLoc(),
3934 diag::err_typecheck_call_different_arg_types)
3935 << MagnitudeTy << SignTy;
3936 }
3937
3938 TheCall->setArg(0, Magnitude.get());
3939 TheCall->setArg(1, Sign.get());
3940 TheCall->setType(Magnitude.get()->getType());
3941 break;
3942 }
3943 case Builtin::BI__builtin_elementwise_clzg:
3944 case Builtin::BI__builtin_elementwise_ctzg:
3945 // These builtins can be unary or binary. Note for empty calls we call the
3946 // unary checker in order to not emit an error that says the function
3947 // expects 2 arguments, which would be misleading.
3948 if (TheCall->getNumArgs() <= 1) {
3951 return ExprError();
3952 } else if (BuiltinElementwiseMath(
3954 return ExprError();
3955 break;
3956 case Builtin::BI__builtin_reduce_max:
3957 case Builtin::BI__builtin_reduce_min: {
3958 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3959 return ExprError();
3960
3961 const Expr *Arg = TheCall->getArg(0);
3962 const auto *TyA = Arg->getType()->getAs<VectorType>();
3963
3964 QualType ElTy;
3965 if (TyA)
3966 ElTy = TyA->getElementType();
3967 else if (Arg->getType()->isSizelessVectorType())
3969
3970 if (ElTy.isNull()) {
3971 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3972 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3973 << Arg->getType();
3974 return ExprError();
3975 }
3976
3977 TheCall->setType(ElTy);
3978 break;
3979 }
3980 case Builtin::BI__builtin_reduce_maximum:
3981 case Builtin::BI__builtin_reduce_minimum: {
3982 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3983 return ExprError();
3984
3985 const Expr *Arg = TheCall->getArg(0);
3986 const auto *TyA = Arg->getType()->getAs<VectorType>();
3987
3988 QualType ElTy;
3989 if (TyA)
3990 ElTy = TyA->getElementType();
3991 else if (Arg->getType()->isSizelessVectorType())
3993
3994 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3995 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3996 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3997 << Arg->getType();
3998 return ExprError();
3999 }
4000
4001 TheCall->setType(ElTy);
4002 break;
4003 }
4004
4005 // These builtins support vectors of integers only.
4006 // TODO: ADD/MUL should support floating-point types.
4007 case Builtin::BI__builtin_reduce_add:
4008 case Builtin::BI__builtin_reduce_mul:
4009 case Builtin::BI__builtin_reduce_xor:
4010 case Builtin::BI__builtin_reduce_or:
4011 case Builtin::BI__builtin_reduce_and: {
4012 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4013 return ExprError();
4014
4015 const Expr *Arg = TheCall->getArg(0);
4016
4017 QualType ElTy = getVectorElementType(Context, Arg->getType());
4018 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4019 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4020 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4021 << Arg->getType();
4022 return ExprError();
4023 }
4024
4025 TheCall->setType(ElTy);
4026 break;
4027 }
4028
4029 case Builtin::BI__builtin_reduce_assoc_fadd:
4030 case Builtin::BI__builtin_reduce_in_order_fadd: {
4031 // For in-order reductions require the user to specify the start value.
4032 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4033 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
4034 return ExprError();
4035
4036 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
4037 if (Vec.isInvalid())
4038 return ExprError();
4039
4040 TheCall->setArg(0, Vec.get());
4041
4042 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
4043 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4044 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4045 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4046 << Vec.get()->getType();
4047 return ExprError();
4048 }
4049
4050 if (TheCall->getNumArgs() == 2) {
4051 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
4052 if (StartValue.isInvalid())
4053 return ExprError();
4054
4055 if (!StartValue.get()->getType()->isRealFloatingType()) {
4056 Diag(StartValue.get()->getBeginLoc(),
4057 diag::err_builtin_invalid_arg_type)
4058 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4059 << StartValue.get()->getType();
4060 return ExprError();
4061 }
4062 TheCall->setArg(1, StartValue.get());
4063 }
4064
4065 TheCall->setType(ElTy);
4066 break;
4067 }
4068
4069 case Builtin::BI__builtin_matrix_transpose:
4070 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4071
4072 case Builtin::BI__builtin_matrix_column_major_load:
4073 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4074
4075 case Builtin::BI__builtin_matrix_column_major_store:
4076 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4077
4078 case Builtin::BI__builtin_verbose_trap:
4079 if (!checkBuiltinVerboseTrap(TheCall, *this))
4080 return ExprError();
4081 break;
4082
4083 case Builtin::BI__builtin_get_device_side_mangled_name: {
4084 auto Check = [](CallExpr *TheCall) {
4085 if (TheCall->getNumArgs() != 1)
4086 return false;
4087 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
4088 if (!DRE)
4089 return false;
4090 auto *D = DRE->getDecl();
4091 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
4092 return false;
4093 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4094 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4095 };
4096 if (!Check(TheCall)) {
4097 Diag(TheCall->getBeginLoc(),
4098 diag::err_hip_invalid_args_builtin_mangled_name);
4099 return ExprError();
4100 }
4101 break;
4102 }
4103 case Builtin::BI__builtin_bswapg:
4104 if (BuiltinBswapg(*this, TheCall))
4105 return ExprError();
4106 break;
4107 case Builtin::BI__builtin_bitreverseg:
4108 if (BuiltinBitreverseg(*this, TheCall))
4109 return ExprError();
4110 break;
4111 case Builtin::BI__builtin_popcountg:
4112 if (BuiltinPopcountg(*this, TheCall))
4113 return ExprError();
4114 break;
4115 case Builtin::BI__builtin_clzg:
4116 case Builtin::BI__builtin_ctzg:
4117 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
4118 return ExprError();
4119 break;
4120
4121 case Builtin::BI__builtin_stdc_rotate_left:
4122 case Builtin::BI__builtin_stdc_rotate_right:
4123 if (BuiltinRotateGeneric(*this, TheCall))
4124 return ExprError();
4125 break;
4126
4127 case Builtin::BI__builtin_stdc_memreverse8:
4128 case Builtin::BIstdc_memreverse8:
4129 case Builtin::BIstdc_memreverse8u8:
4130 case Builtin::BIstdc_memreverse8u16:
4131 case Builtin::BIstdc_memreverse8u32:
4132 case Builtin::BIstdc_memreverse8u64:
4133 if (Context.getTargetInfo().getCharWidth() != 8) {
4134 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
4135 << TheCall->getDirectCallee()->getName();
4136 return ExprError();
4137 }
4138 break;
4139
4140 case Builtin::BI__builtin_stdc_bit_floor:
4141 case Builtin::BI__builtin_stdc_bit_ceil:
4142 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4143 return ExprError();
4144 break;
4145 case Builtin::BI__builtin_stdc_has_single_bit:
4146 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4147 return ExprError();
4148 break;
4149 case Builtin::BI__builtin_stdc_leading_zeros:
4150 case Builtin::BI__builtin_stdc_leading_ones:
4151 case Builtin::BI__builtin_stdc_trailing_zeros:
4152 case Builtin::BI__builtin_stdc_trailing_ones:
4153 case Builtin::BI__builtin_stdc_first_leading_zero:
4154 case Builtin::BI__builtin_stdc_first_leading_one:
4155 case Builtin::BI__builtin_stdc_first_trailing_zero:
4156 case Builtin::BI__builtin_stdc_first_trailing_one:
4157 case Builtin::BI__builtin_stdc_count_zeros:
4158 case Builtin::BI__builtin_stdc_count_ones:
4159 case Builtin::BI__builtin_stdc_bit_width:
4160 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4161 return ExprError();
4162 break;
4163
4164 case Builtin::BI__builtin_allow_runtime_check: {
4165 Expr *Arg = TheCall->getArg(0);
4166 // Check if the argument is a string literal.
4168 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4169 << Arg->getSourceRange();
4170 return ExprError();
4171 }
4172 break;
4173 }
4174
4175 case Builtin::BI__builtin_allow_sanitize_check: {
4176 if (checkArgCount(TheCall, 1))
4177 return ExprError();
4178
4179 Expr *Arg = TheCall->getArg(0);
4180 // Check if the argument is a string literal.
4181 const StringLiteral *SanitizerName =
4182 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4183 if (!SanitizerName) {
4184 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4185 << Arg->getSourceRange();
4186 return ExprError();
4187 }
4188 // Validate the sanitizer name.
4189 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4190 .Cases({"address", "thread", "memory", "hwaddress",
4191 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4192 true)
4193 .Default(false)) {
4194 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4195 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4196 << Arg->getSourceRange();
4197 return ExprError();
4198 }
4199 break;
4200 }
4201 case Builtin::BI__builtin_counted_by_ref:
4202 if (BuiltinCountedByRef(TheCall))
4203 return ExprError();
4204 break;
4205 }
4206
4207 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4208 return ExprError();
4209
4210 // Since the target specific builtins for each arch overlap, only check those
4211 // of the arch we are compiling for.
4212 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4213 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4214 assert(Context.getAuxTargetInfo() &&
4215 "Aux Target Builtin, but not an aux target?");
4216
4217 if (CheckTSBuiltinFunctionCall(
4218 *Context.getAuxTargetInfo(),
4219 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4220 return ExprError();
4221 } else {
4222 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4223 TheCall))
4224 return ExprError();
4225 }
4226 }
4227
4228 return TheCallResult;
4229}
4230
4231bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4232 llvm::APSInt Result;
4233 // We can't check the value of a dependent argument.
4234 Expr *Arg = TheCall->getArg(ArgNum);
4235 if (Arg->isTypeDependent() || Arg->isValueDependent())
4236 return false;
4237
4238 // Check constant-ness first.
4239 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4240 return true;
4241
4242 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4243 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4244 return false;
4245
4246 return Diag(TheCall->getBeginLoc(),
4247 diag::err_argument_not_contiguous_bit_field)
4248 << ArgNum << Arg->getSourceRange();
4249}
4250
4251bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4252 unsigned FirstArg, FormatStringInfo *FSI) {
4253 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4254 bool IsVariadic = false;
4255 if (const FunctionType *FnTy = D->getFunctionType())
4256 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4257 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4258 IsVariadic = BD->isVariadic();
4259 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4260 IsVariadic = OMD->isVariadic();
4261
4262 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4263 IsVariadic, FSI);
4264}
4265
4266bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4267 bool HasImplicitThisParam, bool IsVariadic,
4268 FormatStringInfo *FSI) {
4269 if (FirstArg == 0)
4271 else if (IsVariadic)
4273 else
4275 FSI->FormatIdx = FormatIdx - 1;
4276 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4277
4278 // The way the format attribute works in GCC, the implicit this argument
4279 // of member functions is counted. However, it doesn't appear in our own
4280 // lists, so decrement format_idx in that case.
4281 if (HasImplicitThisParam) {
4282 if(FSI->FormatIdx == 0)
4283 return false;
4284 --FSI->FormatIdx;
4285 if (FSI->FirstDataArg != 0)
4286 --FSI->FirstDataArg;
4287 }
4288 return true;
4289}
4290
4291/// Checks if a the given expression evaluates to null.
4292///
4293/// Returns true if the value evaluates to null.
4294static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4295 // Treat (smart) pointers constructed from nullptr as null, whether we can
4296 // const-evaluate them or not.
4297 // This must happen first: the smart pointer expr might have _Nonnull type!
4301 return true;
4302
4303 // If the expression has non-null type, it doesn't evaluate to null.
4304 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4305 if (*nullability == NullabilityKind::NonNull)
4306 return false;
4307 }
4308
4309 // As a special case, transparent unions initialized with zero are
4310 // considered null for the purposes of the nonnull attribute.
4311 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4312 UT &&
4313 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4314 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4315 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4316 Expr = ILE->getInit(0);
4317 }
4318
4319 bool Result;
4320 return (!Expr->isValueDependent() &&
4322 !Result);
4323}
4324
4326 const Expr *ArgExpr,
4327 SourceLocation CallSiteLoc) {
4328 if (CheckNonNullExpr(S, ArgExpr))
4329 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4330 S.PDiag(diag::warn_null_arg)
4331 << ArgExpr->getSourceRange());
4332}
4333
4334/// Determine whether the given type has a non-null nullability annotation.
4336 if (auto nullability = type->getNullability())
4337 return *nullability == NullabilityKind::NonNull;
4338
4339 return false;
4340}
4341
4343 const NamedDecl *FDecl,
4344 const FunctionProtoType *Proto,
4346 SourceLocation CallSiteLoc) {
4347 assert((FDecl || Proto) && "Need a function declaration or prototype");
4348
4349 // Already checked by constant evaluator.
4351 return;
4352 // Check the attributes attached to the method/function itself.
4353 llvm::SmallBitVector NonNullArgs;
4354 if (FDecl) {
4355 // Handle the nonnull attribute on the function/method declaration itself.
4356 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4357 if (!NonNull->args_size()) {
4358 // Easy case: all pointer arguments are nonnull.
4359 for (const auto *Arg : Args)
4360 if (S.isValidPointerAttrType(Arg->getType()))
4361 CheckNonNullArgument(S, Arg, CallSiteLoc);
4362 return;
4363 }
4364
4365 for (const ParamIdx &Idx : NonNull->args()) {
4366 unsigned IdxAST = Idx.getASTIndex();
4367 if (IdxAST >= Args.size())
4368 continue;
4369 if (NonNullArgs.empty())
4370 NonNullArgs.resize(Args.size());
4371 NonNullArgs.set(IdxAST);
4372 }
4373 }
4374 }
4375
4376 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4377 // Handle the nonnull attribute on the parameters of the
4378 // function/method.
4380 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4381 parms = FD->parameters();
4382 else
4383 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4384
4385 unsigned ParamIndex = 0;
4386 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4387 I != E; ++I, ++ParamIndex) {
4388 const ParmVarDecl *PVD = *I;
4389 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4390 if (NonNullArgs.empty())
4391 NonNullArgs.resize(Args.size());
4392
4393 NonNullArgs.set(ParamIndex);
4394 }
4395 }
4396 } else {
4397 // If we have a non-function, non-method declaration but no
4398 // function prototype, try to dig out the function prototype.
4399 if (!Proto) {
4400 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4401 QualType type = VD->getType().getNonReferenceType();
4402 if (auto pointerType = type->getAs<PointerType>())
4403 type = pointerType->getPointeeType();
4404 else if (auto blockType = type->getAs<BlockPointerType>())
4405 type = blockType->getPointeeType();
4406 // FIXME: data member pointers?
4407
4408 // Dig out the function prototype, if there is one.
4409 Proto = type->getAs<FunctionProtoType>();
4410 }
4411 }
4412
4413 // Fill in non-null argument information from the nullability
4414 // information on the parameter types (if we have them).
4415 if (Proto) {
4416 unsigned Index = 0;
4417 for (auto paramType : Proto->getParamTypes()) {
4418 if (isNonNullType(paramType)) {
4419 if (NonNullArgs.empty())
4420 NonNullArgs.resize(Args.size());
4421
4422 NonNullArgs.set(Index);
4423 }
4424
4425 ++Index;
4426 }
4427 }
4428 }
4429
4430 // Check for non-null arguments.
4431 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4432 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4433 if (NonNullArgs[ArgIndex])
4434 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4435 }
4436}
4437
4438void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4439 StringRef ParamName, QualType ArgTy,
4440 QualType ParamTy) {
4441
4442 // If a function accepts a pointer or reference type
4443 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4444 return;
4445
4446 // If the parameter is a pointer type, get the pointee type for the
4447 // argument too. If the parameter is a reference type, don't try to get
4448 // the pointee type for the argument.
4449 if (ParamTy->isPointerType())
4450 ArgTy = ArgTy->getPointeeType();
4451
4452 // Remove reference or pointer
4453 ParamTy = ParamTy->getPointeeType();
4454
4455 // Find expected alignment, and the actual alignment of the passed object.
4456 // getTypeAlignInChars requires complete types
4457 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4458 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4459 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4460 return;
4461
4462 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4463 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4464
4465 // If the argument is less aligned than the parameter, there is a
4466 // potential alignment issue.
4467 if (ArgAlign < ParamAlign)
4468 Diag(Loc, diag::warn_param_mismatched_alignment)
4469 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4470 << ParamName << (FDecl != nullptr) << FDecl;
4471}
4472
4473void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4474 const Expr *ThisArg,
4476 if (!FD || Args.empty())
4477 return;
4478 auto GetArgAt = [&](int Idx) -> const Expr * {
4479 if (Idx == LifetimeCaptureByAttr::Global ||
4480 Idx == LifetimeCaptureByAttr::Unknown)
4481 return nullptr;
4482 if (IsMemberFunction && Idx == 0)
4483 return ThisArg;
4484 return Args[Idx - IsMemberFunction];
4485 };
4486 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4487 unsigned ArgIdx) {
4488 if (!Attr)
4489 return;
4490
4491 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4492 for (int CapturingParamIdx : Attr->params()) {
4493 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4494 continue;
4495 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4496 // initialization codepath.
4497 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4499 continue;
4500 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4501 CapturingEntity CE{Capturing};
4502 // Ensure that 'Captured' outlives the 'Capturing' entity.
4503 checkCaptureByLifetime(*this, CE, Captured);
4504 }
4505 };
4506 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4507 for (const auto *A :
4508 FD->getParamDecl(I)->specific_attrs<LifetimeCaptureByAttr>())
4509 HandleCaptureByAttr(A, I + IsMemberFunction);
4510 // Check when the implicit object param is captured.
4511 if (IsMemberFunction) {
4512 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4513 if (!TSI)
4514 return;
4516 for (TypeLoc TL = TSI->getTypeLoc();
4517 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4518 TL = ATL.getModifiedLoc())
4519 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4520 }
4521}
4522
4524 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4525 bool IsMemberFunction, SourceLocation Loc,
4526 SourceRange Range, VariadicCallType CallType) {
4527
4528 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4529 llvm::any_of(Args, [](const Expr *E) {
4530 return E && E->isInstantiationDependent();
4531 }))
4532 return;
4533
4534 // Printf and scanf checking.
4535 llvm::SmallBitVector CheckedVarArgs;
4536 if (FDecl) {
4537 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4538 // Only create vector if there are format attributes.
4539 CheckedVarArgs.resize(Args.size());
4540 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4541 CheckedVarArgs);
4542 }
4543
4544 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4545 CheckedVarArgs.resize(Args.size());
4546 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4547 CheckedVarArgs);
4548 }
4549 }
4550
4551 // Refuse POD arguments that weren't caught by the format string
4552 // checks above.
4553 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4554 if (CallType != VariadicCallType::DoesNotApply &&
4555 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4556 unsigned NumParams = Proto ? Proto->getNumParams()
4557 : isa_and_nonnull<FunctionDecl>(FDecl)
4558 ? cast<FunctionDecl>(FDecl)->getNumParams()
4559 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4560 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4561 : 0;
4562
4563 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4564 // Args[ArgIdx] can be null in malformed code.
4565 if (const Expr *Arg = Args[ArgIdx]) {
4566 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4567 checkVariadicArgument(Arg, CallType);
4568 }
4569 }
4570 }
4571 if (FD)
4572 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4573 if (FDecl || Proto) {
4574 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4575
4576 // Type safety checking.
4577 if (FDecl) {
4578 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4579 CheckArgumentWithTypeTag(I, Args, Loc);
4580 }
4581 }
4582
4583 // Check that passed arguments match the alignment of original arguments.
4584 // Try to get the missing prototype from the declaration.
4585 if (!Proto && FDecl) {
4586 const auto *FT = FDecl->getFunctionType();
4587 if (isa_and_nonnull<FunctionProtoType>(FT))
4588 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4589 }
4590 if (Proto) {
4591 // For variadic functions, we may have more args than parameters.
4592 // For some K&R functions, we may have less args than parameters.
4593 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4594 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4595 bool IsScalableArg = false;
4596 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4597 // Args[ArgIdx] can be null in malformed code.
4598 if (const Expr *Arg = Args[ArgIdx]) {
4599 if (Arg->containsErrors())
4600 continue;
4601
4602 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4603 FDecl->hasLinkage() &&
4604 FDecl->getFormalLinkage() != Linkage::Internal &&
4606 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4607
4608 QualType ParamTy = Proto->getParamType(ArgIdx);
4609 if (ParamTy->isSizelessVectorType())
4610 IsScalableArg = true;
4611 QualType ArgTy = Arg->getType();
4612 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4613 ArgTy, ParamTy);
4614 }
4615 }
4616
4617 // If the callee has an AArch64 SME attribute to indicate that it is an
4618 // __arm_streaming function, then the caller requires SME to be available.
4621 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4622 llvm::StringMap<bool> CallerFeatureMap;
4623 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4624 if (!CallerFeatureMap.contains("sme"))
4625 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4626 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4627 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4628 }
4629 }
4630
4631 // If the call requires a streaming-mode change and has scalable vector
4632 // arguments or return values, then warn the user that the streaming and
4633 // non-streaming vector lengths may be different.
4634 // When both streaming and non-streaming vector lengths are defined and
4635 // mismatched, produce an error.
4636 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4637 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4638 (IsScalableArg || IsScalableRet)) {
4639 bool IsCalleeStreaming =
4641 bool IsCalleeStreamingCompatible =
4642 ExtInfo.AArch64SMEAttributes &
4644 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4645 if (!IsCalleeStreamingCompatible &&
4646 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4647 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4648 const LangOptions &LO = getLangOpts();
4649 unsigned VL = LO.VScaleMin * 128;
4650 unsigned SVL = LO.VScaleStreamingMin * 128;
4651 bool IsVLMismatch = VL && SVL && VL != SVL;
4652
4653 auto EmitDiag = [&](bool IsArg) {
4654 if (IsVLMismatch) {
4655 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4656 // Emit warning for streaming-compatible callers
4657 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4658 << IsArg << IsCalleeStreaming << SVL << VL;
4659 else
4660 // Emit error otherwise
4661 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4662 << IsArg << SVL << VL;
4663 } else
4664 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4665 << IsArg;
4666 };
4667
4668 if (IsScalableArg)
4669 EmitDiag(true);
4670 if (IsScalableRet)
4671 EmitDiag(false);
4672 }
4673 }
4674
4675 FunctionType::ArmStateValue CalleeArmZAState =
4677 FunctionType::ArmStateValue CalleeArmZT0State =
4679 if (CalleeArmZAState != FunctionType::ARM_None ||
4680 CalleeArmZT0State != FunctionType::ARM_None) {
4681 bool CallerHasZAState = false;
4682 bool CallerHasZT0State = false;
4683 if (CallerFD) {
4684 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4685 if (Attr && Attr->isNewZA())
4686 CallerHasZAState = true;
4687 if (Attr && Attr->isNewZT0())
4688 CallerHasZT0State = true;
4689 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4690 CallerHasZAState |=
4692 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4694 CallerHasZT0State |=
4696 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4698 }
4699 }
4700
4701 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4702 Diag(Loc, diag::err_sme_za_call_no_za_state);
4703
4704 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4705 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4706
4707 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4708 CalleeArmZT0State != FunctionType::ARM_None) {
4709 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4710 Diag(Loc, diag::note_sme_use_preserves_za);
4711 }
4712 }
4713 }
4714
4715 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4716 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4717 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4718 if (!Arg->isValueDependent()) {
4719 Expr::EvalResult Align;
4720 if (Arg->EvaluateAsInt(Align, Context)) {
4721 const llvm::APSInt &I = Align.Val.getInt();
4722 if (!I.isPowerOf2())
4723 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4724 << Arg->getSourceRange();
4725
4726 if (I > Sema::MaximumAlignment)
4727 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4728 << Arg->getSourceRange() << Sema::MaximumAlignment;
4729 }
4730 }
4731 }
4732
4733 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4735 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4736 << diag::OffloadLang::SYCL;
4737
4738 if (FD)
4739 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4740}
4741
4742void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4743 if (TemplateDecl *Decl =
4744 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4745 DiagnoseUseOfDecl(Decl, Loc);
4746 }
4747}
4748
4749void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4751 const FunctionProtoType *Proto,
4752 SourceLocation Loc) {
4753 VariadicCallType CallType = Proto->isVariadic()
4756
4757 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4758 CheckArgAlignment(
4759 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4760 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4761
4762 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4763 Loc, SourceRange(), CallType);
4764}
4765
4767 const FunctionProtoType *Proto) {
4768 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4769 isa<CXXMethodDecl>(FDecl);
4770 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4771 IsMemberOperatorCall;
4772 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4773 TheCall->getCallee());
4774 Expr** Args = TheCall->getArgs();
4775 unsigned NumArgs = TheCall->getNumArgs();
4776
4777 Expr *ImplicitThis = nullptr;
4778 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4779 // If this is a call to a member operator, hide the first
4780 // argument from checkCall.
4781 // FIXME: Our choice of AST representation here is less than ideal.
4782 ImplicitThis = Args[0];
4783 ++Args;
4784 --NumArgs;
4785 } else if (IsMemberFunction && !FDecl->isStatic() &&
4787 ImplicitThis =
4788 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4789
4790 if (ImplicitThis) {
4791 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4792 // used.
4793 QualType ThisType = ImplicitThis->getType();
4794 if (!ThisType->isPointerType()) {
4795 assert(!ThisType->isReferenceType());
4796 ThisType = Context.getPointerType(ThisType);
4797 }
4798
4799 QualType ThisTypeFromDecl = Context.getPointerType(
4800 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4801
4802 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4803 ThisTypeFromDecl);
4804 }
4805
4806 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4807 IsMemberFunction, TheCall->getRParenLoc(),
4808 TheCall->getCallee()->getSourceRange(), CallType);
4809
4810 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4811 // None of the checks below are needed for functions that don't have
4812 // simple names (e.g., C++ conversion functions).
4813 if (!FnInfo)
4814 return false;
4815
4816 // Enforce TCB except for builtin calls, which are always allowed.
4817 if (FDecl->getBuiltinID() == 0)
4818 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4819
4820 CheckAbsoluteValueFunction(TheCall, FDecl);
4821 CheckMaxUnsignedZero(TheCall, FDecl);
4822 CheckInfNaNFunction(TheCall, FDecl);
4823
4824 if (getLangOpts().ObjC)
4825 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4826
4827 unsigned CMId = FDecl->getMemoryFunctionKind();
4828
4829 // Handle memory setting and copying functions.
4830 switch (CMId) {
4831 case 0:
4832 return false;
4833 case Builtin::BIstrlcpy: // fallthrough
4834 case Builtin::BIstrlcat:
4835 CheckStrlcpycatArguments(TheCall, FnInfo);
4836 break;
4837 case Builtin::BIstrncat:
4838 CheckStrncatArguments(TheCall, FnInfo);
4839 break;
4840 case Builtin::BIfree:
4841 CheckFreeArguments(TheCall);
4842 break;
4843 default:
4844 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4845 }
4846
4847 return false;
4848}
4849
4850bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4851 const FunctionProtoType *Proto) {
4852 QualType Ty;
4853 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4854 Ty = V->getType().getNonReferenceType();
4855 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4856 Ty = F->getType().getNonReferenceType();
4857 else
4858 return false;
4859
4860 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4861 !Ty->isFunctionProtoType())
4862 return false;
4863
4864 VariadicCallType CallType;
4865 if (!Proto || !Proto->isVariadic()) {
4867 } else if (Ty->isBlockPointerType()) {
4868 CallType = VariadicCallType::Block;
4869 } else { // Ty->isFunctionPointerType()
4870 CallType = VariadicCallType::Function;
4871 }
4872
4873 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4874 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4875 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4876 TheCall->getCallee()->getSourceRange(), CallType);
4877
4878 return false;
4879}
4880
4881bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4882 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4883 TheCall->getCallee());
4884 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4885 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4886 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4887 TheCall->getCallee()->getSourceRange(), CallType);
4888
4889 return false;
4890}
4891
4892static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4893 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4894 return false;
4895
4896 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4897 switch (Op) {
4898 case AtomicExpr::AO__c11_atomic_init:
4899 case AtomicExpr::AO__opencl_atomic_init:
4900 llvm_unreachable("There is no ordering argument for an init");
4901
4902 case AtomicExpr::AO__c11_atomic_load:
4903 case AtomicExpr::AO__opencl_atomic_load:
4904 case AtomicExpr::AO__hip_atomic_load:
4905 case AtomicExpr::AO__atomic_load_n:
4906 case AtomicExpr::AO__atomic_load:
4907 case AtomicExpr::AO__scoped_atomic_load_n:
4908 case AtomicExpr::AO__scoped_atomic_load:
4909 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4910 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4911
4912 case AtomicExpr::AO__c11_atomic_store:
4913 case AtomicExpr::AO__opencl_atomic_store:
4914 case AtomicExpr::AO__hip_atomic_store:
4915 case AtomicExpr::AO__atomic_store:
4916 case AtomicExpr::AO__atomic_store_n:
4917 case AtomicExpr::AO__scoped_atomic_store:
4918 case AtomicExpr::AO__scoped_atomic_store_n:
4919 case AtomicExpr::AO__atomic_clear:
4920 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4921 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4922 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4923
4924 default:
4925 return true;
4926 }
4927}
4928
4929ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4931 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4932 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4933 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4934 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4935 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4936 Op);
4937}
4938
4939/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4940/// equivalents. Provide a fixit when the scope is a compile-time constant and
4941/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4942/// compare_exchange builtins differ in how they accept the desired value, so
4943/// only a warning (without a fixit) is emitted for those.
4945 MultiExprArg Args,
4947 StringRef OldName;
4948 StringRef NewName;
4949 bool CanFixIt;
4950
4951 switch (Op) {
4952#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4953 case AtomicExpr::AO__hip_atomic_##hip: \
4954 OldName = "__hip_atomic_" #hip; \
4955 NewName = "__scoped_atomic_" #scoped; \
4956 CanFixIt = true; \
4957 break;
4958 HIP_ATOMIC_FIXABLE(load, load_n)
4959 HIP_ATOMIC_FIXABLE(store, store_n)
4960 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4961 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4962 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4963 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4964 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4965 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4966 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4967 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4968#undef HIP_ATOMIC_FIXABLE
4969 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4970 OldName = "__hip_atomic_compare_exchange_weak";
4971 NewName = "__scoped_atomic_compare_exchange";
4972 CanFixIt = false;
4973 break;
4974 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4975 OldName = "__hip_atomic_compare_exchange_strong";
4976 NewName = "__scoped_atomic_compare_exchange";
4977 CanFixIt = false;
4978 break;
4979 default:
4980 llvm_unreachable("unhandled HIP atomic op");
4981 }
4982
4983 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4984 << OldName << NewName;
4985 if (!CanFixIt)
4986 return;
4987
4988 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4989
4990 Expr *Scope = Args[Args.size() - 1];
4991 std::optional<llvm::APSInt> ScopeVal =
4992 Scope->getIntegerConstantExpr(S.Context);
4993 if (!ScopeVal)
4994 return;
4995
4996 StringRef ScopeName;
4997 switch (ScopeVal->getZExtValue()) {
4999 ScopeName = "__MEMORY_SCOPE_SINGLE";
5000 break;
5002 ScopeName = "__MEMORY_SCOPE_WVFRNT";
5003 break;
5005 ScopeName = "__MEMORY_SCOPE_WRKGRP";
5006 break;
5008 ScopeName = "__MEMORY_SCOPE_DEVICE";
5009 break;
5011 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5012 break;
5014 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5015 break;
5016 default:
5017 return;
5018 }
5019
5021 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
5022}
5023
5025 SourceLocation RParenLoc, MultiExprArg Args,
5027 AtomicArgumentOrder ArgOrder) {
5028 // All the non-OpenCL operations take one of the following forms.
5029 // The OpenCL operations take the __c11 forms with one extra argument for
5030 // synchronization scope.
5031 enum {
5032 // C __c11_atomic_init(A *, C)
5033 Init,
5034
5035 // C __c11_atomic_load(A *, int)
5036 Load,
5037
5038 // void __atomic_load(A *, CP, int)
5039 LoadCopy,
5040
5041 // void __atomic_store(A *, CP, int)
5042 Copy,
5043
5044 // C __c11_atomic_add(A *, M, int)
5045 Arithmetic,
5046
5047 // C __atomic_exchange_n(A *, CP, int)
5048 Xchg,
5049
5050 // void __atomic_exchange(A *, C *, CP, int)
5051 GNUXchg,
5052
5053 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5054 C11CmpXchg,
5055
5056 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5057 GNUCmpXchg,
5058
5059 // bool __atomic_test_and_set(A *, int)
5060 TestAndSetByte,
5061
5062 // void __atomic_clear(A *, int)
5063 ClearByte,
5064 } Form = Init;
5065
5066 const unsigned NumForm = ClearByte + 1;
5067 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5068 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5069 // where:
5070 // C is an appropriate type,
5071 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5072 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5073 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5074 // the int parameters are for orderings.
5075
5076 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5077 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5078 "need to update code for modified forms");
5079 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5080 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5081 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5082 "need to update code for modified C11 atomics");
5083 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5084 Op <= AtomicExpr::AO__opencl_atomic_store;
5085 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5086 Op <= AtomicExpr::AO__hip_atomic_store;
5087 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5088 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5089 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5090 Op <= AtomicExpr::AO__c11_atomic_store) ||
5091 IsOpenCL;
5092 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5093 Op == AtomicExpr::AO__atomic_store_n ||
5094 Op == AtomicExpr::AO__atomic_exchange_n ||
5095 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5096 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5097 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5098 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5099 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5100 // Bit mask for extra allowed value types other than integers for atomic
5101 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5102 // allow floating point.
5103 enum ArithOpExtraValueType {
5104 AOEVT_None = 0,
5105 AOEVT_Pointer = 1,
5106 AOEVT_FP = 2,
5107 AOEVT_Int = 4,
5108 };
5109 unsigned ArithAllows = AOEVT_None;
5110
5111 switch (Op) {
5112 case AtomicExpr::AO__c11_atomic_init:
5113 case AtomicExpr::AO__opencl_atomic_init:
5114 Form = Init;
5115 break;
5116
5117 case AtomicExpr::AO__c11_atomic_load:
5118 case AtomicExpr::AO__opencl_atomic_load:
5119 case AtomicExpr::AO__hip_atomic_load:
5120 case AtomicExpr::AO__atomic_load_n:
5121 case AtomicExpr::AO__scoped_atomic_load_n:
5122 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5123 Form = Load;
5124 break;
5125
5126 case AtomicExpr::AO__atomic_load:
5127 case AtomicExpr::AO__scoped_atomic_load:
5128 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5129 Form = LoadCopy;
5130 break;
5131
5132 case AtomicExpr::AO__c11_atomic_store:
5133 case AtomicExpr::AO__opencl_atomic_store:
5134 case AtomicExpr::AO__hip_atomic_store:
5135 case AtomicExpr::AO__atomic_store:
5136 case AtomicExpr::AO__atomic_store_n:
5137 case AtomicExpr::AO__scoped_atomic_store:
5138 case AtomicExpr::AO__scoped_atomic_store_n:
5139 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5140 Form = Copy;
5141 break;
5142 case AtomicExpr::AO__atomic_fetch_add:
5143 case AtomicExpr::AO__atomic_fetch_sub:
5144 case AtomicExpr::AO__atomic_add_fetch:
5145 case AtomicExpr::AO__atomic_sub_fetch:
5146 case AtomicExpr::AO__scoped_atomic_fetch_add:
5147 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5148 case AtomicExpr::AO__scoped_atomic_add_fetch:
5149 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5150 case AtomicExpr::AO__c11_atomic_fetch_add:
5151 case AtomicExpr::AO__c11_atomic_fetch_sub:
5152 case AtomicExpr::AO__opencl_atomic_fetch_add:
5153 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5154 case AtomicExpr::AO__hip_atomic_fetch_add:
5155 case AtomicExpr::AO__hip_atomic_fetch_sub:
5156 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5157 Form = Arithmetic;
5158 break;
5159 case AtomicExpr::AO__atomic_fetch_fminimum:
5160 case AtomicExpr::AO__atomic_fetch_fmaximum:
5161 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5162 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5163 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5164 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5165 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5166 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5167 ArithAllows = AOEVT_FP;
5168 Form = Arithmetic;
5169 break;
5170 case AtomicExpr::AO__atomic_fetch_max:
5171 case AtomicExpr::AO__atomic_fetch_min:
5172 case AtomicExpr::AO__atomic_max_fetch:
5173 case AtomicExpr::AO__atomic_min_fetch:
5174 case AtomicExpr::AO__scoped_atomic_fetch_max:
5175 case AtomicExpr::AO__scoped_atomic_fetch_min:
5176 case AtomicExpr::AO__scoped_atomic_max_fetch:
5177 case AtomicExpr::AO__scoped_atomic_min_fetch:
5178 case AtomicExpr::AO__c11_atomic_fetch_max:
5179 case AtomicExpr::AO__c11_atomic_fetch_min:
5180 case AtomicExpr::AO__opencl_atomic_fetch_max:
5181 case AtomicExpr::AO__opencl_atomic_fetch_min:
5182 case AtomicExpr::AO__hip_atomic_fetch_max:
5183 case AtomicExpr::AO__hip_atomic_fetch_min:
5184 ArithAllows = AOEVT_Int | AOEVT_FP;
5185 Form = Arithmetic;
5186 break;
5187 case AtomicExpr::AO__c11_atomic_fetch_and:
5188 case AtomicExpr::AO__c11_atomic_fetch_or:
5189 case AtomicExpr::AO__c11_atomic_fetch_xor:
5190 case AtomicExpr::AO__hip_atomic_fetch_and:
5191 case AtomicExpr::AO__hip_atomic_fetch_or:
5192 case AtomicExpr::AO__hip_atomic_fetch_xor:
5193 case AtomicExpr::AO__c11_atomic_fetch_nand:
5194 case AtomicExpr::AO__opencl_atomic_fetch_and:
5195 case AtomicExpr::AO__opencl_atomic_fetch_or:
5196 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5197 case AtomicExpr::AO__atomic_fetch_and:
5198 case AtomicExpr::AO__atomic_fetch_or:
5199 case AtomicExpr::AO__atomic_fetch_xor:
5200 case AtomicExpr::AO__atomic_fetch_nand:
5201 case AtomicExpr::AO__atomic_and_fetch:
5202 case AtomicExpr::AO__atomic_or_fetch:
5203 case AtomicExpr::AO__atomic_xor_fetch:
5204 case AtomicExpr::AO__atomic_nand_fetch:
5205 case AtomicExpr::AO__atomic_fetch_uinc:
5206 case AtomicExpr::AO__atomic_fetch_udec:
5207 case AtomicExpr::AO__scoped_atomic_fetch_and:
5208 case AtomicExpr::AO__scoped_atomic_fetch_or:
5209 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5210 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5211 case AtomicExpr::AO__scoped_atomic_and_fetch:
5212 case AtomicExpr::AO__scoped_atomic_or_fetch:
5213 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5214 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5215 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5216 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5217 Form = Arithmetic;
5218 break;
5219
5220 case AtomicExpr::AO__c11_atomic_exchange:
5221 case AtomicExpr::AO__hip_atomic_exchange:
5222 case AtomicExpr::AO__opencl_atomic_exchange:
5223 case AtomicExpr::AO__atomic_exchange_n:
5224 case AtomicExpr::AO__scoped_atomic_exchange_n:
5225 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5226 Form = Xchg;
5227 break;
5228
5229 case AtomicExpr::AO__atomic_exchange:
5230 case AtomicExpr::AO__scoped_atomic_exchange:
5231 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5232 Form = GNUXchg;
5233 break;
5234
5235 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5236 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5237 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5238 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5239 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5240 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5241 Form = C11CmpXchg;
5242 break;
5243
5244 case AtomicExpr::AO__atomic_compare_exchange:
5245 case AtomicExpr::AO__atomic_compare_exchange_n:
5246 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5247 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5248 ArithAllows = AOEVT_Pointer;
5249 Form = GNUCmpXchg;
5250 break;
5251
5252 case AtomicExpr::AO__atomic_test_and_set:
5253 Form = TestAndSetByte;
5254 break;
5255
5256 case AtomicExpr::AO__atomic_clear:
5257 Form = ClearByte;
5258 break;
5259 }
5260
5261 unsigned AdjustedNumArgs = NumArgs[Form];
5262 if ((IsOpenCL || IsHIP || IsScoped) &&
5263 Op != AtomicExpr::AO__opencl_atomic_init)
5264 ++AdjustedNumArgs;
5265 // Check we have the right number of arguments.
5266 if (Args.size() < AdjustedNumArgs) {
5267 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5268 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5269 << /*is non object*/ 0 << ExprRange;
5270 return ExprError();
5271 } else if (Args.size() > AdjustedNumArgs) {
5272 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5273 diag::err_typecheck_call_too_many_args)
5274 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5275 << /*is non object*/ 0 << ExprRange;
5276 return ExprError();
5277 }
5278
5279 // Inspect the first argument of the atomic operation.
5280 Expr *Ptr = Args[0];
5282 if (ConvertedPtr.isInvalid())
5283 return ExprError();
5284
5285 Ptr = ConvertedPtr.get();
5286 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5287 if (!pointerType) {
5288 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5289 << Ptr->getType() << 0 << Ptr->getSourceRange();
5290 return ExprError();
5291 }
5292
5293 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5294 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5295 QualType ValType = AtomTy; // 'C'
5296 if (IsC11) {
5297 if (!AtomTy->isAtomicType()) {
5298 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5299 << Ptr->getType() << Ptr->getSourceRange();
5300 return ExprError();
5301 }
5302 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5304 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5305 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5306 << Ptr->getSourceRange();
5307 return ExprError();
5308 }
5309 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5310 } else if (Form != Load && Form != LoadCopy) {
5311 if (ValType.isConstQualified()) {
5312 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5313 << Ptr->getType() << Ptr->getSourceRange();
5314 return ExprError();
5315 }
5316 }
5317
5318 if (Form != TestAndSetByte && Form != ClearByte) {
5319 // Pointer to object of size zero is not allowed.
5320 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5321 diag::err_incomplete_type))
5322 return ExprError();
5323
5324 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5325 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5326 << Ptr->getType() << 1 << Ptr->getSourceRange();
5327 return ExprError();
5328 }
5329 } else {
5330 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5331 // non-const pointer type, including void* and pointers to incomplete
5332 // structs, but only access the first byte.
5333 AtomTy = Context.CharTy;
5334 AtomTy = AtomTy.withCVRQualifiers(
5335 pointerType->getPointeeType().getCVRQualifiers());
5336 QualType PointerQT = Context.getPointerType(AtomTy);
5337 pointerType = PointerQT->getAs<PointerType>();
5338 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5339 ValType = AtomTy;
5340 }
5341
5342 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5343 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5344 Diag(ExprRange.getBegin(),
5345 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5346 << 0 << Ptr->getType() << Ptr->getSourceRange();
5347 return ExprError();
5348 }
5349
5350 // For an arithmetic operation, the implied arithmetic must be well-formed.
5351 // For _n operations, the value type must also be a valid atomic type.
5352 if (Form == Arithmetic || IsN) {
5353 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5354 // trivial type errors.
5355 auto IsAllowedValueType = [&](QualType ValType,
5356 unsigned AllowedType) -> bool {
5357 bool IsX87LongDouble =
5358 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5359 &Context.getTargetInfo().getLongDoubleFormat() ==
5360 &llvm::APFloat::x87DoubleExtended();
5361 if (ValType->isIntegerType())
5362 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5363 // integers. Explicit AOEVT_Int or other combinations allow integers.
5364 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5365 if (ValType->isPointerType())
5366 return AllowedType & AOEVT_Pointer;
5367 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5368 return false;
5369 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5370 if (IsX87LongDouble)
5371 return false;
5372 return true;
5373 };
5374 if (!IsAllowedValueType(ValType, ArithAllows)) {
5375 auto DID =
5376 ArithAllows == AOEVT_FP
5377 ? diag::err_atomic_op_needs_atomic_fp
5378 : (ArithAllows & AOEVT_FP
5379 ? (ArithAllows & AOEVT_Pointer
5380 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5381 : diag::err_atomic_op_needs_atomic_int_or_fp)
5382 : (ArithAllows & AOEVT_Pointer
5383 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5384 : diag::err_atomic_op_needs_atomic_int));
5385 Diag(ExprRange.getBegin(), DID)
5386 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5387 return ExprError();
5388 }
5389 if (IsC11 && ValType->isPointerType() &&
5390 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5391 diag::err_incomplete_type)) {
5392 return ExprError();
5393 }
5394 }
5395
5396 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5397 !AtomTy->isScalarType()) {
5398 // For GNU atomics, require a trivially-copyable type. This is not part of
5399 // the GNU atomics specification but we enforce it for consistency with
5400 // other atomics which generally all require a trivially-copyable type. This
5401 // is because atomics just copy bits.
5402 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5403 << Ptr->getType() << Ptr->getSourceRange();
5404 return ExprError();
5405 }
5406
5407 switch (ValType.getObjCLifetime()) {
5410 // okay
5411 break;
5412
5416 // FIXME: Can this happen? By this point, ValType should be known
5417 // to be trivially copyable.
5418 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5419 << ValType << Ptr->getSourceRange();
5420 return ExprError();
5421 }
5422
5423 // All atomic operations have an overload which takes a pointer to a volatile
5424 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5425 // into the result or the other operands. Similarly atomic_load takes a
5426 // pointer to a const 'A'.
5427 ValType.removeLocalVolatile();
5428 ValType.removeLocalConst();
5429 QualType ResultType = ValType;
5430 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5431 Form == ClearByte)
5432 ResultType = Context.VoidTy;
5433 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5434 ResultType = Context.BoolTy;
5435
5436 // The type of a parameter passed 'by value'. In the GNU atomics, such
5437 // arguments are actually passed as pointers.
5438 QualType ByValType = ValType; // 'CP'
5439 bool IsPassedByAddress = false;
5440 if (!IsC11 && !IsHIP && !IsN) {
5441 ByValType = Ptr->getType();
5442 IsPassedByAddress = true;
5443 }
5444
5445 SmallVector<Expr *, 5> APIOrderedArgs;
5446 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5447 APIOrderedArgs.push_back(Args[0]);
5448 switch (Form) {
5449 case Init:
5450 case Load:
5451 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5452 break;
5453 case LoadCopy:
5454 case Copy:
5455 case Arithmetic:
5456 case Xchg:
5457 APIOrderedArgs.push_back(Args[2]); // Val1
5458 APIOrderedArgs.push_back(Args[1]); // Order
5459 break;
5460 case GNUXchg:
5461 APIOrderedArgs.push_back(Args[2]); // Val1
5462 APIOrderedArgs.push_back(Args[3]); // Val2
5463 APIOrderedArgs.push_back(Args[1]); // Order
5464 break;
5465 case C11CmpXchg:
5466 APIOrderedArgs.push_back(Args[2]); // Val1
5467 APIOrderedArgs.push_back(Args[4]); // Val2
5468 APIOrderedArgs.push_back(Args[1]); // Order
5469 APIOrderedArgs.push_back(Args[3]); // OrderFail
5470 break;
5471 case GNUCmpXchg:
5472 APIOrderedArgs.push_back(Args[2]); // Val1
5473 APIOrderedArgs.push_back(Args[4]); // Val2
5474 APIOrderedArgs.push_back(Args[5]); // Weak
5475 APIOrderedArgs.push_back(Args[1]); // Order
5476 APIOrderedArgs.push_back(Args[3]); // OrderFail
5477 break;
5478 case TestAndSetByte:
5479 case ClearByte:
5480 APIOrderedArgs.push_back(Args[1]); // Order
5481 break;
5482 }
5483 } else
5484 APIOrderedArgs.append(Args.begin(), Args.end());
5485
5486 // The first argument's non-CV pointer type is used to deduce the type of
5487 // subsequent arguments, except for:
5488 // - weak flag (always converted to bool)
5489 // - memory order (always converted to int)
5490 // - scope (always converted to int)
5491 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5492 QualType Ty;
5493 if (i < NumVals[Form] + 1) {
5494 switch (i) {
5495 case 0:
5496 // The first argument is always a pointer. It has a fixed type.
5497 // It is always dereferenced, a nullptr is undefined.
5498 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5499 // Nothing else to do: we already know all we want about this pointer.
5500 continue;
5501 case 1:
5502 // The second argument is the non-atomic operand. For arithmetic, this
5503 // is always passed by value, and for a compare_exchange it is always
5504 // passed by address. For the rest, GNU uses by-address and C11 uses
5505 // by-value.
5506 assert(Form != Load);
5507 if (Form == Arithmetic && ValType->isPointerType())
5508 Ty = Context.getPointerDiffType();
5509 else if (Form == Init || Form == Arithmetic)
5510 Ty = ValType;
5511 else if (Form == Copy || Form == Xchg) {
5512 if (IsPassedByAddress) {
5513 // The value pointer is always dereferenced, a nullptr is undefined.
5514 CheckNonNullArgument(*this, APIOrderedArgs[i],
5515 ExprRange.getBegin());
5516 }
5517 Ty = ByValType;
5518 } else {
5519 Expr *ValArg = APIOrderedArgs[i];
5520 // The value pointer is always dereferenced, a nullptr is undefined.
5521 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5523 // Keep address space of non-atomic pointer type.
5524 if (const PointerType *PtrTy =
5525 ValArg->getType()->getAs<PointerType>()) {
5526 AS = PtrTy->getPointeeType().getAddressSpace();
5527 }
5528 Ty = Context.getPointerType(
5529 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5530 }
5531 break;
5532 case 2:
5533 // The third argument to compare_exchange / GNU exchange is the desired
5534 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5535 if (IsPassedByAddress)
5536 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5537 Ty = ByValType;
5538 break;
5539 case 3:
5540 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5541 Ty = Context.BoolTy;
5542 break;
5543 }
5544 } else {
5545 // The order(s) and scope are always converted to int.
5546 Ty = Context.IntTy;
5547 }
5548
5549 InitializedEntity Entity =
5551 ExprResult Arg = APIOrderedArgs[i];
5552 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5553 if (Arg.isInvalid())
5554 return true;
5555 APIOrderedArgs[i] = Arg.get();
5556 }
5557
5558 // Permute the arguments into a 'consistent' order.
5559 SmallVector<Expr*, 5> SubExprs;
5560 SubExprs.push_back(Ptr);
5561 switch (Form) {
5562 case Init:
5563 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5564 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5565 break;
5566 case Load:
5567 case TestAndSetByte:
5568 case ClearByte:
5569 SubExprs.push_back(APIOrderedArgs[1]); // Order
5570 break;
5571 case LoadCopy:
5572 case Copy:
5573 case Arithmetic:
5574 case Xchg:
5575 SubExprs.push_back(APIOrderedArgs[2]); // Order
5576 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5577 break;
5578 case GNUXchg:
5579 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5580 SubExprs.push_back(APIOrderedArgs[3]); // Order
5581 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5582 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5583 break;
5584 case C11CmpXchg:
5585 SubExprs.push_back(APIOrderedArgs[3]); // Order
5586 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5587 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5588 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5589 break;
5590 case GNUCmpXchg:
5591 SubExprs.push_back(APIOrderedArgs[4]); // Order
5592 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5593 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5594 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5595 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5596 break;
5597 }
5598
5599 // If the memory orders are constants, check they are valid.
5600 if (SubExprs.size() >= 2 && Form != Init) {
5601 std::optional<llvm::APSInt> Success =
5602 SubExprs[1]->getIntegerConstantExpr(Context);
5603 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5604 Diag(SubExprs[1]->getBeginLoc(),
5605 diag::warn_atomic_op_has_invalid_memory_order)
5606 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5607 << SubExprs[1]->getSourceRange();
5608 }
5609 if (SubExprs.size() >= 5) {
5610 if (std::optional<llvm::APSInt> Failure =
5611 SubExprs[3]->getIntegerConstantExpr(Context)) {
5612 if (!llvm::is_contained(
5613 {llvm::AtomicOrderingCABI::relaxed,
5614 llvm::AtomicOrderingCABI::consume,
5615 llvm::AtomicOrderingCABI::acquire,
5616 llvm::AtomicOrderingCABI::seq_cst},
5617 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5618 Diag(SubExprs[3]->getBeginLoc(),
5619 diag::warn_atomic_op_has_invalid_memory_order)
5620 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5621 }
5622 }
5623 }
5624 }
5625
5626 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5627 auto *Scope = Args[Args.size() - 1];
5628 if (std::optional<llvm::APSInt> Result =
5629 Scope->getIntegerConstantExpr(Context)) {
5630 if (!ScopeModel->isValid(Result->getZExtValue()))
5631 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5632 << Scope->getSourceRange();
5633 }
5634 SubExprs.push_back(Scope);
5635 }
5636
5637 if (IsHIP)
5638 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5639
5640 AtomicExpr *AE = new (Context)
5641 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5642
5643 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5644 Op == AtomicExpr::AO__c11_atomic_store ||
5645 Op == AtomicExpr::AO__opencl_atomic_load ||
5646 Op == AtomicExpr::AO__hip_atomic_load ||
5647 Op == AtomicExpr::AO__opencl_atomic_store ||
5648 Op == AtomicExpr::AO__hip_atomic_store) &&
5649 Context.AtomicUsesUnsupportedLibcall(AE))
5650 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5651 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5652 Op == AtomicExpr::AO__opencl_atomic_load ||
5653 Op == AtomicExpr::AO__hip_atomic_load)
5654 ? 0
5655 : 1);
5656
5657 if (ValType->isBitIntType()) {
5658 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5659 return ExprError();
5660 }
5661
5662 return AE;
5663}
5664
5665/// checkBuiltinArgument - Given a call to a builtin function, perform
5666/// normal type-checking on the given argument, updating the call in
5667/// place. This is useful when a builtin function requires custom
5668/// type-checking for some of its arguments but not necessarily all of
5669/// them.
5670///
5671/// Returns true on error.
5672static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5673 FunctionDecl *Fn = E->getDirectCallee();
5674 assert(Fn && "builtin call without direct callee!");
5675
5676 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5677 InitializedEntity Entity =
5679
5680 ExprResult Arg = E->getArg(ArgIndex);
5681 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5682 if (Arg.isInvalid())
5683 return true;
5684
5685 E->setArg(ArgIndex, Arg.get());
5686 return false;
5687}
5688
5689ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5690 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5691 Expr *Callee = TheCall->getCallee();
5692 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5693 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5694
5695 // Ensure that we have at least one argument to do type inference from.
5696 if (TheCall->getNumArgs() < 1) {
5697 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5698 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5699 << Callee->getSourceRange();
5700 return ExprError();
5701 }
5702
5703 // Inspect the first argument of the atomic builtin. This should always be
5704 // a pointer type, whose element is an integral scalar or pointer type.
5705 // Because it is a pointer type, we don't have to worry about any implicit
5706 // casts here.
5707 // FIXME: We don't allow floating point scalars as input.
5708 Expr *FirstArg = TheCall->getArg(0);
5709 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5710 if (FirstArgResult.isInvalid())
5711 return ExprError();
5712 FirstArg = FirstArgResult.get();
5713 TheCall->setArg(0, FirstArg);
5714
5715 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5716 if (!pointerType) {
5717 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5718 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5719 return ExprError();
5720 }
5721
5722 QualType ValType = pointerType->getPointeeType();
5723 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5724 !ValType->isBlockPointerType()) {
5725 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5726 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5727 return ExprError();
5728 }
5729 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5730 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5731 Diag(FirstArg->getBeginLoc(),
5732 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5733 << 1 << ValType << FirstArg->getSourceRange();
5734 return ExprError();
5735 }
5736
5737 if (ValType.isConstQualified()) {
5738 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5739 << FirstArg->getType() << FirstArg->getSourceRange();
5740 return ExprError();
5741 }
5742
5743 switch (ValType.getObjCLifetime()) {
5746 // okay
5747 break;
5748
5752 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5753 << ValType << FirstArg->getSourceRange();
5754 return ExprError();
5755 }
5756
5757 // Strip any qualifiers off ValType.
5758 ValType = ValType.getUnqualifiedType();
5759
5760 // The majority of builtins return a value, but a few have special return
5761 // types, so allow them to override appropriately below.
5762 QualType ResultType = ValType;
5763
5764 // We need to figure out which concrete builtin this maps onto. For example,
5765 // __sync_fetch_and_add with a 2 byte object turns into
5766 // __sync_fetch_and_add_2.
5767#define BUILTIN_ROW(x) \
5768 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5769 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5770
5771 static const unsigned BuiltinIndices[][5] = {
5772 BUILTIN_ROW(__sync_fetch_and_add),
5773 BUILTIN_ROW(__sync_fetch_and_sub),
5774 BUILTIN_ROW(__sync_fetch_and_or),
5775 BUILTIN_ROW(__sync_fetch_and_and),
5776 BUILTIN_ROW(__sync_fetch_and_xor),
5777 BUILTIN_ROW(__sync_fetch_and_nand),
5778
5779 BUILTIN_ROW(__sync_add_and_fetch),
5780 BUILTIN_ROW(__sync_sub_and_fetch),
5781 BUILTIN_ROW(__sync_and_and_fetch),
5782 BUILTIN_ROW(__sync_or_and_fetch),
5783 BUILTIN_ROW(__sync_xor_and_fetch),
5784 BUILTIN_ROW(__sync_nand_and_fetch),
5785
5786 BUILTIN_ROW(__sync_val_compare_and_swap),
5787 BUILTIN_ROW(__sync_bool_compare_and_swap),
5788 BUILTIN_ROW(__sync_lock_test_and_set),
5789 BUILTIN_ROW(__sync_lock_release),
5790 BUILTIN_ROW(__sync_swap)
5791 };
5792#undef BUILTIN_ROW
5793
5794 // Determine the index of the size.
5795 unsigned SizeIndex;
5796 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5797 case 1: SizeIndex = 0; break;
5798 case 2: SizeIndex = 1; break;
5799 case 4: SizeIndex = 2; break;
5800 case 8: SizeIndex = 3; break;
5801 case 16: SizeIndex = 4; break;
5802 default:
5803 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5804 << FirstArg->getType() << FirstArg->getSourceRange();
5805 return ExprError();
5806 }
5807
5808 // Each of these builtins has one pointer argument, followed by some number of
5809 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5810 // that we ignore. Find out which row of BuiltinIndices to read from as well
5811 // as the number of fixed args.
5812 unsigned BuiltinID = FDecl->getBuiltinID();
5813 unsigned BuiltinIndex, NumFixed = 1;
5814 bool WarnAboutSemanticsChange = false;
5815 switch (BuiltinID) {
5816 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5817 case Builtin::BI__sync_fetch_and_add:
5818 case Builtin::BI__sync_fetch_and_add_1:
5819 case Builtin::BI__sync_fetch_and_add_2:
5820 case Builtin::BI__sync_fetch_and_add_4:
5821 case Builtin::BI__sync_fetch_and_add_8:
5822 case Builtin::BI__sync_fetch_and_add_16:
5823 BuiltinIndex = 0;
5824 break;
5825
5826 case Builtin::BI__sync_fetch_and_sub:
5827 case Builtin::BI__sync_fetch_and_sub_1:
5828 case Builtin::BI__sync_fetch_and_sub_2:
5829 case Builtin::BI__sync_fetch_and_sub_4:
5830 case Builtin::BI__sync_fetch_and_sub_8:
5831 case Builtin::BI__sync_fetch_and_sub_16:
5832 BuiltinIndex = 1;
5833 break;
5834
5835 case Builtin::BI__sync_fetch_and_or:
5836 case Builtin::BI__sync_fetch_and_or_1:
5837 case Builtin::BI__sync_fetch_and_or_2:
5838 case Builtin::BI__sync_fetch_and_or_4:
5839 case Builtin::BI__sync_fetch_and_or_8:
5840 case Builtin::BI__sync_fetch_and_or_16:
5841 BuiltinIndex = 2;
5842 break;
5843
5844 case Builtin::BI__sync_fetch_and_and:
5845 case Builtin::BI__sync_fetch_and_and_1:
5846 case Builtin::BI__sync_fetch_and_and_2:
5847 case Builtin::BI__sync_fetch_and_and_4:
5848 case Builtin::BI__sync_fetch_and_and_8:
5849 case Builtin::BI__sync_fetch_and_and_16:
5850 BuiltinIndex = 3;
5851 break;
5852
5853 case Builtin::BI__sync_fetch_and_xor:
5854 case Builtin::BI__sync_fetch_and_xor_1:
5855 case Builtin::BI__sync_fetch_and_xor_2:
5856 case Builtin::BI__sync_fetch_and_xor_4:
5857 case Builtin::BI__sync_fetch_and_xor_8:
5858 case Builtin::BI__sync_fetch_and_xor_16:
5859 BuiltinIndex = 4;
5860 break;
5861
5862 case Builtin::BI__sync_fetch_and_nand:
5863 case Builtin::BI__sync_fetch_and_nand_1:
5864 case Builtin::BI__sync_fetch_and_nand_2:
5865 case Builtin::BI__sync_fetch_and_nand_4:
5866 case Builtin::BI__sync_fetch_and_nand_8:
5867 case Builtin::BI__sync_fetch_and_nand_16:
5868 BuiltinIndex = 5;
5869 WarnAboutSemanticsChange = true;
5870 break;
5871
5872 case Builtin::BI__sync_add_and_fetch:
5873 case Builtin::BI__sync_add_and_fetch_1:
5874 case Builtin::BI__sync_add_and_fetch_2:
5875 case Builtin::BI__sync_add_and_fetch_4:
5876 case Builtin::BI__sync_add_and_fetch_8:
5877 case Builtin::BI__sync_add_and_fetch_16:
5878 BuiltinIndex = 6;
5879 break;
5880
5881 case Builtin::BI__sync_sub_and_fetch:
5882 case Builtin::BI__sync_sub_and_fetch_1:
5883 case Builtin::BI__sync_sub_and_fetch_2:
5884 case Builtin::BI__sync_sub_and_fetch_4:
5885 case Builtin::BI__sync_sub_and_fetch_8:
5886 case Builtin::BI__sync_sub_and_fetch_16:
5887 BuiltinIndex = 7;
5888 break;
5889
5890 case Builtin::BI__sync_and_and_fetch:
5891 case Builtin::BI__sync_and_and_fetch_1:
5892 case Builtin::BI__sync_and_and_fetch_2:
5893 case Builtin::BI__sync_and_and_fetch_4:
5894 case Builtin::BI__sync_and_and_fetch_8:
5895 case Builtin::BI__sync_and_and_fetch_16:
5896 BuiltinIndex = 8;
5897 break;
5898
5899 case Builtin::BI__sync_or_and_fetch:
5900 case Builtin::BI__sync_or_and_fetch_1:
5901 case Builtin::BI__sync_or_and_fetch_2:
5902 case Builtin::BI__sync_or_and_fetch_4:
5903 case Builtin::BI__sync_or_and_fetch_8:
5904 case Builtin::BI__sync_or_and_fetch_16:
5905 BuiltinIndex = 9;
5906 break;
5907
5908 case Builtin::BI__sync_xor_and_fetch:
5909 case Builtin::BI__sync_xor_and_fetch_1:
5910 case Builtin::BI__sync_xor_and_fetch_2:
5911 case Builtin::BI__sync_xor_and_fetch_4:
5912 case Builtin::BI__sync_xor_and_fetch_8:
5913 case Builtin::BI__sync_xor_and_fetch_16:
5914 BuiltinIndex = 10;
5915 break;
5916
5917 case Builtin::BI__sync_nand_and_fetch:
5918 case Builtin::BI__sync_nand_and_fetch_1:
5919 case Builtin::BI__sync_nand_and_fetch_2:
5920 case Builtin::BI__sync_nand_and_fetch_4:
5921 case Builtin::BI__sync_nand_and_fetch_8:
5922 case Builtin::BI__sync_nand_and_fetch_16:
5923 BuiltinIndex = 11;
5924 WarnAboutSemanticsChange = true;
5925 break;
5926
5927 case Builtin::BI__sync_val_compare_and_swap:
5928 case Builtin::BI__sync_val_compare_and_swap_1:
5929 case Builtin::BI__sync_val_compare_and_swap_2:
5930 case Builtin::BI__sync_val_compare_and_swap_4:
5931 case Builtin::BI__sync_val_compare_and_swap_8:
5932 case Builtin::BI__sync_val_compare_and_swap_16:
5933 BuiltinIndex = 12;
5934 NumFixed = 2;
5935 break;
5936
5937 case Builtin::BI__sync_bool_compare_and_swap:
5938 case Builtin::BI__sync_bool_compare_and_swap_1:
5939 case Builtin::BI__sync_bool_compare_and_swap_2:
5940 case Builtin::BI__sync_bool_compare_and_swap_4:
5941 case Builtin::BI__sync_bool_compare_and_swap_8:
5942 case Builtin::BI__sync_bool_compare_and_swap_16:
5943 BuiltinIndex = 13;
5944 NumFixed = 2;
5945 ResultType = Context.BoolTy;
5946 break;
5947
5948 case Builtin::BI__sync_lock_test_and_set:
5949 case Builtin::BI__sync_lock_test_and_set_1:
5950 case Builtin::BI__sync_lock_test_and_set_2:
5951 case Builtin::BI__sync_lock_test_and_set_4:
5952 case Builtin::BI__sync_lock_test_and_set_8:
5953 case Builtin::BI__sync_lock_test_and_set_16:
5954 BuiltinIndex = 14;
5955 break;
5956
5957 case Builtin::BI__sync_lock_release:
5958 case Builtin::BI__sync_lock_release_1:
5959 case Builtin::BI__sync_lock_release_2:
5960 case Builtin::BI__sync_lock_release_4:
5961 case Builtin::BI__sync_lock_release_8:
5962 case Builtin::BI__sync_lock_release_16:
5963 BuiltinIndex = 15;
5964 NumFixed = 0;
5965 ResultType = Context.VoidTy;
5966 break;
5967
5968 case Builtin::BI__sync_swap:
5969 case Builtin::BI__sync_swap_1:
5970 case Builtin::BI__sync_swap_2:
5971 case Builtin::BI__sync_swap_4:
5972 case Builtin::BI__sync_swap_8:
5973 case Builtin::BI__sync_swap_16:
5974 BuiltinIndex = 16;
5975 break;
5976 }
5977
5978 // Now that we know how many fixed arguments we expect, first check that we
5979 // have at least that many.
5980 if (TheCall->getNumArgs() < 1+NumFixed) {
5981 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5982 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5983 << Callee->getSourceRange();
5984 return ExprError();
5985 }
5986
5987 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5988 << Callee->getSourceRange();
5989
5990 if (WarnAboutSemanticsChange) {
5991 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5992 << Callee->getSourceRange();
5993 }
5994
5995 // Get the decl for the concrete builtin from this, we can tell what the
5996 // concrete integer type we should convert to is.
5997 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5998 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5999 FunctionDecl *NewBuiltinDecl;
6000 if (NewBuiltinID == BuiltinID)
6001 NewBuiltinDecl = FDecl;
6002 else {
6003 // Perform builtin lookup to avoid redeclaring it.
6004 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6005 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6006 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6007 assert(Res.getFoundDecl());
6008 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6009 if (!NewBuiltinDecl)
6010 return ExprError();
6011 }
6012
6013 // The first argument --- the pointer --- has a fixed type; we
6014 // deduce the types of the rest of the arguments accordingly. Walk
6015 // the remaining arguments, converting them to the deduced value type.
6016 for (unsigned i = 0; i != NumFixed; ++i) {
6017 ExprResult Arg = TheCall->getArg(i+1);
6018
6019 // GCC does an implicit conversion to the pointer or integer ValType. This
6020 // can fail in some cases (1i -> int**), check for this error case now.
6021 // Initialize the argument.
6022 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6023 ValType, /*consume*/ false);
6024 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6025 if (Arg.isInvalid())
6026 return ExprError();
6027
6028 // Okay, we have something that *can* be converted to the right type. Check
6029 // to see if there is a potentially weird extension going on here. This can
6030 // happen when you do an atomic operation on something like an char* and
6031 // pass in 42. The 42 gets converted to char. This is even more strange
6032 // for things like 45.123 -> char, etc.
6033 // FIXME: Do this check.
6034 TheCall->setArg(i+1, Arg.get());
6035 }
6036
6037 // Create a new DeclRefExpr to refer to the new decl.
6038 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6039 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6040 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6041 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6042
6043 // Set the callee in the CallExpr.
6044 // FIXME: This loses syntactic information.
6045 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6046 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6047 CK_BuiltinFnToFnPtr);
6048 TheCall->setCallee(PromotedCall.get());
6049
6050 // Change the result type of the call to match the original value type. This
6051 // is arbitrary, but the codegen for these builtins ins design to handle it
6052 // gracefully.
6053 TheCall->setType(ResultType);
6054
6055 // Prohibit problematic uses of bit-precise integer types with atomic
6056 // builtins. The arguments would have already been converted to the first
6057 // argument's type, so only need to check the first argument.
6058 const auto *BitIntValType = ValType->getAs<BitIntType>();
6059 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6060 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6061 return ExprError();
6062 }
6063
6064 return TheCallResult;
6065}
6066
6067ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6068 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6069 DeclRefExpr *DRE =
6071 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6072 unsigned BuiltinID = FDecl->getBuiltinID();
6073 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6074 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6075 "Unexpected nontemporal load/store builtin!");
6076 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6077 unsigned numArgs = isStore ? 2 : 1;
6078
6079 // Ensure that we have the proper number of arguments.
6080 if (checkArgCount(TheCall, numArgs))
6081 return ExprError();
6082
6083 // Inspect the last argument of the nontemporal builtin. This should always
6084 // be a pointer type, from which we imply the type of the memory access.
6085 // Because it is a pointer type, we don't have to worry about any implicit
6086 // casts here.
6087 Expr *PointerArg = TheCall->getArg(numArgs - 1);
6088 ExprResult PointerArgResult =
6090
6091 if (PointerArgResult.isInvalid())
6092 return ExprError();
6093 PointerArg = PointerArgResult.get();
6094 TheCall->setArg(numArgs - 1, PointerArg);
6095
6096 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6097 if (!pointerType) {
6098 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6099 << PointerArg->getType() << PointerArg->getSourceRange();
6100 return ExprError();
6101 }
6102
6103 QualType ValType = pointerType->getPointeeType();
6104
6105 // Strip any qualifiers off ValType.
6106 ValType = ValType.getUnqualifiedType();
6107 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6108 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6109 !ValType->isVectorType()) {
6110 Diag(DRE->getBeginLoc(),
6111 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6112 << PointerArg->getType() << PointerArg->getSourceRange();
6113 return ExprError();
6114 }
6115
6116 if (!isStore) {
6117 TheCall->setType(ValType);
6118 return TheCallResult;
6119 }
6120
6121 ExprResult ValArg = TheCall->getArg(0);
6122 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6123 Context, ValType, /*consume*/ false);
6124 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6125 if (ValArg.isInvalid())
6126 return ExprError();
6127
6128 TheCall->setArg(0, ValArg.get());
6129 TheCall->setType(Context.VoidTy);
6130 return TheCallResult;
6131}
6132
6133/// CheckObjCString - Checks that the format string argument to the os_log()
6134/// and os_trace() functions is correct, and converts it to const char *.
6135ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6136 Arg = Arg->IgnoreParenCasts();
6137 auto *Literal = dyn_cast<StringLiteral>(Arg);
6138 if (!Literal) {
6139 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6140 Literal = ObjcLiteral->getString();
6141 }
6142 }
6143
6144 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6145 return ExprError(
6146 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6147 << Arg->getSourceRange());
6148 }
6149
6150 ExprResult Result(Literal);
6151 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6152 InitializedEntity Entity =
6154 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6155 return Result;
6156}
6157
6158/// Check that the user is calling the appropriate va_start builtin for the
6159/// target and calling convention.
6160static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6161 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6162 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6163 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6164 TT.getArch() == llvm::Triple::aarch64_32);
6165 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6166 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6167 if (IsX64 || IsAArch64) {
6168 CallingConv CC = CC_C;
6169 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6170 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6171 if (IsMSVAStart) {
6172 // Don't allow this in System V ABI functions.
6173 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6174 return S.Diag(Fn->getBeginLoc(),
6175 diag::err_ms_va_start_used_in_sysv_function);
6176 } else {
6177 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6178 // On x64 Windows, don't allow this in System V ABI functions.
6179 // (Yes, that means there's no corresponding way to support variadic
6180 // System V ABI functions on Windows.)
6181 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6182 (!IsWindowsOrUEFI && CC == CC_Win64))
6183 return S.Diag(Fn->getBeginLoc(),
6184 diag::err_va_start_used_in_wrong_abi_function)
6185 << !IsWindowsOrUEFI;
6186 }
6187 return false;
6188 }
6189
6190 if (IsMSVAStart)
6191 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6192 return false;
6193}
6194
6196 ParmVarDecl **LastParam = nullptr) {
6197 // Determine whether the current function, block, or obj-c method is variadic
6198 // and get its parameter list.
6199 bool IsVariadic = false;
6201 DeclContext *Caller =
6203 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6204 IsVariadic = Block->isVariadic();
6205 Params = Block->parameters();
6206 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6207 IsVariadic = FD->isVariadic();
6208 Params = FD->parameters();
6209 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6210 IsVariadic = MD->isVariadic();
6211 // FIXME: This isn't correct for methods (results in bogus warning).
6212 Params = MD->parameters();
6213 } else if (isa<CapturedDecl>(Caller)) {
6214 // We don't support va_start in a CapturedDecl.
6215 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6216 return true;
6217 } else {
6218 // This must be some other declcontext that parses exprs.
6219 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6220 return true;
6221 }
6222
6223 if (!IsVariadic) {
6224 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6225 return true;
6226 }
6227
6228 if (LastParam)
6229 *LastParam = Params.empty() ? nullptr : Params.back();
6230
6231 return false;
6232}
6233
6234bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6235 Expr *Fn = TheCall->getCallee();
6236 if (checkVAStartABI(*this, BuiltinID, Fn))
6237 return true;
6238
6239 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6240 // This builtin requires one argument (the va_list), allows two arguments,
6241 // but diagnoses more than two arguments. e.g.,
6242 // __builtin_c23_va_start(); // error
6243 // __builtin_c23_va_start(list); // ok
6244 // __builtin_c23_va_start(list, param); // ok
6245 // __builtin_c23_va_start(list, anything, anything); // error
6246 // This differs from the GCC behavior in that they accept the last case
6247 // with a warning, but it doesn't seem like a useful behavior to allow.
6248 if (checkArgCountRange(TheCall, 1, 2))
6249 return true;
6250 } else {
6251 // In C23 mode, va_start only needs one argument. However, the builtin still
6252 // requires two arguments (which matches the behavior of the GCC builtin),
6253 // <stdarg.h> passes `0` as the second argument in C23 mode.
6254 if (checkArgCount(TheCall, 2))
6255 return true;
6256 }
6257
6258 // Type-check the first argument normally.
6259 if (checkBuiltinArgument(*this, TheCall, 0))
6260 return true;
6261
6262 // Check that the current function is variadic, and get its last parameter.
6263 ParmVarDecl *LastParam;
6264 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6265 return true;
6266
6267 // Verify that the second argument to the builtin is the last non-variadic
6268 // argument of the current function or method. In C23 mode, if the call is
6269 // not to __builtin_c23_va_start, and the second argument is an integer
6270 // constant expression with value 0, then we don't bother with this check.
6271 // For __builtin_c23_va_start, we only perform the check for the second
6272 // argument being the last argument to the current function if there is a
6273 // second argument present.
6274 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6275 TheCall->getNumArgs() < 2) {
6276 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6277 return false;
6278 }
6279
6280 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6281 if (std::optional<llvm::APSInt> Val =
6283 Val && LangOpts.C23 && *Val == 0 &&
6284 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6285 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6286 return false;
6287 }
6288
6289 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6290 // next block.
6291 QualType Type;
6292 SourceLocation ParamLoc;
6293 bool IsCRegister = false;
6294 bool SecondArgIsLastNonVariadicArgument = false;
6295 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6296 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6297 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6298
6299 Type = PV->getType();
6300 ParamLoc = PV->getLocation();
6301 IsCRegister =
6302 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6303 }
6304 }
6305
6306 if (!SecondArgIsLastNonVariadicArgument)
6307 Diag(TheCall->getArg(1)->getBeginLoc(),
6308 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6309 else if (IsCRegister || Type->isReferenceType() ||
6310 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6311 // Promotable integers are UB, but enumerations need a bit of
6312 // extra checking to see what their promotable type actually is.
6313 if (!Context.isPromotableIntegerType(Type))
6314 return false;
6315 const auto *ED = Type->getAsEnumDecl();
6316 if (!ED)
6317 return true;
6318 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6319 }()) {
6320 unsigned Reason = 0;
6321 if (Type->isReferenceType()) Reason = 1;
6322 else if (IsCRegister) Reason = 2;
6323 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6324 Diag(ParamLoc, diag::note_parameter_type) << Type;
6325 }
6326
6327 return false;
6328}
6329
6330bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6331 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6332 const LangOptions &LO = getLangOpts();
6333
6334 if (LO.CPlusPlus)
6335 return Arg->getType()
6337 .getTypePtr()
6338 ->getPointeeType()
6340
6341 // In C, allow aliasing through `char *`, this is required for AArch64 at
6342 // least.
6343 return true;
6344 };
6345
6346 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6347 // const char *named_addr);
6348
6349 Expr *Func = Call->getCallee();
6350
6351 if (Call->getNumArgs() < 3)
6352 return Diag(Call->getEndLoc(),
6353 diag::err_typecheck_call_too_few_args_at_least)
6354 << 0 /*function call*/ << 3 << Call->getNumArgs()
6355 << /*is non object*/ 0;
6356
6357 // Type-check the first argument normally.
6358 if (checkBuiltinArgument(*this, Call, 0))
6359 return true;
6360
6361 // Check that the current function is variadic.
6363 return true;
6364
6365 // __va_start on Windows does not validate the parameter qualifiers
6366
6367 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6368 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6369
6370 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6371 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6372
6373 const QualType &ConstCharPtrTy =
6374 Context.getPointerType(Context.CharTy.withConst());
6375 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6376 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6377 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6378 << 0 /* qualifier difference */
6379 << 3 /* parameter mismatch */
6380 << 2 << Arg1->getType() << ConstCharPtrTy;
6381
6382 const QualType SizeTy = Context.getSizeType();
6383 if (!Context.hasSameType(
6385 SizeTy))
6386 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6387 << Arg2->getType() << SizeTy << 1 /* different class */
6388 << 0 /* qualifier difference */
6389 << 3 /* parameter mismatch */
6390 << 3 << Arg2->getType() << SizeTy;
6391
6392 return false;
6393}
6394
6395bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6396 if (checkArgCount(TheCall, 2))
6397 return true;
6398
6399 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6400 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6401 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6402 << 1 << 0 << TheCall->getSourceRange();
6403
6404 ExprResult OrigArg0 = TheCall->getArg(0);
6405 ExprResult OrigArg1 = TheCall->getArg(1);
6406
6407 // Do standard promotions between the two arguments, returning their common
6408 // type.
6409 QualType Res = UsualArithmeticConversions(
6410 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6411 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6412 return true;
6413
6414 // Make sure any conversions are pushed back into the call; this is
6415 // type safe since unordered compare builtins are declared as "_Bool
6416 // foo(...)".
6417 TheCall->setArg(0, OrigArg0.get());
6418 TheCall->setArg(1, OrigArg1.get());
6419
6420 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6421 return false;
6422
6423 // If the common type isn't a real floating type, then the arguments were
6424 // invalid for this operation.
6425 if (Res.isNull() || !Res->isRealFloatingType())
6426 return Diag(OrigArg0.get()->getBeginLoc(),
6427 diag::err_typecheck_call_invalid_ordered_compare)
6428 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6429 << SourceRange(OrigArg0.get()->getBeginLoc(),
6430 OrigArg1.get()->getEndLoc());
6431
6432 return false;
6433}
6434
6435bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6436 unsigned BuiltinID) {
6437 if (checkArgCount(TheCall, NumArgs))
6438 return true;
6439
6440 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6441 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6442 BuiltinID == Builtin::BI__builtin_isinf ||
6443 BuiltinID == Builtin::BI__builtin_isinf_sign))
6444 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6445 << 0 << 0 << TheCall->getSourceRange();
6446
6447 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6448 BuiltinID == Builtin::BI__builtin_isunordered))
6449 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6450 << 1 << 0 << TheCall->getSourceRange();
6451
6452 bool IsFPClass = NumArgs == 2;
6453
6454 // Find out position of floating-point argument.
6455 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6456
6457 // We can count on all parameters preceding the floating-point just being int.
6458 // Try all of those.
6459 for (unsigned i = 0; i < FPArgNo; ++i) {
6460 Expr *Arg = TheCall->getArg(i);
6461
6462 if (Arg->isTypeDependent())
6463 return false;
6464
6467
6468 if (Res.isInvalid())
6469 return true;
6470 TheCall->setArg(i, Res.get());
6471 }
6472
6473 Expr *OrigArg = TheCall->getArg(FPArgNo);
6474
6475 if (OrigArg->isTypeDependent())
6476 return false;
6477
6478 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6480 if (!Res.isUsable())
6481 return true;
6482 OrigArg = Res.get();
6483
6484 TheCall->setArg(FPArgNo, OrigArg);
6485
6486 QualType VectorResultTy;
6487 QualType ElementTy = OrigArg->getType();
6488 // TODO: When all classification function are implemented with is_fpclass,
6489 // vector argument can be supported in all of them.
6490 if (ElementTy->isVectorType() && IsFPClass) {
6491 VectorResultTy = GetSignedVectorType(ElementTy);
6492 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6493 }
6494
6495 // This operation requires a non-_Complex floating-point number.
6496 if (!ElementTy->isRealFloatingType())
6497 return Diag(OrigArg->getBeginLoc(),
6498 diag::err_typecheck_call_invalid_unary_fp)
6499 << OrigArg->getType() << OrigArg->getSourceRange();
6500
6501 // __builtin_isfpclass has integer parameter that specify test mask. It is
6502 // passed in (...), so it should be analyzed completely here.
6503 if (IsFPClass) {
6504 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6505 return true;
6506
6508 TheCall->getArg(NumArgs - 1), Context.IntTy, AssignmentAction::Passing);
6509 if (!MaskRes.isUsable())
6510 return true;
6511 TheCall->setArg(NumArgs - 1, MaskRes.get());
6512 }
6513
6514 // TODO: enable this code to all classification functions.
6515 if (IsFPClass) {
6516 QualType ResultTy;
6517 if (!VectorResultTy.isNull())
6518 ResultTy = VectorResultTy;
6519 else
6520 ResultTy = Context.IntTy;
6521 TheCall->setType(ResultTy);
6522 }
6523
6524 return false;
6525}
6526
6527bool Sema::BuiltinComplex(CallExpr *TheCall) {
6528 if (checkArgCount(TheCall, 2))
6529 return true;
6530
6531 bool Dependent = false;
6532 for (unsigned I = 0; I != 2; ++I) {
6533 Expr *Arg = TheCall->getArg(I);
6534 QualType T = Arg->getType();
6535 if (T->isDependentType()) {
6536 Dependent = true;
6537 continue;
6538 }
6539
6540 // Despite supporting _Complex int, GCC requires a real floating point type
6541 // for the operands of __builtin_complex.
6542 if (!T->isRealFloatingType()) {
6543 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6544 << Arg->getType() << Arg->getSourceRange();
6545 }
6546
6547 ExprResult Converted = DefaultLvalueConversion(Arg);
6548 if (Converted.isInvalid())
6549 return true;
6550 TheCall->setArg(I, Converted.get());
6551 }
6552
6553 if (Dependent) {
6554 TheCall->setType(Context.DependentTy);
6555 return false;
6556 }
6557
6558 Expr *Real = TheCall->getArg(0);
6559 Expr *Imag = TheCall->getArg(1);
6560 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6561 return Diag(Real->getBeginLoc(),
6562 diag::err_typecheck_call_different_arg_types)
6563 << Real->getType() << Imag->getType()
6564 << Real->getSourceRange() << Imag->getSourceRange();
6565 }
6566
6567 TheCall->setType(Context.getComplexType(Real->getType()));
6568 return false;
6569}
6570
6571/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6572// This is declared to take (...), so we have to check everything.
6574 unsigned NumArgs = TheCall->getNumArgs();
6575 if (NumArgs < 2)
6576 return ExprError(Diag(TheCall->getEndLoc(),
6577 diag::err_typecheck_call_too_few_args_at_least)
6578 << 0 /*function call*/ << 2 << NumArgs
6579 << /*is non object*/ 0 << TheCall->getSourceRange());
6580
6581 // Determine which of the following types of shufflevector we're checking:
6582 // 1) unary, vector mask: (lhs, mask)
6583 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6584 QualType ResType = TheCall->getArg(0)->getType();
6585 unsigned NumElements = 0;
6586
6587 if (!TheCall->getArg(0)->isTypeDependent() &&
6588 !TheCall->getArg(1)->isTypeDependent()) {
6589 QualType LHSType = TheCall->getArg(0)->getType();
6590 QualType RHSType = TheCall->getArg(1)->getType();
6591
6592 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6593 return ExprError(
6594 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6595 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6596 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6597 TheCall->getArg(1)->getEndLoc()));
6598
6599 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6600 unsigned NumResElements = NumArgs - 2;
6601
6602 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6603 // with mask. If so, verify that RHS is an integer vector type with the
6604 // same number of elts as lhs.
6605 if (NumArgs == 2) {
6606 auto *RHSVecType = RHSType->castAs<VectorType>();
6607 if (RHSVecType->getElementType()->isBooleanType() ||
6608 !RHSVecType->getElementType()->isIntegerType()) {
6609 return ExprError(
6610 Diag(TheCall->getBeginLoc(), diag::err_builtin_invalid_arg_type)
6611 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6612 << /*no fp*/ 0 << RHSType
6613 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6614 TheCall->getArg(1)->getEndLoc()));
6615 }
6616
6617 if (RHSVecType->getNumElements() != NumElements)
6618 return ExprError(Diag(TheCall->getBeginLoc(),
6619 diag::err_typecheck_vector_lengths_not_equal)
6620 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6621 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6622 TheCall->getArg(1)->getEndLoc()));
6623 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6624 return ExprError(Diag(TheCall->getBeginLoc(),
6625 diag::err_vec_builtin_incompatible_vector)
6626 << TheCall->getDirectCallee()
6627 << /*isMoreThanTwoArgs*/ false
6628 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6629 TheCall->getArg(1)->getEndLoc()));
6630 } else if (NumElements != NumResElements) {
6631 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6632 ResType = ResType->isExtVectorType()
6633 ? Context.getExtVectorType(EltType, NumResElements)
6634 : Context.getVectorType(EltType, NumResElements,
6636 }
6637 }
6638
6639 for (unsigned I = 2; I != NumArgs; ++I) {
6640 Expr *Arg = TheCall->getArg(I);
6641 if (Arg->isTypeDependent() || Arg->isValueDependent())
6642 continue;
6643
6644 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6645 if (!Result)
6646 return ExprError(Diag(TheCall->getBeginLoc(),
6647 diag::err_shufflevector_nonconstant_argument)
6648 << Arg->getSourceRange());
6649
6650 // Allow -1 which will be translated to undef in the IR.
6651 if (Result->isSigned() && Result->isAllOnes())
6652 ;
6653 else if (Result->getActiveBits() > 64 ||
6654 Result->getZExtValue() >= NumElements * 2)
6655 return ExprError(Diag(TheCall->getBeginLoc(),
6656 diag::err_shufflevector_argument_too_large)
6657 << Arg->getSourceRange());
6658
6659 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6660 }
6661
6662 auto *Result = new (Context) ShuffleVectorExpr(
6663 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6664 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6665
6666 // All moved to Result.
6667 TheCall->shrinkNumArgs(0);
6668 return Result;
6669}
6670
6672 SourceLocation BuiltinLoc,
6673 SourceLocation RParenLoc) {
6676 QualType DstTy = TInfo->getType();
6677 QualType SrcTy = E->getType();
6678
6679 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6680 return ExprError(Diag(BuiltinLoc,
6681 diag::err_convertvector_non_vector)
6682 << E->getSourceRange());
6683 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6684 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6685 << "second"
6686 << "__builtin_convertvector");
6687
6688 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6689 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6690 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6691 if (SrcElts != DstElts)
6692 return ExprError(Diag(BuiltinLoc,
6693 diag::err_convertvector_incompatible_vector)
6694 << E->getSourceRange());
6695 }
6696
6697 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6698 RParenLoc, CurFPFeatureOverrides());
6699}
6700
6701bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6702 unsigned NumArgs = TheCall->getNumArgs();
6703
6704 if (NumArgs > 3)
6705 return Diag(TheCall->getEndLoc(),
6706 diag::err_typecheck_call_too_many_args_at_most)
6707 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6708 << TheCall->getSourceRange();
6709
6710 // Argument 0 is checked for us and the remaining arguments must be
6711 // constant integers.
6712 for (unsigned i = 1; i != NumArgs; ++i) {
6713 if (convertArgumentToType(TheCall->getArgs()[i], Context.IntTy))
6714 return true;
6715 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6716 return true;
6717 }
6718
6719 return false;
6720}
6721
6722bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6723 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6724 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6725 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6726 if (checkArgCount(TheCall, 1))
6727 return true;
6728 Expr *Arg = TheCall->getArg(0);
6729 if (Arg->isInstantiationDependent())
6730 return false;
6731
6732 QualType ArgTy = Arg->getType();
6733 if (!ArgTy->hasFloatingRepresentation())
6734 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6735 << ArgTy;
6736 if (Arg->isLValue()) {
6737 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6738 TheCall->setArg(0, FirstArg.get());
6739 }
6740 TheCall->setType(TheCall->getArg(0)->getType());
6741 return false;
6742}
6743
6744bool Sema::BuiltinAssume(CallExpr *TheCall) {
6745 Expr *Arg = TheCall->getArg(0);
6746 if (Arg->isInstantiationDependent()) return false;
6747
6748 if (Arg->HasSideEffects(Context))
6749 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6750 << Arg->getSourceRange()
6751 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6752
6753 return false;
6754}
6755
6756bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6757 // The alignment must be a constant integer.
6758 Expr *Arg = TheCall->getArg(1);
6759
6760 // We can't check the value of a dependent argument.
6761 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6762 if (const auto *UE =
6763 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6764 if (UE->getKind() == UETT_AlignOf ||
6765 UE->getKind() == UETT_PreferredAlignOf)
6766 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6767 << Arg->getSourceRange();
6768
6769 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6770
6771 if (!Result.isPowerOf2())
6772 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6773 << Arg->getSourceRange();
6774
6775 if (Result < Context.getCharWidth())
6776 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6777 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6778
6779 if (Result > std::numeric_limits<int32_t>::max())
6780 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6781 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6782 }
6783
6784 return false;
6785}
6786
6787bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6788 if (checkArgCountRange(TheCall, 2, 3))
6789 return true;
6790
6791 unsigned NumArgs = TheCall->getNumArgs();
6792 Expr *FirstArg = TheCall->getArg(0);
6793
6794 {
6795 ExprResult FirstArgResult =
6797 if (!FirstArgResult.get()->getType()->isPointerType()) {
6798 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6799 << TheCall->getSourceRange();
6800 return true;
6801 }
6802 TheCall->setArg(0, FirstArgResult.get());
6803 }
6804
6805 // The alignment must be a constant integer.
6806 Expr *SecondArg = TheCall->getArg(1);
6807
6808 // We can't check the value of a dependent argument.
6809 if (!SecondArg->isValueDependent()) {
6810 llvm::APSInt Result;
6811 if (BuiltinConstantArg(TheCall, 1, Result))
6812 return true;
6813
6814 if (!Result.isPowerOf2())
6815 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6816 << SecondArg->getSourceRange();
6817
6819 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6820 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6821
6822 TheCall->setArg(1,
6824 }
6825
6826 if (NumArgs > 2) {
6827 Expr *ThirdArg = TheCall->getArg(2);
6828 if (convertArgumentToType(ThirdArg, Context.getSizeType()))
6829 return true;
6830 TheCall->setArg(2, ThirdArg);
6831 }
6832
6833 return false;
6834}
6835
6836bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6837 unsigned BuiltinID =
6838 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6839 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6840
6841 unsigned NumArgs = TheCall->getNumArgs();
6842 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6843 if (NumArgs < NumRequiredArgs) {
6844 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6845 << 0 /* function call */ << NumRequiredArgs << NumArgs
6846 << /*is non object*/ 0 << TheCall->getSourceRange();
6847 }
6848 if (NumArgs >= NumRequiredArgs + 0x100) {
6849 return Diag(TheCall->getEndLoc(),
6850 diag::err_typecheck_call_too_many_args_at_most)
6851 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6852 << /*is non object*/ 0 << TheCall->getSourceRange();
6853 }
6854 unsigned i = 0;
6855
6856 // For formatting call, check buffer arg.
6857 if (!IsSizeCall) {
6858 ExprResult Arg(TheCall->getArg(i));
6859 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6860 Context, Context.VoidPtrTy, false);
6861 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6862 if (Arg.isInvalid())
6863 return true;
6864 TheCall->setArg(i, Arg.get());
6865 i++;
6866 }
6867
6868 // Check string literal arg.
6869 unsigned FormatIdx = i;
6870 {
6871 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6872 if (Arg.isInvalid())
6873 return true;
6874 TheCall->setArg(i, Arg.get());
6875 i++;
6876 }
6877
6878 // Make sure variadic args are scalar.
6879 unsigned FirstDataArg = i;
6880 while (i < NumArgs) {
6882 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6883 if (Arg.isInvalid())
6884 return true;
6885 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6886 if (ArgSize.getQuantity() >= 0x100) {
6887 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6888 << i << (int)ArgSize.getQuantity() << 0xff
6889 << TheCall->getSourceRange();
6890 }
6891 TheCall->setArg(i, Arg.get());
6892 i++;
6893 }
6894
6895 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6896 // call to avoid duplicate diagnostics.
6897 if (!IsSizeCall) {
6898 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6899 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6900 bool Success = CheckFormatArguments(
6901 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6903 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6904 if (!Success)
6905 return true;
6906 }
6907
6908 if (IsSizeCall) {
6909 TheCall->setType(Context.getSizeType());
6910 } else {
6911 TheCall->setType(Context.VoidPtrTy);
6912 }
6913 return false;
6914}
6915
6916bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6917 llvm::APSInt &Result) {
6918 Expr *Arg = TheCall->getArg(ArgNum);
6919
6920 if (Arg->isTypeDependent() || Arg->isValueDependent())
6921 return false;
6922
6923 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6924 if (!R) {
6925 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6926 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6927 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6928 << FDecl->getDeclName() << Arg->getSourceRange();
6929 }
6930 Result = *R;
6931
6932 return false;
6933}
6934
6935bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6936 int High, bool RangeIsError) {
6938 return false;
6939 llvm::APSInt Result;
6940
6941 // We can't check the value of a dependent argument.
6942 Expr *Arg = TheCall->getArg(ArgNum);
6943 if (Arg->isTypeDependent() || Arg->isValueDependent())
6944 return false;
6945
6946 // Check constant-ness first.
6947 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6948 return true;
6949
6950 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6951 if (RangeIsError)
6952 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6953 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6954 else
6955 // Defer the warning until we know if the code will be emitted so that
6956 // dead code can ignore this.
6957 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6958 PDiag(diag::warn_argument_invalid_range)
6959 << toString(Result, 10) << Low << High
6960 << Arg->getSourceRange());
6961 }
6962
6963 return false;
6964}
6965
6966bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6967 unsigned Num) {
6968 llvm::APSInt Result;
6969
6970 // We can't check the value of a dependent argument.
6971 Expr *Arg = TheCall->getArg(ArgNum);
6972 if (Arg->isTypeDependent() || Arg->isValueDependent())
6973 return false;
6974
6975 // Check constant-ness first.
6976 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6977 return true;
6978
6979 if (Result.getSExtValue() % Num != 0)
6980 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6981 << Num << Arg->getSourceRange();
6982
6983 return false;
6984}
6985
6986bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6987 llvm::APSInt Result;
6988
6989 // We can't check the value of a dependent argument.
6990 Expr *Arg = TheCall->getArg(ArgNum);
6991 if (Arg->isTypeDependent() || Arg->isValueDependent())
6992 return false;
6993
6994 // Check constant-ness first.
6995 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6996 return true;
6997
6998 if (Result.isPowerOf2())
6999 return false;
7000
7001 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7002 << Arg->getSourceRange();
7003}
7004
7005static bool IsShiftedByte(llvm::APSInt Value) {
7006 if (Value.isNegative())
7007 return false;
7008
7009 // Check if it's a shifted byte, by shifting it down
7010 while (true) {
7011 // If the value fits in the bottom byte, the check passes.
7012 if (Value < 0x100)
7013 return true;
7014
7015 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7016 // fails.
7017 if ((Value & 0xFF) != 0)
7018 return false;
7019
7020 // If the bottom 8 bits are all 0, but something above that is nonzero,
7021 // then shifting the value right by 8 bits won't affect whether it's a
7022 // shifted byte or not. So do that, and go round again.
7023 Value >>= 8;
7024 }
7025}
7026
7027bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7028 unsigned ArgBits) {
7029 llvm::APSInt Result;
7030
7031 // We can't check the value of a dependent argument.
7032 Expr *Arg = TheCall->getArg(ArgNum);
7033 if (Arg->isTypeDependent() || Arg->isValueDependent())
7034 return false;
7035
7036 // Check constant-ness first.
7037 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7038 return true;
7039
7040 // Truncate to the given size.
7041 Result = Result.getLoBits(ArgBits);
7042 Result.setIsUnsigned(true);
7043
7044 if (IsShiftedByte(Result))
7045 return false;
7046
7047 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7048 << Arg->getSourceRange();
7049}
7050
7052 unsigned ArgNum,
7053 unsigned ArgBits) {
7054 llvm::APSInt Result;
7055
7056 // We can't check the value of a dependent argument.
7057 Expr *Arg = TheCall->getArg(ArgNum);
7058 if (Arg->isTypeDependent() || Arg->isValueDependent())
7059 return false;
7060
7061 // Check constant-ness first.
7062 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7063 return true;
7064
7065 // Truncate to the given size.
7066 Result = Result.getLoBits(ArgBits);
7067 Result.setIsUnsigned(true);
7068
7069 // Check to see if it's in either of the required forms.
7070 if (IsShiftedByte(Result) ||
7071 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7072 return false;
7073
7074 return Diag(TheCall->getBeginLoc(),
7075 diag::err_argument_not_shifted_byte_or_xxff)
7076 << Arg->getSourceRange();
7077}
7078
7079bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7080 if (!Context.getTargetInfo().hasSjLjLowering())
7081 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7082 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7083
7084 Expr *Arg = TheCall->getArg(1);
7085 llvm::APSInt Result;
7086
7087 // TODO: This is less than ideal. Overload this to take a value.
7088 if (BuiltinConstantArg(TheCall, 1, Result))
7089 return true;
7090
7091 if (Result != 1)
7092 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7093 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7094
7095 return false;
7096}
7097
7098bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7099 if (!Context.getTargetInfo().hasSjLjLowering())
7100 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7101 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7102 return false;
7103}
7104
7105bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7106 if (checkArgCount(TheCall, 1))
7107 return true;
7108
7109 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
7110 if (ArgRes.isInvalid())
7111 return true;
7112
7113 // For simplicity, we support only limited expressions for the argument.
7114 // Specifically a flexible array member or a pointer with counted_by:
7115 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7116 // complex casting, which really shouldn't be a huge problem.
7117 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7118 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7119 return Diag(Arg->getBeginLoc(),
7120 diag::err_builtin_counted_by_ref_invalid_arg)
7121 << Arg->getSourceRange();
7122
7123 if (Arg->HasSideEffects(Context))
7124 return Diag(Arg->getBeginLoc(),
7125 diag::err_builtin_counted_by_ref_has_side_effects)
7126 << Arg->getSourceRange();
7127
7128 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7129 const auto *CATy =
7130 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7131
7132 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7133 // Member has counted_by attribute - return pointer to count field
7134 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
7135 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7136 TheCall->setType(Context.getPointerType(CountFD->getType()));
7137 return false;
7138 }
7139 }
7140
7141 // FAMs and pointers without counted_by return void*
7142 QualType MemberTy = ME->getMemberDecl()->getType();
7143 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7144 return Diag(Arg->getBeginLoc(),
7145 diag::err_builtin_counted_by_ref_invalid_arg)
7146 << Arg->getSourceRange();
7147 } else {
7148 return Diag(Arg->getBeginLoc(),
7149 diag::err_builtin_counted_by_ref_invalid_arg)
7150 << Arg->getSourceRange();
7151 }
7152
7153 TheCall->setType(Context.getPointerType(Context.VoidTy));
7154 return false;
7155}
7156
7157/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7158/// It allows leaking and modification of bounds safety information.
7159bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7161 const CallExpr *CE =
7162 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7163 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7164 return false;
7165
7166 switch (K) {
7169 Diag(E->getExprLoc(),
7170 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7171 << 0 << E->getSourceRange();
7172 break;
7174 Diag(E->getExprLoc(),
7175 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7176 << 1 << E->getSourceRange();
7177 break;
7179 Diag(E->getExprLoc(),
7180 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7181 << 2 << E->getSourceRange();
7182 break;
7184 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7185 << 0 << E->getSourceRange();
7186 break;
7188 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7189 << 1 << E->getSourceRange();
7190 break;
7191 }
7192
7193 return true;
7194}
7195
7196namespace {
7197
7198class UncoveredArgHandler {
7199 enum { Unknown = -1, AllCovered = -2 };
7200
7201 signed FirstUncoveredArg = Unknown;
7202 SmallVector<const Expr *, 4> DiagnosticExprs;
7203
7204public:
7205 UncoveredArgHandler() = default;
7206
7207 bool hasUncoveredArg() const {
7208 return (FirstUncoveredArg >= 0);
7209 }
7210
7211 unsigned getUncoveredArg() const {
7212 assert(hasUncoveredArg() && "no uncovered argument");
7213 return FirstUncoveredArg;
7214 }
7215
7216 void setAllCovered() {
7217 // A string has been found with all arguments covered, so clear out
7218 // the diagnostics.
7219 DiagnosticExprs.clear();
7220 FirstUncoveredArg = AllCovered;
7221 }
7222
7223 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7224 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7225
7226 // Don't update if a previous string covers all arguments.
7227 if (FirstUncoveredArg == AllCovered)
7228 return;
7229
7230 // UncoveredArgHandler tracks the highest uncovered argument index
7231 // and with it all the strings that match this index.
7232 if (NewFirstUncoveredArg == FirstUncoveredArg)
7233 DiagnosticExprs.push_back(StrExpr);
7234 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7235 DiagnosticExprs.clear();
7236 DiagnosticExprs.push_back(StrExpr);
7237 FirstUncoveredArg = NewFirstUncoveredArg;
7238 }
7239 }
7240
7241 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7242};
7243
7244enum StringLiteralCheckType {
7245 SLCT_NotALiteral,
7246 SLCT_UncheckedLiteral,
7247 SLCT_CheckedLiteral
7248};
7249
7250} // namespace
7251
7252static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7253 BinaryOperatorKind BinOpKind,
7254 bool AddendIsRight) {
7255 unsigned BitWidth = Offset.getBitWidth();
7256 unsigned AddendBitWidth = Addend.getBitWidth();
7257 // There might be negative interim results.
7258 if (Addend.isUnsigned()) {
7259 Addend = Addend.zext(++AddendBitWidth);
7260 Addend.setIsSigned(true);
7261 }
7262 // Adjust the bit width of the APSInts.
7263 if (AddendBitWidth > BitWidth) {
7264 Offset = Offset.sext(AddendBitWidth);
7265 BitWidth = AddendBitWidth;
7266 } else if (BitWidth > AddendBitWidth) {
7267 Addend = Addend.sext(BitWidth);
7268 }
7269
7270 bool Ov = false;
7271 llvm::APSInt ResOffset = Offset;
7272 if (BinOpKind == BO_Add)
7273 ResOffset = Offset.sadd_ov(Addend, Ov);
7274 else {
7275 assert(AddendIsRight && BinOpKind == BO_Sub &&
7276 "operator must be add or sub with addend on the right");
7277 ResOffset = Offset.ssub_ov(Addend, Ov);
7278 }
7279
7280 // We add an offset to a pointer here so we should support an offset as big as
7281 // possible.
7282 if (Ov) {
7283 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7284 "index (intermediate) result too big");
7285 Offset = Offset.sext(2 * BitWidth);
7286 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7287 return;
7288 }
7289
7290 Offset = std::move(ResOffset);
7291}
7292
7293namespace {
7294
7295// This is a wrapper class around StringLiteral to support offsetted string
7296// literals as format strings. It takes the offset into account when returning
7297// the string and its length or the source locations to display notes correctly.
7298class FormatStringLiteral {
7299 const StringLiteral *FExpr;
7300 int64_t Offset;
7301
7302public:
7303 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7304 : FExpr(fexpr), Offset(Offset) {}
7305
7306 const StringLiteral *getFormatString() const { return FExpr; }
7307
7308 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7309
7310 unsigned getByteLength() const {
7311 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7312 }
7313
7314 unsigned getLength() const { return FExpr->getLength() - Offset; }
7315 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7316
7317 StringLiteralKind getKind() const { return FExpr->getKind(); }
7318
7319 QualType getType() const { return FExpr->getType(); }
7320
7321 bool isAscii() const { return FExpr->isOrdinary(); }
7322 bool isWide() const { return FExpr->isWide(); }
7323 bool isUTF8() const { return FExpr->isUTF8(); }
7324 bool isUTF16() const { return FExpr->isUTF16(); }
7325 bool isUTF32() const { return FExpr->isUTF32(); }
7326 bool isPascal() const { return FExpr->isPascal(); }
7327
7328 SourceLocation getLocationOfByte(
7329 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7330 const TargetInfo &Target, unsigned *StartToken = nullptr,
7331 unsigned *StartTokenByteOffset = nullptr) const {
7332 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7333 StartToken, StartTokenByteOffset);
7334 }
7335
7336 SourceLocation getBeginLoc() const LLVM_READONLY {
7337 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7338 }
7339
7340 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7341};
7342
7343} // namespace
7344
7345static void CheckFormatString(
7346 Sema &S, const FormatStringLiteral *FExpr,
7347 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7349 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7350 bool inFunctionCall, VariadicCallType CallType,
7351 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7352 bool IgnoreStringsWithoutSpecifiers);
7353
7354static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7355 const Expr *E);
7356
7357// Determine if an expression is a string literal or constant string.
7358// If this function returns false on the arguments to a function expecting a
7359// format string, we will usually need to emit a warning.
7360// True string literals are then checked by CheckFormatString.
7361static StringLiteralCheckType
7362checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7363 const Expr *E, ArrayRef<const Expr *> Args,
7364 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7365 unsigned firstDataArg, FormatStringType Type,
7366 VariadicCallType CallType, bool InFunctionCall,
7367 llvm::SmallBitVector &CheckedVarArgs,
7368 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7369 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7370 bool IgnoreStringsWithoutSpecifiers = false) {
7372 return SLCT_NotALiteral;
7373tryAgain:
7374 assert(Offset.isSigned() && "invalid offset");
7375
7376 if (E->isTypeDependent() || E->isValueDependent())
7377 return SLCT_NotALiteral;
7378
7379 E = E->IgnoreParenCasts();
7380
7382 // Technically -Wformat-nonliteral does not warn about this case.
7383 // The behavior of printf and friends in this case is implementation
7384 // dependent. Ideally if the format string cannot be null then
7385 // it should have a 'nonnull' attribute in the function prototype.
7386 return SLCT_UncheckedLiteral;
7387
7388 switch (E->getStmtClass()) {
7389 case Stmt::InitListExprClass:
7390 // Handle expressions like {"foobar"}.
7391 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7392 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7393 format_idx, firstDataArg, Type, CallType,
7394 /*InFunctionCall*/ false, CheckedVarArgs,
7395 UncoveredArg, Offset, CallerFormatParamIdx,
7396 IgnoreStringsWithoutSpecifiers);
7397 }
7398 return SLCT_NotALiteral;
7399 case Stmt::BinaryConditionalOperatorClass:
7400 case Stmt::ConditionalOperatorClass: {
7401 // The expression is a literal if both sub-expressions were, and it was
7402 // completely checked only if both sub-expressions were checked.
7405
7406 // Determine whether it is necessary to check both sub-expressions, for
7407 // example, because the condition expression is a constant that can be
7408 // evaluated at compile time.
7409 bool CheckLeft = true, CheckRight = true;
7410
7411 bool Cond;
7412 if (C->getCond()->EvaluateAsBooleanCondition(
7413 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
7414 if (Cond)
7415 CheckRight = false;
7416 else
7417 CheckLeft = false;
7418 }
7419
7420 // We need to maintain the offsets for the right and the left hand side
7421 // separately to check if every possible indexed expression is a valid
7422 // string literal. They might have different offsets for different string
7423 // literals in the end.
7424 StringLiteralCheckType Left;
7425 if (!CheckLeft)
7426 Left = SLCT_UncheckedLiteral;
7427 else {
7428 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7429 Args, APK, format_idx, firstDataArg, Type,
7430 CallType, InFunctionCall, CheckedVarArgs,
7431 UncoveredArg, Offset, CallerFormatParamIdx,
7432 IgnoreStringsWithoutSpecifiers);
7433 if (Left == SLCT_NotALiteral || !CheckRight) {
7434 return Left;
7435 }
7436 }
7437
7438 StringLiteralCheckType Right = checkFormatStringExpr(
7439 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7440 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7441 UncoveredArg, Offset, CallerFormatParamIdx,
7442 IgnoreStringsWithoutSpecifiers);
7443
7444 return (CheckLeft && Left < Right) ? Left : Right;
7445 }
7446
7447 case Stmt::ImplicitCastExprClass:
7448 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7449 goto tryAgain;
7450
7451 case Stmt::OpaqueValueExprClass:
7452 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7453 E = src;
7454 goto tryAgain;
7455 }
7456 return SLCT_NotALiteral;
7457
7458 case Stmt::PredefinedExprClass:
7459 // While __func__, etc., are technically not string literals, they
7460 // cannot contain format specifiers and thus are not a security
7461 // liability.
7462 return SLCT_UncheckedLiteral;
7463
7464 case Stmt::DeclRefExprClass: {
7465 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7466
7467 // As an exception, do not flag errors for variables binding to
7468 // const string literals.
7469 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7470 bool isConstant = false;
7471 QualType T = DR->getType();
7472
7473 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7474 isConstant = AT->getElementType().isConstant(S.Context);
7475 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7476 isConstant = T.isConstant(S.Context) &&
7477 PT->getPointeeType().isConstant(S.Context);
7478 } else if (T->isObjCObjectPointerType()) {
7479 // In ObjC, there is usually no "const ObjectPointer" type,
7480 // so don't check if the pointee type is constant.
7481 isConstant = T.isConstant(S.Context);
7482 }
7483
7484 if (isConstant) {
7485 if (const Expr *Init = VD->getAnyInitializer()) {
7486 // Look through initializers like const char c[] = { "foo" }
7487 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7488 if (InitList->isStringLiteralInit())
7489 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7490 }
7491 return checkFormatStringExpr(
7492 S, ReferenceFormatString, Init, Args, APK, format_idx,
7493 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7494 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7495 }
7496 }
7497
7498 // When the format argument is an argument of this function, and this
7499 // function also has the format attribute, there are several interactions
7500 // for which there shouldn't be a warning. For instance, when calling
7501 // v*printf from a function that has the printf format attribute, we
7502 // should not emit a warning about using `fmt`, even though it's not
7503 // constant, because the arguments have already been checked for the
7504 // caller of `logmessage`:
7505 //
7506 // __attribute__((format(printf, 1, 2)))
7507 // void logmessage(char const *fmt, ...) {
7508 // va_list ap;
7509 // va_start(ap, fmt);
7510 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7511 // ...
7512 // }
7513 //
7514 // Another interaction that we need to support is using a format string
7515 // specified by the format_matches attribute:
7516 //
7517 // __attribute__((format_matches(printf, 1, "%s %d")))
7518 // void logmessage(char const *fmt, const char *a, int b) {
7519 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7520 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7521 // ...
7522 // }
7523 //
7524 // Yet another interaction that we need to support is calling a variadic
7525 // format function from a format function that has fixed arguments. For
7526 // instance:
7527 //
7528 // __attribute__((format(printf, 1, 2)))
7529 // void logstring(char const *fmt, char const *str) {
7530 // printf(fmt, str); /* do not emit a warning about "fmt" */
7531 // }
7532 //
7533 // Same (and perhaps more relatably) for the variadic template case:
7534 //
7535 // template<typename... Args>
7536 // __attribute__((format(printf, 1, 2)))
7537 // void log(const char *fmt, Args&&... args) {
7538 // printf(fmt, forward<Args>(args)...);
7539 // /* do not emit a warning about "fmt" */
7540 // }
7541 //
7542 // Due to implementation difficulty, we only check the format, not the
7543 // format arguments, in all cases.
7544 //
7545 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7546 if (CallerFormatParamIdx)
7547 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7548 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7549 for (const auto *PVFormatMatches :
7550 D->specific_attrs<FormatMatchesAttr>()) {
7551 Sema::FormatStringInfo CalleeFSI;
7552 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7553 0, &CalleeFSI))
7554 continue;
7555 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7556 // If using the wrong type of format string, emit a diagnostic
7557 // here and stop checking to avoid irrelevant diagnostics.
7558 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7559 S.Diag(Args[format_idx]->getBeginLoc(),
7560 diag::warn_format_string_type_incompatible)
7561 << PVFormatMatches->getType()->getName()
7563 if (!InFunctionCall) {
7564 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7565 diag::note_format_string_defined);
7566 }
7567 return SLCT_UncheckedLiteral;
7568 }
7569 return checkFormatStringExpr(
7570 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7571 Args, APK, format_idx, firstDataArg, Type, CallType,
7572 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7573 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7574 }
7575 }
7576
7577 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7578 Sema::FormatStringInfo CallerFSI;
7579 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7580 PVFormat->getFirstArg(), &CallerFSI))
7581 continue;
7582 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7583 // We also check if the formats are compatible.
7584 // We can't pass a 'scanf' string to a 'printf' function.
7585 if (Type != S.GetFormatStringType(PVFormat)) {
7586 S.Diag(Args[format_idx]->getBeginLoc(),
7587 diag::warn_format_string_type_incompatible)
7588 << PVFormat->getType()->getName()
7590 if (!InFunctionCall) {
7591 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7592 }
7593 return SLCT_UncheckedLiteral;
7594 }
7595 // Lastly, check that argument passing kinds transition in a
7596 // way that makes sense:
7597 // from a caller with FAPK_VAList, allow FAPK_VAList
7598 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7599 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7600 // from a caller with FAPK_Variadic, allow FAPK_VAList
7601 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7606 return SLCT_UncheckedLiteral;
7607 }
7608 }
7609 }
7610 }
7611 }
7612 }
7613
7614 return SLCT_NotALiteral;
7615 }
7616
7617 case Stmt::CallExprClass:
7618 case Stmt::CXXMemberCallExprClass: {
7619 const CallExpr *CE = cast<CallExpr>(E);
7620 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7621 bool IsFirst = true;
7622 StringLiteralCheckType CommonResult;
7623 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7624 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7625 StringLiteralCheckType Result = checkFormatStringExpr(
7626 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7627 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7628 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7629 if (IsFirst) {
7630 CommonResult = Result;
7631 IsFirst = false;
7632 }
7633 }
7634 if (!IsFirst)
7635 return CommonResult;
7636
7637 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7638 unsigned BuiltinID = FD->getBuiltinID();
7639 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7640 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7641 const Expr *Arg = CE->getArg(0);
7642 return checkFormatStringExpr(
7643 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7644 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7645 UncoveredArg, Offset, CallerFormatParamIdx,
7646 IgnoreStringsWithoutSpecifiers);
7647 }
7648 }
7649 }
7650 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7651 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7652 format_idx, firstDataArg, Type, CallType,
7653 /*InFunctionCall*/ false, CheckedVarArgs,
7654 UncoveredArg, Offset, CallerFormatParamIdx,
7655 IgnoreStringsWithoutSpecifiers);
7656 return SLCT_NotALiteral;
7657 }
7658 case Stmt::ObjCMessageExprClass: {
7659 const auto *ME = cast<ObjCMessageExpr>(E);
7660 if (const auto *MD = ME->getMethodDecl()) {
7661 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7662 // As a special case heuristic, if we're using the method -[NSBundle
7663 // localizedStringForKey:value:table:], ignore any key strings that lack
7664 // format specifiers. The idea is that if the key doesn't have any
7665 // format specifiers then its probably just a key to map to the
7666 // localized strings. If it does have format specifiers though, then its
7667 // likely that the text of the key is the format string in the
7668 // programmer's language, and should be checked.
7669 const ObjCInterfaceDecl *IFace;
7670 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7671 IFace->getIdentifier()->isStr("NSBundle") &&
7672 MD->getSelector().isKeywordSelector(
7673 {"localizedStringForKey", "value", "table"})) {
7674 IgnoreStringsWithoutSpecifiers = true;
7675 }
7676
7677 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7678 return checkFormatStringExpr(
7679 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7680 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7681 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7682 }
7683 }
7684
7685 return SLCT_NotALiteral;
7686 }
7687 case Stmt::ObjCStringLiteralClass:
7688 case Stmt::StringLiteralClass: {
7689 const StringLiteral *StrE = nullptr;
7690
7691 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7692 StrE = ObjCFExpr->getString();
7693 else
7694 StrE = cast<StringLiteral>(E);
7695
7696 if (StrE) {
7697 if (Offset.isNegative() || Offset > StrE->getLength()) {
7698 // TODO: It would be better to have an explicit warning for out of
7699 // bounds literals.
7700 return SLCT_NotALiteral;
7701 }
7702 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7703 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7704 format_idx, firstDataArg, Type, InFunctionCall,
7705 CallType, CheckedVarArgs, UncoveredArg,
7706 IgnoreStringsWithoutSpecifiers);
7707 return SLCT_CheckedLiteral;
7708 }
7709
7710 return SLCT_NotALiteral;
7711 }
7712 case Stmt::BinaryOperatorClass: {
7713 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7714
7715 // A string literal + an int offset is still a string literal.
7716 if (BinOp->isAdditiveOp()) {
7717 Expr::EvalResult LResult, RResult;
7718
7719 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7720 LResult, S.Context, Expr::SE_NoSideEffects,
7722 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7723 RResult, S.Context, Expr::SE_NoSideEffects,
7725
7726 if (LIsInt != RIsInt) {
7727 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7728
7729 if (LIsInt) {
7730 if (BinOpKind == BO_Add) {
7731 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7732 E = BinOp->getRHS();
7733 goto tryAgain;
7734 }
7735 } else {
7736 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7737 E = BinOp->getLHS();
7738 goto tryAgain;
7739 }
7740 }
7741 }
7742
7743 return SLCT_NotALiteral;
7744 }
7745 case Stmt::UnaryOperatorClass: {
7746 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7747 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7748 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7749 Expr::EvalResult IndexResult;
7750 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7753 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7754 /*RHS is int*/ true);
7755 E = ASE->getBase();
7756 goto tryAgain;
7757 }
7758 }
7759
7760 return SLCT_NotALiteral;
7761 }
7762
7763 default:
7764 return SLCT_NotALiteral;
7765 }
7766}
7767
7768// If this expression can be evaluated at compile-time,
7769// check if the result is a StringLiteral and return it
7770// otherwise return nullptr
7772 const Expr *E) {
7774 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7775 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7776 if (isa_and_nonnull<StringLiteral>(LVE))
7777 return LVE;
7778 }
7779 return nullptr;
7780}
7781
7783 switch (FST) {
7785 return "scanf";
7787 return "printf";
7789 return "NSString";
7791 return "strftime";
7793 return "strfmon";
7795 return "kprintf";
7797 return "freebsd_kprintf";
7799 return "os_log";
7800 default:
7801 return "<unknown>";
7802 }
7803}
7804
7806 return llvm::StringSwitch<FormatStringType>(Flavor)
7807 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7808 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7810 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7811 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7812 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7813 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7815 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7816 .Case("os_trace", FormatStringType::OSLog)
7817 .Case("os_log", FormatStringType::OSLog)
7818 .Default(FormatStringType::Unknown);
7819}
7820
7822 return GetFormatStringType(Format->getType()->getName());
7823}
7824
7825FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7826 return GetFormatStringType(Format->getType()->getName());
7827}
7828
7829bool Sema::CheckFormatArguments(const FormatAttr *Format,
7830 ArrayRef<const Expr *> Args, bool IsCXXMember,
7831 VariadicCallType CallType, SourceLocation Loc,
7832 SourceRange Range,
7833 llvm::SmallBitVector &CheckedVarArgs) {
7834 FormatStringInfo FSI;
7835 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7836 IsCXXMember,
7837 CallType != VariadicCallType::DoesNotApply, &FSI))
7838 return CheckFormatArguments(
7839 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7840 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7841 return false;
7842}
7843
7844bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7845 ArrayRef<const Expr *> Args, bool IsCXXMember,
7846 VariadicCallType CallType, SourceLocation Loc,
7847 SourceRange Range,
7848 llvm::SmallBitVector &CheckedVarArgs) {
7849 FormatStringInfo FSI;
7850 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7851 &FSI)) {
7852 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7853 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7854 Format->getFormatString(), FSI.FormatIdx,
7855 FSI.FirstDataArg, GetFormatStringType(Format),
7856 CallType, Loc, Range, CheckedVarArgs);
7857 }
7858 return false;
7859}
7860
7863 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7864 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7865 SourceLocation Loc) {
7866 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7867 return false;
7868
7870 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7871 return false;
7872 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7873
7874 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7875
7876 // Find the offset to convert between attribute and parameter indexes.
7877 unsigned CallerArgumentIndexOffset =
7878 hasImplicitObjectParameter(Caller) ? 2 : 1;
7879
7880 unsigned FirstArgumentIndex = -1;
7881 switch (APK) {
7884 // As an extension, clang allows the format attribute on non-variadic
7885 // functions.
7886 // Caller must have fixed arguments to pass them to a fixed or variadic
7887 // function. Try to match caller and callee arguments. If successful, then
7888 // emit a diag with the caller idx, otherwise we can't determine the callee
7889 // arguments.
7890 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7891 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7892 // There aren't enough arguments in the caller to pass to callee.
7893 return false;
7894 }
7895 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7896 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7897 const auto *Arg =
7898 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7899 if (!Arg)
7900 return false;
7901 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7902 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7903 return false;
7904 }
7905 FirstArgumentIndex =
7906 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7907 break;
7908 }
7910 // Caller arguments are either variadic or a va_list.
7911 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7912 ? (NumCallerParams + CallerArgumentIndexOffset)
7913 : 0;
7914 break;
7916 // The callee has a format_matches attribute. We will emit that instead.
7917 if (!ReferenceFormatString)
7918 return false;
7919 break;
7920 }
7921
7922 // Emit the diagnostic and fixit.
7923 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7924 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7925 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7926 do {
7927 std::string Attr, Fixit;
7928 llvm::raw_string_ostream AttrOS(Attr);
7930 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7931 << FirstArgumentIndex << ")";
7932 } else {
7933 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7934 << ", \"";
7935 AttrOS.write_escaped(ReferenceFormatString->getString());
7936 AttrOS << "\")";
7937 }
7938 AttrOS.flush();
7939 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7940 if (ND)
7941 DB << ND;
7942 else
7943 DB << "block";
7944
7945 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7946 if (isa<BlockDecl>(Caller))
7947 break;
7948
7949 SourceLocation SL;
7950 llvm::raw_string_ostream IS(Fixit);
7951 // The attribute goes at the start of the declaration in C/C++ functions
7952 // and methods, but after the declaration for Objective-C methods.
7953 if (isa<ObjCMethodDecl>(Caller)) {
7954 IS << ' ';
7955 SL = Caller->getEndLoc();
7956 }
7957 const LangOptions &LO = S->getLangOpts();
7958 if (LO.C23 || LO.CPlusPlus11)
7959 IS << "[[gnu::" << Attr << "]]";
7960 else if (LO.ObjC || LO.GNUMode)
7961 IS << "__attribute__((" << Attr << "))";
7962 else
7963 break;
7964 if (!isa<ObjCMethodDecl>(Caller)) {
7965 IS << ' ';
7966 SL = Caller->getBeginLoc();
7967 }
7968 IS.flush();
7969
7970 DB << FixItHint::CreateInsertion(SL, Fixit);
7971 } while (false);
7972
7973 // Add implicit format or format_matches attribute.
7975 Caller->addAttr(FormatAttr::CreateImplicit(
7976 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7977 FormatStringIndex, FirstArgumentIndex));
7978 } else {
7979 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7980 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7981 FormatStringIndex, ReferenceFormatString));
7982 }
7983
7984 {
7985 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7986 if (ND)
7987 DB << ND;
7988 else
7989 DB << "block";
7990 }
7991 return true;
7992}
7993
7994bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7996 StringLiteral *ReferenceFormatString,
7997 unsigned format_idx, unsigned firstDataArg,
7999 VariadicCallType CallType, SourceLocation Loc,
8000 SourceRange Range,
8001 llvm::SmallBitVector &CheckedVarArgs) {
8002 // CHECK: printf/scanf-like function is called with no format string.
8003 if (format_idx >= Args.size()) {
8004 Diag(Loc, diag::warn_missing_format_string) << Range;
8005 return false;
8006 }
8007
8008 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8009
8010 // CHECK: format string is not a string literal.
8011 //
8012 // Dynamically generated format strings are difficult to
8013 // automatically vet at compile time. Requiring that format strings
8014 // are string literals: (1) permits the checking of format strings by
8015 // the compiler and thereby (2) can practically remove the source of
8016 // many format string exploits.
8017
8018 // Format string can be either ObjC string (e.g. @"%d") or
8019 // C string (e.g. "%d")
8020 // ObjC string uses the same format specifiers as C string, so we can use
8021 // the same format string checking logic for both ObjC and C strings.
8022 UncoveredArgHandler UncoveredArg;
8023 std::optional<unsigned> CallerParamIdx;
8024 StringLiteralCheckType CT = checkFormatStringExpr(
8025 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
8026 firstDataArg, Type, CallType,
8027 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
8028 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
8029
8030 // Generate a diagnostic where an uncovered argument is detected.
8031 if (UncoveredArg.hasUncoveredArg()) {
8032 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8033 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8034 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8035 }
8036
8037 if (CT != SLCT_NotALiteral)
8038 // Literal format string found, check done!
8039 return CT == SLCT_CheckedLiteral;
8040
8041 // Do not emit diag when the string param is a macro expansion and the
8042 // format is either NSString or CFString. This is a hack to prevent
8043 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8044 // which are usually used in place of NS and CF string literals.
8045 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8047 SourceMgr.isInSystemMacro(FormatLoc))
8048 return false;
8049
8050 if (CallerParamIdx && CheckMissingFormatAttribute(
8051 this, Args, APK, ReferenceFormatString, format_idx,
8052 firstDataArg, Type, *CallerParamIdx, Loc))
8053 return false;
8054
8055 // Strftime is particular as it always uses a single 'time' argument,
8056 // so it is safe to pass a non-literal string.
8058 return false;
8059
8060 // If there are no arguments specified, warn with -Wformat-security, otherwise
8061 // warn only with -Wformat-nonliteral.
8062 if (Args.size() == firstDataArg) {
8063 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8064 << OrigFormatExpr->getSourceRange();
8065 switch (Type) {
8066 default:
8067 break;
8071 Diag(FormatLoc, diag::note_format_security_fixit)
8072 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8073 break;
8075 Diag(FormatLoc, diag::note_format_security_fixit)
8076 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8077 break;
8078 }
8079 } else {
8080 Diag(FormatLoc, diag::warn_format_nonliteral)
8081 << OrigFormatExpr->getSourceRange();
8082 }
8083 return false;
8084}
8085
8086namespace {
8087
8088class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8089protected:
8090 Sema &S;
8091 const FormatStringLiteral *FExpr;
8092 const Expr *OrigFormatExpr;
8093 const FormatStringType FSType;
8094 const unsigned FirstDataArg;
8095 const unsigned NumDataArgs;
8096 const char *Beg; // Start of format string.
8097 const Sema::FormatArgumentPassingKind ArgPassingKind;
8098 ArrayRef<const Expr *> Args;
8099 unsigned FormatIdx;
8100 llvm::SmallBitVector CoveredArgs;
8101 bool usesPositionalArgs = false;
8102 bool atFirstArg = true;
8103 bool inFunctionCall;
8104 VariadicCallType CallType;
8105 llvm::SmallBitVector &CheckedVarArgs;
8106 UncoveredArgHandler &UncoveredArg;
8107
8108public:
8109 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8110 const Expr *origFormatExpr, const FormatStringType type,
8111 unsigned firstDataArg, unsigned numDataArgs,
8112 const char *beg, Sema::FormatArgumentPassingKind APK,
8113 ArrayRef<const Expr *> Args, unsigned formatIdx,
8114 bool inFunctionCall, VariadicCallType callType,
8115 llvm::SmallBitVector &CheckedVarArgs,
8116 UncoveredArgHandler &UncoveredArg)
8117 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8118 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8119 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8120 inFunctionCall(inFunctionCall), CallType(callType),
8121 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8122 CoveredArgs.resize(numDataArgs);
8123 CoveredArgs.reset();
8124 }
8125
8126 bool HasFormatArguments() const {
8127 return ArgPassingKind == Sema::FAPK_Fixed ||
8128 ArgPassingKind == Sema::FAPK_Variadic;
8129 }
8130
8131 void DoneProcessing();
8132
8133 void HandleIncompleteSpecifier(const char *startSpecifier,
8134 unsigned specifierLen) override;
8135
8136 void HandleInvalidLengthModifier(
8137 const analyze_format_string::FormatSpecifier &FS,
8138 const analyze_format_string::ConversionSpecifier &CS,
8139 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8140
8141 void HandleNonStandardLengthModifier(
8142 const analyze_format_string::FormatSpecifier &FS,
8143 const char *startSpecifier, unsigned specifierLen);
8144
8145 void HandleNonStandardConversionSpecifier(
8146 const analyze_format_string::ConversionSpecifier &CS,
8147 const char *startSpecifier, unsigned specifierLen);
8148
8149 void HandlePosition(const char *startPos, unsigned posLen) override;
8150
8151 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8153
8154 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8155
8156 void HandleNullChar(const char *nullCharacter) override;
8157
8158 template <typename Range>
8159 static void
8160 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8161 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8162 bool IsStringLocation, Range StringRange,
8163 ArrayRef<FixItHint> Fixit = {});
8164
8165protected:
8166 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8167 const char *startSpec,
8168 unsigned specifierLen,
8169 const char *csStart, unsigned csLen);
8170
8171 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8172 const char *startSpec,
8173 unsigned specifierLen);
8174
8175 SourceRange getFormatStringRange();
8176 CharSourceRange getSpecifierRange(const char *startSpecifier,
8177 unsigned specifierLen);
8178 SourceLocation getLocationOfByte(const char *x);
8179
8180 const Expr *getDataArg(unsigned i) const;
8181
8182 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8183 const analyze_format_string::ConversionSpecifier &CS,
8184 const char *startSpecifier, unsigned specifierLen,
8185 unsigned argIndex);
8186
8187 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8188 const Expr *E, const char *startSpecifier,
8189 unsigned specifierLen);
8190
8191 template <typename Range>
8192 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8193 bool IsStringLocation, Range StringRange,
8194 ArrayRef<FixItHint> Fixit = {});
8195};
8196
8197} // namespace
8198
8199SourceRange CheckFormatHandler::getFormatStringRange() {
8200 return OrigFormatExpr->getSourceRange();
8201}
8202
8204CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8205 unsigned specifierLen) {
8206 SourceLocation Start = getLocationOfByte(startSpecifier);
8207 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8208
8209 // Advance the end SourceLocation by one due to half-open ranges.
8210 End = End.getLocWithOffset(1);
8211
8212 return CharSourceRange::getCharRange(Start, End);
8213}
8214
8215SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8216 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8218}
8219
8220void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8221 unsigned specifierLen) {
8222 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8223 getLocationOfByte(startSpecifier),
8224 /*IsStringLocation*/ true,
8225 getSpecifierRange(startSpecifier, specifierLen));
8226}
8227
8228bool CheckFormatHandler::CheckUnsupportedType(
8229 const analyze_format_string::ArgType &AT, const Expr *E,
8230 const char *StartSpecifier, unsigned SpecifierLen) {
8231 if (!AT.isUnsupported())
8232 return false;
8233
8234 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8236 E->getExprLoc(), /*IsStringLocation=*/false,
8237 getSpecifierRange(StartSpecifier, SpecifierLen));
8238 return true;
8239}
8240
8241void CheckFormatHandler::HandleInvalidLengthModifier(
8244 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8245 using namespace analyze_format_string;
8246
8247 const LengthModifier &LM = FS.getLengthModifier();
8248 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8249
8250 // See if we know how to fix this length modifier.
8251 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8252 if (FixedLM) {
8253 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8254 getLocationOfByte(LM.getStart()),
8255 /*IsStringLocation*/ true,
8256 getSpecifierRange(startSpecifier, specifierLen));
8257
8258 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8259 << FixedLM->toString()
8260 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8261
8262 } else {
8263 FixItHint Hint;
8264 if (DiagID == diag::warn_format_nonsensical_length)
8265 Hint = FixItHint::CreateRemoval(LMRange);
8266
8267 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8268 getLocationOfByte(LM.getStart()),
8269 /*IsStringLocation*/ true,
8270 getSpecifierRange(startSpecifier, specifierLen), Hint);
8271 }
8272}
8273
8274void CheckFormatHandler::HandleNonStandardLengthModifier(
8276 const char *startSpecifier, unsigned specifierLen) {
8277 using namespace analyze_format_string;
8278
8279 const LengthModifier &LM = FS.getLengthModifier();
8280 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8281
8282 // See if we know how to fix this length modifier.
8283 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8284 if (FixedLM) {
8285 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8286 << LM.toString() << 0,
8287 getLocationOfByte(LM.getStart()),
8288 /*IsStringLocation*/ true,
8289 getSpecifierRange(startSpecifier, specifierLen));
8290
8291 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8292 << FixedLM->toString()
8293 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8294
8295 } else {
8296 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8297 << LM.toString() << 0,
8298 getLocationOfByte(LM.getStart()),
8299 /*IsStringLocation*/ true,
8300 getSpecifierRange(startSpecifier, specifierLen));
8301 }
8302}
8303
8304void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8306 const char *startSpecifier, unsigned specifierLen) {
8307 using namespace analyze_format_string;
8308
8309 // See if we know how to fix this conversion specifier.
8310 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8311 if (FixedCS) {
8312 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8313 << CS.toString() << /*conversion specifier*/ 1,
8314 getLocationOfByte(CS.getStart()),
8315 /*IsStringLocation*/ true,
8316 getSpecifierRange(startSpecifier, specifierLen));
8317
8318 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8319 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8320 << FixedCS->toString()
8321 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8322 } else {
8323 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8324 << CS.toString() << /*conversion specifier*/ 1,
8325 getLocationOfByte(CS.getStart()),
8326 /*IsStringLocation*/ true,
8327 getSpecifierRange(startSpecifier, specifierLen));
8328 }
8329}
8330
8331void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8332 if (!S.getDiagnostics().isIgnored(
8333 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8334 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8335 getLocationOfByte(startPos),
8336 /*IsStringLocation*/ true,
8337 getSpecifierRange(startPos, posLen));
8338}
8339
8340void CheckFormatHandler::HandleInvalidPosition(
8341 const char *startSpecifier, unsigned specifierLen,
8343 if (!S.getDiagnostics().isIgnored(
8344 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8345 EmitFormatDiagnostic(
8346 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8347 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8348 getSpecifierRange(startSpecifier, specifierLen));
8349}
8350
8351void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8352 unsigned posLen) {
8353 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8354 SourceLocation()))
8355 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8356 getLocationOfByte(startPos),
8357 /*IsStringLocation*/ true,
8358 getSpecifierRange(startPos, posLen));
8359}
8360
8361void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8362 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8363 // The presence of a null character is likely an error.
8364 EmitFormatDiagnostic(
8365 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8366 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8367 getFormatStringRange());
8368 }
8369}
8370
8371// Note that this may return NULL if there was an error parsing or building
8372// one of the argument expressions.
8373const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8374 return Args[FirstDataArg + i];
8375}
8376
8377void CheckFormatHandler::DoneProcessing() {
8378 // Does the number of data arguments exceed the number of
8379 // format conversions in the format string?
8380 if (HasFormatArguments()) {
8381 // Find any arguments that weren't covered.
8382 CoveredArgs.flip();
8383 signed notCoveredArg = CoveredArgs.find_first();
8384 if (notCoveredArg >= 0) {
8385 assert((unsigned)notCoveredArg < NumDataArgs);
8386 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8387 } else {
8388 UncoveredArg.setAllCovered();
8389 }
8390 }
8391}
8392
8393void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8394 const Expr *ArgExpr) {
8395 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8396
8397 if (!ArgExpr)
8398 return;
8399
8400 SourceLocation Loc = ArgExpr->getBeginLoc();
8401
8402 if (S.getSourceManager().isInSystemMacro(Loc))
8403 return;
8404
8405 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8406 for (auto E : DiagnosticExprs)
8407 PDiag << E->getSourceRange();
8408
8409 CheckFormatHandler::EmitFormatDiagnostic(
8410 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8411 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8412}
8413
8414bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8415 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8416 unsigned specifierLen, const char *csStart, unsigned csLen) {
8417 bool keepGoing = true;
8418 if (argIndex < NumDataArgs) {
8419 // Consider the argument coverered, even though the specifier doesn't
8420 // make sense.
8421 CoveredArgs.set(argIndex);
8422 } else {
8423 // If argIndex exceeds the number of data arguments we
8424 // don't issue a warning because that is just a cascade of warnings (and
8425 // they may have intended '%%' anyway). We don't want to continue processing
8426 // the format string after this point, however, as we will like just get
8427 // gibberish when trying to match arguments.
8428 keepGoing = false;
8429 }
8430
8431 StringRef Specifier(csStart, csLen);
8432
8433 // If the specifier in non-printable, it could be the first byte of a UTF-8
8434 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8435 // hex value.
8436 std::string CodePointStr;
8437 if (!llvm::sys::locale::isPrint(*csStart)) {
8438 llvm::UTF32 CodePoint;
8439 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8440 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8441 llvm::ConversionResult Result =
8442 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8443
8444 if (Result != llvm::conversionOK) {
8445 unsigned char FirstChar = *csStart;
8446 CodePoint = (llvm::UTF32)FirstChar;
8447 }
8448
8449 llvm::raw_string_ostream OS(CodePointStr);
8450 if (CodePoint < 256)
8451 OS << "\\x" << llvm::format("%02x", CodePoint);
8452 else if (CodePoint <= 0xFFFF)
8453 OS << "\\u" << llvm::format("%04x", CodePoint);
8454 else
8455 OS << "\\U" << llvm::format("%08x", CodePoint);
8456 Specifier = CodePointStr;
8457 }
8458
8459 EmitFormatDiagnostic(
8460 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8461 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8462
8463 return keepGoing;
8464}
8465
8466void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8467 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8468 EmitFormatDiagnostic(
8469 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8470 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8471}
8472
8473bool CheckFormatHandler::CheckNumArgs(
8476 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8477
8478 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8479 PartialDiagnostic PDiag =
8481 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8482 << (argIndex + 1) << NumDataArgs)
8483 : S.PDiag(diag::warn_printf_insufficient_data_args);
8484 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8485 /*IsStringLocation*/ true,
8486 getSpecifierRange(startSpecifier, specifierLen));
8487
8488 // Since more arguments than conversion tokens are given, by extension
8489 // all arguments are covered, so mark this as so.
8490 UncoveredArg.setAllCovered();
8491 return false;
8492 }
8493 return true;
8494}
8495
8496template <typename Range>
8497void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8498 SourceLocation Loc,
8499 bool IsStringLocation,
8500 Range StringRange,
8501 ArrayRef<FixItHint> FixIt) {
8502 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8503 IsStringLocation, StringRange, FixIt);
8504}
8505
8506/// If the format string is not within the function call, emit a note
8507/// so that the function call and string are in diagnostic messages.
8508///
8509/// \param InFunctionCall if true, the format string is within the function
8510/// call and only one diagnostic message will be produced. Otherwise, an
8511/// extra note will be emitted pointing to location of the format string.
8512///
8513/// \param ArgumentExpr the expression that is passed as the format string
8514/// argument in the function call. Used for getting locations when two
8515/// diagnostics are emitted.
8516///
8517/// \param PDiag the callee should already have provided any strings for the
8518/// diagnostic message. This function only adds locations and fixits
8519/// to diagnostics.
8520///
8521/// \param Loc primary location for diagnostic. If two diagnostics are
8522/// required, one will be at Loc and a new SourceLocation will be created for
8523/// the other one.
8524///
8525/// \param IsStringLocation if true, Loc points to the format string should be
8526/// used for the note. Otherwise, Loc points to the argument list and will
8527/// be used with PDiag.
8528///
8529/// \param StringRange some or all of the string to highlight. This is
8530/// templated so it can accept either a CharSourceRange or a SourceRange.
8531///
8532/// \param FixIt optional fix it hint for the format string.
8533template <typename Range>
8534void CheckFormatHandler::EmitFormatDiagnostic(
8535 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8536 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8537 Range StringRange, ArrayRef<FixItHint> FixIt) {
8538 if (InFunctionCall) {
8539 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8540 D << StringRange;
8541 D << FixIt;
8542 } else {
8543 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8544 << ArgumentExpr->getSourceRange();
8545
8547 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8548 diag::note_format_string_defined);
8549
8550 Note << StringRange;
8551 Note << FixIt;
8552 }
8553}
8554
8555//===--- CHECK: Printf format string checking -----------------------------===//
8556
8557namespace {
8558
8559class CheckPrintfHandler : public CheckFormatHandler {
8560public:
8561 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8562 const Expr *origFormatExpr, const FormatStringType type,
8563 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8564 const char *beg, Sema::FormatArgumentPassingKind APK,
8565 ArrayRef<const Expr *> Args, unsigned formatIdx,
8566 bool inFunctionCall, VariadicCallType CallType,
8567 llvm::SmallBitVector &CheckedVarArgs,
8568 UncoveredArgHandler &UncoveredArg)
8569 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8570 numDataArgs, beg, APK, Args, formatIdx,
8571 inFunctionCall, CallType, CheckedVarArgs,
8572 UncoveredArg) {}
8573
8574 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8575
8576 /// Returns true if '%@' specifiers are allowed in the format string.
8577 bool allowsObjCArg() const {
8578 return FSType == FormatStringType::NSString ||
8579 FSType == FormatStringType::OSLog ||
8580 FSType == FormatStringType::OSTrace;
8581 }
8582
8583 bool HandleInvalidPrintfConversionSpecifier(
8584 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8585 unsigned specifierLen) override;
8586
8587 void handleInvalidMaskType(StringRef MaskType) override;
8588
8589 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8590 const char *startSpecifier, unsigned specifierLen,
8591 const TargetInfo &Target) override;
8592 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8593 const char *StartSpecifier, unsigned SpecifierLen,
8594 const Expr *E);
8595
8596 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8597 unsigned k, const char *startSpecifier,
8598 unsigned specifierLen);
8599 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8600 const analyze_printf::OptionalAmount &Amt,
8601 unsigned type, const char *startSpecifier,
8602 unsigned specifierLen);
8603 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8604 const analyze_printf::OptionalFlag &flag,
8605 const char *startSpecifier, unsigned specifierLen);
8606 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8607 const analyze_printf::OptionalFlag &ignoredFlag,
8608 const analyze_printf::OptionalFlag &flag,
8609 const char *startSpecifier, unsigned specifierLen);
8610 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8611
8612 void HandleEmptyObjCModifierFlag(const char *startFlag,
8613 unsigned flagLen) override;
8614
8615 void HandleInvalidObjCModifierFlag(const char *startFlag,
8616 unsigned flagLen) override;
8617
8618 void
8619 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8620 const char *flagsEnd,
8621 const char *conversionPosition) override;
8622};
8623
8624/// Keeps around the information needed to verify that two specifiers are
8625/// compatible.
8626class EquatableFormatArgument {
8627public:
8628 enum SpecifierSensitivity : unsigned {
8629 SS_None,
8630 SS_Private,
8631 SS_Public,
8632 SS_Sensitive
8633 };
8634
8635 enum FormatArgumentRole : unsigned {
8636 FAR_Data,
8637 FAR_FieldWidth,
8638 FAR_Precision,
8639 FAR_Auxiliary, // FreeBSD kernel %b and %D
8640 };
8641
8642private:
8643 analyze_format_string::ArgType ArgType;
8644 analyze_format_string::LengthModifier LengthMod;
8645 StringRef SpecifierLetter;
8646 CharSourceRange Range;
8647 SourceLocation ElementLoc;
8648 FormatArgumentRole Role : 2;
8649 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8650 unsigned Position : 14;
8651 unsigned ModifierFor : 14; // not set for FAR_Data
8652
8653 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8654 bool InFunctionCall) const;
8655
8656public:
8657 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8658 analyze_format_string::LengthModifier LengthMod,
8659 StringRef SpecifierLetter,
8660 analyze_format_string::ArgType ArgType,
8661 FormatArgumentRole Role,
8662 SpecifierSensitivity Sensitivity, unsigned Position,
8663 unsigned ModifierFor)
8664 : ArgType(ArgType), LengthMod(LengthMod),
8665 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8666 Role(Role), Sensitivity(Sensitivity), Position(Position),
8667 ModifierFor(ModifierFor) {}
8668
8669 unsigned getPosition() const { return Position; }
8670 SourceLocation getSourceLocation() const { return ElementLoc; }
8671 CharSourceRange getSourceRange() const { return Range; }
8672 analyze_format_string::LengthModifier getLengthModifier() const {
8673 return LengthMod;
8674 }
8675 void setModifierFor(unsigned V) { ModifierFor = V; }
8676
8677 std::string buildFormatSpecifier() const {
8678 std::string result;
8679 llvm::raw_string_ostream(result)
8680 << getLengthModifier().toString() << SpecifierLetter;
8681 return result;
8682 }
8683
8684 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8685 const Expr *FmtExpr, bool InFunctionCall) const;
8686};
8687
8688/// Turns format strings into lists of EquatableSpecifier objects.
8689class DecomposePrintfHandler : public CheckPrintfHandler {
8690 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8691 bool HadError;
8692
8693 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8694 const Expr *origFormatExpr,
8695 const FormatStringType type, unsigned firstDataArg,
8696 unsigned numDataArgs, bool isObjC, const char *beg,
8698 ArrayRef<const Expr *> Args, unsigned formatIdx,
8699 bool inFunctionCall, VariadicCallType CallType,
8700 llvm::SmallBitVector &CheckedVarArgs,
8701 UncoveredArgHandler &UncoveredArg,
8702 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8703 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8704 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8705 inFunctionCall, CallType, CheckedVarArgs,
8706 UncoveredArg),
8707 Specs(Specs), HadError(false) {}
8708
8709public:
8710 static bool
8711 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8712 FormatStringType type, bool IsObjC, bool InFunctionCall,
8713 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8714
8715 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8716 const char *startSpecifier,
8717 unsigned specifierLen,
8718 const TargetInfo &Target) override;
8719};
8720
8721} // namespace
8722
8723bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8724 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8725 unsigned specifierLen) {
8728
8729 return HandleInvalidConversionSpecifier(
8730 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8731 specifierLen, CS.getStart(), CS.getLength());
8732}
8733
8734void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8735 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8736}
8737
8738// Error out if struct or complex type argments are passed to os_log.
8740 QualType T) {
8741 if (FSType != FormatStringType::OSLog)
8742 return false;
8743 return T->isRecordType() || T->isComplexType();
8744}
8745
8746bool CheckPrintfHandler::HandleAmount(
8747 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8748 const char *startSpecifier, unsigned specifierLen) {
8749 if (Amt.hasDataArgument()) {
8750 if (HasFormatArguments()) {
8751 unsigned argIndex = Amt.getArgIndex();
8752 if (argIndex >= NumDataArgs) {
8753 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8754 << k,
8755 getLocationOfByte(Amt.getStart()),
8756 /*IsStringLocation*/ true,
8757 getSpecifierRange(startSpecifier, specifierLen));
8758 // Don't do any more checking. We will just emit
8759 // spurious errors.
8760 return false;
8761 }
8762
8763 // Type check the data argument. It should be an 'int'.
8764 // Although not in conformance with C99, we also allow the argument to be
8765 // an 'unsigned int' as that is a reasonably safe case. GCC also
8766 // doesn't emit a warning for that case.
8767 CoveredArgs.set(argIndex);
8768 const Expr *Arg = getDataArg(argIndex);
8769 if (!Arg)
8770 return false;
8771
8772 QualType T = Arg->getType();
8773
8774 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8775 assert(AT.isValid());
8776
8777 if (!AT.matchesType(S.Context, T)) {
8778 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8779 ? diag::err_printf_asterisk_wrong_type
8780 : diag::warn_printf_asterisk_wrong_type;
8781 EmitFormatDiagnostic(S.PDiag(DiagID)
8783 << T << Arg->getSourceRange(),
8784 getLocationOfByte(Amt.getStart()),
8785 /*IsStringLocation*/ true,
8786 getSpecifierRange(startSpecifier, specifierLen));
8787 // Don't do any more checking. We will just emit
8788 // spurious errors.
8789 return false;
8790 }
8791 }
8792 }
8793 return true;
8794}
8795
8796void CheckPrintfHandler::HandleInvalidAmount(
8798 const analyze_printf::OptionalAmount &Amt, unsigned type,
8799 const char *startSpecifier, unsigned specifierLen) {
8802
8803 FixItHint fixit =
8806 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8807 : FixItHint();
8808
8809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8810 << type << CS.toString(),
8811 getLocationOfByte(Amt.getStart()),
8812 /*IsStringLocation*/ true,
8813 getSpecifierRange(startSpecifier, specifierLen), fixit);
8814}
8815
8816void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8817 const analyze_printf::OptionalFlag &flag,
8818 const char *startSpecifier,
8819 unsigned specifierLen) {
8820 // Warn about pointless flag with a fixit removal.
8823 EmitFormatDiagnostic(
8824 S.PDiag(diag::warn_printf_nonsensical_flag)
8825 << flag.toString() << CS.toString(),
8826 getLocationOfByte(flag.getPosition()),
8827 /*IsStringLocation*/ true,
8828 getSpecifierRange(startSpecifier, specifierLen),
8829 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8830}
8831
8832void CheckPrintfHandler::HandleIgnoredFlag(
8834 const analyze_printf::OptionalFlag &ignoredFlag,
8835 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8836 unsigned specifierLen) {
8837 // Warn about ignored flag with a fixit removal.
8838 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8839 << ignoredFlag.toString() << flag.toString(),
8840 getLocationOfByte(ignoredFlag.getPosition()),
8841 /*IsStringLocation*/ true,
8842 getSpecifierRange(startSpecifier, specifierLen),
8844 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8845}
8846
8847void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8848 unsigned flagLen) {
8849 // Warn about an empty flag.
8850 EmitFormatDiagnostic(
8851 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8852 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8853}
8854
8855void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8856 unsigned flagLen) {
8857 // Warn about an invalid flag.
8858 auto Range = getSpecifierRange(startFlag, flagLen);
8859 StringRef flag(startFlag, flagLen);
8860 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8861 getLocationOfByte(startFlag),
8862 /*IsStringLocation*/ true, Range,
8864}
8865
8866void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8867 const char *flagsStart, const char *flagsEnd,
8868 const char *conversionPosition) {
8869 // Warn about using '[...]' without a '@' conversion.
8870 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8871 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8872 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8873 getLocationOfByte(conversionPosition),
8874 /*IsStringLocation*/ true, Range,
8876}
8877
8878void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8879 const Expr *FmtExpr,
8880 bool InFunctionCall) const {
8881 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8882 ElementLoc, true, Range);
8883}
8884
8885bool EquatableFormatArgument::VerifyCompatible(
8886 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8887 bool InFunctionCall) const {
8889 if (Role != Other.Role) {
8890 // diagnose and stop
8891 EmitDiagnostic(
8892 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8893 FmtExpr, InFunctionCall);
8894 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8895 return false;
8896 }
8897
8898 if (Role != FAR_Data) {
8899 if (ModifierFor != Other.ModifierFor) {
8900 // diagnose and stop
8901 EmitDiagnostic(S,
8902 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8903 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8904 FmtExpr, InFunctionCall);
8905 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8906 return false;
8907 }
8908 return true;
8909 }
8910
8911 bool HadError = false;
8912 if (Sensitivity != Other.Sensitivity) {
8913 // diagnose and continue
8914 EmitDiagnostic(S,
8915 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8916 << Sensitivity << Other.Sensitivity,
8917 FmtExpr, InFunctionCall);
8918 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8919 << 0 << Other.Range;
8920 }
8921
8922 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8923 case MK::Match:
8924 break;
8925
8926 case MK::MatchPromotion:
8927 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8928 // MatchPromotion is treated as a failure by format_matches.
8929 case MK::NoMatch:
8930 case MK::NoMatchTypeConfusion:
8931 case MK::NoMatchPromotionTypeConfusion:
8932 EmitDiagnostic(S,
8933 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8934 << buildFormatSpecifier()
8935 << Other.buildFormatSpecifier(),
8936 FmtExpr, InFunctionCall);
8937 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8938 << 0 << Other.Range;
8939 break;
8940
8941 case MK::NoMatchPedantic:
8942 EmitDiagnostic(S,
8943 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8944 << buildFormatSpecifier()
8945 << Other.buildFormatSpecifier(),
8946 FmtExpr, InFunctionCall);
8947 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8948 << 0 << Other.Range;
8949 break;
8950
8951 case MK::NoMatchSignedness:
8952 EmitDiagnostic(S,
8953 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8954 << buildFormatSpecifier()
8955 << Other.buildFormatSpecifier(),
8956 FmtExpr, InFunctionCall);
8957 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8958 << 0 << Other.Range;
8959 break;
8960 }
8961 return !HadError;
8962}
8963
8964bool DecomposePrintfHandler::GetSpecifiers(
8965 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8966 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8968 StringRef Data = FSL->getString();
8969 const char *Str = Data.data();
8970 llvm::SmallBitVector BV;
8971 UncoveredArgHandler UA;
8972 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8973 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8974 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8975 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8976 UA, Args);
8977
8979 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8981 H.DoneProcessing();
8982 if (H.HadError)
8983 return false;
8984
8985 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8986 const EquatableFormatArgument &B) {
8987 return A.getPosition() < B.getPosition();
8988 });
8989 return true;
8990}
8991
8992bool DecomposePrintfHandler::HandlePrintfSpecifier(
8993 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8994 unsigned specifierLen, const TargetInfo &Target) {
8995 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8996 specifierLen, Target)) {
8997 HadError = true;
8998 return false;
8999 }
9000
9001 // Do not add any specifiers to the list for %%. This is possibly incorrect
9002 // if using a precision/width with a data argument, but that combination is
9003 // meaningless and we wouldn't know which format to attach the
9004 // precision/width to.
9005 const auto &CS = FS.getConversionSpecifier();
9007 return true;
9008
9009 // have to patch these to have the right ModifierFor if they are used
9010 const unsigned Unset = ~0;
9011 unsigned FieldWidthIndex = Unset;
9012 unsigned PrecisionIndex = Unset;
9013
9014 // field width?
9015 const auto &FieldWidth = FS.getFieldWidth();
9016 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9017 FieldWidthIndex = Specs.size();
9018 Specs.emplace_back(
9019 getSpecifierRange(startSpecifier, specifierLen),
9020 getLocationOfByte(FieldWidth.getStart()),
9021 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
9022 FieldWidth.getArgType(S.Context),
9023 EquatableFormatArgument::FAR_FieldWidth,
9024 EquatableFormatArgument::SS_None,
9025 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9026 : FieldWidthIndex,
9027 0);
9028 }
9029 // precision?
9030 const auto &Precision = FS.getPrecision();
9031 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9032 PrecisionIndex = Specs.size();
9033 Specs.emplace_back(
9034 getSpecifierRange(startSpecifier, specifierLen),
9035 getLocationOfByte(Precision.getStart()),
9036 analyze_format_string::LengthModifier(), Precision.getCharacters(),
9037 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
9038 EquatableFormatArgument::SS_None,
9039 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9040 : PrecisionIndex,
9041 0);
9042 }
9043
9044 // this specifier
9045 unsigned SpecIndex =
9046 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9047 if (FieldWidthIndex != Unset)
9048 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9049 if (PrecisionIndex != Unset)
9050 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9051
9052 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9053 if (FS.isPrivate())
9054 Sensitivity = EquatableFormatArgument::SS_Private;
9055 else if (FS.isPublic())
9056 Sensitivity = EquatableFormatArgument::SS_Public;
9057 else if (FS.isSensitive())
9058 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9059 else
9060 Sensitivity = EquatableFormatArgument::SS_None;
9061
9062 Specs.emplace_back(
9063 getSpecifierRange(startSpecifier, specifierLen),
9064 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
9065 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
9066 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9067
9068 // auxiliary argument?
9071 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9072 getLocationOfByte(CS.getStart()),
9074 CS.getCharacters(),
9076 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9077 SpecIndex + 1, SpecIndex);
9078 }
9079 return true;
9080}
9081
9082// Determines if the specified is a C++ class or struct containing
9083// a member with the specified name and kind (e.g. a CXXMethodDecl named
9084// "c_str()").
9085template<typename MemberKind>
9087CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9088 auto *RD = Ty->getAsCXXRecordDecl();
9090
9091 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9092 return Results;
9093
9094 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9096 R.suppressDiagnostics();
9097
9098 // We just need to include all members of the right kind turned up by the
9099 // filter, at this point.
9100 if (S.LookupQualifiedName(R, RD))
9101 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9102 NamedDecl *decl = (*I)->getUnderlyingDecl();
9103 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9104 Results.insert(FK);
9105 }
9106 return Results;
9107}
9108
9109/// Check if we could call '.c_str()' on an object.
9110///
9111/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9112/// allow the call, or if it would be ambiguous).
9114 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9115
9116 MethodSet Results =
9117 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9118 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9119 MI != ME; ++MI)
9120 if ((*MI)->getMinRequiredArguments() == 0)
9121 return true;
9122 return false;
9123}
9124
9125// Check if a (w)string was passed when a (w)char* was needed, and offer a
9126// better diagnostic if so. AT is assumed to be valid.
9127// Returns true when a c_str() conversion method is found.
9128bool CheckPrintfHandler::checkForCStrMembers(
9129 const analyze_printf::ArgType &AT, const Expr *E) {
9130 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9131
9132 MethodSet Results =
9134
9135 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9136 MI != ME; ++MI) {
9137 const CXXMethodDecl *Method = *MI;
9138 if (Method->getMinRequiredArguments() == 0 &&
9139 AT.matchesType(S.Context, Method->getReturnType())) {
9140 // FIXME: Suggest parens if the expression needs them.
9142 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9143 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9144 return true;
9145 }
9146 }
9147
9148 return false;
9149}
9150
9151bool CheckPrintfHandler::HandlePrintfSpecifier(
9152 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9153 unsigned specifierLen, const TargetInfo &Target) {
9154 using namespace analyze_format_string;
9155 using namespace analyze_printf;
9156
9157 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9158
9159 if (FS.consumesDataArgument()) {
9160 if (atFirstArg) {
9161 atFirstArg = false;
9162 usesPositionalArgs = FS.usesPositionalArg();
9163 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9164 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9165 startSpecifier, specifierLen);
9166 return false;
9167 }
9168 }
9169
9170 // First check if the field width, precision, and conversion specifier
9171 // have matching data arguments.
9172 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9173 specifierLen)) {
9174 return false;
9175 }
9176
9177 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9178 specifierLen)) {
9179 return false;
9180 }
9181
9182 if (!CS.consumesDataArgument()) {
9183 // FIXME: Technically specifying a precision or field width here
9184 // makes no sense. Worth issuing a warning at some point.
9185 return true;
9186 }
9187
9188 // Consume the argument.
9189 unsigned argIndex = FS.getArgIndex();
9190 if (argIndex < NumDataArgs) {
9191 // The check to see if the argIndex is valid will come later.
9192 // We set the bit here because we may exit early from this
9193 // function if we encounter some other error.
9194 CoveredArgs.set(argIndex);
9195 }
9196
9197 // FreeBSD kernel extensions.
9198 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9199 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9200 // We need at least two arguments.
9201 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9202 return false;
9203
9204 if (HasFormatArguments()) {
9205 // Claim the second argument.
9206 CoveredArgs.set(argIndex + 1);
9207
9208 // Type check the first argument (int for %b, pointer for %D)
9209 const Expr *Ex = getDataArg(argIndex);
9210 const analyze_printf::ArgType &AT =
9211 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9212 ? ArgType(S.Context.IntTy)
9213 : ArgType::CPointerTy;
9214 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9215 EmitFormatDiagnostic(
9216 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9217 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9218 << false << Ex->getSourceRange(),
9219 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9220 getSpecifierRange(startSpecifier, specifierLen));
9221
9222 // Type check the second argument (char * for both %b and %D)
9223 Ex = getDataArg(argIndex + 1);
9225 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9226 EmitFormatDiagnostic(
9227 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9228 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9229 << false << Ex->getSourceRange(),
9230 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9231 getSpecifierRange(startSpecifier, specifierLen));
9232 }
9233 return true;
9234 }
9235
9236 // Check for using an Objective-C specific conversion specifier
9237 // in a non-ObjC literal.
9238 if (!allowsObjCArg() && CS.isObjCArg()) {
9239 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9240 specifierLen);
9241 }
9242
9243 // %P can only be used with os_log.
9244 if (FSType != FormatStringType::OSLog &&
9245 CS.getKind() == ConversionSpecifier::PArg) {
9246 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9247 specifierLen);
9248 }
9249
9250 // %n is not allowed with os_log.
9251 if (FSType == FormatStringType::OSLog &&
9252 CS.getKind() == ConversionSpecifier::nArg) {
9253 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9254 getLocationOfByte(CS.getStart()),
9255 /*IsStringLocation*/ false,
9256 getSpecifierRange(startSpecifier, specifierLen));
9257
9258 return true;
9259 }
9260
9261 // Only scalars are allowed for os_trace.
9262 if (FSType == FormatStringType::OSTrace &&
9263 (CS.getKind() == ConversionSpecifier::PArg ||
9264 CS.getKind() == ConversionSpecifier::sArg ||
9265 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9266 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9267 specifierLen);
9268 }
9269
9270 // Check for use of public/private annotation outside of os_log().
9271 if (FSType != FormatStringType::OSLog) {
9272 if (FS.isPublic().isSet()) {
9273 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9274 << "public",
9275 getLocationOfByte(FS.isPublic().getPosition()),
9276 /*IsStringLocation*/ false,
9277 getSpecifierRange(startSpecifier, specifierLen));
9278 }
9279 if (FS.isPrivate().isSet()) {
9280 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9281 << "private",
9282 getLocationOfByte(FS.isPrivate().getPosition()),
9283 /*IsStringLocation*/ false,
9284 getSpecifierRange(startSpecifier, specifierLen));
9285 }
9286 }
9287
9288 const llvm::Triple &Triple = Target.getTriple();
9289 if (CS.getKind() == ConversionSpecifier::nArg &&
9290 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9291 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9292 getLocationOfByte(CS.getStart()),
9293 /*IsStringLocation*/ false,
9294 getSpecifierRange(startSpecifier, specifierLen));
9295 }
9296
9297 // Check for invalid use of field width
9298 if (!FS.hasValidFieldWidth()) {
9299 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9300 startSpecifier, specifierLen);
9301 }
9302
9303 // Check for invalid use of precision
9304 if (!FS.hasValidPrecision()) {
9305 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9306 startSpecifier, specifierLen);
9307 }
9308
9309 // Precision is mandatory for %P specifier.
9310 if (CS.getKind() == ConversionSpecifier::PArg &&
9312 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9313 getLocationOfByte(startSpecifier),
9314 /*IsStringLocation*/ false,
9315 getSpecifierRange(startSpecifier, specifierLen));
9316 }
9317
9318 // Check each flag does not conflict with any other component.
9320 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9321 if (!FS.hasValidLeadingZeros())
9322 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9323 if (!FS.hasValidPlusPrefix())
9324 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9325 if (!FS.hasValidSpacePrefix())
9326 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9327 if (!FS.hasValidAlternativeForm())
9328 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9329 if (!FS.hasValidLeftJustified())
9330 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9331
9332 // Check that flags are not ignored by another flag
9333 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9334 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9335 startSpecifier, specifierLen);
9336 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9337 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9338 startSpecifier, specifierLen);
9339
9340 // Check the length modifier is valid with the given conversion specifier.
9342 S.getLangOpts()))
9343 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9344 diag::warn_format_nonsensical_length);
9345 else if (!FS.hasStandardLengthModifier())
9346 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9348 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9349 diag::warn_format_non_standard_conversion_spec);
9350
9352 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9353
9354 // The remaining checks depend on the data arguments.
9355 if (!HasFormatArguments())
9356 return true;
9357
9358 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9359 return false;
9360
9361 const Expr *Arg = getDataArg(argIndex);
9362 if (!Arg)
9363 return true;
9364
9365 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9366}
9367
9368static bool requiresParensToAddCast(const Expr *E) {
9369 // FIXME: We should have a general way to reason about operator
9370 // precedence and whether parens are actually needed here.
9371 // Take care of a few common cases where they aren't.
9372 const Expr *Inside = E->IgnoreImpCasts();
9373 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9374 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9375
9376 switch (Inside->getStmtClass()) {
9377 case Stmt::ArraySubscriptExprClass:
9378 case Stmt::CallExprClass:
9379 case Stmt::CharacterLiteralClass:
9380 case Stmt::CXXBoolLiteralExprClass:
9381 case Stmt::DeclRefExprClass:
9382 case Stmt::FloatingLiteralClass:
9383 case Stmt::IntegerLiteralClass:
9384 case Stmt::MemberExprClass:
9385 case Stmt::ObjCArrayLiteralClass:
9386 case Stmt::ObjCBoolLiteralExprClass:
9387 case Stmt::ObjCBoxedExprClass:
9388 case Stmt::ObjCDictionaryLiteralClass:
9389 case Stmt::ObjCEncodeExprClass:
9390 case Stmt::ObjCIvarRefExprClass:
9391 case Stmt::ObjCMessageExprClass:
9392 case Stmt::ObjCPropertyRefExprClass:
9393 case Stmt::ObjCStringLiteralClass:
9394 case Stmt::ObjCSubscriptRefExprClass:
9395 case Stmt::ParenExprClass:
9396 case Stmt::StringLiteralClass:
9397 case Stmt::UnaryOperatorClass:
9398 return false;
9399 default:
9400 return true;
9401 }
9402}
9403
9404static std::pair<QualType, StringRef>
9405shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9406 const Expr *E) {
9407 // Use a 'while' to peel off layers of typedefs.
9408 QualType TyTy = IntendedTy;
9409 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9410 StringRef Name = UserTy->getDecl()->getName();
9411 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9412 .Case("CFIndex", Context.getNSIntegerType())
9413 .Case("NSInteger", Context.getNSIntegerType())
9414 .Case("NSUInteger", Context.getNSUIntegerType())
9415 .Case("SInt32", Context.IntTy)
9416 .Case("UInt32", Context.UnsignedIntTy)
9417 .Default(QualType());
9418
9419 if (!CastTy.isNull())
9420 return std::make_pair(CastTy, Name);
9421
9422 TyTy = UserTy->desugar();
9423 }
9424
9425 // Strip parens if necessary.
9426 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9427 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9428 PE->getSubExpr());
9429
9430 // If this is a conditional expression, then its result type is constructed
9431 // via usual arithmetic conversions and thus there might be no necessary
9432 // typedef sugar there. Recurse to operands to check for NSInteger &
9433 // Co. usage condition.
9434 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9435 QualType TrueTy, FalseTy;
9436 StringRef TrueName, FalseName;
9437
9438 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9439 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9440 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9441 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9442
9443 if (TrueTy == FalseTy)
9444 return std::make_pair(TrueTy, TrueName);
9445 else if (TrueTy.isNull())
9446 return std::make_pair(FalseTy, FalseName);
9447 else if (FalseTy.isNull())
9448 return std::make_pair(TrueTy, TrueName);
9449 }
9450
9451 return std::make_pair(QualType(), StringRef());
9452}
9453
9454/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9455/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9456/// type do not count.
9458 const ImplicitCastExpr *ICE) {
9459 QualType From = ICE->getSubExpr()->getType();
9460 QualType To = ICE->getType();
9461 // It's an integer promotion if the destination type is the promoted
9462 // source type.
9463 if (ICE->getCastKind() == CK_IntegralCast &&
9465 S.Context.getPromotedIntegerType(From) == To)
9466 return true;
9467 // Look through vector types, since we do default argument promotion for
9468 // those in OpenCL.
9469 if (const auto *VecTy = From->getAs<ExtVectorType>())
9470 From = VecTy->getElementType();
9471 if (const auto *VecTy = To->getAs<ExtVectorType>())
9472 To = VecTy->getElementType();
9473 // It's a floating promotion if the source type is a lower rank.
9474 return ICE->getCastKind() == CK_FloatingCast &&
9475 S.Context.getFloatingTypeOrder(From, To) < 0;
9476}
9477
9480 DiagnosticsEngine &Diags, SourceLocation Loc) {
9482 if (Diags.isIgnored(
9483 diag::warn_format_conversion_argument_type_mismatch_signedness,
9484 Loc) ||
9485 Diags.isIgnored(
9486 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9487 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9489 }
9490 }
9491 return Match;
9492}
9493
9494bool CheckPrintfHandler::checkFormatExpr(
9495 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9496 unsigned SpecifierLen, const Expr *E) {
9497 using namespace analyze_format_string;
9498 using namespace analyze_printf;
9499
9500 // Now type check the data expression that matches the
9501 // format specifier.
9502 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9503 if (!AT.isValid())
9504 return true;
9505
9506 QualType ExprTy = E->getType();
9507 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9508 ExprTy = TET->getUnderlyingExpr()->getType();
9509 }
9510
9511 if (const OverflowBehaviorType *OBT =
9512 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9513 ExprTy = OBT->getUnderlyingType();
9514
9515 // When using the format attribute in C++, you can receive a function or an
9516 // array that will necessarily decay to a pointer when passed to the final
9517 // format consumer. Apply decay before type comparison.
9518 if (ExprTy->canDecayToPointerType())
9519 ExprTy = S.Context.getDecayedType(ExprTy);
9520
9521 // Diagnose attempts to print a boolean value as a character. Unlike other
9522 // -Wformat diagnostics, this is fine from a type perspective, but it still
9523 // doesn't make sense.
9526 const CharSourceRange &CSR =
9527 getSpecifierRange(StartSpecifier, SpecifierLen);
9528 SmallString<4> FSString;
9529 llvm::raw_svector_ostream os(FSString);
9530 FS.toString(os);
9531 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9532 << FSString,
9533 E->getExprLoc(), false, CSR);
9534 return true;
9535 }
9536
9537 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9538 // dumping raw class data (like is-a pointer), not actual data.
9540 ExprTy->isObjCObjectPointerType()) {
9541 const CharSourceRange &CSR =
9542 getSpecifierRange(StartSpecifier, SpecifierLen);
9543 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9544 E->getExprLoc(), false, CSR);
9545 return true;
9546 }
9547
9548 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9549 return true;
9550
9551 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9553 ArgType::MatchKind OrigMatch = Match;
9554
9556 if (Match == ArgType::Match)
9557 return true;
9558
9559 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9560 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9561
9562 // Look through argument promotions for our error message's reported type.
9563 // This includes the integral and floating promotions, but excludes array
9564 // and function pointer decay (seeing that an argument intended to be a
9565 // string has type 'char [6]' is probably more confusing than 'char *') and
9566 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9567 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9568 if (isArithmeticArgumentPromotion(S, ICE)) {
9569 E = ICE->getSubExpr();
9570 ExprTy = E->getType();
9571
9572 // Check if we didn't match because of an implicit cast from a 'char'
9573 // or 'short' to an 'int'. This is done because printf is a varargs
9574 // function.
9575 if (ICE->getType() == S.Context.IntTy ||
9576 ICE->getType() == S.Context.UnsignedIntTy) {
9577 // All further checking is done on the subexpression
9578 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9579 if (OrigMatch == ArgType::NoMatchSignedness &&
9580 ImplicitMatch != ArgType::NoMatchSignedness)
9581 // If the original match was a signedness match this match on the
9582 // implicit cast type also need to be signedness match otherwise we
9583 // might introduce new unexpected warnings from -Wformat-signedness.
9584 return true;
9585 ImplicitMatch = handleFormatSignedness(
9586 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9587 if (ImplicitMatch == ArgType::Match)
9588 return true;
9589 }
9590 }
9591 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9592 // Special case for 'a', which has type 'int' in C.
9593 // Note, however, that we do /not/ want to treat multibyte constants like
9594 // 'MooV' as characters! This form is deprecated but still exists. In
9595 // addition, don't treat expressions as of type 'char' if one byte length
9596 // modifier is provided.
9597 if (ExprTy == S.Context.IntTy &&
9599 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9600 ExprTy = S.Context.CharTy;
9601 // To improve check results, we consider a character literal in C
9602 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9603 // more likely a type confusion situation, so we will suggest to
9604 // use '%hhd' instead by discarding the MatchPromotion.
9605 if (Match == ArgType::MatchPromotion)
9607 }
9608 }
9609 if (Match == ArgType::MatchPromotion) {
9610 // WG14 N2562 only clarified promotions in *printf
9611 // For NSLog in ObjC, just preserve -Wformat behavior
9612 if (!S.getLangOpts().ObjC &&
9613 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9614 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9615 return true;
9617 }
9618 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9619 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9620 Match = ImplicitMatch;
9621 assert(Match != ArgType::MatchPromotion);
9622
9623 // Look through unscoped enums to their underlying type.
9624 bool IsEnum = false;
9625 bool IsScopedEnum = false;
9626 QualType IntendedTy = ExprTy;
9627 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9628 IntendedTy = ED->getIntegerType();
9629 if (!ED->isScoped()) {
9630 ExprTy = IntendedTy;
9631 // This controls whether we're talking about the underlying type or not,
9632 // which we only want to do when it's an unscoped enum.
9633 IsEnum = true;
9634 } else {
9635 IsScopedEnum = true;
9636 }
9637 }
9638
9639 // %C in an Objective-C context prints a unichar, not a wchar_t.
9640 // If the argument is an integer of some kind, believe the %C and suggest
9641 // a cast instead of changing the conversion specifier.
9642 if (isObjCContext() &&
9645 !ExprTy->isCharType()) {
9646 // 'unichar' is defined as a typedef of unsigned short, but we should
9647 // prefer using the typedef if it is visible.
9648 IntendedTy = S.Context.UnsignedShortTy;
9649
9650 // While we are here, check if the value is an IntegerLiteral that happens
9651 // to be within the valid range.
9652 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9653 const llvm::APInt &V = IL->getValue();
9654 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9655 return true;
9656 }
9657
9658 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9660 if (S.LookupName(Result, S.getCurScope())) {
9661 NamedDecl *ND = Result.getFoundDecl();
9662 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9663 if (TD->getUnderlyingType() == IntendedTy)
9664 IntendedTy =
9666 /*Qualifier=*/std::nullopt, TD);
9667 }
9668 }
9669 }
9670
9671 // Special-case some of Darwin's platform-independence types by suggesting
9672 // casts to primitive types that are known to be large enough.
9673 bool ShouldNotPrintDirectly = false;
9674 StringRef CastTyName;
9675 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9676 QualType CastTy;
9677 std::tie(CastTy, CastTyName) =
9678 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9679 if (!CastTy.isNull()) {
9680 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9681 // (long in ASTContext). Only complain to pedants or when they're the
9682 // underlying type of a scoped enum (which always needs a cast).
9683 if (!IsScopedEnum &&
9684 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9685 (AT.isSizeT() || AT.isPtrdiffT()) &&
9686 AT.matchesType(S.Context, CastTy))
9688 IntendedTy = CastTy;
9689 ShouldNotPrintDirectly = true;
9690 }
9691 }
9692
9693 // We may be able to offer a FixItHint if it is a supported type.
9694 PrintfSpecifier fixedFS = FS;
9695 bool Success =
9696 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9697
9698 if (Success) {
9699 // Get the fix string from the fixed format specifier
9700 SmallString<16> buf;
9701 llvm::raw_svector_ostream os(buf);
9702 fixedFS.toString(os);
9703
9704 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9705
9706 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9707 unsigned Diag;
9708 switch (Match) {
9709 case ArgType::Match:
9712 llvm_unreachable("expected non-matching");
9714 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9715 break;
9717 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9718 break;
9720 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9721 break;
9722 case ArgType::NoMatch:
9723 Diag = diag::warn_format_conversion_argument_type_mismatch;
9724 break;
9725 }
9726
9727 // In this case, the specifier is wrong and should be changed to match
9728 // the argument.
9729 EmitFormatDiagnostic(S.PDiag(Diag)
9731 << IntendedTy << IsEnum << E->getSourceRange(),
9732 E->getBeginLoc(),
9733 /*IsStringLocation*/ false, SpecRange,
9734 FixItHint::CreateReplacement(SpecRange, os.str()));
9735 } else {
9736 // The canonical type for formatting this value is different from the
9737 // actual type of the expression. (This occurs, for example, with Darwin's
9738 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9739 // should be printed as 'long' for 64-bit compatibility.)
9740 // Rather than emitting a normal format/argument mismatch, we want to
9741 // add a cast to the recommended type (and correct the format string
9742 // if necessary). We should also do so for scoped enumerations.
9743 SmallString<16> CastBuf;
9744 llvm::raw_svector_ostream CastFix(CastBuf);
9745 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9746 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9747 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9748
9750 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9751 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9752 E->getExprLoc());
9753 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9754 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9755
9756 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9757 // If there's already a cast present, just replace it.
9758 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9759 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9760
9761 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9762 // If the expression has high enough precedence,
9763 // just write the C-style cast.
9764 Hints.push_back(
9765 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9766 } else {
9767 // Otherwise, add parens around the expression as well as the cast.
9768 CastFix << "(";
9769 Hints.push_back(
9770 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9771
9772 // We don't use getLocForEndOfToken because it returns invalid source
9773 // locations for macro expansions (by design).
9777 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9778 }
9779
9780 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9781 // The expression has a type that should not be printed directly.
9782 // We extract the name from the typedef because we don't want to show
9783 // the underlying type in the diagnostic.
9784 StringRef Name;
9785 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9786 Name = TypedefTy->getDecl()->getName();
9787 else
9788 Name = CastTyName;
9789 unsigned Diag = Match == ArgType::NoMatchPedantic
9790 ? diag::warn_format_argument_needs_cast_pedantic
9791 : diag::warn_format_argument_needs_cast;
9792 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9793 << E->getSourceRange(),
9794 E->getBeginLoc(), /*IsStringLocation=*/false,
9795 SpecRange, Hints);
9796 } else {
9797 // In this case, the expression could be printed using a different
9798 // specifier, but we've decided that the specifier is probably correct
9799 // and we should cast instead. Just use the normal warning message.
9800
9801 unsigned Diag =
9802 IsScopedEnum
9803 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9804 : diag::warn_format_conversion_argument_type_mismatch;
9805
9806 EmitFormatDiagnostic(
9807 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9808 << IsEnum << E->getSourceRange(),
9809 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9810 }
9811 }
9812 } else {
9813 const CharSourceRange &CSR =
9814 getSpecifierRange(StartSpecifier, SpecifierLen);
9815 // Since the warning for passing non-POD types to variadic functions
9816 // was deferred until now, we emit a warning for non-POD
9817 // arguments here.
9818 bool EmitTypeMismatch = false;
9819 // Record and complex type arguments cannot be code generated for os_log
9820 // and would crash CodeGen, so they are rejected with a hard error emitted
9821 // after the switch below.
9822 bool EmitOSLogError = false;
9823 switch (S.isValidVarArgType(ExprTy)) {
9824 case VarArgKind::Valid:
9826 unsigned Diag;
9827 switch (Match) {
9828 case ArgType::Match:
9831 llvm_unreachable("expected non-matching");
9833 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9834 break;
9836 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9837 break;
9839 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9840 break;
9841 case ArgType::NoMatch:
9842 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
9843 Diag = diag::warn_format_conversion_argument_type_mismatch;
9844 break;
9845 }
9846
9847 if (!EmitOSLogError)
9848 EmitFormatDiagnostic(
9849 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9850 << IsEnum << CSR << E->getSourceRange(),
9851 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9852 break;
9853 }
9856 if (CallType == VariadicCallType::DoesNotApply) {
9857 EmitTypeMismatch = true;
9858 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
9859 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9860 // does not stop compilation.
9861 EmitOSLogError = true;
9862 } else {
9863 EmitFormatDiagnostic(
9864 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9865 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9866 << AT.getRepresentativeTypeName(S.Context) << CSR
9867 << E->getSourceRange(),
9868 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9869 checkForCStrMembers(AT, E);
9870 }
9871 break;
9872
9874 if (CallType == VariadicCallType::DoesNotApply)
9875 EmitTypeMismatch = true;
9876 else if (ExprTy->isObjCObjectType())
9877 EmitFormatDiagnostic(
9878 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9879 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9880 << AT.getRepresentativeTypeName(S.Context) << CSR
9881 << E->getSourceRange(),
9882 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9883 else
9884 // FIXME: If this is an initializer list, suggest removing the braces
9885 // or inserting a cast to the target type.
9886 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9887 << isa<InitListExpr>(E) << ExprTy << CallType
9889 break;
9890 }
9891
9892 if (EmitOSLogError)
9893 EmitFormatDiagnostic(
9894 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
9895 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9896 << CSR << E->getSourceRange(),
9897 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9898
9899 if (EmitTypeMismatch) {
9900 // The function is not variadic, so we do not generate warnings about
9901 // being allowed to pass that object as a variadic argument. Instead,
9902 // since there are inherently no printf specifiers for types which cannot
9903 // be passed as variadic arguments, emit a plain old specifier mismatch
9904 // argument.
9905 EmitFormatDiagnostic(
9906 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9907 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9908 << E->getSourceRange(),
9909 E->getBeginLoc(), false, CSR);
9910 }
9911
9912 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9913 "format string specifier index out of range");
9914 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9915 }
9916
9917 return true;
9918}
9919
9920//===--- CHECK: Scanf format string checking ------------------------------===//
9921
9922namespace {
9923
9924class CheckScanfHandler : public CheckFormatHandler {
9925public:
9926 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9927 const Expr *origFormatExpr, FormatStringType type,
9928 unsigned firstDataArg, unsigned numDataArgs,
9929 const char *beg, Sema::FormatArgumentPassingKind APK,
9930 ArrayRef<const Expr *> Args, unsigned formatIdx,
9931 bool inFunctionCall, VariadicCallType CallType,
9932 llvm::SmallBitVector &CheckedVarArgs,
9933 UncoveredArgHandler &UncoveredArg)
9934 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9935 numDataArgs, beg, APK, Args, formatIdx,
9936 inFunctionCall, CallType, CheckedVarArgs,
9937 UncoveredArg) {}
9938
9939 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9940 const char *startSpecifier,
9941 unsigned specifierLen) override;
9942
9943 bool
9944 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9945 const char *startSpecifier,
9946 unsigned specifierLen) override;
9947
9948 void HandleIncompleteScanList(const char *start, const char *end) override;
9949};
9950
9951} // namespace
9952
9953void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9954 const char *end) {
9955 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9956 getLocationOfByte(end), /*IsStringLocation*/ true,
9957 getSpecifierRange(start, end - start));
9958}
9959
9960bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9961 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9962 unsigned specifierLen) {
9965
9966 return HandleInvalidConversionSpecifier(
9967 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9968 specifierLen, CS.getStart(), CS.getLength());
9969}
9970
9971bool CheckScanfHandler::HandleScanfSpecifier(
9972 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9973 unsigned specifierLen) {
9974 using namespace analyze_scanf;
9975 using namespace analyze_format_string;
9976
9977 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9978
9979 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9980 // be used to decide if we are using positional arguments consistently.
9981 if (FS.consumesDataArgument()) {
9982 if (atFirstArg) {
9983 atFirstArg = false;
9984 usesPositionalArgs = FS.usesPositionalArg();
9985 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9986 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9987 startSpecifier, specifierLen);
9988 return false;
9989 }
9990 }
9991
9992 // Check if the field with is non-zero.
9993 const OptionalAmount &Amt = FS.getFieldWidth();
9995 if (Amt.getConstantAmount() == 0) {
9996 const CharSourceRange &R =
9997 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9998 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9999 getLocationOfByte(Amt.getStart()),
10000 /*IsStringLocation*/ true, R,
10002 }
10003 }
10004
10005 if (!FS.consumesDataArgument()) {
10006 // FIXME: Technically specifying a precision or field width here
10007 // makes no sense. Worth issuing a warning at some point.
10008 return true;
10009 }
10010
10011 // Consume the argument.
10012 unsigned argIndex = FS.getArgIndex();
10013 if (argIndex < NumDataArgs) {
10014 // The check to see if the argIndex is valid will come later.
10015 // We set the bit here because we may exit early from this
10016 // function if we encounter some other error.
10017 CoveredArgs.set(argIndex);
10018 }
10019
10020 // Check the length modifier is valid with the given conversion specifier.
10022 S.getLangOpts()))
10023 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10024 diag::warn_format_nonsensical_length);
10025 else if (!FS.hasStandardLengthModifier())
10026 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10028 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10029 diag::warn_format_non_standard_conversion_spec);
10030
10032 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10033
10034 // The remaining checks depend on the data arguments.
10035 if (!HasFormatArguments())
10036 return true;
10037
10038 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10039 return false;
10040
10041 // Check that the argument type matches the format specifier.
10042 const Expr *Ex = getDataArg(argIndex);
10043 if (!Ex)
10044 return true;
10045
10047
10048 if (!AT.isValid()) {
10049 return true;
10050 }
10051
10052 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10053 return true;
10054
10056 AT.matchesType(S.Context, Ex->getType());
10059 return true;
10062
10063 ScanfSpecifier fixedFS = FS;
10064 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10065 S.getLangOpts(), S.Context);
10066
10067 unsigned Diag =
10068 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10069 : Signedness
10070 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10071 : diag::warn_format_conversion_argument_type_mismatch;
10072
10073 if (Success) {
10074 // Get the fix string from the fixed format specifier.
10075 SmallString<128> buf;
10076 llvm::raw_svector_ostream os(buf);
10077 fixedFS.toString(os);
10078
10079 EmitFormatDiagnostic(
10081 << Ex->getType() << false << Ex->getSourceRange(),
10082 Ex->getBeginLoc(),
10083 /*IsStringLocation*/ false,
10084 getSpecifierRange(startSpecifier, specifierLen),
10086 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10087 } else {
10088 EmitFormatDiagnostic(S.PDiag(Diag)
10090 << Ex->getType() << false << Ex->getSourceRange(),
10091 Ex->getBeginLoc(),
10092 /*IsStringLocation*/ false,
10093 getSpecifierRange(startSpecifier, specifierLen));
10094 }
10095
10096 return true;
10097}
10098
10099static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10101 const StringLiteral *Fmt,
10103 const Expr *FmtExpr, bool InFunctionCall) {
10104 bool HadError = false;
10105 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10106 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10107 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10108 // In positional-style format strings, the same specifier can appear
10109 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10110 // are sorted by getPosition(), and we process each range of equal
10111 // getPosition() values as one group.
10112 // RefArgs are taken from a string literal that was given to
10113 // attribute(format_matches), and if we got this far, we have already
10114 // verified that if it has positional specifiers that appear in multiple
10115 // locations, then they are all mutually compatible. What's left for us to
10116 // do is verify that all specifiers with the same position in FmtArgs are
10117 // compatible with the RefArgs specifiers. We check each specifier from
10118 // FmtArgs against the first member of the RefArgs group.
10119 for (; FmtIter < FmtEnd; ++FmtIter) {
10120 // Clang does not diagnose missing format specifiers in positional-style
10121 // strings (TODO: which it probably should do, as it is UB to skip over a
10122 // format argument). Skip specifiers if needed.
10123 if (FmtIter->getPosition() < RefIter->getPosition())
10124 continue;
10125
10126 // Delimits a new getPosition() value.
10127 if (FmtIter->getPosition() > RefIter->getPosition())
10128 break;
10129
10130 HadError |=
10131 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10132 }
10133
10134 // Jump RefIter to the start of the next group.
10135 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
10136 return Arg.getPosition() != RefIter->getPosition();
10137 });
10138 }
10139
10140 if (FmtIter < FmtEnd) {
10141 CheckFormatHandler::EmitFormatDiagnostic(
10142 S, InFunctionCall, FmtExpr,
10143 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10144 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
10145 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
10146 } else if (RefIter < RefEnd) {
10147 CheckFormatHandler::EmitFormatDiagnostic(
10148 S, InFunctionCall, FmtExpr,
10149 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10150 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
10151 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
10152 << 1 << RefIter->getSourceRange();
10153 }
10154 return !HadError;
10155}
10156
10158 Sema &S, const FormatStringLiteral *FExpr,
10159 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10161 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10162 bool inFunctionCall, VariadicCallType CallType,
10163 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10164 bool IgnoreStringsWithoutSpecifiers) {
10165 // CHECK: is the format string a wide literal?
10166 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10167 CheckFormatHandler::EmitFormatDiagnostic(
10168 S, inFunctionCall, Args[format_idx],
10169 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10170 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10171 return;
10172 }
10173
10174 // Str - The format string. NOTE: this is NOT null-terminated!
10175 StringRef StrRef = FExpr->getString();
10176 const char *Str = StrRef.data();
10177 // Account for cases where the string literal is truncated in a declaration.
10178 const ConstantArrayType *T =
10179 S.Context.getAsConstantArrayType(FExpr->getType());
10180 assert(T && "String literal not of constant array type!");
10181 size_t TypeSize = T->getZExtSize();
10182 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10183 const unsigned numDataArgs = Args.size() - firstDataArg;
10184
10185 if (IgnoreStringsWithoutSpecifiers &&
10187 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10188 return;
10189
10190 // Emit a warning if the string literal is truncated and does not contain an
10191 // embedded null character.
10192 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10193 CheckFormatHandler::EmitFormatDiagnostic(
10194 S, inFunctionCall, Args[format_idx],
10195 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10196 FExpr->getBeginLoc(),
10197 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10198 return;
10199 }
10200
10201 // CHECK: empty format string?
10202 if (StrLen == 0 && numDataArgs > 0) {
10203 CheckFormatHandler::EmitFormatDiagnostic(
10204 S, inFunctionCall, Args[format_idx],
10205 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10206 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10207 return;
10208 }
10209
10214 bool IsObjC =
10216 if (ReferenceFormatString == nullptr) {
10217 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10218 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10219 inFunctionCall, CallType, CheckedVarArgs,
10220 UncoveredArg);
10221
10223 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10226 H.DoneProcessing();
10227 } else {
10229 Type, ReferenceFormatString, FExpr->getFormatString(),
10230 inFunctionCall ? nullptr : Args[format_idx]);
10231 }
10232 } else if (Type == FormatStringType::Scanf) {
10233 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10234 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10235 CallType, CheckedVarArgs, UncoveredArg);
10236
10238 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10239 H.DoneProcessing();
10240 } // TODO: handle other formats
10241}
10242
10244 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10245 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10250 return true;
10251
10252 bool IsObjC =
10255 FormatStringLiteral RefLit = AuthoritativeFormatString;
10256 FormatStringLiteral TestLit = TestedFormatString;
10257 const Expr *Arg;
10258 bool DiagAtStringLiteral;
10259 if (FunctionCallArg) {
10260 Arg = FunctionCallArg;
10261 DiagAtStringLiteral = false;
10262 } else {
10263 Arg = TestedFormatString;
10264 DiagAtStringLiteral = true;
10265 }
10266 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10267 AuthoritativeFormatString, Type,
10268 IsObjC, true, RefArgs) &&
10269 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10270 DiagAtStringLiteral, FmtArgs)) {
10271 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10272 TestedFormatString, FmtArgs, Arg,
10273 DiagAtStringLiteral);
10274 }
10275 return false;
10276}
10277
10279 const StringLiteral *Str) {
10284 return true;
10285
10286 FormatStringLiteral RefLit = Str;
10288 bool IsObjC =
10290 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10291 true, Args))
10292 return false;
10293
10294 // Group arguments by getPosition() value, and check that each member of the
10295 // group is compatible with the first member. This verifies that when
10296 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10297 // are mutually compatible. As an optimization, don't test the first member
10298 // against itself.
10299 bool HadError = false;
10300 auto Iter = Args.begin();
10301 auto End = Args.end();
10302 while (Iter != End) {
10303 const auto &FirstInGroup = *Iter;
10304 for (++Iter;
10305 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10306 ++Iter) {
10307 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10308 }
10309 }
10310 return !HadError;
10311}
10312
10314 // Str - The format string. NOTE: this is NOT null-terminated!
10315 StringRef StrRef = FExpr->getString();
10316 const char *Str = StrRef.data();
10317 // Account for cases where the string literal is truncated in a declaration.
10318 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10319 assert(T && "String literal not of constant array type!");
10320 size_t TypeSize = T->getZExtSize();
10321 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10323 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10324}
10325
10326//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10327
10328// Returns the related absolute value function that is larger, of 0 if one
10329// does not exist.
10330static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10331 switch (AbsFunction) {
10332 default:
10333 return 0;
10334
10335 case Builtin::BI__builtin_abs:
10336 return Builtin::BI__builtin_labs;
10337 case Builtin::BI__builtin_labs:
10338 return Builtin::BI__builtin_llabs;
10339 case Builtin::BI__builtin_llabs:
10340 return 0;
10341
10342 case Builtin::BI__builtin_fabsf:
10343 return Builtin::BI__builtin_fabs;
10344 case Builtin::BI__builtin_fabs:
10345 return Builtin::BI__builtin_fabsl;
10346 case Builtin::BI__builtin_fabsl:
10347 return 0;
10348
10349 case Builtin::BI__builtin_cabsf:
10350 return Builtin::BI__builtin_cabs;
10351 case Builtin::BI__builtin_cabs:
10352 return Builtin::BI__builtin_cabsl;
10353 case Builtin::BI__builtin_cabsl:
10354 return 0;
10355
10356 case Builtin::BIabs:
10357 return Builtin::BIlabs;
10358 case Builtin::BIlabs:
10359 return Builtin::BIllabs;
10360 case Builtin::BIllabs:
10361 return 0;
10362
10363 case Builtin::BIfabsf:
10364 return Builtin::BIfabs;
10365 case Builtin::BIfabs:
10366 return Builtin::BIfabsl;
10367 case Builtin::BIfabsl:
10368 return 0;
10369
10370 case Builtin::BIcabsf:
10371 return Builtin::BIcabs;
10372 case Builtin::BIcabs:
10373 return Builtin::BIcabsl;
10374 case Builtin::BIcabsl:
10375 return 0;
10376 }
10377}
10378
10379// Returns the argument type of the absolute value function.
10381 unsigned AbsType) {
10382 if (AbsType == 0)
10383 return QualType();
10384
10386 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10388 return QualType();
10389
10391 if (!FT)
10392 return QualType();
10393
10394 if (FT->getNumParams() != 1)
10395 return QualType();
10396
10397 return FT->getParamType(0);
10398}
10399
10400// Returns the best absolute value function, or zero, based on type and
10401// current absolute value function.
10402static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10403 unsigned AbsFunctionKind) {
10404 unsigned BestKind = 0;
10405 uint64_t ArgSize = Context.getTypeSize(ArgType);
10406 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10407 Kind = getLargerAbsoluteValueFunction(Kind)) {
10408 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10409 if (Context.getTypeSize(ParamType) >= ArgSize) {
10410 if (BestKind == 0)
10411 BestKind = Kind;
10412 else if (Context.hasSameType(ParamType, ArgType)) {
10413 BestKind = Kind;
10414 break;
10415 }
10416 }
10417 }
10418 return BestKind;
10419}
10420
10426
10428 if (T->isIntegralOrEnumerationType())
10429 return AVK_Integer;
10430 if (T->isRealFloatingType())
10431 return AVK_Floating;
10432 if (T->isAnyComplexType())
10433 return AVK_Complex;
10434
10435 llvm_unreachable("Type not integer, floating, or complex");
10436}
10437
10438// Changes the absolute value function to a different type. Preserves whether
10439// the function is a builtin.
10440static unsigned changeAbsFunction(unsigned AbsKind,
10441 AbsoluteValueKind ValueKind) {
10442 switch (ValueKind) {
10443 case AVK_Integer:
10444 switch (AbsKind) {
10445 default:
10446 return 0;
10447 case Builtin::BI__builtin_fabsf:
10448 case Builtin::BI__builtin_fabs:
10449 case Builtin::BI__builtin_fabsl:
10450 case Builtin::BI__builtin_cabsf:
10451 case Builtin::BI__builtin_cabs:
10452 case Builtin::BI__builtin_cabsl:
10453 return Builtin::BI__builtin_abs;
10454 case Builtin::BIfabsf:
10455 case Builtin::BIfabs:
10456 case Builtin::BIfabsl:
10457 case Builtin::BIcabsf:
10458 case Builtin::BIcabs:
10459 case Builtin::BIcabsl:
10460 return Builtin::BIabs;
10461 }
10462 case AVK_Floating:
10463 switch (AbsKind) {
10464 default:
10465 return 0;
10466 case Builtin::BI__builtin_abs:
10467 case Builtin::BI__builtin_labs:
10468 case Builtin::BI__builtin_llabs:
10469 case Builtin::BI__builtin_cabsf:
10470 case Builtin::BI__builtin_cabs:
10471 case Builtin::BI__builtin_cabsl:
10472 return Builtin::BI__builtin_fabsf;
10473 case Builtin::BIabs:
10474 case Builtin::BIlabs:
10475 case Builtin::BIllabs:
10476 case Builtin::BIcabsf:
10477 case Builtin::BIcabs:
10478 case Builtin::BIcabsl:
10479 return Builtin::BIfabsf;
10480 }
10481 case AVK_Complex:
10482 switch (AbsKind) {
10483 default:
10484 return 0;
10485 case Builtin::BI__builtin_abs:
10486 case Builtin::BI__builtin_labs:
10487 case Builtin::BI__builtin_llabs:
10488 case Builtin::BI__builtin_fabsf:
10489 case Builtin::BI__builtin_fabs:
10490 case Builtin::BI__builtin_fabsl:
10491 return Builtin::BI__builtin_cabsf;
10492 case Builtin::BIabs:
10493 case Builtin::BIlabs:
10494 case Builtin::BIllabs:
10495 case Builtin::BIfabsf:
10496 case Builtin::BIfabs:
10497 case Builtin::BIfabsl:
10498 return Builtin::BIcabsf;
10499 }
10500 }
10501 llvm_unreachable("Unable to convert function");
10502}
10503
10504static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10505 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10506 if (!FnInfo)
10507 return 0;
10508
10509 switch (FDecl->getBuiltinID()) {
10510 default:
10511 return 0;
10512 case Builtin::BI__builtin_abs:
10513 case Builtin::BI__builtin_fabs:
10514 case Builtin::BI__builtin_fabsf:
10515 case Builtin::BI__builtin_fabsl:
10516 case Builtin::BI__builtin_labs:
10517 case Builtin::BI__builtin_llabs:
10518 case Builtin::BI__builtin_cabs:
10519 case Builtin::BI__builtin_cabsf:
10520 case Builtin::BI__builtin_cabsl:
10521 case Builtin::BIabs:
10522 case Builtin::BIlabs:
10523 case Builtin::BIllabs:
10524 case Builtin::BIfabs:
10525 case Builtin::BIfabsf:
10526 case Builtin::BIfabsl:
10527 case Builtin::BIcabs:
10528 case Builtin::BIcabsf:
10529 case Builtin::BIcabsl:
10530 return FDecl->getBuiltinID();
10531 }
10532 llvm_unreachable("Unknown Builtin type");
10533}
10534
10535// If the replacement is valid, emit a note with replacement function.
10536// Additionally, suggest including the proper header if not already included.
10538 unsigned AbsKind, QualType ArgType) {
10539 bool EmitHeaderHint = true;
10540 const char *HeaderName = nullptr;
10541 std::string FunctionName;
10542 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10543 FunctionName = "std::abs";
10544 if (ArgType->isIntegralOrEnumerationType()) {
10545 HeaderName = "cstdlib";
10546 } else if (ArgType->isRealFloatingType()) {
10547 HeaderName = "cmath";
10548 } else {
10549 llvm_unreachable("Invalid Type");
10550 }
10551
10552 // Lookup all std::abs
10553 if (NamespaceDecl *Std = S.getStdNamespace()) {
10554 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10555 R.suppressDiagnostics();
10556 S.LookupQualifiedName(R, Std);
10557
10558 for (const auto *I : R) {
10559 const FunctionDecl *FDecl = nullptr;
10560 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10561 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10562 } else {
10563 FDecl = dyn_cast<FunctionDecl>(I);
10564 }
10565 if (!FDecl)
10566 continue;
10567
10568 // Found std::abs(), check that they are the right ones.
10569 if (FDecl->getNumParams() != 1)
10570 continue;
10571
10572 // Check that the parameter type can handle the argument.
10573 QualType ParamType = FDecl->getParamDecl(0)->getType();
10574 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10575 S.Context.getTypeSize(ArgType) <=
10576 S.Context.getTypeSize(ParamType)) {
10577 // Found a function, don't need the header hint.
10578 EmitHeaderHint = false;
10579 break;
10580 }
10581 }
10582 }
10583 } else {
10584 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10585 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10586
10587 if (HeaderName) {
10588 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10589 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10590 R.suppressDiagnostics();
10591 S.LookupName(R, S.getCurScope());
10592
10593 if (R.isSingleResult()) {
10594 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10595 if (FD && FD->getBuiltinID() == AbsKind) {
10596 EmitHeaderHint = false;
10597 } else {
10598 return;
10599 }
10600 } else if (!R.empty()) {
10601 return;
10602 }
10603 }
10604 }
10605
10606 S.Diag(Loc, diag::note_replace_abs_function)
10607 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10608
10609 if (!HeaderName)
10610 return;
10611
10612 if (!EmitHeaderHint)
10613 return;
10614
10615 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10616 << FunctionName;
10617}
10618
10619template <std::size_t StrLen>
10620static bool IsStdFunction(const FunctionDecl *FDecl,
10621 const char (&Str)[StrLen]) {
10622 if (!FDecl)
10623 return false;
10624 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10625 return false;
10626 if (!FDecl->isInStdNamespace())
10627 return false;
10628
10629 return true;
10630}
10631
10632enum class MathCheck { NaN, Inf };
10633static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10634 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10635 return llvm::is_contained(names, calleeName);
10636 };
10637
10638 switch (Check) {
10639 case MathCheck::NaN:
10640 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10641 "__builtin_nanf16", "__builtin_nanf128"});
10642 case MathCheck::Inf:
10643 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10644 "__builtin_inff16", "__builtin_inff128"});
10645 }
10646 llvm_unreachable("unknown MathCheck");
10647}
10648
10649static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10650 if (FDecl->getName() != "infinity")
10651 return false;
10652
10653 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10654 const CXXRecordDecl *RDecl = MDecl->getParent();
10655 if (RDecl->getName() != "numeric_limits")
10656 return false;
10657
10658 if (const NamespaceDecl *NSDecl =
10659 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10660 return NSDecl->isStdNamespace();
10661 }
10662
10663 return false;
10664}
10665
10666void Sema::CheckInfNaNFunction(const CallExpr *Call,
10667 const FunctionDecl *FDecl) {
10668 if (!FDecl->getIdentifier())
10669 return;
10670
10671 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10672 if (FPO.getNoHonorNaNs() &&
10673 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10675 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10676 << 1 << 0 << Call->getSourceRange();
10677 return;
10678 }
10679
10680 if (FPO.getNoHonorInfs() &&
10681 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10682 IsInfinityFunction(FDecl) ||
10684 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10685 << 0 << 0 << Call->getSourceRange();
10686 }
10687}
10688
10689void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10690 const FunctionDecl *FDecl) {
10691 if (Call->getNumArgs() != 1)
10692 return;
10693
10694 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10695 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10696 if (AbsKind == 0 && !IsStdAbs)
10697 return;
10698
10699 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10700 QualType ParamType = Call->getArg(0)->getType();
10701
10702 // Unsigned types cannot be negative. Suggest removing the absolute value
10703 // function call.
10704 if (ArgType->isUnsignedIntegerType()) {
10705 std::string FunctionName =
10706 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10707 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10708 Diag(Call->getExprLoc(), diag::note_remove_abs)
10709 << FunctionName
10710 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10711 return;
10712 }
10713
10714 // Taking the absolute value of a pointer is very suspicious, they probably
10715 // wanted to index into an array, dereference a pointer, call a function, etc.
10716 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10717 unsigned DiagType = 0;
10718 if (ArgType->isFunctionType())
10719 DiagType = 1;
10720 else if (ArgType->isArrayType())
10721 DiagType = 2;
10722
10723 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10724 return;
10725 }
10726
10727 // std::abs has overloads which prevent most of the absolute value problems
10728 // from occurring.
10729 if (IsStdAbs)
10730 return;
10731
10732 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10733 // types.
10734 if (!ArgType->isIntegralOrEnumerationType() &&
10735 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10736 return;
10737
10738 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10739 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10740
10741 // The argument and parameter are the same kind. Check if they are the right
10742 // size.
10743 if (ArgValueKind == ParamValueKind) {
10744 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10745 return;
10746
10747 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10748 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10749 << FDecl << ArgType << ParamType;
10750
10751 if (NewAbsKind == 0)
10752 return;
10753
10754 emitReplacement(*this, Call->getExprLoc(),
10755 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10756 return;
10757 }
10758
10759 // ArgValueKind != ParamValueKind
10760 // The wrong type of absolute value function was used. Attempt to find the
10761 // proper one.
10762 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10763 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10764 if (NewAbsKind == 0)
10765 return;
10766
10767 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10768 << FDecl << ParamValueKind << ArgValueKind;
10769
10770 emitReplacement(*this, Call->getExprLoc(),
10771 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10772}
10773
10774//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10775void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10776 const FunctionDecl *FDecl) {
10777 if (!Call || !FDecl) return;
10778
10779 // Ignore template specializations and macros.
10780 if (inTemplateInstantiation()) return;
10781 if (Call->getExprLoc().isMacroID()) return;
10782
10783 // Only care about the one template argument, two function parameter std::max
10784 if (Call->getNumArgs() != 2) return;
10785 if (!IsStdFunction(FDecl, "max")) return;
10786 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10787 if (!ArgList) return;
10788 if (ArgList->size() != 1) return;
10789
10790 // Check that template type argument is unsigned integer.
10791 const auto& TA = ArgList->get(0);
10792 if (TA.getKind() != TemplateArgument::Type) return;
10793 QualType ArgType = TA.getAsType();
10794 if (!ArgType->isUnsignedIntegerType()) return;
10795
10796 // See if either argument is a literal zero.
10797 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10798 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10799 if (!MTE) return false;
10800 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10801 if (!Num) return false;
10802 if (Num->getValue() != 0) return false;
10803 return true;
10804 };
10805
10806 const Expr *FirstArg = Call->getArg(0);
10807 const Expr *SecondArg = Call->getArg(1);
10808 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10809 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10810
10811 // Only warn when exactly one argument is zero.
10812 if (IsFirstArgZero == IsSecondArgZero) return;
10813
10814 SourceRange FirstRange = FirstArg->getSourceRange();
10815 SourceRange SecondRange = SecondArg->getSourceRange();
10816
10817 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10818
10819 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10820 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10821
10822 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10823 SourceRange RemovalRange;
10824 if (IsFirstArgZero) {
10825 RemovalRange = SourceRange(FirstRange.getBegin(),
10826 SecondRange.getBegin().getLocWithOffset(-1));
10827 } else {
10828 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10829 SecondRange.getEnd());
10830 }
10831
10832 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10833 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10834 << FixItHint::CreateRemoval(RemovalRange);
10835}
10836
10837//===--- CHECK: Standard memory functions ---------------------------------===//
10838
10839/// Takes the expression passed to the size_t parameter of functions
10840/// such as memcmp, strncat, etc and warns if it's a comparison.
10841///
10842/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10844 const IdentifierInfo *FnName,
10845 SourceLocation FnLoc,
10846 SourceLocation RParenLoc) {
10847 const auto *Size = dyn_cast<BinaryOperator>(E);
10848 if (!Size)
10849 return false;
10850
10851 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10852 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10853 return false;
10854
10855 SourceRange SizeRange = Size->getSourceRange();
10856 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10857 << SizeRange << FnName;
10858 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10859 << FnName
10861 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10862 << FixItHint::CreateRemoval(RParenLoc);
10863 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10864 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10866 ")");
10867
10868 return true;
10869}
10870
10871/// Determine whether the given type is or contains a dynamic class type
10872/// (e.g., whether it has a vtable).
10874 bool &IsContained) {
10875 // Look through array types while ignoring qualifiers.
10876 const Type *Ty = T->getBaseElementTypeUnsafe();
10877 IsContained = false;
10878
10879 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10880 RD = RD ? RD->getDefinition() : nullptr;
10881 if (!RD || RD->isInvalidDecl())
10882 return nullptr;
10883
10884 if (RD->isDynamicClass())
10885 return RD;
10886
10887 // Check all the fields. If any bases were dynamic, the class is dynamic.
10888 // It's impossible for a class to transitively contain itself by value, so
10889 // infinite recursion is impossible.
10890 for (auto *FD : RD->fields()) {
10891 bool SubContained;
10892 if (const CXXRecordDecl *ContainedRD =
10893 getContainedDynamicClass(FD->getType(), SubContained)) {
10894 IsContained = true;
10895 return ContainedRD;
10896 }
10897 }
10898
10899 return nullptr;
10900}
10901
10903 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10904 if (Unary->getKind() == UETT_SizeOf)
10905 return Unary;
10906 return nullptr;
10907}
10908
10909/// If E is a sizeof expression, returns its argument expression,
10910/// otherwise returns NULL.
10911static const Expr *getSizeOfExprArg(const Expr *E) {
10913 if (!SizeOf->isArgumentType())
10914 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10915 return nullptr;
10916}
10917
10918/// If E is a sizeof expression, returns its argument type.
10921 return SizeOf->getTypeOfArgument();
10922 return QualType();
10923}
10924
10925namespace {
10926
10927struct SearchNonTrivialToInitializeField
10928 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10929 using Super =
10930 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10931
10932 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10933
10934 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10935 SourceLocation SL) {
10936 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10937 asDerived().visitArray(PDIK, AT, SL);
10938 return;
10939 }
10940
10941 Super::visitWithKind(PDIK, FT, SL);
10942 }
10943
10944 void visitARCStrong(QualType FT, SourceLocation SL) {
10945 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10946 }
10947 void visitARCWeak(QualType FT, SourceLocation SL) {
10948 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10949 }
10950 void visitStruct(QualType FT, SourceLocation SL) {
10951 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10952 visit(FD->getType(), FD->getLocation());
10953 }
10954 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10955 const ArrayType *AT, SourceLocation SL) {
10956 visit(getContext().getBaseElementType(AT), SL);
10957 }
10958 void visitTrivial(QualType FT, SourceLocation SL) {}
10959
10960 static void diag(QualType RT, const Expr *E, Sema &S) {
10961 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10962 }
10963
10964 ASTContext &getContext() { return S.getASTContext(); }
10965
10966 const Expr *E;
10967 Sema &S;
10968};
10969
10970struct SearchNonTrivialToCopyField
10971 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10972 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10973
10974 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10975
10976 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10977 SourceLocation SL) {
10978 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10979 asDerived().visitArray(PCK, AT, SL);
10980 return;
10981 }
10982
10983 Super::visitWithKind(PCK, FT, SL);
10984 }
10985
10986 void visitARCStrong(QualType FT, SourceLocation SL) {
10987 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10988 }
10989 void visitARCWeak(QualType FT, SourceLocation SL) {
10990 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10991 }
10992 void visitPtrAuth(QualType FT, SourceLocation SL) {
10993 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10994 }
10995 void visitStruct(QualType FT, SourceLocation SL) {
10996 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10997 visit(FD->getType(), FD->getLocation());
10998 }
10999 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11000 SourceLocation SL) {
11001 visit(getContext().getBaseElementType(AT), SL);
11002 }
11003 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11004 SourceLocation SL) {}
11005 void visitTrivial(QualType FT, SourceLocation SL) {}
11006 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11007
11008 static void diag(QualType RT, const Expr *E, Sema &S) {
11009 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
11010 }
11011
11012 ASTContext &getContext() { return S.getASTContext(); }
11013
11014 const Expr *E;
11015 Sema &S;
11016};
11017
11018}
11019
11020/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11021static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11022 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11023
11024 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
11025 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11026 return false;
11027
11028 return doesExprLikelyComputeSize(BO->getLHS()) ||
11029 doesExprLikelyComputeSize(BO->getRHS());
11030 }
11031
11032 return getAsSizeOfExpr(SizeofExpr) != nullptr;
11033}
11034
11035/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11036///
11037/// \code
11038/// #define MACRO 0
11039/// foo(MACRO);
11040/// foo(0);
11041/// \endcode
11042///
11043/// This should return true for the first call to foo, but not for the second
11044/// (regardless of whether foo is a macro or function).
11046 SourceLocation CallLoc,
11047 SourceLocation ArgLoc) {
11048 if (!CallLoc.isMacroID())
11049 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11050
11051 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11053}
11054
11055/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11056/// last two arguments transposed.
11057static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11058 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11059 return;
11060
11061 const Expr *SizeArg =
11062 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11063
11064 auto isLiteralZero = [](const Expr *E) {
11065 return (isa<IntegerLiteral>(E) &&
11066 cast<IntegerLiteral>(E)->getValue() == 0) ||
11068 cast<CharacterLiteral>(E)->getValue() == 0);
11069 };
11070
11071 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11072 SourceLocation CallLoc = Call->getRParenLoc();
11074 if (isLiteralZero(SizeArg) &&
11075 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11076
11077 SourceLocation DiagLoc = SizeArg->getExprLoc();
11078
11079 // Some platforms #define bzero to __builtin_memset. See if this is the
11080 // case, and if so, emit a better diagnostic.
11081 if (BId == Builtin::BIbzero ||
11083 CallLoc, SM, S.getLangOpts()) == "bzero")) {
11084 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11085 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11086 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11087 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11088 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11089 }
11090 return;
11091 }
11092
11093 // If the second argument to a memset is a sizeof expression and the third
11094 // isn't, this is also likely an error. This should catch
11095 // 'memset(buf, sizeof(buf), 0xff)'.
11096 if (BId == Builtin::BImemset &&
11097 doesExprLikelyComputeSize(Call->getArg(1)) &&
11098 !doesExprLikelyComputeSize(Call->getArg(2))) {
11099 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11100 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11101 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11102 return;
11103 }
11104}
11105
11106void Sema::CheckMemaccessArguments(const CallExpr *Call,
11107 unsigned BId,
11108 IdentifierInfo *FnName) {
11109 assert(BId != 0);
11110
11111 // It is possible to have a non-standard definition of memset. Validate
11112 // we have enough arguments, and if not, abort further checking.
11113 unsigned ExpectedNumArgs =
11114 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11115 if (Call->getNumArgs() < ExpectedNumArgs)
11116 return;
11117
11118 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11119 BId == Builtin::BIstrndup ? 1 : 2);
11120 unsigned LenArg =
11121 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11122 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11123
11124 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11125 Call->getBeginLoc(), Call->getRParenLoc()))
11126 return;
11127
11128 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11129 CheckMemaccessSize(*this, BId, Call);
11130
11131 // We have special checking when the length is a sizeof expression.
11132 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11133
11134 // Although widely used, 'bzero' is not a standard function. Be more strict
11135 // with the argument types before allowing diagnostics and only allow the
11136 // form bzero(ptr, sizeof(...)).
11137 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11138 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11139 return;
11140
11141 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11142 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11143 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11144
11145 QualType DestTy = Dest->getType();
11146 QualType PointeeTy;
11147 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11148 PointeeTy = DestPtrTy->getPointeeType();
11149
11150 // Never warn about void type pointers. This can be used to suppress
11151 // false positives.
11152 if (PointeeTy->isVoidType())
11153 continue;
11154
11155 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11156 // actually comparing the expressions for equality. Because computing the
11157 // expression IDs can be expensive, we only do this if the diagnostic is
11158 // enabled.
11159 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11160 break;
11161
11162 // Also check for cases where the sizeof argument is the exact same
11163 // type as the memory argument, and where it points to a user-defined
11164 // record type.
11165 if (SizeOfArgTy != QualType()) {
11166 if (PointeeTy->isRecordType() &&
11167 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11168 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11169 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11170 << FnName << SizeOfArgTy << ArgIdx
11171 << PointeeTy << Dest->getSourceRange()
11172 << LenExpr->getSourceRange());
11173 break;
11174 }
11175 }
11176 } else if (DestTy->isArrayType()) {
11177 PointeeTy = DestTy;
11178 }
11179
11180 if (PointeeTy == QualType())
11181 continue;
11182
11183 // Always complain about dynamic classes.
11184 bool IsContained;
11185 if (const CXXRecordDecl *ContainedRD =
11186 getContainedDynamicClass(PointeeTy, IsContained)) {
11187
11188 unsigned OperationType = 0;
11189 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11190 // "overwritten" if we're warning about the destination for any call
11191 // but memcmp; otherwise a verb appropriate to the call.
11192 if (ArgIdx != 0 || IsCmp) {
11193 if (BId == Builtin::BImemcpy)
11194 OperationType = 1;
11195 else if(BId == Builtin::BImemmove)
11196 OperationType = 2;
11197 else if (IsCmp)
11198 OperationType = 3;
11199 }
11200
11201 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11202 PDiag(diag::warn_dyn_class_memaccess)
11203 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11204 << IsContained << ContainedRD << OperationType
11205 << Call->getCallee()->getSourceRange());
11206 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11207 BId != Builtin::BImemset)
11209 Dest->getExprLoc(), Dest,
11210 PDiag(diag::warn_arc_object_memaccess)
11211 << ArgIdx << FnName << PointeeTy
11212 << Call->getCallee()->getSourceRange());
11213 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11214
11215 // FIXME: Do not consider incomplete types even though they may be
11216 // completed later. GCC does not diagnose such code, but we may want to
11217 // consider diagnosing it in the future, perhaps under a different, but
11218 // related, diagnostic group.
11219 bool NonTriviallyCopyableCXXRecord =
11220 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11221 !PointeeTy.isTriviallyCopyableType(Context);
11222
11223 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11225 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11226 PDiag(diag::warn_cstruct_memaccess)
11227 << ArgIdx << FnName << PointeeTy << 0);
11228 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11229 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11230 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11231 // FIXME: Limiting this warning to dest argument until we decide
11232 // whether it's valid for source argument too.
11233 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11234 PDiag(diag::warn_cxxstruct_memaccess)
11235 << FnName << PointeeTy);
11236 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11238 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11239 PDiag(diag::warn_cstruct_memaccess)
11240 << ArgIdx << FnName << PointeeTy << 1);
11241 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11242 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11243 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11244 // FIXME: Limiting this warning to dest argument until we decide
11245 // whether it's valid for source argument too.
11246 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11247 PDiag(diag::warn_cxxstruct_memaccess)
11248 << FnName << PointeeTy);
11249 } else {
11250 continue;
11251 }
11252 } else
11253 continue;
11254
11256 Dest->getExprLoc(), Dest,
11257 PDiag(diag::note_bad_memaccess_silence)
11258 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11259 break;
11260 }
11261}
11262
11263bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11264 IdentifierInfo *FnName) {
11265 llvm::FoldingSetNodeID SizeOfArgID;
11266 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11267 if (!SizeOfArg)
11268 return false;
11269 // Computing this warning is expensive, so we only do so if the warning is
11270 // enabled.
11271 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11272 SizeOfArg->getExprLoc()))
11273 return false;
11274 QualType DestTy = Dest->getType();
11275 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11276 if (!DestPtrTy)
11277 return false;
11278
11279 QualType PointeeTy = DestPtrTy->getPointeeType();
11280
11281 if (SizeOfArgID == llvm::FoldingSetNodeID())
11282 SizeOfArg->Profile(SizeOfArgID, Context, true);
11283
11284 llvm::FoldingSetNodeID DestID;
11285 Dest->Profile(DestID, Context, true);
11286 if (DestID == SizeOfArgID) {
11287 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11288 // over sizeof(src) as well.
11289 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11290 StringRef ReadableName = FnName->getName();
11291
11292 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11293 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11294 ActionIdx = 1; // If its an address-of operator, just remove it.
11295 if (!PointeeTy->isIncompleteType() &&
11296 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11297 ActionIdx = 2; // If the pointee's size is sizeof(char),
11298 // suggest an explicit length.
11299
11300 // If the function is defined as a builtin macro, do not show macro
11301 // expansion.
11302 SourceLocation SL = SizeOfArg->getExprLoc();
11303 SourceRange DSR = Dest->getSourceRange();
11304 SourceRange SSR = SizeOfArg->getSourceRange();
11305 SourceManager &SM = getSourceManager();
11306
11307 if (SM.isMacroArgExpansion(SL)) {
11308 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11309 SL = SM.getSpellingLoc(SL);
11310 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11311 SM.getSpellingLoc(DSR.getEnd()));
11312 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11313 SM.getSpellingLoc(SSR.getEnd()));
11314 }
11315
11316 DiagRuntimeBehavior(SL, SizeOfArg,
11317 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11318 << ReadableName << PointeeTy << DestTy << DSR
11319 << SSR);
11320 DiagRuntimeBehavior(SL, SizeOfArg,
11321 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11322 << ActionIdx << SSR);
11323 return true;
11324 }
11325 return false;
11326}
11327
11328// A little helper routine: ignore addition and subtraction of integer literals.
11329// This intentionally does not ignore all integer constant expressions because
11330// we don't want to remove sizeof().
11331static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11332 Ex = Ex->IgnoreParenCasts();
11333
11334 while (true) {
11335 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11336 if (!BO || !BO->isAdditiveOp())
11337 break;
11338
11339 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11340 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11341
11342 if (isa<IntegerLiteral>(RHS))
11343 Ex = LHS;
11344 else if (isa<IntegerLiteral>(LHS))
11345 Ex = RHS;
11346 else
11347 break;
11348 }
11349
11350 return Ex;
11351}
11352
11354 ASTContext &Context) {
11355 // Only handle constant-sized or VLAs, but not flexible members.
11356 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11357 // Only issue the FIXIT for arrays of size > 1.
11358 if (CAT->getZExtSize() <= 1)
11359 return false;
11360 } else if (!Ty->isVariableArrayType()) {
11361 return false;
11362 }
11363 return true;
11364}
11365
11366void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11367 IdentifierInfo *FnName) {
11368
11369 // Don't crash if the user has the wrong number of arguments
11370 unsigned NumArgs = Call->getNumArgs();
11371 if ((NumArgs != 3) && (NumArgs != 4))
11372 return;
11373
11374 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11375 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11376 const Expr *CompareWithSrc = nullptr;
11377
11378 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11379 Call->getBeginLoc(), Call->getRParenLoc()))
11380 return;
11381
11382 // Look for 'strlcpy(dst, x, sizeof(x))'
11383 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11384 CompareWithSrc = Ex;
11385 else {
11386 // Look for 'strlcpy(dst, x, strlen(x))'
11387 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11388 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11389 SizeCall->getNumArgs() == 1)
11390 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11391 }
11392 }
11393
11394 if (!CompareWithSrc)
11395 return;
11396
11397 // Determine if the argument to sizeof/strlen is equal to the source
11398 // argument. In principle there's all kinds of things you could do
11399 // here, for instance creating an == expression and evaluating it with
11400 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11401 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11402 if (!SrcArgDRE)
11403 return;
11404
11405 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11406 if (!CompareWithSrcDRE ||
11407 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11408 return;
11409
11410 const Expr *OriginalSizeArg = Call->getArg(2);
11411 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11412 << OriginalSizeArg->getSourceRange() << FnName;
11413
11414 // Output a FIXIT hint if the destination is an array (rather than a
11415 // pointer to an array). This could be enhanced to handle some
11416 // pointers if we know the actual size, like if DstArg is 'array+2'
11417 // we could say 'sizeof(array)-2'.
11418 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11420 return;
11421
11422 SmallString<128> sizeString;
11423 llvm::raw_svector_ostream OS(sizeString);
11424 OS << "sizeof(";
11425 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11426 OS << ")";
11427
11428 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11429 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11430 OS.str());
11431}
11432
11433/// Check if two expressions refer to the same declaration.
11434static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11435 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11436 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11437 return D1->getDecl() == D2->getDecl();
11438 return false;
11439}
11440
11441static const Expr *getStrlenExprArg(const Expr *E) {
11442 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11443 const FunctionDecl *FD = CE->getDirectCallee();
11444 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11445 return nullptr;
11446 return CE->getArg(0)->IgnoreParenCasts();
11447 }
11448 return nullptr;
11449}
11450
11451void Sema::CheckStrncatArguments(const CallExpr *CE,
11452 const IdentifierInfo *FnName) {
11453 // Don't crash if the user has the wrong number of arguments.
11454 if (CE->getNumArgs() < 3)
11455 return;
11456 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11457 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11458 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11459
11460 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11461 CE->getRParenLoc()))
11462 return;
11463
11464 // Identify common expressions, which are wrongly used as the size argument
11465 // to strncat and may lead to buffer overflows.
11466 unsigned PatternType = 0;
11467 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11468 // - sizeof(dst)
11469 if (referToTheSameDecl(SizeOfArg, DstArg))
11470 PatternType = 1;
11471 // - sizeof(src)
11472 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11473 PatternType = 2;
11474 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11475 if (BE->getOpcode() == BO_Sub) {
11476 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11477 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11478 // - sizeof(dst) - strlen(dst)
11479 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11481 PatternType = 1;
11482 // - sizeof(src) - (anything)
11483 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11484 PatternType = 2;
11485 }
11486 }
11487
11488 if (PatternType == 0)
11489 return;
11490
11491 // Generate the diagnostic.
11492 SourceLocation SL = LenArg->getBeginLoc();
11493 SourceRange SR = LenArg->getSourceRange();
11494 SourceManager &SM = getSourceManager();
11495
11496 // If the function is defined as a builtin macro, do not show macro expansion.
11497 if (SM.isMacroArgExpansion(SL)) {
11498 SL = SM.getSpellingLoc(SL);
11499 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11500 SM.getSpellingLoc(SR.getEnd()));
11501 }
11502
11503 // Check if the destination is an array (rather than a pointer to an array).
11504 QualType DstTy = DstArg->getType();
11505 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11506 Context);
11507 if (!isKnownSizeArray) {
11508 if (PatternType == 1)
11509 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11510 else
11511 Diag(SL, diag::warn_strncat_src_size) << SR;
11512 return;
11513 }
11514
11515 if (PatternType == 1)
11516 Diag(SL, diag::warn_strncat_large_size) << SR;
11517 else
11518 Diag(SL, diag::warn_strncat_src_size) << SR;
11519
11520 SmallString<128> sizeString;
11521 llvm::raw_svector_ostream OS(sizeString);
11522 OS << "sizeof(";
11523 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11524 OS << ") - ";
11525 OS << "strlen(";
11526 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11527 OS << ") - 1";
11528
11529 Diag(SL, diag::note_strncat_wrong_size)
11530 << FixItHint::CreateReplacement(SR, OS.str());
11531}
11532
11533namespace {
11534void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11535 const UnaryOperator *UnaryExpr, const Decl *D) {
11537 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11538 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11539 return;
11540 }
11541}
11542
11543void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11544 const UnaryOperator *UnaryExpr) {
11545 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11546 const Decl *D = Lvalue->getDecl();
11547 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11548 if (!DD->getType()->isReferenceType())
11549 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11550 }
11551 }
11552
11553 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11554 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11555 Lvalue->getMemberDecl());
11556}
11557
11558void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11559 const UnaryOperator *UnaryExpr) {
11560 const auto *Lambda = dyn_cast<LambdaExpr>(
11562 if (!Lambda)
11563 return;
11564
11565 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11566 << CalleeName << 2 /*object: lambda expression*/;
11567}
11568
11569void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11570 const DeclRefExpr *Lvalue) {
11571 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11572 if (Var == nullptr)
11573 return;
11574
11575 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11576 << CalleeName << 0 /*object: */ << Var;
11577}
11578
11579void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11580 const CastExpr *Cast) {
11581 SmallString<128> SizeString;
11582 llvm::raw_svector_ostream OS(SizeString);
11583
11584 clang::CastKind Kind = Cast->getCastKind();
11585 if (Kind == clang::CK_BitCast &&
11586 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11587 return;
11588 if (Kind == clang::CK_IntegralToPointer &&
11590 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11591 return;
11592
11593 switch (Cast->getCastKind()) {
11594 case clang::CK_BitCast:
11595 case clang::CK_IntegralToPointer:
11596 case clang::CK_FunctionToPointerDecay:
11597 OS << '\'';
11598 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11599 OS << '\'';
11600 break;
11601 default:
11602 return;
11603 }
11604
11605 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11606 << CalleeName << 0 /*object: */ << OS.str();
11607}
11608} // namespace
11609
11610void Sema::CheckFreeArguments(const CallExpr *E) {
11611 const std::string CalleeName =
11612 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11613
11614 { // Prefer something that doesn't involve a cast to make things simpler.
11615 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11616 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11617 switch (UnaryExpr->getOpcode()) {
11618 case UnaryOperator::Opcode::UO_AddrOf:
11619 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11620 case UnaryOperator::Opcode::UO_Plus:
11621 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11622 default:
11623 break;
11624 }
11625
11626 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11627 if (Lvalue->getType()->isArrayType())
11628 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11629
11630 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11631 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11632 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11633 return;
11634 }
11635
11636 if (isa<BlockExpr>(Arg)) {
11637 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11638 << CalleeName << 1 /*object: block*/;
11639 return;
11640 }
11641 }
11642 // Maybe the cast was important, check after the other cases.
11643 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11644 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11645}
11646
11647void
11648Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11649 SourceLocation ReturnLoc,
11650 bool isObjCMethod,
11651 const AttrVec *Attrs,
11652 const FunctionDecl *FD) {
11653 // Check if the return value is null but should not be.
11654 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11655 (!isObjCMethod && isNonNullType(lhsType))) &&
11656 CheckNonNullExpr(*this, RetValExp))
11657 Diag(ReturnLoc, diag::warn_null_ret)
11658 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11659
11660 // C++11 [basic.stc.dynamic.allocation]p4:
11661 // If an allocation function declared with a non-throwing
11662 // exception-specification fails to allocate storage, it shall return
11663 // a null pointer. Any other allocation function that fails to allocate
11664 // storage shall indicate failure only by throwing an exception [...]
11665 if (FD) {
11667 if (Op == OO_New || Op == OO_Array_New) {
11668 const FunctionProtoType *Proto
11669 = FD->getType()->castAs<FunctionProtoType>();
11670 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11671 CheckNonNullExpr(*this, RetValExp))
11672 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11673 << FD << getLangOpts().CPlusPlus11;
11674 }
11675 }
11676
11677 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11678 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11679 }
11680
11681 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11682 // here prevent the user from using a PPC MMA type as trailing return type.
11683 if (Context.getTargetInfo().getTriple().isPPC64())
11684 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11685}
11686
11688 const Expr *RHS, BinaryOperatorKind Opcode) {
11689 if (!BinaryOperator::isEqualityOp(Opcode))
11690 return;
11691
11692 // Match and capture subexpressions such as "(float) X == 0.1".
11693 const FloatingLiteral *FPLiteral;
11694 const CastExpr *FPCast;
11695 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11696 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11697 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11698 return FPLiteral && FPCast;
11699 };
11700
11701 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11702 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11703 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11704 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11705 TargetTy->isFloatingPoint()) {
11706 bool Lossy;
11707 llvm::APFloat TargetC = FPLiteral->getValue();
11708 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11709 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11710 if (Lossy) {
11711 // If the literal cannot be represented in the source type, then a
11712 // check for == is always false and check for != is always true.
11713 Diag(Loc, diag::warn_float_compare_literal)
11714 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11715 << LHS->getSourceRange() << RHS->getSourceRange();
11716 return;
11717 }
11718 }
11719 }
11720
11721 // Match a more general floating-point equality comparison (-Wfloat-equal).
11722 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11723 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11724
11725 // Special case: check for x == x (which is OK).
11726 // Do not emit warnings for such cases.
11727 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11728 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11729 if (DRL->getDecl() == DRR->getDecl())
11730 return;
11731
11732 // Special case: check for comparisons against literals that can be exactly
11733 // represented by APFloat. In such cases, do not emit a warning. This
11734 // is a heuristic: often comparison against such literals are used to
11735 // detect if a value in a variable has not changed. This clearly can
11736 // lead to false negatives.
11737 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11738 if (FLL->isExact())
11739 return;
11740 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11741 if (FLR->isExact())
11742 return;
11743
11744 // Check for comparisons with builtin types.
11745 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11746 CL && CL->getBuiltinCallee())
11747 return;
11748
11749 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11750 CR && CR->getBuiltinCallee())
11751 return;
11752
11753 // Emit the diagnostic.
11754 Diag(Loc, diag::warn_floatingpoint_eq)
11755 << LHS->getSourceRange() << RHS->getSourceRange();
11756}
11757
11758//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11759//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11760
11761namespace {
11762
11763/// Structure recording the 'active' range of an integer-valued
11764/// expression.
11765struct IntRange {
11766 /// The number of bits active in the int. Note that this includes exactly one
11767 /// sign bit if !NonNegative.
11768 unsigned Width;
11769
11770 /// True if the int is known not to have negative values. If so, all leading
11771 /// bits before Width are known zero, otherwise they are known to be the
11772 /// same as the MSB within Width.
11773 bool NonNegative;
11774
11775 IntRange(unsigned Width, bool NonNegative)
11776 : Width(Width), NonNegative(NonNegative) {}
11777
11778 /// Number of bits excluding the sign bit.
11779 unsigned valueBits() const {
11780 return NonNegative ? Width : Width - 1;
11781 }
11782
11783 /// Returns the range of the bool type.
11784 static IntRange forBoolType() {
11785 return IntRange(1, true);
11786 }
11787
11788 /// Returns the range of an opaque value of the given integral type.
11789 static IntRange forValueOfType(ASTContext &C, QualType T) {
11790 return forValueOfCanonicalType(C,
11792 }
11793
11794 /// Returns the range of an opaque value of a canonical integral type.
11795 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11796 assert(T->isCanonicalUnqualified());
11797
11798 if (const auto *VT = dyn_cast<VectorType>(T))
11799 T = VT->getElementType().getTypePtr();
11800 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11801 T = MT->getElementType().getTypePtr();
11802 if (const auto *CT = dyn_cast<ComplexType>(T))
11803 T = CT->getElementType().getTypePtr();
11804 if (const auto *AT = dyn_cast<AtomicType>(T))
11805 T = AT->getValueType().getTypePtr();
11806 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11807 T = OBT->getUnderlyingType().getTypePtr();
11808
11809 if (!C.getLangOpts().CPlusPlus) {
11810 // For enum types in C code, use the underlying datatype.
11811 if (const auto *ED = T->getAsEnumDecl())
11812 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11813 } else if (auto *Enum = T->getAsEnumDecl()) {
11814 // For enum types in C++, use the known bit width of the enumerators.
11815 // In C++11, enums can have a fixed underlying type. Use this type to
11816 // compute the range.
11817 if (Enum->isFixed()) {
11818 return IntRange(C.getIntWidth(QualType(T, 0)),
11819 !Enum->getIntegerType()->isSignedIntegerType());
11820 }
11821
11822 unsigned NumPositive = Enum->getNumPositiveBits();
11823 unsigned NumNegative = Enum->getNumNegativeBits();
11824
11825 if (NumNegative == 0)
11826 return IntRange(NumPositive, true/*NonNegative*/);
11827 else
11828 return IntRange(std::max(NumPositive + 1, NumNegative),
11829 false/*NonNegative*/);
11830 }
11831
11832 if (const auto *EIT = dyn_cast<BitIntType>(T))
11833 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11834
11835 const BuiltinType *BT = cast<BuiltinType>(T);
11836 assert(BT->isInteger());
11837
11838 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11839 }
11840
11841 /// Returns the "target" range of a canonical integral type, i.e.
11842 /// the range of values expressible in the type.
11843 ///
11844 /// This matches forValueOfCanonicalType except that enums have the
11845 /// full range of their type, not the range of their enumerators.
11846 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11847 assert(T->isCanonicalUnqualified());
11848
11849 if (const VectorType *VT = dyn_cast<VectorType>(T))
11850 T = VT->getElementType().getTypePtr();
11851 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11852 T = MT->getElementType().getTypePtr();
11853 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11854 T = CT->getElementType().getTypePtr();
11855 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11856 T = AT->getValueType().getTypePtr();
11857 if (const auto *ED = T->getAsEnumDecl())
11858 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11859 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11860 T = OBT->getUnderlyingType().getTypePtr();
11861
11862 if (const auto *EIT = dyn_cast<BitIntType>(T))
11863 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11864
11865 const BuiltinType *BT = cast<BuiltinType>(T);
11866 assert(BT->isInteger());
11867
11868 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11869 }
11870
11871 /// Returns the supremum of two ranges: i.e. their conservative merge.
11872 static IntRange join(IntRange L, IntRange R) {
11873 bool Unsigned = L.NonNegative && R.NonNegative;
11874 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11875 L.NonNegative && R.NonNegative);
11876 }
11877
11878 /// Return the range of a bitwise-AND of the two ranges.
11879 static IntRange bit_and(IntRange L, IntRange R) {
11880 unsigned Bits = std::max(L.Width, R.Width);
11881 bool NonNegative = false;
11882 if (L.NonNegative) {
11883 Bits = std::min(Bits, L.Width);
11884 NonNegative = true;
11885 }
11886 if (R.NonNegative) {
11887 Bits = std::min(Bits, R.Width);
11888 NonNegative = true;
11889 }
11890 return IntRange(Bits, NonNegative);
11891 }
11892
11893 /// Return the range of a sum of the two ranges.
11894 static IntRange sum(IntRange L, IntRange R) {
11895 bool Unsigned = L.NonNegative && R.NonNegative;
11896 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11897 Unsigned);
11898 }
11899
11900 /// Return the range of a difference of the two ranges.
11901 static IntRange difference(IntRange L, IntRange R) {
11902 // We need a 1-bit-wider range if:
11903 // 1) LHS can be negative: least value can be reduced.
11904 // 2) RHS can be negative: greatest value can be increased.
11905 bool CanWiden = !L.NonNegative || !R.NonNegative;
11906 bool Unsigned = L.NonNegative && R.Width == 0;
11907 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11908 !Unsigned,
11909 Unsigned);
11910 }
11911
11912 /// Return the range of a product of the two ranges.
11913 static IntRange product(IntRange L, IntRange R) {
11914 // If both LHS and RHS can be negative, we can form
11915 // -2^L * -2^R = 2^(L + R)
11916 // which requires L + R + 1 value bits to represent.
11917 bool CanWiden = !L.NonNegative && !R.NonNegative;
11918 bool Unsigned = L.NonNegative && R.NonNegative;
11919 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11920 Unsigned);
11921 }
11922
11923 /// Return the range of a remainder operation between the two ranges.
11924 static IntRange rem(IntRange L, IntRange R) {
11925 // The result of a remainder can't be larger than the result of
11926 // either side. The sign of the result is the sign of the LHS.
11927 bool Unsigned = L.NonNegative;
11928 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11929 Unsigned);
11930 }
11931};
11932
11933} // namespace
11934
11935static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11936 if (value.isSigned() && value.isNegative())
11937 return IntRange(value.getSignificantBits(), false);
11938
11939 if (value.getBitWidth() > MaxWidth)
11940 value = value.trunc(MaxWidth);
11941
11942 // isNonNegative() just checks the sign bit without considering
11943 // signedness.
11944 return IntRange(value.getActiveBits(), true);
11945}
11946
11947static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11948 if (result.isInt())
11949 return GetValueRange(result.getInt(), MaxWidth);
11950
11951 if (result.isVector()) {
11952 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11953 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11954 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11955 R = IntRange::join(R, El);
11956 }
11957 return R;
11958 }
11959
11960 if (result.isComplexInt()) {
11961 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11962 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11963 return IntRange::join(R, I);
11964 }
11965
11966 // This can happen with lossless casts to intptr_t of "based" lvalues.
11967 // Assume it might use arbitrary bits.
11968 // FIXME: The only reason we need to pass the type in here is to get
11969 // the sign right on this one case. It would be nice if APValue
11970 // preserved this.
11971 assert(result.isLValue() || result.isAddrLabelDiff());
11972 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11973}
11974
11975static QualType GetExprType(const Expr *E) {
11976 QualType Ty = E->getType();
11977 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11978 Ty = AtomicRHS->getValueType();
11979 return Ty;
11980}
11981
11982/// Attempts to estimate an approximate range for the given integer expression.
11983/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11984/// reliable estimation cannot be determined.
11985///
11986/// \param MaxWidth The width to which the value will be truncated.
11987/// \param InConstantContext If \c true, interpret the expression within a
11988/// constant context.
11989/// \param Approximate If \c true, provide a likely range of values by assuming
11990/// that arithmetic on narrower types remains within those types.
11991/// If \c false, return a range that includes all possible values
11992/// resulting from the expression.
11993/// \returns A range of values that the expression might take, or
11994/// std::nullopt if a reliable estimation cannot be determined.
11995static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11996 unsigned MaxWidth,
11997 bool InConstantContext,
11998 bool Approximate) {
11999 E = E->IgnoreParens();
12000
12001 // Try a full evaluation first.
12002 Expr::EvalResult result;
12003 if (E->EvaluateAsRValue(result, C, InConstantContext))
12004 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
12005
12006 // I think we only want to look through implicit casts here; if the
12007 // user has an explicit widening cast, we should treat the value as
12008 // being of the new, wider type.
12009 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
12010 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12011 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
12012 Approximate);
12013
12014 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
12015
12016 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12017 CE->getCastKind() == CK_BooleanToSignedIntegral;
12018
12019 // Assume that non-integer casts can span the full range of the type.
12020 if (!isIntegerCast)
12021 return OutputTypeRange;
12022
12023 std::optional<IntRange> SubRange = TryGetExprRange(
12024 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
12025 InConstantContext, Approximate);
12026 if (!SubRange)
12027 return std::nullopt;
12028
12029 // Bail out if the subexpr's range is as wide as the cast type.
12030 if (SubRange->Width >= OutputTypeRange.Width)
12031 return OutputTypeRange;
12032
12033 // Otherwise, we take the smaller width, and we're non-negative if
12034 // either the output type or the subexpr is.
12035 return IntRange(SubRange->Width,
12036 SubRange->NonNegative || OutputTypeRange.NonNegative);
12037 }
12038
12039 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12040 // If we can fold the condition, just take that operand.
12041 bool CondResult;
12042 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12043 return TryGetExprRange(
12044 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12045 InConstantContext, Approximate);
12046
12047 // Otherwise, conservatively merge.
12048 // TryGetExprRange requires an integer expression, but a throw expression
12049 // results in a void type.
12050 Expr *TrueExpr = CO->getTrueExpr();
12051 if (TrueExpr->getType()->isVoidType())
12052 return std::nullopt;
12053
12054 std::optional<IntRange> L =
12055 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
12056 if (!L)
12057 return std::nullopt;
12058
12059 Expr *FalseExpr = CO->getFalseExpr();
12060 if (FalseExpr->getType()->isVoidType())
12061 return std::nullopt;
12062
12063 std::optional<IntRange> R =
12064 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
12065 if (!R)
12066 return std::nullopt;
12067
12068 return IntRange::join(*L, *R);
12069 }
12070
12071 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12072 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12073
12074 switch (BO->getOpcode()) {
12075 case BO_Cmp:
12076 llvm_unreachable("builtin <=> should have class type");
12077
12078 // Boolean-valued operations are single-bit and positive.
12079 case BO_LAnd:
12080 case BO_LOr:
12081 case BO_LT:
12082 case BO_GT:
12083 case BO_LE:
12084 case BO_GE:
12085 case BO_EQ:
12086 case BO_NE:
12087 return IntRange::forBoolType();
12088
12089 // The type of the assignments is the type of the LHS, so the RHS
12090 // is not necessarily the same type.
12091 case BO_MulAssign:
12092 case BO_DivAssign:
12093 case BO_RemAssign:
12094 case BO_AddAssign:
12095 case BO_SubAssign:
12096 case BO_XorAssign:
12097 case BO_OrAssign:
12098 // TODO: bitfields?
12099 return IntRange::forValueOfType(C, GetExprType(E));
12100
12101 // Simple assignments just pass through the RHS, which will have
12102 // been coerced to the LHS type.
12103 case BO_Assign:
12104 // TODO: bitfields?
12105 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12106 Approximate);
12107
12108 // Operations with opaque sources are black-listed.
12109 case BO_PtrMemD:
12110 case BO_PtrMemI:
12111 return IntRange::forValueOfType(C, GetExprType(E));
12112
12113 // Bitwise-and uses the *infinum* of the two source ranges.
12114 case BO_And:
12115 case BO_AndAssign:
12116 Combine = IntRange::bit_and;
12117 break;
12118
12119 // Left shift gets black-listed based on a judgement call.
12120 case BO_Shl:
12121 // ...except that we want to treat '1 << (blah)' as logically
12122 // positive. It's an important idiom.
12123 if (IntegerLiteral *I
12124 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12125 if (I->getValue() == 1) {
12126 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12127 return IntRange(R.Width, /*NonNegative*/ true);
12128 }
12129 }
12130 [[fallthrough]];
12131
12132 case BO_ShlAssign:
12133 return IntRange::forValueOfType(C, GetExprType(E));
12134
12135 // Right shift by a constant can narrow its left argument.
12136 case BO_Shr:
12137 case BO_ShrAssign: {
12138 std::optional<IntRange> L = TryGetExprRange(
12139 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12140 if (!L)
12141 return std::nullopt;
12142
12143 // If the shift amount is a positive constant, drop the width by
12144 // that much.
12145 if (std::optional<llvm::APSInt> shift =
12146 BO->getRHS()->getIntegerConstantExpr(C)) {
12147 if (shift->isNonNegative()) {
12148 if (shift->uge(L->Width))
12149 L->Width = (L->NonNegative ? 0 : 1);
12150 else
12151 L->Width -= shift->getZExtValue();
12152 }
12153 }
12154
12155 return L;
12156 }
12157
12158 // Comma acts as its right operand.
12159 case BO_Comma:
12160 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12161 Approximate);
12162
12163 case BO_Add:
12164 if (!Approximate)
12165 Combine = IntRange::sum;
12166 break;
12167
12168 case BO_Sub:
12169 if (BO->getLHS()->getType()->isPointerType())
12170 return IntRange::forValueOfType(C, GetExprType(E));
12171 if (!Approximate)
12172 Combine = IntRange::difference;
12173 break;
12174
12175 case BO_Mul:
12176 if (!Approximate)
12177 Combine = IntRange::product;
12178 break;
12179
12180 // The width of a division result is mostly determined by the size
12181 // of the LHS.
12182 case BO_Div: {
12183 // Don't 'pre-truncate' the operands.
12184 unsigned opWidth = C.getIntWidth(GetExprType(E));
12185 std::optional<IntRange> L = TryGetExprRange(
12186 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12187 if (!L)
12188 return std::nullopt;
12189
12190 // If the divisor is constant, use that.
12191 if (std::optional<llvm::APSInt> divisor =
12192 BO->getRHS()->getIntegerConstantExpr(C)) {
12193 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12194 if (log2 >= L->Width)
12195 L->Width = (L->NonNegative ? 0 : 1);
12196 else
12197 L->Width = std::min(L->Width - log2, MaxWidth);
12198 return L;
12199 }
12200
12201 // Otherwise, just use the LHS's width.
12202 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12203 // could be -1.
12204 std::optional<IntRange> R = TryGetExprRange(
12205 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12206 if (!R)
12207 return std::nullopt;
12208
12209 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12210 }
12211
12212 case BO_Rem:
12213 Combine = IntRange::rem;
12214 break;
12215
12216 // The default behavior is okay for these.
12217 case BO_Xor:
12218 case BO_Or:
12219 break;
12220 }
12221
12222 // Combine the two ranges, but limit the result to the type in which we
12223 // performed the computation.
12224 QualType T = GetExprType(E);
12225 unsigned opWidth = C.getIntWidth(T);
12226 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12227 InConstantContext, Approximate);
12228 if (!L)
12229 return std::nullopt;
12230
12231 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12232 InConstantContext, Approximate);
12233 if (!R)
12234 return std::nullopt;
12235
12236 IntRange C = Combine(*L, *R);
12237 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12238 C.Width = std::min(C.Width, MaxWidth);
12239 return C;
12240 }
12241
12242 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12243 switch (UO->getOpcode()) {
12244 // Boolean-valued operations are white-listed.
12245 case UO_LNot:
12246 return IntRange::forBoolType();
12247
12248 // Operations with opaque sources are black-listed.
12249 case UO_Deref:
12250 case UO_AddrOf: // should be impossible
12251 return IntRange::forValueOfType(C, GetExprType(E));
12252
12253 case UO_Minus: {
12254 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12255 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12256 Approximate);
12257 }
12258
12259 std::optional<IntRange> SubRange = TryGetExprRange(
12260 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12261
12262 if (!SubRange)
12263 return std::nullopt;
12264
12265 // If the range was previously non-negative, we need an extra bit for the
12266 // sign bit. Otherwise, we need an extra bit because the negation of the
12267 // most-negative value is one bit wider than that value.
12268 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12269 }
12270
12271 case UO_Not: {
12272 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12273 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12274 Approximate);
12275 }
12276
12277 std::optional<IntRange> SubRange = TryGetExprRange(
12278 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12279
12280 if (!SubRange)
12281 return std::nullopt;
12282
12283 // The width increments by 1 if the sub-expression cannot be negative
12284 // since it now can be.
12285 return IntRange(
12286 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12287 false);
12288 }
12289
12290 default:
12291 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12292 Approximate);
12293 }
12294 }
12295
12296 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12297 // The source expression is null for the OpaqueValueExpr that stands in for
12298 // a non-type template argument of pointer or reference type; fall back to
12299 // the range of the type in that case.
12300 if (const Expr *SourceExpr = OVE->getSourceExpr())
12301 return TryGetExprRange(C, SourceExpr, MaxWidth, InConstantContext,
12302 Approximate);
12303 }
12304
12305 if (const auto *BitField = E->getSourceBitField())
12306 return IntRange(BitField->getBitWidthValue(),
12307 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12308
12309 if (GetExprType(E)->isVoidType())
12310 return std::nullopt;
12311
12312 return IntRange::forValueOfType(C, GetExprType(E));
12313}
12314
12315static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12316 bool InConstantContext,
12317 bool Approximate) {
12318 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12319 Approximate);
12320}
12321
12322/// Checks whether the given value, which currently has the given
12323/// source semantics, has the same value when coerced through the
12324/// target semantics.
12325static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12326 const llvm::fltSemantics &Src,
12327 const llvm::fltSemantics &Tgt) {
12328 llvm::APFloat truncated = value;
12329
12330 bool ignored;
12331 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12332 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12333
12334 return truncated.bitwiseIsEqual(value);
12335}
12336
12337/// Checks whether the given value, which currently has the given
12338/// source semantics, has the same value when coerced through the
12339/// target semantics.
12340///
12341/// The value might be a vector of floats (or a complex number).
12342static bool IsSameFloatAfterCast(const APValue &value,
12343 const llvm::fltSemantics &Src,
12344 const llvm::fltSemantics &Tgt) {
12345 if (value.isFloat())
12346 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12347
12348 if (value.isVector()) {
12349 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12350 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12351 return false;
12352 return true;
12353 }
12354
12355 if (value.isMatrix()) {
12356 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12357 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12358 return false;
12359 return true;
12360 }
12361
12362 assert(value.isComplexFloat());
12363 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12364 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12365}
12366
12367static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12368 bool IsListInit = false);
12369
12370static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12371 // Suppress cases where we are comparing against an enum constant.
12372 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12373 if (isa<EnumConstantDecl>(DR->getDecl()))
12374 return true;
12375
12376 // Suppress cases where the value is expanded from a macro, unless that macro
12377 // is how a language represents a boolean literal. This is the case in both C
12378 // and Objective-C.
12379 SourceLocation BeginLoc = E->getBeginLoc();
12380 if (BeginLoc.isMacroID()) {
12381 StringRef MacroName = Lexer::getImmediateMacroName(
12382 BeginLoc, S.getSourceManager(), S.getLangOpts());
12383 return MacroName != "YES" && MacroName != "NO" &&
12384 MacroName != "true" && MacroName != "false";
12385 }
12386
12387 return false;
12388}
12389
12390static bool isKnownToHaveUnsignedValue(const Expr *E) {
12391 return E->getType()->isIntegerType() &&
12392 (!E->getType()->isSignedIntegerType() ||
12394}
12395
12396namespace {
12397/// The promoted range of values of a type. In general this has the
12398/// following structure:
12399///
12400/// |-----------| . . . |-----------|
12401/// ^ ^ ^ ^
12402/// Min HoleMin HoleMax Max
12403///
12404/// ... where there is only a hole if a signed type is promoted to unsigned
12405/// (in which case Min and Max are the smallest and largest representable
12406/// values).
12407struct PromotedRange {
12408 // Min, or HoleMax if there is a hole.
12409 llvm::APSInt PromotedMin;
12410 // Max, or HoleMin if there is a hole.
12411 llvm::APSInt PromotedMax;
12412
12413 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12414 if (R.Width == 0)
12415 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12416 else if (R.Width >= BitWidth && !Unsigned) {
12417 // Promotion made the type *narrower*. This happens when promoting
12418 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12419 // Treat all values of 'signed int' as being in range for now.
12420 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12421 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12422 } else {
12423 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12424 .extOrTrunc(BitWidth);
12425 PromotedMin.setIsUnsigned(Unsigned);
12426
12427 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12428 .extOrTrunc(BitWidth);
12429 PromotedMax.setIsUnsigned(Unsigned);
12430 }
12431 }
12432
12433 // Determine whether this range is contiguous (has no hole).
12434 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12435
12436 // Where a constant value is within the range.
12437 enum ComparisonResult {
12438 LT = 0x1,
12439 LE = 0x2,
12440 GT = 0x4,
12441 GE = 0x8,
12442 EQ = 0x10,
12443 NE = 0x20,
12444 InRangeFlag = 0x40,
12445
12446 Less = LE | LT | NE,
12447 Min = LE | InRangeFlag,
12448 InRange = InRangeFlag,
12449 Max = GE | InRangeFlag,
12450 Greater = GE | GT | NE,
12451
12452 OnlyValue = LE | GE | EQ | InRangeFlag,
12453 InHole = NE
12454 };
12455
12456 ComparisonResult compare(const llvm::APSInt &Value) const {
12457 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12458 Value.isUnsigned() == PromotedMin.isUnsigned());
12459 if (!isContiguous()) {
12460 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12461 if (Value.isMinValue()) return Min;
12462 if (Value.isMaxValue()) return Max;
12463 if (Value >= PromotedMin) return InRange;
12464 if (Value <= PromotedMax) return InRange;
12465 return InHole;
12466 }
12467
12468 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12469 case -1: return Less;
12470 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12471 case 1:
12472 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12473 case -1: return InRange;
12474 case 0: return Max;
12475 case 1: return Greater;
12476 }
12477 }
12478
12479 llvm_unreachable("impossible compare result");
12480 }
12481
12482 static std::optional<StringRef>
12483 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12484 if (Op == BO_Cmp) {
12485 ComparisonResult LTFlag = LT, GTFlag = GT;
12486 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12487
12488 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12489 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12490 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12491 return std::nullopt;
12492 }
12493
12494 ComparisonResult TrueFlag, FalseFlag;
12495 if (Op == BO_EQ) {
12496 TrueFlag = EQ;
12497 FalseFlag = NE;
12498 } else if (Op == BO_NE) {
12499 TrueFlag = NE;
12500 FalseFlag = EQ;
12501 } else {
12502 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12503 TrueFlag = LT;
12504 FalseFlag = GE;
12505 } else {
12506 TrueFlag = GT;
12507 FalseFlag = LE;
12508 }
12509 if (Op == BO_GE || Op == BO_LE)
12510 std::swap(TrueFlag, FalseFlag);
12511 }
12512 if (R & TrueFlag)
12513 return StringRef("true");
12514 if (R & FalseFlag)
12515 return StringRef("false");
12516 return std::nullopt;
12517 }
12518};
12519}
12520
12521static bool HasEnumType(const Expr *E) {
12522 // Strip off implicit integral promotions.
12523 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12524 if (ICE->getCastKind() != CK_IntegralCast &&
12525 ICE->getCastKind() != CK_NoOp)
12526 break;
12527 E = ICE->getSubExpr();
12528 }
12529
12530 return E->getType()->isEnumeralType();
12531}
12532
12534 // The values of this enumeration are used in the diagnostics
12535 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12536 enum ConstantValueKind {
12537 Miscellaneous = 0,
12538 LiteralTrue,
12539 LiteralFalse
12540 };
12541 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12542 return BL->getValue() ? ConstantValueKind::LiteralTrue
12543 : ConstantValueKind::LiteralFalse;
12544 return ConstantValueKind::Miscellaneous;
12545}
12546
12549 const llvm::APSInt &Value,
12550 bool RhsConstant) {
12552 return false;
12553
12554 Expr *OriginalOther = Other;
12555
12556 Constant = Constant->IgnoreParenImpCasts();
12557 Other = Other->IgnoreParenImpCasts();
12558
12559 // Suppress warnings on tautological comparisons between values of the same
12560 // enumeration type. There are only two ways we could warn on this:
12561 // - If the constant is outside the range of representable values of
12562 // the enumeration. In such a case, we should warn about the cast
12563 // to enumeration type, not about the comparison.
12564 // - If the constant is the maximum / minimum in-range value. For an
12565 // enumeratin type, such comparisons can be meaningful and useful.
12566 if (Constant->getType()->isEnumeralType() &&
12567 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12568 return false;
12569
12570 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12571 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12572 if (!OtherValueRange)
12573 return false;
12574
12575 QualType OtherT = Other->getType();
12576 if (const auto *AT = OtherT->getAs<AtomicType>())
12577 OtherT = AT->getValueType();
12578 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12579
12580 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12581 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12582 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12583 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12584 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12585
12586 // Whether we're treating Other as being a bool because of the form of
12587 // expression despite it having another type (typically 'int' in C).
12588 bool OtherIsBooleanDespiteType =
12589 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12590 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12591 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12592
12593 // Check if all values in the range of possible values of this expression
12594 // lead to the same comparison outcome.
12595 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12596 Value.isUnsigned());
12597 auto Cmp = OtherPromotedValueRange.compare(Value);
12598 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12599 if (!Result)
12600 return false;
12601
12602 // Also consider the range determined by the type alone. This allows us to
12603 // classify the warning under the proper diagnostic group.
12604 bool TautologicalTypeCompare = false;
12605 {
12606 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12607 Value.isUnsigned());
12608 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12609 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12610 RhsConstant)) {
12611 TautologicalTypeCompare = true;
12612 Cmp = TypeCmp;
12614 }
12615 }
12616
12617 // Don't warn if the non-constant operand actually always evaluates to the
12618 // same value.
12619 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12620 return false;
12621
12622 // Suppress the diagnostic for an in-range comparison if the constant comes
12623 // from a macro or enumerator. We don't want to diagnose
12624 //
12625 // some_long_value <= INT_MAX
12626 //
12627 // when sizeof(int) == sizeof(long).
12628 bool InRange = Cmp & PromotedRange::InRangeFlag;
12629 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12630 return false;
12631
12632 // A comparison of an unsigned bit-field against 0 is really a type problem,
12633 // even though at the type level the bit-field might promote to 'signed int'.
12634 if (Other->refersToBitField() && InRange && Value == 0 &&
12635 Other->getType()->isUnsignedIntegerOrEnumerationType())
12636 TautologicalTypeCompare = true;
12637
12638 // If this is a comparison to an enum constant, include that
12639 // constant in the diagnostic.
12640 const EnumConstantDecl *ED = nullptr;
12641 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12642 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12643
12644 // Should be enough for uint128 (39 decimal digits)
12645 SmallString<64> PrettySourceValue;
12646 llvm::raw_svector_ostream OS(PrettySourceValue);
12647 if (ED) {
12648 OS << '\'' << *ED << "' (" << Value << ")";
12649 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12650 Constant->IgnoreParenImpCasts())) {
12651 OS << (BL->getValue() ? "YES" : "NO");
12652 } else {
12653 OS << Value;
12654 }
12655
12656 if (!TautologicalTypeCompare) {
12657 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12658 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12659 << E->getOpcodeStr() << OS.str() << *Result
12660 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12661 return true;
12662 }
12663
12664 if (IsObjCSignedCharBool) {
12666 S.PDiag(diag::warn_tautological_compare_objc_bool)
12667 << OS.str() << *Result);
12668 return true;
12669 }
12670
12671 // FIXME: We use a somewhat different formatting for the in-range cases and
12672 // cases involving boolean values for historical reasons. We should pick a
12673 // consistent way of presenting these diagnostics.
12674 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12675
12677 E->getOperatorLoc(), E,
12678 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12679 : diag::warn_tautological_bool_compare)
12680 << OS.str() << classifyConstantValue(Constant) << OtherT
12681 << OtherIsBooleanDespiteType << *Result
12682 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12683 } else {
12684 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12685 unsigned Diag =
12686 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12687 ? (HasEnumType(OriginalOther)
12688 ? diag::warn_unsigned_enum_always_true_comparison
12689 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12690 : diag::warn_unsigned_always_true_comparison)
12691 : diag::warn_tautological_constant_compare;
12692
12693 S.Diag(E->getOperatorLoc(), Diag)
12694 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12695 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12696 }
12697
12698 return true;
12699}
12700
12701/// Analyze the operands of the given comparison. Implements the
12702/// fallback case from AnalyzeComparison.
12707
12708/// Implements -Wsign-compare.
12709///
12710/// \param E the binary operator to check for warnings
12712 // The type the comparison is being performed in.
12713 QualType T = E->getLHS()->getType();
12714
12715 // Only analyze comparison operators where both sides have been converted to
12716 // the same type.
12718 return AnalyzeImpConvsInComparison(S, E);
12719
12720 // Don't analyze value-dependent comparisons directly.
12721 if (E->isValueDependent())
12722 return AnalyzeImpConvsInComparison(S, E);
12723
12724 Expr *LHS = E->getLHS();
12725 Expr *RHS = E->getRHS();
12726
12727 if (T->isIntegralType(S.Context)) {
12728 std::optional<llvm::APSInt> RHSValue =
12730 std::optional<llvm::APSInt> LHSValue =
12732
12733 // We don't care about expressions whose result is a constant.
12734 if (RHSValue && LHSValue)
12735 return AnalyzeImpConvsInComparison(S, E);
12736
12737 // We only care about expressions where just one side is literal
12738 if ((bool)RHSValue ^ (bool)LHSValue) {
12739 // Is the constant on the RHS or LHS?
12740 const bool RhsConstant = (bool)RHSValue;
12741 Expr *Const = RhsConstant ? RHS : LHS;
12742 Expr *Other = RhsConstant ? LHS : RHS;
12743 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12744
12745 // Check whether an integer constant comparison results in a value
12746 // of 'true' or 'false'.
12747 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12748 return AnalyzeImpConvsInComparison(S, E);
12749 }
12750 }
12751
12752 if (!T->hasUnsignedIntegerRepresentation()) {
12753 // We don't do anything special if this isn't an unsigned integral
12754 // comparison: we're only interested in integral comparisons, and
12755 // signed comparisons only happen in cases we don't care to warn about.
12756 return AnalyzeImpConvsInComparison(S, E);
12757 }
12758
12759 LHS = LHS->IgnoreParenImpCasts();
12760 RHS = RHS->IgnoreParenImpCasts();
12761
12762 if (!S.getLangOpts().CPlusPlus) {
12763 // Avoid warning about comparison of integers with different signs when
12764 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12765 // the type of `E`.
12766 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12767 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12768 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12769 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12770 }
12771
12772 // Check to see if one of the (unmodified) operands is of different
12773 // signedness.
12774 Expr *signedOperand, *unsignedOperand;
12776 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12777 "unsigned comparison between two signed integer expressions?");
12778 signedOperand = LHS;
12779 unsignedOperand = RHS;
12780 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12781 signedOperand = RHS;
12782 unsignedOperand = LHS;
12783 } else {
12784 return AnalyzeImpConvsInComparison(S, E);
12785 }
12786
12787 // Otherwise, calculate the effective range of the signed operand.
12788 std::optional<IntRange> signedRange =
12790 /*Approximate=*/true);
12791 if (!signedRange)
12792 return;
12793
12794 // Go ahead and analyze implicit conversions in the operands. Note
12795 // that we skip the implicit conversions on both sides.
12798
12799 // If the signed range is non-negative, -Wsign-compare won't fire.
12800 if (signedRange->NonNegative)
12801 return;
12802
12803 // For (in)equality comparisons, if the unsigned operand is a
12804 // constant which cannot collide with a overflowed signed operand,
12805 // then reinterpreting the signed operand as unsigned will not
12806 // change the result of the comparison.
12807 if (E->isEqualityOp()) {
12808 unsigned comparisonWidth = S.Context.getIntWidth(T);
12809 std::optional<IntRange> unsignedRange = TryGetExprRange(
12810 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12811 /*Approximate=*/true);
12812 if (!unsignedRange)
12813 return;
12814
12815 // We should never be unable to prove that the unsigned operand is
12816 // non-negative.
12817 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12818
12819 if (unsignedRange->Width < comparisonWidth)
12820 return;
12821 }
12822
12824 S.PDiag(diag::warn_mixed_sign_comparison)
12825 << LHS->getType() << RHS->getType()
12826 << LHS->getSourceRange() << RHS->getSourceRange());
12827}
12828
12829/// Analyzes an attempt to assign the given value to a bitfield.
12830///
12831/// Returns true if there was something fishy about the attempt.
12833 SourceLocation InitLoc) {
12834 assert(Bitfield->isBitField());
12835 if (Bitfield->isInvalidDecl())
12836 return false;
12837
12838 // White-list bool bitfields.
12839 QualType BitfieldType = Bitfield->getType();
12840 if (BitfieldType->isBooleanType())
12841 return false;
12842
12843 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12844 // If the underlying enum type was not explicitly specified as an unsigned
12845 // type and the enum contain only positive values, MSVC++ will cause an
12846 // inconsistency by storing this as a signed type.
12847 if (S.getLangOpts().CPlusPlus11 &&
12848 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12849 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12850 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12851 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12852 << BitfieldEnumDecl;
12853 }
12854 }
12855
12856 // Ignore value- or type-dependent expressions.
12857 if (Bitfield->getBitWidth()->isValueDependent() ||
12858 Bitfield->getBitWidth()->isTypeDependent() ||
12859 Init->isValueDependent() ||
12860 Init->isTypeDependent())
12861 return false;
12862
12863 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12864 unsigned FieldWidth = Bitfield->getBitWidthValue();
12865
12867 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12869 // The RHS is not constant. If the RHS has an enum type, make sure the
12870 // bitfield is wide enough to hold all the values of the enum without
12871 // truncation.
12872 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12873 const PreferredTypeAttr *PTAttr = nullptr;
12874 if (!ED) {
12875 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12876 if (PTAttr)
12877 ED = PTAttr->getType()->getAsEnumDecl();
12878 }
12879 if (ED) {
12880 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12881
12882 // Enum types are implicitly signed on Windows, so check if there are any
12883 // negative enumerators to see if the enum was intended to be signed or
12884 // not.
12885 bool SignedEnum = ED->getNumNegativeBits() > 0;
12886
12887 // Check for surprising sign changes when assigning enum values to a
12888 // bitfield of different signedness. If the bitfield is signed and we
12889 // have exactly the right number of bits to store this unsigned enum,
12890 // suggest changing the enum to an unsigned type. This typically happens
12891 // on Windows where unfixed enums always use an underlying type of 'int'.
12892 unsigned DiagID = 0;
12893 if (SignedEnum && !SignedBitfield) {
12894 DiagID =
12895 PTAttr == nullptr
12896 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12897 : diag::
12898 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12899 } else if (SignedBitfield && !SignedEnum &&
12900 ED->getNumPositiveBits() == FieldWidth) {
12901 DiagID =
12902 PTAttr == nullptr
12903 ? diag::warn_signed_bitfield_enum_conversion
12904 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12905 }
12906 if (DiagID) {
12907 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12908 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12909 SourceRange TypeRange =
12910 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12911 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12912 << SignedEnum << TypeRange;
12913 if (PTAttr)
12914 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12915 << ED;
12916 }
12917
12918 // Compute the required bitwidth. If the enum has negative values, we need
12919 // one more bit than the normal number of positive bits to represent the
12920 // sign bit.
12921 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12922 ED->getNumNegativeBits())
12923 : ED->getNumPositiveBits();
12924
12925 // Check the bitwidth.
12926 if (BitsNeeded > FieldWidth) {
12927 Expr *WidthExpr = Bitfield->getBitWidth();
12928 auto DiagID =
12929 PTAttr == nullptr
12930 ? diag::warn_bitfield_too_small_for_enum
12931 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12932 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12933 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12934 << BitsNeeded << ED << WidthExpr->getSourceRange();
12935 if (PTAttr)
12936 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12937 << ED;
12938 }
12939 }
12940
12941 return false;
12942 }
12943
12944 llvm::APSInt Value = Result.Val.getInt();
12945
12946 unsigned OriginalWidth = Value.getBitWidth();
12947
12948 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12949 // false positives where the user is demonstrating they intend to use the
12950 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12951 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12952 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12953 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12954 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12955 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12956 S.findMacroSpelling(MaybeMacroLoc, "true"))
12957 return false;
12958 }
12959
12960 if (!Value.isSigned() || Value.isNegative())
12961 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12962 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12963 OriginalWidth = Value.getSignificantBits();
12964
12965 if (OriginalWidth <= FieldWidth)
12966 return false;
12967
12968 // Compute the value which the bitfield will contain.
12969 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12970 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12971
12972 // Check whether the stored value is equal to the original value.
12973 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12974 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12975 return false;
12976
12977 std::string PrettyValue = toString(Value, 10);
12978 std::string PrettyTrunc = toString(TruncatedValue, 10);
12979
12980 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12981 ? diag::warn_impcast_single_bit_bitield_precision_constant
12982 : diag::warn_impcast_bitfield_precision_constant)
12983 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12984 << Init->getSourceRange();
12985
12986 return true;
12987}
12988
12989/// Analyze the given simple or compound assignment for warning-worthy
12990/// operations.
12992 // Just recurse on the LHS.
12994
12995 // We want to recurse on the RHS as normal unless we're assigning to
12996 // a bitfield.
12997 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12998 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12999 E->getOperatorLoc())) {
13000 // Recurse, ignoring any implicit conversions on the RHS.
13002 E->getOperatorLoc());
13003 }
13004 }
13005
13006 // Set context flag for overflow behavior type assignment analysis, use RAII
13007 // pattern to handle nested assignments.
13008 llvm::SaveAndRestore OBTAssignmentContext(
13010
13012
13013 // Diagnose implicitly sequentially-consistent atomic assignment.
13014 if (E->getLHS()->getType()->isAtomicType())
13015 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13016}
13017
13018/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13019static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13020 QualType T, SourceLocation CContext, unsigned diag,
13021 bool PruneControlFlow = false) {
13022 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13023 // address space annotations isn't really useful. The warnings aren't because
13024 // you're converting a `private int` to `unsigned int`, it is because you're
13025 // conerting `int` to `unsigned int`.
13026 if (SourceType.hasAddressSpace())
13027 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
13028 if (T.hasAddressSpace())
13030 if (PruneControlFlow) {
13032 S.PDiag(diag)
13033 << SourceType << T << E->getSourceRange()
13034 << SourceRange(CContext));
13035 return;
13036 }
13037 S.Diag(E->getExprLoc(), diag)
13038 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13039}
13040
13041/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13042static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13043 SourceLocation CContext, unsigned diag,
13044 bool PruneControlFlow = false) {
13045 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
13046}
13047
13048/// Diagnose an implicit cast from a floating point value to an integer value.
13049static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13050 SourceLocation CContext) {
13051 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13052 bool PruneWarnings = S.inTemplateInstantiation();
13053
13054 const Expr *InnerE = E->IgnoreParenImpCasts();
13055 // We also want to warn on, e.g., "int i = -1.234"
13056 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13057 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13058 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13059
13060 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13061
13062 llvm::APFloat Value(0.0);
13063 bool IsConstant =
13065 if (!IsConstant) {
13066 if (S.ObjC().isSignedCharBool(T)) {
13068 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13069 << E->getType());
13070 }
13071
13072 return DiagnoseImpCast(S, E, T, CContext,
13073 diag::warn_impcast_float_integer, PruneWarnings);
13074 }
13075
13076 bool isExact = false;
13077
13078 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13079 T->hasUnsignedIntegerRepresentation());
13080 llvm::APFloat::opStatus Result = Value.convertToInteger(
13081 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13082
13083 // FIXME: Force the precision of the source value down so we don't print
13084 // digits which are usually useless (we don't really care here if we
13085 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13086 // would automatically print the shortest representation, but it's a bit
13087 // tricky to implement.
13088 SmallString<16> PrettySourceValue;
13089 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13090 precision = (precision * 59 + 195) / 196;
13091 Value.toString(PrettySourceValue, precision);
13092
13093 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
13095 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13096 << PrettySourceValue);
13097 }
13098
13099 if (Result == llvm::APFloat::opOK && isExact) {
13100 if (IsLiteral) return;
13101 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13102 PruneWarnings);
13103 }
13104
13105 // Conversion of a floating-point value to a non-bool integer where the
13106 // integral part cannot be represented by the integer type is undefined.
13107 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13108 return DiagnoseImpCast(
13109 S, E, T, CContext,
13110 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13111 : diag::warn_impcast_float_to_integer_out_of_range,
13112 PruneWarnings);
13113
13114 unsigned DiagID = 0;
13115 if (IsLiteral) {
13116 // Warn on floating point literal to integer.
13117 DiagID = diag::warn_impcast_literal_float_to_integer;
13118 } else if (IntegerValue == 0) {
13119 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13120 return DiagnoseImpCast(S, E, T, CContext,
13121 diag::warn_impcast_float_integer, PruneWarnings);
13122 }
13123 // Warn on non-zero to zero conversion.
13124 DiagID = diag::warn_impcast_float_to_integer_zero;
13125 } else {
13126 if (IntegerValue.isUnsigned()) {
13127 if (!IntegerValue.isMaxValue()) {
13128 return DiagnoseImpCast(S, E, T, CContext,
13129 diag::warn_impcast_float_integer, PruneWarnings);
13130 }
13131 } else { // IntegerValue.isSigned()
13132 if (!IntegerValue.isMaxSignedValue() &&
13133 !IntegerValue.isMinSignedValue()) {
13134 return DiagnoseImpCast(S, E, T, CContext,
13135 diag::warn_impcast_float_integer, PruneWarnings);
13136 }
13137 }
13138 // Warn on evaluatable floating point expression to integer conversion.
13139 DiagID = diag::warn_impcast_float_to_integer;
13140 }
13141
13142 SmallString<16> PrettyTargetValue;
13143 if (IsBool)
13144 PrettyTargetValue = Value.isZero() ? "false" : "true";
13145 else
13146 IntegerValue.toString(PrettyTargetValue);
13147
13148 if (PruneWarnings) {
13150 S.PDiag(DiagID)
13151 << E->getType() << T.getUnqualifiedType()
13152 << PrettySourceValue << PrettyTargetValue
13153 << E->getSourceRange() << SourceRange(CContext));
13154 } else {
13155 S.Diag(E->getExprLoc(), DiagID)
13156 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13157 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13158 }
13159}
13160
13161/// Analyze the given compound assignment for the possible losing of
13162/// floating-point precision.
13164 assert(isa<CompoundAssignOperator>(E) &&
13165 "Must be compound assignment operation");
13166 // Recurse on the LHS and RHS in here
13169
13170 if (E->getLHS()->getType()->isAtomicType())
13171 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13172
13173 // Now check the outermost expression
13174 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13175 const auto *RBT = cast<CompoundAssignOperator>(E)
13176 ->getComputationResultType()
13177 ->getAs<BuiltinType>();
13178
13179 // The below checks assume source is floating point.
13180 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13181
13182 // If source is floating point but target is an integer.
13183 if (ResultBT->isInteger())
13184 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13185 E->getExprLoc(), diag::warn_impcast_float_integer);
13186
13187 if (!ResultBT->isFloatingPoint())
13188 return;
13189
13190 // If both source and target are floating points, warn about losing precision.
13192 QualType(ResultBT, 0), QualType(RBT, 0));
13193 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13194 // warn about dropping FP rank.
13195 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13196 diag::warn_impcast_float_result_precision);
13197}
13198
13199static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13200 IntRange Range) {
13201 if (!Range.Width) return "0";
13202
13203 llvm::APSInt ValueInRange = Value;
13204 ValueInRange.setIsSigned(!Range.NonNegative);
13205 ValueInRange = ValueInRange.trunc(Range.Width);
13206 return toString(ValueInRange, 10);
13207}
13208
13209static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13210 bool ToBool) {
13211 if (!isa<ImplicitCastExpr>(Ex))
13212 return false;
13213
13214 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13216 const Type *Source =
13218 if (Target->isDependentType())
13219 return false;
13220
13221 const auto *FloatCandidateBT =
13222 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13223 const Type *BoolCandidateType = ToBool ? Target : Source;
13224
13225 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13226 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13227}
13228
13229static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13230 SourceLocation CC) {
13231 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13232 const Expr *CurrA = TheCall->getArg(I);
13233 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13234 continue;
13235
13236 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13237 S, TheCall->getArg(I - 1), false));
13238 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13239 S, TheCall->getArg(I + 1), false));
13240 if (IsSwapped) {
13241 // Warn on this floating-point to bool conversion.
13243 CurrA->getType(), CC,
13244 diag::warn_impcast_floating_point_to_bool);
13245 }
13246 }
13247}
13248
13250 SourceLocation CC) {
13251 // Don't warn on functions which have return type nullptr_t.
13252 if (isa<CallExpr>(E))
13253 return;
13254
13255 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13256 const Expr *NewE = E->IgnoreParenImpCasts();
13257 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13258 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13259 if (!IsGNUNullExpr && !HasNullPtrType)
13260 return;
13261
13262 // Return if target type is a safe conversion.
13263 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13264 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13265 return;
13266
13267 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13268 E->getExprLoc()))
13269 return;
13270
13272
13273 // Venture through the macro stacks to get to the source of macro arguments.
13274 // The new location is a better location than the complete location that was
13275 // passed in.
13276 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13278
13279 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13280 if (IsGNUNullExpr && Loc.isMacroID()) {
13281 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13282 Loc, S.SourceMgr, S.getLangOpts());
13283 if (MacroName == "NULL")
13285 }
13286
13287 // Only warn if the null and context location are in the same macro expansion.
13288 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13289 return;
13290
13291 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13292 << HasNullPtrType << T << SourceRange(CC)
13295}
13296
13297// Helper function to filter out cases for constant width constant conversion.
13298// Don't warn on unsigned char array initialization or for non-decimal
13299// values.
13301 SourceLocation CC) {
13302 // If initializing from a constant, and the constant starts with '0',
13303 // then it is a binary, octal, or hexadecimal. Allow these constants
13304 // to fill all the bits, even if there is a sign change.
13305 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13306 const char FirstLiteralCharacter =
13307 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13308 if (FirstLiteralCharacter == '0')
13309 return false;
13310 }
13311
13312 // If the CC location points to a '{' and the type is an unsigned char
13313 // type, assume it is an array initialization.
13314 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13315 const char FirstContextCharacter =
13317 if (FirstContextCharacter == '{')
13318 return false;
13319 }
13320
13321 return true;
13322}
13323
13325 const auto *IL = dyn_cast<IntegerLiteral>(E);
13326 if (!IL) {
13327 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13328 if (UO->getOpcode() == UO_Minus)
13329 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13330 }
13331 }
13332
13333 return IL;
13334}
13335
13337 E = E->IgnoreParenImpCasts();
13338 SourceLocation ExprLoc = E->getExprLoc();
13339
13340 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13341 BinaryOperator::Opcode Opc = BO->getOpcode();
13343 // Do not diagnose unsigned shifts.
13344 if (Opc == BO_Shl) {
13345 const auto *LHS = getIntegerLiteral(BO->getLHS());
13346 const auto *RHS = getIntegerLiteral(BO->getRHS());
13347 if (LHS && LHS->getValue() == 0)
13348 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13349 else if (!E->isValueDependent() && LHS && RHS &&
13350 RHS->getValue().isNonNegative() &&
13352 S.Diag(ExprLoc, diag::warn_left_shift_always)
13353 << (Result.Val.getInt() != 0);
13354 else if (E->getType()->isSignedIntegerType())
13355 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13358 ") != 0");
13359 }
13360 }
13361
13362 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13363 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13364 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13365 if (!LHS || !RHS)
13366 return;
13367 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13368 (RHS->getValue() == 0 || RHS->getValue() == 1))
13369 // Do not diagnose common idioms.
13370 return;
13371 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13372 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13373 }
13374}
13375
13377 const Type *Target, Expr *E,
13378 QualType T,
13379 SourceLocation CC) {
13380 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13381 Source != Target);
13382
13383 // Lone surrogates have a distinct representation in UTF-32.
13384 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13385 // so don't warn on such conversion.
13386 if (Source->isChar16Type() && Target->isChar32Type())
13387 return;
13388
13392 llvm::APSInt Value(32);
13393 Value = Result.Val.getInt();
13394 bool IsASCII = Value <= 0x7F;
13395 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13396 bool ConversionPreservesSemantics =
13397 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13398
13399 if (!ConversionPreservesSemantics) {
13400 auto IsSingleCodeUnitCP = [](const QualType &T,
13401 const llvm::APSInt &Value) {
13402 if (T->isChar8Type())
13403 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13404 if (T->isChar16Type())
13405 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13406 assert(T->isChar32Type());
13407 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13408 };
13409
13410 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13411 << E->getType() << T
13412 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13413 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13414 }
13415 } else {
13416 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13418 DiagnoseImpCast(S, E, T, CC,
13419 LosesPrecision ? diag::warn_impcast_unicode_precision
13420 : diag::warn_impcast_unicode_char_type);
13421 }
13422}
13423
13425 From = Context.getCanonicalType(From);
13426 To = Context.getCanonicalType(To);
13427 QualType MaybePointee = From->getPointeeType();
13428 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13429 From = MaybePointee;
13430 MaybePointee = To->getPointeeType();
13431 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13432 To = MaybePointee;
13433
13434 if (const auto *FromFn = From->getAs<FunctionType>()) {
13435 if (const auto *ToFn = To->getAs<FunctionType>()) {
13436 if (FromFn->getCFIUncheckedCalleeAttr() &&
13437 !ToFn->getCFIUncheckedCalleeAttr())
13438 return true;
13439 }
13440 }
13441 return false;
13442}
13443
13445 bool *ICContext, bool IsListInit) {
13446 if (E->isTypeDependent() || E->isValueDependent()) return;
13447
13448 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13449 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13450 if (Source == Target) return;
13451 if (Target->isDependentType()) return;
13452
13453 // If the conversion context location is invalid don't complain. We also
13454 // don't want to emit a warning if the issue occurs from the expansion of
13455 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13456 // delay this check as long as possible. Once we detect we are in that
13457 // scenario, we just return.
13458 if (CC.isInvalid())
13459 return;
13460
13461 if (Source->isAtomicType())
13462 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13463
13464 // Diagnose implicit casts to bool.
13465 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13466 if (isa<StringLiteral>(E))
13467 // Warn on string literal to bool. Checks for string literals in logical
13468 // and expressions, for instance, assert(0 && "error here"), are
13469 // prevented by a check in AnalyzeImplicitConversions().
13470 return DiagnoseImpCast(*this, E, T, CC,
13471 diag::warn_impcast_string_literal_to_bool);
13474 // This covers the literal expressions that evaluate to Objective-C
13475 // objects.
13476 return DiagnoseImpCast(*this, E, T, CC,
13477 diag::warn_impcast_objective_c_literal_to_bool);
13478 }
13479 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13480 // Warn on pointer to bool conversion that is always true.
13482 SourceRange(CC));
13483 }
13484 }
13485
13487
13488 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13489 // is a typedef for signed char (macOS), then that constant value has to be 1
13490 // or 0.
13491 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13494 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13496 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13497 << toString(Result.Val.getInt(), 10));
13498 }
13499 return;
13500 }
13501 }
13502
13503 // Check implicit casts from Objective-C collection literals to specialized
13504 // collection types, e.g., NSArray<NSString *> *.
13505 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13506 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13507 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13508 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13509
13510 // Strip complex types.
13511 if (isa<ComplexType>(Source)) {
13512 if (!isa<ComplexType>(Target)) {
13513 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13514 return;
13515
13516 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13517 return DiagnoseImpCast(*this, E, T, CC,
13518 diag::err_impcast_incompatible_type);
13519 }
13520
13521 return DiagnoseImpCast(*this, E, T, CC,
13523 ? diag::err_impcast_complex_scalar
13524 : diag::warn_impcast_complex_scalar);
13525 }
13526
13527 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13528 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13529 }
13530
13531 // Strip vector types.
13532 if (isa<VectorType>(Source)) {
13533 if (Target->isSveVLSBuiltinType() &&
13534 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13535 QualType(Source, 0)) ||
13536 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13537 QualType(Source, 0))))
13538 return;
13539
13540 if (Target->isRVVVLSBuiltinType() &&
13541 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13542 QualType(Source, 0)) ||
13543 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13544 QualType(Source, 0))))
13545 return;
13546
13547 if (!isa<VectorType>(Target)) {
13548 if (SourceMgr.isInSystemMacro(CC))
13549 return;
13550 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13551 }
13552 if (getLangOpts().HLSL &&
13553 Target->castAs<VectorType>()->getNumElements() <
13554 Source->castAs<VectorType>()->getNumElements()) {
13555 // Diagnose vector truncation but don't return. We may also want to
13556 // diagnose an element conversion.
13557 DiagnoseImpCast(*this, E, T, CC,
13558 diag::warn_hlsl_impcast_vector_truncation);
13559 }
13560
13561 // If the vector cast is cast between two vectors of the same size, it is
13562 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13563 if (!getLangOpts().HLSL &&
13564 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13565 return;
13566
13567 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13568 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13569 }
13570 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13571 Target = VecTy->getElementType().getTypePtr();
13572
13573 // Strip matrix types.
13574 if (isa<ConstantMatrixType>(Source)) {
13575 if (Target->isScalarType())
13576 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13577
13580 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13581 // Diagnose Matrix truncation but don't return. We may also want to
13582 // diagnose an element conversion.
13583 DiagnoseImpCast(*this, E, T, CC,
13584 diag::warn_hlsl_impcast_matrix_truncation);
13585 }
13586
13587 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13588 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13589 }
13590 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13591 Target = MatTy->getElementType().getTypePtr();
13592
13593 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13594 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13595
13596 // Strip SVE vector types
13597 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13598 // Need the original target type for vector type checks
13599 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13600 // Handle conversion from scalable to fixed when msve-vector-bits is
13601 // specified
13602 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13603 QualType(Source, 0)) ||
13604 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13605 QualType(Source, 0)))
13606 return;
13607
13608 // If the vector cast is cast between two vectors of the same size, it is
13609 // a bitcast, not a conversion.
13610 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13611 return;
13612
13613 Source = SourceBT->getSveEltType(Context).getTypePtr();
13614 }
13615
13616 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13617 Target = TargetBT->getSveEltType(Context).getTypePtr();
13618
13619 // Nothing to diagnose if stripping the wrappers left identical element types
13620 // (e.g. a scalar splatted to a vector of its own type).
13621 if (Source == Target)
13622 return;
13623
13624 // If the source is floating point...
13625 if (SourceBT && SourceBT->isFloatingPoint()) {
13626 // ...and the target is floating point...
13627 if (TargetBT && TargetBT->isFloatingPoint()) {
13628 // ...then warn if we're dropping FP rank.
13629
13631 QualType(SourceBT, 0), QualType(TargetBT, 0));
13632 if (Order > 0) {
13633 // Don't warn about float constants that are precisely
13634 // representable in the target type.
13635 Expr::EvalResult result;
13636 if (E->EvaluateAsRValue(result, Context)) {
13637 // Value might be a float, a float vector, or a float complex.
13639 result.Val,
13640 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13641 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13642 return;
13643 }
13644
13645 if (SourceMgr.isInSystemMacro(CC))
13646 return;
13647
13648 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13649 }
13650 // ... or possibly if we're increasing rank, too
13651 else if (Order < 0) {
13652 if (SourceMgr.isInSystemMacro(CC))
13653 return;
13654
13655 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13656 }
13657 return;
13658 }
13659
13660 // If the target is integral, always warn.
13661 if (TargetBT && TargetBT->isInteger()) {
13662 if (SourceMgr.isInSystemMacro(CC))
13663 return;
13664
13665 DiagnoseFloatingImpCast(*this, E, T, CC);
13666 }
13667
13668 // Detect the case where a call result is converted from floating-point to
13669 // to bool, and the final argument to the call is converted from bool, to
13670 // discover this typo:
13671 //
13672 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13673 //
13674 // FIXME: This is an incredibly special case; is there some more general
13675 // way to detect this class of misplaced-parentheses bug?
13676 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13677 // Check last argument of function call to see if it is an
13678 // implicit cast from a type matching the type the result
13679 // is being cast to.
13680 CallExpr *CEx = cast<CallExpr>(E);
13681 if (unsigned NumArgs = CEx->getNumArgs()) {
13682 Expr *LastA = CEx->getArg(NumArgs - 1);
13683 Expr *InnerE = LastA->IgnoreParenImpCasts();
13684 if (isa<ImplicitCastExpr>(LastA) &&
13685 InnerE->getType()->isBooleanType()) {
13686 // Warn on this floating-point to bool conversion
13687 DiagnoseImpCast(*this, E, T, CC,
13688 diag::warn_impcast_floating_point_to_bool);
13689 }
13690 }
13691 }
13692 return;
13693 }
13694
13695 // Valid casts involving fixed point types should be accounted for here.
13696 if (Source->isFixedPointType()) {
13697 if (Target->isUnsaturatedFixedPointType()) {
13701 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13702 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13703 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13704 if (Value > MaxVal || Value < MinVal) {
13706 PDiag(diag::warn_impcast_fixed_point_range)
13707 << Value.toString() << T
13708 << E->getSourceRange()
13709 << clang::SourceRange(CC));
13710 return;
13711 }
13712 }
13713 } else if (Target->isIntegerType()) {
13717 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13718
13719 bool Overflowed;
13720 llvm::APSInt IntResult = FXResult.convertToInt(
13721 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13722 &Overflowed);
13723
13724 if (Overflowed) {
13726 PDiag(diag::warn_impcast_fixed_point_range)
13727 << FXResult.toString() << T
13728 << E->getSourceRange()
13729 << clang::SourceRange(CC));
13730 return;
13731 }
13732 }
13733 }
13734 } else if (Target->isUnsaturatedFixedPointType()) {
13735 if (Source->isIntegerType()) {
13739 llvm::APSInt Value = Result.Val.getInt();
13740
13741 bool Overflowed;
13742 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13743 Value, Context.getFixedPointSemantics(T), &Overflowed);
13744
13745 if (Overflowed) {
13747 PDiag(diag::warn_impcast_fixed_point_range)
13748 << toString(Value, /*Radix=*/10) << T
13749 << E->getSourceRange()
13750 << clang::SourceRange(CC));
13751 return;
13752 }
13753 }
13754 }
13755 }
13756
13757 // If we are casting an integer type to a floating point type without
13758 // initialization-list syntax, we might lose accuracy if the floating
13759 // point type has a narrower significand than the integer type.
13760 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13761 TargetBT->isFloatingType() && !IsListInit) {
13762 // Determine the number of precision bits in the source integer type.
13763 std::optional<IntRange> SourceRange =
13765 /*Approximate=*/true);
13766 if (!SourceRange)
13767 return;
13768 unsigned int SourcePrecision = SourceRange->Width;
13769
13770 // Determine the number of precision bits in the
13771 // target floating point type.
13772 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13773 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13774
13775 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13776 SourcePrecision > TargetPrecision) {
13777
13778 if (std::optional<llvm::APSInt> SourceInt =
13780 // If the source integer is a constant, convert it to the target
13781 // floating point type. Issue a warning if the value changes
13782 // during the whole conversion.
13783 llvm::APFloat TargetFloatValue(
13784 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13785 llvm::APFloat::opStatus ConversionStatus =
13786 TargetFloatValue.convertFromAPInt(
13787 *SourceInt, SourceBT->isSignedInteger(),
13788 llvm::APFloat::rmNearestTiesToEven);
13789
13790 if (ConversionStatus != llvm::APFloat::opOK) {
13791 SmallString<32> PrettySourceValue;
13792 SourceInt->toString(PrettySourceValue, 10);
13793 SmallString<32> PrettyTargetValue;
13794 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13795
13797 E->getExprLoc(), E,
13798 PDiag(diag::warn_impcast_integer_float_precision_constant)
13799 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13800 << E->getSourceRange() << clang::SourceRange(CC));
13801 }
13802 } else {
13803 // Otherwise, the implicit conversion may lose precision.
13804 DiagnoseImpCast(*this, E, T, CC,
13805 diag::warn_impcast_integer_float_precision);
13806 }
13807 }
13808 }
13809
13810 DiagnoseNullConversion(*this, E, T, CC);
13811
13813
13814 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13815 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13816 return;
13817 }
13818
13819 if (Target->isBooleanType())
13820 DiagnoseIntInBoolContext(*this, E);
13821
13823 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13824 << QualType(Source, 0) << QualType(Target, 0);
13825 }
13826
13827 if (!Source->isIntegerType() || !Target->isIntegerType())
13828 return;
13829
13830 // TODO: remove this early return once the false positives for constant->bool
13831 // in templates, macros, etc, are reduced or removed.
13832 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13833 return;
13834
13835 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13836 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13838 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13839 << E->getType());
13840 }
13841 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13842 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13843 if (!LikelySourceRange)
13844 return;
13845
13846 IntRange SourceTypeRange =
13847 IntRange::forTargetOfCanonicalType(Context, Source);
13848 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13849
13850 if (LikelySourceRange->Width > TargetRange.Width) {
13851 // Check if target is a wrapping OBT - if so, don't warn about constant
13852 // conversion as this type may be used intentionally with implicit
13853 // truncation, especially during assignments.
13854 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13855 if (TargetOBT->isWrapKind()) {
13856 return;
13857 }
13858 }
13859
13860 // Check if source expression has an explicit __ob_wrap cast because if so,
13861 // wrapping was explicitly requested and we shouldn't warn
13862 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13863 if (SourceOBT->isWrapKind()) {
13864 return;
13865 }
13866 }
13867
13868 // If the source is a constant, use a default-on diagnostic.
13869 // TODO: this should happen for bitfield stores, too.
13873 llvm::APSInt Value(32);
13874 Value = Result.Val.getInt();
13875
13876 if (SourceMgr.isInSystemMacro(CC))
13877 return;
13878
13879 std::string PrettySourceValue = toString(Value, 10);
13880 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13881
13883 PDiag(diag::warn_impcast_integer_precision_constant)
13884 << PrettySourceValue << PrettyTargetValue
13885 << E->getType() << T << E->getSourceRange()
13886 << SourceRange(CC));
13887 return;
13888 }
13889
13890 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13891 if (SourceMgr.isInSystemMacro(CC))
13892 return;
13893
13894 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13895 if (UO->getOpcode() == UO_Minus)
13896 return DiagnoseImpCast(
13897 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13898 }
13899
13900 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13901 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13902 /* pruneControlFlow */ true);
13903 return DiagnoseImpCast(*this, E, T, CC,
13904 diag::warn_impcast_integer_precision);
13905 }
13906
13907 if (TargetRange.Width > SourceTypeRange.Width) {
13908 if (auto *UO = dyn_cast<UnaryOperator>(E))
13909 if (UO->getOpcode() == UO_Minus)
13910 if (Source->isUnsignedIntegerType()) {
13911 if (Target->isUnsignedIntegerType())
13912 return DiagnoseImpCast(*this, E, T, CC,
13913 diag::warn_impcast_high_order_zero_bits);
13914 if (Target->isSignedIntegerType())
13915 return DiagnoseImpCast(*this, E, T, CC,
13916 diag::warn_impcast_nonnegative_result);
13917 }
13918 }
13919
13920 if (TargetRange.Width == LikelySourceRange->Width &&
13921 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13922 Source->isSignedIntegerType()) {
13923 // Warn when doing a signed to signed conversion, warn if the positive
13924 // source value is exactly the width of the target type, which will
13925 // cause a negative value to be stored.
13926
13929 !SourceMgr.isInSystemMacro(CC)) {
13930 llvm::APSInt Value = Result.Val.getInt();
13931 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13932 std::string PrettySourceValue = toString(Value, 10);
13933 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13934
13935 Diag(E->getExprLoc(),
13936 PDiag(diag::warn_impcast_integer_precision_constant)
13937 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13938 << E->getSourceRange() << SourceRange(CC));
13939 return;
13940 }
13941 }
13942
13943 // Fall through for non-constants to give a sign conversion warning.
13944 }
13945
13946 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13947 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13948 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13949 LikelySourceRange->Width == TargetRange.Width))) {
13950 if (SourceMgr.isInSystemMacro(CC))
13951 return;
13952
13953 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13954 TargetBT->isInteger() &&
13955 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13956 return;
13957 }
13958
13959 unsigned DiagID = diag::warn_impcast_integer_sign;
13960
13961 // Traditionally, gcc has warned about this under -Wsign-compare.
13962 // We also want to warn about it in -Wconversion.
13963 // So if -Wconversion is off, use a completely identical diagnostic
13964 // in the sign-compare group.
13965 // The conditional-checking code will
13966 if (ICContext) {
13967 DiagID = diag::warn_impcast_integer_sign_conditional;
13968 *ICContext = true;
13969 }
13970
13971 DiagnoseImpCast(*this, E, T, CC, DiagID);
13972 }
13973
13974 // If we're implicitly converting from an integer into an enumeration, that
13975 // is valid in C but invalid in C++.
13976 QualType SourceType = E->getEnumCoercedType(Context);
13977 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13978 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13979 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13980
13981 // Diagnose conversions between different enumeration types.
13982 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13983 // type, to give us better diagnostics.
13984 Source = Context.getCanonicalType(SourceType).getTypePtr();
13985
13986 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13987 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13988 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13989 TargetEnum->getDecl()->hasNameForLinkage() &&
13990 SourceEnum != TargetEnum) {
13991 if (SourceMgr.isInSystemMacro(CC))
13992 return;
13993
13994 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13995 diag::warn_impcast_different_enum_types);
13996 }
13997}
13998
14001
14003 SourceLocation CC, bool &ICContext) {
14004 E = E->IgnoreParenImpCasts();
14005 // Diagnose incomplete type for second or third operand in C.
14006 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
14007 S.RequireCompleteExprType(E, diag::err_incomplete_type);
14008
14009 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
14010 return CheckConditionalOperator(S, CO, CC, T);
14011
14013 if (E->getType() != T)
14014 return S.CheckImplicitConversion(E, T, CC, &ICContext);
14015}
14016
14020
14021 Expr *TrueExpr = E->getTrueExpr();
14022 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
14023 TrueExpr = BCO->getCommon();
14024
14025 bool Suspicious = false;
14026 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
14027 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
14028
14029 if (T->isBooleanType())
14031
14032 // If -Wconversion would have warned about either of the candidates
14033 // for a signedness conversion to the context type...
14034 if (!Suspicious) return;
14035
14036 // ...but it's currently ignored...
14037 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
14038 return;
14039
14040 // ...then check whether it would have warned about either of the
14041 // candidates for a signedness conversion to the condition type.
14042 if (E->getType() == T) return;
14043
14044 Suspicious = false;
14045 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
14046 &Suspicious);
14047 if (!Suspicious)
14049 E->getType(), CC, &Suspicious);
14050}
14051
14052/// Check conversion of given expression to boolean.
14053/// Input argument E is a logical expression.
14055 // Run the bool-like conversion checks only for C since there bools are
14056 // still not used as the return type from "boolean" operators or as the input
14057 // type for conditional operators.
14058 if (S.getLangOpts().CPlusPlus)
14059 return;
14061 return;
14063}
14064
14065namespace {
14066struct AnalyzeImplicitConversionsWorkItem {
14067 Expr *E;
14068 SourceLocation CC;
14069 bool IsListInit;
14070};
14071}
14072
14074 Sema &S, Expr *E, QualType T, SourceLocation CC,
14075 bool ExtraCheckForImplicitConversion,
14077 E = E->IgnoreParenImpCasts();
14078 WorkList.push_back({E, CC, false});
14079
14080 if (ExtraCheckForImplicitConversion && E->getType() != T)
14081 S.CheckImplicitConversion(E, T, CC);
14082}
14083
14084/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14085/// that should be visited are added to WorkList.
14087 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14089 Expr *OrigE = Item.E;
14090 SourceLocation CC = Item.CC;
14091
14092 QualType T = OrigE->getType();
14093 Expr *E = OrigE->IgnoreParenImpCasts();
14094
14095 // Propagate whether we are in a C++ list initialization expression.
14096 // If so, we do not issue warnings for implicit int-float conversion
14097 // precision loss, because C++11 narrowing already handles it.
14098 //
14099 // HLSL's initialization lists are special, so they shouldn't observe the C++
14100 // behavior here.
14101 bool IsListInit =
14102 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
14103 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14104
14105 if (E->isTypeDependent() || E->isValueDependent())
14106 return;
14107
14108 Expr *SourceExpr = E;
14109 // Examine, but don't traverse into the source expression of an
14110 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14111 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14112 // evaluate it in the context of checking the specific conversion to T though.
14113 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14114 if (auto *Src = OVE->getSourceExpr())
14115 SourceExpr = Src;
14116
14117 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14118 if (UO->getOpcode() == UO_Not &&
14119 UO->getSubExpr()->isKnownToHaveBooleanValue())
14120 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14121 << OrigE->getSourceRange() << T->isBooleanType()
14122 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14123
14124 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14125 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14126 BO->getLHS()->isKnownToHaveBooleanValue() &&
14127 BO->getRHS()->isKnownToHaveBooleanValue() &&
14128 BO->getLHS()->HasSideEffects(S.Context) &&
14129 BO->getRHS()->HasSideEffects(S.Context)) {
14131 const LangOptions &LO = S.getLangOpts();
14132 SourceLocation BLoc = BO->getOperatorLoc();
14133 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
14134 StringRef SR = clang::Lexer::getSourceText(
14135 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
14136 // To reduce false positives, only issue the diagnostic if the operator
14137 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14138 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14139 // in C, along with other macro spellings the user might invent.
14140 if (SR.str() == "&" || SR.str() == "|") {
14141
14142 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14143 << (BO->getOpcode() == BO_And ? "&" : "|")
14144 << OrigE->getSourceRange()
14146 BO->getOperatorLoc(),
14147 (BO->getOpcode() == BO_And ? "&&" : "||"));
14148 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14149 }
14150 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14151 /// Analyze the given comma operator. The basic idea behind the analysis
14152 /// is to analyze the left and right operands slightly differently. The
14153 /// left operand needs to check whether the operand itself has an implicit
14154 /// conversion, but not whether the left operand induces an implicit
14155 /// conversion for the entire comma expression itself. This is similar to
14156 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14157 /// were directly used for the implicit conversion check.
14158 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
14159 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14160 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
14161 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14162 return;
14163 }
14164 }
14165
14166 // For conditional operators, we analyze the arguments as if they
14167 // were being fed directly into the output.
14168 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14169 CheckConditionalOperator(S, CO, CC, T);
14170 return;
14171 }
14172
14173 // Check implicit argument conversions for function calls.
14174 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14176
14177 // Go ahead and check any implicit conversions we might have skipped.
14178 // The non-canonical typecheck is just an optimization;
14179 // CheckImplicitConversion will filter out dead implicit conversions.
14180 if (SourceExpr->getType() != T)
14181 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14182
14183 // Now continue drilling into this expression.
14184
14185 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14186 // The bound subexpressions in a PseudoObjectExpr are not reachable
14187 // as transitive children.
14188 // FIXME: Use a more uniform representation for this.
14189 for (auto *SE : POE->semantics())
14190 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14191 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14192 }
14193
14194 // Skip past explicit casts.
14195 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14196 E = CE->getSubExpr();
14197 // In the special case of a C++ function-style cast with braces,
14198 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14199 // initializer. This InitListExpr basically belongs to the cast itself, so
14200 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14202 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14203 if (InitListE->getNumInits() == 1) {
14204 E = InitListE->getInit(0);
14205 }
14206 }
14207 }
14208 E = E->IgnoreParenImpCasts();
14209 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14210 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14211 WorkList.push_back({E, CC, IsListInit});
14212 return;
14213 }
14214
14215 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14216 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14217 // The base expression is only used to initialize the parameter for
14218 // arguments to `inout` parameters, so we only traverse down the base
14219 // expression for `inout` cases.
14220 if (OutArgE->isInOut())
14221 WorkList.push_back(
14222 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14223 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14224 return;
14225 }
14226
14227 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14228 // Do a somewhat different check with comparison operators.
14229 if (BO->isComparisonOp())
14230 return AnalyzeComparison(S, BO);
14231
14232 // And with simple assignments.
14233 if (BO->getOpcode() == BO_Assign)
14234 return AnalyzeAssignment(S, BO);
14235 // And with compound assignments.
14236 if (BO->isAssignmentOp())
14237 return AnalyzeCompoundAssignment(S, BO);
14238 }
14239
14240 // These break the otherwise-useful invariant below. Fortunately,
14241 // we don't really need to recurse into them, because any internal
14242 // expressions should have been analyzed already when they were
14243 // built into statements.
14244 if (isa<StmtExpr>(E)) return;
14245
14246 // Don't descend into unevaluated contexts.
14247 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14248
14249 // Now just recurse over the expression's children.
14250 CC = E->getExprLoc();
14251 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14252 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14253 for (Stmt *SubStmt : E->children()) {
14254 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14255 if (!ChildExpr)
14256 continue;
14257
14258 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14259 if (ChildExpr == CSE->getOperand())
14260 // Do not recurse over a CoroutineSuspendExpr's operand.
14261 // The operand is also a subexpression of getCommonExpr(), and
14262 // recursing into it directly would produce duplicate diagnostics.
14263 continue;
14264
14265 if (IsLogicalAndOperator &&
14267 // Ignore checking string literals that are in logical and operators.
14268 // This is a common pattern for asserts.
14269 continue;
14270 WorkList.push_back({ChildExpr, CC, IsListInit});
14271 }
14272
14273 if (BO && BO->isLogicalOp()) {
14274 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14275 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14276 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14277
14278 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14279 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14280 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14281 }
14282
14283 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14284 if (U->getOpcode() == UO_LNot) {
14285 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14286 } else if (U->getOpcode() != UO_AddrOf) {
14287 if (U->getSubExpr()->getType()->isAtomicType())
14288 S.Diag(U->getSubExpr()->getBeginLoc(),
14289 diag::warn_atomic_implicit_seq_cst);
14290 }
14291 }
14292}
14293
14294/// AnalyzeImplicitConversions - Find and report any interesting
14295/// implicit conversions in the given expression. There are a couple
14296/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14298 bool IsListInit/*= false*/) {
14300 WorkList.push_back({OrigE, CC, IsListInit});
14301 while (!WorkList.empty())
14302 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14303}
14304
14305// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14306// Returns true when emitting a warning about taking the address of a reference.
14307static bool CheckForReference(Sema &SemaRef, const Expr *E,
14308 const PartialDiagnostic &PD) {
14309 E = E->IgnoreParenImpCasts();
14310
14311 const FunctionDecl *FD = nullptr;
14312
14313 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14314 if (!DRE->getDecl()->getType()->isReferenceType())
14315 return false;
14316 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14317 if (!M->getMemberDecl()->getType()->isReferenceType())
14318 return false;
14319 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14320 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14321 return false;
14322 FD = Call->getDirectCallee();
14323 } else {
14324 return false;
14325 }
14326
14327 SemaRef.Diag(E->getExprLoc(), PD);
14328
14329 // If possible, point to location of function.
14330 if (FD) {
14331 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14332 }
14333
14334 return true;
14335}
14336
14337// Returns true if the SourceLocation is expanded from any macro body.
14338// Returns false if the SourceLocation is invalid, is from not in a macro
14339// expansion, or is from expanded from a top-level macro argument.
14340static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14341 if (Loc.isInvalid())
14342 return false;
14343
14344 while (Loc.isMacroID()) {
14345 if (SM.isMacroBodyExpansion(Loc))
14346 return true;
14347 Loc = SM.getImmediateMacroCallerLoc(Loc);
14348 }
14349
14350 return false;
14351}
14352
14355 bool IsEqual, SourceRange Range) {
14356 if (!E)
14357 return;
14358
14359 // Don't warn inside macros.
14360 if (E->getExprLoc().isMacroID()) {
14361 const SourceManager &SM = getSourceManager();
14362 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14363 IsInAnyMacroBody(SM, Range.getBegin()))
14364 return;
14365 }
14366 E = E->IgnoreImpCasts();
14367
14368 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14369
14370 if (isa<CXXThisExpr>(E)) {
14371 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14372 : diag::warn_this_bool_conversion;
14373 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14374 return;
14375 }
14376
14377 bool IsAddressOf = false;
14378
14379 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14380 if (UO->getOpcode() != UO_AddrOf)
14381 return;
14382 IsAddressOf = true;
14383 E = UO->getSubExpr();
14384 }
14385
14386 if (IsAddressOf) {
14387 unsigned DiagID = IsCompare
14388 ? diag::warn_address_of_reference_null_compare
14389 : diag::warn_address_of_reference_bool_conversion;
14390 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14391 << IsEqual;
14392 if (CheckForReference(*this, E, PD)) {
14393 return;
14394 }
14395 }
14396
14397 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14398 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14399 std::string Str;
14400 llvm::raw_string_ostream S(Str);
14401 E->printPretty(S, nullptr, getPrintingPolicy());
14402 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14403 : diag::warn_cast_nonnull_to_bool;
14404 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14405 << E->getSourceRange() << Range << IsEqual;
14406 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14407 };
14408
14409 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14410 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14411 if (auto *Callee = Call->getDirectCallee()) {
14412 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14413 ComplainAboutNonnullParamOrCall(A);
14414 return;
14415 }
14416 }
14417 }
14418
14419 // Complain if we are converting a lambda expression to a boolean value
14420 // outside of instantiation.
14421 if (!inTemplateInstantiation()) {
14422 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14423 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14424 MRecordDecl && MRecordDecl->isLambda()) {
14425 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14426 << /*LambdaPointerConversionOperatorType=*/3
14427 << MRecordDecl->getSourceRange() << Range << IsEqual;
14428 return;
14429 }
14430 }
14431 }
14432
14433 // Expect to find a single Decl. Skip anything more complicated.
14434 ValueDecl *D = nullptr;
14435 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14436 D = R->getDecl();
14437 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14438 D = M->getMemberDecl();
14439 }
14440
14441 // Weak Decls can be null.
14442 if (!D || D->isWeak())
14443 return;
14444
14445 // Check for parameter decl with nonnull attribute
14446 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14447 if (getCurFunction() &&
14448 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14449 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14450 ComplainAboutNonnullParamOrCall(A);
14451 return;
14452 }
14453
14454 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14455 // Skip function template not specialized yet.
14457 return;
14458 auto ParamIter = llvm::find(FD->parameters(), PV);
14459 assert(ParamIter != FD->param_end());
14460 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14461
14462 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14463 if (!NonNull->args_size()) {
14464 ComplainAboutNonnullParamOrCall(NonNull);
14465 return;
14466 }
14467
14468 for (const ParamIdx &ArgNo : NonNull->args()) {
14469 if (ArgNo.getASTIndex() == ParamNo) {
14470 ComplainAboutNonnullParamOrCall(NonNull);
14471 return;
14472 }
14473 }
14474 }
14475 }
14476 }
14477 }
14478
14479 QualType T = D->getType();
14480 // A reference to a function is never null either; look through it.
14481 const bool IsFunctionReference =
14482 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14483 if (IsFunctionReference)
14484 T = T->getPointeeType();
14485 const bool IsArray = T->isArrayType();
14486 const bool IsFunction = T->isFunctionType();
14487
14488 // Address of function is used to silence the function warning.
14489 if (IsAddressOf && IsFunction) {
14490 return;
14491 }
14492
14493 // Found nothing.
14494 if (!IsAddressOf && !IsFunction && !IsArray)
14495 return;
14496
14497 // Pretty print the expression for the diagnostic.
14498 std::string Str;
14499 llvm::raw_string_ostream S(Str);
14500 E->printPretty(S, nullptr, getPrintingPolicy());
14501
14502 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14503 : diag::warn_impcast_pointer_to_bool;
14504 enum {
14505 AddressOf,
14506 FunctionPointer,
14507 ArrayPointer
14508 } DiagType;
14509 if (IsAddressOf)
14510 DiagType = AddressOf;
14511 else if (IsFunction)
14512 DiagType = FunctionPointer;
14513 else if (IsArray)
14514 DiagType = ArrayPointer;
14515 else
14516 llvm_unreachable("Could not determine diagnostic.");
14517 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14518 << Range << IsEqual;
14519
14520 // The fix-it notes below only apply to a bare function name, not a reference.
14521 if (!IsFunction || IsFunctionReference)
14522 return;
14523
14524 // Suggest '&' to silence the function warning.
14525 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14527
14528 // Check to see if '()' fixit should be emitted.
14529 QualType ReturnType;
14530 UnresolvedSet<4> NonTemplateOverloads;
14531 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14532 if (ReturnType.isNull())
14533 return;
14534
14535 if (IsCompare) {
14536 // There are two cases here. If there is null constant, the only suggest
14537 // for a pointer return type. If the null is 0, then suggest if the return
14538 // type is a pointer or an integer type.
14539 if (!ReturnType->isPointerType()) {
14540 if (NullKind == Expr::NPCK_ZeroExpression ||
14541 NullKind == Expr::NPCK_ZeroLiteral) {
14542 if (!ReturnType->isIntegerType())
14543 return;
14544 } else {
14545 return;
14546 }
14547 }
14548 } else { // !IsCompare
14549 // For function to bool, only suggest if the function pointer has bool
14550 // return type.
14551 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14552 return;
14553 }
14554 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14556}
14557
14559 SourceLocation CC) {
14560 QualType Source = E->getType();
14561 QualType Target = T;
14562
14563 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14564 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14565 // Overflow behavior type is being stripped - issue warning
14566 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14567 Target->isUnsignedIntegerType()) {
14568 // For unsigned wrap to unsigned conversions, use pedantic version
14569 unsigned DiagId =
14571 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14572 : diag::warn_impcast_overflow_behavior_pedantic;
14573 DiagnoseImpCast(*this, E, T, CC, DiagId);
14574 } else {
14575 unsigned DiagId = InOverflowBehaviorAssignmentContext
14576 ? diag::warn_impcast_overflow_behavior_assignment
14577 : diag::warn_impcast_overflow_behavior;
14578 DiagnoseImpCast(*this, E, T, CC, DiagId);
14579 }
14580 }
14581 }
14582
14583 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14584 if (TargetOBT->isWrapKind()) {
14585 return true;
14586 }
14587 }
14588
14589 return false;
14590}
14591
14592void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14593 // Don't diagnose in unevaluated contexts.
14595 return;
14596
14597 // Don't diagnose for value- or type-dependent expressions.
14598 if (E->isTypeDependent() || E->isValueDependent())
14599 return;
14600
14601 // Check for array bounds violations in cases where the check isn't triggered
14602 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14603 // ArraySubscriptExpr is on the RHS of a variable initialization.
14604 CheckArrayAccess(E);
14605
14606 // This is not the right CC for (e.g.) a variable initialization.
14607 AnalyzeImplicitConversions(*this, E, CC);
14608}
14609
14610void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14611 ::CheckBoolLikeConversion(*this, E, CC);
14612}
14613
14614void Sema::CheckForIntOverflow (const Expr *E) {
14615 // Use a work list to deal with nested struct initializers.
14616 SmallVector<const Expr *, 2> Exprs(1, E);
14617
14618 do {
14619 const Expr *OriginalE = Exprs.pop_back_val();
14620 const Expr *E = OriginalE->IgnoreParenCasts();
14621
14622 if (isa<BinaryOperator>(E) ||
14623 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14625 continue;
14626 }
14627
14628 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14629 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14630 else if (isa<ObjCBoxedExpr>(OriginalE))
14632 else if (const auto *Call = dyn_cast<CallExpr>(E))
14633 Exprs.append(Call->arg_begin(), Call->arg_end());
14634 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14635 Exprs.append(Message->arg_begin(), Message->arg_end());
14636 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14637 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14638 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14639 Exprs.push_back(Temporary->getSubExpr());
14640 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14641 Exprs.push_back(Array->getIdx());
14642 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14643 Exprs.push_back(Compound->getInitializer());
14644 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14645 New && New->isArray()) {
14646 if (auto ArraySize = New->getArraySize())
14647 Exprs.push_back(*ArraySize);
14648 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14649 Exprs.push_back(MTE->getSubExpr());
14650 } while (!Exprs.empty());
14651}
14652
14653namespace {
14654
14655/// Visitor for expressions which looks for unsequenced operations on the
14656/// same object.
14657class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14658 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14659
14660 /// A tree of sequenced regions within an expression. Two regions are
14661 /// unsequenced if one is an ancestor or a descendent of the other. When we
14662 /// finish processing an expression with sequencing, such as a comma
14663 /// expression, we fold its tree nodes into its parent, since they are
14664 /// unsequenced with respect to nodes we will visit later.
14665 class SequenceTree {
14666 struct Value {
14667 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14668 unsigned Parent : 31;
14669 LLVM_PREFERRED_TYPE(bool)
14670 unsigned Merged : 1;
14671 };
14672 SmallVector<Value, 8> Values;
14673
14674 public:
14675 /// A region within an expression which may be sequenced with respect
14676 /// to some other region.
14677 class Seq {
14678 friend class SequenceTree;
14679
14680 unsigned Index;
14681
14682 explicit Seq(unsigned N) : Index(N) {}
14683
14684 public:
14685 Seq() : Index(0) {}
14686 };
14687
14688 SequenceTree() { Values.push_back(Value(0)); }
14689 Seq root() const { return Seq(0); }
14690
14691 /// Create a new sequence of operations, which is an unsequenced
14692 /// subset of \p Parent. This sequence of operations is sequenced with
14693 /// respect to other children of \p Parent.
14694 Seq allocate(Seq Parent) {
14695 Values.push_back(Value(Parent.Index));
14696 return Seq(Values.size() - 1);
14697 }
14698
14699 /// Merge a sequence of operations into its parent.
14700 void merge(Seq S) {
14701 Values[S.Index].Merged = true;
14702 }
14703
14704 /// Determine whether two operations are unsequenced. This operation
14705 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14706 /// should have been merged into its parent as appropriate.
14707 bool isUnsequenced(Seq Cur, Seq Old) {
14708 unsigned C = representative(Cur.Index);
14709 unsigned Target = representative(Old.Index);
14710 while (C >= Target) {
14711 if (C == Target)
14712 return true;
14713 C = Values[C].Parent;
14714 }
14715 return false;
14716 }
14717
14718 private:
14719 /// Pick a representative for a sequence.
14720 unsigned representative(unsigned K) {
14721 if (Values[K].Merged)
14722 // Perform path compression as we go.
14723 return Values[K].Parent = representative(Values[K].Parent);
14724 return K;
14725 }
14726 };
14727
14728 /// An object for which we can track unsequenced uses.
14729 using Object = const NamedDecl *;
14730
14731 /// Different flavors of object usage which we track. We only track the
14732 /// least-sequenced usage of each kind.
14733 enum UsageKind {
14734 /// A read of an object. Multiple unsequenced reads are OK.
14735 UK_Use,
14736
14737 /// A modification of an object which is sequenced before the value
14738 /// computation of the expression, such as ++n in C++.
14739 UK_ModAsValue,
14740
14741 /// A modification of an object which is not sequenced before the value
14742 /// computation of the expression, such as n++.
14743 UK_ModAsSideEffect,
14744
14745 UK_Count = UK_ModAsSideEffect + 1
14746 };
14747
14748 /// Bundle together a sequencing region and the expression corresponding
14749 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14750 struct Usage {
14751 const Expr *UsageExpr = nullptr;
14752 SequenceTree::Seq Seq;
14753
14754 Usage() = default;
14755 };
14756
14757 struct UsageInfo {
14758 Usage Uses[UK_Count];
14759
14760 /// Have we issued a diagnostic for this object already?
14761 bool Diagnosed = false;
14762
14763 UsageInfo();
14764 };
14765 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14766
14767 Sema &SemaRef;
14768
14769 /// Sequenced regions within the expression.
14770 SequenceTree Tree;
14771
14772 /// Declaration modifications and references which we have seen.
14773 UsageInfoMap UsageMap;
14774
14775 /// The region we are currently within.
14776 SequenceTree::Seq Region;
14777
14778 /// Filled in with declarations which were modified as a side-effect
14779 /// (that is, post-increment operations).
14780 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14781
14782 /// Expressions to check later. We defer checking these to reduce
14783 /// stack usage.
14784 SmallVectorImpl<const Expr *> &WorkList;
14785
14786 /// RAII object wrapping the visitation of a sequenced subexpression of an
14787 /// expression. At the end of this process, the side-effects of the evaluation
14788 /// become sequenced with respect to the value computation of the result, so
14789 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14790 /// UK_ModAsValue.
14791 struct SequencedSubexpression {
14792 SequencedSubexpression(SequenceChecker &Self)
14793 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14794 Self.ModAsSideEffect = &ModAsSideEffect;
14795 }
14796
14797 ~SequencedSubexpression() {
14798 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14799 // Add a new usage with usage kind UK_ModAsValue, and then restore
14800 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14801 // the previous one was empty).
14802 UsageInfo &UI = Self.UsageMap[M.first];
14803 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14804 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14805 SideEffectUsage = M.second;
14806 }
14807 Self.ModAsSideEffect = OldModAsSideEffect;
14808 }
14809
14810 SequenceChecker &Self;
14811 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14812 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14813 };
14814
14815 /// RAII object wrapping the visitation of a subexpression which we might
14816 /// choose to evaluate as a constant. If any subexpression is evaluated and
14817 /// found to be non-constant, this allows us to suppress the evaluation of
14818 /// the outer expression.
14819 class EvaluationTracker {
14820 public:
14821 EvaluationTracker(SequenceChecker &Self)
14822 : Self(Self), Prev(Self.EvalTracker) {
14823 Self.EvalTracker = this;
14824 }
14825
14826 ~EvaluationTracker() {
14827 Self.EvalTracker = Prev;
14828 if (Prev)
14829 Prev->EvalOK &= EvalOK;
14830 }
14831
14832 bool evaluate(const Expr *E, bool &Result) {
14833 if (!EvalOK || E->isValueDependent())
14834 return false;
14835 EvalOK = E->EvaluateAsBooleanCondition(
14836 Result, Self.SemaRef.Context,
14837 Self.SemaRef.isConstantEvaluatedContext());
14838 return EvalOK;
14839 }
14840
14841 private:
14842 SequenceChecker &Self;
14843 EvaluationTracker *Prev;
14844 bool EvalOK = true;
14845 } *EvalTracker = nullptr;
14846
14847 /// Find the object which is produced by the specified expression,
14848 /// if any.
14849 Object getObject(const Expr *E, bool Mod) const {
14850 E = E->IgnoreParenCasts();
14851 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14852 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14853 return getObject(UO->getSubExpr(), Mod);
14854 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14855 if (BO->getOpcode() == BO_Comma)
14856 return getObject(BO->getRHS(), Mod);
14857 if (Mod && BO->isAssignmentOp())
14858 return getObject(BO->getLHS(), Mod);
14859 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14860 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14861 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14862 return ME->getMemberDecl();
14863 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14864 // FIXME: If this is a reference, map through to its value.
14865 return DRE->getDecl();
14866 return nullptr;
14867 }
14868
14869 /// Note that an object \p O was modified or used by an expression
14870 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14871 /// the object \p O as obtained via the \p UsageMap.
14872 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14873 // Get the old usage for the given object and usage kind.
14874 Usage &U = UI.Uses[UK];
14875 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14876 // If we have a modification as side effect and are in a sequenced
14877 // subexpression, save the old Usage so that we can restore it later
14878 // in SequencedSubexpression::~SequencedSubexpression.
14879 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14880 ModAsSideEffect->push_back(std::make_pair(O, U));
14881 // Then record the new usage with the current sequencing region.
14882 U.UsageExpr = UsageExpr;
14883 U.Seq = Region;
14884 }
14885 }
14886
14887 /// Check whether a modification or use of an object \p O in an expression
14888 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14889 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14890 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14891 /// usage and false we are checking for a mod-use unsequenced usage.
14892 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14893 UsageKind OtherKind, bool IsModMod) {
14894 if (UI.Diagnosed)
14895 return;
14896
14897 const Usage &U = UI.Uses[OtherKind];
14898 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14899 return;
14900
14901 const Expr *Mod = U.UsageExpr;
14902 const Expr *ModOrUse = UsageExpr;
14903 if (OtherKind == UK_Use)
14904 std::swap(Mod, ModOrUse);
14905
14906 SemaRef.DiagRuntimeBehavior(
14907 Mod->getExprLoc(), {Mod, ModOrUse},
14908 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14909 : diag::warn_unsequenced_mod_use)
14910 << O << SourceRange(ModOrUse->getExprLoc()));
14911 UI.Diagnosed = true;
14912 }
14913
14914 // A note on note{Pre, Post}{Use, Mod}:
14915 //
14916 // (It helps to follow the algorithm with an expression such as
14917 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14918 // operations before C++17 and both are well-defined in C++17).
14919 //
14920 // When visiting a node which uses/modify an object we first call notePreUse
14921 // or notePreMod before visiting its sub-expression(s). At this point the
14922 // children of the current node have not yet been visited and so the eventual
14923 // uses/modifications resulting from the children of the current node have not
14924 // been recorded yet.
14925 //
14926 // We then visit the children of the current node. After that notePostUse or
14927 // notePostMod is called. These will 1) detect an unsequenced modification
14928 // as side effect (as in "k++ + k") and 2) add a new usage with the
14929 // appropriate usage kind.
14930 //
14931 // We also have to be careful that some operation sequences modification as
14932 // side effect as well (for example: || or ,). To account for this we wrap
14933 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14934 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14935 // which record usages which are modifications as side effect, and then
14936 // downgrade them (or more accurately restore the previous usage which was a
14937 // modification as side effect) when exiting the scope of the sequenced
14938 // subexpression.
14939
14940 void notePreUse(Object O, const Expr *UseExpr) {
14941 UsageInfo &UI = UsageMap[O];
14942 // Uses conflict with other modifications.
14943 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14944 }
14945
14946 void notePostUse(Object O, const Expr *UseExpr) {
14947 UsageInfo &UI = UsageMap[O];
14948 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14949 /*IsModMod=*/false);
14950 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14951 }
14952
14953 void notePreMod(Object O, const Expr *ModExpr) {
14954 UsageInfo &UI = UsageMap[O];
14955 // Modifications conflict with other modifications and with uses.
14956 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14957 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14958 }
14959
14960 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14961 UsageInfo &UI = UsageMap[O];
14962 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14963 /*IsModMod=*/true);
14964 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14965 }
14966
14967public:
14968 SequenceChecker(Sema &S, const Expr *E,
14969 SmallVectorImpl<const Expr *> &WorkList)
14970 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14971 Visit(E);
14972 // Silence a -Wunused-private-field since WorkList is now unused.
14973 // TODO: Evaluate if it can be used, and if not remove it.
14974 (void)this->WorkList;
14975 }
14976
14977 void VisitStmt(const Stmt *S) {
14978 // Skip all statements which aren't expressions for now.
14979 }
14980
14981 void VisitExpr(const Expr *E) {
14982 // By default, just recurse to evaluated subexpressions.
14983 Base::VisitStmt(E);
14984 }
14985
14986 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14987 for (auto *Sub : CSE->children()) {
14988 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14989 if (!ChildExpr)
14990 continue;
14991
14992 if (ChildExpr == CSE->getOperand())
14993 // Do not recurse over a CoroutineSuspendExpr's operand.
14994 // The operand is also a subexpression of getCommonExpr(), and
14995 // recursing into it directly could confuse object management
14996 // for the sake of sequence tracking.
14997 continue;
14998
14999 Visit(Sub);
15000 }
15001 }
15002
15003 void VisitCastExpr(const CastExpr *E) {
15004 Object O = Object();
15005 if (E->getCastKind() == CK_LValueToRValue)
15006 O = getObject(E->getSubExpr(), false);
15007
15008 if (O)
15009 notePreUse(O, E);
15010 VisitExpr(E);
15011 if (O)
15012 notePostUse(O, E);
15013 }
15014
15015 void VisitSequencedExpressions(const Expr *SequencedBefore,
15016 const Expr *SequencedAfter) {
15017 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
15018 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
15019 SequenceTree::Seq OldRegion = Region;
15020
15021 {
15022 SequencedSubexpression SeqBefore(*this);
15023 Region = BeforeRegion;
15024 Visit(SequencedBefore);
15025 }
15026
15027 Region = AfterRegion;
15028 Visit(SequencedAfter);
15029
15030 Region = OldRegion;
15031
15032 Tree.merge(BeforeRegion);
15033 Tree.merge(AfterRegion);
15034 }
15035
15036 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15037 // C++17 [expr.sub]p1:
15038 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15039 // expression E1 is sequenced before the expression E2.
15040 if (SemaRef.getLangOpts().CPlusPlus17)
15041 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
15042 else {
15043 Visit(ASE->getLHS());
15044 Visit(ASE->getRHS());
15045 }
15046 }
15047
15048 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15049 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15050 void VisitBinPtrMem(const BinaryOperator *BO) {
15051 // C++17 [expr.mptr.oper]p4:
15052 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15053 // the expression E1 is sequenced before the expression E2.
15054 if (SemaRef.getLangOpts().CPlusPlus17)
15055 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15056 else {
15057 Visit(BO->getLHS());
15058 Visit(BO->getRHS());
15059 }
15060 }
15061
15062 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15063 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15064 void VisitBinShlShr(const BinaryOperator *BO) {
15065 // C++17 [expr.shift]p4:
15066 // The expression E1 is sequenced before the expression E2.
15067 if (SemaRef.getLangOpts().CPlusPlus17)
15068 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15069 else {
15070 Visit(BO->getLHS());
15071 Visit(BO->getRHS());
15072 }
15073 }
15074
15075 void VisitBinComma(const BinaryOperator *BO) {
15076 // C++11 [expr.comma]p1:
15077 // Every value computation and side effect associated with the left
15078 // expression is sequenced before every value computation and side
15079 // effect associated with the right expression.
15080 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15081 }
15082
15083 void VisitBinAssign(const BinaryOperator *BO) {
15084 SequenceTree::Seq RHSRegion;
15085 SequenceTree::Seq LHSRegion;
15086 if (SemaRef.getLangOpts().CPlusPlus17) {
15087 RHSRegion = Tree.allocate(Region);
15088 LHSRegion = Tree.allocate(Region);
15089 } else {
15090 RHSRegion = Region;
15091 LHSRegion = Region;
15092 }
15093 SequenceTree::Seq OldRegion = Region;
15094
15095 // C++11 [expr.ass]p1:
15096 // [...] the assignment is sequenced after the value computation
15097 // of the right and left operands, [...]
15098 //
15099 // so check it before inspecting the operands and update the
15100 // map afterwards.
15101 Object O = getObject(BO->getLHS(), /*Mod=*/true);
15102 if (O)
15103 notePreMod(O, BO);
15104
15105 if (SemaRef.getLangOpts().CPlusPlus17) {
15106 // C++17 [expr.ass]p1:
15107 // [...] The right operand is sequenced before the left operand. [...]
15108 {
15109 SequencedSubexpression SeqBefore(*this);
15110 Region = RHSRegion;
15111 Visit(BO->getRHS());
15112 }
15113
15114 Region = LHSRegion;
15115 Visit(BO->getLHS());
15116
15117 if (O && isa<CompoundAssignOperator>(BO))
15118 notePostUse(O, BO);
15119
15120 } else {
15121 // C++11 does not specify any sequencing between the LHS and RHS.
15122 Region = LHSRegion;
15123 Visit(BO->getLHS());
15124
15125 if (O && isa<CompoundAssignOperator>(BO))
15126 notePostUse(O, BO);
15127
15128 Region = RHSRegion;
15129 Visit(BO->getRHS());
15130 }
15131
15132 // C++11 [expr.ass]p1:
15133 // the assignment is sequenced [...] before the value computation of the
15134 // assignment expression.
15135 // C11 6.5.16/3 has no such rule.
15136 Region = OldRegion;
15137 if (O)
15138 notePostMod(O, BO,
15139 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15140 : UK_ModAsSideEffect);
15141 if (SemaRef.getLangOpts().CPlusPlus17) {
15142 Tree.merge(RHSRegion);
15143 Tree.merge(LHSRegion);
15144 }
15145 }
15146
15147 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15148 VisitBinAssign(CAO);
15149 }
15150
15151 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15152 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15153 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15154 Object O = getObject(UO->getSubExpr(), true);
15155 if (!O)
15156 return VisitExpr(UO);
15157
15158 notePreMod(O, UO);
15159 Visit(UO->getSubExpr());
15160 // C++11 [expr.pre.incr]p1:
15161 // the expression ++x is equivalent to x+=1
15162 notePostMod(O, UO,
15163 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15164 : UK_ModAsSideEffect);
15165 }
15166
15167 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15168 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15169 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15170 Object O = getObject(UO->getSubExpr(), true);
15171 if (!O)
15172 return VisitExpr(UO);
15173
15174 notePreMod(O, UO);
15175 Visit(UO->getSubExpr());
15176 notePostMod(O, UO, UK_ModAsSideEffect);
15177 }
15178
15179 void VisitBinLOr(const BinaryOperator *BO) {
15180 // C++11 [expr.log.or]p2:
15181 // If the second expression is evaluated, every value computation and
15182 // side effect associated with the first expression is sequenced before
15183 // every value computation and side effect associated with the
15184 // second expression.
15185 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15186 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15187 SequenceTree::Seq OldRegion = Region;
15188
15189 EvaluationTracker Eval(*this);
15190 {
15191 SequencedSubexpression Sequenced(*this);
15192 Region = LHSRegion;
15193 Visit(BO->getLHS());
15194 }
15195
15196 // C++11 [expr.log.or]p1:
15197 // [...] the second operand is not evaluated if the first operand
15198 // evaluates to true.
15199 bool EvalResult = false;
15200 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15201 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15202 if (ShouldVisitRHS) {
15203 Region = RHSRegion;
15204 Visit(BO->getRHS());
15205 }
15206
15207 Region = OldRegion;
15208 Tree.merge(LHSRegion);
15209 Tree.merge(RHSRegion);
15210 }
15211
15212 void VisitBinLAnd(const BinaryOperator *BO) {
15213 // C++11 [expr.log.and]p2:
15214 // If the second expression is evaluated, every value computation and
15215 // side effect associated with the first expression is sequenced before
15216 // every value computation and side effect associated with the
15217 // second expression.
15218 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15219 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15220 SequenceTree::Seq OldRegion = Region;
15221
15222 EvaluationTracker Eval(*this);
15223 {
15224 SequencedSubexpression Sequenced(*this);
15225 Region = LHSRegion;
15226 Visit(BO->getLHS());
15227 }
15228
15229 // C++11 [expr.log.and]p1:
15230 // [...] the second operand is not evaluated if the first operand is false.
15231 bool EvalResult = false;
15232 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15233 bool ShouldVisitRHS = !EvalOK || EvalResult;
15234 if (ShouldVisitRHS) {
15235 Region = RHSRegion;
15236 Visit(BO->getRHS());
15237 }
15238
15239 Region = OldRegion;
15240 Tree.merge(LHSRegion);
15241 Tree.merge(RHSRegion);
15242 }
15243
15244 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15245 // C++11 [expr.cond]p1:
15246 // [...] Every value computation and side effect associated with the first
15247 // expression is sequenced before every value computation and side effect
15248 // associated with the second or third expression.
15249 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15250
15251 // No sequencing is specified between the true and false expression.
15252 // However since exactly one of both is going to be evaluated we can
15253 // consider them to be sequenced. This is needed to avoid warning on
15254 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15255 // both the true and false expressions because we can't evaluate x.
15256 // This will still allow us to detect an expression like (pre C++17)
15257 // "(x ? y += 1 : y += 2) = y".
15258 //
15259 // We don't wrap the visitation of the true and false expression with
15260 // SequencedSubexpression because we don't want to downgrade modifications
15261 // as side effect in the true and false expressions after the visition
15262 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15263 // not warn between the two "y++", but we should warn between the "y++"
15264 // and the "y".
15265 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15266 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15267 SequenceTree::Seq OldRegion = Region;
15268
15269 EvaluationTracker Eval(*this);
15270 {
15271 SequencedSubexpression Sequenced(*this);
15272 Region = ConditionRegion;
15273 Visit(CO->getCond());
15274 }
15275
15276 // C++11 [expr.cond]p1:
15277 // [...] The first expression is contextually converted to bool (Clause 4).
15278 // It is evaluated and if it is true, the result of the conditional
15279 // expression is the value of the second expression, otherwise that of the
15280 // third expression. Only one of the second and third expressions is
15281 // evaluated. [...]
15282 bool EvalResult = false;
15283 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15284 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15285 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15286 if (ShouldVisitTrueExpr) {
15287 Region = TrueRegion;
15288 Visit(CO->getTrueExpr());
15289 }
15290 if (ShouldVisitFalseExpr) {
15291 Region = FalseRegion;
15292 Visit(CO->getFalseExpr());
15293 }
15294
15295 Region = OldRegion;
15296 Tree.merge(ConditionRegion);
15297 Tree.merge(TrueRegion);
15298 Tree.merge(FalseRegion);
15299 }
15300
15301 void VisitCallExpr(const CallExpr *CE) {
15302 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15303
15304 if (CE->isUnevaluatedBuiltinCall(Context))
15305 return;
15306
15307 // C++11 [intro.execution]p15:
15308 // When calling a function [...], every value computation and side effect
15309 // associated with any argument expression, or with the postfix expression
15310 // designating the called function, is sequenced before execution of every
15311 // expression or statement in the body of the function [and thus before
15312 // the value computation of its result].
15313 SequencedSubexpression Sequenced(*this);
15314 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15315 // C++17 [expr.call]p5
15316 // The postfix-expression is sequenced before each expression in the
15317 // expression-list and any default argument. [...]
15318 SequenceTree::Seq CalleeRegion;
15319 SequenceTree::Seq OtherRegion;
15320 if (SemaRef.getLangOpts().CPlusPlus17) {
15321 CalleeRegion = Tree.allocate(Region);
15322 OtherRegion = Tree.allocate(Region);
15323 } else {
15324 CalleeRegion = Region;
15325 OtherRegion = Region;
15326 }
15327 SequenceTree::Seq OldRegion = Region;
15328
15329 // Visit the callee expression first.
15330 Region = CalleeRegion;
15331 if (SemaRef.getLangOpts().CPlusPlus17) {
15332 SequencedSubexpression Sequenced(*this);
15333 Visit(CE->getCallee());
15334 } else {
15335 Visit(CE->getCallee());
15336 }
15337
15338 // Then visit the argument expressions.
15339 Region = OtherRegion;
15340 for (const Expr *Argument : CE->arguments())
15341 Visit(Argument);
15342
15343 Region = OldRegion;
15344 if (SemaRef.getLangOpts().CPlusPlus17) {
15345 Tree.merge(CalleeRegion);
15346 Tree.merge(OtherRegion);
15347 }
15348 });
15349 }
15350
15351 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15352 // C++17 [over.match.oper]p2:
15353 // [...] the operator notation is first transformed to the equivalent
15354 // function-call notation as summarized in Table 12 (where @ denotes one
15355 // of the operators covered in the specified subclause). However, the
15356 // operands are sequenced in the order prescribed for the built-in
15357 // operator (Clause 8).
15358 //
15359 // From the above only overloaded binary operators and overloaded call
15360 // operators have sequencing rules in C++17 that we need to handle
15361 // separately.
15362 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15363 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15364 return VisitCallExpr(CXXOCE);
15365
15366 enum {
15367 NoSequencing,
15368 LHSBeforeRHS,
15369 RHSBeforeLHS,
15370 LHSBeforeRest
15371 } SequencingKind;
15372 switch (CXXOCE->getOperator()) {
15373 case OO_Equal:
15374 case OO_PlusEqual:
15375 case OO_MinusEqual:
15376 case OO_StarEqual:
15377 case OO_SlashEqual:
15378 case OO_PercentEqual:
15379 case OO_CaretEqual:
15380 case OO_AmpEqual:
15381 case OO_PipeEqual:
15382 case OO_LessLessEqual:
15383 case OO_GreaterGreaterEqual:
15384 SequencingKind = RHSBeforeLHS;
15385 break;
15386
15387 case OO_LessLess:
15388 case OO_GreaterGreater:
15389 case OO_AmpAmp:
15390 case OO_PipePipe:
15391 case OO_Comma:
15392 case OO_ArrowStar:
15393 case OO_Subscript:
15394 SequencingKind = LHSBeforeRHS;
15395 break;
15396
15397 case OO_Call:
15398 SequencingKind = LHSBeforeRest;
15399 break;
15400
15401 default:
15402 SequencingKind = NoSequencing;
15403 break;
15404 }
15405
15406 if (SequencingKind == NoSequencing)
15407 return VisitCallExpr(CXXOCE);
15408
15409 // This is a call, so all subexpressions are sequenced before the result.
15410 SequencedSubexpression Sequenced(*this);
15411
15412 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15413 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15414 "Should only get there with C++17 and above!");
15415 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15416 "Should only get there with an overloaded binary operator"
15417 " or an overloaded call operator!");
15418
15419 if (SequencingKind == LHSBeforeRest) {
15420 assert(CXXOCE->getOperator() == OO_Call &&
15421 "We should only have an overloaded call operator here!");
15422
15423 // This is very similar to VisitCallExpr, except that we only have the
15424 // C++17 case. The postfix-expression is the first argument of the
15425 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15426 // are in the following arguments.
15427 //
15428 // Note that we intentionally do not visit the callee expression since
15429 // it is just a decayed reference to a function.
15430 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15431 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15432 SequenceTree::Seq OldRegion = Region;
15433
15434 assert(CXXOCE->getNumArgs() >= 1 &&
15435 "An overloaded call operator must have at least one argument"
15436 " for the postfix-expression!");
15437 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15438 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15439 CXXOCE->getNumArgs() - 1);
15440
15441 // Visit the postfix-expression first.
15442 {
15443 Region = PostfixExprRegion;
15444 SequencedSubexpression Sequenced(*this);
15445 Visit(PostfixExpr);
15446 }
15447
15448 // Then visit the argument expressions.
15449 Region = ArgsRegion;
15450 for (const Expr *Arg : Args)
15451 Visit(Arg);
15452
15453 Region = OldRegion;
15454 Tree.merge(PostfixExprRegion);
15455 Tree.merge(ArgsRegion);
15456 } else {
15457 assert(CXXOCE->getNumArgs() == 2 &&
15458 "Should only have two arguments here!");
15459 assert((SequencingKind == LHSBeforeRHS ||
15460 SequencingKind == RHSBeforeLHS) &&
15461 "Unexpected sequencing kind!");
15462
15463 // We do not visit the callee expression since it is just a decayed
15464 // reference to a function.
15465 const Expr *E1 = CXXOCE->getArg(0);
15466 const Expr *E2 = CXXOCE->getArg(1);
15467 if (SequencingKind == RHSBeforeLHS)
15468 std::swap(E1, E2);
15469
15470 return VisitSequencedExpressions(E1, E2);
15471 }
15472 });
15473 }
15474
15475 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15476 // This is a call, so all subexpressions are sequenced before the result.
15477 SequencedSubexpression Sequenced(*this);
15478
15479 if (!CCE->isListInitialization())
15480 return VisitExpr(CCE);
15481
15482 // In C++11, list initializations are sequenced.
15483 SequenceExpressionsInOrder(
15484 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15485 }
15486
15487 void VisitInitListExpr(const InitListExpr *ILE) {
15488 if (!SemaRef.getLangOpts().CPlusPlus11)
15489 return VisitExpr(ILE);
15490
15491 // In C++11, list initializations are sequenced.
15492 SequenceExpressionsInOrder(ILE->inits());
15493 }
15494
15495 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15496 // C++20 parenthesized list initializations are sequenced. See C++20
15497 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15498 SequenceExpressionsInOrder(PLIE->getInitExprs());
15499 }
15500
15501private:
15502 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15504 SequenceTree::Seq Parent = Region;
15505 for (const Expr *E : ExpressionList) {
15506 if (!E)
15507 continue;
15508 Region = Tree.allocate(Parent);
15509 Elts.push_back(Region);
15510 Visit(E);
15511 }
15512
15513 // Forget that the initializers are sequenced.
15514 Region = Parent;
15515 for (unsigned I = 0; I < Elts.size(); ++I)
15516 Tree.merge(Elts[I]);
15517 }
15518};
15519
15520SequenceChecker::UsageInfo::UsageInfo() = default;
15521
15522} // namespace
15523
15524void Sema::CheckUnsequencedOperations(const Expr *E) {
15525 SmallVector<const Expr *, 8> WorkList;
15526 WorkList.push_back(E);
15527 while (!WorkList.empty()) {
15528 const Expr *Item = WorkList.pop_back_val();
15529 SequenceChecker(*this, Item, WorkList);
15530 }
15531}
15532
15533void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15534 bool IsConstexpr) {
15535 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15536 IsConstexpr || isa<ConstantExpr>(E));
15537 CheckImplicitConversions(E, CheckLoc);
15538 if (!E->isInstantiationDependent())
15539 CheckUnsequencedOperations(E);
15540 if (!IsConstexpr && !E->isValueDependent())
15541 CheckForIntOverflow(E);
15542}
15543
15544void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15545 FieldDecl *BitField,
15546 Expr *Init) {
15547 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15548}
15549
15551 SourceLocation Loc) {
15552 if (!PType->isVariablyModifiedType())
15553 return;
15554 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15555 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15556 return;
15557 }
15558 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15559 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15560 return;
15561 }
15562 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15563 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15564 return;
15565 }
15566
15567 const ArrayType *AT = S.Context.getAsArrayType(PType);
15568 if (!AT)
15569 return;
15570
15573 return;
15574 }
15575
15576 S.Diag(Loc, diag::err_array_star_in_function_definition);
15577}
15578
15580 bool CheckParameterNames) {
15581 bool HasInvalidParm = false;
15582 for (ParmVarDecl *Param : Parameters) {
15583 assert(Param && "null in a parameter list");
15584 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15585 // function declarator that is part of a function definition of
15586 // that function shall not have incomplete type.
15587 //
15588 // C++23 [dcl.fct.def.general]/p2
15589 // The type of a parameter [...] for a function definition
15590 // shall not be a (possibly cv-qualified) class type that is incomplete
15591 // or abstract within the function body unless the function is deleted.
15592 if (!Param->isInvalidDecl() &&
15593 (RequireCompleteType(Param->getLocation(), Param->getType(),
15594 diag::err_typecheck_decl_incomplete_type) ||
15595 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15596 diag::err_abstract_type_in_decl,
15598 Param->setInvalidDecl();
15599 HasInvalidParm = true;
15600 }
15601
15602 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15603 // declaration of each parameter shall include an identifier.
15604 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15605 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15606 // Diagnose this as an extension in C17 and earlier.
15607 if (!getLangOpts().C23)
15608 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15609 }
15610
15611 // C99 6.7.5.3p12:
15612 // If the function declarator is not part of a definition of that
15613 // function, parameters may have incomplete type and may use the [*]
15614 // notation in their sequences of declarator specifiers to specify
15615 // variable length array types.
15616 QualType PType = Param->getOriginalType();
15617 // FIXME: This diagnostic should point the '[*]' if source-location
15618 // information is added for it.
15619 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15620
15621 // If the parameter is a c++ class type and it has to be destructed in the
15622 // callee function, declare the destructor so that it can be called by the
15623 // callee function. Do not perform any direct access check on the dtor here.
15624 if (!Param->isInvalidDecl()) {
15625 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15626 if (!ClassDecl->isInvalidDecl() &&
15627 !ClassDecl->hasIrrelevantDestructor() &&
15628 !ClassDecl->isDependentContext() &&
15629 ClassDecl->isParamDestroyedInCallee()) {
15631 MarkFunctionReferenced(Param->getLocation(), Destructor);
15632 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15633 }
15634 }
15635 }
15636
15637 // Parameters with the pass_object_size attribute only need to be marked
15638 // constant at function definitions. Because we lack information about
15639 // whether we're on a declaration or definition when we're instantiating the
15640 // attribute, we need to check for constness here.
15641 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15642 if (!Param->getType().isConstQualified())
15643 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15644 << Attr->getSpelling() << 1;
15645
15646 // Check for parameter names shadowing fields from the class.
15647 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15648 // The owning context for the parameter should be the function, but we
15649 // want to see if this function's declaration context is a record.
15650 DeclContext *DC = Param->getDeclContext();
15651 if (DC && DC->isFunctionOrMethod()) {
15652 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15653 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15654 RD, /*DeclIsField*/ false);
15655 }
15656 }
15657
15658 if (!Param->isInvalidDecl() &&
15659 Param->getOriginalType()->isWebAssemblyTableType()) {
15660 Param->setInvalidDecl();
15661 HasInvalidParm = true;
15662 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15663 }
15664 }
15665
15666 return HasInvalidParm;
15667}
15668
15669std::optional<std::pair<
15671 *E,
15673 &Ctx);
15674
15675/// Compute the alignment and offset of the base class object given the
15676/// derived-to-base cast expression and the alignment and offset of the derived
15677/// class object.
15678static std::pair<CharUnits, CharUnits>
15680 CharUnits BaseAlignment, CharUnits Offset,
15681 ASTContext &Ctx) {
15682 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15683 ++PathI) {
15684 const CXXBaseSpecifier *Base = *PathI;
15685 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15686 if (Base->isVirtual()) {
15687 // The complete object may have a lower alignment than the non-virtual
15688 // alignment of the base, in which case the base may be misaligned. Choose
15689 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15690 // conservative lower bound of the complete object alignment.
15691 CharUnits NonVirtualAlignment =
15693 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15694 Offset = CharUnits::Zero();
15695 } else {
15696 const ASTRecordLayout &RL =
15697 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15698 Offset += RL.getBaseClassOffset(BaseDecl);
15699 }
15700 DerivedType = Base->getType();
15701 }
15702
15703 return std::make_pair(BaseAlignment, Offset);
15704}
15705
15706/// Compute the alignment and offset of a binary additive operator.
15707static std::optional<std::pair<CharUnits, CharUnits>>
15709 bool IsSub, ASTContext &Ctx) {
15710 QualType PointeeType = PtrE->getType()->getPointeeType();
15711
15712 if (!PointeeType->isConstantSizeType())
15713 return std::nullopt;
15714
15715 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15716
15717 if (!P)
15718 return std::nullopt;
15719
15720 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15721 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15722 CharUnits Offset = EltSize * IdxRes->getExtValue();
15723 if (IsSub)
15724 Offset = -Offset;
15725 return std::make_pair(P->first, P->second + Offset);
15726 }
15727
15728 // If the integer expression isn't a constant expression, compute the lower
15729 // bound of the alignment using the alignment and offset of the pointer
15730 // expression and the element size.
15731 return std::make_pair(
15732 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15733 CharUnits::Zero());
15734}
15735
15736/// This helper function takes an lvalue expression and returns the alignment of
15737/// a VarDecl and a constant offset from the VarDecl.
15738std::optional<std::pair<
15739 CharUnits,
15741 ASTContext &Ctx) {
15742 E = E->IgnoreParens();
15743 switch (E->getStmtClass()) {
15744 default:
15745 break;
15746 case Stmt::CStyleCastExprClass:
15747 case Stmt::CXXStaticCastExprClass:
15748 case Stmt::ImplicitCastExprClass: {
15749 auto *CE = cast<CastExpr>(E);
15750 const Expr *From = CE->getSubExpr();
15751 switch (CE->getCastKind()) {
15752 default:
15753 break;
15754 case CK_NoOp:
15755 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15756 case CK_UncheckedDerivedToBase:
15757 case CK_DerivedToBase: {
15758 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15759 if (!P)
15760 break;
15761 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15762 P->second, Ctx);
15763 }
15764 }
15765 break;
15766 }
15767 case Stmt::ArraySubscriptExprClass: {
15768 auto *ASE = cast<ArraySubscriptExpr>(E);
15770 false, Ctx);
15771 }
15772 case Stmt::DeclRefExprClass: {
15773 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15774 // FIXME: If VD is captured by copy or is an escaping __block variable,
15775 // use the alignment of VD's type.
15776 if (!VD->getType()->isReferenceType()) {
15777 // Dependent alignment cannot be resolved -> bail out.
15778 if (VD->hasDependentAlignment())
15779 break;
15780 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15781 }
15782 if (VD->hasInit())
15783 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15784 }
15785 break;
15786 }
15787 case Stmt::MemberExprClass: {
15788 auto *ME = cast<MemberExpr>(E);
15789 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15790 if (!FD || FD->getType()->isReferenceType() ||
15792 break;
15793 std::optional<std::pair<CharUnits, CharUnits>> P;
15794 if (ME->isArrow())
15795 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15796 else
15797 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15798 if (!P)
15799 break;
15800 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15801 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15802 return std::make_pair(P->first,
15803 P->second + CharUnits::fromQuantity(Offset));
15804 }
15805 case Stmt::UnaryOperatorClass: {
15806 auto *UO = cast<UnaryOperator>(E);
15807 switch (UO->getOpcode()) {
15808 default:
15809 break;
15810 case UO_Deref:
15812 }
15813 break;
15814 }
15815 case Stmt::BinaryOperatorClass: {
15816 auto *BO = cast<BinaryOperator>(E);
15817 auto Opcode = BO->getOpcode();
15818 switch (Opcode) {
15819 default:
15820 break;
15821 case BO_Comma:
15823 }
15824 break;
15825 }
15826 }
15827 return std::nullopt;
15828}
15829
15830/// This helper function takes a pointer expression and returns the alignment of
15831/// a VarDecl and a constant offset from the VarDecl.
15832std::optional<std::pair<
15834 *E,
15836 &Ctx) {
15837 E = E->IgnoreParens();
15838 switch (E->getStmtClass()) {
15839 default:
15840 break;
15841 case Stmt::CStyleCastExprClass:
15842 case Stmt::CXXStaticCastExprClass:
15843 case Stmt::ImplicitCastExprClass: {
15844 auto *CE = cast<CastExpr>(E);
15845 const Expr *From = CE->getSubExpr();
15846 switch (CE->getCastKind()) {
15847 default:
15848 break;
15849 case CK_NoOp:
15850 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15851 case CK_ArrayToPointerDecay:
15852 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15853 case CK_UncheckedDerivedToBase:
15854 case CK_DerivedToBase: {
15855 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15856 if (!P)
15857 break;
15859 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15860 }
15861 }
15862 break;
15863 }
15864 case Stmt::CXXThisExprClass: {
15865 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15867 return std::make_pair(Alignment, CharUnits::Zero());
15868 }
15869 case Stmt::UnaryOperatorClass: {
15870 auto *UO = cast<UnaryOperator>(E);
15871 if (UO->getOpcode() == UO_AddrOf)
15873 break;
15874 }
15875 case Stmt::BinaryOperatorClass: {
15876 auto *BO = cast<BinaryOperator>(E);
15877 auto Opcode = BO->getOpcode();
15878 switch (Opcode) {
15879 default:
15880 break;
15881 case BO_Add:
15882 case BO_Sub: {
15883 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15884 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15885 std::swap(LHS, RHS);
15886 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15887 Ctx);
15888 }
15889 case BO_Comma:
15890 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15891 }
15892 break;
15893 }
15894 }
15895 return std::nullopt;
15896}
15897
15899 // See if we can compute the alignment of a VarDecl and an offset from it.
15900 std::optional<std::pair<CharUnits, CharUnits>> P =
15902
15903 if (P)
15904 return P->first.alignmentAtOffset(P->second);
15905
15906 // If that failed, return the type's alignment.
15908}
15909
15911 // This is actually a lot of work to potentially be doing on every
15912 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15913 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15914 return;
15915
15916 // Ignore dependent types.
15917 if (T->isDependentType() || Op->getType()->isDependentType())
15918 return;
15919
15920 // Require that the destination be a pointer type.
15921 const PointerType *DestPtr = T->getAs<PointerType>();
15922 if (!DestPtr) return;
15923
15924 // If the destination has alignment 1, we're done.
15925 QualType DestPointee = DestPtr->getPointeeType();
15926 if (DestPointee->isIncompleteType()) return;
15927 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15928 if (DestAlign.isOne()) return;
15929
15930 // Require that the source be a pointer type.
15931 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15932 if (!SrcPtr) return;
15933 QualType SrcPointee = SrcPtr->getPointeeType();
15934
15935 // Explicitly allow casts from cv void*. We already implicitly
15936 // allowed casts to cv void*, since they have alignment 1.
15937 // Also allow casts involving incomplete types, which implicitly
15938 // includes 'void'.
15939 if (SrcPointee->isIncompleteType()) return;
15940
15941 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15942
15943 if (SrcAlign >= DestAlign) return;
15944
15945 Diag(TRange.getBegin(), diag::warn_cast_align)
15946 << Op->getType() << T
15947 << static_cast<unsigned>(SrcAlign.getQuantity())
15948 << static_cast<unsigned>(DestAlign.getQuantity())
15949 << TRange << Op->getSourceRange();
15950}
15951
15952void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15953 const ArraySubscriptExpr *ASE,
15954 bool AllowOnePastEnd, bool IndexNegated) {
15955 // Already diagnosed by the constant evaluator.
15957 return;
15958
15959 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15960 if (IndexExpr->isValueDependent())
15961 return;
15962
15963 const Type *EffectiveType =
15965 BaseExpr = BaseExpr->IgnoreParenCasts();
15966 const ConstantArrayType *ArrayTy =
15967 Context.getAsConstantArrayType(BaseExpr->getType());
15968
15970 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15971
15972 const Type *BaseType =
15973 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15974 bool IsUnboundedArray =
15975 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15976 Context, StrictFlexArraysLevel,
15977 /*IgnoreTemplateOrMacroSubstitution=*/true);
15978 if (EffectiveType->isDependentType() ||
15979 (!IsUnboundedArray && BaseType->isDependentType()))
15980 return;
15981
15983 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15984 return;
15985
15986 llvm::APSInt index = Result.Val.getInt();
15987 if (IndexNegated) {
15988 index.setIsUnsigned(false);
15989 index = -index;
15990 }
15991
15992 if (IsUnboundedArray) {
15993 if (EffectiveType->isFunctionType())
15994 return;
15995 if (index.isUnsigned() || !index.isNegative()) {
15996 const auto &ASTC = getASTContext();
15997 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15998 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15999 if (index.getBitWidth() < AddrBits)
16000 index = index.zext(AddrBits);
16001 std::optional<CharUnits> ElemCharUnits =
16002 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
16003 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
16004 // pointer) bounds-checking isn't meaningful.
16005 if (!ElemCharUnits || ElemCharUnits->isZero())
16006 return;
16007 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
16008 // If index has more active bits than address space, we already know
16009 // we have a bounds violation to warn about. Otherwise, compute
16010 // address of (index + 1)th element, and warn about bounds violation
16011 // only if that address exceeds address space.
16012 if (index.getActiveBits() <= AddrBits) {
16013 bool Overflow;
16014 llvm::APInt Product(index);
16015 Product += 1;
16016 Product = Product.umul_ov(ElemBytes, Overflow);
16017 if (!Overflow && Product.getActiveBits() <= AddrBits)
16018 return;
16019 }
16020
16021 // Need to compute max possible elements in address space, since that
16022 // is included in diag message.
16023 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
16024 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
16025 MaxElems += 1;
16026 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
16027 MaxElems = MaxElems.udiv(ElemBytes);
16028
16029 unsigned DiagID =
16030 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16031 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16032
16033 // Diag message shows element size in bits and in "bytes" (platform-
16034 // dependent CharUnits)
16035 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16036 PDiag(DiagID) << index << AddrBits
16037 << (unsigned)ASTC.toBits(*ElemCharUnits)
16038 << ElemBytes << MaxElems
16039 << MaxElems.getZExtValue()
16040 << IndexExpr->getSourceRange());
16041
16042 const NamedDecl *ND = nullptr;
16043 // Try harder to find a NamedDecl to point at in the note.
16044 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16045 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16046 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16047 ND = DRE->getDecl();
16048 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16049 ND = ME->getMemberDecl();
16050
16051 if (ND)
16052 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16053 PDiag(diag::note_array_declared_here) << ND);
16054 }
16055 return;
16056 }
16057
16058 if (index.isUnsigned() || !index.isNegative()) {
16059 // It is possible that the type of the base expression after
16060 // IgnoreParenCasts is incomplete, even though the type of the base
16061 // expression before IgnoreParenCasts is complete (see PR39746 for an
16062 // example). In this case we have no information about whether the array
16063 // access exceeds the array bounds. However we can still diagnose an array
16064 // access which precedes the array bounds.
16065 if (BaseType->isIncompleteType())
16066 return;
16067
16068 llvm::APInt size = ArrayTy->getSize();
16069
16070 if (BaseType != EffectiveType) {
16071 // Make sure we're comparing apples to apples when comparing index to
16072 // size.
16073 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
16074 uint64_t array_typesize = Context.getTypeSize(BaseType);
16075
16076 // Handle ptrarith_typesize being zero, such as when casting to void*.
16077 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16078 if (!ptrarith_typesize)
16079 ptrarith_typesize = Context.getCharWidth();
16080
16081 if (ptrarith_typesize != array_typesize) {
16082 // There's a cast to a different size type involved.
16083 uint64_t ratio = array_typesize / ptrarith_typesize;
16084
16085 // TODO: Be smarter about handling cases where array_typesize is not a
16086 // multiple of ptrarith_typesize.
16087 if (ptrarith_typesize * ratio == array_typesize)
16088 size *= llvm::APInt(size.getBitWidth(), ratio);
16089 }
16090 }
16091
16092 if (size.getBitWidth() > index.getBitWidth())
16093 index = index.zext(size.getBitWidth());
16094 else if (size.getBitWidth() < index.getBitWidth())
16095 size = size.zext(index.getBitWidth());
16096
16097 // For array subscripting the index must be less than size, but for pointer
16098 // arithmetic also allow the index (offset) to be equal to size since
16099 // computing the next address after the end of the array is legal and
16100 // commonly done e.g. in C++ iterators and range-based for loops.
16101 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16102 return;
16103
16104 // Suppress the warning if the subscript expression (as identified by the
16105 // ']' location) and the index expression are both from macro expansions
16106 // within a system header.
16107 if (ASE) {
16108 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16109 ASE->getRBracketLoc());
16110 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
16111 SourceLocation IndexLoc =
16112 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
16113 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16114 return;
16115 }
16116 }
16117
16118 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16119 : diag::warn_ptr_arith_exceeds_bounds;
16120 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16121 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16122
16123 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16124 PDiag(DiagID)
16125 << index << ArrayTy->desugar() << CastMsg
16126 << CastMsgTy << IndexExpr->getSourceRange());
16127 } else {
16128 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16129 if (!ASE) {
16130 DiagID = diag::warn_ptr_arith_precedes_bounds;
16131 if (index.isNegative()) index = -index;
16132 }
16133
16134 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16135 PDiag(DiagID) << index << IndexExpr->getSourceRange());
16136 }
16137
16138 const NamedDecl *ND = nullptr;
16139 // Try harder to find a NamedDecl to point at in the note.
16140 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16141 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16142 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16143 ND = DRE->getDecl();
16144 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16145 ND = ME->getMemberDecl();
16146
16147 if (ND)
16148 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16149 PDiag(diag::note_array_declared_here) << ND);
16150}
16151
16152void Sema::CheckArrayAccess(const Expr *expr) {
16153 int AllowOnePastEnd = 0;
16154 while (expr) {
16155 expr = expr->IgnoreParenImpCasts();
16156 switch (expr->getStmtClass()) {
16157 case Stmt::ArraySubscriptExprClass: {
16158 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16159 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16160 AllowOnePastEnd > 0);
16161 expr = ASE->getBase();
16162 break;
16163 }
16164 case Stmt::MemberExprClass: {
16165 expr = cast<MemberExpr>(expr)->getBase();
16166 break;
16167 }
16168 case Stmt::CXXMemberCallExprClass: {
16169 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16170 break;
16171 }
16172 case Stmt::ArraySectionExprClass: {
16173 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16174 // FIXME: We should probably be checking all of the elements to the
16175 // 'length' here as well.
16176 if (ASE->getLowerBound())
16177 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16178 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16179 return;
16180 }
16181 case Stmt::UnaryOperatorClass: {
16182 // Only unwrap the * and & unary operators
16183 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16184 expr = UO->getSubExpr();
16185 switch (UO->getOpcode()) {
16186 case UO_AddrOf:
16187 AllowOnePastEnd++;
16188 break;
16189 case UO_Deref:
16190 AllowOnePastEnd--;
16191 break;
16192 default:
16193 return;
16194 }
16195 break;
16196 }
16197 case Stmt::ConditionalOperatorClass: {
16198 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16199 if (const Expr *lhs = cond->getLHS())
16200 CheckArrayAccess(lhs);
16201 if (const Expr *rhs = cond->getRHS())
16202 CheckArrayAccess(rhs);
16203 return;
16204 }
16205 case Stmt::CXXOperatorCallExprClass: {
16206 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16207 for (const auto *Arg : OCE->arguments())
16208 CheckArrayAccess(Arg);
16209 return;
16210 }
16211 default:
16212 return;
16213 }
16214 }
16215}
16216
16218 Expr *RHS, bool isProperty) {
16219 // Check if RHS is an Objective-C object literal, which also can get
16220 // immediately zapped in a weak reference. Note that we explicitly
16221 // allow ObjCStringLiterals, since those are designed to never really die.
16222 RHS = RHS->IgnoreParenImpCasts();
16223
16224 // This enum needs to match with the 'select' in
16225 // warn_objc_arc_literal_assign (off-by-1).
16227 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16228 return false;
16229
16230 S.Diag(Loc, diag::warn_arc_literal_assign)
16231 << (unsigned) Kind
16232 << (isProperty ? 0 : 1)
16233 << RHS->getSourceRange();
16234
16235 return true;
16236}
16237
16240 Expr *RHS, bool isProperty) {
16241 // Strip off any implicit cast added to get to the one ARC-specific.
16242 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16243 if (cast->getCastKind() == CK_ARCConsumeObject) {
16244 S.Diag(Loc, diag::warn_arc_retained_assign)
16246 << (isProperty ? 0 : 1)
16247 << RHS->getSourceRange();
16248 return true;
16249 }
16250 RHS = cast->getSubExpr();
16251 }
16252
16253 if (LT == Qualifiers::OCL_Weak &&
16254 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16255 return true;
16256
16257 return false;
16258}
16259
16261 QualType LHS, Expr *RHS) {
16263
16265 return false;
16266
16267 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16268 return true;
16269
16270 return false;
16271}
16272
16274 Expr *LHS, Expr *RHS) {
16275 QualType LHSType;
16276 // PropertyRef on LHS type need be directly obtained from
16277 // its declaration as it has a PseudoType.
16279 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16280 if (PRE && !PRE->isImplicitProperty()) {
16281 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16282 if (PD)
16283 LHSType = PD->getType();
16284 }
16285
16286 if (LHSType.isNull())
16287 LHSType = LHS->getType();
16288
16290
16291 if (LT == Qualifiers::OCL_Weak) {
16292 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16294 }
16295
16296 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16297 return;
16298
16299 // FIXME. Check for other life times.
16300 if (LT != Qualifiers::OCL_None)
16301 return;
16302
16303 if (PRE) {
16304 if (PRE->isImplicitProperty())
16305 return;
16306 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16307 if (!PD)
16308 return;
16309
16310 unsigned Attributes = PD->getPropertyAttributes();
16311 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16312 // when 'assign' attribute was not explicitly specified
16313 // by user, ignore it and rely on property type itself
16314 // for lifetime info.
16315 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16316 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16317 LHSType->isObjCRetainableType())
16318 return;
16319
16320 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16321 if (cast->getCastKind() == CK_ARCConsumeObject) {
16322 Diag(Loc, diag::warn_arc_retained_property_assign)
16323 << RHS->getSourceRange();
16324 return;
16325 }
16326 RHS = cast->getSubExpr();
16327 }
16328 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16329 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16330 return;
16331 }
16332 }
16333}
16334
16335//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16336
16337static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16338 SourceLocation StmtLoc,
16339 const NullStmt *Body) {
16340 // Do not warn if the body is a macro that expands to nothing, e.g:
16341 //
16342 // #define CALL(x)
16343 // if (condition)
16344 // CALL(0);
16345 if (Body->hasLeadingEmptyMacro())
16346 return false;
16347
16348 // Get line numbers of statement and body.
16349 bool StmtLineInvalid;
16350 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16351 &StmtLineInvalid);
16352 if (StmtLineInvalid)
16353 return false;
16354
16355 bool BodyLineInvalid;
16356 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16357 &BodyLineInvalid);
16358 if (BodyLineInvalid)
16359 return false;
16360
16361 // Warn if null statement and body are on the same line.
16362 if (StmtLine != BodyLine)
16363 return false;
16364
16365 return true;
16366}
16367
16369 const Stmt *Body,
16370 unsigned DiagID) {
16371 // Since this is a syntactic check, don't emit diagnostic for template
16372 // instantiations, this just adds noise.
16374 return;
16375
16376 // The body should be a null statement.
16377 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16378 if (!NBody)
16379 return;
16380
16381 // Do the usual checks.
16382 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16383 return;
16384
16385 Diag(NBody->getSemiLoc(), DiagID);
16386 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16387}
16388
16390 const Stmt *PossibleBody) {
16391 assert(!CurrentInstantiationScope); // Ensured by caller
16392
16393 SourceLocation StmtLoc;
16394 const Stmt *Body;
16395 unsigned DiagID;
16396 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16397 StmtLoc = FS->getRParenLoc();
16398 Body = FS->getBody();
16399 DiagID = diag::warn_empty_for_body;
16400 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16401 StmtLoc = WS->getRParenLoc();
16402 Body = WS->getBody();
16403 DiagID = diag::warn_empty_while_body;
16404 } else
16405 return; // Neither `for' nor `while'.
16406
16407 // The body should be a null statement.
16408 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16409 if (!NBody)
16410 return;
16411
16412 // Skip expensive checks if diagnostic is disabled.
16413 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16414 return;
16415
16416 // Do the usual checks.
16417 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16418 return;
16419
16420 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16421 // noise level low, emit diagnostics only if for/while is followed by a
16422 // CompoundStmt, e.g.:
16423 // for (int i = 0; i < n; i++);
16424 // {
16425 // a(i);
16426 // }
16427 // or if for/while is followed by a statement with more indentation
16428 // than for/while itself:
16429 // for (int i = 0; i < n; i++);
16430 // a(i);
16431 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16432 if (!ProbableTypo) {
16433 bool BodyColInvalid;
16434 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16435 PossibleBody->getBeginLoc(), &BodyColInvalid);
16436 if (BodyColInvalid)
16437 return;
16438
16439 bool StmtColInvalid;
16440 unsigned StmtCol =
16441 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16442 if (StmtColInvalid)
16443 return;
16444
16445 if (BodyCol > StmtCol)
16446 ProbableTypo = true;
16447 }
16448
16449 if (ProbableTypo) {
16450 Diag(NBody->getSemiLoc(), DiagID);
16451 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16452 }
16453}
16454
16455//===--- CHECK: Warn on self move with std::move. -------------------------===//
16456
16457void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16458 SourceLocation OpLoc) {
16459 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16460 return;
16461
16463 return;
16464
16465 // Strip parens and casts away.
16466 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16467 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16468
16469 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16470 // which we can treat as an inlined std::move
16471 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16472 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16473 RHSExpr = CE->getArg(0);
16474 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16475 CXXSCE && CXXSCE->isXValue())
16476 RHSExpr = CXXSCE->getSubExpr();
16477 else
16478 return;
16479
16480 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16481 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16482
16483 // Two DeclRefExpr's, check that the decls are the same.
16484 if (LHSDeclRef && RHSDeclRef) {
16485 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16486 return;
16487 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16488 RHSDeclRef->getDecl()->getCanonicalDecl())
16489 return;
16490
16491 auto D = Diag(OpLoc, diag::warn_self_move)
16492 << LHSExpr->getType() << LHSExpr->getSourceRange()
16493 << RHSExpr->getSourceRange();
16494 if (const FieldDecl *F =
16496 D << 1 << F
16497 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16498 else
16499 D << 0;
16500 return;
16501 }
16502
16503 // Member variables require a different approach to check for self moves.
16504 // MemberExpr's are the same if every nested MemberExpr refers to the same
16505 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16506 // the base Expr's are CXXThisExpr's.
16507 const Expr *LHSBase = LHSExpr;
16508 const Expr *RHSBase = RHSExpr;
16509 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16510 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16511 if (!LHSME || !RHSME)
16512 return;
16513
16514 while (LHSME && RHSME) {
16515 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16516 RHSME->getMemberDecl()->getCanonicalDecl())
16517 return;
16518
16519 LHSBase = LHSME->getBase();
16520 RHSBase = RHSME->getBase();
16521 LHSME = dyn_cast<MemberExpr>(LHSBase);
16522 RHSME = dyn_cast<MemberExpr>(RHSBase);
16523 }
16524
16525 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16526 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16527 if (LHSDeclRef && RHSDeclRef) {
16528 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16529 return;
16530 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16531 RHSDeclRef->getDecl()->getCanonicalDecl())
16532 return;
16533
16534 Diag(OpLoc, diag::warn_self_move)
16535 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16536 << RHSExpr->getSourceRange();
16537 return;
16538 }
16539
16540 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16541 Diag(OpLoc, diag::warn_self_move)
16542 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16543 << RHSExpr->getSourceRange();
16544}
16545
16546//===--- Layout compatibility ----------------------------------------------//
16547
16548static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16549
16550/// Check if two enumeration types are layout-compatible.
16551static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16552 const EnumDecl *ED2) {
16553 // C++11 [dcl.enum] p8:
16554 // Two enumeration types are layout-compatible if they have the same
16555 // underlying type.
16556 return ED1->isComplete() && ED2->isComplete() &&
16557 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16558}
16559
16560/// Check if two fields are layout-compatible.
16561/// Can be used on union members, which are exempt from alignment requirement
16562/// of common initial sequence.
16563static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16564 const FieldDecl *Field2,
16565 bool AreUnionMembers = false) {
16566#ifndef NDEBUG
16567 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16568 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16569 assert(((Field1Parent->isStructureOrClassType() &&
16570 Field2Parent->isStructureOrClassType()) ||
16571 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16572 "Can't evaluate layout compatibility between a struct field and a "
16573 "union field.");
16574 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16575 (AreUnionMembers && Field1Parent->isUnionType())) &&
16576 "AreUnionMembers should be 'true' for union fields (only).");
16577#endif
16578
16579 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16580 return false;
16581
16582 if (Field1->isBitField() != Field2->isBitField())
16583 return false;
16584
16585 if (Field1->isBitField()) {
16586 // Make sure that the bit-fields are the same length.
16587 unsigned Bits1 = Field1->getBitWidthValue();
16588 unsigned Bits2 = Field2->getBitWidthValue();
16589
16590 if (Bits1 != Bits2)
16591 return false;
16592 }
16593
16594 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16595 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16596 return false;
16597
16598 if (!AreUnionMembers &&
16599 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16600 return false;
16601
16602 return true;
16603}
16604
16605/// Check if two standard-layout structs are layout-compatible.
16606/// (C++11 [class.mem] p17)
16607static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16608 const RecordDecl *RD2) {
16609 // Get to the class where the fields are declared
16610 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16611 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16612
16613 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16614 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16615
16616 // Check the fields.
16617 return llvm::equal(RD1->fields(), RD2->fields(),
16618 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16619 return isLayoutCompatible(C, F1, F2);
16620 });
16621}
16622
16623/// Check if two standard-layout unions are layout-compatible.
16624/// (C++11 [class.mem] p18)
16625static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16626 const RecordDecl *RD2) {
16627 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16628 RD2->fields());
16629
16630 for (auto *Field1 : RD1->fields()) {
16631 auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
16632 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
16633 });
16634 if (It == UnmatchedFields.end())
16635 return false;
16636 [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
16637 assert(Result);
16638 }
16639
16640 return UnmatchedFields.empty();
16641}
16642
16643static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16644 const RecordDecl *RD2) {
16645 if (RD1->isUnion() != RD2->isUnion())
16646 return false;
16647
16648 if (RD1->isUnion())
16649 return isLayoutCompatibleUnion(C, RD1, RD2);
16650 else
16651 return isLayoutCompatibleStruct(C, RD1, RD2);
16652}
16653
16654/// Check if two types are layout-compatible in C++11 sense.
16655static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16656 if (T1.isNull() || T2.isNull())
16657 return false;
16658
16659 // C++20 [basic.types] p11:
16660 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16661 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16662 // or layout-compatible standard-layout class types (11.4).
16665
16666 if (C.hasSameType(T1, T2))
16667 return true;
16668
16669 const Type::TypeClass TC1 = T1->getTypeClass();
16670 const Type::TypeClass TC2 = T2->getTypeClass();
16671
16672 if (TC1 != TC2)
16673 return false;
16674
16675 if (TC1 == Type::Enum)
16676 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16677 if (TC1 == Type::Record) {
16678 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16679 return false;
16680
16682 T2->castAsRecordDecl());
16683 }
16684
16685 return false;
16686}
16687
16689 return isLayoutCompatible(getASTContext(), T1, T2);
16690}
16691
16692//===-------------- Pointer interconvertibility ----------------------------//
16693
16695 const TypeSourceInfo *Derived) {
16696 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16697 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16698
16699 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16700 getASTContext().hasSameType(BaseT, DerivedT))
16701 return true;
16702
16703 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16704 return false;
16705
16706 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16707 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16708 return true;
16709
16710 return false;
16711}
16712
16713//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16714
16715/// Given a type tag expression find the type tag itself.
16716///
16717/// \param TypeExpr Type tag expression, as it appears in user's code.
16718///
16719/// \param VD Declaration of an identifier that appears in a type tag.
16720///
16721/// \param MagicValue Type tag magic value.
16722///
16723/// \param isConstantEvaluated whether the evalaution should be performed in
16724
16725/// constant context.
16726static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16727 const ValueDecl **VD, uint64_t *MagicValue,
16728 bool isConstantEvaluated) {
16729 while(true) {
16730 if (!TypeExpr)
16731 return false;
16732
16733 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16734
16735 switch (TypeExpr->getStmtClass()) {
16736 case Stmt::UnaryOperatorClass: {
16737 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16738 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16739 TypeExpr = UO->getSubExpr();
16740 continue;
16741 }
16742 return false;
16743 }
16744
16745 case Stmt::DeclRefExprClass: {
16746 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16747 *VD = DRE->getDecl();
16748 return true;
16749 }
16750
16751 case Stmt::IntegerLiteralClass: {
16752 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16753 llvm::APInt MagicValueAPInt = IL->getValue();
16754 if (MagicValueAPInt.getActiveBits() <= 64) {
16755 *MagicValue = MagicValueAPInt.getZExtValue();
16756 return true;
16757 } else
16758 return false;
16759 }
16760
16761 case Stmt::BinaryConditionalOperatorClass:
16762 case Stmt::ConditionalOperatorClass: {
16763 const AbstractConditionalOperator *ACO =
16765 bool Result;
16766 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16767 isConstantEvaluated)) {
16768 if (Result)
16769 TypeExpr = ACO->getTrueExpr();
16770 else
16771 TypeExpr = ACO->getFalseExpr();
16772 continue;
16773 }
16774 return false;
16775 }
16776
16777 case Stmt::BinaryOperatorClass: {
16778 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16779 if (BO->getOpcode() == BO_Comma) {
16780 TypeExpr = BO->getRHS();
16781 continue;
16782 }
16783 return false;
16784 }
16785
16786 default:
16787 return false;
16788 }
16789 }
16790}
16791
16792/// Retrieve the C type corresponding to type tag TypeExpr.
16793///
16794/// \param TypeExpr Expression that specifies a type tag.
16795///
16796/// \param MagicValues Registered magic values.
16797///
16798/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16799/// kind.
16800///
16801/// \param TypeInfo Information about the corresponding C type.
16802///
16803/// \param isConstantEvaluated whether the evalaution should be performed in
16804/// constant context.
16805///
16806/// \returns true if the corresponding C type was found.
16808 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16809 const ASTContext &Ctx,
16810 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16811 *MagicValues,
16812 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16813 bool isConstantEvaluated) {
16814 FoundWrongKind = false;
16815
16816 // Variable declaration that has type_tag_for_datatype attribute.
16817 const ValueDecl *VD = nullptr;
16818
16819 uint64_t MagicValue;
16820
16821 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16822 return false;
16823
16824 if (VD) {
16825 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16826 if (I->getArgumentKind() != ArgumentKind) {
16827 FoundWrongKind = true;
16828 return false;
16829 }
16830 TypeInfo.Type = I->getMatchingCType();
16831 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16832 TypeInfo.MustBeNull = I->getMustBeNull();
16833 return true;
16834 }
16835 return false;
16836 }
16837
16838 if (!MagicValues)
16839 return false;
16840
16841 llvm::DenseMap<Sema::TypeTagMagicValue,
16843 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16844 if (I == MagicValues->end())
16845 return false;
16846
16847 TypeInfo = I->second;
16848 return true;
16849}
16850
16852 uint64_t MagicValue, QualType Type,
16853 bool LayoutCompatible,
16854 bool MustBeNull) {
16855 if (!TypeTagForDatatypeMagicValues)
16856 TypeTagForDatatypeMagicValues.reset(
16857 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16858
16859 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16860 (*TypeTagForDatatypeMagicValues)[Magic] =
16861 TypeTagData(Type, LayoutCompatible, MustBeNull);
16862}
16863
16864static bool IsSameCharType(QualType T1, QualType T2) {
16865 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16866 if (!BT1)
16867 return false;
16868
16869 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16870 if (!BT2)
16871 return false;
16872
16873 BuiltinType::Kind T1Kind = BT1->getKind();
16874 BuiltinType::Kind T2Kind = BT2->getKind();
16875
16876 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16877 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16878 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16879 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16880}
16881
16882void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16883 const ArrayRef<const Expr *> ExprArgs,
16884 SourceLocation CallSiteLoc) {
16885 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16886 bool IsPointerAttr = Attr->getIsPointer();
16887
16888 // Retrieve the argument representing the 'type_tag'.
16889 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16890 if (TypeTagIdxAST >= ExprArgs.size()) {
16891 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16892 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16893 return;
16894 }
16895 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16896 bool FoundWrongKind;
16897 TypeTagData TypeInfo;
16898 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16899 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16900 TypeInfo, isConstantEvaluatedContext())) {
16901 if (FoundWrongKind)
16902 Diag(TypeTagExpr->getExprLoc(),
16903 diag::warn_type_tag_for_datatype_wrong_kind)
16904 << TypeTagExpr->getSourceRange();
16905 return;
16906 }
16907
16908 // Retrieve the argument representing the 'arg_idx'.
16909 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16910 if (ArgumentIdxAST >= ExprArgs.size()) {
16911 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16912 << 1 << Attr->getArgumentIdx().getSourceIndex();
16913 return;
16914 }
16915 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16916 if (IsPointerAttr) {
16917 // Skip implicit cast of pointer to `void *' (as a function argument).
16918 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16919 if (ICE->getType()->isVoidPointerType() &&
16920 ICE->getCastKind() == CK_BitCast)
16921 ArgumentExpr = ICE->getSubExpr();
16922 }
16923 QualType ArgumentType = ArgumentExpr->getType();
16924
16925 // Passing a `void*' pointer shouldn't trigger a warning.
16926 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16927 return;
16928
16929 if (TypeInfo.MustBeNull) {
16930 // Type tag with matching void type requires a null pointer.
16931 if (!ArgumentExpr->isNullPointerConstant(Context,
16933 Diag(ArgumentExpr->getExprLoc(),
16934 diag::warn_type_safety_null_pointer_required)
16935 << ArgumentKind->getName()
16936 << ArgumentExpr->getSourceRange()
16937 << TypeTagExpr->getSourceRange();
16938 }
16939 return;
16940 }
16941
16942 QualType RequiredType = TypeInfo.Type;
16943 if (IsPointerAttr)
16944 RequiredType = Context.getPointerType(RequiredType);
16945
16946 bool mismatch = false;
16947 if (!TypeInfo.LayoutCompatible) {
16948 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16949
16950 // C++11 [basic.fundamental] p1:
16951 // Plain char, signed char, and unsigned char are three distinct types.
16952 //
16953 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16954 // char' depending on the current char signedness mode.
16955 if (mismatch)
16956 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16957 RequiredType->getPointeeType())) ||
16958 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16959 mismatch = false;
16960 } else
16961 if (IsPointerAttr)
16962 mismatch = !isLayoutCompatible(Context,
16963 ArgumentType->getPointeeType(),
16964 RequiredType->getPointeeType());
16965 else
16966 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16967
16968 if (mismatch)
16969 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16970 << ArgumentType << ArgumentKind
16971 << TypeInfo.LayoutCompatible << RequiredType
16972 << ArgumentExpr->getSourceRange()
16973 << TypeTagExpr->getSourceRange();
16974}
16975
16976void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16977 CharUnits Alignment) {
16978 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16979 Alignment);
16980}
16981
16983 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16984 const NamedDecl *ND = m.RD;
16985 if (ND->getName().empty()) {
16986 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16987 ND = TD;
16988 }
16989 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16990 << m.MD << ND << m.E->getSourceRange();
16991 }
16993}
16994
16996 E = E->IgnoreParens();
16997 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16998 return;
16999 if (isa<UnaryOperator>(E) &&
17000 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
17001 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
17002 if (isa<MemberExpr>(Op)) {
17003 auto &MisalignedMembersForExpr =
17005 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
17006 if (MA != MisalignedMembersForExpr.end() &&
17007 (T->isDependentType() || T->isIntegerType() ||
17008 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17009 Context.getTypeAlignInChars(
17010 T->getPointeeType()) <= MA->Alignment))))
17011 MisalignedMembersForExpr.erase(MA);
17012 }
17013 }
17014}
17015
17017 Expr *E,
17018 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17019 Action) {
17020 const auto *ME = dyn_cast<MemberExpr>(E);
17021 if (!ME)
17022 return;
17023
17024 // No need to check expressions with an __unaligned-qualified type.
17025 if (E->getType().getQualifiers().hasUnaligned())
17026 return;
17027
17028 // For a chain of MemberExpr like "a.b.c.d" this list
17029 // will keep FieldDecl's like [d, c, b].
17030 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17031 const MemberExpr *TopME = nullptr;
17032 bool AnyIsPacked = false;
17033 do {
17034 QualType BaseType = ME->getBase()->getType();
17035 if (BaseType->isDependentType())
17036 return;
17037 if (ME->isArrow())
17038 BaseType = BaseType->getPointeeType();
17039 auto *RD = BaseType->castAsRecordDecl();
17040 if (RD->isInvalidDecl())
17041 return;
17042
17043 ValueDecl *MD = ME->getMemberDecl();
17044 auto *FD = dyn_cast<FieldDecl>(MD);
17045 // We do not care about non-data members.
17046 if (!FD || FD->isInvalidDecl())
17047 return;
17048
17049 AnyIsPacked =
17050 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17051 ReverseMemberChain.push_back(FD);
17052
17053 TopME = ME;
17054 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17055 } while (ME);
17056 assert(TopME && "We did not compute a topmost MemberExpr!");
17057
17058 // Not the scope of this diagnostic.
17059 if (!AnyIsPacked)
17060 return;
17061
17062 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17063 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17064 // TODO: The innermost base of the member expression may be too complicated.
17065 // For now, just disregard these cases. This is left for future
17066 // improvement.
17067 if (!DRE && !isa<CXXThisExpr>(TopBase))
17068 return;
17069
17070 // Alignment expected by the whole expression.
17071 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17072
17073 // No need to do anything else with this case.
17074 if (ExpectedAlignment.isOne())
17075 return;
17076
17077 // Synthesize offset of the whole access.
17078 CharUnits Offset;
17079 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17080 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17081
17082 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17083 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17084 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17085
17086 // The base expression of the innermost MemberExpr may give
17087 // stronger guarantees than the class containing the member.
17088 if (DRE && !TopME->isArrow()) {
17089 const ValueDecl *VD = DRE->getDecl();
17090 if (!VD->getType()->isReferenceType())
17091 CompleteObjectAlignment =
17092 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17093 }
17094
17095 // Check if the synthesized offset fulfills the alignment.
17096 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17097 // It may fulfill the offset it but the effective alignment may still be
17098 // lower than the expected expression alignment.
17099 CompleteObjectAlignment < ExpectedAlignment) {
17100 // If this happens, we want to determine a sensible culprit of this.
17101 // Intuitively, watching the chain of member expressions from right to
17102 // left, we start with the required alignment (as required by the field
17103 // type) but some packed attribute in that chain has reduced the alignment.
17104 // It may happen that another packed structure increases it again. But if
17105 // we are here such increase has not been enough. So pointing the first
17106 // FieldDecl that either is packed or else its RecordDecl is,
17107 // seems reasonable.
17108 FieldDecl *FD = nullptr;
17109 CharUnits Alignment;
17110 for (FieldDecl *FDI : ReverseMemberChain) {
17111 if (FDI->hasAttr<PackedAttr>() ||
17112 FDI->getParent()->hasAttr<PackedAttr>()) {
17113 FD = FDI;
17114 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
17115 Context.getTypeAlignInChars(
17116 Context.getCanonicalTagType(FD->getParent())));
17117 break;
17118 }
17119 }
17120 assert(FD && "We did not find a packed FieldDecl!");
17121 Action(E, FD->getParent(), FD, Alignment);
17122 }
17123}
17124
17125void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17126 using namespace std::placeholders;
17127
17129 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17130 _2, _3, _4));
17131}
17132
17134 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17135 if (checkArgCount(TheCall, 1))
17136 return true;
17137
17138 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
17139 if (A.isInvalid())
17140 return true;
17141
17142 TheCall->setArg(0, A.get());
17143 QualType TyA = A.get()->getType();
17144
17145 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
17146 ArgTyRestr, 1))
17147 return true;
17148
17149 TheCall->setType(TyA);
17150 return false;
17151}
17152
17153bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17154 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17155 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17156 TheCall->setType(*Res);
17157 return false;
17158 }
17159 return true;
17160}
17161
17163 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17164 if (!Res)
17165 return true;
17166
17167 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17168 TheCall->setType(VecTy0->getElementType());
17169 else
17170 TheCall->setType(*Res);
17171
17172 return false;
17173}
17174
17176 SourceLocation Loc) {
17178 R = RHS->getEnumCoercedType(S.Context);
17179 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17181 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17182 << LHS->getSourceRange() << RHS->getSourceRange()
17183 << /*Arithmetic Between*/ 0 << L << R;
17184 }
17185 return false;
17186}
17187
17188/// Check if all arguments have the same type. If the types don't match, emit an
17189/// error message and return true. Otherwise return false.
17190///
17191/// For scalars we directly compare their unqualified types. But even if we
17192/// compare unqualified vector types, a difference in qualifiers in the element
17193/// types can make the vector types be considered not equal. For example,
17194/// vector of 4 'const float' values vs vector of 4 'float' values.
17195/// So we compare unqualified types of their elements and number of elements.
17197 ArrayRef<Expr *> Args) {
17198 assert(!Args.empty() && "Should have at least one argument.");
17199
17200 Expr *Arg0 = Args.front();
17201 QualType Ty0 = Arg0->getType();
17202
17203 auto EmitError = [&](Expr *ArgI) {
17204 SemaRef.Diag(Arg0->getBeginLoc(),
17205 diag::err_typecheck_call_different_arg_types)
17206 << Arg0->getType() << ArgI->getType();
17207 };
17208
17209 // Compare scalar types.
17210 if (!Ty0->isVectorType()) {
17211 for (Expr *ArgI : Args.drop_front())
17212 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17213 EmitError(ArgI);
17214 return true;
17215 }
17216
17217 return false;
17218 }
17219
17220 // Compare vector types.
17221 const auto *Vec0 = Ty0->castAs<VectorType>();
17222 for (Expr *ArgI : Args.drop_front()) {
17223 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17224 if (!VecI ||
17225 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17226 VecI->getElementType()) ||
17227 Vec0->getNumElements() != VecI->getNumElements()) {
17228 EmitError(ArgI);
17229 return true;
17230 }
17231 }
17232
17233 return false;
17234}
17235
17236std::optional<QualType>
17238 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17239 if (checkArgCount(TheCall, 2))
17240 return std::nullopt;
17241
17243 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17244 return std::nullopt;
17245
17246 Expr *Args[2];
17247 for (int I = 0; I < 2; ++I) {
17248 ExprResult Converted =
17249 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17250 if (Converted.isInvalid())
17251 return std::nullopt;
17252 Args[I] = Converted.get();
17253 }
17254
17255 SourceLocation LocA = Args[0]->getBeginLoc();
17256 QualType TyA = Args[0]->getType();
17257
17258 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17259 return std::nullopt;
17260
17261 if (checkBuiltinVectorMathArgTypes(*this, Args))
17262 return std::nullopt;
17263
17264 TheCall->setArg(0, Args[0]);
17265 TheCall->setArg(1, Args[1]);
17266 return TyA;
17267}
17268
17270 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17271 if (checkArgCount(TheCall, 3))
17272 return true;
17273
17274 SourceLocation Loc = TheCall->getExprLoc();
17275 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17276 TheCall->getArg(1), Loc) ||
17277 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17278 TheCall->getArg(2), Loc))
17279 return true;
17280
17281 Expr *Args[3];
17282 for (int I = 0; I < 3; ++I) {
17283 ExprResult Converted =
17284 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17285 if (Converted.isInvalid())
17286 return true;
17287 Args[I] = Converted.get();
17288 }
17289
17290 int ArgOrdinal = 1;
17291 for (Expr *Arg : Args) {
17292 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17293 ArgTyRestr, ArgOrdinal++))
17294 return true;
17295 }
17296
17297 if (checkBuiltinVectorMathArgTypes(*this, Args))
17298 return true;
17299
17300 for (int I = 0; I < 3; ++I)
17301 TheCall->setArg(I, Args[I]);
17302
17303 TheCall->setType(Args[0]->getType());
17304 return false;
17305}
17306
17307bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17308 if (checkArgCount(TheCall, 1))
17309 return true;
17310
17311 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17312 if (A.isInvalid())
17313 return true;
17314
17315 TheCall->setArg(0, A.get());
17316 return false;
17317}
17318
17319bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17320 if (checkArgCount(TheCall, 1))
17321 return true;
17322
17323 ExprResult Arg = TheCall->getArg(0);
17324 QualType TyArg = Arg.get()->getType();
17325
17326 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17327 return Diag(TheCall->getArg(0)->getBeginLoc(),
17328 diag::err_builtin_invalid_arg_type)
17329 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17330
17331 TheCall->setType(TyArg);
17332 return false;
17333}
17334
17335ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17336 ExprResult CallResult) {
17337 if (checkArgCount(TheCall, 1))
17338 return ExprError();
17339
17340 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17341 if (MatrixArg.isInvalid())
17342 return MatrixArg;
17343 Expr *Matrix = MatrixArg.get();
17344
17345 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17346 if (!MType) {
17347 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17348 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17349 << Matrix->getType();
17350 return ExprError();
17351 }
17352
17353 // Create returned matrix type by swapping rows and columns of the argument
17354 // matrix type.
17355 QualType ResultType = Context.getConstantMatrixType(
17356 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17357
17358 // Change the return type to the type of the returned matrix.
17359 TheCall->setType(ResultType);
17360
17361 // Update call argument to use the possibly converted matrix argument.
17362 TheCall->setArg(0, Matrix);
17363 return CallResult;
17364}
17365
17366// Get and verify the matrix dimensions.
17367static std::optional<unsigned>
17369 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17370 if (!Value) {
17371 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17372 << Name;
17373 return {};
17374 }
17375 uint64_t Dim = Value->getZExtValue();
17376 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17377 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17378 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17379 return {};
17380 }
17381 return Dim;
17382}
17383
17384ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17385 ExprResult CallResult) {
17386 if (!getLangOpts().MatrixTypes) {
17387 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17388 return ExprError();
17389 }
17390
17391 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17393 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17394 << /*column*/ 1 << /*load*/ 0;
17395 return ExprError();
17396 }
17397
17398 if (checkArgCount(TheCall, 4))
17399 return ExprError();
17400
17401 unsigned PtrArgIdx = 0;
17402 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17403 Expr *RowsExpr = TheCall->getArg(1);
17404 Expr *ColumnsExpr = TheCall->getArg(2);
17405 Expr *StrideExpr = TheCall->getArg(3);
17406
17407 bool ArgError = false;
17408
17409 // Check pointer argument.
17410 {
17412 if (PtrConv.isInvalid())
17413 return PtrConv;
17414 PtrExpr = PtrConv.get();
17415 TheCall->setArg(0, PtrExpr);
17416 if (PtrExpr->isTypeDependent()) {
17417 TheCall->setType(Context.DependentTy);
17418 return TheCall;
17419 }
17420 }
17421
17422 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17423 QualType ElementTy;
17424 if (!PtrTy) {
17425 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17426 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17427 << PtrExpr->getType();
17428 ArgError = true;
17429 } else {
17430 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17431
17433 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17434 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17435 << /* no fp */ 0 << PtrExpr->getType();
17436 ArgError = true;
17437 }
17438 }
17439
17440 // Apply default Lvalue conversions and convert the expression to size_t.
17441 auto ApplyArgumentConversions = [this](Expr *E) {
17443 if (Conv.isInvalid())
17444 return Conv;
17445
17446 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17447 };
17448
17449 // Apply conversion to row and column expressions.
17450 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17451 if (!RowsConv.isInvalid()) {
17452 RowsExpr = RowsConv.get();
17453 TheCall->setArg(1, RowsExpr);
17454 } else
17455 RowsExpr = nullptr;
17456
17457 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17458 if (!ColumnsConv.isInvalid()) {
17459 ColumnsExpr = ColumnsConv.get();
17460 TheCall->setArg(2, ColumnsExpr);
17461 } else
17462 ColumnsExpr = nullptr;
17463
17464 // If any part of the result matrix type is still pending, just use
17465 // Context.DependentTy, until all parts are resolved.
17466 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17467 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17468 TheCall->setType(Context.DependentTy);
17469 return CallResult;
17470 }
17471
17472 // Check row and column dimensions.
17473 std::optional<unsigned> MaybeRows;
17474 if (RowsExpr)
17475 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17476
17477 std::optional<unsigned> MaybeColumns;
17478 if (ColumnsExpr)
17479 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17480
17481 // Check stride argument.
17482 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17483 if (StrideConv.isInvalid())
17484 return ExprError();
17485 StrideExpr = StrideConv.get();
17486 TheCall->setArg(3, StrideExpr);
17487
17488 if (MaybeRows) {
17489 if (std::optional<llvm::APSInt> Value =
17490 StrideExpr->getIntegerConstantExpr(Context)) {
17491 uint64_t Stride = Value->getZExtValue();
17492 if (Stride < *MaybeRows) {
17493 Diag(StrideExpr->getBeginLoc(),
17494 diag::err_builtin_matrix_stride_too_small);
17495 ArgError = true;
17496 }
17497 }
17498 }
17499
17500 if (ArgError || !MaybeRows || !MaybeColumns)
17501 return ExprError();
17502
17503 TheCall->setType(
17504 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17505 return CallResult;
17506}
17507
17508ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17509 ExprResult CallResult) {
17510 if (!getLangOpts().MatrixTypes) {
17511 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17512 return ExprError();
17513 }
17514
17515 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17517 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17518 << /*column*/ 1 << /*store*/ 1;
17519 return ExprError();
17520 }
17521
17522 if (checkArgCount(TheCall, 3))
17523 return ExprError();
17524
17525 unsigned PtrArgIdx = 1;
17526 Expr *MatrixExpr = TheCall->getArg(0);
17527 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17528 Expr *StrideExpr = TheCall->getArg(2);
17529
17530 bool ArgError = false;
17531
17532 {
17533 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17534 if (MatrixConv.isInvalid())
17535 return MatrixConv;
17536 MatrixExpr = MatrixConv.get();
17537 TheCall->setArg(0, MatrixExpr);
17538 }
17539 if (MatrixExpr->isTypeDependent()) {
17540 TheCall->setType(Context.DependentTy);
17541 return TheCall;
17542 }
17543
17544 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17545 if (!MatrixTy) {
17546 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17547 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17548 ArgError = true;
17549 }
17550
17551 {
17553 if (PtrConv.isInvalid())
17554 return PtrConv;
17555 PtrExpr = PtrConv.get();
17556 TheCall->setArg(1, PtrExpr);
17557 if (PtrExpr->isTypeDependent()) {
17558 TheCall->setType(Context.DependentTy);
17559 return TheCall;
17560 }
17561 }
17562
17563 // Check pointer argument.
17564 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17565 if (!PtrTy) {
17566 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17567 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17568 << PtrExpr->getType();
17569 ArgError = true;
17570 } else {
17571 QualType ElementTy = PtrTy->getPointeeType();
17572 if (ElementTy.isConstQualified()) {
17573 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17574 ArgError = true;
17575 }
17576 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17577 if (MatrixTy &&
17578 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17579 Diag(PtrExpr->getBeginLoc(),
17580 diag::err_builtin_matrix_pointer_arg_mismatch)
17581 << ElementTy << MatrixTy->getElementType();
17582 ArgError = true;
17583 }
17584 }
17585
17586 // Apply default Lvalue conversions and convert the stride expression to
17587 // size_t.
17588 {
17589 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17590 if (StrideConv.isInvalid())
17591 return StrideConv;
17592
17593 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17594 if (StrideConv.isInvalid())
17595 return StrideConv;
17596 StrideExpr = StrideConv.get();
17597 TheCall->setArg(2, StrideExpr);
17598 }
17599
17600 // Check stride argument.
17601 if (MatrixTy) {
17602 if (std::optional<llvm::APSInt> Value =
17603 StrideExpr->getIntegerConstantExpr(Context)) {
17604 uint64_t Stride = Value->getZExtValue();
17605 if (Stride < MatrixTy->getNumRows()) {
17606 Diag(StrideExpr->getBeginLoc(),
17607 diag::err_builtin_matrix_stride_too_small);
17608 ArgError = true;
17609 }
17610 }
17611 }
17612
17613 if (ArgError)
17614 return ExprError();
17615
17616 return CallResult;
17617}
17618
17620 const NamedDecl *Callee) {
17621 // This warning does not make sense in code that has no runtime behavior.
17623 return;
17624
17625 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17626
17627 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17628 return;
17629
17630 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17631 // all TCBs the callee is a part of.
17632 llvm::StringSet<> CalleeTCBs;
17633 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17634 CalleeTCBs.insert(A->getTCBName());
17635 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17636 CalleeTCBs.insert(A->getTCBName());
17637
17638 // Go through the TCBs the caller is a part of and emit warnings if Caller
17639 // is in a TCB that the Callee is not.
17640 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17641 StringRef CallerTCB = A->getTCBName();
17642 if (CalleeTCBs.count(CallerTCB) == 0) {
17643 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17644 << Callee << CallerTCB;
17645 }
17646 }
17647}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
Defines enumerations for traits support.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
llvm::json::Object Object
llvm::json::Array Array
static std::string getFunctionName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static QualType getVectorElementType(ASTContext &Context, QualType VecTy)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call)
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static 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)
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
@ 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:239
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:846
Builtin::Context & BuiltinInfo
Definition ASTContext.h:848
const LangOptions & getLangOpts() const
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:899
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:965
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:4397
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4575
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4581
SourceLocation getQuestionLoc() const
Definition Expr.h:4424
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4587
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:7347
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7351
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
SourceLocation getRBracketLoc() const
Definition Expr.h:2813
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2794
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3813
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3827
QualType getElementType() const
Definition TypeBase.h:3825
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6978
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7127
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7109
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:4082
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4215
Expr * getLHS() const
Definition Expr.h:4132
SourceLocation getOperatorLoc() const
Definition Expr.h:4124
SourceLocation getExprLoc() const
Definition Expr.h:4123
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2164
Expr * getRHS() const
Definition Expr.h:4134
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4168
Opcode getOpcode() const
Definition Expr.h:4127
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4179
BinaryOperatorKind Opcode
Definition Expr.h:4087
Pointer to a block type.
Definition TypeBase.h:3646
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
bool isInteger() const
Definition TypeBase.h:3305
bool isFloatingPoint() const
Definition TypeBase.h:3317
bool isSignedInteger() const
Definition TypeBase.h:3309
bool isUnsignedInteger() const
Definition TypeBase.h:3313
Kind getKind() const
Definition TypeBase.h:3292
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:99
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:383
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:4013
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1634
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:158
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:115
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5194
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5234
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:1235
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool isDynamicClass() const
Definition DeclCXX.h:575
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:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
SourceLocation getBeginLoc() const
Definition Expr.h:3321
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3204
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1620
arg_iterator arg_begin()
Definition Expr.h:3244
arg_iterator arg_end()
Definition Expr.h:3247
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
bool isCallToStdMove() const
Definition Expr.cpp:3676
Expr * getCallee()
Definition Expr.h:3134
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3280
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3181
arg_range arguments()
Definition Expr.h:3239
SourceLocation getEndLoc() const
Definition Expr.h:3340
SourceLocation getRParenLoc() const
Definition Expr.h:3318
Decl * getCalleeDecl()
Definition Expr.h:3164
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:1625
void setCallee(Expr *F)
Definition Expr.h:3136
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3223
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:3720
path_iterator path_begin()
Definition Expr.h:3790
CastKind getCastKind() const
Definition Expr.h:3764
path_iterator path_end()
Definition Expr.h:3791
Expr * getSubExpr()
Definition Expr.h:3770
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:4435
Expr * getLHS() const
Definition Expr.h:4469
Expr * getRHS() const
Definition Expr.h:4470
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3851
QualType desugar() const
Definition TypeBase.h:3952
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3907
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:4478
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4500
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:5725
Expr * getOperand() const
Definition ExprCXX.h:5377
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:2423
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2181
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
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:1383
ValueDecl * getDecl()
Definition Expr.h:1358
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1488
SourceLocation getBeginLoc() const
Definition Expr.h:1369
SourceLocation getLocation() const
Definition Expr.h:1366
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:2004
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:970
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3558
Represents an enum.
Definition Decl.h:4146
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4378
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
This represents one expression.
Definition Expr.h:113
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:3150
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:695
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:692
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
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:3123
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
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:3119
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:212
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4265
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
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:3107
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3115
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:3722
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:224
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:822
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:831
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:834
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:824
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:4104
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:465
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:468
QualType getType() const
Definition Expr.h:145
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:527
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:4358
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4817
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3411
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1686
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Represents a function declaration or definition.
Definition Decl.h:2059
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4612
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3804
param_iterator param_end()
Definition Decl.h:2918
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3907
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
param_iterator param_begin()
Definition Decl.h:2917
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3119
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4368
bool isStatic() const
Definition Decl.h:3060
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4183
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4169
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3868
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5398
unsigned getNumParams() const
Definition TypeBase.h:5676
QualType getParamType(unsigned i) const
Definition TypeBase.h:5678
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5802
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5687
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5797
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5683
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4594
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4903
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4899
QualType getReturnType() const
Definition TypeBase.h:4934
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:3897
Describes an C or C++ initializer list.
Definition Expr.h:5352
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
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:4428
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4449
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
bool isArrow() const
Definition Expr.h:3592
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3744
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1944
Represent a C++ namespace.
Definition Decl.h:593
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1715
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1729
SourceLocation getSemiLoc() const
Definition Stmt.h:1726
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
QualType getType() const
Definition DeclObjC.h:810
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:833
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:821
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:649
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:738
bool isImplicitProperty() const
Definition ExprObjC.h:735
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:83
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:2226
Represents a parameter to a function.
Definition Decl.h:1820
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:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6854
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5232
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8512
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3090
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:8428
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8554
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8468
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:8480
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8522
void removeLocalVolatile()
Definition TypeBase.h:8544
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
void removeLocalConst()
Definition TypeBase.h:8536
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8501
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8549
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1837
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8474
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:4460
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4546
field_range fields() const
Definition Decl.h:4663
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4538
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(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1159
@ 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:1242
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:574
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10385
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10390
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:1446
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:13182
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1137
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:2801
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9394
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9402
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9439
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:6971
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:2079
SemaHexagon & Hexagon()
Definition Sema.h:1486
SemaSYCL & SYCL()
Definition Sema.h:1556
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:1768
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:843
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1576
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:1304
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:228
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1516
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1371
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition Sema.h:935
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:777
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2639
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:1208
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:2746
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:1461
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:1476
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:1302
static const uint64_t MaximumAlignment
Definition Sema.h:1231
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:962
SemaHLSL & HLSL()
Definition Sema.h:1481
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1501
SemaRISCV & RISCV()
Definition Sema.h:1546
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool convertArgumentToType(Expr *&Value, QualType Ty)
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:2812
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7007
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1780
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:1339
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:2719
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15583
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:2456
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:648
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:1444
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:1526
FormatArgumentPassingKind
Definition Sema.h:2649
@ FAPK_Elsewhere
Definition Sema.h:2653
@ FAPK_Fixed
Definition Sema.h:2650
@ FAPK_Variadic
Definition Sema.h:2651
@ FAPK_VAList
Definition Sema.h:2652
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:8232
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:14079
SourceManager & getSourceManager() const
Definition Sema.h:933
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:2641
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:1536
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:1263
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:1566
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:1307
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:793
DiagnosticsEngine & Diags
Definition Sema.h:1306
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:1511
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:646
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
@ AbstractParamType
Definition Sema.h:6324
SemaSPIRV & SPIRV()
Definition Sema.h:1551
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:1491
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6459
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:1571
SemaARM & ARM()
Definition Sema.h:1451
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:4687
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1505
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:1819
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2017
bool isUTF8() const
Definition Expr.h:1954
bool isWide() const
Definition Expr.h:1953
bool isPascal() const
Definition Expr.h:1958
unsigned getLength() const
Definition Expr.h:1944
StringLiteralKind getKind() const
Definition Expr.h:1948
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
Return a source location that points to the specified byte of this string literal.
Definition Expr.cpp:1332
bool isUTF32() const
Definition Expr.h:1956
unsigned getByteLength() const
Definition Expr.h:1942
StringRef getString() const
Definition Expr.h:1887
bool isUTF16() const
Definition Expr.h:1955
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:2018
bool isOrdinary() const
Definition Expr.h:1952
unsigned getCharByteWidth() const
Definition Expr.h:1946
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3973
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
bool isUnion() const
Definition Decl.h:4063
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:394
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:6308
A container of type source information.
Definition TypeBase.h:8399
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:8410
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8685
bool isVoidType() const
Definition TypeBase.h:9037
bool isBooleanType() const
Definition TypeBase.h:9174
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2411
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9224
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:916
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2388
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2479
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2295
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:9204
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:841
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2641
bool isArrayType() const
Definition TypeBase.h:8764
bool isCharType() const
Definition Type.cpp:2315
bool isFunctionPointerType() const
Definition TypeBase.h:8732
bool isPointerType() const
Definition TypeBase.h:8665
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9081
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9331
bool isReferenceType() const
Definition TypeBase.h:8689
bool isEnumeralType() const
Definition TypeBase.h:8796
bool isScalarType() const
Definition TypeBase.h:9143
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:2076
bool isVariableArrayType() const
Definition TypeBase.h:8776
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2825
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9159
bool isExtVectorType() const
Definition TypeBase.h:8808
bool isExtVectorBoolType() const
Definition TypeBase.h:8812
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2864
bool isBitIntType() const
Definition TypeBase.h:8940
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9006
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8788
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8800
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2432
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3196
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2775
bool isMemberPointerType() const
Definition TypeBase.h:8746
bool isAtomicType() const
Definition TypeBase.h:8857
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8828
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3325
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2877
bool isUnscopedEnumerationType() const
Definition Type.cpp:2308
bool isObjCObjectType() const
Definition TypeBase.h:8848
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9317
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9180
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2651
bool isFunctionType() const
Definition TypeBase.h:8661
bool isObjCObjectPointerType() const
Definition TypeBase.h:8844
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2521
bool isStructureOrClassType() const
Definition Type.cpp:835
bool isVectorType() const
Definition TypeBase.h:8804
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2529
bool isFloatingType() const
Definition Type.cpp:2513
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:2456
bool isAnyPointerType() const
Definition TypeBase.h:8673
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
bool isNullPtrType() const
Definition TypeBase.h:9074
bool isRecordType() const
Definition TypeBase.h:8792
bool isObjCRetainableType() const
Definition Type.cpp:5591
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2787
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5310
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2852
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Expr * getSubExpr() const
Definition Expr.h:2329
Opcode getOpcode() const
Definition Expr.h:2324
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2406
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5646
Represents a variable declaration or definition.
Definition Decl.h:933
Represents a GCC generic vector type.
Definition TypeBase.h:4266
unsigned getNumElements() const
Definition TypeBase.h:4281
QualType getElementType() const
Definition TypeBase.h:4280
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
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:238
@ 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:1540
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1525
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1518
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1532
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2883
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1471
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1547
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:49
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
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:507
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:657
@ Comparison
A comparison.
Definition Sema.h:661
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
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:588
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
@ 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:677
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:144
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:558
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:493
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:515
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:158
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:65
StringLiteralKind
Definition Expr.h:1783
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:4227
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6017
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6010
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1775
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:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
Extra information about a function prototype.
Definition TypeBase.h:5483
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:13364
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13390
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13380
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13328
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6865
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2661
#define log2(__x)
Definition tgmath.h:970