clang 23.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any errors, even if we managed to build the
545 // call. We don't want to produce more than one error.
546 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1151 CallExpr *TheCall) {
1152 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1154 return;
1155
1156 bool UseDABAttr = false;
1157 const FunctionDecl *UseDecl = FD;
1158
1159 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1160 if (DABAttr) {
1161 UseDecl = DABAttr->getFunction();
1162 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1163 UseDABAttr = true;
1164 }
1165
1166 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1167
1168 if (!BuiltinID)
1169 return;
1170
1171 const TargetInfo &TI = getASTContext().getTargetInfo();
1172 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1173
1174 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1175 // If we refer to a diagnose_as_builtin attribute, we need to change the
1176 // argument index to refer to the arguments of the called function. Unless
1177 // the index is out of bounds, which presumably means it's a variadic
1178 // function.
1179 if (!UseDABAttr)
1180 return Index;
1181 unsigned DABIndices = DABAttr->argIndices_size();
1182 unsigned NewIndex = Index < DABIndices
1183 ? DABAttr->argIndices_begin()[Index]
1184 : Index - DABIndices + FD->getNumParams();
1185 if (NewIndex >= TheCall->getNumArgs())
1186 return std::nullopt;
1187 return NewIndex;
1188 };
1189
1190 auto ComputeExplicitObjectSizeArgument =
1191 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1192 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1193 if (!IndexOptional)
1194 return std::nullopt;
1195 unsigned NewIndex = *IndexOptional;
1196 Expr::EvalResult Result;
1197 Expr *SizeArg = TheCall->getArg(NewIndex);
1198 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1199 return std::nullopt;
1200 llvm::APSInt Integer = Result.Val.getInt();
1201 Integer.setIsUnsigned(true);
1202 return Integer;
1203 };
1204
1205 auto ComputeSizeArgument =
1206 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1207 // If the parameter has a pass_object_size attribute, then we should use its
1208 // (potentially) more strict checking mode. Otherwise, conservatively assume
1209 // type 0.
1210 int BOSType = 0;
1211 // This check can fail for variadic functions.
1212 if (Index < FD->getNumParams()) {
1213 if (const auto *POS =
1214 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1215 BOSType = POS->getType();
1216 }
1217
1218 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1219 if (!IndexOptional)
1220 return std::nullopt;
1221 unsigned NewIndex = *IndexOptional;
1222
1223 if (NewIndex >= TheCall->getNumArgs())
1224 return std::nullopt;
1225
1226 const Expr *ObjArg = TheCall->getArg(NewIndex);
1227 if (std::optional<uint64_t> ObjSize =
1228 ObjArg->tryEvaluateObjectSize(getASTContext(), BOSType)) {
1229 // Get the object size in the target's size_t width.
1230 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1231 }
1232 return std::nullopt;
1233 };
1234
1235 auto ComputeStrLenArgument =
1236 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1237 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1238 if (!IndexOptional)
1239 return std::nullopt;
1240 unsigned NewIndex = *IndexOptional;
1241
1242 const Expr *ObjArg = TheCall->getArg(NewIndex);
1243
1244 if (std::optional<uint64_t> Result =
1245 ObjArg->tryEvaluateStrLen(getASTContext())) {
1246 // Add 1 for null byte.
1247 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1248 }
1249 return std::nullopt;
1250 };
1251
1252 std::optional<llvm::APSInt> SourceSize;
1253 std::optional<llvm::APSInt> DestinationSize;
1254 unsigned DiagID = 0;
1255 bool IsChkVariant = false;
1256
1257 auto GetFunctionName = [&]() {
1258 std::string FunctionNameStr =
1259 getASTContext().BuiltinInfo.getName(BuiltinID);
1260 llvm::StringRef FunctionName = FunctionNameStr;
1261 // Skim off the details of whichever builtin was called to produce a better
1262 // diagnostic, as it's unlikely that the user wrote the __builtin
1263 // explicitly.
1264 if (IsChkVariant) {
1265 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1266 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1267 } else {
1268 FunctionName.consume_front("__builtin_");
1269 }
1270 return FunctionName.str();
1271 };
1272
1273 switch (BuiltinID) {
1274 default:
1275 return;
1276 case Builtin::BI__builtin_strcat:
1277 case Builtin::BIstrcat:
1278 case Builtin::BI__builtin_stpcpy:
1279 case Builtin::BIstpcpy:
1280 case Builtin::BI__builtin_strcpy:
1281 case Builtin::BIstrcpy: {
1282 DiagID = diag::warn_fortify_strlen_overflow;
1283 SourceSize = ComputeStrLenArgument(1);
1284 DestinationSize = ComputeSizeArgument(0);
1285 break;
1286 }
1287
1288 case Builtin::BI__builtin___strcat_chk:
1289 case Builtin::BI__builtin___stpcpy_chk:
1290 case Builtin::BI__builtin___strcpy_chk: {
1291 DiagID = diag::warn_fortify_strlen_overflow;
1292 SourceSize = ComputeStrLenArgument(1);
1293 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1294 IsChkVariant = true;
1295 break;
1296 }
1297
1298 case Builtin::BIscanf:
1299 case Builtin::BIfscanf:
1300 case Builtin::BIsscanf: {
1301 unsigned FormatIndex = 1;
1302 unsigned DataIndex = 2;
1303 if (BuiltinID == Builtin::BIscanf) {
1304 FormatIndex = 0;
1305 DataIndex = 1;
1306 }
1307
1308 const auto *FormatExpr =
1309 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1310
1311 StringRef FormatStrRef;
1312 size_t StrLen;
1313 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1314 return;
1315
1316 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1317 unsigned SourceSize) {
1318 DiagID = diag::warn_fortify_scanf_overflow;
1319 unsigned Index = ArgIndex + DataIndex;
1320 std::string FunctionName = GetFunctionName();
1321 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1322 PDiag(DiagID) << FunctionName << (Index + 1)
1323 << DestSize << SourceSize);
1324 };
1325
1326 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1327 return ComputeSizeArgument(Index + DataIndex);
1328 };
1329 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1330 const char *FormatBytes = FormatStrRef.data();
1332 FormatBytes + StrLen, getLangOpts(),
1333 Context.getTargetInfo());
1334
1335 // Unlike the other cases, in this one we have already issued the diagnostic
1336 // here, so no need to continue (because unlike the other cases, here the
1337 // diagnostic refers to the argument number).
1338 return;
1339 }
1340
1341 case Builtin::BIsprintf:
1342 case Builtin::BI__builtin___sprintf_chk: {
1343 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1344 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1345
1346 StringRef FormatStrRef;
1347 size_t StrLen;
1348 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1349 EstimateSizeFormatHandler H(FormatStrRef);
1350 const char *FormatBytes = FormatStrRef.data();
1352 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1353 Context.getTargetInfo(), false)) {
1354 DiagID = H.isKernelCompatible()
1355 ? diag::warn_format_overflow
1356 : diag::warn_format_overflow_non_kprintf;
1357 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1358 .extOrTrunc(SizeTypeWidth);
1359 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1360 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1361 IsChkVariant = true;
1362 } else {
1363 DestinationSize = ComputeSizeArgument(0);
1364 }
1365 break;
1366 }
1367 }
1368 return;
1369 }
1370 case Builtin::BI__builtin___memcpy_chk:
1371 case Builtin::BI__builtin___memmove_chk:
1372 case Builtin::BI__builtin___memset_chk:
1373 case Builtin::BI__builtin___strlcat_chk:
1374 case Builtin::BI__builtin___strlcpy_chk:
1375 case Builtin::BI__builtin___strncat_chk:
1376 case Builtin::BI__builtin___strncpy_chk:
1377 case Builtin::BI__builtin___stpncpy_chk:
1378 case Builtin::BI__builtin___memccpy_chk:
1379 case Builtin::BI__builtin___mempcpy_chk: {
1380 DiagID = diag::warn_builtin_chk_overflow;
1381 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1382 DestinationSize =
1383 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1384 IsChkVariant = true;
1385 break;
1386 }
1387
1388 case Builtin::BI__builtin___snprintf_chk:
1389 case Builtin::BI__builtin___vsnprintf_chk: {
1390 DiagID = diag::warn_builtin_chk_overflow;
1391 SourceSize = ComputeExplicitObjectSizeArgument(1);
1392 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1393 IsChkVariant = true;
1394 break;
1395 }
1396
1397 case Builtin::BIstrncat:
1398 case Builtin::BI__builtin_strncat:
1399 case Builtin::BIstrncpy:
1400 case Builtin::BI__builtin_strncpy:
1401 case Builtin::BIstpncpy:
1402 case Builtin::BI__builtin_stpncpy: {
1403 // Whether these functions overflow depends on the runtime strlen of the
1404 // string, not just the buffer size, so emitting the "always overflow"
1405 // diagnostic isn't quite right. We should still diagnose passing a buffer
1406 // size larger than the destination buffer though; this is a runtime abort
1407 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1408 DiagID = diag::warn_fortify_source_size_mismatch;
1409 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1410 DestinationSize = ComputeSizeArgument(0);
1411 break;
1412 }
1413
1414 case Builtin::BIbzero:
1415 case Builtin::BI__builtin_bzero:
1416 case Builtin::BImemcpy:
1417 case Builtin::BI__builtin_memcpy:
1418 case Builtin::BImemmove:
1419 case Builtin::BI__builtin_memmove:
1420 case Builtin::BImemset:
1421 case Builtin::BI__builtin_memset:
1422 case Builtin::BImempcpy:
1423 case Builtin::BI__builtin_mempcpy: {
1424 DiagID = diag::warn_fortify_source_overflow;
1425 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1426 DestinationSize = ComputeSizeArgument(0);
1427 break;
1428 }
1429 case Builtin::BIbcopy:
1430 case Builtin::BI__builtin_bcopy: {
1431 DiagID = diag::warn_fortify_source_overflow;
1432 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1433 DestinationSize = ComputeSizeArgument(1);
1434 break;
1435 }
1436 case Builtin::BIsnprintf:
1437 case Builtin::BI__builtin_snprintf:
1438 case Builtin::BIvsnprintf:
1439 case Builtin::BI__builtin_vsnprintf: {
1440 DiagID = diag::warn_fortify_source_size_mismatch;
1441 SourceSize = ComputeExplicitObjectSizeArgument(1);
1442 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1443 StringRef FormatStrRef;
1444 size_t StrLen;
1445 if (SourceSize &&
1446 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1447 EstimateSizeFormatHandler H(FormatStrRef);
1448 const char *FormatBytes = FormatStrRef.data();
1450 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1451 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1452 llvm::APSInt FormatSize =
1453 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1454 .extOrTrunc(SizeTypeWidth);
1455 if (FormatSize > *SourceSize && *SourceSize != 0) {
1456 unsigned TruncationDiagID =
1457 H.isKernelCompatible() ? diag::warn_format_truncation
1458 : diag::warn_format_truncation_non_kprintf;
1459 SmallString<16> SpecifiedSizeStr;
1460 SmallString<16> FormatSizeStr;
1461 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1462 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1463 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1464 PDiag(TruncationDiagID)
1465 << GetFunctionName() << SpecifiedSizeStr
1466 << FormatSizeStr);
1467 }
1468 }
1469 }
1470 DestinationSize = ComputeSizeArgument(0);
1471 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1472 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1473 IdentifierInfo *FnInfo = FD->getIdentifier();
1474 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1475 }
1476 }
1477
1478 if (!SourceSize || !DestinationSize ||
1479 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1480 return;
1481
1482 std::string FunctionName = GetFunctionName();
1483
1484 SmallString<16> DestinationStr;
1485 SmallString<16> SourceStr;
1486 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1487 SourceSize->toString(SourceStr, /*Radix=*/10);
1488 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1489 PDiag(DiagID)
1490 << FunctionName << DestinationStr << SourceStr);
1491}
1492
1493static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1494 Scope::ScopeFlags NeededScopeFlags,
1495 unsigned DiagID) {
1496 // Scopes aren't available during instantiation. Fortunately, builtin
1497 // functions cannot be template args so they cannot be formed through template
1498 // instantiation. Therefore checking once during the parse is sufficient.
1499 if (SemaRef.inTemplateInstantiation())
1500 return false;
1501
1502 Scope *S = SemaRef.getCurScope();
1503 while (S && !S->isSEHExceptScope())
1504 S = S->getParent();
1505 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1506 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1507 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1508 << DRE->getDecl()->getIdentifier();
1509 return true;
1510 }
1511
1512 return false;
1513}
1514
1515// In OpenCL, __builtin_alloca_* should return a pointer to address space
1516// that corresponds to the stack address space i.e private address space.
1517static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1518 QualType RT = TheCall->getType();
1519 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1520 "__builtin_alloca has invalid address space");
1521
1522 RT = RT->getPointeeType();
1524 TheCall->setType(S.Context.getPointerType(RT));
1525}
1526
1527static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1528 if (S.checkArgCountAtLeast(TheCall, 1))
1529 return true;
1530
1531 for (Expr *Arg : TheCall->arguments()) {
1532 // If argument is dependent on a template parameter, we can't resolve now.
1533 if (Arg->isTypeDependent() || Arg->isValueDependent())
1534 continue;
1535 // Reject void types.
1536 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1537 if (ArgTy->isVoidType())
1538 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1539 }
1540
1541 TheCall->setType(S.Context.getSizeType());
1542 return false;
1543}
1544
1545namespace {
1546enum PointerAuthOpKind {
1547 PAO_Strip,
1548 PAO_Sign,
1549 PAO_Auth,
1550 PAO_SignGeneric,
1551 PAO_Discriminator,
1552 PAO_BlendPointer,
1553 PAO_BlendInteger
1554};
1555}
1556
1558 if (getLangOpts().PointerAuthIntrinsics)
1559 return false;
1560
1561 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1562 return true;
1563}
1564
1565static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1567}
1568
1569static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1570 // Convert it to type 'int'.
1571 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1572 return true;
1573
1574 // Value-dependent expressions are okay; wait for template instantiation.
1575 if (Arg->isValueDependent())
1576 return false;
1577
1578 unsigned KeyValue;
1579 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1580}
1581
1583 // Attempt to constant-evaluate the expression.
1584 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1585 if (!KeyValue) {
1586 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1587 << 0 << Arg->getSourceRange();
1588 return true;
1589 }
1590
1591 // Ask the target to validate the key parameter.
1592 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1594 {
1595 llvm::raw_svector_ostream Str(Value);
1596 Str << *KeyValue;
1597 }
1598
1599 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1600 << Value << Arg->getSourceRange();
1601 return true;
1602 }
1603
1604 Result = KeyValue->getZExtValue();
1605 return false;
1606}
1607
1610 unsigned &IntVal) {
1611 if (!Arg) {
1612 IntVal = 0;
1613 return true;
1614 }
1615
1616 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1617 if (!Result) {
1618 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1619 return false;
1620 }
1621
1622 unsigned Max;
1623 bool IsAddrDiscArg = false;
1624
1625 switch (Kind) {
1627 Max = 1;
1628 IsAddrDiscArg = true;
1629 break;
1632 break;
1633 };
1634
1636 if (IsAddrDiscArg)
1637 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1638 << Result->getExtValue();
1639 else
1640 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1641 << Result->getExtValue() << Max;
1642
1643 return false;
1644 };
1645
1646 IntVal = Result->getZExtValue();
1647 return true;
1648}
1649
1650static std::pair<const ValueDecl *, CharUnits>
1652 // Must evaluate as a pointer.
1654 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1655 return {nullptr, CharUnits()};
1656
1657 const auto *BaseDecl =
1658 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1659 if (!BaseDecl)
1660 return {nullptr, CharUnits()};
1661
1662 return {BaseDecl, Result.Val.getLValueOffset()};
1663}
1664
1665static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1666 bool RequireConstant = false) {
1667 if (Arg->hasPlaceholderType()) {
1669 if (R.isInvalid())
1670 return true;
1671 Arg = R.get();
1672 }
1673
1674 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1675 return OpKind != PAO_BlendInteger;
1676 };
1677 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1678 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1679 OpKind == PAO_SignGeneric;
1680 };
1681
1682 // Require the value to have the right range of type.
1683 QualType ExpectedTy;
1684 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1685 ExpectedTy = Arg->getType().getUnqualifiedType();
1686 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1687 ExpectedTy = S.Context.VoidPtrTy;
1688 } else if (AllowsInteger(OpKind) &&
1690 ExpectedTy = S.Context.getUIntPtrType();
1691
1692 } else {
1693 // Diagnose the failures.
1694 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1695 << unsigned(OpKind == PAO_Discriminator ? 1
1696 : OpKind == PAO_BlendPointer ? 2
1697 : OpKind == PAO_BlendInteger ? 3
1698 : 0)
1699 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1700 << Arg->getType() << Arg->getSourceRange();
1701 return true;
1702 }
1703
1704 // Convert to that type. This should just be an lvalue-to-rvalue
1705 // conversion.
1706 if (convertArgumentToType(S, Arg, ExpectedTy))
1707 return true;
1708
1709 if (!RequireConstant) {
1710 // Warn about null pointers for non-generic sign and auth operations.
1711 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1713 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1714 ? diag::warn_ptrauth_sign_null_pointer
1715 : diag::warn_ptrauth_auth_null_pointer)
1716 << Arg->getSourceRange();
1717 }
1718
1719 return false;
1720 }
1721
1722 // Perform special checking on the arguments to ptrauth_sign_constant.
1723
1724 // The main argument.
1725 if (OpKind == PAO_Sign) {
1726 // Require the value we're signing to have a special form.
1727 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1728 bool Invalid;
1729
1730 // Must be rooted in a declaration reference.
1731 if (!BaseDecl)
1732 Invalid = true;
1733
1734 // If it's a function declaration, we can't have an offset.
1735 else if (isa<FunctionDecl>(BaseDecl))
1736 Invalid = !Offset.isZero();
1737
1738 // Otherwise we're fine.
1739 else
1740 Invalid = false;
1741
1742 if (Invalid)
1743 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1744 return Invalid;
1745 }
1746
1747 // The discriminator argument.
1748 assert(OpKind == PAO_Discriminator);
1749
1750 // Must be a pointer or integer or blend thereof.
1751 Expr *Pointer = nullptr;
1752 Expr *Integer = nullptr;
1753 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1754 if (Call->getBuiltinCallee() ==
1755 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1756 Pointer = Call->getArg(0);
1757 Integer = Call->getArg(1);
1758 }
1759 }
1760 if (!Pointer && !Integer) {
1761 if (Arg->getType()->isPointerType())
1762 Pointer = Arg;
1763 else
1764 Integer = Arg;
1765 }
1766
1767 // Check the pointer.
1768 bool Invalid = false;
1769 if (Pointer) {
1770 assert(Pointer->getType()->isPointerType());
1771
1772 // TODO: if we're initializing a global, check that the address is
1773 // somehow related to what we're initializing. This probably will
1774 // never really be feasible and we'll have to catch it at link-time.
1775 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1776 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1777 Invalid = true;
1778 }
1779
1780 // Check the integer.
1781 if (Integer) {
1782 assert(Integer->getType()->isIntegerType());
1783 if (!Integer->isEvaluatable(S.Context))
1784 Invalid = true;
1785 }
1786
1787 if (Invalid)
1788 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1789 return Invalid;
1790}
1791
1793 if (S.checkArgCount(Call, 2))
1794 return ExprError();
1796 return ExprError();
1797 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1798 checkPointerAuthKey(S, Call->getArgs()[1]))
1799 return ExprError();
1800
1801 Call->setType(Call->getArgs()[0]->getType());
1802 return Call;
1803}
1804
1806 if (S.checkArgCount(Call, 2))
1807 return ExprError();
1809 return ExprError();
1810 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1811 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1812 return ExprError();
1813
1814 Call->setType(S.Context.getUIntPtrType());
1815 return Call;
1816}
1817
1819 if (S.checkArgCount(Call, 2))
1820 return ExprError();
1822 return ExprError();
1823 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1824 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1825 return ExprError();
1826
1827 Call->setType(S.Context.getUIntPtrType());
1828 return Call;
1829}
1830
1832 PointerAuthOpKind OpKind,
1833 bool RequireConstant) {
1834 if (S.checkArgCount(Call, 3))
1835 return ExprError();
1837 return ExprError();
1838 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1839 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1840 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1841 RequireConstant))
1842 return ExprError();
1843
1844 Call->setType(Call->getArgs()[0]->getType());
1845 return Call;
1846}
1847
1849 if (S.checkArgCount(Call, 5))
1850 return ExprError();
1852 return ExprError();
1853 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1854 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1855 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1856 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1857 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1858 return ExprError();
1859
1860 Call->setType(Call->getArgs()[0]->getType());
1861 return Call;
1862}
1863
1865 if (S.checkArgCount(Call, 6))
1866 return ExprError();
1868 return ExprError();
1869 const Expr *AddendExpr = Call->getArg(5);
1870 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
1871 if (!AddendIsConstInt) {
1872 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
1873 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
1874 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1875 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
1876 << FDecl->getDeclName() << Arg->getSourceRange();
1877 }
1878 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1879 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1880 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1881 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1882 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
1883 !AddendIsConstInt)
1884 return ExprError();
1885
1886 Call->setType(Call->getArgs()[0]->getType());
1887 return Call;
1888}
1889
1892 return ExprError();
1893
1894 // We've already performed normal call type-checking.
1895 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1896
1897 // Operand must be an ordinary or UTF-8 string literal.
1898 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1899 if (!Literal || Literal->getCharByteWidth() != 1) {
1900 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1901 << (Literal ? 1 : 0) << Arg->getSourceRange();
1902 return ExprError();
1903 }
1904
1905 return Call;
1906}
1907
1909 if (S.checkArgCount(Call, 1))
1910 return ExprError();
1911 Expr *FirstArg = Call->getArg(0);
1912 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1913 if (FirstValue.isInvalid())
1914 return ExprError();
1915 Call->setArg(0, FirstValue.get());
1916 QualType FirstArgType = FirstArg->getType();
1917 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1918 FirstArgType = S.Context.getDecayedType(FirstArgType);
1919
1920 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1921 if (!FirstArgRecord) {
1922 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1923 << /*isPolymorphic=*/0 << FirstArgType;
1924 return ExprError();
1925 }
1926 if (S.RequireCompleteType(
1927 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1928 diag::err_get_vtable_pointer_requires_complete_type)) {
1929 return ExprError();
1930 }
1931
1932 if (!FirstArgRecord->isPolymorphic()) {
1933 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1934 << /*isPolymorphic=*/1 << FirstArgRecord;
1935 return ExprError();
1936 }
1938 Call->setType(ReturnType);
1939 return Call;
1940}
1941
1943 if (S.checkArgCount(TheCall, 1))
1944 return ExprError();
1945
1946 // Compute __builtin_launder's parameter type from the argument.
1947 // The parameter type is:
1948 // * The type of the argument if it's not an array or function type,
1949 // Otherwise,
1950 // * The decayed argument type.
1951 QualType ParamTy = [&]() {
1952 QualType ArgTy = TheCall->getArg(0)->getType();
1953 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1954 return S.Context.getPointerType(Ty->getElementType());
1955 if (ArgTy->isFunctionType()) {
1956 return S.Context.getPointerType(ArgTy);
1957 }
1958 return ArgTy;
1959 }();
1960
1961 TheCall->setType(ParamTy);
1962
1963 auto DiagSelect = [&]() -> std::optional<unsigned> {
1964 if (!ParamTy->isPointerType())
1965 return 0;
1966 if (ParamTy->isFunctionPointerType())
1967 return 1;
1968 if (ParamTy->isVoidPointerType())
1969 return 2;
1970 return std::optional<unsigned>{};
1971 }();
1972 if (DiagSelect) {
1973 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1974 << *DiagSelect << TheCall->getSourceRange();
1975 return ExprError();
1976 }
1977
1978 // We either have an incomplete class type, or we have a class template
1979 // whose instantiation has not been forced. Example:
1980 //
1981 // template <class T> struct Foo { T value; };
1982 // Foo<int> *p = nullptr;
1983 // auto *d = __builtin_launder(p);
1984 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1985 diag::err_incomplete_type))
1986 return ExprError();
1987
1988 assert(ParamTy->getPointeeType()->isObjectType() &&
1989 "Unhandled non-object pointer case");
1990
1991 InitializedEntity Entity =
1993 ExprResult Arg =
1994 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1995 if (Arg.isInvalid())
1996 return ExprError();
1997 TheCall->setArg(0, Arg.get());
1998
1999 return TheCall;
2000}
2001
2003 if (S.checkArgCount(TheCall, 1))
2004 return ExprError();
2005
2007 if (Arg.isInvalid())
2008 return ExprError();
2009 QualType ParamTy = Arg.get()->getType();
2010 TheCall->setArg(0, Arg.get());
2011 TheCall->setType(S.Context.BoolTy);
2012
2013 // Only accept pointers to objects as arguments, which should have object
2014 // pointer or void pointer types.
2015 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2016 // LWG4138: Function pointer types not allowed
2017 if (PT->getPointeeType()->isFunctionType()) {
2018 S.Diag(TheCall->getArg(0)->getExprLoc(),
2019 diag::err_builtin_is_within_lifetime_invalid_arg)
2020 << 1;
2021 return ExprError();
2022 }
2023 // Disallow VLAs too since those shouldn't be able to
2024 // be a template parameter for `std::is_within_lifetime`
2025 if (PT->getPointeeType()->isVariableArrayType()) {
2026 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2027 << 1 << "__builtin_is_within_lifetime";
2028 return ExprError();
2029 }
2030 } else {
2031 S.Diag(TheCall->getArg(0)->getExprLoc(),
2032 diag::err_builtin_is_within_lifetime_invalid_arg)
2033 << 0;
2034 return ExprError();
2035 }
2036 return TheCall;
2037}
2038
2040 if (S.checkArgCount(TheCall, 3))
2041 return ExprError();
2042
2043 QualType Dest = TheCall->getArg(0)->getType();
2044 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2045 S.Diag(TheCall->getArg(0)->getExprLoc(),
2046 diag::err_builtin_trivially_relocate_invalid_arg_type)
2047 << /*a pointer*/ 0;
2048 return ExprError();
2049 }
2050
2051 QualType T = Dest->getPointeeType();
2052 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2053 diag::err_incomplete_type))
2054 return ExprError();
2055
2056 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2057 T->isIncompleteArrayType()) {
2058 S.Diag(TheCall->getArg(0)->getExprLoc(),
2059 diag::err_builtin_trivially_relocate_invalid_arg_type)
2060 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2061 return ExprError();
2062 }
2063
2064 TheCall->setType(Dest);
2065
2066 QualType Src = TheCall->getArg(1)->getType();
2067 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2068 S.Diag(TheCall->getArg(1)->getExprLoc(),
2069 diag::err_builtin_trivially_relocate_invalid_arg_type)
2070 << /*the same*/ 3;
2071 return ExprError();
2072 }
2073
2074 Expr *SizeExpr = TheCall->getArg(2);
2075 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2076 if (Size.isInvalid())
2077 return ExprError();
2078
2079 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2080 if (Size.isInvalid())
2081 return ExprError();
2082 SizeExpr = Size.get();
2083 TheCall->setArg(2, SizeExpr);
2084
2085 return TheCall;
2086}
2087
2088// Emit an error and return true if the current object format type is in the
2089// list of unsupported types.
2091 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2092 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2093 llvm::Triple::ObjectFormatType CurObjFormat =
2094 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2095 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2096 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2097 << TheCall->getSourceRange();
2098 return true;
2099 }
2100 return false;
2101}
2102
2103// Emit an error and return true if the current architecture is not in the list
2104// of supported architectures.
2105static bool
2107 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2108 llvm::Triple::ArchType CurArch =
2109 S.getASTContext().getTargetInfo().getTriple().getArch();
2110 if (llvm::is_contained(SupportedArchs, CurArch))
2111 return false;
2112 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2113 << TheCall->getSourceRange();
2114 return true;
2115}
2116
2117static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2118 SourceLocation CallSiteLoc);
2119
2120bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2121 CallExpr *TheCall) {
2122 switch (TI.getTriple().getArch()) {
2123 default:
2124 // Some builtins don't require additional checking, so just consider these
2125 // acceptable.
2126 return false;
2127 case llvm::Triple::arm:
2128 case llvm::Triple::armeb:
2129 case llvm::Triple::thumb:
2130 case llvm::Triple::thumbeb:
2131 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2132 case llvm::Triple::aarch64:
2133 case llvm::Triple::aarch64_32:
2134 case llvm::Triple::aarch64_be:
2135 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2136 case llvm::Triple::bpfeb:
2137 case llvm::Triple::bpfel:
2138 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2139 case llvm::Triple::dxil:
2140 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2141 case llvm::Triple::hexagon:
2142 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2143 case llvm::Triple::mips:
2144 case llvm::Triple::mipsel:
2145 case llvm::Triple::mips64:
2146 case llvm::Triple::mips64el:
2147 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2148 case llvm::Triple::spirv:
2149 case llvm::Triple::spirv32:
2150 case llvm::Triple::spirv64:
2151 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2152 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2153 return false;
2154 case llvm::Triple::systemz:
2155 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2156 case llvm::Triple::x86:
2157 case llvm::Triple::x86_64:
2158 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2159 case llvm::Triple::ppc:
2160 case llvm::Triple::ppcle:
2161 case llvm::Triple::ppc64:
2162 case llvm::Triple::ppc64le:
2163 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2164 case llvm::Triple::amdgcn:
2165 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2166 case llvm::Triple::riscv32:
2167 case llvm::Triple::riscv64:
2168 case llvm::Triple::riscv32be:
2169 case llvm::Triple::riscv64be:
2170 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2171 case llvm::Triple::loongarch32:
2172 case llvm::Triple::loongarch64:
2173 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2174 TheCall);
2175 case llvm::Triple::wasm32:
2176 case llvm::Triple::wasm64:
2177 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2178 case llvm::Triple::nvptx:
2179 case llvm::Triple::nvptx64:
2180 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2181 }
2182}
2183
2185 return T->isDependentType() ||
2186 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2187}
2188
2189// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2190// not a valid type, emit an error message and return true. Otherwise return
2191// false.
2192static bool
2195 int ArgOrdinal) {
2196 clang::QualType EltTy =
2197 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2198 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2199 : ArgTy;
2200
2201 switch (ArgTyRestr) {
2203 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2204 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2205 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2206 << ArgTy;
2207 }
2208 break;
2210 if (!EltTy->isRealFloatingType()) {
2211 // FIXME: make diagnostic's wording correct for matrices
2212 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2213 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2214 << /* floating-point */ 1 << ArgTy;
2215 }
2216 break;
2218 if (!EltTy->isIntegerType()) {
2219 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2220 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2221 << /* no fp */ 0 << ArgTy;
2222 }
2223 break;
2225 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2226 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2227 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2228 << /* or fp */ 1 << ArgTy;
2229 }
2230 break;
2231 }
2232
2233 return false;
2234}
2235
2236/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2237/// This checks that the target supports the builtin and that the string
2238/// argument is constant and valid.
2239static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2240 const TargetInfo *AuxTI, unsigned BuiltinID) {
2241 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2242 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2243 "Expecting __builtin_cpu_...");
2244
2245 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2246 const TargetInfo *TheTI = &TI;
2247 auto SupportsBI = [=](const TargetInfo *TInfo) {
2248 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2249 (!IsCPUSupports && TInfo->supportsCpuIs()));
2250 };
2251 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2252 TheTI = AuxTI;
2253
2254 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2255 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2256 return S.Diag(TheCall->getBeginLoc(),
2257 TI.getTriple().isOSAIX()
2258 ? diag::err_builtin_aix_os_unsupported
2259 : diag::err_builtin_target_unsupported)
2260 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2261
2262 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2263 // Check if the argument is a string literal.
2264 if (!isa<StringLiteral>(Arg))
2265 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2266 << Arg->getSourceRange();
2267
2268 // Check the contents of the string.
2269 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2270 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2271 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2272 << Arg->getSourceRange();
2273 return false;
2274 }
2275 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2276 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2277 << Arg->getSourceRange();
2278 return false;
2279}
2280
2281/// Checks that __builtin_bswapg was called with a single argument, which is an
2282/// unsigned integer, and overrides the return value type to the integer type.
2283static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2284 if (S.checkArgCount(TheCall, 1))
2285 return true;
2286 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2287 if (ArgRes.isInvalid())
2288 return true;
2289
2290 Expr *Arg = ArgRes.get();
2291 TheCall->setArg(0, Arg);
2292 if (Arg->isTypeDependent())
2293 return false;
2294
2295 QualType ArgTy = Arg->getType();
2296
2297 if (!ArgTy->isIntegerType()) {
2298 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2299 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2300 << ArgTy;
2301 return true;
2302 }
2303 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2304 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2305 BT->getNumBits() != 1) {
2306 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2307 << ArgTy << BT->getNumBits();
2308 return true;
2309 }
2310 }
2311 TheCall->setType(ArgTy);
2312 return false;
2313}
2314
2315/// Checks that __builtin_bitreverseg was called with a single argument, which
2316/// is an integer
2317static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2318 if (S.checkArgCount(TheCall, 1))
2319 return true;
2320 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2321 if (ArgRes.isInvalid())
2322 return true;
2323
2324 Expr *Arg = ArgRes.get();
2325 TheCall->setArg(0, Arg);
2326 if (Arg->isTypeDependent())
2327 return false;
2328
2329 QualType ArgTy = Arg->getType();
2330
2331 if (!ArgTy->isIntegerType()) {
2332 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2333 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2334 << ArgTy;
2335 return true;
2336 }
2337 TheCall->setType(ArgTy);
2338 return false;
2339}
2340
2341/// Checks that __builtin_popcountg was called with a single argument, which is
2342/// an unsigned integer.
2343static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2344 if (S.checkArgCount(TheCall, 1))
2345 return true;
2346
2347 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2348 if (ArgRes.isInvalid())
2349 return true;
2350
2351 Expr *Arg = ArgRes.get();
2352 TheCall->setArg(0, Arg);
2353
2354 QualType ArgTy = Arg->getType();
2355
2356 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2357 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2358 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2359 << ArgTy;
2360 return true;
2361 }
2362 return false;
2363}
2364
2365/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2366/// argument and return either int, bool, or the argument type.
2367static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2368 QualType ReturnType) {
2369 if (S.checkArgCount(TheCall, 1))
2370 return true;
2371
2372 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2373 if (ArgRes.isInvalid())
2374 return true;
2375
2376 Expr *Arg = ArgRes.get();
2377 TheCall->setArg(0, Arg);
2378
2379 QualType ArgTy = Arg->getType();
2380 // C23 stdbit.h functions do not permit bool or enumeration types.
2381 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2382 return S.Diag(Arg->getBeginLoc(),
2383 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2384 << 1 /*1st argument*/ << ArgTy;
2385 if (!ArgTy->isUnsignedIntegerType())
2386 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2387 << 1 /*1st argument*/ << ArgTy;
2388
2389 // For builtins returning unsigned int, verify the argument's bit width fits.
2390 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2391 // produce a count that overflows the return type.
2392 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2393 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2394 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2395 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2396 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2397 << ArgTy;
2398 }
2399
2400 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2401 return false;
2402}
2403
2404/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2405/// an unsigned integer, and an optional second argument, which is promoted to
2406/// an 'int'.
2407static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2408 if (S.checkArgCountRange(TheCall, 1, 2))
2409 return true;
2410
2411 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2412 if (Arg0Res.isInvalid())
2413 return true;
2414
2415 Expr *Arg0 = Arg0Res.get();
2416 TheCall->setArg(0, Arg0);
2417
2418 QualType Arg0Ty = Arg0->getType();
2419
2420 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2421 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2422 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2423 << Arg0Ty;
2424 return true;
2425 }
2426
2427 if (TheCall->getNumArgs() > 1) {
2428 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2429 if (Arg1Res.isInvalid())
2430 return true;
2431
2432 Expr *Arg1 = Arg1Res.get();
2433 TheCall->setArg(1, Arg1);
2434
2435 QualType Arg1Ty = Arg1->getType();
2436
2437 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2438 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2439 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2440 return true;
2441 }
2442 }
2443
2444 return false;
2445}
2446
2448 unsigned ArgIndex;
2449 bool OnlyUnsigned;
2450
2452 QualType T) {
2453 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2454 << ArgIndex << /*scalar*/ 1
2455 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2456 << /*no fp*/ 0 << T;
2457 }
2458
2459public:
2460 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2461 : ContextualImplicitConverter(/*Suppress=*/false,
2462 /*SuppressConversion=*/true),
2463 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2464
2465 bool match(QualType T) override {
2466 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2467 }
2468
2470 QualType T) override {
2471 return emitError(S, Loc, T);
2472 }
2473
2475 QualType T) override {
2476 return emitError(S, Loc, T);
2477 }
2478
2480 QualType T,
2481 QualType ConvTy) override {
2482 return emitError(S, Loc, T);
2483 }
2484
2486 QualType ConvTy) override {
2487 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2488 }
2489
2491 QualType T) override {
2492 return emitError(S, Loc, T);
2493 }
2494
2496 QualType ConvTy) override {
2497 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2498 }
2499
2501 QualType T,
2502 QualType ConvTy) override {
2503 llvm_unreachable("conversion functions are permitted");
2504 }
2505};
2506
2507/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2508/// arguments, that the first argument is an unsigned integer type, and that
2509/// the second argument is an integer type.
2510static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2511 if (S.checkArgCount(TheCall, 2))
2512 return true;
2513
2514 // First argument (value to rotate) must be unsigned integer type.
2515 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2517 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2518 if (Arg0Res.isInvalid())
2519 return true;
2520
2521 Expr *Arg0 = Arg0Res.get();
2522 TheCall->setArg(0, Arg0);
2523
2524 QualType Arg0Ty = Arg0->getType();
2525 if (!Arg0Ty->isUnsignedIntegerType())
2526 return true;
2527
2528 // Second argument (rotation count) must be integer type.
2529 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2531 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2532 if (Arg1Res.isInvalid())
2533 return true;
2534
2535 Expr *Arg1 = Arg1Res.get();
2536 TheCall->setArg(1, Arg1);
2537
2538 QualType Arg1Ty = Arg1->getType();
2539 if (!Arg1Ty->isIntegerType())
2540 return true;
2541
2542 TheCall->setType(Arg0Ty);
2543 return false;
2544}
2545
2546static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2547 unsigned Pos, bool AllowConst,
2548 bool AllowAS) {
2549 QualType MaskTy = MaskArg->getType();
2550 if (!MaskTy->isExtVectorBoolType())
2551 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2552 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2553 << MaskTy;
2554
2555 QualType PtrTy = PtrArg->getType();
2556 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2557 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2558 << Pos << "scalar pointer";
2559
2560 QualType PointeeTy = PtrTy->getPointeeType();
2561 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2562 (!AllowConst && PointeeTy.isConstQualified()) ||
2563 (!AllowAS && PointeeTy.hasAddressSpace())) {
2566 return S.Diag(PtrArg->getExprLoc(),
2567 diag::err_typecheck_convert_incompatible)
2568 << PtrTy << Target << /*different qualifiers=*/5
2569 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2570 << PtrTy << Target;
2571 }
2572 return false;
2573}
2574
2575static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2576 bool TypeDependent = false;
2577 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2578 ExprResult Converted =
2580 if (Converted.isInvalid())
2581 return true;
2582 TheCall->setArg(Arg, Converted.get());
2583 TypeDependent |= Converted.get()->isTypeDependent();
2584 }
2585
2586 if (TypeDependent)
2587 TheCall->setType(S.Context.DependentTy);
2588 return false;
2589}
2590
2592 if (S.checkArgCountRange(TheCall, 2, 3))
2593 return ExprError();
2594
2595 if (ConvertMaskedBuiltinArgs(S, TheCall))
2596 return ExprError();
2597
2598 Expr *MaskArg = TheCall->getArg(0);
2599 Expr *PtrArg = TheCall->getArg(1);
2600 if (TheCall->isTypeDependent())
2601 return TheCall;
2602
2603 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2604 TheCall->getBuiltinCallee() ==
2605 Builtin::BI__builtin_masked_load))
2606 return ExprError();
2607
2608 QualType MaskTy = MaskArg->getType();
2609 QualType PtrTy = PtrArg->getType();
2610 QualType PointeeTy = PtrTy->getPointeeType();
2611 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2612
2614 MaskVecTy->getNumElements());
2615 if (TheCall->getNumArgs() == 3) {
2616 Expr *PassThruArg = TheCall->getArg(2);
2617 QualType PassThruTy = PassThruArg->getType();
2618 if (!S.Context.hasSameType(PassThruTy, RetTy))
2619 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2620 << /* third argument */ 3 << RetTy;
2621 }
2622
2623 TheCall->setType(RetTy);
2624 return TheCall;
2625}
2626
2628 if (S.checkArgCount(TheCall, 3))
2629 return ExprError();
2630
2631 if (ConvertMaskedBuiltinArgs(S, TheCall))
2632 return ExprError();
2633
2634 Expr *MaskArg = TheCall->getArg(0);
2635 Expr *ValArg = TheCall->getArg(1);
2636 Expr *PtrArg = TheCall->getArg(2);
2637 if (TheCall->isTypeDependent())
2638 return TheCall;
2639
2640 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2641 TheCall->getBuiltinCallee() ==
2642 Builtin::BI__builtin_masked_store))
2643 return ExprError();
2644
2645 QualType MaskTy = MaskArg->getType();
2646 QualType PtrTy = PtrArg->getType();
2647 QualType ValTy = ValArg->getType();
2648 if (!ValTy->isVectorType())
2649 return ExprError(
2650 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2651 << 2 << "vector");
2652
2653 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2654 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2655
2656 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2657 return ExprError(
2658 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2660 TheCall->getBuiltinCallee())
2661 << MaskTy << ValTy);
2662 }
2663
2664 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2665 PtrTy->getPointeeType().getUnqualifiedType()))
2666 return ExprError(S.Diag(TheCall->getBeginLoc(),
2667 diag::err_vec_builtin_incompatible_vector)
2668 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2669 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2670 TheCall->getArg(1)->getEndLoc()));
2671
2672 TheCall->setType(S.Context.VoidTy);
2673 return TheCall;
2674}
2675
2677 if (S.checkArgCountRange(TheCall, 3, 4))
2678 return ExprError();
2679
2680 if (ConvertMaskedBuiltinArgs(S, TheCall))
2681 return ExprError();
2682
2683 Expr *MaskArg = TheCall->getArg(0);
2684 Expr *IdxArg = TheCall->getArg(1);
2685 Expr *PtrArg = TheCall->getArg(2);
2686 if (TheCall->isTypeDependent())
2687 return TheCall;
2688
2689 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2690 /*AllowAS=*/true))
2691 return ExprError();
2692
2693 QualType IdxTy = IdxArg->getType();
2694 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2695 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2696 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2697 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2698 << IdxTy;
2699
2700 QualType MaskTy = MaskArg->getType();
2701 QualType PtrTy = PtrArg->getType();
2702 QualType PointeeTy = PtrTy->getPointeeType();
2703 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2704 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2705 return ExprError(
2706 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2708 TheCall->getBuiltinCallee())
2709 << MaskTy << IdxTy);
2710
2712 MaskVecTy->getNumElements());
2713 if (TheCall->getNumArgs() == 4) {
2714 Expr *PassThruArg = TheCall->getArg(3);
2715 QualType PassThruTy = PassThruArg->getType();
2716 if (!S.Context.hasSameType(PassThruTy, RetTy))
2717 return S.Diag(PassThruArg->getExprLoc(),
2718 diag::err_vec_masked_load_store_ptr)
2719 << /* fourth argument */ 4 << RetTy;
2720 }
2721
2722 TheCall->setType(RetTy);
2723 return TheCall;
2724}
2725
2727 if (S.checkArgCount(TheCall, 4))
2728 return ExprError();
2729
2730 if (ConvertMaskedBuiltinArgs(S, TheCall))
2731 return ExprError();
2732
2733 Expr *MaskArg = TheCall->getArg(0);
2734 Expr *IdxArg = TheCall->getArg(1);
2735 Expr *ValArg = TheCall->getArg(2);
2736 Expr *PtrArg = TheCall->getArg(3);
2737 if (TheCall->isTypeDependent())
2738 return TheCall;
2739
2740 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2741 /*AllowAS=*/true))
2742 return ExprError();
2743
2744 QualType IdxTy = IdxArg->getType();
2745 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2746 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2747 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2748 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2749 << IdxTy;
2750
2751 QualType ValTy = ValArg->getType();
2752 QualType MaskTy = MaskArg->getType();
2753 QualType PtrTy = PtrArg->getType();
2754
2755 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2756 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2757 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2758 return ExprError(
2759 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2761 TheCall->getBuiltinCallee())
2762 << MaskTy << IdxTy);
2763 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2764 return ExprError(
2765 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2767 TheCall->getBuiltinCallee())
2768 << MaskTy << ValTy);
2769
2770 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2771 PtrTy->getPointeeType().getUnqualifiedType()))
2772 return ExprError(S.Diag(TheCall->getBeginLoc(),
2773 diag::err_vec_builtin_incompatible_vector)
2774 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2775 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2776 TheCall->getArg(1)->getEndLoc()));
2777
2778 TheCall->setType(S.Context.VoidTy);
2779 return TheCall;
2780}
2781
2783 SourceLocation Loc = TheCall->getBeginLoc();
2784 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2785 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2786
2787 if (Args.size() == 0) {
2788 S.Diag(TheCall->getBeginLoc(),
2789 diag::err_typecheck_call_too_few_args_at_least)
2790 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2791 << /*is_non_object=*/0 << TheCall->getSourceRange();
2792 return ExprError();
2793 }
2794
2795 QualType FuncT = Args[0]->getType();
2796
2797 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2798 if (Args.size() < 2) {
2799 S.Diag(TheCall->getBeginLoc(),
2800 diag::err_typecheck_call_too_few_args_at_least)
2801 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2802 << /*is_non_object=*/0 << TheCall->getSourceRange();
2803 return ExprError();
2804 }
2805
2806 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2807 QualType ObjectT = Args[1]->getType();
2808
2809 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2810 return ExprError();
2811
2812 ExprResult ObjectArg = [&]() -> ExprResult {
2813 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2814 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2815 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2816 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2817 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2818 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2819 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2820 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2821 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2822 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2823 return Args[1];
2824 }
2825
2826 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2827 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2828 // reference_wrapper;
2829 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2830 if (RD->isInStdNamespace() &&
2831 RD->getDeclName().getAsString() == "reference_wrapper") {
2832 CXXScopeSpec SS;
2833 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2834 UnqualifiedId GetID;
2835 GetID.setIdentifier(GetName, Loc);
2836
2838 S.getCurScope(), Args[1], Loc, tok::period, SS,
2839 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2840
2841 if (MemExpr.isInvalid())
2842 return ExprError();
2843
2844 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2845 }
2846 }
2847
2848 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2849 // class T and t1 does not satisfy the previous two items;
2850
2851 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2852 }();
2853
2854 if (ObjectArg.isInvalid())
2855 return ExprError();
2856
2857 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2858 tok::periodstar, ObjectArg.get(), Args[0]);
2859 if (BinOp.isInvalid())
2860 return ExprError();
2861
2862 if (MPT->isMemberDataPointer())
2863 return BinOp;
2864
2865 auto *MemCall = new (S.Context)
2867
2868 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2869 Args.drop_front(2), TheCall->getRParenLoc());
2870 }
2871 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2872 Args.drop_front(), TheCall->getRParenLoc());
2873}
2874
2875// Performs a similar job to Sema::UsualUnaryConversions, but without any
2876// implicit promotion of integral/enumeration types.
2878 // First, convert to an r-value.
2880 if (Res.isInvalid())
2881 return ExprError();
2882
2883 // Promote floating-point types.
2884 return S.UsualUnaryFPConversions(Res.get());
2885}
2886
2888 if (const auto *TyA = VecTy->getAs<VectorType>())
2889 return TyA->getElementType();
2890 if (VecTy->isSizelessVectorType())
2891 return VecTy->getSizelessVectorEltType(Context);
2892 return QualType();
2893}
2894
2896Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2897 CallExpr *TheCall) {
2898 ExprResult TheCallResult(TheCall);
2899
2900 // Find out if any arguments are required to be integer constant expressions.
2901 unsigned ICEArguments = 0;
2903 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2905 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2906
2907 // If any arguments are required to be ICE's, check and diagnose.
2908 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2909 // Skip arguments not required to be ICE's.
2910 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2911
2912 llvm::APSInt Result;
2913 // If we don't have enough arguments, continue so we can issue better
2914 // diagnostic in checkArgCount(...)
2915 if (ArgNo < TheCall->getNumArgs() &&
2916 BuiltinConstantArg(TheCall, ArgNo, Result))
2917 return true;
2918 ICEArguments &= ~(1 << ArgNo);
2919 }
2920
2921 FPOptions FPO;
2922 switch (BuiltinID) {
2923 case Builtin::BI__builtin_cpu_supports:
2924 case Builtin::BI__builtin_cpu_is:
2925 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2926 Context.getAuxTargetInfo(), BuiltinID))
2927 return ExprError();
2928 break;
2929 case Builtin::BI__builtin_cpu_init:
2930 if (!Context.getTargetInfo().supportsCpuInit()) {
2931 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2932 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2933 return ExprError();
2934 }
2935 break;
2936 case Builtin::BI__builtin___CFStringMakeConstantString:
2937 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2938 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2940 *this, BuiltinID, TheCall,
2941 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2942 return ExprError();
2943 assert(TheCall->getNumArgs() == 1 &&
2944 "Wrong # arguments to builtin CFStringMakeConstantString");
2945 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2946 return ExprError();
2947 break;
2948 case Builtin::BI__builtin_ms_va_start:
2949 case Builtin::BI__builtin_stdarg_start:
2950 case Builtin::BI__builtin_va_start:
2951 case Builtin::BI__builtin_c23_va_start:
2952 if (BuiltinVAStart(BuiltinID, TheCall))
2953 return ExprError();
2954 break;
2955 case Builtin::BI__va_start: {
2956 switch (Context.getTargetInfo().getTriple().getArch()) {
2957 case llvm::Triple::aarch64:
2958 case llvm::Triple::arm:
2959 case llvm::Triple::thumb:
2960 if (BuiltinVAStartARMMicrosoft(TheCall))
2961 return ExprError();
2962 break;
2963 default:
2964 if (BuiltinVAStart(BuiltinID, TheCall))
2965 return ExprError();
2966 break;
2967 }
2968 break;
2969 }
2970
2971 // The acquire, release, and no fence variants are ARM and AArch64 only.
2972 case Builtin::BI_interlockedbittestandset_acq:
2973 case Builtin::BI_interlockedbittestandset_rel:
2974 case Builtin::BI_interlockedbittestandset_nf:
2975 case Builtin::BI_interlockedbittestandreset_acq:
2976 case Builtin::BI_interlockedbittestandreset_rel:
2977 case Builtin::BI_interlockedbittestandreset_nf:
2979 *this, TheCall,
2980 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2981 return ExprError();
2982 break;
2983
2984 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2985 case Builtin::BI_bittest64:
2986 case Builtin::BI_bittestandcomplement64:
2987 case Builtin::BI_bittestandreset64:
2988 case Builtin::BI_bittestandset64:
2989 case Builtin::BI_interlockedbittestandreset64:
2990 case Builtin::BI_interlockedbittestandset64:
2992 *this, TheCall,
2993 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2994 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2995 return ExprError();
2996 break;
2997
2998 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2999 case Builtin::BI_interlockedbittestandreset64_acq:
3000 case Builtin::BI_interlockedbittestandreset64_rel:
3001 case Builtin::BI_interlockedbittestandreset64_nf:
3002 case Builtin::BI_interlockedbittestandset64_acq:
3003 case Builtin::BI_interlockedbittestandset64_rel:
3004 case Builtin::BI_interlockedbittestandset64_nf:
3005 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3006 return ExprError();
3007 break;
3008
3009 case Builtin::BI__builtin_set_flt_rounds:
3011 *this, TheCall,
3012 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3013 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
3014 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3015 llvm::Triple::ppc64le}))
3016 return ExprError();
3017 break;
3018
3019 case Builtin::BI__builtin_isgreater:
3020 case Builtin::BI__builtin_isgreaterequal:
3021 case Builtin::BI__builtin_isless:
3022 case Builtin::BI__builtin_islessequal:
3023 case Builtin::BI__builtin_islessgreater:
3024 case Builtin::BI__builtin_isunordered:
3025 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3026 return ExprError();
3027 break;
3028 case Builtin::BI__builtin_fpclassify:
3029 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3030 return ExprError();
3031 break;
3032 case Builtin::BI__builtin_isfpclass:
3033 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3034 return ExprError();
3035 break;
3036 case Builtin::BI__builtin_isfinite:
3037 case Builtin::BI__builtin_isinf:
3038 case Builtin::BI__builtin_isinf_sign:
3039 case Builtin::BI__builtin_isnan:
3040 case Builtin::BI__builtin_issignaling:
3041 case Builtin::BI__builtin_isnormal:
3042 case Builtin::BI__builtin_issubnormal:
3043 case Builtin::BI__builtin_iszero:
3044 case Builtin::BI__builtin_signbit:
3045 case Builtin::BI__builtin_signbitf:
3046 case Builtin::BI__builtin_signbitl:
3047 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3048 return ExprError();
3049 break;
3050 case Builtin::BI__builtin_shufflevector:
3051 return BuiltinShuffleVector(TheCall);
3052 // TheCall will be freed by the smart pointer here, but that's fine, since
3053 // BuiltinShuffleVector guts it, but then doesn't release it.
3054 case Builtin::BI__builtin_masked_load:
3055 case Builtin::BI__builtin_masked_expand_load:
3056 return BuiltinMaskedLoad(*this, TheCall);
3057 case Builtin::BI__builtin_masked_store:
3058 case Builtin::BI__builtin_masked_compress_store:
3059 return BuiltinMaskedStore(*this, TheCall);
3060 case Builtin::BI__builtin_masked_gather:
3061 return BuiltinMaskedGather(*this, TheCall);
3062 case Builtin::BI__builtin_masked_scatter:
3063 return BuiltinMaskedScatter(*this, TheCall);
3064 case Builtin::BI__builtin_invoke:
3065 return BuiltinInvoke(*this, TheCall);
3066 case Builtin::BI__builtin_prefetch:
3067 if (BuiltinPrefetch(TheCall))
3068 return ExprError();
3069 break;
3070 case Builtin::BI__builtin_alloca_with_align:
3071 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3072 if (BuiltinAllocaWithAlign(TheCall))
3073 return ExprError();
3074 [[fallthrough]];
3075 case Builtin::BI__builtin_alloca:
3076 case Builtin::BI__builtin_alloca_uninitialized:
3077 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3078 << TheCall->getDirectCallee();
3079 if (getLangOpts().OpenCL) {
3080 builtinAllocaAddrSpace(*this, TheCall);
3081 }
3082 break;
3083 case Builtin::BI__builtin_infer_alloc_token:
3084 if (checkBuiltinInferAllocToken(*this, TheCall))
3085 return ExprError();
3086 break;
3087 case Builtin::BI__arithmetic_fence:
3088 if (BuiltinArithmeticFence(TheCall))
3089 return ExprError();
3090 break;
3091 case Builtin::BI__assume:
3092 case Builtin::BI__builtin_assume:
3093 if (BuiltinAssume(TheCall))
3094 return ExprError();
3095 break;
3096 case Builtin::BI__builtin_assume_aligned:
3097 if (BuiltinAssumeAligned(TheCall))
3098 return ExprError();
3099 break;
3100 case Builtin::BI__builtin_dynamic_object_size:
3101 case Builtin::BI__builtin_object_size:
3102 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3103 return ExprError();
3104 break;
3105 case Builtin::BI__builtin_longjmp:
3106 if (BuiltinLongjmp(TheCall))
3107 return ExprError();
3108 break;
3109 case Builtin::BI__builtin_setjmp:
3110 if (BuiltinSetjmp(TheCall))
3111 return ExprError();
3112 break;
3113 case Builtin::BI__builtin_complex:
3114 if (BuiltinComplex(TheCall))
3115 return ExprError();
3116 break;
3117 case Builtin::BI__builtin_classify_type:
3118 case Builtin::BI__builtin_constant_p: {
3119 if (checkArgCount(TheCall, 1))
3120 return true;
3122 if (Arg.isInvalid()) return true;
3123 TheCall->setArg(0, Arg.get());
3124 TheCall->setType(Context.IntTy);
3125 break;
3126 }
3127 case Builtin::BI__builtin_launder:
3128 return BuiltinLaunder(*this, TheCall);
3129 case Builtin::BI__builtin_is_within_lifetime:
3130 return BuiltinIsWithinLifetime(*this, TheCall);
3131 case Builtin::BI__builtin_trivially_relocate:
3132 return BuiltinTriviallyRelocate(*this, TheCall);
3133 case Builtin::BI__builtin_clear_padding: {
3134 if (checkArgCount(TheCall, 1))
3135 return ExprError();
3136
3137 const Expr *PtrArg = TheCall->getArg(0);
3138 const QualType PtrArgType = PtrArg->getType();
3139 if (!PtrArgType->isPointerType()) {
3140 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3141 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3142 << "pointer";
3143 return ExprError();
3144 }
3145 QualType PointeeType = PtrArgType->getPointeeType();
3146 if (PointeeType.isConstQualified()) {
3147 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3148 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3149 return ExprError();
3150 }
3151 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3152 diag::err_typecheck_decl_incomplete_type))
3153 return ExprError();
3154
3155 // For non trivially copyable types, we try to match gcc's behaviour.
3156 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3157 // object, either a local variable or a function parameter passed by value
3158 auto IsAddrOfDeclExpr = [&]() {
3159 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3160 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3161 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3162 return false;
3163
3164 const Expr *Operand =
3165 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3166 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3167 if (!DeclRef)
3168 return false;
3169
3170 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3171 if (!VarDecl || VarDecl->getType()->isReferenceType())
3172 return false;
3173
3174 // matching GCC behaviour
3175 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3176 QualType VarQType = VarDecl->getType();
3177 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3178 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3179 };
3180
3181 if (!PointeeType.isTriviallyCopyableType(Context) &&
3182 !PointeeType->isAtomicType() // _Atomic is not copyable
3183 && !IsAddrOfDeclExpr()) {
3184 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3185 << PtrArg->getType() << PtrArg->getSourceRange();
3186 return ExprError();
3187 }
3188
3189 if (auto *Record = PointeeType->getAsRecordDecl();
3191 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3192 << PointeeType << PtrArg->getSourceRange();
3193 return ExprError();
3194 }
3195
3196 break;
3197 }
3198 case Builtin::BI__sync_fetch_and_add:
3199 case Builtin::BI__sync_fetch_and_add_1:
3200 case Builtin::BI__sync_fetch_and_add_2:
3201 case Builtin::BI__sync_fetch_and_add_4:
3202 case Builtin::BI__sync_fetch_and_add_8:
3203 case Builtin::BI__sync_fetch_and_add_16:
3204 case Builtin::BI__sync_fetch_and_sub:
3205 case Builtin::BI__sync_fetch_and_sub_1:
3206 case Builtin::BI__sync_fetch_and_sub_2:
3207 case Builtin::BI__sync_fetch_and_sub_4:
3208 case Builtin::BI__sync_fetch_and_sub_8:
3209 case Builtin::BI__sync_fetch_and_sub_16:
3210 case Builtin::BI__sync_fetch_and_or:
3211 case Builtin::BI__sync_fetch_and_or_1:
3212 case Builtin::BI__sync_fetch_and_or_2:
3213 case Builtin::BI__sync_fetch_and_or_4:
3214 case Builtin::BI__sync_fetch_and_or_8:
3215 case Builtin::BI__sync_fetch_and_or_16:
3216 case Builtin::BI__sync_fetch_and_and:
3217 case Builtin::BI__sync_fetch_and_and_1:
3218 case Builtin::BI__sync_fetch_and_and_2:
3219 case Builtin::BI__sync_fetch_and_and_4:
3220 case Builtin::BI__sync_fetch_and_and_8:
3221 case Builtin::BI__sync_fetch_and_and_16:
3222 case Builtin::BI__sync_fetch_and_xor:
3223 case Builtin::BI__sync_fetch_and_xor_1:
3224 case Builtin::BI__sync_fetch_and_xor_2:
3225 case Builtin::BI__sync_fetch_and_xor_4:
3226 case Builtin::BI__sync_fetch_and_xor_8:
3227 case Builtin::BI__sync_fetch_and_xor_16:
3228 case Builtin::BI__sync_fetch_and_nand:
3229 case Builtin::BI__sync_fetch_and_nand_1:
3230 case Builtin::BI__sync_fetch_and_nand_2:
3231 case Builtin::BI__sync_fetch_and_nand_4:
3232 case Builtin::BI__sync_fetch_and_nand_8:
3233 case Builtin::BI__sync_fetch_and_nand_16:
3234 case Builtin::BI__sync_add_and_fetch:
3235 case Builtin::BI__sync_add_and_fetch_1:
3236 case Builtin::BI__sync_add_and_fetch_2:
3237 case Builtin::BI__sync_add_and_fetch_4:
3238 case Builtin::BI__sync_add_and_fetch_8:
3239 case Builtin::BI__sync_add_and_fetch_16:
3240 case Builtin::BI__sync_sub_and_fetch:
3241 case Builtin::BI__sync_sub_and_fetch_1:
3242 case Builtin::BI__sync_sub_and_fetch_2:
3243 case Builtin::BI__sync_sub_and_fetch_4:
3244 case Builtin::BI__sync_sub_and_fetch_8:
3245 case Builtin::BI__sync_sub_and_fetch_16:
3246 case Builtin::BI__sync_and_and_fetch:
3247 case Builtin::BI__sync_and_and_fetch_1:
3248 case Builtin::BI__sync_and_and_fetch_2:
3249 case Builtin::BI__sync_and_and_fetch_4:
3250 case Builtin::BI__sync_and_and_fetch_8:
3251 case Builtin::BI__sync_and_and_fetch_16:
3252 case Builtin::BI__sync_or_and_fetch:
3253 case Builtin::BI__sync_or_and_fetch_1:
3254 case Builtin::BI__sync_or_and_fetch_2:
3255 case Builtin::BI__sync_or_and_fetch_4:
3256 case Builtin::BI__sync_or_and_fetch_8:
3257 case Builtin::BI__sync_or_and_fetch_16:
3258 case Builtin::BI__sync_xor_and_fetch:
3259 case Builtin::BI__sync_xor_and_fetch_1:
3260 case Builtin::BI__sync_xor_and_fetch_2:
3261 case Builtin::BI__sync_xor_and_fetch_4:
3262 case Builtin::BI__sync_xor_and_fetch_8:
3263 case Builtin::BI__sync_xor_and_fetch_16:
3264 case Builtin::BI__sync_nand_and_fetch:
3265 case Builtin::BI__sync_nand_and_fetch_1:
3266 case Builtin::BI__sync_nand_and_fetch_2:
3267 case Builtin::BI__sync_nand_and_fetch_4:
3268 case Builtin::BI__sync_nand_and_fetch_8:
3269 case Builtin::BI__sync_nand_and_fetch_16:
3270 case Builtin::BI__sync_val_compare_and_swap:
3271 case Builtin::BI__sync_val_compare_and_swap_1:
3272 case Builtin::BI__sync_val_compare_and_swap_2:
3273 case Builtin::BI__sync_val_compare_and_swap_4:
3274 case Builtin::BI__sync_val_compare_and_swap_8:
3275 case Builtin::BI__sync_val_compare_and_swap_16:
3276 case Builtin::BI__sync_bool_compare_and_swap:
3277 case Builtin::BI__sync_bool_compare_and_swap_1:
3278 case Builtin::BI__sync_bool_compare_and_swap_2:
3279 case Builtin::BI__sync_bool_compare_and_swap_4:
3280 case Builtin::BI__sync_bool_compare_and_swap_8:
3281 case Builtin::BI__sync_bool_compare_and_swap_16:
3282 case Builtin::BI__sync_lock_test_and_set:
3283 case Builtin::BI__sync_lock_test_and_set_1:
3284 case Builtin::BI__sync_lock_test_and_set_2:
3285 case Builtin::BI__sync_lock_test_and_set_4:
3286 case Builtin::BI__sync_lock_test_and_set_8:
3287 case Builtin::BI__sync_lock_test_and_set_16:
3288 case Builtin::BI__sync_lock_release:
3289 case Builtin::BI__sync_lock_release_1:
3290 case Builtin::BI__sync_lock_release_2:
3291 case Builtin::BI__sync_lock_release_4:
3292 case Builtin::BI__sync_lock_release_8:
3293 case Builtin::BI__sync_lock_release_16:
3294 case Builtin::BI__sync_swap:
3295 case Builtin::BI__sync_swap_1:
3296 case Builtin::BI__sync_swap_2:
3297 case Builtin::BI__sync_swap_4:
3298 case Builtin::BI__sync_swap_8:
3299 case Builtin::BI__sync_swap_16:
3300 return BuiltinAtomicOverloaded(TheCallResult);
3301 case Builtin::BI__sync_synchronize:
3302 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3303 << TheCall->getCallee()->getSourceRange();
3304 break;
3305 case Builtin::BI__builtin_nontemporal_load:
3306 case Builtin::BI__builtin_nontemporal_store:
3307 return BuiltinNontemporalOverloaded(TheCallResult);
3308 case Builtin::BI__builtin_memcpy_inline: {
3309 clang::Expr *SizeOp = TheCall->getArg(2);
3310 // We warn about copying to or from `nullptr` pointers when `size` is
3311 // greater than 0. When `size` is value dependent we cannot evaluate its
3312 // value so we bail out.
3313 if (SizeOp->isValueDependent())
3314 break;
3315 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3316 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3317 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3318 }
3319 break;
3320 }
3321 case Builtin::BI__builtin_memset_inline: {
3322 clang::Expr *SizeOp = TheCall->getArg(2);
3323 // We warn about filling to `nullptr` pointers when `size` is greater than
3324 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3325 // out.
3326 if (SizeOp->isValueDependent())
3327 break;
3328 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3329 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3330 break;
3331 }
3332#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3333 case Builtin::BI##ID: \
3334 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3335#include "clang/Basic/Builtins.inc"
3336 case Builtin::BI__annotation: {
3337 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3338 if (!TT.isOSWindows() && !TT.isUEFI()) {
3339 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3340 << TheCall->getSourceRange();
3341 return ExprError();
3342 }
3343 if (BuiltinMSVCAnnotation(*this, TheCall))
3344 return ExprError();
3345 break;
3346 }
3347 case Builtin::BI__builtin_annotation:
3348 if (BuiltinAnnotation(*this, TheCall))
3349 return ExprError();
3350 break;
3351 case Builtin::BI__builtin_addressof:
3352 if (BuiltinAddressof(*this, TheCall))
3353 return ExprError();
3354 break;
3355 case Builtin::BI__builtin_function_start:
3356 if (BuiltinFunctionStart(*this, TheCall))
3357 return ExprError();
3358 break;
3359 case Builtin::BI__builtin_is_aligned:
3360 case Builtin::BI__builtin_align_up:
3361 case Builtin::BI__builtin_align_down:
3362 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3363 return ExprError();
3364 break;
3365 case Builtin::BI__builtin_add_overflow:
3366 case Builtin::BI__builtin_sub_overflow:
3367 case Builtin::BI__builtin_mul_overflow:
3368 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3369 return ExprError();
3370 break;
3371 case Builtin::BI__builtin_operator_new:
3372 case Builtin::BI__builtin_operator_delete: {
3373 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3374 ExprResult Res =
3375 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3376 return Res;
3377 }
3378 case Builtin::BI__builtin_dump_struct:
3379 return BuiltinDumpStruct(*this, TheCall);
3380 case Builtin::BI__builtin_expect_with_probability: {
3381 // We first want to ensure we are called with 3 arguments
3382 if (checkArgCount(TheCall, 3))
3383 return ExprError();
3384 // then check probability is constant float in range [0.0, 1.0]
3385 const Expr *ProbArg = TheCall->getArg(2);
3386 SmallVector<PartialDiagnosticAt, 8> Notes;
3387 Expr::EvalResult Eval;
3388 Eval.Diag = &Notes;
3389 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3390 !Eval.Val.isFloat()) {
3391 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3392 << ProbArg->getSourceRange();
3393 for (const PartialDiagnosticAt &PDiag : Notes)
3394 Diag(PDiag.first, PDiag.second);
3395 return ExprError();
3396 }
3397 llvm::APFloat Probability = Eval.Val.getFloat();
3398 bool LoseInfo = false;
3399 Probability.convert(llvm::APFloat::IEEEdouble(),
3400 llvm::RoundingMode::Dynamic, &LoseInfo);
3401 if (!(Probability >= llvm::APFloat(0.0) &&
3402 Probability <= llvm::APFloat(1.0))) {
3403 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3404 << ProbArg->getSourceRange();
3405 return ExprError();
3406 }
3407 break;
3408 }
3409 case Builtin::BI__builtin_preserve_access_index:
3410 if (BuiltinPreserveAI(*this, TheCall))
3411 return ExprError();
3412 break;
3413 case Builtin::BI__builtin_call_with_static_chain:
3414 if (BuiltinCallWithStaticChain(*this, TheCall))
3415 return ExprError();
3416 break;
3417 case Builtin::BI__exception_code:
3418 case Builtin::BI_exception_code:
3419 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3420 diag::err_seh___except_block))
3421 return ExprError();
3422 break;
3423 case Builtin::BI__exception_info:
3424 case Builtin::BI_exception_info:
3425 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3426 diag::err_seh___except_filter))
3427 return ExprError();
3428 break;
3429 case Builtin::BI__GetExceptionInfo:
3430 if (checkArgCount(TheCall, 1))
3431 return ExprError();
3432
3434 TheCall->getBeginLoc(),
3435 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3436 TheCall))
3437 return ExprError();
3438
3439 TheCall->setType(Context.VoidPtrTy);
3440 break;
3441 case Builtin::BIaddressof:
3442 case Builtin::BI__addressof:
3443 case Builtin::BIforward:
3444 case Builtin::BIforward_like:
3445 case Builtin::BImove:
3446 case Builtin::BImove_if_noexcept:
3447 case Builtin::BIas_const: {
3448 // These are all expected to be of the form
3449 // T &/&&/* f(U &/&&)
3450 // where T and U only differ in qualification.
3451 if (checkArgCount(TheCall, 1))
3452 return ExprError();
3453 QualType Param = FDecl->getParamDecl(0)->getType();
3454 QualType Result = FDecl->getReturnType();
3455 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3456 BuiltinID == Builtin::BI__addressof;
3457 if (!(Param->isReferenceType() &&
3458 (ReturnsPointer ? Result->isAnyPointerType()
3459 : Result->isReferenceType()) &&
3460 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3461 Result->getPointeeType()))) {
3462 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3463 << FDecl;
3464 return ExprError();
3465 }
3466 break;
3467 }
3468 case Builtin::BI__builtin_ptrauth_strip:
3469 return PointerAuthStrip(*this, TheCall);
3470 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3471 return PointerAuthBlendDiscriminator(*this, TheCall);
3472 case Builtin::BI__builtin_ptrauth_sign_constant:
3473 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3474 /*RequireConstant=*/true);
3475 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3476 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3477 /*RequireConstant=*/false);
3478 case Builtin::BI__builtin_ptrauth_auth:
3479 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3480 /*RequireConstant=*/false);
3481 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3482 return PointerAuthSignGenericData(*this, TheCall);
3483 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3484 return PointerAuthAuthAndResign(*this, TheCall);
3485 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3486 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3487 case Builtin::BI__builtin_ptrauth_string_discriminator:
3488 return PointerAuthStringDiscriminator(*this, TheCall);
3489
3490 case Builtin::BI__builtin_get_vtable_pointer:
3491 return GetVTablePointer(*this, TheCall);
3492
3493 // OpenCL v2.0, s6.13.16 - Pipe functions
3494 case Builtin::BIread_pipe:
3495 case Builtin::BIwrite_pipe:
3496 // Since those two functions are declared with var args, we need a semantic
3497 // check for the argument.
3498 if (OpenCL().checkBuiltinRWPipe(TheCall))
3499 return ExprError();
3500 break;
3501 case Builtin::BIreserve_read_pipe:
3502 case Builtin::BIreserve_write_pipe:
3503 case Builtin::BIwork_group_reserve_read_pipe:
3504 case Builtin::BIwork_group_reserve_write_pipe:
3505 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3506 return ExprError();
3507 break;
3508 case Builtin::BIsub_group_reserve_read_pipe:
3509 case Builtin::BIsub_group_reserve_write_pipe:
3510 if (OpenCL().checkSubgroupExt(TheCall) ||
3511 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3512 return ExprError();
3513 break;
3514 case Builtin::BIcommit_read_pipe:
3515 case Builtin::BIcommit_write_pipe:
3516 case Builtin::BIwork_group_commit_read_pipe:
3517 case Builtin::BIwork_group_commit_write_pipe:
3518 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3519 return ExprError();
3520 break;
3521 case Builtin::BIsub_group_commit_read_pipe:
3522 case Builtin::BIsub_group_commit_write_pipe:
3523 if (OpenCL().checkSubgroupExt(TheCall) ||
3524 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3525 return ExprError();
3526 break;
3527 case Builtin::BIget_pipe_num_packets:
3528 case Builtin::BIget_pipe_max_packets:
3529 if (OpenCL().checkBuiltinPipePackets(TheCall))
3530 return ExprError();
3531 break;
3532 case Builtin::BIto_global:
3533 case Builtin::BIto_local:
3534 case Builtin::BIto_private:
3535 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3536 return ExprError();
3537 break;
3538 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3539 case Builtin::BIenqueue_kernel:
3540 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3541 return ExprError();
3542 break;
3543 case Builtin::BIget_kernel_work_group_size:
3544 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3545 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3546 return ExprError();
3547 break;
3548 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3549 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3550 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3551 return ExprError();
3552 break;
3553 case Builtin::BI__builtin_os_log_format:
3554 Cleanup.setExprNeedsCleanups(true);
3555 [[fallthrough]];
3556 case Builtin::BI__builtin_os_log_format_buffer_size:
3557 if (BuiltinOSLogFormat(TheCall))
3558 return ExprError();
3559 break;
3560 case Builtin::BI__builtin_frame_address:
3561 case Builtin::BI__builtin_return_address: {
3562 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3563 return ExprError();
3564
3565 // -Wframe-address warning if non-zero passed to builtin
3566 // return/frame address.
3567 Expr::EvalResult Result;
3568 if (!TheCall->getArg(0)->isValueDependent() &&
3569 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3570 Result.Val.getInt() != 0)
3571 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3572 << ((BuiltinID == Builtin::BI__builtin_return_address)
3573 ? "__builtin_return_address"
3574 : "__builtin_frame_address")
3575 << TheCall->getSourceRange();
3576 break;
3577 }
3578
3579 case Builtin::BI__builtin_nondeterministic_value: {
3580 if (BuiltinNonDeterministicValue(TheCall))
3581 return ExprError();
3582 break;
3583 }
3584
3585 // __builtin_elementwise_abs restricts the element type to signed integers or
3586 // floating point types only.
3587 case Builtin::BI__builtin_elementwise_abs:
3590 return ExprError();
3591 break;
3592
3593 // These builtins restrict the element type to floating point
3594 // types only.
3595 case Builtin::BI__builtin_elementwise_acos:
3596 case Builtin::BI__builtin_elementwise_asin:
3597 case Builtin::BI__builtin_elementwise_atan:
3598 case Builtin::BI__builtin_elementwise_ceil:
3599 case Builtin::BI__builtin_elementwise_cos:
3600 case Builtin::BI__builtin_elementwise_cosh:
3601 case Builtin::BI__builtin_elementwise_exp:
3602 case Builtin::BI__builtin_elementwise_exp2:
3603 case Builtin::BI__builtin_elementwise_exp10:
3604 case Builtin::BI__builtin_elementwise_floor:
3605 case Builtin::BI__builtin_elementwise_log:
3606 case Builtin::BI__builtin_elementwise_log2:
3607 case Builtin::BI__builtin_elementwise_log10:
3608 case Builtin::BI__builtin_elementwise_roundeven:
3609 case Builtin::BI__builtin_elementwise_round:
3610 case Builtin::BI__builtin_elementwise_rint:
3611 case Builtin::BI__builtin_elementwise_nearbyint:
3612 case Builtin::BI__builtin_elementwise_sin:
3613 case Builtin::BI__builtin_elementwise_sinh:
3614 case Builtin::BI__builtin_elementwise_sqrt:
3615 case Builtin::BI__builtin_elementwise_tan:
3616 case Builtin::BI__builtin_elementwise_tanh:
3617 case Builtin::BI__builtin_elementwise_trunc:
3618 case Builtin::BI__builtin_elementwise_canonicalize:
3621 return ExprError();
3622 break;
3623 case Builtin::BI__builtin_elementwise_fma:
3624 if (BuiltinElementwiseTernaryMath(TheCall))
3625 return ExprError();
3626 break;
3627
3628 case Builtin::BI__builtin_elementwise_ldexp: {
3629 if (checkArgCount(TheCall, 2))
3630 return ExprError();
3631
3632 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3633 if (A.isInvalid())
3634 return ExprError();
3635 QualType TyA = A.get()->getType();
3636 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3638 return ExprError();
3639
3640 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3641 if (Exp.isInvalid())
3642 return ExprError();
3643 QualType TyExp = Exp.get()->getType();
3644 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3646 2))
3647 return ExprError();
3648
3649 // Check the two arguments are either scalars or vectors of equal length.
3650 const auto *Vec0 = TyA->getAs<VectorType>();
3651 const auto *Vec1 = TyExp->getAs<VectorType>();
3652 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3653 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3654 if (Arg0Length != Arg1Length) {
3655 Diag(Exp.get()->getBeginLoc(),
3656 diag::err_typecheck_vector_lengths_not_equal)
3657 << TyA << TyExp << A.get()->getSourceRange()
3658 << Exp.get()->getSourceRange();
3659 return ExprError();
3660 }
3661
3662 TheCall->setArg(0, A.get());
3663 TheCall->setArg(1, Exp.get());
3664 TheCall->setType(TyA);
3665 break;
3666 }
3667
3668 // These builtins restrict the element type to floating point
3669 // types only, and take in two arguments.
3670 case Builtin::BI__builtin_elementwise_minnum:
3671 case Builtin::BI__builtin_elementwise_maxnum:
3672 case Builtin::BI__builtin_elementwise_minimum:
3673 case Builtin::BI__builtin_elementwise_maximum:
3674 case Builtin::BI__builtin_elementwise_minimumnum:
3675 case Builtin::BI__builtin_elementwise_maximumnum:
3676 case Builtin::BI__builtin_elementwise_atan2:
3677 case Builtin::BI__builtin_elementwise_fmod:
3678 case Builtin::BI__builtin_elementwise_pow:
3679 if (BuiltinElementwiseMath(TheCall,
3681 return ExprError();
3682 break;
3683 // These builtins restrict the element type to integer
3684 // types only.
3685 case Builtin::BI__builtin_elementwise_add_sat:
3686 case Builtin::BI__builtin_elementwise_sub_sat:
3687 case Builtin::BI__builtin_elementwise_clmul:
3688 if (BuiltinElementwiseMath(TheCall,
3690 return ExprError();
3691 break;
3692 case Builtin::BI__builtin_elementwise_fshl:
3693 case Builtin::BI__builtin_elementwise_fshr:
3696 return ExprError();
3697 break;
3698 case Builtin::BI__builtin_elementwise_min:
3699 case Builtin::BI__builtin_elementwise_max: {
3700 if (BuiltinElementwiseMath(TheCall))
3701 return ExprError();
3702 Expr *Arg0 = TheCall->getArg(0);
3703 Expr *Arg1 = TheCall->getArg(1);
3704 QualType Ty0 = Arg0->getType();
3705 QualType Ty1 = Arg1->getType();
3706 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3707 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3708 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3709 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3710 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3711 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3712 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3713 break;
3714 }
3715 case Builtin::BI__builtin_elementwise_popcount:
3716 case Builtin::BI__builtin_elementwise_bitreverse:
3719 return ExprError();
3720 break;
3721 case Builtin::BI__builtin_elementwise_copysign: {
3722 if (checkArgCount(TheCall, 2))
3723 return ExprError();
3724
3725 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3726 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3727 if (Magnitude.isInvalid() || Sign.isInvalid())
3728 return ExprError();
3729
3730 QualType MagnitudeTy = Magnitude.get()->getType();
3731 QualType SignTy = Sign.get()->getType();
3733 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3736 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3738 return ExprError();
3739 }
3740
3741 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3742 return Diag(Sign.get()->getBeginLoc(),
3743 diag::err_typecheck_call_different_arg_types)
3744 << MagnitudeTy << SignTy;
3745 }
3746
3747 TheCall->setArg(0, Magnitude.get());
3748 TheCall->setArg(1, Sign.get());
3749 TheCall->setType(Magnitude.get()->getType());
3750 break;
3751 }
3752 case Builtin::BI__builtin_elementwise_clzg:
3753 case Builtin::BI__builtin_elementwise_ctzg:
3754 // These builtins can be unary or binary. Note for empty calls we call the
3755 // unary checker in order to not emit an error that says the function
3756 // expects 2 arguments, which would be misleading.
3757 if (TheCall->getNumArgs() <= 1) {
3760 return ExprError();
3761 } else if (BuiltinElementwiseMath(
3763 return ExprError();
3764 break;
3765 case Builtin::BI__builtin_reduce_max:
3766 case Builtin::BI__builtin_reduce_min: {
3767 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3768 return ExprError();
3769
3770 const Expr *Arg = TheCall->getArg(0);
3771 const auto *TyA = Arg->getType()->getAs<VectorType>();
3772
3773 QualType ElTy;
3774 if (TyA)
3775 ElTy = TyA->getElementType();
3776 else if (Arg->getType()->isSizelessVectorType())
3778
3779 if (ElTy.isNull()) {
3780 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3781 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3782 << Arg->getType();
3783 return ExprError();
3784 }
3785
3786 TheCall->setType(ElTy);
3787 break;
3788 }
3789 case Builtin::BI__builtin_reduce_maximum:
3790 case Builtin::BI__builtin_reduce_minimum: {
3791 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3792 return ExprError();
3793
3794 const Expr *Arg = TheCall->getArg(0);
3795 const auto *TyA = Arg->getType()->getAs<VectorType>();
3796
3797 QualType ElTy;
3798 if (TyA)
3799 ElTy = TyA->getElementType();
3800 else if (Arg->getType()->isSizelessVectorType())
3802
3803 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3804 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3805 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3806 << Arg->getType();
3807 return ExprError();
3808 }
3809
3810 TheCall->setType(ElTy);
3811 break;
3812 }
3813
3814 // These builtins support vectors of integers only.
3815 // TODO: ADD/MUL should support floating-point types.
3816 case Builtin::BI__builtin_reduce_add:
3817 case Builtin::BI__builtin_reduce_mul:
3818 case Builtin::BI__builtin_reduce_xor:
3819 case Builtin::BI__builtin_reduce_or:
3820 case Builtin::BI__builtin_reduce_and: {
3821 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3822 return ExprError();
3823
3824 const Expr *Arg = TheCall->getArg(0);
3825
3826 QualType ElTy = getVectorElementType(Context, Arg->getType());
3827 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3828 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3829 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3830 << Arg->getType();
3831 return ExprError();
3832 }
3833
3834 TheCall->setType(ElTy);
3835 break;
3836 }
3837
3838 case Builtin::BI__builtin_reduce_assoc_fadd:
3839 case Builtin::BI__builtin_reduce_in_order_fadd: {
3840 // For in-order reductions require the user to specify the start value.
3841 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3842 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
3843 return ExprError();
3844
3845 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
3846 if (Vec.isInvalid())
3847 return ExprError();
3848
3849 TheCall->setArg(0, Vec.get());
3850
3851 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
3852 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3853 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3854 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3855 << Vec.get()->getType();
3856 return ExprError();
3857 }
3858
3859 if (TheCall->getNumArgs() == 2) {
3860 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
3861 if (StartValue.isInvalid())
3862 return ExprError();
3863
3864 if (!StartValue.get()->getType()->isRealFloatingType()) {
3865 Diag(StartValue.get()->getBeginLoc(),
3866 diag::err_builtin_invalid_arg_type)
3867 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3868 << StartValue.get()->getType();
3869 return ExprError();
3870 }
3871 TheCall->setArg(1, StartValue.get());
3872 }
3873
3874 TheCall->setType(ElTy);
3875 break;
3876 }
3877
3878 case Builtin::BI__builtin_matrix_transpose:
3879 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3880
3881 case Builtin::BI__builtin_matrix_column_major_load:
3882 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3883
3884 case Builtin::BI__builtin_matrix_column_major_store:
3885 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3886
3887 case Builtin::BI__builtin_verbose_trap:
3888 if (!checkBuiltinVerboseTrap(TheCall, *this))
3889 return ExprError();
3890 break;
3891
3892 case Builtin::BI__builtin_get_device_side_mangled_name: {
3893 auto Check = [](CallExpr *TheCall) {
3894 if (TheCall->getNumArgs() != 1)
3895 return false;
3896 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3897 if (!DRE)
3898 return false;
3899 auto *D = DRE->getDecl();
3900 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3901 return false;
3902 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3903 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3904 };
3905 if (!Check(TheCall)) {
3906 Diag(TheCall->getBeginLoc(),
3907 diag::err_hip_invalid_args_builtin_mangled_name);
3908 return ExprError();
3909 }
3910 break;
3911 }
3912 case Builtin::BI__builtin_bswapg:
3913 if (BuiltinBswapg(*this, TheCall))
3914 return ExprError();
3915 break;
3916 case Builtin::BI__builtin_bitreverseg:
3917 if (BuiltinBitreverseg(*this, TheCall))
3918 return ExprError();
3919 break;
3920 case Builtin::BI__builtin_popcountg:
3921 if (BuiltinPopcountg(*this, TheCall))
3922 return ExprError();
3923 break;
3924 case Builtin::BI__builtin_clzg:
3925 case Builtin::BI__builtin_ctzg:
3926 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3927 return ExprError();
3928 break;
3929
3930 case Builtin::BI__builtin_stdc_rotate_left:
3931 case Builtin::BI__builtin_stdc_rotate_right:
3932 if (BuiltinRotateGeneric(*this, TheCall))
3933 return ExprError();
3934 break;
3935
3936 case Builtin::BI__builtin_stdc_bit_floor:
3937 case Builtin::BI__builtin_stdc_bit_ceil:
3938 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
3939 return ExprError();
3940 break;
3941 case Builtin::BI__builtin_stdc_has_single_bit:
3942 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
3943 return ExprError();
3944 break;
3945 case Builtin::BI__builtin_stdc_leading_zeros:
3946 case Builtin::BI__builtin_stdc_leading_ones:
3947 case Builtin::BI__builtin_stdc_trailing_zeros:
3948 case Builtin::BI__builtin_stdc_trailing_ones:
3949 case Builtin::BI__builtin_stdc_first_leading_zero:
3950 case Builtin::BI__builtin_stdc_first_leading_one:
3951 case Builtin::BI__builtin_stdc_first_trailing_zero:
3952 case Builtin::BI__builtin_stdc_first_trailing_one:
3953 case Builtin::BI__builtin_stdc_count_zeros:
3954 case Builtin::BI__builtin_stdc_count_ones:
3955 case Builtin::BI__builtin_stdc_bit_width:
3956 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
3957 return ExprError();
3958 break;
3959
3960 case Builtin::BI__builtin_allow_runtime_check: {
3961 Expr *Arg = TheCall->getArg(0);
3962 // Check if the argument is a string literal.
3964 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3965 << Arg->getSourceRange();
3966 return ExprError();
3967 }
3968 break;
3969 }
3970
3971 case Builtin::BI__builtin_allow_sanitize_check: {
3972 if (checkArgCount(TheCall, 1))
3973 return ExprError();
3974
3975 Expr *Arg = TheCall->getArg(0);
3976 // Check if the argument is a string literal.
3977 const StringLiteral *SanitizerName =
3978 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
3979 if (!SanitizerName) {
3980 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3981 << Arg->getSourceRange();
3982 return ExprError();
3983 }
3984 // Validate the sanitizer name.
3985 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3986 .Cases({"address", "thread", "memory", "hwaddress",
3987 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3988 true)
3989 .Default(false)) {
3990 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
3991 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3992 << Arg->getSourceRange();
3993 return ExprError();
3994 }
3995 break;
3996 }
3997 case Builtin::BI__builtin_counted_by_ref:
3998 if (BuiltinCountedByRef(TheCall))
3999 return ExprError();
4000 break;
4001 }
4002
4003 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4004 return ExprError();
4005
4006 // Since the target specific builtins for each arch overlap, only check those
4007 // of the arch we are compiling for.
4008 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4009 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4010 assert(Context.getAuxTargetInfo() &&
4011 "Aux Target Builtin, but not an aux target?");
4012
4013 if (CheckTSBuiltinFunctionCall(
4014 *Context.getAuxTargetInfo(),
4015 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4016 return ExprError();
4017 } else {
4018 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4019 TheCall))
4020 return ExprError();
4021 }
4022 }
4023
4024 return TheCallResult;
4025}
4026
4027bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4028 llvm::APSInt Result;
4029 // We can't check the value of a dependent argument.
4030 Expr *Arg = TheCall->getArg(ArgNum);
4031 if (Arg->isTypeDependent() || Arg->isValueDependent())
4032 return false;
4033
4034 // Check constant-ness first.
4035 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4036 return true;
4037
4038 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4039 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4040 return false;
4041
4042 return Diag(TheCall->getBeginLoc(),
4043 diag::err_argument_not_contiguous_bit_field)
4044 << ArgNum << Arg->getSourceRange();
4045}
4046
4047bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4048 unsigned FirstArg, FormatStringInfo *FSI) {
4049 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4050 bool IsVariadic = false;
4051 if (const FunctionType *FnTy = D->getFunctionType())
4052 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4053 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4054 IsVariadic = BD->isVariadic();
4055 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4056 IsVariadic = OMD->isVariadic();
4057
4058 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4059 IsVariadic, FSI);
4060}
4061
4062bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4063 bool HasImplicitThisParam, bool IsVariadic,
4064 FormatStringInfo *FSI) {
4065 if (FirstArg == 0)
4067 else if (IsVariadic)
4069 else
4071 FSI->FormatIdx = FormatIdx - 1;
4072 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4073
4074 // The way the format attribute works in GCC, the implicit this argument
4075 // of member functions is counted. However, it doesn't appear in our own
4076 // lists, so decrement format_idx in that case.
4077 if (HasImplicitThisParam) {
4078 if(FSI->FormatIdx == 0)
4079 return false;
4080 --FSI->FormatIdx;
4081 if (FSI->FirstDataArg != 0)
4082 --FSI->FirstDataArg;
4083 }
4084 return true;
4085}
4086
4087/// Checks if a the given expression evaluates to null.
4088///
4089/// Returns true if the value evaluates to null.
4090static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4091 // Treat (smart) pointers constructed from nullptr as null, whether we can
4092 // const-evaluate them or not.
4093 // This must happen first: the smart pointer expr might have _Nonnull type!
4097 return true;
4098
4099 // If the expression has non-null type, it doesn't evaluate to null.
4100 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4101 if (*nullability == NullabilityKind::NonNull)
4102 return false;
4103 }
4104
4105 // As a special case, transparent unions initialized with zero are
4106 // considered null for the purposes of the nonnull attribute.
4107 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4108 UT &&
4109 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4110 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4111 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4112 Expr = ILE->getInit(0);
4113 }
4114
4115 bool Result;
4116 return (!Expr->isValueDependent() &&
4118 !Result);
4119}
4120
4122 const Expr *ArgExpr,
4123 SourceLocation CallSiteLoc) {
4124 if (CheckNonNullExpr(S, ArgExpr))
4125 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4126 S.PDiag(diag::warn_null_arg)
4127 << ArgExpr->getSourceRange());
4128}
4129
4130/// Determine whether the given type has a non-null nullability annotation.
4132 if (auto nullability = type->getNullability())
4133 return *nullability == NullabilityKind::NonNull;
4134
4135 return false;
4136}
4137
4139 const NamedDecl *FDecl,
4140 const FunctionProtoType *Proto,
4142 SourceLocation CallSiteLoc) {
4143 assert((FDecl || Proto) && "Need a function declaration or prototype");
4144
4145 // Already checked by constant evaluator.
4147 return;
4148 // Check the attributes attached to the method/function itself.
4149 llvm::SmallBitVector NonNullArgs;
4150 if (FDecl) {
4151 // Handle the nonnull attribute on the function/method declaration itself.
4152 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4153 if (!NonNull->args_size()) {
4154 // Easy case: all pointer arguments are nonnull.
4155 for (const auto *Arg : Args)
4156 if (S.isValidPointerAttrType(Arg->getType()))
4157 CheckNonNullArgument(S, Arg, CallSiteLoc);
4158 return;
4159 }
4160
4161 for (const ParamIdx &Idx : NonNull->args()) {
4162 unsigned IdxAST = Idx.getASTIndex();
4163 if (IdxAST >= Args.size())
4164 continue;
4165 if (NonNullArgs.empty())
4166 NonNullArgs.resize(Args.size());
4167 NonNullArgs.set(IdxAST);
4168 }
4169 }
4170 }
4171
4172 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4173 // Handle the nonnull attribute on the parameters of the
4174 // function/method.
4176 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4177 parms = FD->parameters();
4178 else
4179 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4180
4181 unsigned ParamIndex = 0;
4182 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4183 I != E; ++I, ++ParamIndex) {
4184 const ParmVarDecl *PVD = *I;
4185 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4186 if (NonNullArgs.empty())
4187 NonNullArgs.resize(Args.size());
4188
4189 NonNullArgs.set(ParamIndex);
4190 }
4191 }
4192 } else {
4193 // If we have a non-function, non-method declaration but no
4194 // function prototype, try to dig out the function prototype.
4195 if (!Proto) {
4196 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4197 QualType type = VD->getType().getNonReferenceType();
4198 if (auto pointerType = type->getAs<PointerType>())
4199 type = pointerType->getPointeeType();
4200 else if (auto blockType = type->getAs<BlockPointerType>())
4201 type = blockType->getPointeeType();
4202 // FIXME: data member pointers?
4203
4204 // Dig out the function prototype, if there is one.
4205 Proto = type->getAs<FunctionProtoType>();
4206 }
4207 }
4208
4209 // Fill in non-null argument information from the nullability
4210 // information on the parameter types (if we have them).
4211 if (Proto) {
4212 unsigned Index = 0;
4213 for (auto paramType : Proto->getParamTypes()) {
4214 if (isNonNullType(paramType)) {
4215 if (NonNullArgs.empty())
4216 NonNullArgs.resize(Args.size());
4217
4218 NonNullArgs.set(Index);
4219 }
4220
4221 ++Index;
4222 }
4223 }
4224 }
4225
4226 // Check for non-null arguments.
4227 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4228 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4229 if (NonNullArgs[ArgIndex])
4230 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4231 }
4232}
4233
4234void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4235 StringRef ParamName, QualType ArgTy,
4236 QualType ParamTy) {
4237
4238 // If a function accepts a pointer or reference type
4239 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4240 return;
4241
4242 // If the parameter is a pointer type, get the pointee type for the
4243 // argument too. If the parameter is a reference type, don't try to get
4244 // the pointee type for the argument.
4245 if (ParamTy->isPointerType())
4246 ArgTy = ArgTy->getPointeeType();
4247
4248 // Remove reference or pointer
4249 ParamTy = ParamTy->getPointeeType();
4250
4251 // Find expected alignment, and the actual alignment of the passed object.
4252 // getTypeAlignInChars requires complete types
4253 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4254 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4255 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4256 return;
4257
4258 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4259 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4260
4261 // If the argument is less aligned than the parameter, there is a
4262 // potential alignment issue.
4263 if (ArgAlign < ParamAlign)
4264 Diag(Loc, diag::warn_param_mismatched_alignment)
4265 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4266 << ParamName << (FDecl != nullptr) << FDecl;
4267}
4268
4269void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4270 const Expr *ThisArg,
4272 if (!FD || Args.empty())
4273 return;
4274 auto GetArgAt = [&](int Idx) -> const Expr * {
4275 if (Idx == LifetimeCaptureByAttr::Global ||
4276 Idx == LifetimeCaptureByAttr::Unknown)
4277 return nullptr;
4278 if (IsMemberFunction && Idx == 0)
4279 return ThisArg;
4280 return Args[Idx - IsMemberFunction];
4281 };
4282 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4283 unsigned ArgIdx) {
4284 if (!Attr)
4285 return;
4286
4287 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4288 for (int CapturingParamIdx : Attr->params()) {
4289 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4290 continue;
4291 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4292 // initialization codepath.
4293 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4295 continue;
4296 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4297 CapturingEntity CE{Capturing};
4298 // Ensure that 'Captured' outlives the 'Capturing' entity.
4299 checkCaptureByLifetime(*this, CE, Captured);
4300 }
4301 };
4302 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4303 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4304 I + IsMemberFunction);
4305 // Check when the implicit object param is captured.
4306 if (IsMemberFunction) {
4307 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4308 if (!TSI)
4309 return;
4311 for (TypeLoc TL = TSI->getTypeLoc();
4312 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4313 TL = ATL.getModifiedLoc())
4314 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4315 }
4316}
4317
4319 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4320 bool IsMemberFunction, SourceLocation Loc,
4321 SourceRange Range, VariadicCallType CallType) {
4322
4323 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4324 llvm::any_of(Args, [](const Expr *E) {
4325 return E && E->isInstantiationDependent();
4326 }))
4327 return;
4328
4329 // Printf and scanf checking.
4330 llvm::SmallBitVector CheckedVarArgs;
4331 if (FDecl) {
4332 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4333 // Only create vector if there are format attributes.
4334 CheckedVarArgs.resize(Args.size());
4335 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4336 CheckedVarArgs);
4337 }
4338
4339 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4340 CheckedVarArgs.resize(Args.size());
4341 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4342 CheckedVarArgs);
4343 }
4344 }
4345
4346 // Refuse POD arguments that weren't caught by the format string
4347 // checks above.
4348 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4349 if (CallType != VariadicCallType::DoesNotApply &&
4350 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4351 unsigned NumParams = Proto ? Proto->getNumParams()
4352 : isa_and_nonnull<FunctionDecl>(FDecl)
4353 ? cast<FunctionDecl>(FDecl)->getNumParams()
4354 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4355 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4356 : 0;
4357
4358 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4359 // Args[ArgIdx] can be null in malformed code.
4360 if (const Expr *Arg = Args[ArgIdx]) {
4361 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4362 checkVariadicArgument(Arg, CallType);
4363 }
4364 }
4365 }
4366 if (FD)
4367 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4368 if (FDecl || Proto) {
4369 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4370
4371 // Type safety checking.
4372 if (FDecl) {
4373 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4374 CheckArgumentWithTypeTag(I, Args, Loc);
4375 }
4376 }
4377
4378 // Check that passed arguments match the alignment of original arguments.
4379 // Try to get the missing prototype from the declaration.
4380 if (!Proto && FDecl) {
4381 const auto *FT = FDecl->getFunctionType();
4382 if (isa_and_nonnull<FunctionProtoType>(FT))
4383 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4384 }
4385 if (Proto) {
4386 // For variadic functions, we may have more args than parameters.
4387 // For some K&R functions, we may have less args than parameters.
4388 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4389 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4390 bool IsScalableArg = false;
4391 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4392 // Args[ArgIdx] can be null in malformed code.
4393 if (const Expr *Arg = Args[ArgIdx]) {
4394 if (Arg->containsErrors())
4395 continue;
4396
4397 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4398 FDecl->hasLinkage() &&
4399 FDecl->getFormalLinkage() != Linkage::Internal &&
4401 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4402
4403 QualType ParamTy = Proto->getParamType(ArgIdx);
4404 if (ParamTy->isSizelessVectorType())
4405 IsScalableArg = true;
4406 QualType ArgTy = Arg->getType();
4407 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4408 ArgTy, ParamTy);
4409 }
4410 }
4411
4412 // If the callee has an AArch64 SME attribute to indicate that it is an
4413 // __arm_streaming function, then the caller requires SME to be available.
4416 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4417 llvm::StringMap<bool> CallerFeatureMap;
4418 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4419 if (!CallerFeatureMap.contains("sme"))
4420 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4421 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4422 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4423 }
4424 }
4425
4426 // If the call requires a streaming-mode change and has scalable vector
4427 // arguments or return values, then warn the user that the streaming and
4428 // non-streaming vector lengths may be different.
4429 // When both streaming and non-streaming vector lengths are defined and
4430 // mismatched, produce an error.
4431 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4432 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4433 (IsScalableArg || IsScalableRet)) {
4434 bool IsCalleeStreaming =
4436 bool IsCalleeStreamingCompatible =
4437 ExtInfo.AArch64SMEAttributes &
4439 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4440 if (!IsCalleeStreamingCompatible &&
4441 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4442 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4443 const LangOptions &LO = getLangOpts();
4444 unsigned VL = LO.VScaleMin * 128;
4445 unsigned SVL = LO.VScaleStreamingMin * 128;
4446 bool IsVLMismatch = VL && SVL && VL != SVL;
4447
4448 auto EmitDiag = [&](bool IsArg) {
4449 if (IsVLMismatch) {
4450 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4451 // Emit warning for streaming-compatible callers
4452 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4453 << IsArg << IsCalleeStreaming << SVL << VL;
4454 else
4455 // Emit error otherwise
4456 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4457 << IsArg << SVL << VL;
4458 } else
4459 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4460 << IsArg;
4461 };
4462
4463 if (IsScalableArg)
4464 EmitDiag(true);
4465 if (IsScalableRet)
4466 EmitDiag(false);
4467 }
4468 }
4469
4470 FunctionType::ArmStateValue CalleeArmZAState =
4472 FunctionType::ArmStateValue CalleeArmZT0State =
4474 if (CalleeArmZAState != FunctionType::ARM_None ||
4475 CalleeArmZT0State != FunctionType::ARM_None) {
4476 bool CallerHasZAState = false;
4477 bool CallerHasZT0State = false;
4478 if (CallerFD) {
4479 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4480 if (Attr && Attr->isNewZA())
4481 CallerHasZAState = true;
4482 if (Attr && Attr->isNewZT0())
4483 CallerHasZT0State = true;
4484 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4485 CallerHasZAState |=
4487 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4489 CallerHasZT0State |=
4491 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4493 }
4494 }
4495
4496 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4497 Diag(Loc, diag::err_sme_za_call_no_za_state);
4498
4499 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4500 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4501
4502 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4503 CalleeArmZT0State != FunctionType::ARM_None) {
4504 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4505 Diag(Loc, diag::note_sme_use_preserves_za);
4506 }
4507 }
4508 }
4509
4510 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4511 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4512 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4513 if (!Arg->isValueDependent()) {
4514 Expr::EvalResult Align;
4515 if (Arg->EvaluateAsInt(Align, Context)) {
4516 const llvm::APSInt &I = Align.Val.getInt();
4517 if (!I.isPowerOf2())
4518 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4519 << Arg->getSourceRange();
4520
4521 if (I > Sema::MaximumAlignment)
4522 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4523 << Arg->getSourceRange() << Sema::MaximumAlignment;
4524 }
4525 }
4526 }
4527
4528 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4530 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4531 << diag::OffloadLang::SYCL;
4532
4533 if (FD)
4534 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4535}
4536
4537void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4538 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4539 DiagnoseUseOfDecl(Decl, Loc);
4540 }
4541}
4542
4543void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4545 const FunctionProtoType *Proto,
4546 SourceLocation Loc) {
4547 VariadicCallType CallType = Proto->isVariadic()
4550
4551 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4552 CheckArgAlignment(
4553 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4554 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4555
4556 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4557 Loc, SourceRange(), CallType);
4558}
4559
4561 const FunctionProtoType *Proto) {
4562 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4563 isa<CXXMethodDecl>(FDecl);
4564 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4565 IsMemberOperatorCall;
4566 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4567 TheCall->getCallee());
4568 Expr** Args = TheCall->getArgs();
4569 unsigned NumArgs = TheCall->getNumArgs();
4570
4571 Expr *ImplicitThis = nullptr;
4572 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4573 // If this is a call to a member operator, hide the first
4574 // argument from checkCall.
4575 // FIXME: Our choice of AST representation here is less than ideal.
4576 ImplicitThis = Args[0];
4577 ++Args;
4578 --NumArgs;
4579 } else if (IsMemberFunction && !FDecl->isStatic() &&
4581 ImplicitThis =
4582 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4583
4584 if (ImplicitThis) {
4585 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4586 // used.
4587 QualType ThisType = ImplicitThis->getType();
4588 if (!ThisType->isPointerType()) {
4589 assert(!ThisType->isReferenceType());
4590 ThisType = Context.getPointerType(ThisType);
4591 }
4592
4593 QualType ThisTypeFromDecl = Context.getPointerType(
4594 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4595
4596 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4597 ThisTypeFromDecl);
4598 }
4599
4600 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4601 IsMemberFunction, TheCall->getRParenLoc(),
4602 TheCall->getCallee()->getSourceRange(), CallType);
4603
4604 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4605 // None of the checks below are needed for functions that don't have
4606 // simple names (e.g., C++ conversion functions).
4607 if (!FnInfo)
4608 return false;
4609
4610 // Enforce TCB except for builtin calls, which are always allowed.
4611 if (FDecl->getBuiltinID() == 0)
4612 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4613
4614 CheckAbsoluteValueFunction(TheCall, FDecl);
4615 CheckMaxUnsignedZero(TheCall, FDecl);
4616 CheckInfNaNFunction(TheCall, FDecl);
4617
4618 if (getLangOpts().ObjC)
4619 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4620
4621 unsigned CMId = FDecl->getMemoryFunctionKind();
4622
4623 // Handle memory setting and copying functions.
4624 switch (CMId) {
4625 case 0:
4626 return false;
4627 case Builtin::BIstrlcpy: // fallthrough
4628 case Builtin::BIstrlcat:
4629 CheckStrlcpycatArguments(TheCall, FnInfo);
4630 break;
4631 case Builtin::BIstrncat:
4632 CheckStrncatArguments(TheCall, FnInfo);
4633 break;
4634 case Builtin::BIfree:
4635 CheckFreeArguments(TheCall);
4636 break;
4637 default:
4638 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4639 }
4640
4641 return false;
4642}
4643
4644bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4645 const FunctionProtoType *Proto) {
4646 QualType Ty;
4647 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4648 Ty = V->getType().getNonReferenceType();
4649 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4650 Ty = F->getType().getNonReferenceType();
4651 else
4652 return false;
4653
4654 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4655 !Ty->isFunctionProtoType())
4656 return false;
4657
4658 VariadicCallType CallType;
4659 if (!Proto || !Proto->isVariadic()) {
4661 } else if (Ty->isBlockPointerType()) {
4662 CallType = VariadicCallType::Block;
4663 } else { // Ty->isFunctionPointerType()
4664 CallType = VariadicCallType::Function;
4665 }
4666
4667 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4668 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4669 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4670 TheCall->getCallee()->getSourceRange(), CallType);
4671
4672 return false;
4673}
4674
4675bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4676 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4677 TheCall->getCallee());
4678 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4679 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4680 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4681 TheCall->getCallee()->getSourceRange(), CallType);
4682
4683 return false;
4684}
4685
4686static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4687 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4688 return false;
4689
4690 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4691 switch (Op) {
4692 case AtomicExpr::AO__c11_atomic_init:
4693 case AtomicExpr::AO__opencl_atomic_init:
4694 llvm_unreachable("There is no ordering argument for an init");
4695
4696 case AtomicExpr::AO__c11_atomic_load:
4697 case AtomicExpr::AO__opencl_atomic_load:
4698 case AtomicExpr::AO__hip_atomic_load:
4699 case AtomicExpr::AO__atomic_load_n:
4700 case AtomicExpr::AO__atomic_load:
4701 case AtomicExpr::AO__scoped_atomic_load_n:
4702 case AtomicExpr::AO__scoped_atomic_load:
4703 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4704 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4705
4706 case AtomicExpr::AO__c11_atomic_store:
4707 case AtomicExpr::AO__opencl_atomic_store:
4708 case AtomicExpr::AO__hip_atomic_store:
4709 case AtomicExpr::AO__atomic_store:
4710 case AtomicExpr::AO__atomic_store_n:
4711 case AtomicExpr::AO__scoped_atomic_store:
4712 case AtomicExpr::AO__scoped_atomic_store_n:
4713 case AtomicExpr::AO__atomic_clear:
4714 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4715 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4716 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4717
4718 default:
4719 return true;
4720 }
4721}
4722
4723ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4725 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4726 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4727 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4728 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4729 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4730 Op);
4731}
4732
4733/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4734/// equivalents. Provide a fixit when the scope is a compile-time constant and
4735/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4736/// compare_exchange builtins differ in how they accept the desired value, so
4737/// only a warning (without a fixit) is emitted for those.
4739 MultiExprArg Args,
4741 StringRef OldName;
4742 StringRef NewName;
4743 bool CanFixIt;
4744
4745 switch (Op) {
4746#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4747 case AtomicExpr::AO__hip_atomic_##hip: \
4748 OldName = "__hip_atomic_" #hip; \
4749 NewName = "__scoped_atomic_" #scoped; \
4750 CanFixIt = true; \
4751 break;
4752 HIP_ATOMIC_FIXABLE(load, load_n)
4753 HIP_ATOMIC_FIXABLE(store, store_n)
4754 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4755 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4756 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4757 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4758 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4759 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4760 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4761 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4762#undef HIP_ATOMIC_FIXABLE
4763 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4764 OldName = "__hip_atomic_compare_exchange_weak";
4765 NewName = "__scoped_atomic_compare_exchange";
4766 CanFixIt = false;
4767 break;
4768 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4769 OldName = "__hip_atomic_compare_exchange_strong";
4770 NewName = "__scoped_atomic_compare_exchange";
4771 CanFixIt = false;
4772 break;
4773 default:
4774 llvm_unreachable("unhandled HIP atomic op");
4775 }
4776
4777 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4778 << OldName << NewName;
4779 if (!CanFixIt)
4780 return;
4781
4782 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4783
4784 Expr *Scope = Args[Args.size() - 1];
4785 std::optional<llvm::APSInt> ScopeVal =
4786 Scope->getIntegerConstantExpr(S.Context);
4787 if (!ScopeVal)
4788 return;
4789
4790 StringRef ScopeName;
4791 switch (ScopeVal->getZExtValue()) {
4793 ScopeName = "__MEMORY_SCOPE_SINGLE";
4794 break;
4796 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4797 break;
4799 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4800 break;
4802 ScopeName = "__MEMORY_SCOPE_DEVICE";
4803 break;
4805 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4806 break;
4808 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4809 break;
4810 default:
4811 return;
4812 }
4813
4815 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
4816}
4817
4819 SourceLocation RParenLoc, MultiExprArg Args,
4821 AtomicArgumentOrder ArgOrder) {
4822 // All the non-OpenCL operations take one of the following forms.
4823 // The OpenCL operations take the __c11 forms with one extra argument for
4824 // synchronization scope.
4825 enum {
4826 // C __c11_atomic_init(A *, C)
4827 Init,
4828
4829 // C __c11_atomic_load(A *, int)
4830 Load,
4831
4832 // void __atomic_load(A *, CP, int)
4833 LoadCopy,
4834
4835 // void __atomic_store(A *, CP, int)
4836 Copy,
4837
4838 // C __c11_atomic_add(A *, M, int)
4839 Arithmetic,
4840
4841 // C __atomic_exchange_n(A *, CP, int)
4842 Xchg,
4843
4844 // void __atomic_exchange(A *, C *, CP, int)
4845 GNUXchg,
4846
4847 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4848 C11CmpXchg,
4849
4850 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4851 GNUCmpXchg,
4852
4853 // bool __atomic_test_and_set(A *, int)
4854 TestAndSetByte,
4855
4856 // void __atomic_clear(A *, int)
4857 ClearByte,
4858 } Form = Init;
4859
4860 const unsigned NumForm = ClearByte + 1;
4861 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4862 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4863 // where:
4864 // C is an appropriate type,
4865 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4866 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4867 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4868 // the int parameters are for orderings.
4869
4870 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4871 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4872 "need to update code for modified forms");
4873 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4874 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4875 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4876 "need to update code for modified C11 atomics");
4877 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4878 Op <= AtomicExpr::AO__opencl_atomic_store;
4879 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4880 Op <= AtomicExpr::AO__hip_atomic_store;
4881 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4882 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4883 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4884 Op <= AtomicExpr::AO__c11_atomic_store) ||
4885 IsOpenCL;
4886 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4887 Op == AtomicExpr::AO__atomic_store_n ||
4888 Op == AtomicExpr::AO__atomic_exchange_n ||
4889 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4890 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4891 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4892 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4893 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4894 // Bit mask for extra allowed value types other than integers for atomic
4895 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4896 // allow floating point.
4897 enum ArithOpExtraValueType {
4898 AOEVT_None = 0,
4899 AOEVT_Pointer = 1,
4900 AOEVT_FP = 2,
4901 };
4902 unsigned ArithAllows = AOEVT_None;
4903
4904 switch (Op) {
4905 case AtomicExpr::AO__c11_atomic_init:
4906 case AtomicExpr::AO__opencl_atomic_init:
4907 Form = Init;
4908 break;
4909
4910 case AtomicExpr::AO__c11_atomic_load:
4911 case AtomicExpr::AO__opencl_atomic_load:
4912 case AtomicExpr::AO__hip_atomic_load:
4913 case AtomicExpr::AO__atomic_load_n:
4914 case AtomicExpr::AO__scoped_atomic_load_n:
4915 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4916 Form = Load;
4917 break;
4918
4919 case AtomicExpr::AO__atomic_load:
4920 case AtomicExpr::AO__scoped_atomic_load:
4921 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4922 Form = LoadCopy;
4923 break;
4924
4925 case AtomicExpr::AO__c11_atomic_store:
4926 case AtomicExpr::AO__opencl_atomic_store:
4927 case AtomicExpr::AO__hip_atomic_store:
4928 case AtomicExpr::AO__atomic_store:
4929 case AtomicExpr::AO__atomic_store_n:
4930 case AtomicExpr::AO__scoped_atomic_store:
4931 case AtomicExpr::AO__scoped_atomic_store_n:
4932 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4933 Form = Copy;
4934 break;
4935 case AtomicExpr::AO__atomic_fetch_add:
4936 case AtomicExpr::AO__atomic_fetch_sub:
4937 case AtomicExpr::AO__atomic_add_fetch:
4938 case AtomicExpr::AO__atomic_sub_fetch:
4939 case AtomicExpr::AO__scoped_atomic_fetch_add:
4940 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4941 case AtomicExpr::AO__scoped_atomic_add_fetch:
4942 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4943 case AtomicExpr::AO__c11_atomic_fetch_add:
4944 case AtomicExpr::AO__c11_atomic_fetch_sub:
4945 case AtomicExpr::AO__opencl_atomic_fetch_add:
4946 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4947 case AtomicExpr::AO__hip_atomic_fetch_add:
4948 case AtomicExpr::AO__hip_atomic_fetch_sub:
4949 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4950 Form = Arithmetic;
4951 break;
4952 case AtomicExpr::AO__atomic_fetch_max:
4953 case AtomicExpr::AO__atomic_fetch_min:
4954 case AtomicExpr::AO__atomic_max_fetch:
4955 case AtomicExpr::AO__atomic_min_fetch:
4956 case AtomicExpr::AO__scoped_atomic_fetch_max:
4957 case AtomicExpr::AO__scoped_atomic_fetch_min:
4958 case AtomicExpr::AO__scoped_atomic_max_fetch:
4959 case AtomicExpr::AO__scoped_atomic_min_fetch:
4960 case AtomicExpr::AO__c11_atomic_fetch_max:
4961 case AtomicExpr::AO__c11_atomic_fetch_min:
4962 case AtomicExpr::AO__opencl_atomic_fetch_max:
4963 case AtomicExpr::AO__opencl_atomic_fetch_min:
4964 case AtomicExpr::AO__hip_atomic_fetch_max:
4965 case AtomicExpr::AO__hip_atomic_fetch_min:
4966 ArithAllows = AOEVT_FP;
4967 Form = Arithmetic;
4968 break;
4969 case AtomicExpr::AO__c11_atomic_fetch_and:
4970 case AtomicExpr::AO__c11_atomic_fetch_or:
4971 case AtomicExpr::AO__c11_atomic_fetch_xor:
4972 case AtomicExpr::AO__hip_atomic_fetch_and:
4973 case AtomicExpr::AO__hip_atomic_fetch_or:
4974 case AtomicExpr::AO__hip_atomic_fetch_xor:
4975 case AtomicExpr::AO__c11_atomic_fetch_nand:
4976 case AtomicExpr::AO__opencl_atomic_fetch_and:
4977 case AtomicExpr::AO__opencl_atomic_fetch_or:
4978 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4979 case AtomicExpr::AO__atomic_fetch_and:
4980 case AtomicExpr::AO__atomic_fetch_or:
4981 case AtomicExpr::AO__atomic_fetch_xor:
4982 case AtomicExpr::AO__atomic_fetch_nand:
4983 case AtomicExpr::AO__atomic_and_fetch:
4984 case AtomicExpr::AO__atomic_or_fetch:
4985 case AtomicExpr::AO__atomic_xor_fetch:
4986 case AtomicExpr::AO__atomic_nand_fetch:
4987 case AtomicExpr::AO__atomic_fetch_uinc:
4988 case AtomicExpr::AO__atomic_fetch_udec:
4989 case AtomicExpr::AO__scoped_atomic_fetch_and:
4990 case AtomicExpr::AO__scoped_atomic_fetch_or:
4991 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4992 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4993 case AtomicExpr::AO__scoped_atomic_and_fetch:
4994 case AtomicExpr::AO__scoped_atomic_or_fetch:
4995 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4996 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4997 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4998 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4999 Form = Arithmetic;
5000 break;
5001
5002 case AtomicExpr::AO__c11_atomic_exchange:
5003 case AtomicExpr::AO__hip_atomic_exchange:
5004 case AtomicExpr::AO__opencl_atomic_exchange:
5005 case AtomicExpr::AO__atomic_exchange_n:
5006 case AtomicExpr::AO__scoped_atomic_exchange_n:
5007 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5008 Form = Xchg;
5009 break;
5010
5011 case AtomicExpr::AO__atomic_exchange:
5012 case AtomicExpr::AO__scoped_atomic_exchange:
5013 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5014 Form = GNUXchg;
5015 break;
5016
5017 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5018 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5019 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5020 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5021 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5022 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5023 Form = C11CmpXchg;
5024 break;
5025
5026 case AtomicExpr::AO__atomic_compare_exchange:
5027 case AtomicExpr::AO__atomic_compare_exchange_n:
5028 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5029 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5030 ArithAllows = AOEVT_Pointer;
5031 Form = GNUCmpXchg;
5032 break;
5033
5034 case AtomicExpr::AO__atomic_test_and_set:
5035 Form = TestAndSetByte;
5036 break;
5037
5038 case AtomicExpr::AO__atomic_clear:
5039 Form = ClearByte;
5040 break;
5041 }
5042
5043 unsigned AdjustedNumArgs = NumArgs[Form];
5044 if ((IsOpenCL || IsHIP || IsScoped) &&
5045 Op != AtomicExpr::AO__opencl_atomic_init)
5046 ++AdjustedNumArgs;
5047 // Check we have the right number of arguments.
5048 if (Args.size() < AdjustedNumArgs) {
5049 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5050 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5051 << /*is non object*/ 0 << ExprRange;
5052 return ExprError();
5053 } else if (Args.size() > AdjustedNumArgs) {
5054 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5055 diag::err_typecheck_call_too_many_args)
5056 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5057 << /*is non object*/ 0 << ExprRange;
5058 return ExprError();
5059 }
5060
5061 // Inspect the first argument of the atomic operation.
5062 Expr *Ptr = Args[0];
5064 if (ConvertedPtr.isInvalid())
5065 return ExprError();
5066
5067 Ptr = ConvertedPtr.get();
5068 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5069 if (!pointerType) {
5070 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5071 << Ptr->getType() << 0 << Ptr->getSourceRange();
5072 return ExprError();
5073 }
5074
5075 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5076 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5077 QualType ValType = AtomTy; // 'C'
5078 if (IsC11) {
5079 if (!AtomTy->isAtomicType()) {
5080 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5081 << Ptr->getType() << Ptr->getSourceRange();
5082 return ExprError();
5083 }
5084 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5086 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5087 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5088 << Ptr->getSourceRange();
5089 return ExprError();
5090 }
5091 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5092 } else if (Form != Load && Form != LoadCopy) {
5093 if (ValType.isConstQualified()) {
5094 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5095 << Ptr->getType() << Ptr->getSourceRange();
5096 return ExprError();
5097 }
5098 }
5099
5100 if (Form != TestAndSetByte && Form != ClearByte) {
5101 // Pointer to object of size zero is not allowed.
5102 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5103 diag::err_incomplete_type))
5104 return ExprError();
5105
5106 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5107 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5108 << Ptr->getType() << 1 << Ptr->getSourceRange();
5109 return ExprError();
5110 }
5111 } else {
5112 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5113 // non-const pointer type, including void* and pointers to incomplete
5114 // structs, but only access the first byte.
5115 AtomTy = Context.CharTy;
5116 AtomTy = AtomTy.withCVRQualifiers(
5117 pointerType->getPointeeType().getCVRQualifiers());
5118 QualType PointerQT = Context.getPointerType(AtomTy);
5119 pointerType = PointerQT->getAs<PointerType>();
5120 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5121 ValType = AtomTy;
5122 }
5123
5124 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5125 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5126 Diag(ExprRange.getBegin(),
5127 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5128 << 0 << Ptr->getType() << Ptr->getSourceRange();
5129 return ExprError();
5130 }
5131
5132 // For an arithmetic operation, the implied arithmetic must be well-formed.
5133 // For _n operations, the value type must also be a valid atomic type.
5134 if (Form == Arithmetic || IsN) {
5135 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5136 // trivial type errors.
5137 auto IsAllowedValueType = [&](QualType ValType,
5138 unsigned AllowedType) -> bool {
5139 bool IsX87LongDouble =
5140 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5141 &Context.getTargetInfo().getLongDoubleFormat() ==
5142 &llvm::APFloat::x87DoubleExtended();
5143 if (ValType->isIntegerType())
5144 return true;
5145 if (ValType->isPointerType())
5146 return AllowedType & AOEVT_Pointer;
5147 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5148 return false;
5149 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5150 if (IsX87LongDouble)
5151 return false;
5152 return true;
5153 };
5154 if (!IsAllowedValueType(ValType, ArithAllows)) {
5155 auto DID = ArithAllows & AOEVT_FP
5156 ? (ArithAllows & AOEVT_Pointer
5157 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5158 : diag::err_atomic_op_needs_atomic_int_or_fp)
5159 : (ArithAllows & AOEVT_Pointer
5160 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5161 : diag::err_atomic_op_needs_atomic_int);
5162 Diag(ExprRange.getBegin(), DID)
5163 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5164 return ExprError();
5165 }
5166 if (IsC11 && ValType->isPointerType() &&
5168 diag::err_incomplete_type)) {
5169 return ExprError();
5170 }
5171 }
5172
5173 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5174 !AtomTy->isScalarType()) {
5175 // For GNU atomics, require a trivially-copyable type. This is not part of
5176 // the GNU atomics specification but we enforce it for consistency with
5177 // other atomics which generally all require a trivially-copyable type. This
5178 // is because atomics just copy bits.
5179 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5180 << Ptr->getType() << Ptr->getSourceRange();
5181 return ExprError();
5182 }
5183
5184 switch (ValType.getObjCLifetime()) {
5187 // okay
5188 break;
5189
5193 // FIXME: Can this happen? By this point, ValType should be known
5194 // to be trivially copyable.
5195 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5196 << ValType << Ptr->getSourceRange();
5197 return ExprError();
5198 }
5199
5200 // All atomic operations have an overload which takes a pointer to a volatile
5201 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5202 // into the result or the other operands. Similarly atomic_load takes a
5203 // pointer to a const 'A'.
5204 ValType.removeLocalVolatile();
5205 ValType.removeLocalConst();
5206 QualType ResultType = ValType;
5207 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5208 Form == ClearByte)
5209 ResultType = Context.VoidTy;
5210 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5211 ResultType = Context.BoolTy;
5212
5213 // The type of a parameter passed 'by value'. In the GNU atomics, such
5214 // arguments are actually passed as pointers.
5215 QualType ByValType = ValType; // 'CP'
5216 bool IsPassedByAddress = false;
5217 if (!IsC11 && !IsHIP && !IsN) {
5218 ByValType = Ptr->getType();
5219 IsPassedByAddress = true;
5220 }
5221
5222 SmallVector<Expr *, 5> APIOrderedArgs;
5223 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5224 APIOrderedArgs.push_back(Args[0]);
5225 switch (Form) {
5226 case Init:
5227 case Load:
5228 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5229 break;
5230 case LoadCopy:
5231 case Copy:
5232 case Arithmetic:
5233 case Xchg:
5234 APIOrderedArgs.push_back(Args[2]); // Val1
5235 APIOrderedArgs.push_back(Args[1]); // Order
5236 break;
5237 case GNUXchg:
5238 APIOrderedArgs.push_back(Args[2]); // Val1
5239 APIOrderedArgs.push_back(Args[3]); // Val2
5240 APIOrderedArgs.push_back(Args[1]); // Order
5241 break;
5242 case C11CmpXchg:
5243 APIOrderedArgs.push_back(Args[2]); // Val1
5244 APIOrderedArgs.push_back(Args[4]); // Val2
5245 APIOrderedArgs.push_back(Args[1]); // Order
5246 APIOrderedArgs.push_back(Args[3]); // OrderFail
5247 break;
5248 case GNUCmpXchg:
5249 APIOrderedArgs.push_back(Args[2]); // Val1
5250 APIOrderedArgs.push_back(Args[4]); // Val2
5251 APIOrderedArgs.push_back(Args[5]); // Weak
5252 APIOrderedArgs.push_back(Args[1]); // Order
5253 APIOrderedArgs.push_back(Args[3]); // OrderFail
5254 break;
5255 case TestAndSetByte:
5256 case ClearByte:
5257 APIOrderedArgs.push_back(Args[1]); // Order
5258 break;
5259 }
5260 } else
5261 APIOrderedArgs.append(Args.begin(), Args.end());
5262
5263 // The first argument's non-CV pointer type is used to deduce the type of
5264 // subsequent arguments, except for:
5265 // - weak flag (always converted to bool)
5266 // - memory order (always converted to int)
5267 // - scope (always converted to int)
5268 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5269 QualType Ty;
5270 if (i < NumVals[Form] + 1) {
5271 switch (i) {
5272 case 0:
5273 // The first argument is always a pointer. It has a fixed type.
5274 // It is always dereferenced, a nullptr is undefined.
5275 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5276 // Nothing else to do: we already know all we want about this pointer.
5277 continue;
5278 case 1:
5279 // The second argument is the non-atomic operand. For arithmetic, this
5280 // is always passed by value, and for a compare_exchange it is always
5281 // passed by address. For the rest, GNU uses by-address and C11 uses
5282 // by-value.
5283 assert(Form != Load);
5284 if (Form == Arithmetic && ValType->isPointerType())
5285 Ty = Context.getPointerDiffType();
5286 else if (Form == Init || Form == Arithmetic)
5287 Ty = ValType;
5288 else if (Form == Copy || Form == Xchg) {
5289 if (IsPassedByAddress) {
5290 // The value pointer is always dereferenced, a nullptr is undefined.
5291 CheckNonNullArgument(*this, APIOrderedArgs[i],
5292 ExprRange.getBegin());
5293 }
5294 Ty = ByValType;
5295 } else {
5296 Expr *ValArg = APIOrderedArgs[i];
5297 // The value pointer is always dereferenced, a nullptr is undefined.
5298 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5300 // Keep address space of non-atomic pointer type.
5301 if (const PointerType *PtrTy =
5302 ValArg->getType()->getAs<PointerType>()) {
5303 AS = PtrTy->getPointeeType().getAddressSpace();
5304 }
5305 Ty = Context.getPointerType(
5306 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5307 }
5308 break;
5309 case 2:
5310 // The third argument to compare_exchange / GNU exchange is the desired
5311 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5312 if (IsPassedByAddress)
5313 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5314 Ty = ByValType;
5315 break;
5316 case 3:
5317 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5318 Ty = Context.BoolTy;
5319 break;
5320 }
5321 } else {
5322 // The order(s) and scope are always converted to int.
5323 Ty = Context.IntTy;
5324 }
5325
5326 InitializedEntity Entity =
5328 ExprResult Arg = APIOrderedArgs[i];
5329 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5330 if (Arg.isInvalid())
5331 return true;
5332 APIOrderedArgs[i] = Arg.get();
5333 }
5334
5335 // Permute the arguments into a 'consistent' order.
5336 SmallVector<Expr*, 5> SubExprs;
5337 SubExprs.push_back(Ptr);
5338 switch (Form) {
5339 case Init:
5340 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5341 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5342 break;
5343 case Load:
5344 case TestAndSetByte:
5345 case ClearByte:
5346 SubExprs.push_back(APIOrderedArgs[1]); // Order
5347 break;
5348 case LoadCopy:
5349 case Copy:
5350 case Arithmetic:
5351 case Xchg:
5352 SubExprs.push_back(APIOrderedArgs[2]); // Order
5353 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5354 break;
5355 case GNUXchg:
5356 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5357 SubExprs.push_back(APIOrderedArgs[3]); // Order
5358 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5359 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5360 break;
5361 case C11CmpXchg:
5362 SubExprs.push_back(APIOrderedArgs[3]); // Order
5363 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5364 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5365 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5366 break;
5367 case GNUCmpXchg:
5368 SubExprs.push_back(APIOrderedArgs[4]); // Order
5369 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5370 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5371 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5372 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5373 break;
5374 }
5375
5376 // If the memory orders are constants, check they are valid.
5377 if (SubExprs.size() >= 2 && Form != Init) {
5378 std::optional<llvm::APSInt> Success =
5379 SubExprs[1]->getIntegerConstantExpr(Context);
5380 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5381 Diag(SubExprs[1]->getBeginLoc(),
5382 diag::warn_atomic_op_has_invalid_memory_order)
5383 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5384 << SubExprs[1]->getSourceRange();
5385 }
5386 if (SubExprs.size() >= 5) {
5387 if (std::optional<llvm::APSInt> Failure =
5388 SubExprs[3]->getIntegerConstantExpr(Context)) {
5389 if (!llvm::is_contained(
5390 {llvm::AtomicOrderingCABI::relaxed,
5391 llvm::AtomicOrderingCABI::consume,
5392 llvm::AtomicOrderingCABI::acquire,
5393 llvm::AtomicOrderingCABI::seq_cst},
5394 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5395 Diag(SubExprs[3]->getBeginLoc(),
5396 diag::warn_atomic_op_has_invalid_memory_order)
5397 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5398 }
5399 }
5400 }
5401 }
5402
5403 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5404 auto *Scope = Args[Args.size() - 1];
5405 if (std::optional<llvm::APSInt> Result =
5406 Scope->getIntegerConstantExpr(Context)) {
5407 if (!ScopeModel->isValid(Result->getZExtValue()))
5408 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5409 << Scope->getSourceRange();
5410 }
5411 SubExprs.push_back(Scope);
5412 }
5413
5414 if (IsHIP)
5415 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5416
5417 AtomicExpr *AE = new (Context)
5418 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5419
5420 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5421 Op == AtomicExpr::AO__c11_atomic_store ||
5422 Op == AtomicExpr::AO__opencl_atomic_load ||
5423 Op == AtomicExpr::AO__hip_atomic_load ||
5424 Op == AtomicExpr::AO__opencl_atomic_store ||
5425 Op == AtomicExpr::AO__hip_atomic_store) &&
5426 Context.AtomicUsesUnsupportedLibcall(AE))
5427 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5428 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5429 Op == AtomicExpr::AO__opencl_atomic_load ||
5430 Op == AtomicExpr::AO__hip_atomic_load)
5431 ? 0
5432 : 1);
5433
5434 if (ValType->isBitIntType()) {
5435 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5436 return ExprError();
5437 }
5438
5439 return AE;
5440}
5441
5442/// checkBuiltinArgument - Given a call to a builtin function, perform
5443/// normal type-checking on the given argument, updating the call in
5444/// place. This is useful when a builtin function requires custom
5445/// type-checking for some of its arguments but not necessarily all of
5446/// them.
5447///
5448/// Returns true on error.
5449static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5450 FunctionDecl *Fn = E->getDirectCallee();
5451 assert(Fn && "builtin call without direct callee!");
5452
5453 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5454 InitializedEntity Entity =
5456
5457 ExprResult Arg = E->getArg(ArgIndex);
5458 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5459 if (Arg.isInvalid())
5460 return true;
5461
5462 E->setArg(ArgIndex, Arg.get());
5463 return false;
5464}
5465
5466ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5467 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5468 Expr *Callee = TheCall->getCallee();
5469 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5470 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5471
5472 // Ensure that we have at least one argument to do type inference from.
5473 if (TheCall->getNumArgs() < 1) {
5474 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5475 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5476 << Callee->getSourceRange();
5477 return ExprError();
5478 }
5479
5480 // Inspect the first argument of the atomic builtin. This should always be
5481 // a pointer type, whose element is an integral scalar or pointer type.
5482 // Because it is a pointer type, we don't have to worry about any implicit
5483 // casts here.
5484 // FIXME: We don't allow floating point scalars as input.
5485 Expr *FirstArg = TheCall->getArg(0);
5486 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5487 if (FirstArgResult.isInvalid())
5488 return ExprError();
5489 FirstArg = FirstArgResult.get();
5490 TheCall->setArg(0, FirstArg);
5491
5492 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5493 if (!pointerType) {
5494 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5495 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5496 return ExprError();
5497 }
5498
5499 QualType ValType = pointerType->getPointeeType();
5500 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5501 !ValType->isBlockPointerType()) {
5502 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5503 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5504 return ExprError();
5505 }
5506 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5507 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5508 Diag(FirstArg->getBeginLoc(),
5509 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5510 << 1 << ValType << FirstArg->getSourceRange();
5511 return ExprError();
5512 }
5513
5514 if (ValType.isConstQualified()) {
5515 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5516 << FirstArg->getType() << FirstArg->getSourceRange();
5517 return ExprError();
5518 }
5519
5520 switch (ValType.getObjCLifetime()) {
5523 // okay
5524 break;
5525
5529 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5530 << ValType << FirstArg->getSourceRange();
5531 return ExprError();
5532 }
5533
5534 // Strip any qualifiers off ValType.
5535 ValType = ValType.getUnqualifiedType();
5536
5537 // The majority of builtins return a value, but a few have special return
5538 // types, so allow them to override appropriately below.
5539 QualType ResultType = ValType;
5540
5541 // We need to figure out which concrete builtin this maps onto. For example,
5542 // __sync_fetch_and_add with a 2 byte object turns into
5543 // __sync_fetch_and_add_2.
5544#define BUILTIN_ROW(x) \
5545 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5546 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5547
5548 static const unsigned BuiltinIndices[][5] = {
5549 BUILTIN_ROW(__sync_fetch_and_add),
5550 BUILTIN_ROW(__sync_fetch_and_sub),
5551 BUILTIN_ROW(__sync_fetch_and_or),
5552 BUILTIN_ROW(__sync_fetch_and_and),
5553 BUILTIN_ROW(__sync_fetch_and_xor),
5554 BUILTIN_ROW(__sync_fetch_and_nand),
5555
5556 BUILTIN_ROW(__sync_add_and_fetch),
5557 BUILTIN_ROW(__sync_sub_and_fetch),
5558 BUILTIN_ROW(__sync_and_and_fetch),
5559 BUILTIN_ROW(__sync_or_and_fetch),
5560 BUILTIN_ROW(__sync_xor_and_fetch),
5561 BUILTIN_ROW(__sync_nand_and_fetch),
5562
5563 BUILTIN_ROW(__sync_val_compare_and_swap),
5564 BUILTIN_ROW(__sync_bool_compare_and_swap),
5565 BUILTIN_ROW(__sync_lock_test_and_set),
5566 BUILTIN_ROW(__sync_lock_release),
5567 BUILTIN_ROW(__sync_swap)
5568 };
5569#undef BUILTIN_ROW
5570
5571 // Determine the index of the size.
5572 unsigned SizeIndex;
5573 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5574 case 1: SizeIndex = 0; break;
5575 case 2: SizeIndex = 1; break;
5576 case 4: SizeIndex = 2; break;
5577 case 8: SizeIndex = 3; break;
5578 case 16: SizeIndex = 4; break;
5579 default:
5580 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5581 << FirstArg->getType() << FirstArg->getSourceRange();
5582 return ExprError();
5583 }
5584
5585 // Each of these builtins has one pointer argument, followed by some number of
5586 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5587 // that we ignore. Find out which row of BuiltinIndices to read from as well
5588 // as the number of fixed args.
5589 unsigned BuiltinID = FDecl->getBuiltinID();
5590 unsigned BuiltinIndex, NumFixed = 1;
5591 bool WarnAboutSemanticsChange = false;
5592 switch (BuiltinID) {
5593 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5594 case Builtin::BI__sync_fetch_and_add:
5595 case Builtin::BI__sync_fetch_and_add_1:
5596 case Builtin::BI__sync_fetch_and_add_2:
5597 case Builtin::BI__sync_fetch_and_add_4:
5598 case Builtin::BI__sync_fetch_and_add_8:
5599 case Builtin::BI__sync_fetch_and_add_16:
5600 BuiltinIndex = 0;
5601 break;
5602
5603 case Builtin::BI__sync_fetch_and_sub:
5604 case Builtin::BI__sync_fetch_and_sub_1:
5605 case Builtin::BI__sync_fetch_and_sub_2:
5606 case Builtin::BI__sync_fetch_and_sub_4:
5607 case Builtin::BI__sync_fetch_and_sub_8:
5608 case Builtin::BI__sync_fetch_and_sub_16:
5609 BuiltinIndex = 1;
5610 break;
5611
5612 case Builtin::BI__sync_fetch_and_or:
5613 case Builtin::BI__sync_fetch_and_or_1:
5614 case Builtin::BI__sync_fetch_and_or_2:
5615 case Builtin::BI__sync_fetch_and_or_4:
5616 case Builtin::BI__sync_fetch_and_or_8:
5617 case Builtin::BI__sync_fetch_and_or_16:
5618 BuiltinIndex = 2;
5619 break;
5620
5621 case Builtin::BI__sync_fetch_and_and:
5622 case Builtin::BI__sync_fetch_and_and_1:
5623 case Builtin::BI__sync_fetch_and_and_2:
5624 case Builtin::BI__sync_fetch_and_and_4:
5625 case Builtin::BI__sync_fetch_and_and_8:
5626 case Builtin::BI__sync_fetch_and_and_16:
5627 BuiltinIndex = 3;
5628 break;
5629
5630 case Builtin::BI__sync_fetch_and_xor:
5631 case Builtin::BI__sync_fetch_and_xor_1:
5632 case Builtin::BI__sync_fetch_and_xor_2:
5633 case Builtin::BI__sync_fetch_and_xor_4:
5634 case Builtin::BI__sync_fetch_and_xor_8:
5635 case Builtin::BI__sync_fetch_and_xor_16:
5636 BuiltinIndex = 4;
5637 break;
5638
5639 case Builtin::BI__sync_fetch_and_nand:
5640 case Builtin::BI__sync_fetch_and_nand_1:
5641 case Builtin::BI__sync_fetch_and_nand_2:
5642 case Builtin::BI__sync_fetch_and_nand_4:
5643 case Builtin::BI__sync_fetch_and_nand_8:
5644 case Builtin::BI__sync_fetch_and_nand_16:
5645 BuiltinIndex = 5;
5646 WarnAboutSemanticsChange = true;
5647 break;
5648
5649 case Builtin::BI__sync_add_and_fetch:
5650 case Builtin::BI__sync_add_and_fetch_1:
5651 case Builtin::BI__sync_add_and_fetch_2:
5652 case Builtin::BI__sync_add_and_fetch_4:
5653 case Builtin::BI__sync_add_and_fetch_8:
5654 case Builtin::BI__sync_add_and_fetch_16:
5655 BuiltinIndex = 6;
5656 break;
5657
5658 case Builtin::BI__sync_sub_and_fetch:
5659 case Builtin::BI__sync_sub_and_fetch_1:
5660 case Builtin::BI__sync_sub_and_fetch_2:
5661 case Builtin::BI__sync_sub_and_fetch_4:
5662 case Builtin::BI__sync_sub_and_fetch_8:
5663 case Builtin::BI__sync_sub_and_fetch_16:
5664 BuiltinIndex = 7;
5665 break;
5666
5667 case Builtin::BI__sync_and_and_fetch:
5668 case Builtin::BI__sync_and_and_fetch_1:
5669 case Builtin::BI__sync_and_and_fetch_2:
5670 case Builtin::BI__sync_and_and_fetch_4:
5671 case Builtin::BI__sync_and_and_fetch_8:
5672 case Builtin::BI__sync_and_and_fetch_16:
5673 BuiltinIndex = 8;
5674 break;
5675
5676 case Builtin::BI__sync_or_and_fetch:
5677 case Builtin::BI__sync_or_and_fetch_1:
5678 case Builtin::BI__sync_or_and_fetch_2:
5679 case Builtin::BI__sync_or_and_fetch_4:
5680 case Builtin::BI__sync_or_and_fetch_8:
5681 case Builtin::BI__sync_or_and_fetch_16:
5682 BuiltinIndex = 9;
5683 break;
5684
5685 case Builtin::BI__sync_xor_and_fetch:
5686 case Builtin::BI__sync_xor_and_fetch_1:
5687 case Builtin::BI__sync_xor_and_fetch_2:
5688 case Builtin::BI__sync_xor_and_fetch_4:
5689 case Builtin::BI__sync_xor_and_fetch_8:
5690 case Builtin::BI__sync_xor_and_fetch_16:
5691 BuiltinIndex = 10;
5692 break;
5693
5694 case Builtin::BI__sync_nand_and_fetch:
5695 case Builtin::BI__sync_nand_and_fetch_1:
5696 case Builtin::BI__sync_nand_and_fetch_2:
5697 case Builtin::BI__sync_nand_and_fetch_4:
5698 case Builtin::BI__sync_nand_and_fetch_8:
5699 case Builtin::BI__sync_nand_and_fetch_16:
5700 BuiltinIndex = 11;
5701 WarnAboutSemanticsChange = true;
5702 break;
5703
5704 case Builtin::BI__sync_val_compare_and_swap:
5705 case Builtin::BI__sync_val_compare_and_swap_1:
5706 case Builtin::BI__sync_val_compare_and_swap_2:
5707 case Builtin::BI__sync_val_compare_and_swap_4:
5708 case Builtin::BI__sync_val_compare_and_swap_8:
5709 case Builtin::BI__sync_val_compare_and_swap_16:
5710 BuiltinIndex = 12;
5711 NumFixed = 2;
5712 break;
5713
5714 case Builtin::BI__sync_bool_compare_and_swap:
5715 case Builtin::BI__sync_bool_compare_and_swap_1:
5716 case Builtin::BI__sync_bool_compare_and_swap_2:
5717 case Builtin::BI__sync_bool_compare_and_swap_4:
5718 case Builtin::BI__sync_bool_compare_and_swap_8:
5719 case Builtin::BI__sync_bool_compare_and_swap_16:
5720 BuiltinIndex = 13;
5721 NumFixed = 2;
5722 ResultType = Context.BoolTy;
5723 break;
5724
5725 case Builtin::BI__sync_lock_test_and_set:
5726 case Builtin::BI__sync_lock_test_and_set_1:
5727 case Builtin::BI__sync_lock_test_and_set_2:
5728 case Builtin::BI__sync_lock_test_and_set_4:
5729 case Builtin::BI__sync_lock_test_and_set_8:
5730 case Builtin::BI__sync_lock_test_and_set_16:
5731 BuiltinIndex = 14;
5732 break;
5733
5734 case Builtin::BI__sync_lock_release:
5735 case Builtin::BI__sync_lock_release_1:
5736 case Builtin::BI__sync_lock_release_2:
5737 case Builtin::BI__sync_lock_release_4:
5738 case Builtin::BI__sync_lock_release_8:
5739 case Builtin::BI__sync_lock_release_16:
5740 BuiltinIndex = 15;
5741 NumFixed = 0;
5742 ResultType = Context.VoidTy;
5743 break;
5744
5745 case Builtin::BI__sync_swap:
5746 case Builtin::BI__sync_swap_1:
5747 case Builtin::BI__sync_swap_2:
5748 case Builtin::BI__sync_swap_4:
5749 case Builtin::BI__sync_swap_8:
5750 case Builtin::BI__sync_swap_16:
5751 BuiltinIndex = 16;
5752 break;
5753 }
5754
5755 // Now that we know how many fixed arguments we expect, first check that we
5756 // have at least that many.
5757 if (TheCall->getNumArgs() < 1+NumFixed) {
5758 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5759 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5760 << Callee->getSourceRange();
5761 return ExprError();
5762 }
5763
5764 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5765 << Callee->getSourceRange();
5766
5767 if (WarnAboutSemanticsChange) {
5768 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5769 << Callee->getSourceRange();
5770 }
5771
5772 // Get the decl for the concrete builtin from this, we can tell what the
5773 // concrete integer type we should convert to is.
5774 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5775 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5776 FunctionDecl *NewBuiltinDecl;
5777 if (NewBuiltinID == BuiltinID)
5778 NewBuiltinDecl = FDecl;
5779 else {
5780 // Perform builtin lookup to avoid redeclaring it.
5781 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5782 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5783 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5784 assert(Res.getFoundDecl());
5785 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5786 if (!NewBuiltinDecl)
5787 return ExprError();
5788 }
5789
5790 // The first argument --- the pointer --- has a fixed type; we
5791 // deduce the types of the rest of the arguments accordingly. Walk
5792 // the remaining arguments, converting them to the deduced value type.
5793 for (unsigned i = 0; i != NumFixed; ++i) {
5794 ExprResult Arg = TheCall->getArg(i+1);
5795
5796 // GCC does an implicit conversion to the pointer or integer ValType. This
5797 // can fail in some cases (1i -> int**), check for this error case now.
5798 // Initialize the argument.
5799 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5800 ValType, /*consume*/ false);
5801 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5802 if (Arg.isInvalid())
5803 return ExprError();
5804
5805 // Okay, we have something that *can* be converted to the right type. Check
5806 // to see if there is a potentially weird extension going on here. This can
5807 // happen when you do an atomic operation on something like an char* and
5808 // pass in 42. The 42 gets converted to char. This is even more strange
5809 // for things like 45.123 -> char, etc.
5810 // FIXME: Do this check.
5811 TheCall->setArg(i+1, Arg.get());
5812 }
5813
5814 // Create a new DeclRefExpr to refer to the new decl.
5815 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5816 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5817 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5818 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5819
5820 // Set the callee in the CallExpr.
5821 // FIXME: This loses syntactic information.
5822 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5823 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5824 CK_BuiltinFnToFnPtr);
5825 TheCall->setCallee(PromotedCall.get());
5826
5827 // Change the result type of the call to match the original value type. This
5828 // is arbitrary, but the codegen for these builtins ins design to handle it
5829 // gracefully.
5830 TheCall->setType(ResultType);
5831
5832 // Prohibit problematic uses of bit-precise integer types with atomic
5833 // builtins. The arguments would have already been converted to the first
5834 // argument's type, so only need to check the first argument.
5835 const auto *BitIntValType = ValType->getAs<BitIntType>();
5836 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5837 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5838 return ExprError();
5839 }
5840
5841 return TheCallResult;
5842}
5843
5844ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5845 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5846 DeclRefExpr *DRE =
5848 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5849 unsigned BuiltinID = FDecl->getBuiltinID();
5850 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5851 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5852 "Unexpected nontemporal load/store builtin!");
5853 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5854 unsigned numArgs = isStore ? 2 : 1;
5855
5856 // Ensure that we have the proper number of arguments.
5857 if (checkArgCount(TheCall, numArgs))
5858 return ExprError();
5859
5860 // Inspect the last argument of the nontemporal builtin. This should always
5861 // be a pointer type, from which we imply the type of the memory access.
5862 // Because it is a pointer type, we don't have to worry about any implicit
5863 // casts here.
5864 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5865 ExprResult PointerArgResult =
5867
5868 if (PointerArgResult.isInvalid())
5869 return ExprError();
5870 PointerArg = PointerArgResult.get();
5871 TheCall->setArg(numArgs - 1, PointerArg);
5872
5873 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5874 if (!pointerType) {
5875 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5876 << PointerArg->getType() << PointerArg->getSourceRange();
5877 return ExprError();
5878 }
5879
5880 QualType ValType = pointerType->getPointeeType();
5881
5882 // Strip any qualifiers off ValType.
5883 ValType = ValType.getUnqualifiedType();
5884 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5885 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5886 !ValType->isVectorType()) {
5887 Diag(DRE->getBeginLoc(),
5888 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5889 << PointerArg->getType() << PointerArg->getSourceRange();
5890 return ExprError();
5891 }
5892
5893 if (!isStore) {
5894 TheCall->setType(ValType);
5895 return TheCallResult;
5896 }
5897
5898 ExprResult ValArg = TheCall->getArg(0);
5899 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5900 Context, ValType, /*consume*/ false);
5901 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5902 if (ValArg.isInvalid())
5903 return ExprError();
5904
5905 TheCall->setArg(0, ValArg.get());
5906 TheCall->setType(Context.VoidTy);
5907 return TheCallResult;
5908}
5909
5910/// CheckObjCString - Checks that the format string argument to the os_log()
5911/// and os_trace() functions is correct, and converts it to const char *.
5912ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5913 Arg = Arg->IgnoreParenCasts();
5914 auto *Literal = dyn_cast<StringLiteral>(Arg);
5915 if (!Literal) {
5916 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5917 Literal = ObjcLiteral->getString();
5918 }
5919 }
5920
5921 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5922 return ExprError(
5923 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5924 << Arg->getSourceRange());
5925 }
5926
5927 ExprResult Result(Literal);
5928 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5929 InitializedEntity Entity =
5931 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5932 return Result;
5933}
5934
5935/// Check that the user is calling the appropriate va_start builtin for the
5936/// target and calling convention.
5937static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5938 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5939 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5940 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5941 TT.getArch() == llvm::Triple::aarch64_32);
5942 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5943 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5944 if (IsX64 || IsAArch64) {
5945 CallingConv CC = CC_C;
5946 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5947 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5948 if (IsMSVAStart) {
5949 // Don't allow this in System V ABI functions.
5950 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5951 return S.Diag(Fn->getBeginLoc(),
5952 diag::err_ms_va_start_used_in_sysv_function);
5953 } else {
5954 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5955 // On x64 Windows, don't allow this in System V ABI functions.
5956 // (Yes, that means there's no corresponding way to support variadic
5957 // System V ABI functions on Windows.)
5958 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5959 (!IsWindowsOrUEFI && CC == CC_Win64))
5960 return S.Diag(Fn->getBeginLoc(),
5961 diag::err_va_start_used_in_wrong_abi_function)
5962 << !IsWindowsOrUEFI;
5963 }
5964 return false;
5965 }
5966
5967 if (IsMSVAStart)
5968 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5969 return false;
5970}
5971
5973 ParmVarDecl **LastParam = nullptr) {
5974 // Determine whether the current function, block, or obj-c method is variadic
5975 // and get its parameter list.
5976 bool IsVariadic = false;
5978 DeclContext *Caller = S.CurContext;
5979 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5980 IsVariadic = Block->isVariadic();
5981 Params = Block->parameters();
5982 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5983 IsVariadic = FD->isVariadic();
5984 Params = FD->parameters();
5985 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5986 IsVariadic = MD->isVariadic();
5987 // FIXME: This isn't correct for methods (results in bogus warning).
5988 Params = MD->parameters();
5989 } else if (isa<CapturedDecl>(Caller)) {
5990 // We don't support va_start in a CapturedDecl.
5991 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5992 return true;
5993 } else {
5994 // This must be some other declcontext that parses exprs.
5995 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5996 return true;
5997 }
5998
5999 if (!IsVariadic) {
6000 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6001 return true;
6002 }
6003
6004 if (LastParam)
6005 *LastParam = Params.empty() ? nullptr : Params.back();
6006
6007 return false;
6008}
6009
6010bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6011 Expr *Fn = TheCall->getCallee();
6012 if (checkVAStartABI(*this, BuiltinID, Fn))
6013 return true;
6014
6015 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6016 // This builtin requires one argument (the va_list), allows two arguments,
6017 // but diagnoses more than two arguments. e.g.,
6018 // __builtin_c23_va_start(); // error
6019 // __builtin_c23_va_start(list); // ok
6020 // __builtin_c23_va_start(list, param); // ok
6021 // __builtin_c23_va_start(list, anything, anything); // error
6022 // This differs from the GCC behavior in that they accept the last case
6023 // with a warning, but it doesn't seem like a useful behavior to allow.
6024 if (checkArgCountRange(TheCall, 1, 2))
6025 return true;
6026 } else {
6027 // In C23 mode, va_start only needs one argument. However, the builtin still
6028 // requires two arguments (which matches the behavior of the GCC builtin),
6029 // <stdarg.h> passes `0` as the second argument in C23 mode.
6030 if (checkArgCount(TheCall, 2))
6031 return true;
6032 }
6033
6034 // Type-check the first argument normally.
6035 if (checkBuiltinArgument(*this, TheCall, 0))
6036 return true;
6037
6038 // Check that the current function is variadic, and get its last parameter.
6039 ParmVarDecl *LastParam;
6040 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6041 return true;
6042
6043 // Verify that the second argument to the builtin is the last non-variadic
6044 // argument of the current function or method. In C23 mode, if the call is
6045 // not to __builtin_c23_va_start, and the second argument is an integer
6046 // constant expression with value 0, then we don't bother with this check.
6047 // For __builtin_c23_va_start, we only perform the check for the second
6048 // argument being the last argument to the current function if there is a
6049 // second argument present.
6050 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6051 TheCall->getNumArgs() < 2) {
6052 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6053 return false;
6054 }
6055
6056 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6057 if (std::optional<llvm::APSInt> Val =
6059 Val && LangOpts.C23 && *Val == 0 &&
6060 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6061 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6062 return false;
6063 }
6064
6065 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6066 // next block.
6067 QualType Type;
6068 SourceLocation ParamLoc;
6069 bool IsCRegister = false;
6070 bool SecondArgIsLastNonVariadicArgument = false;
6071 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6072 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6073 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6074
6075 Type = PV->getType();
6076 ParamLoc = PV->getLocation();
6077 IsCRegister =
6078 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6079 }
6080 }
6081
6082 if (!SecondArgIsLastNonVariadicArgument)
6083 Diag(TheCall->getArg(1)->getBeginLoc(),
6084 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6085 else if (IsCRegister || Type->isReferenceType() ||
6086 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6087 // Promotable integers are UB, but enumerations need a bit of
6088 // extra checking to see what their promotable type actually is.
6089 if (!Context.isPromotableIntegerType(Type))
6090 return false;
6091 const auto *ED = Type->getAsEnumDecl();
6092 if (!ED)
6093 return true;
6094 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6095 }()) {
6096 unsigned Reason = 0;
6097 if (Type->isReferenceType()) Reason = 1;
6098 else if (IsCRegister) Reason = 2;
6099 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6100 Diag(ParamLoc, diag::note_parameter_type) << Type;
6101 }
6102
6103 return false;
6104}
6105
6106bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6107 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6108 const LangOptions &LO = getLangOpts();
6109
6110 if (LO.CPlusPlus)
6111 return Arg->getType()
6113 .getTypePtr()
6114 ->getPointeeType()
6116
6117 // In C, allow aliasing through `char *`, this is required for AArch64 at
6118 // least.
6119 return true;
6120 };
6121
6122 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6123 // const char *named_addr);
6124
6125 Expr *Func = Call->getCallee();
6126
6127 if (Call->getNumArgs() < 3)
6128 return Diag(Call->getEndLoc(),
6129 diag::err_typecheck_call_too_few_args_at_least)
6130 << 0 /*function call*/ << 3 << Call->getNumArgs()
6131 << /*is non object*/ 0;
6132
6133 // Type-check the first argument normally.
6134 if (checkBuiltinArgument(*this, Call, 0))
6135 return true;
6136
6137 // Check that the current function is variadic.
6139 return true;
6140
6141 // __va_start on Windows does not validate the parameter qualifiers
6142
6143 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6144 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6145
6146 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6147 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6148
6149 const QualType &ConstCharPtrTy =
6150 Context.getPointerType(Context.CharTy.withConst());
6151 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6152 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6153 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6154 << 0 /* qualifier difference */
6155 << 3 /* parameter mismatch */
6156 << 2 << Arg1->getType() << ConstCharPtrTy;
6157
6158 const QualType SizeTy = Context.getSizeType();
6159 if (!Context.hasSameType(
6161 SizeTy))
6162 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6163 << Arg2->getType() << SizeTy << 1 /* different class */
6164 << 0 /* qualifier difference */
6165 << 3 /* parameter mismatch */
6166 << 3 << Arg2->getType() << SizeTy;
6167
6168 return false;
6169}
6170
6171bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6172 if (checkArgCount(TheCall, 2))
6173 return true;
6174
6175 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6176 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6177 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6178 << 1 << 0 << TheCall->getSourceRange();
6179
6180 ExprResult OrigArg0 = TheCall->getArg(0);
6181 ExprResult OrigArg1 = TheCall->getArg(1);
6182
6183 // Do standard promotions between the two arguments, returning their common
6184 // type.
6185 QualType Res = UsualArithmeticConversions(
6186 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6187 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6188 return true;
6189
6190 // Make sure any conversions are pushed back into the call; this is
6191 // type safe since unordered compare builtins are declared as "_Bool
6192 // foo(...)".
6193 TheCall->setArg(0, OrigArg0.get());
6194 TheCall->setArg(1, OrigArg1.get());
6195
6196 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6197 return false;
6198
6199 // If the common type isn't a real floating type, then the arguments were
6200 // invalid for this operation.
6201 if (Res.isNull() || !Res->isRealFloatingType())
6202 return Diag(OrigArg0.get()->getBeginLoc(),
6203 diag::err_typecheck_call_invalid_ordered_compare)
6204 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6205 << SourceRange(OrigArg0.get()->getBeginLoc(),
6206 OrigArg1.get()->getEndLoc());
6207
6208 return false;
6209}
6210
6211bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6212 unsigned BuiltinID) {
6213 if (checkArgCount(TheCall, NumArgs))
6214 return true;
6215
6216 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6217 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6218 BuiltinID == Builtin::BI__builtin_isinf ||
6219 BuiltinID == Builtin::BI__builtin_isinf_sign))
6220 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6221 << 0 << 0 << TheCall->getSourceRange();
6222
6223 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6224 BuiltinID == Builtin::BI__builtin_isunordered))
6225 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6226 << 1 << 0 << TheCall->getSourceRange();
6227
6228 bool IsFPClass = NumArgs == 2;
6229
6230 // Find out position of floating-point argument.
6231 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6232
6233 // We can count on all parameters preceding the floating-point just being int.
6234 // Try all of those.
6235 for (unsigned i = 0; i < FPArgNo; ++i) {
6236 Expr *Arg = TheCall->getArg(i);
6237
6238 if (Arg->isTypeDependent())
6239 return false;
6240
6243
6244 if (Res.isInvalid())
6245 return true;
6246 TheCall->setArg(i, Res.get());
6247 }
6248
6249 Expr *OrigArg = TheCall->getArg(FPArgNo);
6250
6251 if (OrigArg->isTypeDependent())
6252 return false;
6253
6254 // Usual Unary Conversions will convert half to float, which we want for
6255 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6256 // type how it is, but do normal L->Rvalue conversions.
6257 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6258 ExprResult Res = UsualUnaryConversions(OrigArg);
6259
6260 if (!Res.isUsable())
6261 return true;
6262 OrigArg = Res.get();
6263 } else {
6265
6266 if (!Res.isUsable())
6267 return true;
6268 OrigArg = Res.get();
6269 }
6270 TheCall->setArg(FPArgNo, OrigArg);
6271
6272 QualType VectorResultTy;
6273 QualType ElementTy = OrigArg->getType();
6274 // TODO: When all classification function are implemented with is_fpclass,
6275 // vector argument can be supported in all of them.
6276 if (ElementTy->isVectorType() && IsFPClass) {
6277 VectorResultTy = GetSignedVectorType(ElementTy);
6278 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6279 }
6280
6281 // This operation requires a non-_Complex floating-point number.
6282 if (!ElementTy->isRealFloatingType())
6283 return Diag(OrigArg->getBeginLoc(),
6284 diag::err_typecheck_call_invalid_unary_fp)
6285 << OrigArg->getType() << OrigArg->getSourceRange();
6286
6287 // __builtin_isfpclass has integer parameter that specify test mask. It is
6288 // passed in (...), so it should be analyzed completely here.
6289 if (IsFPClass)
6290 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6291 return true;
6292
6293 // TODO: enable this code to all classification functions.
6294 if (IsFPClass) {
6295 QualType ResultTy;
6296 if (!VectorResultTy.isNull())
6297 ResultTy = VectorResultTy;
6298 else
6299 ResultTy = Context.IntTy;
6300 TheCall->setType(ResultTy);
6301 }
6302
6303 return false;
6304}
6305
6306bool Sema::BuiltinComplex(CallExpr *TheCall) {
6307 if (checkArgCount(TheCall, 2))
6308 return true;
6309
6310 bool Dependent = false;
6311 for (unsigned I = 0; I != 2; ++I) {
6312 Expr *Arg = TheCall->getArg(I);
6313 QualType T = Arg->getType();
6314 if (T->isDependentType()) {
6315 Dependent = true;
6316 continue;
6317 }
6318
6319 // Despite supporting _Complex int, GCC requires a real floating point type
6320 // for the operands of __builtin_complex.
6321 if (!T->isRealFloatingType()) {
6322 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6323 << Arg->getType() << Arg->getSourceRange();
6324 }
6325
6326 ExprResult Converted = DefaultLvalueConversion(Arg);
6327 if (Converted.isInvalid())
6328 return true;
6329 TheCall->setArg(I, Converted.get());
6330 }
6331
6332 if (Dependent) {
6333 TheCall->setType(Context.DependentTy);
6334 return false;
6335 }
6336
6337 Expr *Real = TheCall->getArg(0);
6338 Expr *Imag = TheCall->getArg(1);
6339 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6340 return Diag(Real->getBeginLoc(),
6341 diag::err_typecheck_call_different_arg_types)
6342 << Real->getType() << Imag->getType()
6343 << Real->getSourceRange() << Imag->getSourceRange();
6344 }
6345
6346 TheCall->setType(Context.getComplexType(Real->getType()));
6347 return false;
6348}
6349
6350/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6351// This is declared to take (...), so we have to check everything.
6353 unsigned NumArgs = TheCall->getNumArgs();
6354 if (NumArgs < 2)
6355 return ExprError(Diag(TheCall->getEndLoc(),
6356 diag::err_typecheck_call_too_few_args_at_least)
6357 << 0 /*function call*/ << 2 << NumArgs
6358 << /*is non object*/ 0 << TheCall->getSourceRange());
6359
6360 // Determine which of the following types of shufflevector we're checking:
6361 // 1) unary, vector mask: (lhs, mask)
6362 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6363 QualType ResType = TheCall->getArg(0)->getType();
6364 unsigned NumElements = 0;
6365
6366 if (!TheCall->getArg(0)->isTypeDependent() &&
6367 !TheCall->getArg(1)->isTypeDependent()) {
6368 QualType LHSType = TheCall->getArg(0)->getType();
6369 QualType RHSType = TheCall->getArg(1)->getType();
6370
6371 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6372 return ExprError(
6373 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6374 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6375 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6376 TheCall->getArg(1)->getEndLoc()));
6377
6378 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6379 unsigned NumResElements = NumArgs - 2;
6380
6381 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6382 // with mask. If so, verify that RHS is an integer vector type with the
6383 // same number of elts as lhs.
6384 if (NumArgs == 2) {
6385 if (!RHSType->hasIntegerRepresentation() ||
6386 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6387 return ExprError(Diag(TheCall->getBeginLoc(),
6388 diag::err_vec_builtin_incompatible_vector)
6389 << TheCall->getDirectCallee()
6390 << /*isMoreThanTwoArgs*/ false
6391 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6392 TheCall->getArg(1)->getEndLoc()));
6393 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6394 return ExprError(Diag(TheCall->getBeginLoc(),
6395 diag::err_vec_builtin_incompatible_vector)
6396 << TheCall->getDirectCallee()
6397 << /*isMoreThanTwoArgs*/ false
6398 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6399 TheCall->getArg(1)->getEndLoc()));
6400 } else if (NumElements != NumResElements) {
6401 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6402 ResType = ResType->isExtVectorType()
6403 ? Context.getExtVectorType(EltType, NumResElements)
6404 : Context.getVectorType(EltType, NumResElements,
6406 }
6407 }
6408
6409 for (unsigned I = 2; I != NumArgs; ++I) {
6410 Expr *Arg = TheCall->getArg(I);
6411 if (Arg->isTypeDependent() || Arg->isValueDependent())
6412 continue;
6413
6414 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6415 if (!Result)
6416 return ExprError(Diag(TheCall->getBeginLoc(),
6417 diag::err_shufflevector_nonconstant_argument)
6418 << Arg->getSourceRange());
6419
6420 // Allow -1 which will be translated to undef in the IR.
6421 if (Result->isSigned() && Result->isAllOnes())
6422 ;
6423 else if (Result->getActiveBits() > 64 ||
6424 Result->getZExtValue() >= NumElements * 2)
6425 return ExprError(Diag(TheCall->getBeginLoc(),
6426 diag::err_shufflevector_argument_too_large)
6427 << Arg->getSourceRange());
6428
6429 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6430 }
6431
6432 auto *Result = new (Context) ShuffleVectorExpr(
6433 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6434 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6435
6436 // All moved to Result.
6437 TheCall->shrinkNumArgs(0);
6438 return Result;
6439}
6440
6442 SourceLocation BuiltinLoc,
6443 SourceLocation RParenLoc) {
6446 QualType DstTy = TInfo->getType();
6447 QualType SrcTy = E->getType();
6448
6449 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6450 return ExprError(Diag(BuiltinLoc,
6451 diag::err_convertvector_non_vector)
6452 << E->getSourceRange());
6453 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6454 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6455 << "second"
6456 << "__builtin_convertvector");
6457
6458 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6459 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6460 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6461 if (SrcElts != DstElts)
6462 return ExprError(Diag(BuiltinLoc,
6463 diag::err_convertvector_incompatible_vector)
6464 << E->getSourceRange());
6465 }
6466
6467 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6468 RParenLoc, CurFPFeatureOverrides());
6469}
6470
6471bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6472 unsigned NumArgs = TheCall->getNumArgs();
6473
6474 if (NumArgs > 3)
6475 return Diag(TheCall->getEndLoc(),
6476 diag::err_typecheck_call_too_many_args_at_most)
6477 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6478 << TheCall->getSourceRange();
6479
6480 // Argument 0 is checked for us and the remaining arguments must be
6481 // constant integers.
6482 for (unsigned i = 1; i != NumArgs; ++i)
6483 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6484 return true;
6485
6486 return false;
6487}
6488
6489bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6490 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6491 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6492 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6493 if (checkArgCount(TheCall, 1))
6494 return true;
6495 Expr *Arg = TheCall->getArg(0);
6496 if (Arg->isInstantiationDependent())
6497 return false;
6498
6499 QualType ArgTy = Arg->getType();
6500 if (!ArgTy->hasFloatingRepresentation())
6501 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6502 << ArgTy;
6503 if (Arg->isLValue()) {
6504 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6505 TheCall->setArg(0, FirstArg.get());
6506 }
6507 TheCall->setType(TheCall->getArg(0)->getType());
6508 return false;
6509}
6510
6511bool Sema::BuiltinAssume(CallExpr *TheCall) {
6512 Expr *Arg = TheCall->getArg(0);
6513 if (Arg->isInstantiationDependent()) return false;
6514
6515 if (Arg->HasSideEffects(Context))
6516 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6517 << Arg->getSourceRange()
6518 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6519
6520 return false;
6521}
6522
6523bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6524 // The alignment must be a constant integer.
6525 Expr *Arg = TheCall->getArg(1);
6526
6527 // We can't check the value of a dependent argument.
6528 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6529 if (const auto *UE =
6530 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6531 if (UE->getKind() == UETT_AlignOf ||
6532 UE->getKind() == UETT_PreferredAlignOf)
6533 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6534 << Arg->getSourceRange();
6535
6536 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6537
6538 if (!Result.isPowerOf2())
6539 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6540 << Arg->getSourceRange();
6541
6542 if (Result < Context.getCharWidth())
6543 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6544 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6545
6546 if (Result > std::numeric_limits<int32_t>::max())
6547 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6548 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6549 }
6550
6551 return false;
6552}
6553
6554bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6555 if (checkArgCountRange(TheCall, 2, 3))
6556 return true;
6557
6558 unsigned NumArgs = TheCall->getNumArgs();
6559 Expr *FirstArg = TheCall->getArg(0);
6560
6561 {
6562 ExprResult FirstArgResult =
6564 if (!FirstArgResult.get()->getType()->isPointerType()) {
6565 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6566 << TheCall->getSourceRange();
6567 return true;
6568 }
6569 TheCall->setArg(0, FirstArgResult.get());
6570 }
6571
6572 // The alignment must be a constant integer.
6573 Expr *SecondArg = TheCall->getArg(1);
6574
6575 // We can't check the value of a dependent argument.
6576 if (!SecondArg->isValueDependent()) {
6577 llvm::APSInt Result;
6578 if (BuiltinConstantArg(TheCall, 1, Result))
6579 return true;
6580
6581 if (!Result.isPowerOf2())
6582 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6583 << SecondArg->getSourceRange();
6584
6586 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6587 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6588
6589 TheCall->setArg(1,
6591 }
6592
6593 if (NumArgs > 2) {
6594 Expr *ThirdArg = TheCall->getArg(2);
6595 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6596 return true;
6597 TheCall->setArg(2, ThirdArg);
6598 }
6599
6600 return false;
6601}
6602
6603bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6604 unsigned BuiltinID =
6605 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6606 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6607
6608 unsigned NumArgs = TheCall->getNumArgs();
6609 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6610 if (NumArgs < NumRequiredArgs) {
6611 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6612 << 0 /* function call */ << NumRequiredArgs << NumArgs
6613 << /*is non object*/ 0 << TheCall->getSourceRange();
6614 }
6615 if (NumArgs >= NumRequiredArgs + 0x100) {
6616 return Diag(TheCall->getEndLoc(),
6617 diag::err_typecheck_call_too_many_args_at_most)
6618 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6619 << /*is non object*/ 0 << TheCall->getSourceRange();
6620 }
6621 unsigned i = 0;
6622
6623 // For formatting call, check buffer arg.
6624 if (!IsSizeCall) {
6625 ExprResult Arg(TheCall->getArg(i));
6626 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6627 Context, Context.VoidPtrTy, false);
6628 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6629 if (Arg.isInvalid())
6630 return true;
6631 TheCall->setArg(i, Arg.get());
6632 i++;
6633 }
6634
6635 // Check string literal arg.
6636 unsigned FormatIdx = i;
6637 {
6638 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6639 if (Arg.isInvalid())
6640 return true;
6641 TheCall->setArg(i, Arg.get());
6642 i++;
6643 }
6644
6645 // Make sure variadic args are scalar.
6646 unsigned FirstDataArg = i;
6647 while (i < NumArgs) {
6649 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6650 if (Arg.isInvalid())
6651 return true;
6652 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6653 if (ArgSize.getQuantity() >= 0x100) {
6654 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6655 << i << (int)ArgSize.getQuantity() << 0xff
6656 << TheCall->getSourceRange();
6657 }
6658 TheCall->setArg(i, Arg.get());
6659 i++;
6660 }
6661
6662 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6663 // call to avoid duplicate diagnostics.
6664 if (!IsSizeCall) {
6665 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6666 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6667 bool Success = CheckFormatArguments(
6668 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6670 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6671 if (!Success)
6672 return true;
6673 }
6674
6675 if (IsSizeCall) {
6676 TheCall->setType(Context.getSizeType());
6677 } else {
6678 TheCall->setType(Context.VoidPtrTy);
6679 }
6680 return false;
6681}
6682
6683bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6684 llvm::APSInt &Result) {
6685 Expr *Arg = TheCall->getArg(ArgNum);
6686
6687 if (Arg->isTypeDependent() || Arg->isValueDependent())
6688 return false;
6689
6690 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6691 if (!R) {
6692 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6693 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6694 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6695 << FDecl->getDeclName() << Arg->getSourceRange();
6696 }
6697 Result = *R;
6698
6699 return false;
6700}
6701
6702bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6703 int High, bool RangeIsError) {
6705 return false;
6706 llvm::APSInt Result;
6707
6708 // We can't check the value of a dependent argument.
6709 Expr *Arg = TheCall->getArg(ArgNum);
6710 if (Arg->isTypeDependent() || Arg->isValueDependent())
6711 return false;
6712
6713 // Check constant-ness first.
6714 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6715 return true;
6716
6717 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6718 if (RangeIsError)
6719 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6720 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6721 else
6722 // Defer the warning until we know if the code will be emitted so that
6723 // dead code can ignore this.
6724 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6725 PDiag(diag::warn_argument_invalid_range)
6726 << toString(Result, 10) << Low << High
6727 << Arg->getSourceRange());
6728 }
6729
6730 return false;
6731}
6732
6733bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6734 unsigned Num) {
6735 llvm::APSInt Result;
6736
6737 // We can't check the value of a dependent argument.
6738 Expr *Arg = TheCall->getArg(ArgNum);
6739 if (Arg->isTypeDependent() || Arg->isValueDependent())
6740 return false;
6741
6742 // Check constant-ness first.
6743 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6744 return true;
6745
6746 if (Result.getSExtValue() % Num != 0)
6747 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6748 << Num << Arg->getSourceRange();
6749
6750 return false;
6751}
6752
6753bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6754 llvm::APSInt Result;
6755
6756 // We can't check the value of a dependent argument.
6757 Expr *Arg = TheCall->getArg(ArgNum);
6758 if (Arg->isTypeDependent() || Arg->isValueDependent())
6759 return false;
6760
6761 // Check constant-ness first.
6762 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6763 return true;
6764
6765 if (Result.isPowerOf2())
6766 return false;
6767
6768 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6769 << Arg->getSourceRange();
6770}
6771
6772static bool IsShiftedByte(llvm::APSInt Value) {
6773 if (Value.isNegative())
6774 return false;
6775
6776 // Check if it's a shifted byte, by shifting it down
6777 while (true) {
6778 // If the value fits in the bottom byte, the check passes.
6779 if (Value < 0x100)
6780 return true;
6781
6782 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6783 // fails.
6784 if ((Value & 0xFF) != 0)
6785 return false;
6786
6787 // If the bottom 8 bits are all 0, but something above that is nonzero,
6788 // then shifting the value right by 8 bits won't affect whether it's a
6789 // shifted byte or not. So do that, and go round again.
6790 Value >>= 8;
6791 }
6792}
6793
6794bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6795 unsigned ArgBits) {
6796 llvm::APSInt Result;
6797
6798 // We can't check the value of a dependent argument.
6799 Expr *Arg = TheCall->getArg(ArgNum);
6800 if (Arg->isTypeDependent() || Arg->isValueDependent())
6801 return false;
6802
6803 // Check constant-ness first.
6804 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6805 return true;
6806
6807 // Truncate to the given size.
6808 Result = Result.getLoBits(ArgBits);
6809 Result.setIsUnsigned(true);
6810
6811 if (IsShiftedByte(Result))
6812 return false;
6813
6814 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6815 << Arg->getSourceRange();
6816}
6817
6819 unsigned ArgNum,
6820 unsigned ArgBits) {
6821 llvm::APSInt Result;
6822
6823 // We can't check the value of a dependent argument.
6824 Expr *Arg = TheCall->getArg(ArgNum);
6825 if (Arg->isTypeDependent() || Arg->isValueDependent())
6826 return false;
6827
6828 // Check constant-ness first.
6829 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6830 return true;
6831
6832 // Truncate to the given size.
6833 Result = Result.getLoBits(ArgBits);
6834 Result.setIsUnsigned(true);
6835
6836 // Check to see if it's in either of the required forms.
6837 if (IsShiftedByte(Result) ||
6838 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6839 return false;
6840
6841 return Diag(TheCall->getBeginLoc(),
6842 diag::err_argument_not_shifted_byte_or_xxff)
6843 << Arg->getSourceRange();
6844}
6845
6846bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6847 if (!Context.getTargetInfo().hasSjLjLowering())
6848 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6849 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6850
6851 Expr *Arg = TheCall->getArg(1);
6852 llvm::APSInt Result;
6853
6854 // TODO: This is less than ideal. Overload this to take a value.
6855 if (BuiltinConstantArg(TheCall, 1, Result))
6856 return true;
6857
6858 if (Result != 1)
6859 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6860 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6861
6862 return false;
6863}
6864
6865bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6866 if (!Context.getTargetInfo().hasSjLjLowering())
6867 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6868 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6869 return false;
6870}
6871
6872bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6873 if (checkArgCount(TheCall, 1))
6874 return true;
6875
6876 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6877 if (ArgRes.isInvalid())
6878 return true;
6879
6880 // For simplicity, we support only limited expressions for the argument.
6881 // Specifically a flexible array member or a pointer with counted_by:
6882 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6883 // complex casting, which really shouldn't be a huge problem.
6884 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6885 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6886 return Diag(Arg->getBeginLoc(),
6887 diag::err_builtin_counted_by_ref_invalid_arg)
6888 << Arg->getSourceRange();
6889
6890 if (Arg->HasSideEffects(Context))
6891 return Diag(Arg->getBeginLoc(),
6892 diag::err_builtin_counted_by_ref_has_side_effects)
6893 << Arg->getSourceRange();
6894
6895 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6896 const auto *CATy =
6897 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6898
6899 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6900 // Member has counted_by attribute - return pointer to count field
6901 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6902 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6903 TheCall->setType(Context.getPointerType(CountFD->getType()));
6904 return false;
6905 }
6906 }
6907
6908 // FAMs and pointers without counted_by return void*
6909 QualType MemberTy = ME->getMemberDecl()->getType();
6910 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6911 return Diag(Arg->getBeginLoc(),
6912 diag::err_builtin_counted_by_ref_invalid_arg)
6913 << Arg->getSourceRange();
6914 } else {
6915 return Diag(Arg->getBeginLoc(),
6916 diag::err_builtin_counted_by_ref_invalid_arg)
6917 << Arg->getSourceRange();
6918 }
6919
6920 TheCall->setType(Context.getPointerType(Context.VoidTy));
6921 return false;
6922}
6923
6924/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6925/// It allows leaking and modification of bounds safety information.
6926bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6928 const CallExpr *CE =
6929 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6930 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6931 return false;
6932
6933 switch (K) {
6936 Diag(E->getExprLoc(),
6937 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6938 << 0 << E->getSourceRange();
6939 break;
6941 Diag(E->getExprLoc(),
6942 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6943 << 1 << E->getSourceRange();
6944 break;
6946 Diag(E->getExprLoc(),
6947 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6948 << 2 << E->getSourceRange();
6949 break;
6951 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6952 << 0 << E->getSourceRange();
6953 break;
6955 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6956 << 1 << E->getSourceRange();
6957 break;
6958 }
6959
6960 return true;
6961}
6962
6963namespace {
6964
6965class UncoveredArgHandler {
6966 enum { Unknown = -1, AllCovered = -2 };
6967
6968 signed FirstUncoveredArg = Unknown;
6969 SmallVector<const Expr *, 4> DiagnosticExprs;
6970
6971public:
6972 UncoveredArgHandler() = default;
6973
6974 bool hasUncoveredArg() const {
6975 return (FirstUncoveredArg >= 0);
6976 }
6977
6978 unsigned getUncoveredArg() const {
6979 assert(hasUncoveredArg() && "no uncovered argument");
6980 return FirstUncoveredArg;
6981 }
6982
6983 void setAllCovered() {
6984 // A string has been found with all arguments covered, so clear out
6985 // the diagnostics.
6986 DiagnosticExprs.clear();
6987 FirstUncoveredArg = AllCovered;
6988 }
6989
6990 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6991 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6992
6993 // Don't update if a previous string covers all arguments.
6994 if (FirstUncoveredArg == AllCovered)
6995 return;
6996
6997 // UncoveredArgHandler tracks the highest uncovered argument index
6998 // and with it all the strings that match this index.
6999 if (NewFirstUncoveredArg == FirstUncoveredArg)
7000 DiagnosticExprs.push_back(StrExpr);
7001 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7002 DiagnosticExprs.clear();
7003 DiagnosticExprs.push_back(StrExpr);
7004 FirstUncoveredArg = NewFirstUncoveredArg;
7005 }
7006 }
7007
7008 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7009};
7010
7011enum StringLiteralCheckType {
7012 SLCT_NotALiteral,
7013 SLCT_UncheckedLiteral,
7014 SLCT_CheckedLiteral
7015};
7016
7017} // namespace
7018
7019static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7020 BinaryOperatorKind BinOpKind,
7021 bool AddendIsRight) {
7022 unsigned BitWidth = Offset.getBitWidth();
7023 unsigned AddendBitWidth = Addend.getBitWidth();
7024 // There might be negative interim results.
7025 if (Addend.isUnsigned()) {
7026 Addend = Addend.zext(++AddendBitWidth);
7027 Addend.setIsSigned(true);
7028 }
7029 // Adjust the bit width of the APSInts.
7030 if (AddendBitWidth > BitWidth) {
7031 Offset = Offset.sext(AddendBitWidth);
7032 BitWidth = AddendBitWidth;
7033 } else if (BitWidth > AddendBitWidth) {
7034 Addend = Addend.sext(BitWidth);
7035 }
7036
7037 bool Ov = false;
7038 llvm::APSInt ResOffset = Offset;
7039 if (BinOpKind == BO_Add)
7040 ResOffset = Offset.sadd_ov(Addend, Ov);
7041 else {
7042 assert(AddendIsRight && BinOpKind == BO_Sub &&
7043 "operator must be add or sub with addend on the right");
7044 ResOffset = Offset.ssub_ov(Addend, Ov);
7045 }
7046
7047 // We add an offset to a pointer here so we should support an offset as big as
7048 // possible.
7049 if (Ov) {
7050 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7051 "index (intermediate) result too big");
7052 Offset = Offset.sext(2 * BitWidth);
7053 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7054 return;
7055 }
7056
7057 Offset = std::move(ResOffset);
7058}
7059
7060namespace {
7061
7062// This is a wrapper class around StringLiteral to support offsetted string
7063// literals as format strings. It takes the offset into account when returning
7064// the string and its length or the source locations to display notes correctly.
7065class FormatStringLiteral {
7066 const StringLiteral *FExpr;
7067 int64_t Offset;
7068
7069public:
7070 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7071 : FExpr(fexpr), Offset(Offset) {}
7072
7073 const StringLiteral *getFormatString() const { return FExpr; }
7074
7075 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7076
7077 unsigned getByteLength() const {
7078 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7079 }
7080
7081 unsigned getLength() const { return FExpr->getLength() - Offset; }
7082 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7083
7084 StringLiteralKind getKind() const { return FExpr->getKind(); }
7085
7086 QualType getType() const { return FExpr->getType(); }
7087
7088 bool isAscii() const { return FExpr->isOrdinary(); }
7089 bool isWide() const { return FExpr->isWide(); }
7090 bool isUTF8() const { return FExpr->isUTF8(); }
7091 bool isUTF16() const { return FExpr->isUTF16(); }
7092 bool isUTF32() const { return FExpr->isUTF32(); }
7093 bool isPascal() const { return FExpr->isPascal(); }
7094
7095 SourceLocation getLocationOfByte(
7096 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7097 const TargetInfo &Target, unsigned *StartToken = nullptr,
7098 unsigned *StartTokenByteOffset = nullptr) const {
7099 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7100 StartToken, StartTokenByteOffset);
7101 }
7102
7103 SourceLocation getBeginLoc() const LLVM_READONLY {
7104 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7105 }
7106
7107 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7108};
7109
7110} // namespace
7111
7112static void CheckFormatString(
7113 Sema &S, const FormatStringLiteral *FExpr,
7114 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7116 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7117 bool inFunctionCall, VariadicCallType CallType,
7118 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7119 bool IgnoreStringsWithoutSpecifiers);
7120
7121static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7122 const Expr *E);
7123
7124// Determine if an expression is a string literal or constant string.
7125// If this function returns false on the arguments to a function expecting a
7126// format string, we will usually need to emit a warning.
7127// True string literals are then checked by CheckFormatString.
7128static StringLiteralCheckType
7129checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7130 const Expr *E, ArrayRef<const Expr *> Args,
7131 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7132 unsigned firstDataArg, FormatStringType Type,
7133 VariadicCallType CallType, bool InFunctionCall,
7134 llvm::SmallBitVector &CheckedVarArgs,
7135 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7136 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7137 bool IgnoreStringsWithoutSpecifiers = false) {
7139 return SLCT_NotALiteral;
7140tryAgain:
7141 assert(Offset.isSigned() && "invalid offset");
7142
7143 if (E->isTypeDependent() || E->isValueDependent())
7144 return SLCT_NotALiteral;
7145
7146 E = E->IgnoreParenCasts();
7147
7149 // Technically -Wformat-nonliteral does not warn about this case.
7150 // The behavior of printf and friends in this case is implementation
7151 // dependent. Ideally if the format string cannot be null then
7152 // it should have a 'nonnull' attribute in the function prototype.
7153 return SLCT_UncheckedLiteral;
7154
7155 switch (E->getStmtClass()) {
7156 case Stmt::InitListExprClass:
7157 // Handle expressions like {"foobar"}.
7158 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7159 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7160 format_idx, firstDataArg, Type, CallType,
7161 /*InFunctionCall*/ false, CheckedVarArgs,
7162 UncoveredArg, Offset, CallerFormatParamIdx,
7163 IgnoreStringsWithoutSpecifiers);
7164 }
7165 return SLCT_NotALiteral;
7166 case Stmt::BinaryConditionalOperatorClass:
7167 case Stmt::ConditionalOperatorClass: {
7168 // The expression is a literal if both sub-expressions were, and it was
7169 // completely checked only if both sub-expressions were checked.
7172
7173 // Determine whether it is necessary to check both sub-expressions, for
7174 // example, because the condition expression is a constant that can be
7175 // evaluated at compile time.
7176 bool CheckLeft = true, CheckRight = true;
7177
7178 bool Cond;
7179 if (C->getCond()->EvaluateAsBooleanCondition(
7181 if (Cond)
7182 CheckRight = false;
7183 else
7184 CheckLeft = false;
7185 }
7186
7187 // We need to maintain the offsets for the right and the left hand side
7188 // separately to check if every possible indexed expression is a valid
7189 // string literal. They might have different offsets for different string
7190 // literals in the end.
7191 StringLiteralCheckType Left;
7192 if (!CheckLeft)
7193 Left = SLCT_UncheckedLiteral;
7194 else {
7195 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7196 Args, APK, format_idx, firstDataArg, Type,
7197 CallType, InFunctionCall, CheckedVarArgs,
7198 UncoveredArg, Offset, CallerFormatParamIdx,
7199 IgnoreStringsWithoutSpecifiers);
7200 if (Left == SLCT_NotALiteral || !CheckRight) {
7201 return Left;
7202 }
7203 }
7204
7205 StringLiteralCheckType Right = checkFormatStringExpr(
7206 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7207 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7208 UncoveredArg, Offset, CallerFormatParamIdx,
7209 IgnoreStringsWithoutSpecifiers);
7210
7211 return (CheckLeft && Left < Right) ? Left : Right;
7212 }
7213
7214 case Stmt::ImplicitCastExprClass:
7215 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7216 goto tryAgain;
7217
7218 case Stmt::OpaqueValueExprClass:
7219 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7220 E = src;
7221 goto tryAgain;
7222 }
7223 return SLCT_NotALiteral;
7224
7225 case Stmt::PredefinedExprClass:
7226 // While __func__, etc., are technically not string literals, they
7227 // cannot contain format specifiers and thus are not a security
7228 // liability.
7229 return SLCT_UncheckedLiteral;
7230
7231 case Stmt::DeclRefExprClass: {
7232 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7233
7234 // As an exception, do not flag errors for variables binding to
7235 // const string literals.
7236 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7237 bool isConstant = false;
7238 QualType T = DR->getType();
7239
7240 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7241 isConstant = AT->getElementType().isConstant(S.Context);
7242 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7243 isConstant = T.isConstant(S.Context) &&
7244 PT->getPointeeType().isConstant(S.Context);
7245 } else if (T->isObjCObjectPointerType()) {
7246 // In ObjC, there is usually no "const ObjectPointer" type,
7247 // so don't check if the pointee type is constant.
7248 isConstant = T.isConstant(S.Context);
7249 }
7250
7251 if (isConstant) {
7252 if (const Expr *Init = VD->getAnyInitializer()) {
7253 // Look through initializers like const char c[] = { "foo" }
7254 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7255 if (InitList->isStringLiteralInit())
7256 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7257 }
7258 return checkFormatStringExpr(
7259 S, ReferenceFormatString, Init, Args, APK, format_idx,
7260 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7261 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7262 }
7263 }
7264
7265 // When the format argument is an argument of this function, and this
7266 // function also has the format attribute, there are several interactions
7267 // for which there shouldn't be a warning. For instance, when calling
7268 // v*printf from a function that has the printf format attribute, we
7269 // should not emit a warning about using `fmt`, even though it's not
7270 // constant, because the arguments have already been checked for the
7271 // caller of `logmessage`:
7272 //
7273 // __attribute__((format(printf, 1, 2)))
7274 // void logmessage(char const *fmt, ...) {
7275 // va_list ap;
7276 // va_start(ap, fmt);
7277 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7278 // ...
7279 // }
7280 //
7281 // Another interaction that we need to support is using a format string
7282 // specified by the format_matches attribute:
7283 //
7284 // __attribute__((format_matches(printf, 1, "%s %d")))
7285 // void logmessage(char const *fmt, const char *a, int b) {
7286 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7287 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7288 // ...
7289 // }
7290 //
7291 // Yet another interaction that we need to support is calling a variadic
7292 // format function from a format function that has fixed arguments. For
7293 // instance:
7294 //
7295 // __attribute__((format(printf, 1, 2)))
7296 // void logstring(char const *fmt, char const *str) {
7297 // printf(fmt, str); /* do not emit a warning about "fmt" */
7298 // }
7299 //
7300 // Same (and perhaps more relatably) for the variadic template case:
7301 //
7302 // template<typename... Args>
7303 // __attribute__((format(printf, 1, 2)))
7304 // void log(const char *fmt, Args&&... args) {
7305 // printf(fmt, forward<Args>(args)...);
7306 // /* do not emit a warning about "fmt" */
7307 // }
7308 //
7309 // Due to implementation difficulty, we only check the format, not the
7310 // format arguments, in all cases.
7311 //
7312 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7313 if (CallerFormatParamIdx)
7314 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7315 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7316 for (const auto *PVFormatMatches :
7317 D->specific_attrs<FormatMatchesAttr>()) {
7318 Sema::FormatStringInfo CalleeFSI;
7319 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7320 0, &CalleeFSI))
7321 continue;
7322 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7323 // If using the wrong type of format string, emit a diagnostic
7324 // here and stop checking to avoid irrelevant diagnostics.
7325 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7326 S.Diag(Args[format_idx]->getBeginLoc(),
7327 diag::warn_format_string_type_incompatible)
7328 << PVFormatMatches->getType()->getName()
7330 if (!InFunctionCall) {
7331 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7332 diag::note_format_string_defined);
7333 }
7334 return SLCT_UncheckedLiteral;
7335 }
7336 return checkFormatStringExpr(
7337 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7338 Args, APK, format_idx, firstDataArg, Type, CallType,
7339 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7340 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7341 }
7342 }
7343
7344 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7345 Sema::FormatStringInfo CallerFSI;
7346 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7347 PVFormat->getFirstArg(), &CallerFSI))
7348 continue;
7349 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7350 // We also check if the formats are compatible.
7351 // We can't pass a 'scanf' string to a 'printf' function.
7352 if (Type != S.GetFormatStringType(PVFormat)) {
7353 S.Diag(Args[format_idx]->getBeginLoc(),
7354 diag::warn_format_string_type_incompatible)
7355 << PVFormat->getType()->getName()
7357 if (!InFunctionCall) {
7358 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7359 }
7360 return SLCT_UncheckedLiteral;
7361 }
7362 // Lastly, check that argument passing kinds transition in a
7363 // way that makes sense:
7364 // from a caller with FAPK_VAList, allow FAPK_VAList
7365 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7366 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7367 // from a caller with FAPK_Variadic, allow FAPK_VAList
7368 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7373 return SLCT_UncheckedLiteral;
7374 }
7375 }
7376 }
7377 }
7378 }
7379 }
7380
7381 return SLCT_NotALiteral;
7382 }
7383
7384 case Stmt::CallExprClass:
7385 case Stmt::CXXMemberCallExprClass: {
7386 const CallExpr *CE = cast<CallExpr>(E);
7387 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7388 bool IsFirst = true;
7389 StringLiteralCheckType CommonResult;
7390 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7391 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7392 StringLiteralCheckType Result = checkFormatStringExpr(
7393 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7394 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7395 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7396 if (IsFirst) {
7397 CommonResult = Result;
7398 IsFirst = false;
7399 }
7400 }
7401 if (!IsFirst)
7402 return CommonResult;
7403
7404 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7405 unsigned BuiltinID = FD->getBuiltinID();
7406 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7407 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7408 const Expr *Arg = CE->getArg(0);
7409 return checkFormatStringExpr(
7410 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7411 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7412 UncoveredArg, Offset, CallerFormatParamIdx,
7413 IgnoreStringsWithoutSpecifiers);
7414 }
7415 }
7416 }
7417 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7418 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7419 format_idx, firstDataArg, Type, CallType,
7420 /*InFunctionCall*/ false, CheckedVarArgs,
7421 UncoveredArg, Offset, CallerFormatParamIdx,
7422 IgnoreStringsWithoutSpecifiers);
7423 return SLCT_NotALiteral;
7424 }
7425 case Stmt::ObjCMessageExprClass: {
7426 const auto *ME = cast<ObjCMessageExpr>(E);
7427 if (const auto *MD = ME->getMethodDecl()) {
7428 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7429 // As a special case heuristic, if we're using the method -[NSBundle
7430 // localizedStringForKey:value:table:], ignore any key strings that lack
7431 // format specifiers. The idea is that if the key doesn't have any
7432 // format specifiers then its probably just a key to map to the
7433 // localized strings. If it does have format specifiers though, then its
7434 // likely that the text of the key is the format string in the
7435 // programmer's language, and should be checked.
7436 const ObjCInterfaceDecl *IFace;
7437 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7438 IFace->getIdentifier()->isStr("NSBundle") &&
7439 MD->getSelector().isKeywordSelector(
7440 {"localizedStringForKey", "value", "table"})) {
7441 IgnoreStringsWithoutSpecifiers = true;
7442 }
7443
7444 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7445 return checkFormatStringExpr(
7446 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7447 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7448 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7449 }
7450 }
7451
7452 return SLCT_NotALiteral;
7453 }
7454 case Stmt::ObjCStringLiteralClass:
7455 case Stmt::StringLiteralClass: {
7456 const StringLiteral *StrE = nullptr;
7457
7458 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7459 StrE = ObjCFExpr->getString();
7460 else
7461 StrE = cast<StringLiteral>(E);
7462
7463 if (StrE) {
7464 if (Offset.isNegative() || Offset > StrE->getLength()) {
7465 // TODO: It would be better to have an explicit warning for out of
7466 // bounds literals.
7467 return SLCT_NotALiteral;
7468 }
7469 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7470 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7471 format_idx, firstDataArg, Type, InFunctionCall,
7472 CallType, CheckedVarArgs, UncoveredArg,
7473 IgnoreStringsWithoutSpecifiers);
7474 return SLCT_CheckedLiteral;
7475 }
7476
7477 return SLCT_NotALiteral;
7478 }
7479 case Stmt::BinaryOperatorClass: {
7480 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7481
7482 // A string literal + an int offset is still a string literal.
7483 if (BinOp->isAdditiveOp()) {
7484 Expr::EvalResult LResult, RResult;
7485
7486 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7487 LResult, S.Context, Expr::SE_NoSideEffects,
7489 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7490 RResult, S.Context, Expr::SE_NoSideEffects,
7492
7493 if (LIsInt != RIsInt) {
7494 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7495
7496 if (LIsInt) {
7497 if (BinOpKind == BO_Add) {
7498 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7499 E = BinOp->getRHS();
7500 goto tryAgain;
7501 }
7502 } else {
7503 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7504 E = BinOp->getLHS();
7505 goto tryAgain;
7506 }
7507 }
7508 }
7509
7510 return SLCT_NotALiteral;
7511 }
7512 case Stmt::UnaryOperatorClass: {
7513 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7514 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7515 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7516 Expr::EvalResult IndexResult;
7517 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7520 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7521 /*RHS is int*/ true);
7522 E = ASE->getBase();
7523 goto tryAgain;
7524 }
7525 }
7526
7527 return SLCT_NotALiteral;
7528 }
7529
7530 default:
7531 return SLCT_NotALiteral;
7532 }
7533}
7534
7535// If this expression can be evaluated at compile-time,
7536// check if the result is a StringLiteral and return it
7537// otherwise return nullptr
7539 const Expr *E) {
7541 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7542 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7543 if (isa_and_nonnull<StringLiteral>(LVE))
7544 return LVE;
7545 }
7546 return nullptr;
7547}
7548
7550 switch (FST) {
7552 return "scanf";
7554 return "printf";
7556 return "NSString";
7558 return "strftime";
7560 return "strfmon";
7562 return "kprintf";
7564 return "freebsd_kprintf";
7566 return "os_log";
7567 default:
7568 return "<unknown>";
7569 }
7570}
7571
7573 return llvm::StringSwitch<FormatStringType>(Flavor)
7574 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7575 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7577 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7578 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7579 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7580 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7582 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7583 .Case("os_trace", FormatStringType::OSLog)
7584 .Case("os_log", FormatStringType::OSLog)
7585 .Default(FormatStringType::Unknown);
7586}
7587
7589 return GetFormatStringType(Format->getType()->getName());
7590}
7591
7592FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7593 return GetFormatStringType(Format->getType()->getName());
7594}
7595
7596bool Sema::CheckFormatArguments(const FormatAttr *Format,
7597 ArrayRef<const Expr *> Args, bool IsCXXMember,
7598 VariadicCallType CallType, SourceLocation Loc,
7599 SourceRange Range,
7600 llvm::SmallBitVector &CheckedVarArgs) {
7601 FormatStringInfo FSI;
7602 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7603 IsCXXMember,
7604 CallType != VariadicCallType::DoesNotApply, &FSI))
7605 return CheckFormatArguments(
7606 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7607 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7608 return false;
7609}
7610
7611bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7612 ArrayRef<const Expr *> Args, bool IsCXXMember,
7613 VariadicCallType CallType, SourceLocation Loc,
7614 SourceRange Range,
7615 llvm::SmallBitVector &CheckedVarArgs) {
7616 FormatStringInfo FSI;
7617 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7618 &FSI)) {
7619 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7620 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7621 Format->getFormatString(), FSI.FormatIdx,
7622 FSI.FirstDataArg, GetFormatStringType(Format),
7623 CallType, Loc, Range, CheckedVarArgs);
7624 }
7625 return false;
7626}
7627
7630 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7631 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7632 SourceLocation Loc) {
7633 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7634 return false;
7635
7636 DeclContext *DC = S->CurContext;
7637 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7638 return false;
7639 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7640
7641 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7642
7643 // Find the offset to convert between attribute and parameter indexes.
7644 unsigned CallerArgumentIndexOffset =
7645 hasImplicitObjectParameter(Caller) ? 2 : 1;
7646
7647 unsigned FirstArgumentIndex = -1;
7648 switch (APK) {
7651 // As an extension, clang allows the format attribute on non-variadic
7652 // functions.
7653 // Caller must have fixed arguments to pass them to a fixed or variadic
7654 // function. Try to match caller and callee arguments. If successful, then
7655 // emit a diag with the caller idx, otherwise we can't determine the callee
7656 // arguments.
7657 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7658 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7659 // There aren't enough arguments in the caller to pass to callee.
7660 return false;
7661 }
7662 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7663 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7664 const auto *Arg =
7665 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7666 if (!Arg)
7667 return false;
7668 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7669 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7670 return false;
7671 }
7672 FirstArgumentIndex =
7673 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7674 break;
7675 }
7677 // Caller arguments are either variadic or a va_list.
7678 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7679 ? (NumCallerParams + CallerArgumentIndexOffset)
7680 : 0;
7681 break;
7683 // The callee has a format_matches attribute. We will emit that instead.
7684 if (!ReferenceFormatString)
7685 return false;
7686 break;
7687 }
7688
7689 // Emit the diagnostic and fixit.
7690 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7691 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7692 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7693 do {
7694 std::string Attr, Fixit;
7695 llvm::raw_string_ostream AttrOS(Attr);
7697 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7698 << FirstArgumentIndex << ")";
7699 } else {
7700 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7701 << ", \"";
7702 AttrOS.write_escaped(ReferenceFormatString->getString());
7703 AttrOS << "\")";
7704 }
7705 AttrOS.flush();
7706 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7707 if (ND)
7708 DB << ND;
7709 else
7710 DB << "block";
7711
7712 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7713 if (isa<BlockDecl>(Caller))
7714 break;
7715
7716 SourceLocation SL;
7717 llvm::raw_string_ostream IS(Fixit);
7718 // The attribute goes at the start of the declaration in C/C++ functions
7719 // and methods, but after the declaration for Objective-C methods.
7720 if (isa<ObjCMethodDecl>(Caller)) {
7721 IS << ' ';
7722 SL = Caller->getEndLoc();
7723 }
7724 const LangOptions &LO = S->getLangOpts();
7725 if (LO.C23 || LO.CPlusPlus11)
7726 IS << "[[gnu::" << Attr << "]]";
7727 else if (LO.ObjC || LO.GNUMode)
7728 IS << "__attribute__((" << Attr << "))";
7729 else
7730 break;
7731 if (!isa<ObjCMethodDecl>(Caller)) {
7732 IS << ' ';
7733 SL = Caller->getBeginLoc();
7734 }
7735 IS.flush();
7736
7737 DB << FixItHint::CreateInsertion(SL, Fixit);
7738 } while (false);
7739
7740 // Add implicit format or format_matches attribute.
7742 Caller->addAttr(FormatAttr::CreateImplicit(
7743 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7744 FormatStringIndex, FirstArgumentIndex));
7745 } else {
7746 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7747 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7748 FormatStringIndex, ReferenceFormatString));
7749 }
7750
7751 {
7752 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7753 if (ND)
7754 DB << ND;
7755 else
7756 DB << "block";
7757 }
7758 return true;
7759}
7760
7761bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7763 StringLiteral *ReferenceFormatString,
7764 unsigned format_idx, unsigned firstDataArg,
7766 VariadicCallType CallType, SourceLocation Loc,
7767 SourceRange Range,
7768 llvm::SmallBitVector &CheckedVarArgs) {
7769 // CHECK: printf/scanf-like function is called with no format string.
7770 if (format_idx >= Args.size()) {
7771 Diag(Loc, diag::warn_missing_format_string) << Range;
7772 return false;
7773 }
7774
7775 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7776
7777 // CHECK: format string is not a string literal.
7778 //
7779 // Dynamically generated format strings are difficult to
7780 // automatically vet at compile time. Requiring that format strings
7781 // are string literals: (1) permits the checking of format strings by
7782 // the compiler and thereby (2) can practically remove the source of
7783 // many format string exploits.
7784
7785 // Format string can be either ObjC string (e.g. @"%d") or
7786 // C string (e.g. "%d")
7787 // ObjC string uses the same format specifiers as C string, so we can use
7788 // the same format string checking logic for both ObjC and C strings.
7789 UncoveredArgHandler UncoveredArg;
7790 std::optional<unsigned> CallerParamIdx;
7791 StringLiteralCheckType CT = checkFormatStringExpr(
7792 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7793 firstDataArg, Type, CallType,
7794 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7795 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7796
7797 // Generate a diagnostic where an uncovered argument is detected.
7798 if (UncoveredArg.hasUncoveredArg()) {
7799 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7800 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7801 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7802 }
7803
7804 if (CT != SLCT_NotALiteral)
7805 // Literal format string found, check done!
7806 return CT == SLCT_CheckedLiteral;
7807
7808 // Do not emit diag when the string param is a macro expansion and the
7809 // format is either NSString or CFString. This is a hack to prevent
7810 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7811 // which are usually used in place of NS and CF string literals.
7812 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7814 SourceMgr.isInSystemMacro(FormatLoc))
7815 return false;
7816
7817 if (CallerParamIdx && CheckMissingFormatAttribute(
7818 this, Args, APK, ReferenceFormatString, format_idx,
7819 firstDataArg, Type, *CallerParamIdx, Loc))
7820 return false;
7821
7822 // Strftime is particular as it always uses a single 'time' argument,
7823 // so it is safe to pass a non-literal string.
7825 return false;
7826
7827 // If there are no arguments specified, warn with -Wformat-security, otherwise
7828 // warn only with -Wformat-nonliteral.
7829 if (Args.size() == firstDataArg) {
7830 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7831 << OrigFormatExpr->getSourceRange();
7832 switch (Type) {
7833 default:
7834 break;
7838 Diag(FormatLoc, diag::note_format_security_fixit)
7839 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7840 break;
7842 Diag(FormatLoc, diag::note_format_security_fixit)
7843 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7844 break;
7845 }
7846 } else {
7847 Diag(FormatLoc, diag::warn_format_nonliteral)
7848 << OrigFormatExpr->getSourceRange();
7849 }
7850 return false;
7851}
7852
7853namespace {
7854
7855class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7856protected:
7857 Sema &S;
7858 const FormatStringLiteral *FExpr;
7859 const Expr *OrigFormatExpr;
7860 const FormatStringType FSType;
7861 const unsigned FirstDataArg;
7862 const unsigned NumDataArgs;
7863 const char *Beg; // Start of format string.
7864 const Sema::FormatArgumentPassingKind ArgPassingKind;
7865 ArrayRef<const Expr *> Args;
7866 unsigned FormatIdx;
7867 llvm::SmallBitVector CoveredArgs;
7868 bool usesPositionalArgs = false;
7869 bool atFirstArg = true;
7870 bool inFunctionCall;
7871 VariadicCallType CallType;
7872 llvm::SmallBitVector &CheckedVarArgs;
7873 UncoveredArgHandler &UncoveredArg;
7874
7875public:
7876 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7877 const Expr *origFormatExpr, const FormatStringType type,
7878 unsigned firstDataArg, unsigned numDataArgs,
7879 const char *beg, Sema::FormatArgumentPassingKind APK,
7880 ArrayRef<const Expr *> Args, unsigned formatIdx,
7881 bool inFunctionCall, VariadicCallType callType,
7882 llvm::SmallBitVector &CheckedVarArgs,
7883 UncoveredArgHandler &UncoveredArg)
7884 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7885 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7886 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7887 inFunctionCall(inFunctionCall), CallType(callType),
7888 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7889 CoveredArgs.resize(numDataArgs);
7890 CoveredArgs.reset();
7891 }
7892
7893 bool HasFormatArguments() const {
7894 return ArgPassingKind == Sema::FAPK_Fixed ||
7895 ArgPassingKind == Sema::FAPK_Variadic;
7896 }
7897
7898 void DoneProcessing();
7899
7900 void HandleIncompleteSpecifier(const char *startSpecifier,
7901 unsigned specifierLen) override;
7902
7903 void HandleInvalidLengthModifier(
7904 const analyze_format_string::FormatSpecifier &FS,
7905 const analyze_format_string::ConversionSpecifier &CS,
7906 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
7907
7908 void HandleNonStandardLengthModifier(
7909 const analyze_format_string::FormatSpecifier &FS,
7910 const char *startSpecifier, unsigned specifierLen);
7911
7912 void HandleNonStandardConversionSpecifier(
7913 const analyze_format_string::ConversionSpecifier &CS,
7914 const char *startSpecifier, unsigned specifierLen);
7915
7916 void HandlePosition(const char *startPos, unsigned posLen) override;
7917
7918 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
7920
7921 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7922
7923 void HandleNullChar(const char *nullCharacter) override;
7924
7925 template <typename Range>
7926 static void
7927 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7928 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7929 bool IsStringLocation, Range StringRange,
7930 ArrayRef<FixItHint> Fixit = {});
7931
7932protected:
7933 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7934 const char *startSpec,
7935 unsigned specifierLen,
7936 const char *csStart, unsigned csLen);
7937
7938 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7939 const char *startSpec,
7940 unsigned specifierLen);
7941
7942 SourceRange getFormatStringRange();
7943 CharSourceRange getSpecifierRange(const char *startSpecifier,
7944 unsigned specifierLen);
7945 SourceLocation getLocationOfByte(const char *x);
7946
7947 const Expr *getDataArg(unsigned i) const;
7948
7949 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7950 const analyze_format_string::ConversionSpecifier &CS,
7951 const char *startSpecifier, unsigned specifierLen,
7952 unsigned argIndex);
7953
7954 template <typename Range>
7955 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7956 bool IsStringLocation, Range StringRange,
7957 ArrayRef<FixItHint> Fixit = {});
7958};
7959
7960} // namespace
7961
7962SourceRange CheckFormatHandler::getFormatStringRange() {
7963 return OrigFormatExpr->getSourceRange();
7964}
7965
7967CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
7968 unsigned specifierLen) {
7969 SourceLocation Start = getLocationOfByte(startSpecifier);
7970 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7971
7972 // Advance the end SourceLocation by one due to half-open ranges.
7973 End = End.getLocWithOffset(1);
7974
7975 return CharSourceRange::getCharRange(Start, End);
7976}
7977
7978SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7979 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7981}
7982
7983void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7984 unsigned specifierLen) {
7985 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7986 getLocationOfByte(startSpecifier),
7987 /*IsStringLocation*/ true,
7988 getSpecifierRange(startSpecifier, specifierLen));
7989}
7990
7991void CheckFormatHandler::HandleInvalidLengthModifier(
7994 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7995 using namespace analyze_format_string;
7996
7997 const LengthModifier &LM = FS.getLengthModifier();
7998 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7999
8000 // See if we know how to fix this length modifier.
8001 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8002 if (FixedLM) {
8003 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8004 getLocationOfByte(LM.getStart()),
8005 /*IsStringLocation*/ true,
8006 getSpecifierRange(startSpecifier, specifierLen));
8007
8008 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8009 << FixedLM->toString()
8010 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8011
8012 } else {
8013 FixItHint Hint;
8014 if (DiagID == diag::warn_format_nonsensical_length)
8015 Hint = FixItHint::CreateRemoval(LMRange);
8016
8017 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8018 getLocationOfByte(LM.getStart()),
8019 /*IsStringLocation*/ true,
8020 getSpecifierRange(startSpecifier, specifierLen), Hint);
8021 }
8022}
8023
8024void CheckFormatHandler::HandleNonStandardLengthModifier(
8026 const char *startSpecifier, unsigned specifierLen) {
8027 using namespace analyze_format_string;
8028
8029 const LengthModifier &LM = FS.getLengthModifier();
8030 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8031
8032 // See if we know how to fix this length modifier.
8033 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8034 if (FixedLM) {
8035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8036 << LM.toString() << 0,
8037 getLocationOfByte(LM.getStart()),
8038 /*IsStringLocation*/ true,
8039 getSpecifierRange(startSpecifier, specifierLen));
8040
8041 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8042 << FixedLM->toString()
8043 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8044
8045 } else {
8046 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8047 << LM.toString() << 0,
8048 getLocationOfByte(LM.getStart()),
8049 /*IsStringLocation*/ true,
8050 getSpecifierRange(startSpecifier, specifierLen));
8051 }
8052}
8053
8054void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8056 const char *startSpecifier, unsigned specifierLen) {
8057 using namespace analyze_format_string;
8058
8059 // See if we know how to fix this conversion specifier.
8060 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8061 if (FixedCS) {
8062 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8063 << CS.toString() << /*conversion specifier*/ 1,
8064 getLocationOfByte(CS.getStart()),
8065 /*IsStringLocation*/ true,
8066 getSpecifierRange(startSpecifier, specifierLen));
8067
8068 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8069 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8070 << FixedCS->toString()
8071 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8072 } else {
8073 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8074 << CS.toString() << /*conversion specifier*/ 1,
8075 getLocationOfByte(CS.getStart()),
8076 /*IsStringLocation*/ true,
8077 getSpecifierRange(startSpecifier, specifierLen));
8078 }
8079}
8080
8081void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8082 if (!S.getDiagnostics().isIgnored(
8083 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8084 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8085 getLocationOfByte(startPos),
8086 /*IsStringLocation*/ true,
8087 getSpecifierRange(startPos, posLen));
8088}
8089
8090void CheckFormatHandler::HandleInvalidPosition(
8091 const char *startSpecifier, unsigned specifierLen,
8093 if (!S.getDiagnostics().isIgnored(
8094 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8095 EmitFormatDiagnostic(
8096 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8097 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8098 getSpecifierRange(startSpecifier, specifierLen));
8099}
8100
8101void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8102 unsigned posLen) {
8103 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8104 SourceLocation()))
8105 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8106 getLocationOfByte(startPos),
8107 /*IsStringLocation*/ true,
8108 getSpecifierRange(startPos, posLen));
8109}
8110
8111void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8112 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8113 // The presence of a null character is likely an error.
8114 EmitFormatDiagnostic(
8115 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8116 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8117 getFormatStringRange());
8118 }
8119}
8120
8121// Note that this may return NULL if there was an error parsing or building
8122// one of the argument expressions.
8123const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8124 return Args[FirstDataArg + i];
8125}
8126
8127void CheckFormatHandler::DoneProcessing() {
8128 // Does the number of data arguments exceed the number of
8129 // format conversions in the format string?
8130 if (HasFormatArguments()) {
8131 // Find any arguments that weren't covered.
8132 CoveredArgs.flip();
8133 signed notCoveredArg = CoveredArgs.find_first();
8134 if (notCoveredArg >= 0) {
8135 assert((unsigned)notCoveredArg < NumDataArgs);
8136 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8137 } else {
8138 UncoveredArg.setAllCovered();
8139 }
8140 }
8141}
8142
8143void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8144 const Expr *ArgExpr) {
8145 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8146
8147 if (!ArgExpr)
8148 return;
8149
8150 SourceLocation Loc = ArgExpr->getBeginLoc();
8151
8152 if (S.getSourceManager().isInSystemMacro(Loc))
8153 return;
8154
8155 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8156 for (auto E : DiagnosticExprs)
8157 PDiag << E->getSourceRange();
8158
8159 CheckFormatHandler::EmitFormatDiagnostic(
8160 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8161 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8162}
8163
8164bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8165 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8166 unsigned specifierLen, const char *csStart, unsigned csLen) {
8167 bool keepGoing = true;
8168 if (argIndex < NumDataArgs) {
8169 // Consider the argument coverered, even though the specifier doesn't
8170 // make sense.
8171 CoveredArgs.set(argIndex);
8172 } else {
8173 // If argIndex exceeds the number of data arguments we
8174 // don't issue a warning because that is just a cascade of warnings (and
8175 // they may have intended '%%' anyway). We don't want to continue processing
8176 // the format string after this point, however, as we will like just get
8177 // gibberish when trying to match arguments.
8178 keepGoing = false;
8179 }
8180
8181 StringRef Specifier(csStart, csLen);
8182
8183 // If the specifier in non-printable, it could be the first byte of a UTF-8
8184 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8185 // hex value.
8186 std::string CodePointStr;
8187 if (!llvm::sys::locale::isPrint(*csStart)) {
8188 llvm::UTF32 CodePoint;
8189 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8190 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8191 llvm::ConversionResult Result =
8192 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8193
8194 if (Result != llvm::conversionOK) {
8195 unsigned char FirstChar = *csStart;
8196 CodePoint = (llvm::UTF32)FirstChar;
8197 }
8198
8199 llvm::raw_string_ostream OS(CodePointStr);
8200 if (CodePoint < 256)
8201 OS << "\\x" << llvm::format("%02x", CodePoint);
8202 else if (CodePoint <= 0xFFFF)
8203 OS << "\\u" << llvm::format("%04x", CodePoint);
8204 else
8205 OS << "\\U" << llvm::format("%08x", CodePoint);
8206 Specifier = CodePointStr;
8207 }
8208
8209 EmitFormatDiagnostic(
8210 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8211 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8212
8213 return keepGoing;
8214}
8215
8216void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8217 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8218 EmitFormatDiagnostic(
8219 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8220 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8221}
8222
8223bool CheckFormatHandler::CheckNumArgs(
8226 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8227
8228 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8229 PartialDiagnostic PDiag =
8231 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8232 << (argIndex + 1) << NumDataArgs)
8233 : S.PDiag(diag::warn_printf_insufficient_data_args);
8234 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8235 /*IsStringLocation*/ true,
8236 getSpecifierRange(startSpecifier, specifierLen));
8237
8238 // Since more arguments than conversion tokens are given, by extension
8239 // all arguments are covered, so mark this as so.
8240 UncoveredArg.setAllCovered();
8241 return false;
8242 }
8243 return true;
8244}
8245
8246template <typename Range>
8247void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8248 SourceLocation Loc,
8249 bool IsStringLocation,
8250 Range StringRange,
8251 ArrayRef<FixItHint> FixIt) {
8252 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8253 IsStringLocation, StringRange, FixIt);
8254}
8255
8256/// If the format string is not within the function call, emit a note
8257/// so that the function call and string are in diagnostic messages.
8258///
8259/// \param InFunctionCall if true, the format string is within the function
8260/// call and only one diagnostic message will be produced. Otherwise, an
8261/// extra note will be emitted pointing to location of the format string.
8262///
8263/// \param ArgumentExpr the expression that is passed as the format string
8264/// argument in the function call. Used for getting locations when two
8265/// diagnostics are emitted.
8266///
8267/// \param PDiag the callee should already have provided any strings for the
8268/// diagnostic message. This function only adds locations and fixits
8269/// to diagnostics.
8270///
8271/// \param Loc primary location for diagnostic. If two diagnostics are
8272/// required, one will be at Loc and a new SourceLocation will be created for
8273/// the other one.
8274///
8275/// \param IsStringLocation if true, Loc points to the format string should be
8276/// used for the note. Otherwise, Loc points to the argument list and will
8277/// be used with PDiag.
8278///
8279/// \param StringRange some or all of the string to highlight. This is
8280/// templated so it can accept either a CharSourceRange or a SourceRange.
8281///
8282/// \param FixIt optional fix it hint for the format string.
8283template <typename Range>
8284void CheckFormatHandler::EmitFormatDiagnostic(
8285 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8286 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8287 Range StringRange, ArrayRef<FixItHint> FixIt) {
8288 if (InFunctionCall) {
8289 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8290 D << StringRange;
8291 D << FixIt;
8292 } else {
8293 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8294 << ArgumentExpr->getSourceRange();
8295
8297 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8298 diag::note_format_string_defined);
8299
8300 Note << StringRange;
8301 Note << FixIt;
8302 }
8303}
8304
8305//===--- CHECK: Printf format string checking -----------------------------===//
8306
8307namespace {
8308
8309class CheckPrintfHandler : public CheckFormatHandler {
8310public:
8311 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8312 const Expr *origFormatExpr, const FormatStringType type,
8313 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8314 const char *beg, Sema::FormatArgumentPassingKind APK,
8315 ArrayRef<const Expr *> Args, unsigned formatIdx,
8316 bool inFunctionCall, VariadicCallType CallType,
8317 llvm::SmallBitVector &CheckedVarArgs,
8318 UncoveredArgHandler &UncoveredArg)
8319 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8320 numDataArgs, beg, APK, Args, formatIdx,
8321 inFunctionCall, CallType, CheckedVarArgs,
8322 UncoveredArg) {}
8323
8324 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8325
8326 /// Returns true if '%@' specifiers are allowed in the format string.
8327 bool allowsObjCArg() const {
8328 return FSType == FormatStringType::NSString ||
8329 FSType == FormatStringType::OSLog ||
8330 FSType == FormatStringType::OSTrace;
8331 }
8332
8333 bool HandleInvalidPrintfConversionSpecifier(
8334 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8335 unsigned specifierLen) override;
8336
8337 void handleInvalidMaskType(StringRef MaskType) override;
8338
8339 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8340 const char *startSpecifier, unsigned specifierLen,
8341 const TargetInfo &Target) override;
8342 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8343 const char *StartSpecifier, unsigned SpecifierLen,
8344 const Expr *E);
8345
8346 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8347 unsigned k, const char *startSpecifier,
8348 unsigned specifierLen);
8349 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8350 const analyze_printf::OptionalAmount &Amt,
8351 unsigned type, const char *startSpecifier,
8352 unsigned specifierLen);
8353 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8354 const analyze_printf::OptionalFlag &flag,
8355 const char *startSpecifier, unsigned specifierLen);
8356 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8357 const analyze_printf::OptionalFlag &ignoredFlag,
8358 const analyze_printf::OptionalFlag &flag,
8359 const char *startSpecifier, unsigned specifierLen);
8360 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8361
8362 void HandleEmptyObjCModifierFlag(const char *startFlag,
8363 unsigned flagLen) override;
8364
8365 void HandleInvalidObjCModifierFlag(const char *startFlag,
8366 unsigned flagLen) override;
8367
8368 void
8369 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8370 const char *flagsEnd,
8371 const char *conversionPosition) override;
8372};
8373
8374/// Keeps around the information needed to verify that two specifiers are
8375/// compatible.
8376class EquatableFormatArgument {
8377public:
8378 enum SpecifierSensitivity : unsigned {
8379 SS_None,
8380 SS_Private,
8381 SS_Public,
8382 SS_Sensitive
8383 };
8384
8385 enum FormatArgumentRole : unsigned {
8386 FAR_Data,
8387 FAR_FieldWidth,
8388 FAR_Precision,
8389 FAR_Auxiliary, // FreeBSD kernel %b and %D
8390 };
8391
8392private:
8393 analyze_format_string::ArgType ArgType;
8395 StringRef SpecifierLetter;
8396 CharSourceRange Range;
8397 SourceLocation ElementLoc;
8398 FormatArgumentRole Role : 2;
8399 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8400 unsigned Position : 14;
8401 unsigned ModifierFor : 14; // not set for FAR_Data
8402
8403 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8404 bool InFunctionCall) const;
8405
8406public:
8407 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8409 StringRef SpecifierLetter,
8410 analyze_format_string::ArgType ArgType,
8411 FormatArgumentRole Role,
8412 SpecifierSensitivity Sensitivity, unsigned Position,
8413 unsigned ModifierFor)
8414 : ArgType(ArgType), LengthMod(LengthMod),
8415 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8416 Role(Role), Sensitivity(Sensitivity), Position(Position),
8417 ModifierFor(ModifierFor) {}
8418
8419 unsigned getPosition() const { return Position; }
8420 SourceLocation getSourceLocation() const { return ElementLoc; }
8421 CharSourceRange getSourceRange() const { return Range; }
8422 analyze_format_string::LengthModifier getLengthModifier() const {
8423 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8424 }
8425 void setModifierFor(unsigned V) { ModifierFor = V; }
8426
8427 std::string buildFormatSpecifier() const {
8428 std::string result;
8429 llvm::raw_string_ostream(result)
8430 << getLengthModifier().toString() << SpecifierLetter;
8431 return result;
8432 }
8433
8434 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8435 const Expr *FmtExpr, bool InFunctionCall) const;
8436};
8437
8438/// Turns format strings into lists of EquatableSpecifier objects.
8439class DecomposePrintfHandler : public CheckPrintfHandler {
8440 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8441 bool HadError;
8442
8443 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8444 const Expr *origFormatExpr,
8445 const FormatStringType type, unsigned firstDataArg,
8446 unsigned numDataArgs, bool isObjC, const char *beg,
8448 ArrayRef<const Expr *> Args, unsigned formatIdx,
8449 bool inFunctionCall, VariadicCallType CallType,
8450 llvm::SmallBitVector &CheckedVarArgs,
8451 UncoveredArgHandler &UncoveredArg,
8452 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8453 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8454 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8455 inFunctionCall, CallType, CheckedVarArgs,
8456 UncoveredArg),
8457 Specs(Specs), HadError(false) {}
8458
8459public:
8460 static bool
8461 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8462 FormatStringType type, bool IsObjC, bool InFunctionCall,
8463 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8464
8465 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8466 const char *startSpecifier,
8467 unsigned specifierLen,
8468 const TargetInfo &Target) override;
8469};
8470
8471} // namespace
8472
8473bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8474 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8475 unsigned specifierLen) {
8478
8479 return HandleInvalidConversionSpecifier(
8480 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8481 specifierLen, CS.getStart(), CS.getLength());
8482}
8483
8484void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8485 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8486}
8487
8488// Error out if struct or complex type argments are passed to os_log.
8490 QualType T) {
8491 if (FSType != FormatStringType::OSLog)
8492 return false;
8493 return T->isRecordType() || T->isComplexType();
8494}
8495
8496bool CheckPrintfHandler::HandleAmount(
8497 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8498 const char *startSpecifier, unsigned specifierLen) {
8499 if (Amt.hasDataArgument()) {
8500 if (HasFormatArguments()) {
8501 unsigned argIndex = Amt.getArgIndex();
8502 if (argIndex >= NumDataArgs) {
8503 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8504 << k,
8505 getLocationOfByte(Amt.getStart()),
8506 /*IsStringLocation*/ true,
8507 getSpecifierRange(startSpecifier, specifierLen));
8508 // Don't do any more checking. We will just emit
8509 // spurious errors.
8510 return false;
8511 }
8512
8513 // Type check the data argument. It should be an 'int'.
8514 // Although not in conformance with C99, we also allow the argument to be
8515 // an 'unsigned int' as that is a reasonably safe case. GCC also
8516 // doesn't emit a warning for that case.
8517 CoveredArgs.set(argIndex);
8518 const Expr *Arg = getDataArg(argIndex);
8519 if (!Arg)
8520 return false;
8521
8522 QualType T = Arg->getType();
8523
8524 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8525 assert(AT.isValid());
8526
8527 if (!AT.matchesType(S.Context, T)) {
8528 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8529 ? diag::err_printf_asterisk_wrong_type
8530 : diag::warn_printf_asterisk_wrong_type;
8531 EmitFormatDiagnostic(S.PDiag(DiagID)
8533 << T << Arg->getSourceRange(),
8534 getLocationOfByte(Amt.getStart()),
8535 /*IsStringLocation*/ true,
8536 getSpecifierRange(startSpecifier, specifierLen));
8537 // Don't do any more checking. We will just emit
8538 // spurious errors.
8539 return false;
8540 }
8541 }
8542 }
8543 return true;
8544}
8545
8546void CheckPrintfHandler::HandleInvalidAmount(
8548 const analyze_printf::OptionalAmount &Amt, unsigned type,
8549 const char *startSpecifier, unsigned specifierLen) {
8552
8553 FixItHint fixit =
8556 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8557 : FixItHint();
8558
8559 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8560 << type << CS.toString(),
8561 getLocationOfByte(Amt.getStart()),
8562 /*IsStringLocation*/ true,
8563 getSpecifierRange(startSpecifier, specifierLen), fixit);
8564}
8565
8566void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8567 const analyze_printf::OptionalFlag &flag,
8568 const char *startSpecifier,
8569 unsigned specifierLen) {
8570 // Warn about pointless flag with a fixit removal.
8573 EmitFormatDiagnostic(
8574 S.PDiag(diag::warn_printf_nonsensical_flag)
8575 << flag.toString() << CS.toString(),
8576 getLocationOfByte(flag.getPosition()),
8577 /*IsStringLocation*/ true,
8578 getSpecifierRange(startSpecifier, specifierLen),
8579 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8580}
8581
8582void CheckPrintfHandler::HandleIgnoredFlag(
8584 const analyze_printf::OptionalFlag &ignoredFlag,
8585 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8586 unsigned specifierLen) {
8587 // Warn about ignored flag with a fixit removal.
8588 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8589 << ignoredFlag.toString() << flag.toString(),
8590 getLocationOfByte(ignoredFlag.getPosition()),
8591 /*IsStringLocation*/ true,
8592 getSpecifierRange(startSpecifier, specifierLen),
8594 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8595}
8596
8597void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8598 unsigned flagLen) {
8599 // Warn about an empty flag.
8600 EmitFormatDiagnostic(
8601 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8602 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8603}
8604
8605void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8606 unsigned flagLen) {
8607 // Warn about an invalid flag.
8608 auto Range = getSpecifierRange(startFlag, flagLen);
8609 StringRef flag(startFlag, flagLen);
8610 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8611 getLocationOfByte(startFlag),
8612 /*IsStringLocation*/ true, Range,
8614}
8615
8616void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8617 const char *flagsStart, const char *flagsEnd,
8618 const char *conversionPosition) {
8619 // Warn about using '[...]' without a '@' conversion.
8620 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8621 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8622 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8623 getLocationOfByte(conversionPosition),
8624 /*IsStringLocation*/ true, Range,
8626}
8627
8628void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8629 const Expr *FmtExpr,
8630 bool InFunctionCall) const {
8631 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8632 ElementLoc, true, Range);
8633}
8634
8635bool EquatableFormatArgument::VerifyCompatible(
8636 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8637 bool InFunctionCall) const {
8639 if (Role != Other.Role) {
8640 // diagnose and stop
8641 EmitDiagnostic(
8642 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8643 FmtExpr, InFunctionCall);
8644 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8645 return false;
8646 }
8647
8648 if (Role != FAR_Data) {
8649 if (ModifierFor != Other.ModifierFor) {
8650 // diagnose and stop
8651 EmitDiagnostic(S,
8652 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8653 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8654 FmtExpr, InFunctionCall);
8655 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8656 return false;
8657 }
8658 return true;
8659 }
8660
8661 bool HadError = false;
8662 if (Sensitivity != Other.Sensitivity) {
8663 // diagnose and continue
8664 EmitDiagnostic(S,
8665 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8666 << Sensitivity << Other.Sensitivity,
8667 FmtExpr, InFunctionCall);
8668 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8669 << 0 << Other.Range;
8670 }
8671
8672 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8673 case MK::Match:
8674 break;
8675
8676 case MK::MatchPromotion:
8677 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8678 // MatchPromotion is treated as a failure by format_matches.
8679 case MK::NoMatch:
8680 case MK::NoMatchTypeConfusion:
8681 case MK::NoMatchPromotionTypeConfusion:
8682 EmitDiagnostic(S,
8683 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8684 << buildFormatSpecifier()
8685 << Other.buildFormatSpecifier(),
8686 FmtExpr, InFunctionCall);
8687 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8688 << 0 << Other.Range;
8689 break;
8690
8691 case MK::NoMatchPedantic:
8692 EmitDiagnostic(S,
8693 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8694 << buildFormatSpecifier()
8695 << Other.buildFormatSpecifier(),
8696 FmtExpr, InFunctionCall);
8697 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8698 << 0 << Other.Range;
8699 break;
8700
8701 case MK::NoMatchSignedness:
8702 EmitDiagnostic(S,
8703 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8704 << buildFormatSpecifier()
8705 << Other.buildFormatSpecifier(),
8706 FmtExpr, InFunctionCall);
8707 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8708 << 0 << Other.Range;
8709 break;
8710 }
8711 return !HadError;
8712}
8713
8714bool DecomposePrintfHandler::GetSpecifiers(
8715 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8716 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8718 StringRef Data = FSL->getString();
8719 const char *Str = Data.data();
8720 llvm::SmallBitVector BV;
8721 UncoveredArgHandler UA;
8722 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8723 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8724 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8725 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8726 UA, Args);
8727
8729 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8731 H.DoneProcessing();
8732 if (H.HadError)
8733 return false;
8734
8735 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8736 const EquatableFormatArgument &B) {
8737 return A.getPosition() < B.getPosition();
8738 });
8739 return true;
8740}
8741
8742bool DecomposePrintfHandler::HandlePrintfSpecifier(
8743 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8744 unsigned specifierLen, const TargetInfo &Target) {
8745 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8746 specifierLen, Target)) {
8747 HadError = true;
8748 return false;
8749 }
8750
8751 // Do not add any specifiers to the list for %%. This is possibly incorrect
8752 // if using a precision/width with a data argument, but that combination is
8753 // meaningless and we wouldn't know which format to attach the
8754 // precision/width to.
8755 const auto &CS = FS.getConversionSpecifier();
8757 return true;
8758
8759 // have to patch these to have the right ModifierFor if they are used
8760 const unsigned Unset = ~0;
8761 unsigned FieldWidthIndex = Unset;
8762 unsigned PrecisionIndex = Unset;
8763
8764 // field width?
8765 const auto &FieldWidth = FS.getFieldWidth();
8766 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8767 FieldWidthIndex = Specs.size();
8768 Specs.emplace_back(
8769 getSpecifierRange(startSpecifier, specifierLen),
8770 getLocationOfByte(FieldWidth.getStart()),
8771 analyze_format_string::LengthModifier::None, FieldWidth.getCharacters(),
8772 FieldWidth.getArgType(S.Context),
8773 EquatableFormatArgument::FAR_FieldWidth,
8774 EquatableFormatArgument::SS_None,
8775 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8776 : FieldWidthIndex,
8777 0);
8778 }
8779 // precision?
8780 const auto &Precision = FS.getPrecision();
8781 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8782 PrecisionIndex = Specs.size();
8783 Specs.emplace_back(
8784 getSpecifierRange(startSpecifier, specifierLen),
8785 getLocationOfByte(Precision.getStart()),
8786 analyze_format_string::LengthModifier::None, Precision.getCharacters(),
8787 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8788 EquatableFormatArgument::SS_None,
8789 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8790 : PrecisionIndex,
8791 0);
8792 }
8793
8794 // this specifier
8795 unsigned SpecIndex =
8796 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8797 if (FieldWidthIndex != Unset)
8798 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8799 if (PrecisionIndex != Unset)
8800 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8801
8802 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8803 if (FS.isPrivate())
8804 Sensitivity = EquatableFormatArgument::SS_Private;
8805 else if (FS.isPublic())
8806 Sensitivity = EquatableFormatArgument::SS_Public;
8807 else if (FS.isSensitive())
8808 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8809 else
8810 Sensitivity = EquatableFormatArgument::SS_None;
8811
8812 Specs.emplace_back(
8813 getSpecifierRange(startSpecifier, specifierLen),
8814 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8815 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8816 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8817
8818 // auxiliary argument?
8821 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8822 getLocationOfByte(CS.getStart()),
8824 CS.getCharacters(),
8826 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8827 SpecIndex + 1, SpecIndex);
8828 }
8829 return true;
8830}
8831
8832// Determines if the specified is a C++ class or struct containing
8833// a member with the specified name and kind (e.g. a CXXMethodDecl named
8834// "c_str()").
8835template<typename MemberKind>
8837CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8838 auto *RD = Ty->getAsCXXRecordDecl();
8840
8841 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8842 return Results;
8843
8844 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8846 R.suppressDiagnostics();
8847
8848 // We just need to include all members of the right kind turned up by the
8849 // filter, at this point.
8850 if (S.LookupQualifiedName(R, RD))
8851 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8852 NamedDecl *decl = (*I)->getUnderlyingDecl();
8853 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8854 Results.insert(FK);
8855 }
8856 return Results;
8857}
8858
8859/// Check if we could call '.c_str()' on an object.
8860///
8861/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8862/// allow the call, or if it would be ambiguous).
8864 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8865
8866 MethodSet Results =
8867 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8868 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8869 MI != ME; ++MI)
8870 if ((*MI)->getMinRequiredArguments() == 0)
8871 return true;
8872 return false;
8873}
8874
8875// Check if a (w)string was passed when a (w)char* was needed, and offer a
8876// better diagnostic if so. AT is assumed to be valid.
8877// Returns true when a c_str() conversion method is found.
8878bool CheckPrintfHandler::checkForCStrMembers(
8879 const analyze_printf::ArgType &AT, const Expr *E) {
8880 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8881
8882 MethodSet Results =
8884
8885 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8886 MI != ME; ++MI) {
8887 const CXXMethodDecl *Method = *MI;
8888 if (Method->getMinRequiredArguments() == 0 &&
8889 AT.matchesType(S.Context, Method->getReturnType())) {
8890 // FIXME: Suggest parens if the expression needs them.
8892 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8893 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8894 return true;
8895 }
8896 }
8897
8898 return false;
8899}
8900
8901bool CheckPrintfHandler::HandlePrintfSpecifier(
8902 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8903 unsigned specifierLen, const TargetInfo &Target) {
8904 using namespace analyze_format_string;
8905 using namespace analyze_printf;
8906
8907 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8908
8909 if (FS.consumesDataArgument()) {
8910 if (atFirstArg) {
8911 atFirstArg = false;
8912 usesPositionalArgs = FS.usesPositionalArg();
8913 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
8914 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8915 startSpecifier, specifierLen);
8916 return false;
8917 }
8918 }
8919
8920 // First check if the field width, precision, and conversion specifier
8921 // have matching data arguments.
8922 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
8923 specifierLen)) {
8924 return false;
8925 }
8926
8927 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
8928 specifierLen)) {
8929 return false;
8930 }
8931
8932 if (!CS.consumesDataArgument()) {
8933 // FIXME: Technically specifying a precision or field width here
8934 // makes no sense. Worth issuing a warning at some point.
8935 return true;
8936 }
8937
8938 // Consume the argument.
8939 unsigned argIndex = FS.getArgIndex();
8940 if (argIndex < NumDataArgs) {
8941 // The check to see if the argIndex is valid will come later.
8942 // We set the bit here because we may exit early from this
8943 // function if we encounter some other error.
8944 CoveredArgs.set(argIndex);
8945 }
8946
8947 // FreeBSD kernel extensions.
8948 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8949 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8950 // We need at least two arguments.
8951 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8952 return false;
8953
8954 if (HasFormatArguments()) {
8955 // Claim the second argument.
8956 CoveredArgs.set(argIndex + 1);
8957
8958 // Type check the first argument (int for %b, pointer for %D)
8959 const Expr *Ex = getDataArg(argIndex);
8960 const analyze_printf::ArgType &AT =
8961 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8962 ? ArgType(S.Context.IntTy)
8963 : ArgType::CPointerTy;
8964 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8965 EmitFormatDiagnostic(
8966 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8967 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8968 << false << Ex->getSourceRange(),
8969 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8970 getSpecifierRange(startSpecifier, specifierLen));
8971
8972 // Type check the second argument (char * for both %b and %D)
8973 Ex = getDataArg(argIndex + 1);
8975 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8976 EmitFormatDiagnostic(
8977 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8978 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8979 << false << Ex->getSourceRange(),
8980 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8981 getSpecifierRange(startSpecifier, specifierLen));
8982 }
8983 return true;
8984 }
8985
8986 // Check for using an Objective-C specific conversion specifier
8987 // in a non-ObjC literal.
8988 if (!allowsObjCArg() && CS.isObjCArg()) {
8989 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8990 specifierLen);
8991 }
8992
8993 // %P can only be used with os_log.
8994 if (FSType != FormatStringType::OSLog &&
8995 CS.getKind() == ConversionSpecifier::PArg) {
8996 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8997 specifierLen);
8998 }
8999
9000 // %n is not allowed with os_log.
9001 if (FSType == FormatStringType::OSLog &&
9002 CS.getKind() == ConversionSpecifier::nArg) {
9003 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9004 getLocationOfByte(CS.getStart()),
9005 /*IsStringLocation*/ false,
9006 getSpecifierRange(startSpecifier, specifierLen));
9007
9008 return true;
9009 }
9010
9011 // Only scalars are allowed for os_trace.
9012 if (FSType == FormatStringType::OSTrace &&
9013 (CS.getKind() == ConversionSpecifier::PArg ||
9014 CS.getKind() == ConversionSpecifier::sArg ||
9015 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9016 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9017 specifierLen);
9018 }
9019
9020 // Check for use of public/private annotation outside of os_log().
9021 if (FSType != FormatStringType::OSLog) {
9022 if (FS.isPublic().isSet()) {
9023 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9024 << "public",
9025 getLocationOfByte(FS.isPublic().getPosition()),
9026 /*IsStringLocation*/ false,
9027 getSpecifierRange(startSpecifier, specifierLen));
9028 }
9029 if (FS.isPrivate().isSet()) {
9030 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9031 << "private",
9032 getLocationOfByte(FS.isPrivate().getPosition()),
9033 /*IsStringLocation*/ false,
9034 getSpecifierRange(startSpecifier, specifierLen));
9035 }
9036 }
9037
9038 const llvm::Triple &Triple = Target.getTriple();
9039 if (CS.getKind() == ConversionSpecifier::nArg &&
9040 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9041 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9042 getLocationOfByte(CS.getStart()),
9043 /*IsStringLocation*/ false,
9044 getSpecifierRange(startSpecifier, specifierLen));
9045 }
9046
9047 // Check for invalid use of field width
9048 if (!FS.hasValidFieldWidth()) {
9049 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9050 startSpecifier, specifierLen);
9051 }
9052
9053 // Check for invalid use of precision
9054 if (!FS.hasValidPrecision()) {
9055 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9056 startSpecifier, specifierLen);
9057 }
9058
9059 // Precision is mandatory for %P specifier.
9060 if (CS.getKind() == ConversionSpecifier::PArg &&
9062 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9063 getLocationOfByte(startSpecifier),
9064 /*IsStringLocation*/ false,
9065 getSpecifierRange(startSpecifier, specifierLen));
9066 }
9067
9068 // Check each flag does not conflict with any other component.
9070 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9071 if (!FS.hasValidLeadingZeros())
9072 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9073 if (!FS.hasValidPlusPrefix())
9074 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9075 if (!FS.hasValidSpacePrefix())
9076 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9077 if (!FS.hasValidAlternativeForm())
9078 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9079 if (!FS.hasValidLeftJustified())
9080 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9081
9082 // Check that flags are not ignored by another flag
9083 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9084 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9085 startSpecifier, specifierLen);
9086 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9087 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9088 startSpecifier, specifierLen);
9089
9090 // Check the length modifier is valid with the given conversion specifier.
9092 S.getLangOpts()))
9093 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9094 diag::warn_format_nonsensical_length);
9095 else if (!FS.hasStandardLengthModifier())
9096 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9098 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9099 diag::warn_format_non_standard_conversion_spec);
9100
9102 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9103
9104 // The remaining checks depend on the data arguments.
9105 if (!HasFormatArguments())
9106 return true;
9107
9108 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9109 return false;
9110
9111 const Expr *Arg = getDataArg(argIndex);
9112 if (!Arg)
9113 return true;
9114
9115 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9116}
9117
9118static bool requiresParensToAddCast(const Expr *E) {
9119 // FIXME: We should have a general way to reason about operator
9120 // precedence and whether parens are actually needed here.
9121 // Take care of a few common cases where they aren't.
9122 const Expr *Inside = E->IgnoreImpCasts();
9123 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9124 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9125
9126 switch (Inside->getStmtClass()) {
9127 case Stmt::ArraySubscriptExprClass:
9128 case Stmt::CallExprClass:
9129 case Stmt::CharacterLiteralClass:
9130 case Stmt::CXXBoolLiteralExprClass:
9131 case Stmt::DeclRefExprClass:
9132 case Stmt::FloatingLiteralClass:
9133 case Stmt::IntegerLiteralClass:
9134 case Stmt::MemberExprClass:
9135 case Stmt::ObjCArrayLiteralClass:
9136 case Stmt::ObjCBoolLiteralExprClass:
9137 case Stmt::ObjCBoxedExprClass:
9138 case Stmt::ObjCDictionaryLiteralClass:
9139 case Stmt::ObjCEncodeExprClass:
9140 case Stmt::ObjCIvarRefExprClass:
9141 case Stmt::ObjCMessageExprClass:
9142 case Stmt::ObjCPropertyRefExprClass:
9143 case Stmt::ObjCStringLiteralClass:
9144 case Stmt::ObjCSubscriptRefExprClass:
9145 case Stmt::ParenExprClass:
9146 case Stmt::StringLiteralClass:
9147 case Stmt::UnaryOperatorClass:
9148 return false;
9149 default:
9150 return true;
9151 }
9152}
9153
9154static std::pair<QualType, StringRef>
9155shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9156 const Expr *E) {
9157 // Use a 'while' to peel off layers of typedefs.
9158 QualType TyTy = IntendedTy;
9159 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9160 StringRef Name = UserTy->getDecl()->getName();
9161 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9162 .Case("CFIndex", Context.getNSIntegerType())
9163 .Case("NSInteger", Context.getNSIntegerType())
9164 .Case("NSUInteger", Context.getNSUIntegerType())
9165 .Case("SInt32", Context.IntTy)
9166 .Case("UInt32", Context.UnsignedIntTy)
9167 .Default(QualType());
9168
9169 if (!CastTy.isNull())
9170 return std::make_pair(CastTy, Name);
9171
9172 TyTy = UserTy->desugar();
9173 }
9174
9175 // Strip parens if necessary.
9176 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9177 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9178 PE->getSubExpr());
9179
9180 // If this is a conditional expression, then its result type is constructed
9181 // via usual arithmetic conversions and thus there might be no necessary
9182 // typedef sugar there. Recurse to operands to check for NSInteger &
9183 // Co. usage condition.
9184 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9185 QualType TrueTy, FalseTy;
9186 StringRef TrueName, FalseName;
9187
9188 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9189 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9190 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9191 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9192
9193 if (TrueTy == FalseTy)
9194 return std::make_pair(TrueTy, TrueName);
9195 else if (TrueTy.isNull())
9196 return std::make_pair(FalseTy, FalseName);
9197 else if (FalseTy.isNull())
9198 return std::make_pair(TrueTy, TrueName);
9199 }
9200
9201 return std::make_pair(QualType(), StringRef());
9202}
9203
9204/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9205/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9206/// type do not count.
9208 const ImplicitCastExpr *ICE) {
9209 QualType From = ICE->getSubExpr()->getType();
9210 QualType To = ICE->getType();
9211 // It's an integer promotion if the destination type is the promoted
9212 // source type.
9213 if (ICE->getCastKind() == CK_IntegralCast &&
9215 S.Context.getPromotedIntegerType(From) == To)
9216 return true;
9217 // Look through vector types, since we do default argument promotion for
9218 // those in OpenCL.
9219 if (const auto *VecTy = From->getAs<ExtVectorType>())
9220 From = VecTy->getElementType();
9221 if (const auto *VecTy = To->getAs<ExtVectorType>())
9222 To = VecTy->getElementType();
9223 // It's a floating promotion if the source type is a lower rank.
9224 return ICE->getCastKind() == CK_FloatingCast &&
9225 S.Context.getFloatingTypeOrder(From, To) < 0;
9226}
9227
9230 DiagnosticsEngine &Diags, SourceLocation Loc) {
9232 if (Diags.isIgnored(
9233 diag::warn_format_conversion_argument_type_mismatch_signedness,
9234 Loc) ||
9235 Diags.isIgnored(
9236 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9237 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9239 }
9240 }
9241 return Match;
9242}
9243
9244bool CheckPrintfHandler::checkFormatExpr(
9245 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9246 unsigned SpecifierLen, const Expr *E) {
9247 using namespace analyze_format_string;
9248 using namespace analyze_printf;
9249
9250 // Now type check the data expression that matches the
9251 // format specifier.
9252 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9253 if (!AT.isValid())
9254 return true;
9255
9256 QualType ExprTy = E->getType();
9257 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9258 ExprTy = TET->getUnderlyingExpr()->getType();
9259 }
9260
9261 if (const OverflowBehaviorType *OBT =
9262 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9263 ExprTy = OBT->getUnderlyingType();
9264
9265 // When using the format attribute in C++, you can receive a function or an
9266 // array that will necessarily decay to a pointer when passed to the final
9267 // format consumer. Apply decay before type comparison.
9268 if (ExprTy->canDecayToPointerType())
9269 ExprTy = S.Context.getDecayedType(ExprTy);
9270
9271 // Diagnose attempts to print a boolean value as a character. Unlike other
9272 // -Wformat diagnostics, this is fine from a type perspective, but it still
9273 // doesn't make sense.
9276 const CharSourceRange &CSR =
9277 getSpecifierRange(StartSpecifier, SpecifierLen);
9278 SmallString<4> FSString;
9279 llvm::raw_svector_ostream os(FSString);
9280 FS.toString(os);
9281 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9282 << FSString,
9283 E->getExprLoc(), false, CSR);
9284 return true;
9285 }
9286
9287 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9288 // dumping raw class data (like is-a pointer), not actual data.
9290 ExprTy->isObjCObjectPointerType()) {
9291 const CharSourceRange &CSR =
9292 getSpecifierRange(StartSpecifier, SpecifierLen);
9293 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9294 E->getExprLoc(), false, CSR);
9295 return true;
9296 }
9297
9298 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9300 ArgType::MatchKind OrigMatch = Match;
9301
9303 if (Match == ArgType::Match)
9304 return true;
9305
9306 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9307 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9308
9309 // Look through argument promotions for our error message's reported type.
9310 // This includes the integral and floating promotions, but excludes array
9311 // and function pointer decay (seeing that an argument intended to be a
9312 // string has type 'char [6]' is probably more confusing than 'char *') and
9313 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9314 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9315 if (isArithmeticArgumentPromotion(S, ICE)) {
9316 E = ICE->getSubExpr();
9317 ExprTy = E->getType();
9318
9319 // Check if we didn't match because of an implicit cast from a 'char'
9320 // or 'short' to an 'int'. This is done because printf is a varargs
9321 // function.
9322 if (ICE->getType() == S.Context.IntTy ||
9323 ICE->getType() == S.Context.UnsignedIntTy) {
9324 // All further checking is done on the subexpression
9325 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9326 if (OrigMatch == ArgType::NoMatchSignedness &&
9327 ImplicitMatch != ArgType::NoMatchSignedness)
9328 // If the original match was a signedness match this match on the
9329 // implicit cast type also need to be signedness match otherwise we
9330 // might introduce new unexpected warnings from -Wformat-signedness.
9331 return true;
9332 ImplicitMatch = handleFormatSignedness(
9333 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9334 if (ImplicitMatch == ArgType::Match)
9335 return true;
9336 }
9337 }
9338 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9339 // Special case for 'a', which has type 'int' in C.
9340 // Note, however, that we do /not/ want to treat multibyte constants like
9341 // 'MooV' as characters! This form is deprecated but still exists. In
9342 // addition, don't treat expressions as of type 'char' if one byte length
9343 // modifier is provided.
9344 if (ExprTy == S.Context.IntTy &&
9346 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9347 ExprTy = S.Context.CharTy;
9348 // To improve check results, we consider a character literal in C
9349 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9350 // more likely a type confusion situation, so we will suggest to
9351 // use '%hhd' instead by discarding the MatchPromotion.
9352 if (Match == ArgType::MatchPromotion)
9354 }
9355 }
9356 if (Match == ArgType::MatchPromotion) {
9357 // WG14 N2562 only clarified promotions in *printf
9358 // For NSLog in ObjC, just preserve -Wformat behavior
9359 if (!S.getLangOpts().ObjC &&
9360 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9361 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9362 return true;
9364 }
9365 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9366 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9367 Match = ImplicitMatch;
9368 assert(Match != ArgType::MatchPromotion);
9369
9370 // Look through unscoped enums to their underlying type.
9371 bool IsEnum = false;
9372 bool IsScopedEnum = false;
9373 QualType IntendedTy = ExprTy;
9374 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9375 IntendedTy = ED->getIntegerType();
9376 if (!ED->isScoped()) {
9377 ExprTy = IntendedTy;
9378 // This controls whether we're talking about the underlying type or not,
9379 // which we only want to do when it's an unscoped enum.
9380 IsEnum = true;
9381 } else {
9382 IsScopedEnum = true;
9383 }
9384 }
9385
9386 // %C in an Objective-C context prints a unichar, not a wchar_t.
9387 // If the argument is an integer of some kind, believe the %C and suggest
9388 // a cast instead of changing the conversion specifier.
9389 if (isObjCContext() &&
9392 !ExprTy->isCharType()) {
9393 // 'unichar' is defined as a typedef of unsigned short, but we should
9394 // prefer using the typedef if it is visible.
9395 IntendedTy = S.Context.UnsignedShortTy;
9396
9397 // While we are here, check if the value is an IntegerLiteral that happens
9398 // to be within the valid range.
9399 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9400 const llvm::APInt &V = IL->getValue();
9401 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9402 return true;
9403 }
9404
9405 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9407 if (S.LookupName(Result, S.getCurScope())) {
9408 NamedDecl *ND = Result.getFoundDecl();
9409 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9410 if (TD->getUnderlyingType() == IntendedTy)
9411 IntendedTy =
9413 /*Qualifier=*/std::nullopt, TD);
9414 }
9415 }
9416 }
9417
9418 // Special-case some of Darwin's platform-independence types by suggesting
9419 // casts to primitive types that are known to be large enough.
9420 bool ShouldNotPrintDirectly = false;
9421 StringRef CastTyName;
9422 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9423 QualType CastTy;
9424 std::tie(CastTy, CastTyName) =
9425 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9426 if (!CastTy.isNull()) {
9427 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9428 // (long in ASTContext). Only complain to pedants or when they're the
9429 // underlying type of a scoped enum (which always needs a cast).
9430 if (!IsScopedEnum &&
9431 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9432 (AT.isSizeT() || AT.isPtrdiffT()) &&
9433 AT.matchesType(S.Context, CastTy))
9435 IntendedTy = CastTy;
9436 ShouldNotPrintDirectly = true;
9437 }
9438 }
9439
9440 // We may be able to offer a FixItHint if it is a supported type.
9441 PrintfSpecifier fixedFS = FS;
9442 bool Success =
9443 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9444
9445 if (Success) {
9446 // Get the fix string from the fixed format specifier
9447 SmallString<16> buf;
9448 llvm::raw_svector_ostream os(buf);
9449 fixedFS.toString(os);
9450
9451 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9452
9453 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9454 unsigned Diag;
9455 switch (Match) {
9456 case ArgType::Match:
9459 llvm_unreachable("expected non-matching");
9461 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9462 break;
9464 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9465 break;
9467 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9468 break;
9469 case ArgType::NoMatch:
9470 Diag = diag::warn_format_conversion_argument_type_mismatch;
9471 break;
9472 }
9473
9474 // In this case, the specifier is wrong and should be changed to match
9475 // the argument.
9476 EmitFormatDiagnostic(S.PDiag(Diag)
9478 << IntendedTy << IsEnum << E->getSourceRange(),
9479 E->getBeginLoc(),
9480 /*IsStringLocation*/ false, SpecRange,
9481 FixItHint::CreateReplacement(SpecRange, os.str()));
9482 } else {
9483 // The canonical type for formatting this value is different from the
9484 // actual type of the expression. (This occurs, for example, with Darwin's
9485 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9486 // should be printed as 'long' for 64-bit compatibility.)
9487 // Rather than emitting a normal format/argument mismatch, we want to
9488 // add a cast to the recommended type (and correct the format string
9489 // if necessary). We should also do so for scoped enumerations.
9490 SmallString<16> CastBuf;
9491 llvm::raw_svector_ostream CastFix(CastBuf);
9492 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9493 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9494 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9495
9497 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9498 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9499 E->getExprLoc());
9500 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9501 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9502
9503 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9504 // If there's already a cast present, just replace it.
9505 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9506 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9507
9508 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9509 // If the expression has high enough precedence,
9510 // just write the C-style cast.
9511 Hints.push_back(
9512 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9513 } else {
9514 // Otherwise, add parens around the expression as well as the cast.
9515 CastFix << "(";
9516 Hints.push_back(
9517 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9518
9519 // We don't use getLocForEndOfToken because it returns invalid source
9520 // locations for macro expansions (by design).
9524 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9525 }
9526
9527 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9528 // The expression has a type that should not be printed directly.
9529 // We extract the name from the typedef because we don't want to show
9530 // the underlying type in the diagnostic.
9531 StringRef Name;
9532 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9533 Name = TypedefTy->getDecl()->getName();
9534 else
9535 Name = CastTyName;
9536 unsigned Diag = Match == ArgType::NoMatchPedantic
9537 ? diag::warn_format_argument_needs_cast_pedantic
9538 : diag::warn_format_argument_needs_cast;
9539 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9540 << E->getSourceRange(),
9541 E->getBeginLoc(), /*IsStringLocation=*/false,
9542 SpecRange, Hints);
9543 } else {
9544 // In this case, the expression could be printed using a different
9545 // specifier, but we've decided that the specifier is probably correct
9546 // and we should cast instead. Just use the normal warning message.
9547
9548 unsigned Diag =
9549 IsScopedEnum
9550 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9551 : diag::warn_format_conversion_argument_type_mismatch;
9552
9553 EmitFormatDiagnostic(
9554 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9555 << IsEnum << E->getSourceRange(),
9556 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9557 }
9558 }
9559 } else {
9560 const CharSourceRange &CSR =
9561 getSpecifierRange(StartSpecifier, SpecifierLen);
9562 // Since the warning for passing non-POD types to variadic functions
9563 // was deferred until now, we emit a warning for non-POD
9564 // arguments here.
9565 bool EmitTypeMismatch = false;
9566 switch (S.isValidVarArgType(ExprTy)) {
9567 case VarArgKind::Valid:
9569 unsigned Diag;
9570 switch (Match) {
9571 case ArgType::Match:
9574 llvm_unreachable("expected non-matching");
9576 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9577 break;
9579 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9580 break;
9582 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9583 break;
9584 case ArgType::NoMatch:
9585 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9586 ? diag::err_format_conversion_argument_type_mismatch
9587 : diag::warn_format_conversion_argument_type_mismatch;
9588 break;
9589 }
9590
9591 EmitFormatDiagnostic(
9592 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9593 << IsEnum << CSR << E->getSourceRange(),
9594 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9595 break;
9596 }
9599 if (CallType == VariadicCallType::DoesNotApply) {
9600 EmitTypeMismatch = true;
9601 } else {
9602 EmitFormatDiagnostic(
9603 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9604 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9605 << AT.getRepresentativeTypeName(S.Context) << CSR
9606 << E->getSourceRange(),
9607 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9608 checkForCStrMembers(AT, E);
9609 }
9610 break;
9611
9613 if (CallType == VariadicCallType::DoesNotApply)
9614 EmitTypeMismatch = true;
9615 else if (ExprTy->isObjCObjectType())
9616 EmitFormatDiagnostic(
9617 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9618 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9619 << AT.getRepresentativeTypeName(S.Context) << CSR
9620 << E->getSourceRange(),
9621 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9622 else
9623 // FIXME: If this is an initializer list, suggest removing the braces
9624 // or inserting a cast to the target type.
9625 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9626 << isa<InitListExpr>(E) << ExprTy << CallType
9628 break;
9629 }
9630
9631 if (EmitTypeMismatch) {
9632 // The function is not variadic, so we do not generate warnings about
9633 // being allowed to pass that object as a variadic argument. Instead,
9634 // since there are inherently no printf specifiers for types which cannot
9635 // be passed as variadic arguments, emit a plain old specifier mismatch
9636 // argument.
9637 EmitFormatDiagnostic(
9638 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9639 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9640 << E->getSourceRange(),
9641 E->getBeginLoc(), false, CSR);
9642 }
9643
9644 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9645 "format string specifier index out of range");
9646 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9647 }
9648
9649 return true;
9650}
9651
9652//===--- CHECK: Scanf format string checking ------------------------------===//
9653
9654namespace {
9655
9656class CheckScanfHandler : public CheckFormatHandler {
9657public:
9658 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9659 const Expr *origFormatExpr, FormatStringType type,
9660 unsigned firstDataArg, unsigned numDataArgs,
9661 const char *beg, Sema::FormatArgumentPassingKind APK,
9662 ArrayRef<const Expr *> Args, unsigned formatIdx,
9663 bool inFunctionCall, VariadicCallType CallType,
9664 llvm::SmallBitVector &CheckedVarArgs,
9665 UncoveredArgHandler &UncoveredArg)
9666 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9667 numDataArgs, beg, APK, Args, formatIdx,
9668 inFunctionCall, CallType, CheckedVarArgs,
9669 UncoveredArg) {}
9670
9671 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9672 const char *startSpecifier,
9673 unsigned specifierLen) override;
9674
9675 bool
9676 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9677 const char *startSpecifier,
9678 unsigned specifierLen) override;
9679
9680 void HandleIncompleteScanList(const char *start, const char *end) override;
9681};
9682
9683} // namespace
9684
9685void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9686 const char *end) {
9687 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9688 getLocationOfByte(end), /*IsStringLocation*/ true,
9689 getSpecifierRange(start, end - start));
9690}
9691
9692bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9693 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9694 unsigned specifierLen) {
9697
9698 return HandleInvalidConversionSpecifier(
9699 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9700 specifierLen, CS.getStart(), CS.getLength());
9701}
9702
9703bool CheckScanfHandler::HandleScanfSpecifier(
9704 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9705 unsigned specifierLen) {
9706 using namespace analyze_scanf;
9707 using namespace analyze_format_string;
9708
9709 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9710
9711 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9712 // be used to decide if we are using positional arguments consistently.
9713 if (FS.consumesDataArgument()) {
9714 if (atFirstArg) {
9715 atFirstArg = false;
9716 usesPositionalArgs = FS.usesPositionalArg();
9717 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9718 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9719 startSpecifier, specifierLen);
9720 return false;
9721 }
9722 }
9723
9724 // Check if the field with is non-zero.
9725 const OptionalAmount &Amt = FS.getFieldWidth();
9727 if (Amt.getConstantAmount() == 0) {
9728 const CharSourceRange &R =
9729 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9730 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9731 getLocationOfByte(Amt.getStart()),
9732 /*IsStringLocation*/ true, R,
9734 }
9735 }
9736
9737 if (!FS.consumesDataArgument()) {
9738 // FIXME: Technically specifying a precision or field width here
9739 // makes no sense. Worth issuing a warning at some point.
9740 return true;
9741 }
9742
9743 // Consume the argument.
9744 unsigned argIndex = FS.getArgIndex();
9745 if (argIndex < NumDataArgs) {
9746 // The check to see if the argIndex is valid will come later.
9747 // We set the bit here because we may exit early from this
9748 // function if we encounter some other error.
9749 CoveredArgs.set(argIndex);
9750 }
9751
9752 // Check the length modifier is valid with the given conversion specifier.
9754 S.getLangOpts()))
9755 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9756 diag::warn_format_nonsensical_length);
9757 else if (!FS.hasStandardLengthModifier())
9758 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9760 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9761 diag::warn_format_non_standard_conversion_spec);
9762
9764 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9765
9766 // The remaining checks depend on the data arguments.
9767 if (!HasFormatArguments())
9768 return true;
9769
9770 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9771 return false;
9772
9773 // Check that the argument type matches the format specifier.
9774 const Expr *Ex = getDataArg(argIndex);
9775 if (!Ex)
9776 return true;
9777
9779
9780 if (!AT.isValid()) {
9781 return true;
9782 }
9783
9785 AT.matchesType(S.Context, Ex->getType());
9788 return true;
9791
9792 ScanfSpecifier fixedFS = FS;
9793 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9794 S.getLangOpts(), S.Context);
9795
9796 unsigned Diag =
9797 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9798 : Signedness
9799 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9800 : diag::warn_format_conversion_argument_type_mismatch;
9801
9802 if (Success) {
9803 // Get the fix string from the fixed format specifier.
9804 SmallString<128> buf;
9805 llvm::raw_svector_ostream os(buf);
9806 fixedFS.toString(os);
9807
9808 EmitFormatDiagnostic(
9810 << Ex->getType() << false << Ex->getSourceRange(),
9811 Ex->getBeginLoc(),
9812 /*IsStringLocation*/ false,
9813 getSpecifierRange(startSpecifier, specifierLen),
9815 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9816 } else {
9817 EmitFormatDiagnostic(S.PDiag(Diag)
9819 << Ex->getType() << false << Ex->getSourceRange(),
9820 Ex->getBeginLoc(),
9821 /*IsStringLocation*/ false,
9822 getSpecifierRange(startSpecifier, specifierLen));
9823 }
9824
9825 return true;
9826}
9827
9828static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9830 const StringLiteral *Fmt,
9832 const Expr *FmtExpr, bool InFunctionCall) {
9833 bool HadError = false;
9834 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9835 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9836 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9837 // In positional-style format strings, the same specifier can appear
9838 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9839 // are sorted by getPosition(), and we process each range of equal
9840 // getPosition() values as one group.
9841 // RefArgs are taken from a string literal that was given to
9842 // attribute(format_matches), and if we got this far, we have already
9843 // verified that if it has positional specifiers that appear in multiple
9844 // locations, then they are all mutually compatible. What's left for us to
9845 // do is verify that all specifiers with the same position in FmtArgs are
9846 // compatible with the RefArgs specifiers. We check each specifier from
9847 // FmtArgs against the first member of the RefArgs group.
9848 for (; FmtIter < FmtEnd; ++FmtIter) {
9849 // Clang does not diagnose missing format specifiers in positional-style
9850 // strings (TODO: which it probably should do, as it is UB to skip over a
9851 // format argument). Skip specifiers if needed.
9852 if (FmtIter->getPosition() < RefIter->getPosition())
9853 continue;
9854
9855 // Delimits a new getPosition() value.
9856 if (FmtIter->getPosition() > RefIter->getPosition())
9857 break;
9858
9859 HadError |=
9860 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9861 }
9862
9863 // Jump RefIter to the start of the next group.
9864 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9865 return Arg.getPosition() != RefIter->getPosition();
9866 });
9867 }
9868
9869 if (FmtIter < FmtEnd) {
9870 CheckFormatHandler::EmitFormatDiagnostic(
9871 S, InFunctionCall, FmtExpr,
9872 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9873 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9874 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9875 } else if (RefIter < RefEnd) {
9876 CheckFormatHandler::EmitFormatDiagnostic(
9877 S, InFunctionCall, FmtExpr,
9878 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9879 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9880 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9881 << 1 << RefIter->getSourceRange();
9882 }
9883 return !HadError;
9884}
9885
9887 Sema &S, const FormatStringLiteral *FExpr,
9888 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9890 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9891 bool inFunctionCall, VariadicCallType CallType,
9892 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9893 bool IgnoreStringsWithoutSpecifiers) {
9894 // CHECK: is the format string a wide literal?
9895 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9896 CheckFormatHandler::EmitFormatDiagnostic(
9897 S, inFunctionCall, Args[format_idx],
9898 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9899 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9900 return;
9901 }
9902
9903 // Str - The format string. NOTE: this is NOT null-terminated!
9904 StringRef StrRef = FExpr->getString();
9905 const char *Str = StrRef.data();
9906 // Account for cases where the string literal is truncated in a declaration.
9907 const ConstantArrayType *T =
9908 S.Context.getAsConstantArrayType(FExpr->getType());
9909 assert(T && "String literal not of constant array type!");
9910 size_t TypeSize = T->getZExtSize();
9911 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9912 const unsigned numDataArgs = Args.size() - firstDataArg;
9913
9914 if (IgnoreStringsWithoutSpecifiers &&
9916 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9917 return;
9918
9919 // Emit a warning if the string literal is truncated and does not contain an
9920 // embedded null character.
9921 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9922 CheckFormatHandler::EmitFormatDiagnostic(
9923 S, inFunctionCall, Args[format_idx],
9924 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9925 FExpr->getBeginLoc(),
9926 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9927 return;
9928 }
9929
9930 // CHECK: empty format string?
9931 if (StrLen == 0 && numDataArgs > 0) {
9932 CheckFormatHandler::EmitFormatDiagnostic(
9933 S, inFunctionCall, Args[format_idx],
9934 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9935 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9936 return;
9937 }
9938
9943 bool IsObjC =
9945 if (ReferenceFormatString == nullptr) {
9946 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9947 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9948 inFunctionCall, CallType, CheckedVarArgs,
9949 UncoveredArg);
9950
9952 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9955 H.DoneProcessing();
9956 } else {
9958 Type, ReferenceFormatString, FExpr->getFormatString(),
9959 inFunctionCall ? nullptr : Args[format_idx]);
9960 }
9961 } else if (Type == FormatStringType::Scanf) {
9962 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9963 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9964 CallType, CheckedVarArgs, UncoveredArg);
9965
9967 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9968 H.DoneProcessing();
9969 } // TODO: handle other formats
9970}
9971
9973 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9974 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9979 return true;
9980
9981 bool IsObjC =
9984 FormatStringLiteral RefLit = AuthoritativeFormatString;
9985 FormatStringLiteral TestLit = TestedFormatString;
9986 const Expr *Arg;
9987 bool DiagAtStringLiteral;
9988 if (FunctionCallArg) {
9989 Arg = FunctionCallArg;
9990 DiagAtStringLiteral = false;
9991 } else {
9992 Arg = TestedFormatString;
9993 DiagAtStringLiteral = true;
9994 }
9995 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9996 AuthoritativeFormatString, Type,
9997 IsObjC, true, RefArgs) &&
9998 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9999 DiagAtStringLiteral, FmtArgs)) {
10000 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10001 TestedFormatString, FmtArgs, Arg,
10002 DiagAtStringLiteral);
10003 }
10004 return false;
10005}
10006
10008 const StringLiteral *Str) {
10013 return true;
10014
10015 FormatStringLiteral RefLit = Str;
10017 bool IsObjC =
10019 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10020 true, Args))
10021 return false;
10022
10023 // Group arguments by getPosition() value, and check that each member of the
10024 // group is compatible with the first member. This verifies that when
10025 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10026 // are mutually compatible. As an optimization, don't test the first member
10027 // against itself.
10028 bool HadError = false;
10029 auto Iter = Args.begin();
10030 auto End = Args.end();
10031 while (Iter != End) {
10032 const auto &FirstInGroup = *Iter;
10033 for (++Iter;
10034 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10035 ++Iter) {
10036 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10037 }
10038 }
10039 return !HadError;
10040}
10041
10043 // Str - The format string. NOTE: this is NOT null-terminated!
10044 StringRef StrRef = FExpr->getString();
10045 const char *Str = StrRef.data();
10046 // Account for cases where the string literal is truncated in a declaration.
10047 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10048 assert(T && "String literal not of constant array type!");
10049 size_t TypeSize = T->getZExtSize();
10050 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10052 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10053}
10054
10055//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10056
10057// Returns the related absolute value function that is larger, of 0 if one
10058// does not exist.
10059static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10060 switch (AbsFunction) {
10061 default:
10062 return 0;
10063
10064 case Builtin::BI__builtin_abs:
10065 return Builtin::BI__builtin_labs;
10066 case Builtin::BI__builtin_labs:
10067 return Builtin::BI__builtin_llabs;
10068 case Builtin::BI__builtin_llabs:
10069 return 0;
10070
10071 case Builtin::BI__builtin_fabsf:
10072 return Builtin::BI__builtin_fabs;
10073 case Builtin::BI__builtin_fabs:
10074 return Builtin::BI__builtin_fabsl;
10075 case Builtin::BI__builtin_fabsl:
10076 return 0;
10077
10078 case Builtin::BI__builtin_cabsf:
10079 return Builtin::BI__builtin_cabs;
10080 case Builtin::BI__builtin_cabs:
10081 return Builtin::BI__builtin_cabsl;
10082 case Builtin::BI__builtin_cabsl:
10083 return 0;
10084
10085 case Builtin::BIabs:
10086 return Builtin::BIlabs;
10087 case Builtin::BIlabs:
10088 return Builtin::BIllabs;
10089 case Builtin::BIllabs:
10090 return 0;
10091
10092 case Builtin::BIfabsf:
10093 return Builtin::BIfabs;
10094 case Builtin::BIfabs:
10095 return Builtin::BIfabsl;
10096 case Builtin::BIfabsl:
10097 return 0;
10098
10099 case Builtin::BIcabsf:
10100 return Builtin::BIcabs;
10101 case Builtin::BIcabs:
10102 return Builtin::BIcabsl;
10103 case Builtin::BIcabsl:
10104 return 0;
10105 }
10106}
10107
10108// Returns the argument type of the absolute value function.
10110 unsigned AbsType) {
10111 if (AbsType == 0)
10112 return QualType();
10113
10115 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10117 return QualType();
10118
10120 if (!FT)
10121 return QualType();
10122
10123 if (FT->getNumParams() != 1)
10124 return QualType();
10125
10126 return FT->getParamType(0);
10127}
10128
10129// Returns the best absolute value function, or zero, based on type and
10130// current absolute value function.
10131static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10132 unsigned AbsFunctionKind) {
10133 unsigned BestKind = 0;
10134 uint64_t ArgSize = Context.getTypeSize(ArgType);
10135 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10136 Kind = getLargerAbsoluteValueFunction(Kind)) {
10137 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10138 if (Context.getTypeSize(ParamType) >= ArgSize) {
10139 if (BestKind == 0)
10140 BestKind = Kind;
10141 else if (Context.hasSameType(ParamType, ArgType)) {
10142 BestKind = Kind;
10143 break;
10144 }
10145 }
10146 }
10147 return BestKind;
10148}
10149
10155
10157 if (T->isIntegralOrEnumerationType())
10158 return AVK_Integer;
10159 if (T->isRealFloatingType())
10160 return AVK_Floating;
10161 if (T->isAnyComplexType())
10162 return AVK_Complex;
10163
10164 llvm_unreachable("Type not integer, floating, or complex");
10165}
10166
10167// Changes the absolute value function to a different type. Preserves whether
10168// the function is a builtin.
10169static unsigned changeAbsFunction(unsigned AbsKind,
10170 AbsoluteValueKind ValueKind) {
10171 switch (ValueKind) {
10172 case AVK_Integer:
10173 switch (AbsKind) {
10174 default:
10175 return 0;
10176 case Builtin::BI__builtin_fabsf:
10177 case Builtin::BI__builtin_fabs:
10178 case Builtin::BI__builtin_fabsl:
10179 case Builtin::BI__builtin_cabsf:
10180 case Builtin::BI__builtin_cabs:
10181 case Builtin::BI__builtin_cabsl:
10182 return Builtin::BI__builtin_abs;
10183 case Builtin::BIfabsf:
10184 case Builtin::BIfabs:
10185 case Builtin::BIfabsl:
10186 case Builtin::BIcabsf:
10187 case Builtin::BIcabs:
10188 case Builtin::BIcabsl:
10189 return Builtin::BIabs;
10190 }
10191 case AVK_Floating:
10192 switch (AbsKind) {
10193 default:
10194 return 0;
10195 case Builtin::BI__builtin_abs:
10196 case Builtin::BI__builtin_labs:
10197 case Builtin::BI__builtin_llabs:
10198 case Builtin::BI__builtin_cabsf:
10199 case Builtin::BI__builtin_cabs:
10200 case Builtin::BI__builtin_cabsl:
10201 return Builtin::BI__builtin_fabsf;
10202 case Builtin::BIabs:
10203 case Builtin::BIlabs:
10204 case Builtin::BIllabs:
10205 case Builtin::BIcabsf:
10206 case Builtin::BIcabs:
10207 case Builtin::BIcabsl:
10208 return Builtin::BIfabsf;
10209 }
10210 case AVK_Complex:
10211 switch (AbsKind) {
10212 default:
10213 return 0;
10214 case Builtin::BI__builtin_abs:
10215 case Builtin::BI__builtin_labs:
10216 case Builtin::BI__builtin_llabs:
10217 case Builtin::BI__builtin_fabsf:
10218 case Builtin::BI__builtin_fabs:
10219 case Builtin::BI__builtin_fabsl:
10220 return Builtin::BI__builtin_cabsf;
10221 case Builtin::BIabs:
10222 case Builtin::BIlabs:
10223 case Builtin::BIllabs:
10224 case Builtin::BIfabsf:
10225 case Builtin::BIfabs:
10226 case Builtin::BIfabsl:
10227 return Builtin::BIcabsf;
10228 }
10229 }
10230 llvm_unreachable("Unable to convert function");
10231}
10232
10233static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10234 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10235 if (!FnInfo)
10236 return 0;
10237
10238 switch (FDecl->getBuiltinID()) {
10239 default:
10240 return 0;
10241 case Builtin::BI__builtin_abs:
10242 case Builtin::BI__builtin_fabs:
10243 case Builtin::BI__builtin_fabsf:
10244 case Builtin::BI__builtin_fabsl:
10245 case Builtin::BI__builtin_labs:
10246 case Builtin::BI__builtin_llabs:
10247 case Builtin::BI__builtin_cabs:
10248 case Builtin::BI__builtin_cabsf:
10249 case Builtin::BI__builtin_cabsl:
10250 case Builtin::BIabs:
10251 case Builtin::BIlabs:
10252 case Builtin::BIllabs:
10253 case Builtin::BIfabs:
10254 case Builtin::BIfabsf:
10255 case Builtin::BIfabsl:
10256 case Builtin::BIcabs:
10257 case Builtin::BIcabsf:
10258 case Builtin::BIcabsl:
10259 return FDecl->getBuiltinID();
10260 }
10261 llvm_unreachable("Unknown Builtin type");
10262}
10263
10264// If the replacement is valid, emit a note with replacement function.
10265// Additionally, suggest including the proper header if not already included.
10267 unsigned AbsKind, QualType ArgType) {
10268 bool EmitHeaderHint = true;
10269 const char *HeaderName = nullptr;
10270 std::string FunctionName;
10271 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10272 FunctionName = "std::abs";
10273 if (ArgType->isIntegralOrEnumerationType()) {
10274 HeaderName = "cstdlib";
10275 } else if (ArgType->isRealFloatingType()) {
10276 HeaderName = "cmath";
10277 } else {
10278 llvm_unreachable("Invalid Type");
10279 }
10280
10281 // Lookup all std::abs
10282 if (NamespaceDecl *Std = S.getStdNamespace()) {
10283 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10284 R.suppressDiagnostics();
10285 S.LookupQualifiedName(R, Std);
10286
10287 for (const auto *I : R) {
10288 const FunctionDecl *FDecl = nullptr;
10289 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10290 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10291 } else {
10292 FDecl = dyn_cast<FunctionDecl>(I);
10293 }
10294 if (!FDecl)
10295 continue;
10296
10297 // Found std::abs(), check that they are the right ones.
10298 if (FDecl->getNumParams() != 1)
10299 continue;
10300
10301 // Check that the parameter type can handle the argument.
10302 QualType ParamType = FDecl->getParamDecl(0)->getType();
10303 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10304 S.Context.getTypeSize(ArgType) <=
10305 S.Context.getTypeSize(ParamType)) {
10306 // Found a function, don't need the header hint.
10307 EmitHeaderHint = false;
10308 break;
10309 }
10310 }
10311 }
10312 } else {
10313 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10314 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10315
10316 if (HeaderName) {
10317 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10318 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10319 R.suppressDiagnostics();
10320 S.LookupName(R, S.getCurScope());
10321
10322 if (R.isSingleResult()) {
10323 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10324 if (FD && FD->getBuiltinID() == AbsKind) {
10325 EmitHeaderHint = false;
10326 } else {
10327 return;
10328 }
10329 } else if (!R.empty()) {
10330 return;
10331 }
10332 }
10333 }
10334
10335 S.Diag(Loc, diag::note_replace_abs_function)
10336 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10337
10338 if (!HeaderName)
10339 return;
10340
10341 if (!EmitHeaderHint)
10342 return;
10343
10344 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10345 << FunctionName;
10346}
10347
10348template <std::size_t StrLen>
10349static bool IsStdFunction(const FunctionDecl *FDecl,
10350 const char (&Str)[StrLen]) {
10351 if (!FDecl)
10352 return false;
10353 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10354 return false;
10355 if (!FDecl->isInStdNamespace())
10356 return false;
10357
10358 return true;
10359}
10360
10361enum class MathCheck { NaN, Inf };
10362static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10363 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10364 return llvm::is_contained(names, calleeName);
10365 };
10366
10367 switch (Check) {
10368 case MathCheck::NaN:
10369 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10370 "__builtin_nanf16", "__builtin_nanf128"});
10371 case MathCheck::Inf:
10372 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10373 "__builtin_inff16", "__builtin_inff128"});
10374 }
10375 llvm_unreachable("unknown MathCheck");
10376}
10377
10378static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10379 if (FDecl->getName() != "infinity")
10380 return false;
10381
10382 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10383 const CXXRecordDecl *RDecl = MDecl->getParent();
10384 if (RDecl->getName() != "numeric_limits")
10385 return false;
10386
10387 if (const NamespaceDecl *NSDecl =
10388 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10389 return NSDecl->isStdNamespace();
10390 }
10391
10392 return false;
10393}
10394
10395void Sema::CheckInfNaNFunction(const CallExpr *Call,
10396 const FunctionDecl *FDecl) {
10397 if (!FDecl->getIdentifier())
10398 return;
10399
10400 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10401 if (FPO.getNoHonorNaNs() &&
10402 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10404 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10405 << 1 << 0 << Call->getSourceRange();
10406 return;
10407 }
10408
10409 if (FPO.getNoHonorInfs() &&
10410 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10411 IsInfinityFunction(FDecl) ||
10413 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10414 << 0 << 0 << Call->getSourceRange();
10415 }
10416}
10417
10418void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10419 const FunctionDecl *FDecl) {
10420 if (Call->getNumArgs() != 1)
10421 return;
10422
10423 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10424 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10425 if (AbsKind == 0 && !IsStdAbs)
10426 return;
10427
10428 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10429 QualType ParamType = Call->getArg(0)->getType();
10430
10431 // Unsigned types cannot be negative. Suggest removing the absolute value
10432 // function call.
10433 if (ArgType->isUnsignedIntegerType()) {
10434 std::string FunctionName =
10435 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10436 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10437 Diag(Call->getExprLoc(), diag::note_remove_abs)
10438 << FunctionName
10439 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10440 return;
10441 }
10442
10443 // Taking the absolute value of a pointer is very suspicious, they probably
10444 // wanted to index into an array, dereference a pointer, call a function, etc.
10445 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10446 unsigned DiagType = 0;
10447 if (ArgType->isFunctionType())
10448 DiagType = 1;
10449 else if (ArgType->isArrayType())
10450 DiagType = 2;
10451
10452 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10453 return;
10454 }
10455
10456 // std::abs has overloads which prevent most of the absolute value problems
10457 // from occurring.
10458 if (IsStdAbs)
10459 return;
10460
10461 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10462 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10463
10464 // The argument and parameter are the same kind. Check if they are the right
10465 // size.
10466 if (ArgValueKind == ParamValueKind) {
10467 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10468 return;
10469
10470 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10471 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10472 << FDecl << ArgType << ParamType;
10473
10474 if (NewAbsKind == 0)
10475 return;
10476
10477 emitReplacement(*this, Call->getExprLoc(),
10478 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10479 return;
10480 }
10481
10482 // ArgValueKind != ParamValueKind
10483 // The wrong type of absolute value function was used. Attempt to find the
10484 // proper one.
10485 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10486 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10487 if (NewAbsKind == 0)
10488 return;
10489
10490 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10491 << FDecl << ParamValueKind << ArgValueKind;
10492
10493 emitReplacement(*this, Call->getExprLoc(),
10494 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10495}
10496
10497//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10498void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10499 const FunctionDecl *FDecl) {
10500 if (!Call || !FDecl) return;
10501
10502 // Ignore template specializations and macros.
10503 if (inTemplateInstantiation()) return;
10504 if (Call->getExprLoc().isMacroID()) return;
10505
10506 // Only care about the one template argument, two function parameter std::max
10507 if (Call->getNumArgs() != 2) return;
10508 if (!IsStdFunction(FDecl, "max")) return;
10509 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10510 if (!ArgList) return;
10511 if (ArgList->size() != 1) return;
10512
10513 // Check that template type argument is unsigned integer.
10514 const auto& TA = ArgList->get(0);
10515 if (TA.getKind() != TemplateArgument::Type) return;
10516 QualType ArgType = TA.getAsType();
10517 if (!ArgType->isUnsignedIntegerType()) return;
10518
10519 // See if either argument is a literal zero.
10520 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10521 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10522 if (!MTE) return false;
10523 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10524 if (!Num) return false;
10525 if (Num->getValue() != 0) return false;
10526 return true;
10527 };
10528
10529 const Expr *FirstArg = Call->getArg(0);
10530 const Expr *SecondArg = Call->getArg(1);
10531 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10532 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10533
10534 // Only warn when exactly one argument is zero.
10535 if (IsFirstArgZero == IsSecondArgZero) return;
10536
10537 SourceRange FirstRange = FirstArg->getSourceRange();
10538 SourceRange SecondRange = SecondArg->getSourceRange();
10539
10540 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10541
10542 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10543 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10544
10545 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10546 SourceRange RemovalRange;
10547 if (IsFirstArgZero) {
10548 RemovalRange = SourceRange(FirstRange.getBegin(),
10549 SecondRange.getBegin().getLocWithOffset(-1));
10550 } else {
10551 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10552 SecondRange.getEnd());
10553 }
10554
10555 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10556 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10557 << FixItHint::CreateRemoval(RemovalRange);
10558}
10559
10560//===--- CHECK: Standard memory functions ---------------------------------===//
10561
10562/// Takes the expression passed to the size_t parameter of functions
10563/// such as memcmp, strncat, etc and warns if it's a comparison.
10564///
10565/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10567 const IdentifierInfo *FnName,
10568 SourceLocation FnLoc,
10569 SourceLocation RParenLoc) {
10570 const auto *Size = dyn_cast<BinaryOperator>(E);
10571 if (!Size)
10572 return false;
10573
10574 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10575 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10576 return false;
10577
10578 SourceRange SizeRange = Size->getSourceRange();
10579 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10580 << SizeRange << FnName;
10581 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10582 << FnName
10584 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10585 << FixItHint::CreateRemoval(RParenLoc);
10586 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10587 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10589 ")");
10590
10591 return true;
10592}
10593
10594/// Determine whether the given type is or contains a dynamic class type
10595/// (e.g., whether it has a vtable).
10597 bool &IsContained) {
10598 // Look through array types while ignoring qualifiers.
10599 const Type *Ty = T->getBaseElementTypeUnsafe();
10600 IsContained = false;
10601
10602 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10603 RD = RD ? RD->getDefinition() : nullptr;
10604 if (!RD || RD->isInvalidDecl())
10605 return nullptr;
10606
10607 if (RD->isDynamicClass())
10608 return RD;
10609
10610 // Check all the fields. If any bases were dynamic, the class is dynamic.
10611 // It's impossible for a class to transitively contain itself by value, so
10612 // infinite recursion is impossible.
10613 for (auto *FD : RD->fields()) {
10614 bool SubContained;
10615 if (const CXXRecordDecl *ContainedRD =
10616 getContainedDynamicClass(FD->getType(), SubContained)) {
10617 IsContained = true;
10618 return ContainedRD;
10619 }
10620 }
10621
10622 return nullptr;
10623}
10624
10626 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10627 if (Unary->getKind() == UETT_SizeOf)
10628 return Unary;
10629 return nullptr;
10630}
10631
10632/// If E is a sizeof expression, returns its argument expression,
10633/// otherwise returns NULL.
10634static const Expr *getSizeOfExprArg(const Expr *E) {
10636 if (!SizeOf->isArgumentType())
10637 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10638 return nullptr;
10639}
10640
10641/// If E is a sizeof expression, returns its argument type.
10644 return SizeOf->getTypeOfArgument();
10645 return QualType();
10646}
10647
10648namespace {
10649
10650struct SearchNonTrivialToInitializeField
10651 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10652 using Super =
10653 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10654
10655 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10656
10657 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10658 SourceLocation SL) {
10659 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10660 asDerived().visitArray(PDIK, AT, SL);
10661 return;
10662 }
10663
10664 Super::visitWithKind(PDIK, FT, SL);
10665 }
10666
10667 void visitARCStrong(QualType FT, SourceLocation SL) {
10668 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10669 }
10670 void visitARCWeak(QualType FT, SourceLocation SL) {
10671 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10672 }
10673 void visitStruct(QualType FT, SourceLocation SL) {
10674 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10675 visit(FD->getType(), FD->getLocation());
10676 }
10677 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10678 const ArrayType *AT, SourceLocation SL) {
10679 visit(getContext().getBaseElementType(AT), SL);
10680 }
10681 void visitTrivial(QualType FT, SourceLocation SL) {}
10682
10683 static void diag(QualType RT, const Expr *E, Sema &S) {
10684 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10685 }
10686
10687 ASTContext &getContext() { return S.getASTContext(); }
10688
10689 const Expr *E;
10690 Sema &S;
10691};
10692
10693struct SearchNonTrivialToCopyField
10694 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10695 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10696
10697 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10698
10699 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10700 SourceLocation SL) {
10701 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10702 asDerived().visitArray(PCK, AT, SL);
10703 return;
10704 }
10705
10706 Super::visitWithKind(PCK, FT, SL);
10707 }
10708
10709 void visitARCStrong(QualType FT, SourceLocation SL) {
10710 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10711 }
10712 void visitARCWeak(QualType FT, SourceLocation SL) {
10713 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10714 }
10715 void visitPtrAuth(QualType FT, SourceLocation SL) {
10716 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10717 }
10718 void visitStruct(QualType FT, SourceLocation SL) {
10719 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10720 visit(FD->getType(), FD->getLocation());
10721 }
10722 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10723 SourceLocation SL) {
10724 visit(getContext().getBaseElementType(AT), SL);
10725 }
10726 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10727 SourceLocation SL) {}
10728 void visitTrivial(QualType FT, SourceLocation SL) {}
10729 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10730
10731 static void diag(QualType RT, const Expr *E, Sema &S) {
10732 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10733 }
10734
10735 ASTContext &getContext() { return S.getASTContext(); }
10736
10737 const Expr *E;
10738 Sema &S;
10739};
10740
10741}
10742
10743/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10744static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10745 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10746
10747 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10748 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10749 return false;
10750
10751 return doesExprLikelyComputeSize(BO->getLHS()) ||
10752 doesExprLikelyComputeSize(BO->getRHS());
10753 }
10754
10755 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10756}
10757
10758/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10759///
10760/// \code
10761/// #define MACRO 0
10762/// foo(MACRO);
10763/// foo(0);
10764/// \endcode
10765///
10766/// This should return true for the first call to foo, but not for the second
10767/// (regardless of whether foo is a macro or function).
10769 SourceLocation CallLoc,
10770 SourceLocation ArgLoc) {
10771 if (!CallLoc.isMacroID())
10772 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10773
10774 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10775 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10776}
10777
10778/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10779/// last two arguments transposed.
10780static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10781 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10782 return;
10783
10784 const Expr *SizeArg =
10785 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10786
10787 auto isLiteralZero = [](const Expr *E) {
10788 return (isa<IntegerLiteral>(E) &&
10789 cast<IntegerLiteral>(E)->getValue() == 0) ||
10791 cast<CharacterLiteral>(E)->getValue() == 0);
10792 };
10793
10794 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10795 SourceLocation CallLoc = Call->getRParenLoc();
10797 if (isLiteralZero(SizeArg) &&
10798 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10799
10800 SourceLocation DiagLoc = SizeArg->getExprLoc();
10801
10802 // Some platforms #define bzero to __builtin_memset. See if this is the
10803 // case, and if so, emit a better diagnostic.
10804 if (BId == Builtin::BIbzero ||
10806 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10807 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10808 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10809 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10810 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10811 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10812 }
10813 return;
10814 }
10815
10816 // If the second argument to a memset is a sizeof expression and the third
10817 // isn't, this is also likely an error. This should catch
10818 // 'memset(buf, sizeof(buf), 0xff)'.
10819 if (BId == Builtin::BImemset &&
10820 doesExprLikelyComputeSize(Call->getArg(1)) &&
10821 !doesExprLikelyComputeSize(Call->getArg(2))) {
10822 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10823 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10824 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10825 return;
10826 }
10827}
10828
10829void Sema::CheckMemaccessArguments(const CallExpr *Call,
10830 unsigned BId,
10831 IdentifierInfo *FnName) {
10832 assert(BId != 0);
10833
10834 // It is possible to have a non-standard definition of memset. Validate
10835 // we have enough arguments, and if not, abort further checking.
10836 unsigned ExpectedNumArgs =
10837 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10838 if (Call->getNumArgs() < ExpectedNumArgs)
10839 return;
10840
10841 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10842 BId == Builtin::BIstrndup ? 1 : 2);
10843 unsigned LenArg =
10844 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10845 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10846
10847 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10848 Call->getBeginLoc(), Call->getRParenLoc()))
10849 return;
10850
10851 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10852 CheckMemaccessSize(*this, BId, Call);
10853
10854 // We have special checking when the length is a sizeof expression.
10855 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10856
10857 // Although widely used, 'bzero' is not a standard function. Be more strict
10858 // with the argument types before allowing diagnostics and only allow the
10859 // form bzero(ptr, sizeof(...)).
10860 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10861 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10862 return;
10863
10864 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10865 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10866 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10867
10868 QualType DestTy = Dest->getType();
10869 QualType PointeeTy;
10870 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10871 PointeeTy = DestPtrTy->getPointeeType();
10872
10873 // Never warn about void type pointers. This can be used to suppress
10874 // false positives.
10875 if (PointeeTy->isVoidType())
10876 continue;
10877
10878 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10879 // actually comparing the expressions for equality. Because computing the
10880 // expression IDs can be expensive, we only do this if the diagnostic is
10881 // enabled.
10882 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
10883 break;
10884
10885 // Also check for cases where the sizeof argument is the exact same
10886 // type as the memory argument, and where it points to a user-defined
10887 // record type.
10888 if (SizeOfArgTy != QualType()) {
10889 if (PointeeTy->isRecordType() &&
10890 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10891 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10892 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10893 << FnName << SizeOfArgTy << ArgIdx
10894 << PointeeTy << Dest->getSourceRange()
10895 << LenExpr->getSourceRange());
10896 break;
10897 }
10898 }
10899 } else if (DestTy->isArrayType()) {
10900 PointeeTy = DestTy;
10901 }
10902
10903 if (PointeeTy == QualType())
10904 continue;
10905
10906 // Always complain about dynamic classes.
10907 bool IsContained;
10908 if (const CXXRecordDecl *ContainedRD =
10909 getContainedDynamicClass(PointeeTy, IsContained)) {
10910
10911 unsigned OperationType = 0;
10912 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10913 // "overwritten" if we're warning about the destination for any call
10914 // but memcmp; otherwise a verb appropriate to the call.
10915 if (ArgIdx != 0 || IsCmp) {
10916 if (BId == Builtin::BImemcpy)
10917 OperationType = 1;
10918 else if(BId == Builtin::BImemmove)
10919 OperationType = 2;
10920 else if (IsCmp)
10921 OperationType = 3;
10922 }
10923
10924 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10925 PDiag(diag::warn_dyn_class_memaccess)
10926 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10927 << IsContained << ContainedRD << OperationType
10928 << Call->getCallee()->getSourceRange());
10929 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10930 BId != Builtin::BImemset)
10932 Dest->getExprLoc(), Dest,
10933 PDiag(diag::warn_arc_object_memaccess)
10934 << ArgIdx << FnName << PointeeTy
10935 << Call->getCallee()->getSourceRange());
10936 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10937
10938 // FIXME: Do not consider incomplete types even though they may be
10939 // completed later. GCC does not diagnose such code, but we may want to
10940 // consider diagnosing it in the future, perhaps under a different, but
10941 // related, diagnostic group.
10942 bool NonTriviallyCopyableCXXRecord =
10943 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10944 !PointeeTy.isTriviallyCopyableType(Context);
10945
10946 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10948 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10949 PDiag(diag::warn_cstruct_memaccess)
10950 << ArgIdx << FnName << PointeeTy << 0);
10951 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10952 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10953 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10954 // FIXME: Limiting this warning to dest argument until we decide
10955 // whether it's valid for source argument too.
10956 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10957 PDiag(diag::warn_cxxstruct_memaccess)
10958 << FnName << PointeeTy);
10959 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10961 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10962 PDiag(diag::warn_cstruct_memaccess)
10963 << ArgIdx << FnName << PointeeTy << 1);
10964 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10965 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10966 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10967 // FIXME: Limiting this warning to dest argument until we decide
10968 // whether it's valid for source argument too.
10969 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10970 PDiag(diag::warn_cxxstruct_memaccess)
10971 << FnName << PointeeTy);
10972 } else {
10973 continue;
10974 }
10975 } else
10976 continue;
10977
10979 Dest->getExprLoc(), Dest,
10980 PDiag(diag::note_bad_memaccess_silence)
10981 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10982 break;
10983 }
10984}
10985
10986bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10987 IdentifierInfo *FnName) {
10988 llvm::FoldingSetNodeID SizeOfArgID;
10989 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10990 if (!SizeOfArg)
10991 return false;
10992 // Computing this warning is expensive, so we only do so if the warning is
10993 // enabled.
10994 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10995 SizeOfArg->getExprLoc()))
10996 return false;
10997 QualType DestTy = Dest->getType();
10998 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10999 if (!DestPtrTy)
11000 return false;
11001
11002 QualType PointeeTy = DestPtrTy->getPointeeType();
11003
11004 if (SizeOfArgID == llvm::FoldingSetNodeID())
11005 SizeOfArg->Profile(SizeOfArgID, Context, true);
11006
11007 llvm::FoldingSetNodeID DestID;
11008 Dest->Profile(DestID, Context, true);
11009 if (DestID == SizeOfArgID) {
11010 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11011 // over sizeof(src) as well.
11012 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11013 StringRef ReadableName = FnName->getName();
11014
11015 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11016 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11017 ActionIdx = 1; // If its an address-of operator, just remove it.
11018 if (!PointeeTy->isIncompleteType() &&
11019 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11020 ActionIdx = 2; // If the pointee's size is sizeof(char),
11021 // suggest an explicit length.
11022
11023 // If the function is defined as a builtin macro, do not show macro
11024 // expansion.
11025 SourceLocation SL = SizeOfArg->getExprLoc();
11026 SourceRange DSR = Dest->getSourceRange();
11027 SourceRange SSR = SizeOfArg->getSourceRange();
11028 SourceManager &SM = getSourceManager();
11029
11030 if (SM.isMacroArgExpansion(SL)) {
11031 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11032 SL = SM.getSpellingLoc(SL);
11033 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11034 SM.getSpellingLoc(DSR.getEnd()));
11035 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11036 SM.getSpellingLoc(SSR.getEnd()));
11037 }
11038
11039 DiagRuntimeBehavior(SL, SizeOfArg,
11040 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11041 << ReadableName << PointeeTy << DestTy << DSR
11042 << SSR);
11043 DiagRuntimeBehavior(SL, SizeOfArg,
11044 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11045 << ActionIdx << SSR);
11046 return true;
11047 }
11048 return false;
11049}
11050
11051// A little helper routine: ignore addition and subtraction of integer literals.
11052// This intentionally does not ignore all integer constant expressions because
11053// we don't want to remove sizeof().
11054static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11055 Ex = Ex->IgnoreParenCasts();
11056
11057 while (true) {
11058 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11059 if (!BO || !BO->isAdditiveOp())
11060 break;
11061
11062 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11063 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11064
11065 if (isa<IntegerLiteral>(RHS))
11066 Ex = LHS;
11067 else if (isa<IntegerLiteral>(LHS))
11068 Ex = RHS;
11069 else
11070 break;
11071 }
11072
11073 return Ex;
11074}
11075
11077 ASTContext &Context) {
11078 // Only handle constant-sized or VLAs, but not flexible members.
11079 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11080 // Only issue the FIXIT for arrays of size > 1.
11081 if (CAT->getZExtSize() <= 1)
11082 return false;
11083 } else if (!Ty->isVariableArrayType()) {
11084 return false;
11085 }
11086 return true;
11087}
11088
11089void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11090 IdentifierInfo *FnName) {
11091
11092 // Don't crash if the user has the wrong number of arguments
11093 unsigned NumArgs = Call->getNumArgs();
11094 if ((NumArgs != 3) && (NumArgs != 4))
11095 return;
11096
11097 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11098 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11099 const Expr *CompareWithSrc = nullptr;
11100
11101 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11102 Call->getBeginLoc(), Call->getRParenLoc()))
11103 return;
11104
11105 // Look for 'strlcpy(dst, x, sizeof(x))'
11106 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11107 CompareWithSrc = Ex;
11108 else {
11109 // Look for 'strlcpy(dst, x, strlen(x))'
11110 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11111 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11112 SizeCall->getNumArgs() == 1)
11113 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11114 }
11115 }
11116
11117 if (!CompareWithSrc)
11118 return;
11119
11120 // Determine if the argument to sizeof/strlen is equal to the source
11121 // argument. In principle there's all kinds of things you could do
11122 // here, for instance creating an == expression and evaluating it with
11123 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11124 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11125 if (!SrcArgDRE)
11126 return;
11127
11128 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11129 if (!CompareWithSrcDRE ||
11130 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11131 return;
11132
11133 const Expr *OriginalSizeArg = Call->getArg(2);
11134 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11135 << OriginalSizeArg->getSourceRange() << FnName;
11136
11137 // Output a FIXIT hint if the destination is an array (rather than a
11138 // pointer to an array). This could be enhanced to handle some
11139 // pointers if we know the actual size, like if DstArg is 'array+2'
11140 // we could say 'sizeof(array)-2'.
11141 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11143 return;
11144
11145 SmallString<128> sizeString;
11146 llvm::raw_svector_ostream OS(sizeString);
11147 OS << "sizeof(";
11148 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11149 OS << ")";
11150
11151 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11152 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11153 OS.str());
11154}
11155
11156/// Check if two expressions refer to the same declaration.
11157static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11158 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11159 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11160 return D1->getDecl() == D2->getDecl();
11161 return false;
11162}
11163
11164static const Expr *getStrlenExprArg(const Expr *E) {
11165 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11166 const FunctionDecl *FD = CE->getDirectCallee();
11167 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11168 return nullptr;
11169 return CE->getArg(0)->IgnoreParenCasts();
11170 }
11171 return nullptr;
11172}
11173
11174void Sema::CheckStrncatArguments(const CallExpr *CE,
11175 const IdentifierInfo *FnName) {
11176 // Don't crash if the user has the wrong number of arguments.
11177 if (CE->getNumArgs() < 3)
11178 return;
11179 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11180 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11181 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11182
11183 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11184 CE->getRParenLoc()))
11185 return;
11186
11187 // Identify common expressions, which are wrongly used as the size argument
11188 // to strncat and may lead to buffer overflows.
11189 unsigned PatternType = 0;
11190 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11191 // - sizeof(dst)
11192 if (referToTheSameDecl(SizeOfArg, DstArg))
11193 PatternType = 1;
11194 // - sizeof(src)
11195 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11196 PatternType = 2;
11197 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11198 if (BE->getOpcode() == BO_Sub) {
11199 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11200 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11201 // - sizeof(dst) - strlen(dst)
11202 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11204 PatternType = 1;
11205 // - sizeof(src) - (anything)
11206 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11207 PatternType = 2;
11208 }
11209 }
11210
11211 if (PatternType == 0)
11212 return;
11213
11214 // Generate the diagnostic.
11215 SourceLocation SL = LenArg->getBeginLoc();
11216 SourceRange SR = LenArg->getSourceRange();
11217 SourceManager &SM = getSourceManager();
11218
11219 // If the function is defined as a builtin macro, do not show macro expansion.
11220 if (SM.isMacroArgExpansion(SL)) {
11221 SL = SM.getSpellingLoc(SL);
11222 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11223 SM.getSpellingLoc(SR.getEnd()));
11224 }
11225
11226 // Check if the destination is an array (rather than a pointer to an array).
11227 QualType DstTy = DstArg->getType();
11228 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11229 Context);
11230 if (!isKnownSizeArray) {
11231 if (PatternType == 1)
11232 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11233 else
11234 Diag(SL, diag::warn_strncat_src_size) << SR;
11235 return;
11236 }
11237
11238 if (PatternType == 1)
11239 Diag(SL, diag::warn_strncat_large_size) << SR;
11240 else
11241 Diag(SL, diag::warn_strncat_src_size) << SR;
11242
11243 SmallString<128> sizeString;
11244 llvm::raw_svector_ostream OS(sizeString);
11245 OS << "sizeof(";
11246 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11247 OS << ") - ";
11248 OS << "strlen(";
11249 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11250 OS << ") - 1";
11251
11252 Diag(SL, diag::note_strncat_wrong_size)
11253 << FixItHint::CreateReplacement(SR, OS.str());
11254}
11255
11256namespace {
11257void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11258 const UnaryOperator *UnaryExpr, const Decl *D) {
11260 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11261 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11262 return;
11263 }
11264}
11265
11266void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11267 const UnaryOperator *UnaryExpr) {
11268 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11269 const Decl *D = Lvalue->getDecl();
11270 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11271 if (!DD->getType()->isReferenceType())
11272 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11273 }
11274 }
11275
11276 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11277 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11278 Lvalue->getMemberDecl());
11279}
11280
11281void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11282 const UnaryOperator *UnaryExpr) {
11283 const auto *Lambda = dyn_cast<LambdaExpr>(
11285 if (!Lambda)
11286 return;
11287
11288 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11289 << CalleeName << 2 /*object: lambda expression*/;
11290}
11291
11292void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11293 const DeclRefExpr *Lvalue) {
11294 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11295 if (Var == nullptr)
11296 return;
11297
11298 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11299 << CalleeName << 0 /*object: */ << Var;
11300}
11301
11302void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11303 const CastExpr *Cast) {
11304 SmallString<128> SizeString;
11305 llvm::raw_svector_ostream OS(SizeString);
11306
11307 clang::CastKind Kind = Cast->getCastKind();
11308 if (Kind == clang::CK_BitCast &&
11309 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11310 return;
11311 if (Kind == clang::CK_IntegralToPointer &&
11313 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11314 return;
11315
11316 switch (Cast->getCastKind()) {
11317 case clang::CK_BitCast:
11318 case clang::CK_IntegralToPointer:
11319 case clang::CK_FunctionToPointerDecay:
11320 OS << '\'';
11321 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11322 OS << '\'';
11323 break;
11324 default:
11325 return;
11326 }
11327
11328 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11329 << CalleeName << 0 /*object: */ << OS.str();
11330}
11331} // namespace
11332
11333void Sema::CheckFreeArguments(const CallExpr *E) {
11334 const std::string CalleeName =
11335 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11336
11337 { // Prefer something that doesn't involve a cast to make things simpler.
11338 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11339 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11340 switch (UnaryExpr->getOpcode()) {
11341 case UnaryOperator::Opcode::UO_AddrOf:
11342 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11343 case UnaryOperator::Opcode::UO_Plus:
11344 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11345 default:
11346 break;
11347 }
11348
11349 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11350 if (Lvalue->getType()->isArrayType())
11351 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11352
11353 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11354 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11355 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11356 return;
11357 }
11358
11359 if (isa<BlockExpr>(Arg)) {
11360 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11361 << CalleeName << 1 /*object: block*/;
11362 return;
11363 }
11364 }
11365 // Maybe the cast was important, check after the other cases.
11366 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11367 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11368}
11369
11370void
11371Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11372 SourceLocation ReturnLoc,
11373 bool isObjCMethod,
11374 const AttrVec *Attrs,
11375 const FunctionDecl *FD) {
11376 // Check if the return value is null but should not be.
11377 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11378 (!isObjCMethod && isNonNullType(lhsType))) &&
11379 CheckNonNullExpr(*this, RetValExp))
11380 Diag(ReturnLoc, diag::warn_null_ret)
11381 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11382
11383 // C++11 [basic.stc.dynamic.allocation]p4:
11384 // If an allocation function declared with a non-throwing
11385 // exception-specification fails to allocate storage, it shall return
11386 // a null pointer. Any other allocation function that fails to allocate
11387 // storage shall indicate failure only by throwing an exception [...]
11388 if (FD) {
11390 if (Op == OO_New || Op == OO_Array_New) {
11391 const FunctionProtoType *Proto
11392 = FD->getType()->castAs<FunctionProtoType>();
11393 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11394 CheckNonNullExpr(*this, RetValExp))
11395 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11396 << FD << getLangOpts().CPlusPlus11;
11397 }
11398 }
11399
11400 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11401 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11402 }
11403
11404 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11405 // here prevent the user from using a PPC MMA type as trailing return type.
11406 if (Context.getTargetInfo().getTriple().isPPC64())
11407 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11408}
11409
11411 const Expr *RHS, BinaryOperatorKind Opcode) {
11412 if (!BinaryOperator::isEqualityOp(Opcode))
11413 return;
11414
11415 // Match and capture subexpressions such as "(float) X == 0.1".
11416 const FloatingLiteral *FPLiteral;
11417 const CastExpr *FPCast;
11418 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11419 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11420 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11421 return FPLiteral && FPCast;
11422 };
11423
11424 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11425 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11426 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11427 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11428 TargetTy->isFloatingPoint()) {
11429 bool Lossy;
11430 llvm::APFloat TargetC = FPLiteral->getValue();
11431 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11432 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11433 if (Lossy) {
11434 // If the literal cannot be represented in the source type, then a
11435 // check for == is always false and check for != is always true.
11436 Diag(Loc, diag::warn_float_compare_literal)
11437 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11438 << LHS->getSourceRange() << RHS->getSourceRange();
11439 return;
11440 }
11441 }
11442 }
11443
11444 // Match a more general floating-point equality comparison (-Wfloat-equal).
11445 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11446 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11447
11448 // Special case: check for x == x (which is OK).
11449 // Do not emit warnings for such cases.
11450 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11451 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11452 if (DRL->getDecl() == DRR->getDecl())
11453 return;
11454
11455 // Special case: check for comparisons against literals that can be exactly
11456 // represented by APFloat. In such cases, do not emit a warning. This
11457 // is a heuristic: often comparison against such literals are used to
11458 // detect if a value in a variable has not changed. This clearly can
11459 // lead to false negatives.
11460 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11461 if (FLL->isExact())
11462 return;
11463 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11464 if (FLR->isExact())
11465 return;
11466
11467 // Check for comparisons with builtin types.
11468 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11469 CL && CL->getBuiltinCallee())
11470 return;
11471
11472 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11473 CR && CR->getBuiltinCallee())
11474 return;
11475
11476 // Emit the diagnostic.
11477 Diag(Loc, diag::warn_floatingpoint_eq)
11478 << LHS->getSourceRange() << RHS->getSourceRange();
11479}
11480
11481//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11482//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11483
11484namespace {
11485
11486/// Structure recording the 'active' range of an integer-valued
11487/// expression.
11488struct IntRange {
11489 /// The number of bits active in the int. Note that this includes exactly one
11490 /// sign bit if !NonNegative.
11491 unsigned Width;
11492
11493 /// True if the int is known not to have negative values. If so, all leading
11494 /// bits before Width are known zero, otherwise they are known to be the
11495 /// same as the MSB within Width.
11496 bool NonNegative;
11497
11498 IntRange(unsigned Width, bool NonNegative)
11499 : Width(Width), NonNegative(NonNegative) {}
11500
11501 /// Number of bits excluding the sign bit.
11502 unsigned valueBits() const {
11503 return NonNegative ? Width : Width - 1;
11504 }
11505
11506 /// Returns the range of the bool type.
11507 static IntRange forBoolType() {
11508 return IntRange(1, true);
11509 }
11510
11511 /// Returns the range of an opaque value of the given integral type.
11512 static IntRange forValueOfType(ASTContext &C, QualType T) {
11513 return forValueOfCanonicalType(C,
11515 }
11516
11517 /// Returns the range of an opaque value of a canonical integral type.
11518 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11519 assert(T->isCanonicalUnqualified());
11520
11521 if (const auto *VT = dyn_cast<VectorType>(T))
11522 T = VT->getElementType().getTypePtr();
11523 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11524 T = MT->getElementType().getTypePtr();
11525 if (const auto *CT = dyn_cast<ComplexType>(T))
11526 T = CT->getElementType().getTypePtr();
11527 if (const auto *AT = dyn_cast<AtomicType>(T))
11528 T = AT->getValueType().getTypePtr();
11529 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11530 T = OBT->getUnderlyingType().getTypePtr();
11531
11532 if (!C.getLangOpts().CPlusPlus) {
11533 // For enum types in C code, use the underlying datatype.
11534 if (const auto *ED = T->getAsEnumDecl())
11535 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11536 } else if (auto *Enum = T->getAsEnumDecl()) {
11537 // For enum types in C++, use the known bit width of the enumerators.
11538 // In C++11, enums can have a fixed underlying type. Use this type to
11539 // compute the range.
11540 if (Enum->isFixed()) {
11541 return IntRange(C.getIntWidth(QualType(T, 0)),
11542 !Enum->getIntegerType()->isSignedIntegerType());
11543 }
11544
11545 unsigned NumPositive = Enum->getNumPositiveBits();
11546 unsigned NumNegative = Enum->getNumNegativeBits();
11547
11548 if (NumNegative == 0)
11549 return IntRange(NumPositive, true/*NonNegative*/);
11550 else
11551 return IntRange(std::max(NumPositive + 1, NumNegative),
11552 false/*NonNegative*/);
11553 }
11554
11555 if (const auto *EIT = dyn_cast<BitIntType>(T))
11556 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11557
11558 const BuiltinType *BT = cast<BuiltinType>(T);
11559 assert(BT->isInteger());
11560
11561 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11562 }
11563
11564 /// Returns the "target" range of a canonical integral type, i.e.
11565 /// the range of values expressible in the type.
11566 ///
11567 /// This matches forValueOfCanonicalType except that enums have the
11568 /// full range of their type, not the range of their enumerators.
11569 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11570 assert(T->isCanonicalUnqualified());
11571
11572 if (const VectorType *VT = dyn_cast<VectorType>(T))
11573 T = VT->getElementType().getTypePtr();
11574 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11575 T = MT->getElementType().getTypePtr();
11576 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11577 T = CT->getElementType().getTypePtr();
11578 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11579 T = AT->getValueType().getTypePtr();
11580 if (const auto *ED = T->getAsEnumDecl())
11581 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11582 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11583 T = OBT->getUnderlyingType().getTypePtr();
11584
11585 if (const auto *EIT = dyn_cast<BitIntType>(T))
11586 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11587
11588 const BuiltinType *BT = cast<BuiltinType>(T);
11589 assert(BT->isInteger());
11590
11591 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11592 }
11593
11594 /// Returns the supremum of two ranges: i.e. their conservative merge.
11595 static IntRange join(IntRange L, IntRange R) {
11596 bool Unsigned = L.NonNegative && R.NonNegative;
11597 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11598 L.NonNegative && R.NonNegative);
11599 }
11600
11601 /// Return the range of a bitwise-AND of the two ranges.
11602 static IntRange bit_and(IntRange L, IntRange R) {
11603 unsigned Bits = std::max(L.Width, R.Width);
11604 bool NonNegative = false;
11605 if (L.NonNegative) {
11606 Bits = std::min(Bits, L.Width);
11607 NonNegative = true;
11608 }
11609 if (R.NonNegative) {
11610 Bits = std::min(Bits, R.Width);
11611 NonNegative = true;
11612 }
11613 return IntRange(Bits, NonNegative);
11614 }
11615
11616 /// Return the range of a sum of the two ranges.
11617 static IntRange sum(IntRange L, IntRange R) {
11618 bool Unsigned = L.NonNegative && R.NonNegative;
11619 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11620 Unsigned);
11621 }
11622
11623 /// Return the range of a difference of the two ranges.
11624 static IntRange difference(IntRange L, IntRange R) {
11625 // We need a 1-bit-wider range if:
11626 // 1) LHS can be negative: least value can be reduced.
11627 // 2) RHS can be negative: greatest value can be increased.
11628 bool CanWiden = !L.NonNegative || !R.NonNegative;
11629 bool Unsigned = L.NonNegative && R.Width == 0;
11630 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11631 !Unsigned,
11632 Unsigned);
11633 }
11634
11635 /// Return the range of a product of the two ranges.
11636 static IntRange product(IntRange L, IntRange R) {
11637 // If both LHS and RHS can be negative, we can form
11638 // -2^L * -2^R = 2^(L + R)
11639 // which requires L + R + 1 value bits to represent.
11640 bool CanWiden = !L.NonNegative && !R.NonNegative;
11641 bool Unsigned = L.NonNegative && R.NonNegative;
11642 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11643 Unsigned);
11644 }
11645
11646 /// Return the range of a remainder operation between the two ranges.
11647 static IntRange rem(IntRange L, IntRange R) {
11648 // The result of a remainder can't be larger than the result of
11649 // either side. The sign of the result is the sign of the LHS.
11650 bool Unsigned = L.NonNegative;
11651 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11652 Unsigned);
11653 }
11654};
11655
11656} // namespace
11657
11658static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11659 if (value.isSigned() && value.isNegative())
11660 return IntRange(value.getSignificantBits(), false);
11661
11662 if (value.getBitWidth() > MaxWidth)
11663 value = value.trunc(MaxWidth);
11664
11665 // isNonNegative() just checks the sign bit without considering
11666 // signedness.
11667 return IntRange(value.getActiveBits(), true);
11668}
11669
11670static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11671 if (result.isInt())
11672 return GetValueRange(result.getInt(), MaxWidth);
11673
11674 if (result.isVector()) {
11675 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11676 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11677 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11678 R = IntRange::join(R, El);
11679 }
11680 return R;
11681 }
11682
11683 if (result.isComplexInt()) {
11684 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11685 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11686 return IntRange::join(R, I);
11687 }
11688
11689 // This can happen with lossless casts to intptr_t of "based" lvalues.
11690 // Assume it might use arbitrary bits.
11691 // FIXME: The only reason we need to pass the type in here is to get
11692 // the sign right on this one case. It would be nice if APValue
11693 // preserved this.
11694 assert(result.isLValue() || result.isAddrLabelDiff());
11695 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11696}
11697
11698static QualType GetExprType(const Expr *E) {
11699 QualType Ty = E->getType();
11700 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11701 Ty = AtomicRHS->getValueType();
11702 return Ty;
11703}
11704
11705/// Attempts to estimate an approximate range for the given integer expression.
11706/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11707/// reliable estimation cannot be determined.
11708///
11709/// \param MaxWidth The width to which the value will be truncated.
11710/// \param InConstantContext If \c true, interpret the expression within a
11711/// constant context.
11712/// \param Approximate If \c true, provide a likely range of values by assuming
11713/// that arithmetic on narrower types remains within those types.
11714/// If \c false, return a range that includes all possible values
11715/// resulting from the expression.
11716/// \returns A range of values that the expression might take, or
11717/// std::nullopt if a reliable estimation cannot be determined.
11718static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11719 unsigned MaxWidth,
11720 bool InConstantContext,
11721 bool Approximate) {
11722 E = E->IgnoreParens();
11723
11724 // Try a full evaluation first.
11725 Expr::EvalResult result;
11726 if (E->EvaluateAsRValue(result, C, InConstantContext))
11727 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11728
11729 // I think we only want to look through implicit casts here; if the
11730 // user has an explicit widening cast, we should treat the value as
11731 // being of the new, wider type.
11732 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11733 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11734 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11735 Approximate);
11736
11737 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11738
11739 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11740 CE->getCastKind() == CK_BooleanToSignedIntegral;
11741
11742 // Assume that non-integer casts can span the full range of the type.
11743 if (!isIntegerCast)
11744 return OutputTypeRange;
11745
11746 std::optional<IntRange> SubRange = TryGetExprRange(
11747 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11748 InConstantContext, Approximate);
11749 if (!SubRange)
11750 return std::nullopt;
11751
11752 // Bail out if the subexpr's range is as wide as the cast type.
11753 if (SubRange->Width >= OutputTypeRange.Width)
11754 return OutputTypeRange;
11755
11756 // Otherwise, we take the smaller width, and we're non-negative if
11757 // either the output type or the subexpr is.
11758 return IntRange(SubRange->Width,
11759 SubRange->NonNegative || OutputTypeRange.NonNegative);
11760 }
11761
11762 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11763 // If we can fold the condition, just take that operand.
11764 bool CondResult;
11765 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11766 return TryGetExprRange(
11767 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11768 InConstantContext, Approximate);
11769
11770 // Otherwise, conservatively merge.
11771 // TryGetExprRange requires an integer expression, but a throw expression
11772 // results in a void type.
11773 Expr *TrueExpr = CO->getTrueExpr();
11774 if (TrueExpr->getType()->isVoidType())
11775 return std::nullopt;
11776
11777 std::optional<IntRange> L =
11778 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11779 if (!L)
11780 return std::nullopt;
11781
11782 Expr *FalseExpr = CO->getFalseExpr();
11783 if (FalseExpr->getType()->isVoidType())
11784 return std::nullopt;
11785
11786 std::optional<IntRange> R =
11787 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11788 if (!R)
11789 return std::nullopt;
11790
11791 return IntRange::join(*L, *R);
11792 }
11793
11794 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11795 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11796
11797 switch (BO->getOpcode()) {
11798 case BO_Cmp:
11799 llvm_unreachable("builtin <=> should have class type");
11800
11801 // Boolean-valued operations are single-bit and positive.
11802 case BO_LAnd:
11803 case BO_LOr:
11804 case BO_LT:
11805 case BO_GT:
11806 case BO_LE:
11807 case BO_GE:
11808 case BO_EQ:
11809 case BO_NE:
11810 return IntRange::forBoolType();
11811
11812 // The type of the assignments is the type of the LHS, so the RHS
11813 // is not necessarily the same type.
11814 case BO_MulAssign:
11815 case BO_DivAssign:
11816 case BO_RemAssign:
11817 case BO_AddAssign:
11818 case BO_SubAssign:
11819 case BO_XorAssign:
11820 case BO_OrAssign:
11821 // TODO: bitfields?
11822 return IntRange::forValueOfType(C, GetExprType(E));
11823
11824 // Simple assignments just pass through the RHS, which will have
11825 // been coerced to the LHS type.
11826 case BO_Assign:
11827 // TODO: bitfields?
11828 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11829 Approximate);
11830
11831 // Operations with opaque sources are black-listed.
11832 case BO_PtrMemD:
11833 case BO_PtrMemI:
11834 return IntRange::forValueOfType(C, GetExprType(E));
11835
11836 // Bitwise-and uses the *infinum* of the two source ranges.
11837 case BO_And:
11838 case BO_AndAssign:
11839 Combine = IntRange::bit_and;
11840 break;
11841
11842 // Left shift gets black-listed based on a judgement call.
11843 case BO_Shl:
11844 // ...except that we want to treat '1 << (blah)' as logically
11845 // positive. It's an important idiom.
11846 if (IntegerLiteral *I
11847 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11848 if (I->getValue() == 1) {
11849 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11850 return IntRange(R.Width, /*NonNegative*/ true);
11851 }
11852 }
11853 [[fallthrough]];
11854
11855 case BO_ShlAssign:
11856 return IntRange::forValueOfType(C, GetExprType(E));
11857
11858 // Right shift by a constant can narrow its left argument.
11859 case BO_Shr:
11860 case BO_ShrAssign: {
11861 std::optional<IntRange> L = TryGetExprRange(
11862 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11863 if (!L)
11864 return std::nullopt;
11865
11866 // If the shift amount is a positive constant, drop the width by
11867 // that much.
11868 if (std::optional<llvm::APSInt> shift =
11869 BO->getRHS()->getIntegerConstantExpr(C)) {
11870 if (shift->isNonNegative()) {
11871 if (shift->uge(L->Width))
11872 L->Width = (L->NonNegative ? 0 : 1);
11873 else
11874 L->Width -= shift->getZExtValue();
11875 }
11876 }
11877
11878 return L;
11879 }
11880
11881 // Comma acts as its right operand.
11882 case BO_Comma:
11883 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11884 Approximate);
11885
11886 case BO_Add:
11887 if (!Approximate)
11888 Combine = IntRange::sum;
11889 break;
11890
11891 case BO_Sub:
11892 if (BO->getLHS()->getType()->isPointerType())
11893 return IntRange::forValueOfType(C, GetExprType(E));
11894 if (!Approximate)
11895 Combine = IntRange::difference;
11896 break;
11897
11898 case BO_Mul:
11899 if (!Approximate)
11900 Combine = IntRange::product;
11901 break;
11902
11903 // The width of a division result is mostly determined by the size
11904 // of the LHS.
11905 case BO_Div: {
11906 // Don't 'pre-truncate' the operands.
11907 unsigned opWidth = C.getIntWidth(GetExprType(E));
11908 std::optional<IntRange> L = TryGetExprRange(
11909 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11910 if (!L)
11911 return std::nullopt;
11912
11913 // If the divisor is constant, use that.
11914 if (std::optional<llvm::APSInt> divisor =
11915 BO->getRHS()->getIntegerConstantExpr(C)) {
11916 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11917 if (log2 >= L->Width)
11918 L->Width = (L->NonNegative ? 0 : 1);
11919 else
11920 L->Width = std::min(L->Width - log2, MaxWidth);
11921 return L;
11922 }
11923
11924 // Otherwise, just use the LHS's width.
11925 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11926 // could be -1.
11927 std::optional<IntRange> R = TryGetExprRange(
11928 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11929 if (!R)
11930 return std::nullopt;
11931
11932 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11933 }
11934
11935 case BO_Rem:
11936 Combine = IntRange::rem;
11937 break;
11938
11939 // The default behavior is okay for these.
11940 case BO_Xor:
11941 case BO_Or:
11942 break;
11943 }
11944
11945 // Combine the two ranges, but limit the result to the type in which we
11946 // performed the computation.
11947 QualType T = GetExprType(E);
11948 unsigned opWidth = C.getIntWidth(T);
11949 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11950 InConstantContext, Approximate);
11951 if (!L)
11952 return std::nullopt;
11953
11954 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11955 InConstantContext, Approximate);
11956 if (!R)
11957 return std::nullopt;
11958
11959 IntRange C = Combine(*L, *R);
11960 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11961 C.Width = std::min(C.Width, MaxWidth);
11962 return C;
11963 }
11964
11965 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11966 switch (UO->getOpcode()) {
11967 // Boolean-valued operations are white-listed.
11968 case UO_LNot:
11969 return IntRange::forBoolType();
11970
11971 // Operations with opaque sources are black-listed.
11972 case UO_Deref:
11973 case UO_AddrOf: // should be impossible
11974 return IntRange::forValueOfType(C, GetExprType(E));
11975
11976 case UO_Minus: {
11977 if (E->getType()->isUnsignedIntegerType()) {
11978 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11979 Approximate);
11980 }
11981
11982 std::optional<IntRange> SubRange = TryGetExprRange(
11983 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11984
11985 if (!SubRange)
11986 return std::nullopt;
11987
11988 // If the range was previously non-negative, we need an extra bit for the
11989 // sign bit. Otherwise, we need an extra bit because the negation of the
11990 // most-negative value is one bit wider than that value.
11991 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11992 }
11993
11994 case UO_Not: {
11995 if (E->getType()->isUnsignedIntegerType()) {
11996 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11997 Approximate);
11998 }
11999
12000 std::optional<IntRange> SubRange = TryGetExprRange(
12001 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12002
12003 if (!SubRange)
12004 return std::nullopt;
12005
12006 // The width increments by 1 if the sub-expression cannot be negative
12007 // since it now can be.
12008 return IntRange(
12009 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12010 false);
12011 }
12012
12013 default:
12014 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12015 Approximate);
12016 }
12017 }
12018
12019 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12020 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
12021 Approximate);
12022
12023 if (const auto *BitField = E->getSourceBitField())
12024 return IntRange(BitField->getBitWidthValue(),
12025 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12026
12027 if (GetExprType(E)->isVoidType())
12028 return std::nullopt;
12029
12030 return IntRange::forValueOfType(C, GetExprType(E));
12031}
12032
12033static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12034 bool InConstantContext,
12035 bool Approximate) {
12036 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12037 Approximate);
12038}
12039
12040/// Checks whether the given value, which currently has the given
12041/// source semantics, has the same value when coerced through the
12042/// target semantics.
12043static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12044 const llvm::fltSemantics &Src,
12045 const llvm::fltSemantics &Tgt) {
12046 llvm::APFloat truncated = value;
12047
12048 bool ignored;
12049 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12050 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12051
12052 return truncated.bitwiseIsEqual(value);
12053}
12054
12055/// Checks whether the given value, which currently has the given
12056/// source semantics, has the same value when coerced through the
12057/// target semantics.
12058///
12059/// The value might be a vector of floats (or a complex number).
12060static bool IsSameFloatAfterCast(const APValue &value,
12061 const llvm::fltSemantics &Src,
12062 const llvm::fltSemantics &Tgt) {
12063 if (value.isFloat())
12064 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12065
12066 if (value.isVector()) {
12067 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12068 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12069 return false;
12070 return true;
12071 }
12072
12073 if (value.isMatrix()) {
12074 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12075 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12076 return false;
12077 return true;
12078 }
12079
12080 assert(value.isComplexFloat());
12081 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12082 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12083}
12084
12085static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12086 bool IsListInit = false);
12087
12088static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12089 // Suppress cases where we are comparing against an enum constant.
12090 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12091 if (isa<EnumConstantDecl>(DR->getDecl()))
12092 return true;
12093
12094 // Suppress cases where the value is expanded from a macro, unless that macro
12095 // is how a language represents a boolean literal. This is the case in both C
12096 // and Objective-C.
12097 SourceLocation BeginLoc = E->getBeginLoc();
12098 if (BeginLoc.isMacroID()) {
12099 StringRef MacroName = Lexer::getImmediateMacroName(
12100 BeginLoc, S.getSourceManager(), S.getLangOpts());
12101 return MacroName != "YES" && MacroName != "NO" &&
12102 MacroName != "true" && MacroName != "false";
12103 }
12104
12105 return false;
12106}
12107
12108static bool isKnownToHaveUnsignedValue(const Expr *E) {
12109 return E->getType()->isIntegerType() &&
12110 (!E->getType()->isSignedIntegerType() ||
12112}
12113
12114namespace {
12115/// The promoted range of values of a type. In general this has the
12116/// following structure:
12117///
12118/// |-----------| . . . |-----------|
12119/// ^ ^ ^ ^
12120/// Min HoleMin HoleMax Max
12121///
12122/// ... where there is only a hole if a signed type is promoted to unsigned
12123/// (in which case Min and Max are the smallest and largest representable
12124/// values).
12125struct PromotedRange {
12126 // Min, or HoleMax if there is a hole.
12127 llvm::APSInt PromotedMin;
12128 // Max, or HoleMin if there is a hole.
12129 llvm::APSInt PromotedMax;
12130
12131 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12132 if (R.Width == 0)
12133 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12134 else if (R.Width >= BitWidth && !Unsigned) {
12135 // Promotion made the type *narrower*. This happens when promoting
12136 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12137 // Treat all values of 'signed int' as being in range for now.
12138 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12139 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12140 } else {
12141 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12142 .extOrTrunc(BitWidth);
12143 PromotedMin.setIsUnsigned(Unsigned);
12144
12145 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12146 .extOrTrunc(BitWidth);
12147 PromotedMax.setIsUnsigned(Unsigned);
12148 }
12149 }
12150
12151 // Determine whether this range is contiguous (has no hole).
12152 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12153
12154 // Where a constant value is within the range.
12155 enum ComparisonResult {
12156 LT = 0x1,
12157 LE = 0x2,
12158 GT = 0x4,
12159 GE = 0x8,
12160 EQ = 0x10,
12161 NE = 0x20,
12162 InRangeFlag = 0x40,
12163
12164 Less = LE | LT | NE,
12165 Min = LE | InRangeFlag,
12166 InRange = InRangeFlag,
12167 Max = GE | InRangeFlag,
12168 Greater = GE | GT | NE,
12169
12170 OnlyValue = LE | GE | EQ | InRangeFlag,
12171 InHole = NE
12172 };
12173
12174 ComparisonResult compare(const llvm::APSInt &Value) const {
12175 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12176 Value.isUnsigned() == PromotedMin.isUnsigned());
12177 if (!isContiguous()) {
12178 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12179 if (Value.isMinValue()) return Min;
12180 if (Value.isMaxValue()) return Max;
12181 if (Value >= PromotedMin) return InRange;
12182 if (Value <= PromotedMax) return InRange;
12183 return InHole;
12184 }
12185
12186 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12187 case -1: return Less;
12188 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12189 case 1:
12190 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12191 case -1: return InRange;
12192 case 0: return Max;
12193 case 1: return Greater;
12194 }
12195 }
12196
12197 llvm_unreachable("impossible compare result");
12198 }
12199
12200 static std::optional<StringRef>
12201 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12202 if (Op == BO_Cmp) {
12203 ComparisonResult LTFlag = LT, GTFlag = GT;
12204 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12205
12206 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12207 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12208 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12209 return std::nullopt;
12210 }
12211
12212 ComparisonResult TrueFlag, FalseFlag;
12213 if (Op == BO_EQ) {
12214 TrueFlag = EQ;
12215 FalseFlag = NE;
12216 } else if (Op == BO_NE) {
12217 TrueFlag = NE;
12218 FalseFlag = EQ;
12219 } else {
12220 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12221 TrueFlag = LT;
12222 FalseFlag = GE;
12223 } else {
12224 TrueFlag = GT;
12225 FalseFlag = LE;
12226 }
12227 if (Op == BO_GE || Op == BO_LE)
12228 std::swap(TrueFlag, FalseFlag);
12229 }
12230 if (R & TrueFlag)
12231 return StringRef("true");
12232 if (R & FalseFlag)
12233 return StringRef("false");
12234 return std::nullopt;
12235 }
12236};
12237}
12238
12239static bool HasEnumType(const Expr *E) {
12240 // Strip off implicit integral promotions.
12241 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12242 if (ICE->getCastKind() != CK_IntegralCast &&
12243 ICE->getCastKind() != CK_NoOp)
12244 break;
12245 E = ICE->getSubExpr();
12246 }
12247
12248 return E->getType()->isEnumeralType();
12249}
12250
12252 // The values of this enumeration are used in the diagnostics
12253 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12254 enum ConstantValueKind {
12255 Miscellaneous = 0,
12256 LiteralTrue,
12257 LiteralFalse
12258 };
12259 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12260 return BL->getValue() ? ConstantValueKind::LiteralTrue
12261 : ConstantValueKind::LiteralFalse;
12262 return ConstantValueKind::Miscellaneous;
12263}
12264
12267 const llvm::APSInt &Value,
12268 bool RhsConstant) {
12270 return false;
12271
12272 Expr *OriginalOther = Other;
12273
12274 Constant = Constant->IgnoreParenImpCasts();
12275 Other = Other->IgnoreParenImpCasts();
12276
12277 // Suppress warnings on tautological comparisons between values of the same
12278 // enumeration type. There are only two ways we could warn on this:
12279 // - If the constant is outside the range of representable values of
12280 // the enumeration. In such a case, we should warn about the cast
12281 // to enumeration type, not about the comparison.
12282 // - If the constant is the maximum / minimum in-range value. For an
12283 // enumeratin type, such comparisons can be meaningful and useful.
12284 if (Constant->getType()->isEnumeralType() &&
12285 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12286 return false;
12287
12288 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12289 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12290 if (!OtherValueRange)
12291 return false;
12292
12293 QualType OtherT = Other->getType();
12294 if (const auto *AT = OtherT->getAs<AtomicType>())
12295 OtherT = AT->getValueType();
12296 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12297
12298 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12299 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12300 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12301 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12302 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12303
12304 // Whether we're treating Other as being a bool because of the form of
12305 // expression despite it having another type (typically 'int' in C).
12306 bool OtherIsBooleanDespiteType =
12307 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12308 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12309 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12310
12311 // Check if all values in the range of possible values of this expression
12312 // lead to the same comparison outcome.
12313 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12314 Value.isUnsigned());
12315 auto Cmp = OtherPromotedValueRange.compare(Value);
12316 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12317 if (!Result)
12318 return false;
12319
12320 // Also consider the range determined by the type alone. This allows us to
12321 // classify the warning under the proper diagnostic group.
12322 bool TautologicalTypeCompare = false;
12323 {
12324 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12325 Value.isUnsigned());
12326 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12327 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12328 RhsConstant)) {
12329 TautologicalTypeCompare = true;
12330 Cmp = TypeCmp;
12332 }
12333 }
12334
12335 // Don't warn if the non-constant operand actually always evaluates to the
12336 // same value.
12337 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12338 return false;
12339
12340 // Suppress the diagnostic for an in-range comparison if the constant comes
12341 // from a macro or enumerator. We don't want to diagnose
12342 //
12343 // some_long_value <= INT_MAX
12344 //
12345 // when sizeof(int) == sizeof(long).
12346 bool InRange = Cmp & PromotedRange::InRangeFlag;
12347 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12348 return false;
12349
12350 // A comparison of an unsigned bit-field against 0 is really a type problem,
12351 // even though at the type level the bit-field might promote to 'signed int'.
12352 if (Other->refersToBitField() && InRange && Value == 0 &&
12353 Other->getType()->isUnsignedIntegerOrEnumerationType())
12354 TautologicalTypeCompare = true;
12355
12356 // If this is a comparison to an enum constant, include that
12357 // constant in the diagnostic.
12358 const EnumConstantDecl *ED = nullptr;
12359 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12360 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12361
12362 // Should be enough for uint128 (39 decimal digits)
12363 SmallString<64> PrettySourceValue;
12364 llvm::raw_svector_ostream OS(PrettySourceValue);
12365 if (ED) {
12366 OS << '\'' << *ED << "' (" << Value << ")";
12367 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12368 Constant->IgnoreParenImpCasts())) {
12369 OS << (BL->getValue() ? "YES" : "NO");
12370 } else {
12371 OS << Value;
12372 }
12373
12374 if (!TautologicalTypeCompare) {
12375 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12376 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12377 << E->getOpcodeStr() << OS.str() << *Result
12378 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12379 return true;
12380 }
12381
12382 if (IsObjCSignedCharBool) {
12384 S.PDiag(diag::warn_tautological_compare_objc_bool)
12385 << OS.str() << *Result);
12386 return true;
12387 }
12388
12389 // FIXME: We use a somewhat different formatting for the in-range cases and
12390 // cases involving boolean values for historical reasons. We should pick a
12391 // consistent way of presenting these diagnostics.
12392 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12393
12395 E->getOperatorLoc(), E,
12396 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12397 : diag::warn_tautological_bool_compare)
12398 << OS.str() << classifyConstantValue(Constant) << OtherT
12399 << OtherIsBooleanDespiteType << *Result
12400 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12401 } else {
12402 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12403 unsigned Diag =
12404 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12405 ? (HasEnumType(OriginalOther)
12406 ? diag::warn_unsigned_enum_always_true_comparison
12407 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12408 : diag::warn_unsigned_always_true_comparison)
12409 : diag::warn_tautological_constant_compare;
12410
12411 S.Diag(E->getOperatorLoc(), Diag)
12412 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12413 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12414 }
12415
12416 return true;
12417}
12418
12419/// Analyze the operands of the given comparison. Implements the
12420/// fallback case from AnalyzeComparison.
12425
12426/// Implements -Wsign-compare.
12427///
12428/// \param E the binary operator to check for warnings
12430 // The type the comparison is being performed in.
12431 QualType T = E->getLHS()->getType();
12432
12433 // Only analyze comparison operators where both sides have been converted to
12434 // the same type.
12435 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12436 return AnalyzeImpConvsInComparison(S, E);
12437
12438 // Don't analyze value-dependent comparisons directly.
12439 if (E->isValueDependent())
12440 return AnalyzeImpConvsInComparison(S, E);
12441
12442 Expr *LHS = E->getLHS();
12443 Expr *RHS = E->getRHS();
12444
12445 if (T->isIntegralType(S.Context)) {
12446 std::optional<llvm::APSInt> RHSValue =
12448 std::optional<llvm::APSInt> LHSValue =
12450
12451 // We don't care about expressions whose result is a constant.
12452 if (RHSValue && LHSValue)
12453 return AnalyzeImpConvsInComparison(S, E);
12454
12455 // We only care about expressions where just one side is literal
12456 if ((bool)RHSValue ^ (bool)LHSValue) {
12457 // Is the constant on the RHS or LHS?
12458 const bool RhsConstant = (bool)RHSValue;
12459 Expr *Const = RhsConstant ? RHS : LHS;
12460 Expr *Other = RhsConstant ? LHS : RHS;
12461 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12462
12463 // Check whether an integer constant comparison results in a value
12464 // of 'true' or 'false'.
12465 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12466 return AnalyzeImpConvsInComparison(S, E);
12467 }
12468 }
12469
12470 if (!T->hasUnsignedIntegerRepresentation()) {
12471 // We don't do anything special if this isn't an unsigned integral
12472 // comparison: we're only interested in integral comparisons, and
12473 // signed comparisons only happen in cases we don't care to warn about.
12474 return AnalyzeImpConvsInComparison(S, E);
12475 }
12476
12477 LHS = LHS->IgnoreParenImpCasts();
12478 RHS = RHS->IgnoreParenImpCasts();
12479
12480 if (!S.getLangOpts().CPlusPlus) {
12481 // Avoid warning about comparison of integers with different signs when
12482 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12483 // the type of `E`.
12484 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12485 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12486 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12487 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12488 }
12489
12490 // Check to see if one of the (unmodified) operands is of different
12491 // signedness.
12492 Expr *signedOperand, *unsignedOperand;
12494 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12495 "unsigned comparison between two signed integer expressions?");
12496 signedOperand = LHS;
12497 unsignedOperand = RHS;
12498 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12499 signedOperand = RHS;
12500 unsignedOperand = LHS;
12501 } else {
12502 return AnalyzeImpConvsInComparison(S, E);
12503 }
12504
12505 // Otherwise, calculate the effective range of the signed operand.
12506 std::optional<IntRange> signedRange =
12508 /*Approximate=*/true);
12509 if (!signedRange)
12510 return;
12511
12512 // Go ahead and analyze implicit conversions in the operands. Note
12513 // that we skip the implicit conversions on both sides.
12516
12517 // If the signed range is non-negative, -Wsign-compare won't fire.
12518 if (signedRange->NonNegative)
12519 return;
12520
12521 // For (in)equality comparisons, if the unsigned operand is a
12522 // constant which cannot collide with a overflowed signed operand,
12523 // then reinterpreting the signed operand as unsigned will not
12524 // change the result of the comparison.
12525 if (E->isEqualityOp()) {
12526 unsigned comparisonWidth = S.Context.getIntWidth(T);
12527 std::optional<IntRange> unsignedRange = TryGetExprRange(
12528 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12529 /*Approximate=*/true);
12530 if (!unsignedRange)
12531 return;
12532
12533 // We should never be unable to prove that the unsigned operand is
12534 // non-negative.
12535 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12536
12537 if (unsignedRange->Width < comparisonWidth)
12538 return;
12539 }
12540
12542 S.PDiag(diag::warn_mixed_sign_comparison)
12543 << LHS->getType() << RHS->getType()
12544 << LHS->getSourceRange() << RHS->getSourceRange());
12545}
12546
12547/// Analyzes an attempt to assign the given value to a bitfield.
12548///
12549/// Returns true if there was something fishy about the attempt.
12551 SourceLocation InitLoc) {
12552 assert(Bitfield->isBitField());
12553 if (Bitfield->isInvalidDecl())
12554 return false;
12555
12556 // White-list bool bitfields.
12557 QualType BitfieldType = Bitfield->getType();
12558 if (BitfieldType->isBooleanType())
12559 return false;
12560
12561 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12562 // If the underlying enum type was not explicitly specified as an unsigned
12563 // type and the enum contain only positive values, MSVC++ will cause an
12564 // inconsistency by storing this as a signed type.
12565 if (S.getLangOpts().CPlusPlus11 &&
12566 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12567 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12568 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12569 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12570 << BitfieldEnumDecl;
12571 }
12572 }
12573
12574 // Ignore value- or type-dependent expressions.
12575 if (Bitfield->getBitWidth()->isValueDependent() ||
12576 Bitfield->getBitWidth()->isTypeDependent() ||
12577 Init->isValueDependent() ||
12578 Init->isTypeDependent())
12579 return false;
12580
12581 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12582 unsigned FieldWidth = Bitfield->getBitWidthValue();
12583
12585 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12587 // The RHS is not constant. If the RHS has an enum type, make sure the
12588 // bitfield is wide enough to hold all the values of the enum without
12589 // truncation.
12590 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12591 const PreferredTypeAttr *PTAttr = nullptr;
12592 if (!ED) {
12593 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12594 if (PTAttr)
12595 ED = PTAttr->getType()->getAsEnumDecl();
12596 }
12597 if (ED) {
12598 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12599
12600 // Enum types are implicitly signed on Windows, so check if there are any
12601 // negative enumerators to see if the enum was intended to be signed or
12602 // not.
12603 bool SignedEnum = ED->getNumNegativeBits() > 0;
12604
12605 // Check for surprising sign changes when assigning enum values to a
12606 // bitfield of different signedness. If the bitfield is signed and we
12607 // have exactly the right number of bits to store this unsigned enum,
12608 // suggest changing the enum to an unsigned type. This typically happens
12609 // on Windows where unfixed enums always use an underlying type of 'int'.
12610 unsigned DiagID = 0;
12611 if (SignedEnum && !SignedBitfield) {
12612 DiagID =
12613 PTAttr == nullptr
12614 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12615 : diag::
12616 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12617 } else if (SignedBitfield && !SignedEnum &&
12618 ED->getNumPositiveBits() == FieldWidth) {
12619 DiagID =
12620 PTAttr == nullptr
12621 ? diag::warn_signed_bitfield_enum_conversion
12622 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12623 }
12624 if (DiagID) {
12625 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12626 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12627 SourceRange TypeRange =
12628 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12629 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12630 << SignedEnum << TypeRange;
12631 if (PTAttr)
12632 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12633 << ED;
12634 }
12635
12636 // Compute the required bitwidth. If the enum has negative values, we need
12637 // one more bit than the normal number of positive bits to represent the
12638 // sign bit.
12639 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12640 ED->getNumNegativeBits())
12641 : ED->getNumPositiveBits();
12642
12643 // Check the bitwidth.
12644 if (BitsNeeded > FieldWidth) {
12645 Expr *WidthExpr = Bitfield->getBitWidth();
12646 auto DiagID =
12647 PTAttr == nullptr
12648 ? diag::warn_bitfield_too_small_for_enum
12649 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12650 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12651 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12652 << BitsNeeded << ED << WidthExpr->getSourceRange();
12653 if (PTAttr)
12654 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12655 << ED;
12656 }
12657 }
12658
12659 return false;
12660 }
12661
12662 llvm::APSInt Value = Result.Val.getInt();
12663
12664 unsigned OriginalWidth = Value.getBitWidth();
12665
12666 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12667 // false positives where the user is demonstrating they intend to use the
12668 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12669 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12670 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12671 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12672 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12673 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12674 S.findMacroSpelling(MaybeMacroLoc, "true"))
12675 return false;
12676 }
12677
12678 if (!Value.isSigned() || Value.isNegative())
12679 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12680 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12681 OriginalWidth = Value.getSignificantBits();
12682
12683 if (OriginalWidth <= FieldWidth)
12684 return false;
12685
12686 // Compute the value which the bitfield will contain.
12687 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12688 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12689
12690 // Check whether the stored value is equal to the original value.
12691 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12692 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12693 return false;
12694
12695 std::string PrettyValue = toString(Value, 10);
12696 std::string PrettyTrunc = toString(TruncatedValue, 10);
12697
12698 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12699 ? diag::warn_impcast_single_bit_bitield_precision_constant
12700 : diag::warn_impcast_bitfield_precision_constant)
12701 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12702 << Init->getSourceRange();
12703
12704 return true;
12705}
12706
12707/// Analyze the given simple or compound assignment for warning-worthy
12708/// operations.
12710 // Just recurse on the LHS.
12712
12713 // We want to recurse on the RHS as normal unless we're assigning to
12714 // a bitfield.
12715 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12716 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12717 E->getOperatorLoc())) {
12718 // Recurse, ignoring any implicit conversions on the RHS.
12720 E->getOperatorLoc());
12721 }
12722 }
12723
12724 // Set context flag for overflow behavior type assignment analysis, use RAII
12725 // pattern to handle nested assignments.
12726 llvm::SaveAndRestore OBTAssignmentContext(
12728
12730
12731 // Diagnose implicitly sequentially-consistent atomic assignment.
12732 if (E->getLHS()->getType()->isAtomicType())
12733 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12734}
12735
12736/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12737static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12738 QualType T, SourceLocation CContext, unsigned diag,
12739 bool PruneControlFlow = false) {
12740 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12741 // address space annotations isn't really useful. The warnings aren't because
12742 // you're converting a `private int` to `unsigned int`, it is because you're
12743 // conerting `int` to `unsigned int`.
12744 if (SourceType.hasAddressSpace())
12745 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12746 if (T.hasAddressSpace())
12748 if (PruneControlFlow) {
12750 S.PDiag(diag)
12751 << SourceType << T << E->getSourceRange()
12752 << SourceRange(CContext));
12753 return;
12754 }
12755 S.Diag(E->getExprLoc(), diag)
12756 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12757}
12758
12759/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12760static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12761 SourceLocation CContext, unsigned diag,
12762 bool PruneControlFlow = false) {
12763 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12764}
12765
12766/// Diagnose an implicit cast from a floating point value to an integer value.
12767static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12768 SourceLocation CContext) {
12769 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12770 bool PruneWarnings = S.inTemplateInstantiation();
12771
12772 const Expr *InnerE = E->IgnoreParenImpCasts();
12773 // We also want to warn on, e.g., "int i = -1.234"
12774 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12775 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12776 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12777
12778 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12779
12780 llvm::APFloat Value(0.0);
12781 bool IsConstant =
12783 if (!IsConstant) {
12784 if (S.ObjC().isSignedCharBool(T)) {
12786 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12787 << E->getType());
12788 }
12789
12790 return DiagnoseImpCast(S, E, T, CContext,
12791 diag::warn_impcast_float_integer, PruneWarnings);
12792 }
12793
12794 bool isExact = false;
12795
12796 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12797 T->hasUnsignedIntegerRepresentation());
12798 llvm::APFloat::opStatus Result = Value.convertToInteger(
12799 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12800
12801 // FIXME: Force the precision of the source value down so we don't print
12802 // digits which are usually useless (we don't really care here if we
12803 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12804 // would automatically print the shortest representation, but it's a bit
12805 // tricky to implement.
12806 SmallString<16> PrettySourceValue;
12807 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12808 precision = (precision * 59 + 195) / 196;
12809 Value.toString(PrettySourceValue, precision);
12810
12811 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12813 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12814 << PrettySourceValue);
12815 }
12816
12817 if (Result == llvm::APFloat::opOK && isExact) {
12818 if (IsLiteral) return;
12819 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12820 PruneWarnings);
12821 }
12822
12823 // Conversion of a floating-point value to a non-bool integer where the
12824 // integral part cannot be represented by the integer type is undefined.
12825 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12826 return DiagnoseImpCast(
12827 S, E, T, CContext,
12828 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12829 : diag::warn_impcast_float_to_integer_out_of_range,
12830 PruneWarnings);
12831
12832 unsigned DiagID = 0;
12833 if (IsLiteral) {
12834 // Warn on floating point literal to integer.
12835 DiagID = diag::warn_impcast_literal_float_to_integer;
12836 } else if (IntegerValue == 0) {
12837 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12838 return DiagnoseImpCast(S, E, T, CContext,
12839 diag::warn_impcast_float_integer, PruneWarnings);
12840 }
12841 // Warn on non-zero to zero conversion.
12842 DiagID = diag::warn_impcast_float_to_integer_zero;
12843 } else {
12844 if (IntegerValue.isUnsigned()) {
12845 if (!IntegerValue.isMaxValue()) {
12846 return DiagnoseImpCast(S, E, T, CContext,
12847 diag::warn_impcast_float_integer, PruneWarnings);
12848 }
12849 } else { // IntegerValue.isSigned()
12850 if (!IntegerValue.isMaxSignedValue() &&
12851 !IntegerValue.isMinSignedValue()) {
12852 return DiagnoseImpCast(S, E, T, CContext,
12853 diag::warn_impcast_float_integer, PruneWarnings);
12854 }
12855 }
12856 // Warn on evaluatable floating point expression to integer conversion.
12857 DiagID = diag::warn_impcast_float_to_integer;
12858 }
12859
12860 SmallString<16> PrettyTargetValue;
12861 if (IsBool)
12862 PrettyTargetValue = Value.isZero() ? "false" : "true";
12863 else
12864 IntegerValue.toString(PrettyTargetValue);
12865
12866 if (PruneWarnings) {
12868 S.PDiag(DiagID)
12869 << E->getType() << T.getUnqualifiedType()
12870 << PrettySourceValue << PrettyTargetValue
12871 << E->getSourceRange() << SourceRange(CContext));
12872 } else {
12873 S.Diag(E->getExprLoc(), DiagID)
12874 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12875 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12876 }
12877}
12878
12879/// Analyze the given compound assignment for the possible losing of
12880/// floating-point precision.
12882 assert(isa<CompoundAssignOperator>(E) &&
12883 "Must be compound assignment operation");
12884 // Recurse on the LHS and RHS in here
12887
12888 if (E->getLHS()->getType()->isAtomicType())
12889 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12890
12891 // Now check the outermost expression
12892 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12893 const auto *RBT = cast<CompoundAssignOperator>(E)
12894 ->getComputationResultType()
12895 ->getAs<BuiltinType>();
12896
12897 // The below checks assume source is floating point.
12898 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12899
12900 // If source is floating point but target is an integer.
12901 if (ResultBT->isInteger())
12902 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12903 E->getExprLoc(), diag::warn_impcast_float_integer);
12904
12905 if (!ResultBT->isFloatingPoint())
12906 return;
12907
12908 // If both source and target are floating points, warn about losing precision.
12910 QualType(ResultBT, 0), QualType(RBT, 0));
12911 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12912 // warn about dropping FP rank.
12913 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12914 diag::warn_impcast_float_result_precision);
12915}
12916
12917static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12918 IntRange Range) {
12919 if (!Range.Width) return "0";
12920
12921 llvm::APSInt ValueInRange = Value;
12922 ValueInRange.setIsSigned(!Range.NonNegative);
12923 ValueInRange = ValueInRange.trunc(Range.Width);
12924 return toString(ValueInRange, 10);
12925}
12926
12927static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12928 bool ToBool) {
12929 if (!isa<ImplicitCastExpr>(Ex))
12930 return false;
12931
12932 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12934 const Type *Source =
12936 if (Target->isDependentType())
12937 return false;
12938
12939 const auto *FloatCandidateBT =
12940 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12941 const Type *BoolCandidateType = ToBool ? Target : Source;
12942
12943 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12944 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12945}
12946
12947static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12948 SourceLocation CC) {
12949 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12950 const Expr *CurrA = TheCall->getArg(I);
12951 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12952 continue;
12953
12954 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12955 S, TheCall->getArg(I - 1), false));
12956 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12957 S, TheCall->getArg(I + 1), false));
12958 if (IsSwapped) {
12959 // Warn on this floating-point to bool conversion.
12961 CurrA->getType(), CC,
12962 diag::warn_impcast_floating_point_to_bool);
12963 }
12964 }
12965}
12966
12968 SourceLocation CC) {
12969 // Don't warn on functions which have return type nullptr_t.
12970 if (isa<CallExpr>(E))
12971 return;
12972
12973 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12974 const Expr *NewE = E->IgnoreParenImpCasts();
12975 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12976 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12977 if (!IsGNUNullExpr && !HasNullPtrType)
12978 return;
12979
12980 // Return if target type is a safe conversion.
12981 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12982 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12983 return;
12984
12985 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12986 E->getExprLoc()))
12987 return;
12988
12990
12991 // Venture through the macro stacks to get to the source of macro arguments.
12992 // The new location is a better location than the complete location that was
12993 // passed in.
12994 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12996
12997 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12998 if (IsGNUNullExpr && Loc.isMacroID()) {
12999 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13000 Loc, S.SourceMgr, S.getLangOpts());
13001 if (MacroName == "NULL")
13003 }
13004
13005 // Only warn if the null and context location are in the same macro expansion.
13006 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13007 return;
13008
13009 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13010 << HasNullPtrType << T << SourceRange(CC)
13012 S.getFixItZeroLiteralForType(T, Loc));
13013}
13014
13015// Helper function to filter out cases for constant width constant conversion.
13016// Don't warn on char array initialization or for non-decimal values.
13018 SourceLocation CC) {
13019 // If initializing from a constant, and the constant starts with '0',
13020 // then it is a binary, octal, or hexadecimal. Allow these constants
13021 // to fill all the bits, even if there is a sign change.
13022 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13023 const char FirstLiteralCharacter =
13024 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13025 if (FirstLiteralCharacter == '0')
13026 return false;
13027 }
13028
13029 // If the CC location points to a '{', and the type is char, then assume
13030 // assume it is an array initialization.
13031 if (CC.isValid() && T->isCharType()) {
13032 const char FirstContextCharacter =
13034 if (FirstContextCharacter == '{')
13035 return false;
13036 }
13037
13038 return true;
13039}
13040
13042 const auto *IL = dyn_cast<IntegerLiteral>(E);
13043 if (!IL) {
13044 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13045 if (UO->getOpcode() == UO_Minus)
13046 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13047 }
13048 }
13049
13050 return IL;
13051}
13052
13054 E = E->IgnoreParenImpCasts();
13055 SourceLocation ExprLoc = E->getExprLoc();
13056
13057 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13058 BinaryOperator::Opcode Opc = BO->getOpcode();
13060 // Do not diagnose unsigned shifts.
13061 if (Opc == BO_Shl) {
13062 const auto *LHS = getIntegerLiteral(BO->getLHS());
13063 const auto *RHS = getIntegerLiteral(BO->getRHS());
13064 if (LHS && LHS->getValue() == 0)
13065 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13066 else if (!E->isValueDependent() && LHS && RHS &&
13067 RHS->getValue().isNonNegative() &&
13069 S.Diag(ExprLoc, diag::warn_left_shift_always)
13070 << (Result.Val.getInt() != 0);
13071 else if (E->getType()->isSignedIntegerType())
13072 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13075 ") != 0");
13076 }
13077 }
13078
13079 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13080 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13081 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13082 if (!LHS || !RHS)
13083 return;
13084 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13085 (RHS->getValue() == 0 || RHS->getValue() == 1))
13086 // Do not diagnose common idioms.
13087 return;
13088 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13089 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13090 }
13091}
13092
13094 const Type *Target, Expr *E,
13095 QualType T,
13096 SourceLocation CC) {
13097 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13098 Source != Target);
13099
13100 // Lone surrogates have a distinct representation in UTF-32.
13101 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13102 // so don't warn on such conversion.
13103 if (Source->isChar16Type() && Target->isChar32Type())
13104 return;
13105
13109 llvm::APSInt Value(32);
13110 Value = Result.Val.getInt();
13111 bool IsASCII = Value <= 0x7F;
13112 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13113 bool ConversionPreservesSemantics =
13114 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13115
13116 if (!ConversionPreservesSemantics) {
13117 auto IsSingleCodeUnitCP = [](const QualType &T,
13118 const llvm::APSInt &Value) {
13119 if (T->isChar8Type())
13120 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13121 if (T->isChar16Type())
13122 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13123 assert(T->isChar32Type());
13124 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13125 };
13126
13127 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13128 << E->getType() << T
13129 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13130 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13131 }
13132 } else {
13133 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13135 DiagnoseImpCast(S, E, T, CC,
13136 LosesPrecision ? diag::warn_impcast_unicode_precision
13137 : diag::warn_impcast_unicode_char_type);
13138 }
13139}
13140
13142 From = Context.getCanonicalType(From);
13143 To = Context.getCanonicalType(To);
13144 QualType MaybePointee = From->getPointeeType();
13145 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13146 From = MaybePointee;
13147 MaybePointee = To->getPointeeType();
13148 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13149 To = MaybePointee;
13150
13151 if (const auto *FromFn = From->getAs<FunctionType>()) {
13152 if (const auto *ToFn = To->getAs<FunctionType>()) {
13153 if (FromFn->getCFIUncheckedCalleeAttr() &&
13154 !ToFn->getCFIUncheckedCalleeAttr())
13155 return true;
13156 }
13157 }
13158 return false;
13159}
13160
13162 bool *ICContext, bool IsListInit) {
13163 if (E->isTypeDependent() || E->isValueDependent()) return;
13164
13165 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13166 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13167 if (Source == Target) return;
13168 if (Target->isDependentType()) return;
13169
13170 // If the conversion context location is invalid don't complain. We also
13171 // don't want to emit a warning if the issue occurs from the expansion of
13172 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13173 // delay this check as long as possible. Once we detect we are in that
13174 // scenario, we just return.
13175 if (CC.isInvalid())
13176 return;
13177
13178 if (Source->isAtomicType())
13179 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13180
13181 // Diagnose implicit casts to bool.
13182 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13183 if (isa<StringLiteral>(E))
13184 // Warn on string literal to bool. Checks for string literals in logical
13185 // and expressions, for instance, assert(0 && "error here"), are
13186 // prevented by a check in AnalyzeImplicitConversions().
13187 return DiagnoseImpCast(*this, E, T, CC,
13188 diag::warn_impcast_string_literal_to_bool);
13191 // This covers the literal expressions that evaluate to Objective-C
13192 // objects.
13193 return DiagnoseImpCast(*this, E, T, CC,
13194 diag::warn_impcast_objective_c_literal_to_bool);
13195 }
13196 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13197 // Warn on pointer to bool conversion that is always true.
13199 SourceRange(CC));
13200 }
13201 }
13202
13204
13205 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13206 // is a typedef for signed char (macOS), then that constant value has to be 1
13207 // or 0.
13208 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13211 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13213 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13214 << toString(Result.Val.getInt(), 10));
13215 }
13216 return;
13217 }
13218 }
13219
13220 // Check implicit casts from Objective-C collection literals to specialized
13221 // collection types, e.g., NSArray<NSString *> *.
13222 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13223 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13224 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13225 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13226
13227 // Strip complex types.
13228 if (isa<ComplexType>(Source)) {
13229 if (!isa<ComplexType>(Target)) {
13230 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13231 return;
13232
13233 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13234 return DiagnoseImpCast(*this, E, T, CC,
13235 diag::err_impcast_incompatible_type);
13236 }
13237
13238 return DiagnoseImpCast(*this, E, T, CC,
13240 ? diag::err_impcast_complex_scalar
13241 : diag::warn_impcast_complex_scalar);
13242 }
13243
13244 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13245 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13246 }
13247
13248 // Strip vector types.
13249 if (isa<VectorType>(Source)) {
13250 if (Target->isSveVLSBuiltinType() &&
13251 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13252 QualType(Source, 0)) ||
13253 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13254 QualType(Source, 0))))
13255 return;
13256
13257 if (Target->isRVVVLSBuiltinType() &&
13258 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13259 QualType(Source, 0)) ||
13260 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13261 QualType(Source, 0))))
13262 return;
13263
13264 if (!isa<VectorType>(Target)) {
13265 if (SourceMgr.isInSystemMacro(CC))
13266 return;
13267 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13268 }
13269 if (getLangOpts().HLSL &&
13270 Target->castAs<VectorType>()->getNumElements() <
13271 Source->castAs<VectorType>()->getNumElements()) {
13272 // Diagnose vector truncation but don't return. We may also want to
13273 // diagnose an element conversion.
13274 DiagnoseImpCast(*this, E, T, CC,
13275 diag::warn_hlsl_impcast_vector_truncation);
13276 }
13277
13278 // If the vector cast is cast between two vectors of the same size, it is
13279 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13280 if (!getLangOpts().HLSL &&
13281 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13282 return;
13283
13284 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13285 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13286 }
13287 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13288 Target = VecTy->getElementType().getTypePtr();
13289
13290 // Strip matrix types.
13291 if (isa<ConstantMatrixType>(Source)) {
13292 if (Target->isScalarType())
13293 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13294
13297 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13298 // Diagnose Matrix truncation but don't return. We may also want to
13299 // diagnose an element conversion.
13300 DiagnoseImpCast(*this, E, T, CC,
13301 diag::warn_hlsl_impcast_matrix_truncation);
13302 }
13303
13304 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13305 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13306 }
13307 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13308 Target = MatTy->getElementType().getTypePtr();
13309
13310 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13311 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13312
13313 // Strip SVE vector types
13314 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13315 // Need the original target type for vector type checks
13316 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13317 // Handle conversion from scalable to fixed when msve-vector-bits is
13318 // specified
13319 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13320 QualType(Source, 0)) ||
13321 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13322 QualType(Source, 0)))
13323 return;
13324
13325 // If the vector cast is cast between two vectors of the same size, it is
13326 // a bitcast, not a conversion.
13327 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13328 return;
13329
13330 Source = SourceBT->getSveEltType(Context).getTypePtr();
13331 }
13332
13333 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13334 Target = TargetBT->getSveEltType(Context).getTypePtr();
13335
13336 // If the source is floating point...
13337 if (SourceBT && SourceBT->isFloatingPoint()) {
13338 // ...and the target is floating point...
13339 if (TargetBT && TargetBT->isFloatingPoint()) {
13340 // ...then warn if we're dropping FP rank.
13341
13343 QualType(SourceBT, 0), QualType(TargetBT, 0));
13344 if (Order > 0) {
13345 // Don't warn about float constants that are precisely
13346 // representable in the target type.
13347 Expr::EvalResult result;
13348 if (E->EvaluateAsRValue(result, Context)) {
13349 // Value might be a float, a float vector, or a float complex.
13351 result.Val,
13352 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13353 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13354 return;
13355 }
13356
13357 if (SourceMgr.isInSystemMacro(CC))
13358 return;
13359
13360 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13361 }
13362 // ... or possibly if we're increasing rank, too
13363 else if (Order < 0) {
13364 if (SourceMgr.isInSystemMacro(CC))
13365 return;
13366
13367 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13368 }
13369 return;
13370 }
13371
13372 // If the target is integral, always warn.
13373 if (TargetBT && TargetBT->isInteger()) {
13374 if (SourceMgr.isInSystemMacro(CC))
13375 return;
13376
13377 DiagnoseFloatingImpCast(*this, E, T, CC);
13378 }
13379
13380 // Detect the case where a call result is converted from floating-point to
13381 // to bool, and the final argument to the call is converted from bool, to
13382 // discover this typo:
13383 //
13384 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13385 //
13386 // FIXME: This is an incredibly special case; is there some more general
13387 // way to detect this class of misplaced-parentheses bug?
13388 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13389 // Check last argument of function call to see if it is an
13390 // implicit cast from a type matching the type the result
13391 // is being cast to.
13392 CallExpr *CEx = cast<CallExpr>(E);
13393 if (unsigned NumArgs = CEx->getNumArgs()) {
13394 Expr *LastA = CEx->getArg(NumArgs - 1);
13395 Expr *InnerE = LastA->IgnoreParenImpCasts();
13396 if (isa<ImplicitCastExpr>(LastA) &&
13397 InnerE->getType()->isBooleanType()) {
13398 // Warn on this floating-point to bool conversion
13399 DiagnoseImpCast(*this, E, T, CC,
13400 diag::warn_impcast_floating_point_to_bool);
13401 }
13402 }
13403 }
13404 return;
13405 }
13406
13407 // Valid casts involving fixed point types should be accounted for here.
13408 if (Source->isFixedPointType()) {
13409 if (Target->isUnsaturatedFixedPointType()) {
13413 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13414 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13415 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13416 if (Value > MaxVal || Value < MinVal) {
13418 PDiag(diag::warn_impcast_fixed_point_range)
13419 << Value.toString() << T
13420 << E->getSourceRange()
13421 << clang::SourceRange(CC));
13422 return;
13423 }
13424 }
13425 } else if (Target->isIntegerType()) {
13429 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13430
13431 bool Overflowed;
13432 llvm::APSInt IntResult = FXResult.convertToInt(
13433 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13434 &Overflowed);
13435
13436 if (Overflowed) {
13438 PDiag(diag::warn_impcast_fixed_point_range)
13439 << FXResult.toString() << T
13440 << E->getSourceRange()
13441 << clang::SourceRange(CC));
13442 return;
13443 }
13444 }
13445 }
13446 } else if (Target->isUnsaturatedFixedPointType()) {
13447 if (Source->isIntegerType()) {
13451 llvm::APSInt Value = Result.Val.getInt();
13452
13453 bool Overflowed;
13454 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13455 Value, Context.getFixedPointSemantics(T), &Overflowed);
13456
13457 if (Overflowed) {
13459 PDiag(diag::warn_impcast_fixed_point_range)
13460 << toString(Value, /*Radix=*/10) << T
13461 << E->getSourceRange()
13462 << clang::SourceRange(CC));
13463 return;
13464 }
13465 }
13466 }
13467 }
13468
13469 // If we are casting an integer type to a floating point type without
13470 // initialization-list syntax, we might lose accuracy if the floating
13471 // point type has a narrower significand than the integer type.
13472 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13473 TargetBT->isFloatingType() && !IsListInit) {
13474 // Determine the number of precision bits in the source integer type.
13475 std::optional<IntRange> SourceRange =
13477 /*Approximate=*/true);
13478 if (!SourceRange)
13479 return;
13480 unsigned int SourcePrecision = SourceRange->Width;
13481
13482 // Determine the number of precision bits in the
13483 // target floating point type.
13484 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13485 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13486
13487 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13488 SourcePrecision > TargetPrecision) {
13489
13490 if (std::optional<llvm::APSInt> SourceInt =
13492 // If the source integer is a constant, convert it to the target
13493 // floating point type. Issue a warning if the value changes
13494 // during the whole conversion.
13495 llvm::APFloat TargetFloatValue(
13496 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13497 llvm::APFloat::opStatus ConversionStatus =
13498 TargetFloatValue.convertFromAPInt(
13499 *SourceInt, SourceBT->isSignedInteger(),
13500 llvm::APFloat::rmNearestTiesToEven);
13501
13502 if (ConversionStatus != llvm::APFloat::opOK) {
13503 SmallString<32> PrettySourceValue;
13504 SourceInt->toString(PrettySourceValue, 10);
13505 SmallString<32> PrettyTargetValue;
13506 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13507
13509 E->getExprLoc(), E,
13510 PDiag(diag::warn_impcast_integer_float_precision_constant)
13511 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13512 << E->getSourceRange() << clang::SourceRange(CC));
13513 }
13514 } else {
13515 // Otherwise, the implicit conversion may lose precision.
13516 DiagnoseImpCast(*this, E, T, CC,
13517 diag::warn_impcast_integer_float_precision);
13518 }
13519 }
13520 }
13521
13522 DiagnoseNullConversion(*this, E, T, CC);
13523
13525
13526 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13527 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13528 return;
13529 }
13530
13531 if (Target->isBooleanType())
13532 DiagnoseIntInBoolContext(*this, E);
13533
13535 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13536 << QualType(Source, 0) << QualType(Target, 0);
13537 }
13538
13539 if (!Source->isIntegerType() || !Target->isIntegerType())
13540 return;
13541
13542 // TODO: remove this early return once the false positives for constant->bool
13543 // in templates, macros, etc, are reduced or removed.
13544 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13545 return;
13546
13547 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13548 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13550 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13551 << E->getType());
13552 }
13553 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13554 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13555 if (!LikelySourceRange)
13556 return;
13557
13558 IntRange SourceTypeRange =
13559 IntRange::forTargetOfCanonicalType(Context, Source);
13560 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13561
13562 if (LikelySourceRange->Width > TargetRange.Width) {
13563 // Check if target is a wrapping OBT - if so, don't warn about constant
13564 // conversion as this type may be used intentionally with implicit
13565 // truncation, especially during assignments.
13566 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13567 if (TargetOBT->isWrapKind()) {
13568 return;
13569 }
13570 }
13571
13572 // Check if source expression has an explicit __ob_wrap cast because if so,
13573 // wrapping was explicitly requested and we shouldn't warn
13574 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13575 if (SourceOBT->isWrapKind()) {
13576 return;
13577 }
13578 }
13579
13580 // If the source is a constant, use a default-on diagnostic.
13581 // TODO: this should happen for bitfield stores, too.
13585 llvm::APSInt Value(32);
13586 Value = Result.Val.getInt();
13587
13588 if (SourceMgr.isInSystemMacro(CC))
13589 return;
13590
13591 std::string PrettySourceValue = toString(Value, 10);
13592 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13593
13595 PDiag(diag::warn_impcast_integer_precision_constant)
13596 << PrettySourceValue << PrettyTargetValue
13597 << E->getType() << T << E->getSourceRange()
13598 << SourceRange(CC));
13599 return;
13600 }
13601
13602 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13603 if (SourceMgr.isInSystemMacro(CC))
13604 return;
13605
13606 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13607 if (UO->getOpcode() == UO_Minus)
13608 return DiagnoseImpCast(
13609 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13610 }
13611
13612 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13613 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13614 /* pruneControlFlow */ true);
13615 return DiagnoseImpCast(*this, E, T, CC,
13616 diag::warn_impcast_integer_precision);
13617 }
13618
13619 if (TargetRange.Width > SourceTypeRange.Width) {
13620 if (auto *UO = dyn_cast<UnaryOperator>(E))
13621 if (UO->getOpcode() == UO_Minus)
13622 if (Source->isUnsignedIntegerType()) {
13623 if (Target->isUnsignedIntegerType())
13624 return DiagnoseImpCast(*this, E, T, CC,
13625 diag::warn_impcast_high_order_zero_bits);
13626 if (Target->isSignedIntegerType())
13627 return DiagnoseImpCast(*this, E, T, CC,
13628 diag::warn_impcast_nonnegative_result);
13629 }
13630 }
13631
13632 if (TargetRange.Width == LikelySourceRange->Width &&
13633 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13634 Source->isSignedIntegerType()) {
13635 // Warn when doing a signed to signed conversion, warn if the positive
13636 // source value is exactly the width of the target type, which will
13637 // cause a negative value to be stored.
13638
13641 !SourceMgr.isInSystemMacro(CC)) {
13642 llvm::APSInt Value = Result.Val.getInt();
13643 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13644 std::string PrettySourceValue = toString(Value, 10);
13645 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13646
13647 Diag(E->getExprLoc(),
13648 PDiag(diag::warn_impcast_integer_precision_constant)
13649 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13650 << E->getSourceRange() << SourceRange(CC));
13651 return;
13652 }
13653 }
13654
13655 // Fall through for non-constants to give a sign conversion warning.
13656 }
13657
13658 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13659 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13660 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13661 LikelySourceRange->Width == TargetRange.Width))) {
13662 if (SourceMgr.isInSystemMacro(CC))
13663 return;
13664
13665 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13666 TargetBT->isInteger() &&
13667 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13668 return;
13669 }
13670
13671 unsigned DiagID = diag::warn_impcast_integer_sign;
13672
13673 // Traditionally, gcc has warned about this under -Wsign-compare.
13674 // We also want to warn about it in -Wconversion.
13675 // So if -Wconversion is off, use a completely identical diagnostic
13676 // in the sign-compare group.
13677 // The conditional-checking code will
13678 if (ICContext) {
13679 DiagID = diag::warn_impcast_integer_sign_conditional;
13680 *ICContext = true;
13681 }
13682
13683 DiagnoseImpCast(*this, E, T, CC, DiagID);
13684 }
13685
13686 // If we're implicitly converting from an integer into an enumeration, that
13687 // is valid in C but invalid in C++.
13688 QualType SourceType = E->getEnumCoercedType(Context);
13689 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13690 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13691 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13692
13693 // Diagnose conversions between different enumeration types.
13694 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13695 // type, to give us better diagnostics.
13696 Source = Context.getCanonicalType(SourceType).getTypePtr();
13697
13698 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13699 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13700 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13701 TargetEnum->getDecl()->hasNameForLinkage() &&
13702 SourceEnum != TargetEnum) {
13703 if (SourceMgr.isInSystemMacro(CC))
13704 return;
13705
13706 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13707 diag::warn_impcast_different_enum_types);
13708 }
13709}
13710
13712 SourceLocation CC, QualType T);
13713
13715 SourceLocation CC, bool &ICContext) {
13716 E = E->IgnoreParenImpCasts();
13717 // Diagnose incomplete type for second or third operand in C.
13718 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13719 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13720
13721 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13722 return CheckConditionalOperator(S, CO, CC, T);
13723
13725 if (E->getType() != T)
13726 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13727}
13728
13730 SourceLocation CC, QualType T) {
13732
13733 Expr *TrueExpr = E->getTrueExpr();
13734 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13735 TrueExpr = BCO->getCommon();
13736
13737 bool Suspicious = false;
13738 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13739 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13740
13741 if (T->isBooleanType())
13743
13744 // If -Wconversion would have warned about either of the candidates
13745 // for a signedness conversion to the context type...
13746 if (!Suspicious) return;
13747
13748 // ...but it's currently ignored...
13749 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13750 return;
13751
13752 // ...then check whether it would have warned about either of the
13753 // candidates for a signedness conversion to the condition type.
13754 if (E->getType() == T) return;
13755
13756 Suspicious = false;
13757 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13758 &Suspicious);
13759 if (!Suspicious)
13761 E->getType(), CC, &Suspicious);
13762}
13763
13764/// Check conversion of given expression to boolean.
13765/// Input argument E is a logical expression.
13767 // Run the bool-like conversion checks only for C since there bools are
13768 // still not used as the return type from "boolean" operators or as the input
13769 // type for conditional operators.
13770 if (S.getLangOpts().CPlusPlus)
13771 return;
13773 return;
13775}
13776
13777namespace {
13778struct AnalyzeImplicitConversionsWorkItem {
13779 Expr *E;
13780 SourceLocation CC;
13781 bool IsListInit;
13782};
13783}
13784
13786 Sema &S, Expr *E, QualType T, SourceLocation CC,
13787 bool ExtraCheckForImplicitConversion,
13789 E = E->IgnoreParenImpCasts();
13790 WorkList.push_back({E, CC, false});
13791
13792 if (ExtraCheckForImplicitConversion && E->getType() != T)
13793 S.CheckImplicitConversion(E, T, CC);
13794}
13795
13796/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13797/// that should be visited are added to WorkList.
13799 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13801 Expr *OrigE = Item.E;
13802 SourceLocation CC = Item.CC;
13803
13804 QualType T = OrigE->getType();
13805 Expr *E = OrigE->IgnoreParenImpCasts();
13806
13807 // Propagate whether we are in a C++ list initialization expression.
13808 // If so, we do not issue warnings for implicit int-float conversion
13809 // precision loss, because C++11 narrowing already handles it.
13810 //
13811 // HLSL's initialization lists are special, so they shouldn't observe the C++
13812 // behavior here.
13813 bool IsListInit =
13814 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13815 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13816
13817 if (E->isTypeDependent() || E->isValueDependent())
13818 return;
13819
13820 Expr *SourceExpr = E;
13821 // Examine, but don't traverse into the source expression of an
13822 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13823 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13824 // evaluate it in the context of checking the specific conversion to T though.
13825 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13826 if (auto *Src = OVE->getSourceExpr())
13827 SourceExpr = Src;
13828
13829 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13830 if (UO->getOpcode() == UO_Not &&
13831 UO->getSubExpr()->isKnownToHaveBooleanValue())
13832 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13833 << OrigE->getSourceRange() << T->isBooleanType()
13834 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13835
13836 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13837 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13838 BO->getLHS()->isKnownToHaveBooleanValue() &&
13839 BO->getRHS()->isKnownToHaveBooleanValue() &&
13840 BO->getLHS()->HasSideEffects(S.Context) &&
13841 BO->getRHS()->HasSideEffects(S.Context)) {
13843 const LangOptions &LO = S.getLangOpts();
13844 SourceLocation BLoc = BO->getOperatorLoc();
13845 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13846 StringRef SR = clang::Lexer::getSourceText(
13847 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13848 // To reduce false positives, only issue the diagnostic if the operator
13849 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13850 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13851 // in C, along with other macro spellings the user might invent.
13852 if (SR.str() == "&" || SR.str() == "|") {
13853
13854 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13855 << (BO->getOpcode() == BO_And ? "&" : "|")
13856 << OrigE->getSourceRange()
13858 BO->getOperatorLoc(),
13859 (BO->getOpcode() == BO_And ? "&&" : "||"));
13860 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13861 }
13862 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13863 /// Analyze the given comma operator. The basic idea behind the analysis
13864 /// is to analyze the left and right operands slightly differently. The
13865 /// left operand needs to check whether the operand itself has an implicit
13866 /// conversion, but not whether the left operand induces an implicit
13867 /// conversion for the entire comma expression itself. This is similar to
13868 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13869 /// were directly used for the implicit conversion check.
13870 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13871 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13872 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13873 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13874 return;
13875 }
13876 }
13877
13878 // For conditional operators, we analyze the arguments as if they
13879 // were being fed directly into the output.
13880 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13881 CheckConditionalOperator(S, CO, CC, T);
13882 return;
13883 }
13884
13885 // Check implicit argument conversions for function calls.
13886 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13888
13889 // Go ahead and check any implicit conversions we might have skipped.
13890 // The non-canonical typecheck is just an optimization;
13891 // CheckImplicitConversion will filter out dead implicit conversions.
13892 if (SourceExpr->getType() != T)
13893 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13894
13895 // Now continue drilling into this expression.
13896
13897 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13898 // The bound subexpressions in a PseudoObjectExpr are not reachable
13899 // as transitive children.
13900 // FIXME: Use a more uniform representation for this.
13901 for (auto *SE : POE->semantics())
13902 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13903 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13904 }
13905
13906 // Skip past explicit casts.
13907 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13908 E = CE->getSubExpr();
13909 // In the special case of a C++ function-style cast with braces,
13910 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13911 // initializer. This InitListExpr basically belongs to the cast itself, so
13912 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13914 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13915 if (InitListE->getNumInits() == 1) {
13916 E = InitListE->getInit(0);
13917 }
13918 }
13919 }
13920 E = E->IgnoreParenImpCasts();
13921 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13922 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13923 WorkList.push_back({E, CC, IsListInit});
13924 return;
13925 }
13926
13927 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13928 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13929 // The base expression is only used to initialize the parameter for
13930 // arguments to `inout` parameters, so we only traverse down the base
13931 // expression for `inout` cases.
13932 if (OutArgE->isInOut())
13933 WorkList.push_back(
13934 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13935 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13936 return;
13937 }
13938
13939 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13940 // Do a somewhat different check with comparison operators.
13941 if (BO->isComparisonOp())
13942 return AnalyzeComparison(S, BO);
13943
13944 // And with simple assignments.
13945 if (BO->getOpcode() == BO_Assign)
13946 return AnalyzeAssignment(S, BO);
13947 // And with compound assignments.
13948 if (BO->isAssignmentOp())
13949 return AnalyzeCompoundAssignment(S, BO);
13950 }
13951
13952 // These break the otherwise-useful invariant below. Fortunately,
13953 // we don't really need to recurse into them, because any internal
13954 // expressions should have been analyzed already when they were
13955 // built into statements.
13956 if (isa<StmtExpr>(E)) return;
13957
13958 // Don't descend into unevaluated contexts.
13959 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13960
13961 // Now just recurse over the expression's children.
13962 CC = E->getExprLoc();
13963 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13964 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13965 for (Stmt *SubStmt : E->children()) {
13966 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13967 if (!ChildExpr)
13968 continue;
13969
13970 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13971 if (ChildExpr == CSE->getOperand())
13972 // Do not recurse over a CoroutineSuspendExpr's operand.
13973 // The operand is also a subexpression of getCommonExpr(), and
13974 // recursing into it directly would produce duplicate diagnostics.
13975 continue;
13976
13977 if (IsLogicalAndOperator &&
13979 // Ignore checking string literals that are in logical and operators.
13980 // This is a common pattern for asserts.
13981 continue;
13982 WorkList.push_back({ChildExpr, CC, IsListInit});
13983 }
13984
13985 if (BO && BO->isLogicalOp()) {
13986 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13987 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13988 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13989
13990 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13991 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13992 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13993 }
13994
13995 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13996 if (U->getOpcode() == UO_LNot) {
13997 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13998 } else if (U->getOpcode() != UO_AddrOf) {
13999 if (U->getSubExpr()->getType()->isAtomicType())
14000 S.Diag(U->getSubExpr()->getBeginLoc(),
14001 diag::warn_atomic_implicit_seq_cst);
14002 }
14003 }
14004}
14005
14006/// AnalyzeImplicitConversions - Find and report any interesting
14007/// implicit conversions in the given expression. There are a couple
14008/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14010 bool IsListInit/*= false*/) {
14012 WorkList.push_back({OrigE, CC, IsListInit});
14013 while (!WorkList.empty())
14014 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14015}
14016
14017// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14018// Returns true when emitting a warning about taking the address of a reference.
14019static bool CheckForReference(Sema &SemaRef, const Expr *E,
14020 const PartialDiagnostic &PD) {
14021 E = E->IgnoreParenImpCasts();
14022
14023 const FunctionDecl *FD = nullptr;
14024
14025 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14026 if (!DRE->getDecl()->getType()->isReferenceType())
14027 return false;
14028 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14029 if (!M->getMemberDecl()->getType()->isReferenceType())
14030 return false;
14031 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14032 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14033 return false;
14034 FD = Call->getDirectCallee();
14035 } else {
14036 return false;
14037 }
14038
14039 SemaRef.Diag(E->getExprLoc(), PD);
14040
14041 // If possible, point to location of function.
14042 if (FD) {
14043 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14044 }
14045
14046 return true;
14047}
14048
14049// Returns true if the SourceLocation is expanded from any macro body.
14050// Returns false if the SourceLocation is invalid, is from not in a macro
14051// expansion, or is from expanded from a top-level macro argument.
14053 if (Loc.isInvalid())
14054 return false;
14055
14056 while (Loc.isMacroID()) {
14057 if (SM.isMacroBodyExpansion(Loc))
14058 return true;
14059 Loc = SM.getImmediateMacroCallerLoc(Loc);
14060 }
14061
14062 return false;
14063}
14064
14067 bool IsEqual, SourceRange Range) {
14068 if (!E)
14069 return;
14070
14071 // Don't warn inside macros.
14072 if (E->getExprLoc().isMacroID()) {
14074 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14075 IsInAnyMacroBody(SM, Range.getBegin()))
14076 return;
14077 }
14078 E = E->IgnoreImpCasts();
14079
14080 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14081
14082 if (isa<CXXThisExpr>(E)) {
14083 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14084 : diag::warn_this_bool_conversion;
14085 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14086 return;
14087 }
14088
14089 bool IsAddressOf = false;
14090
14091 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14092 if (UO->getOpcode() != UO_AddrOf)
14093 return;
14094 IsAddressOf = true;
14095 E = UO->getSubExpr();
14096 }
14097
14098 if (IsAddressOf) {
14099 unsigned DiagID = IsCompare
14100 ? diag::warn_address_of_reference_null_compare
14101 : diag::warn_address_of_reference_bool_conversion;
14102 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14103 << IsEqual;
14104 if (CheckForReference(*this, E, PD)) {
14105 return;
14106 }
14107 }
14108
14109 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14110 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14111 std::string Str;
14112 llvm::raw_string_ostream S(Str);
14113 E->printPretty(S, nullptr, getPrintingPolicy());
14114 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14115 : diag::warn_cast_nonnull_to_bool;
14116 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14117 << E->getSourceRange() << Range << IsEqual;
14118 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14119 };
14120
14121 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14122 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14123 if (auto *Callee = Call->getDirectCallee()) {
14124 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14125 ComplainAboutNonnullParamOrCall(A);
14126 return;
14127 }
14128 }
14129 }
14130
14131 // Complain if we are converting a lambda expression to a boolean value
14132 // outside of instantiation.
14133 if (!inTemplateInstantiation()) {
14134 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14135 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14136 MRecordDecl && MRecordDecl->isLambda()) {
14137 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14138 << /*LambdaPointerConversionOperatorType=*/3
14139 << MRecordDecl->getSourceRange() << Range << IsEqual;
14140 return;
14141 }
14142 }
14143 }
14144
14145 // Expect to find a single Decl. Skip anything more complicated.
14146 ValueDecl *D = nullptr;
14147 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14148 D = R->getDecl();
14149 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14150 D = M->getMemberDecl();
14151 }
14152
14153 // Weak Decls can be null.
14154 if (!D || D->isWeak())
14155 return;
14156
14157 // Check for parameter decl with nonnull attribute
14158 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14159 if (getCurFunction() &&
14160 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14161 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14162 ComplainAboutNonnullParamOrCall(A);
14163 return;
14164 }
14165
14166 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14167 // Skip function template not specialized yet.
14169 return;
14170 auto ParamIter = llvm::find(FD->parameters(), PV);
14171 assert(ParamIter != FD->param_end());
14172 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14173
14174 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14175 if (!NonNull->args_size()) {
14176 ComplainAboutNonnullParamOrCall(NonNull);
14177 return;
14178 }
14179
14180 for (const ParamIdx &ArgNo : NonNull->args()) {
14181 if (ArgNo.getASTIndex() == ParamNo) {
14182 ComplainAboutNonnullParamOrCall(NonNull);
14183 return;
14184 }
14185 }
14186 }
14187 }
14188 }
14189 }
14190
14191 QualType T = D->getType();
14192 const bool IsArray = T->isArrayType();
14193 const bool IsFunction = T->isFunctionType();
14194
14195 // Address of function is used to silence the function warning.
14196 if (IsAddressOf && IsFunction) {
14197 return;
14198 }
14199
14200 // Found nothing.
14201 if (!IsAddressOf && !IsFunction && !IsArray)
14202 return;
14203
14204 // Pretty print the expression for the diagnostic.
14205 std::string Str;
14206 llvm::raw_string_ostream S(Str);
14207 E->printPretty(S, nullptr, getPrintingPolicy());
14208
14209 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14210 : diag::warn_impcast_pointer_to_bool;
14211 enum {
14212 AddressOf,
14213 FunctionPointer,
14214 ArrayPointer
14215 } DiagType;
14216 if (IsAddressOf)
14217 DiagType = AddressOf;
14218 else if (IsFunction)
14219 DiagType = FunctionPointer;
14220 else if (IsArray)
14221 DiagType = ArrayPointer;
14222 else
14223 llvm_unreachable("Could not determine diagnostic.");
14224 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14225 << Range << IsEqual;
14226
14227 if (!IsFunction)
14228 return;
14229
14230 // Suggest '&' to silence the function warning.
14231 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14233
14234 // Check to see if '()' fixit should be emitted.
14235 QualType ReturnType;
14236 UnresolvedSet<4> NonTemplateOverloads;
14237 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14238 if (ReturnType.isNull())
14239 return;
14240
14241 if (IsCompare) {
14242 // There are two cases here. If there is null constant, the only suggest
14243 // for a pointer return type. If the null is 0, then suggest if the return
14244 // type is a pointer or an integer type.
14245 if (!ReturnType->isPointerType()) {
14246 if (NullKind == Expr::NPCK_ZeroExpression ||
14247 NullKind == Expr::NPCK_ZeroLiteral) {
14248 if (!ReturnType->isIntegerType())
14249 return;
14250 } else {
14251 return;
14252 }
14253 }
14254 } else { // !IsCompare
14255 // For function to bool, only suggest if the function pointer has bool
14256 // return type.
14257 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14258 return;
14259 }
14260 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14262}
14263
14265 SourceLocation CC) {
14266 QualType Source = E->getType();
14267 QualType Target = T;
14268
14269 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14270 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14271 // Overflow behavior type is being stripped - issue warning
14272 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14273 Target->isUnsignedIntegerType()) {
14274 // For unsigned wrap to unsigned conversions, use pedantic version
14275 unsigned DiagId =
14277 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14278 : diag::warn_impcast_overflow_behavior_pedantic;
14279 DiagnoseImpCast(*this, E, T, CC, DiagId);
14280 } else {
14281 unsigned DiagId = InOverflowBehaviorAssignmentContext
14282 ? diag::warn_impcast_overflow_behavior_assignment
14283 : diag::warn_impcast_overflow_behavior;
14284 DiagnoseImpCast(*this, E, T, CC, DiagId);
14285 }
14286 }
14287 }
14288
14289 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14290 if (TargetOBT->isWrapKind()) {
14291 return true;
14292 }
14293 }
14294
14295 return false;
14296}
14297
14298void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14299 // Don't diagnose in unevaluated contexts.
14301 return;
14302
14303 // Don't diagnose for value- or type-dependent expressions.
14304 if (E->isTypeDependent() || E->isValueDependent())
14305 return;
14306
14307 // Check for array bounds violations in cases where the check isn't triggered
14308 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14309 // ArraySubscriptExpr is on the RHS of a variable initialization.
14310 CheckArrayAccess(E);
14311
14312 // This is not the right CC for (e.g.) a variable initialization.
14313 AnalyzeImplicitConversions(*this, E, CC);
14314}
14315
14316void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14317 ::CheckBoolLikeConversion(*this, E, CC);
14318}
14319
14320void Sema::CheckForIntOverflow (const Expr *E) {
14321 // Use a work list to deal with nested struct initializers.
14322 SmallVector<const Expr *, 2> Exprs(1, E);
14323
14324 do {
14325 const Expr *OriginalE = Exprs.pop_back_val();
14326 const Expr *E = OriginalE->IgnoreParenCasts();
14327
14330 continue;
14331 }
14332
14333 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14334 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14335 else if (isa<ObjCBoxedExpr>(OriginalE))
14337 else if (const auto *Call = dyn_cast<CallExpr>(E))
14338 Exprs.append(Call->arg_begin(), Call->arg_end());
14339 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14340 Exprs.append(Message->arg_begin(), Message->arg_end());
14341 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14342 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14343 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14344 Exprs.push_back(Temporary->getSubExpr());
14345 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14346 Exprs.push_back(Array->getIdx());
14347 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14348 Exprs.push_back(Compound->getInitializer());
14349 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14350 New && New->isArray()) {
14351 if (auto ArraySize = New->getArraySize())
14352 Exprs.push_back(*ArraySize);
14353 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14354 Exprs.push_back(MTE->getSubExpr());
14355 } while (!Exprs.empty());
14356}
14357
14358namespace {
14359
14360/// Visitor for expressions which looks for unsequenced operations on the
14361/// same object.
14362class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14363 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14364
14365 /// A tree of sequenced regions within an expression. Two regions are
14366 /// unsequenced if one is an ancestor or a descendent of the other. When we
14367 /// finish processing an expression with sequencing, such as a comma
14368 /// expression, we fold its tree nodes into its parent, since they are
14369 /// unsequenced with respect to nodes we will visit later.
14370 class SequenceTree {
14371 struct Value {
14372 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14373 unsigned Parent : 31;
14374 LLVM_PREFERRED_TYPE(bool)
14375 unsigned Merged : 1;
14376 };
14377 SmallVector<Value, 8> Values;
14378
14379 public:
14380 /// A region within an expression which may be sequenced with respect
14381 /// to some other region.
14382 class Seq {
14383 friend class SequenceTree;
14384
14385 unsigned Index;
14386
14387 explicit Seq(unsigned N) : Index(N) {}
14388
14389 public:
14390 Seq() : Index(0) {}
14391 };
14392
14393 SequenceTree() { Values.push_back(Value(0)); }
14394 Seq root() const { return Seq(0); }
14395
14396 /// Create a new sequence of operations, which is an unsequenced
14397 /// subset of \p Parent. This sequence of operations is sequenced with
14398 /// respect to other children of \p Parent.
14399 Seq allocate(Seq Parent) {
14400 Values.push_back(Value(Parent.Index));
14401 return Seq(Values.size() - 1);
14402 }
14403
14404 /// Merge a sequence of operations into its parent.
14405 void merge(Seq S) {
14406 Values[S.Index].Merged = true;
14407 }
14408
14409 /// Determine whether two operations are unsequenced. This operation
14410 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14411 /// should have been merged into its parent as appropriate.
14412 bool isUnsequenced(Seq Cur, Seq Old) {
14413 unsigned C = representative(Cur.Index);
14414 unsigned Target = representative(Old.Index);
14415 while (C >= Target) {
14416 if (C == Target)
14417 return true;
14418 C = Values[C].Parent;
14419 }
14420 return false;
14421 }
14422
14423 private:
14424 /// Pick a representative for a sequence.
14425 unsigned representative(unsigned K) {
14426 if (Values[K].Merged)
14427 // Perform path compression as we go.
14428 return Values[K].Parent = representative(Values[K].Parent);
14429 return K;
14430 }
14431 };
14432
14433 /// An object for which we can track unsequenced uses.
14434 using Object = const NamedDecl *;
14435
14436 /// Different flavors of object usage which we track. We only track the
14437 /// least-sequenced usage of each kind.
14438 enum UsageKind {
14439 /// A read of an object. Multiple unsequenced reads are OK.
14440 UK_Use,
14441
14442 /// A modification of an object which is sequenced before the value
14443 /// computation of the expression, such as ++n in C++.
14444 UK_ModAsValue,
14445
14446 /// A modification of an object which is not sequenced before the value
14447 /// computation of the expression, such as n++.
14448 UK_ModAsSideEffect,
14449
14450 UK_Count = UK_ModAsSideEffect + 1
14451 };
14452
14453 /// Bundle together a sequencing region and the expression corresponding
14454 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14455 struct Usage {
14456 const Expr *UsageExpr = nullptr;
14457 SequenceTree::Seq Seq;
14458
14459 Usage() = default;
14460 };
14461
14462 struct UsageInfo {
14463 Usage Uses[UK_Count];
14464
14465 /// Have we issued a diagnostic for this object already?
14466 bool Diagnosed = false;
14467
14468 UsageInfo();
14469 };
14470 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14471
14472 Sema &SemaRef;
14473
14474 /// Sequenced regions within the expression.
14475 SequenceTree Tree;
14476
14477 /// Declaration modifications and references which we have seen.
14478 UsageInfoMap UsageMap;
14479
14480 /// The region we are currently within.
14481 SequenceTree::Seq Region;
14482
14483 /// Filled in with declarations which were modified as a side-effect
14484 /// (that is, post-increment operations).
14485 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14486
14487 /// Expressions to check later. We defer checking these to reduce
14488 /// stack usage.
14489 SmallVectorImpl<const Expr *> &WorkList;
14490
14491 /// RAII object wrapping the visitation of a sequenced subexpression of an
14492 /// expression. At the end of this process, the side-effects of the evaluation
14493 /// become sequenced with respect to the value computation of the result, so
14494 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14495 /// UK_ModAsValue.
14496 struct SequencedSubexpression {
14497 SequencedSubexpression(SequenceChecker &Self)
14498 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14499 Self.ModAsSideEffect = &ModAsSideEffect;
14500 }
14501
14502 ~SequencedSubexpression() {
14503 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14504 // Add a new usage with usage kind UK_ModAsValue, and then restore
14505 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14506 // the previous one was empty).
14507 UsageInfo &UI = Self.UsageMap[M.first];
14508 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14509 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14510 SideEffectUsage = M.second;
14511 }
14512 Self.ModAsSideEffect = OldModAsSideEffect;
14513 }
14514
14515 SequenceChecker &Self;
14516 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14517 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14518 };
14519
14520 /// RAII object wrapping the visitation of a subexpression which we might
14521 /// choose to evaluate as a constant. If any subexpression is evaluated and
14522 /// found to be non-constant, this allows us to suppress the evaluation of
14523 /// the outer expression.
14524 class EvaluationTracker {
14525 public:
14526 EvaluationTracker(SequenceChecker &Self)
14527 : Self(Self), Prev(Self.EvalTracker) {
14528 Self.EvalTracker = this;
14529 }
14530
14531 ~EvaluationTracker() {
14532 Self.EvalTracker = Prev;
14533 if (Prev)
14534 Prev->EvalOK &= EvalOK;
14535 }
14536
14537 bool evaluate(const Expr *E, bool &Result) {
14538 if (!EvalOK || E->isValueDependent())
14539 return false;
14540 EvalOK = E->EvaluateAsBooleanCondition(
14541 Result, Self.SemaRef.Context,
14542 Self.SemaRef.isConstantEvaluatedContext());
14543 return EvalOK;
14544 }
14545
14546 private:
14547 SequenceChecker &Self;
14548 EvaluationTracker *Prev;
14549 bool EvalOK = true;
14550 } *EvalTracker = nullptr;
14551
14552 /// Find the object which is produced by the specified expression,
14553 /// if any.
14554 Object getObject(const Expr *E, bool Mod) const {
14555 E = E->IgnoreParenCasts();
14556 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14557 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14558 return getObject(UO->getSubExpr(), Mod);
14559 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14560 if (BO->getOpcode() == BO_Comma)
14561 return getObject(BO->getRHS(), Mod);
14562 if (Mod && BO->isAssignmentOp())
14563 return getObject(BO->getLHS(), Mod);
14564 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14565 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14566 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14567 return ME->getMemberDecl();
14568 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14569 // FIXME: If this is a reference, map through to its value.
14570 return DRE->getDecl();
14571 return nullptr;
14572 }
14573
14574 /// Note that an object \p O was modified or used by an expression
14575 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14576 /// the object \p O as obtained via the \p UsageMap.
14577 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14578 // Get the old usage for the given object and usage kind.
14579 Usage &U = UI.Uses[UK];
14580 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14581 // If we have a modification as side effect and are in a sequenced
14582 // subexpression, save the old Usage so that we can restore it later
14583 // in SequencedSubexpression::~SequencedSubexpression.
14584 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14585 ModAsSideEffect->push_back(std::make_pair(O, U));
14586 // Then record the new usage with the current sequencing region.
14587 U.UsageExpr = UsageExpr;
14588 U.Seq = Region;
14589 }
14590 }
14591
14592 /// Check whether a modification or use of an object \p O in an expression
14593 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14594 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14595 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14596 /// usage and false we are checking for a mod-use unsequenced usage.
14597 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14598 UsageKind OtherKind, bool IsModMod) {
14599 if (UI.Diagnosed)
14600 return;
14601
14602 const Usage &U = UI.Uses[OtherKind];
14603 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14604 return;
14605
14606 const Expr *Mod = U.UsageExpr;
14607 const Expr *ModOrUse = UsageExpr;
14608 if (OtherKind == UK_Use)
14609 std::swap(Mod, ModOrUse);
14610
14611 SemaRef.DiagRuntimeBehavior(
14612 Mod->getExprLoc(), {Mod, ModOrUse},
14613 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14614 : diag::warn_unsequenced_mod_use)
14615 << O << SourceRange(ModOrUse->getExprLoc()));
14616 UI.Diagnosed = true;
14617 }
14618
14619 // A note on note{Pre, Post}{Use, Mod}:
14620 //
14621 // (It helps to follow the algorithm with an expression such as
14622 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14623 // operations before C++17 and both are well-defined in C++17).
14624 //
14625 // When visiting a node which uses/modify an object we first call notePreUse
14626 // or notePreMod before visiting its sub-expression(s). At this point the
14627 // children of the current node have not yet been visited and so the eventual
14628 // uses/modifications resulting from the children of the current node have not
14629 // been recorded yet.
14630 //
14631 // We then visit the children of the current node. After that notePostUse or
14632 // notePostMod is called. These will 1) detect an unsequenced modification
14633 // as side effect (as in "k++ + k") and 2) add a new usage with the
14634 // appropriate usage kind.
14635 //
14636 // We also have to be careful that some operation sequences modification as
14637 // side effect as well (for example: || or ,). To account for this we wrap
14638 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14639 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14640 // which record usages which are modifications as side effect, and then
14641 // downgrade them (or more accurately restore the previous usage which was a
14642 // modification as side effect) when exiting the scope of the sequenced
14643 // subexpression.
14644
14645 void notePreUse(Object O, const Expr *UseExpr) {
14646 UsageInfo &UI = UsageMap[O];
14647 // Uses conflict with other modifications.
14648 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14649 }
14650
14651 void notePostUse(Object O, const Expr *UseExpr) {
14652 UsageInfo &UI = UsageMap[O];
14653 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14654 /*IsModMod=*/false);
14655 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14656 }
14657
14658 void notePreMod(Object O, const Expr *ModExpr) {
14659 UsageInfo &UI = UsageMap[O];
14660 // Modifications conflict with other modifications and with uses.
14661 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14662 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14663 }
14664
14665 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14666 UsageInfo &UI = UsageMap[O];
14667 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14668 /*IsModMod=*/true);
14669 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14670 }
14671
14672public:
14673 SequenceChecker(Sema &S, const Expr *E,
14674 SmallVectorImpl<const Expr *> &WorkList)
14675 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14676 Visit(E);
14677 // Silence a -Wunused-private-field since WorkList is now unused.
14678 // TODO: Evaluate if it can be used, and if not remove it.
14679 (void)this->WorkList;
14680 }
14681
14682 void VisitStmt(const Stmt *S) {
14683 // Skip all statements which aren't expressions for now.
14684 }
14685
14686 void VisitExpr(const Expr *E) {
14687 // By default, just recurse to evaluated subexpressions.
14688 Base::VisitStmt(E);
14689 }
14690
14691 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14692 for (auto *Sub : CSE->children()) {
14693 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14694 if (!ChildExpr)
14695 continue;
14696
14697 if (ChildExpr == CSE->getOperand())
14698 // Do not recurse over a CoroutineSuspendExpr's operand.
14699 // The operand is also a subexpression of getCommonExpr(), and
14700 // recursing into it directly could confuse object management
14701 // for the sake of sequence tracking.
14702 continue;
14703
14704 Visit(Sub);
14705 }
14706 }
14707
14708 void VisitCastExpr(const CastExpr *E) {
14709 Object O = Object();
14710 if (E->getCastKind() == CK_LValueToRValue)
14711 O = getObject(E->getSubExpr(), false);
14712
14713 if (O)
14714 notePreUse(O, E);
14715 VisitExpr(E);
14716 if (O)
14717 notePostUse(O, E);
14718 }
14719
14720 void VisitSequencedExpressions(const Expr *SequencedBefore,
14721 const Expr *SequencedAfter) {
14722 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14723 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14724 SequenceTree::Seq OldRegion = Region;
14725
14726 {
14727 SequencedSubexpression SeqBefore(*this);
14728 Region = BeforeRegion;
14729 Visit(SequencedBefore);
14730 }
14731
14732 Region = AfterRegion;
14733 Visit(SequencedAfter);
14734
14735 Region = OldRegion;
14736
14737 Tree.merge(BeforeRegion);
14738 Tree.merge(AfterRegion);
14739 }
14740
14741 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14742 // C++17 [expr.sub]p1:
14743 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14744 // expression E1 is sequenced before the expression E2.
14745 if (SemaRef.getLangOpts().CPlusPlus17)
14746 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14747 else {
14748 Visit(ASE->getLHS());
14749 Visit(ASE->getRHS());
14750 }
14751 }
14752
14753 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14754 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14755 void VisitBinPtrMem(const BinaryOperator *BO) {
14756 // C++17 [expr.mptr.oper]p4:
14757 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14758 // the expression E1 is sequenced before the expression E2.
14759 if (SemaRef.getLangOpts().CPlusPlus17)
14760 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14761 else {
14762 Visit(BO->getLHS());
14763 Visit(BO->getRHS());
14764 }
14765 }
14766
14767 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14768 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14769 void VisitBinShlShr(const BinaryOperator *BO) {
14770 // C++17 [expr.shift]p4:
14771 // The expression E1 is sequenced before the expression E2.
14772 if (SemaRef.getLangOpts().CPlusPlus17)
14773 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14774 else {
14775 Visit(BO->getLHS());
14776 Visit(BO->getRHS());
14777 }
14778 }
14779
14780 void VisitBinComma(const BinaryOperator *BO) {
14781 // C++11 [expr.comma]p1:
14782 // Every value computation and side effect associated with the left
14783 // expression is sequenced before every value computation and side
14784 // effect associated with the right expression.
14785 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14786 }
14787
14788 void VisitBinAssign(const BinaryOperator *BO) {
14789 SequenceTree::Seq RHSRegion;
14790 SequenceTree::Seq LHSRegion;
14791 if (SemaRef.getLangOpts().CPlusPlus17) {
14792 RHSRegion = Tree.allocate(Region);
14793 LHSRegion = Tree.allocate(Region);
14794 } else {
14795 RHSRegion = Region;
14796 LHSRegion = Region;
14797 }
14798 SequenceTree::Seq OldRegion = Region;
14799
14800 // C++11 [expr.ass]p1:
14801 // [...] the assignment is sequenced after the value computation
14802 // of the right and left operands, [...]
14803 //
14804 // so check it before inspecting the operands and update the
14805 // map afterwards.
14806 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14807 if (O)
14808 notePreMod(O, BO);
14809
14810 if (SemaRef.getLangOpts().CPlusPlus17) {
14811 // C++17 [expr.ass]p1:
14812 // [...] The right operand is sequenced before the left operand. [...]
14813 {
14814 SequencedSubexpression SeqBefore(*this);
14815 Region = RHSRegion;
14816 Visit(BO->getRHS());
14817 }
14818
14819 Region = LHSRegion;
14820 Visit(BO->getLHS());
14821
14822 if (O && isa<CompoundAssignOperator>(BO))
14823 notePostUse(O, BO);
14824
14825 } else {
14826 // C++11 does not specify any sequencing between the LHS and RHS.
14827 Region = LHSRegion;
14828 Visit(BO->getLHS());
14829
14830 if (O && isa<CompoundAssignOperator>(BO))
14831 notePostUse(O, BO);
14832
14833 Region = RHSRegion;
14834 Visit(BO->getRHS());
14835 }
14836
14837 // C++11 [expr.ass]p1:
14838 // the assignment is sequenced [...] before the value computation of the
14839 // assignment expression.
14840 // C11 6.5.16/3 has no such rule.
14841 Region = OldRegion;
14842 if (O)
14843 notePostMod(O, BO,
14844 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14845 : UK_ModAsSideEffect);
14846 if (SemaRef.getLangOpts().CPlusPlus17) {
14847 Tree.merge(RHSRegion);
14848 Tree.merge(LHSRegion);
14849 }
14850 }
14851
14852 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14853 VisitBinAssign(CAO);
14854 }
14855
14856 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14857 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14858 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14859 Object O = getObject(UO->getSubExpr(), true);
14860 if (!O)
14861 return VisitExpr(UO);
14862
14863 notePreMod(O, UO);
14864 Visit(UO->getSubExpr());
14865 // C++11 [expr.pre.incr]p1:
14866 // the expression ++x is equivalent to x+=1
14867 notePostMod(O, UO,
14868 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14869 : UK_ModAsSideEffect);
14870 }
14871
14872 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14873 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14874 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14875 Object O = getObject(UO->getSubExpr(), true);
14876 if (!O)
14877 return VisitExpr(UO);
14878
14879 notePreMod(O, UO);
14880 Visit(UO->getSubExpr());
14881 notePostMod(O, UO, UK_ModAsSideEffect);
14882 }
14883
14884 void VisitBinLOr(const BinaryOperator *BO) {
14885 // C++11 [expr.log.or]p2:
14886 // If the second expression is evaluated, every value computation and
14887 // side effect associated with the first expression is sequenced before
14888 // every value computation and side effect associated with the
14889 // second expression.
14890 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14891 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14892 SequenceTree::Seq OldRegion = Region;
14893
14894 EvaluationTracker Eval(*this);
14895 {
14896 SequencedSubexpression Sequenced(*this);
14897 Region = LHSRegion;
14898 Visit(BO->getLHS());
14899 }
14900
14901 // C++11 [expr.log.or]p1:
14902 // [...] the second operand is not evaluated if the first operand
14903 // evaluates to true.
14904 bool EvalResult = false;
14905 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14906 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14907 if (ShouldVisitRHS) {
14908 Region = RHSRegion;
14909 Visit(BO->getRHS());
14910 }
14911
14912 Region = OldRegion;
14913 Tree.merge(LHSRegion);
14914 Tree.merge(RHSRegion);
14915 }
14916
14917 void VisitBinLAnd(const BinaryOperator *BO) {
14918 // C++11 [expr.log.and]p2:
14919 // If the second expression is evaluated, every value computation and
14920 // side effect associated with the first expression is sequenced before
14921 // every value computation and side effect associated with the
14922 // second expression.
14923 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14924 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14925 SequenceTree::Seq OldRegion = Region;
14926
14927 EvaluationTracker Eval(*this);
14928 {
14929 SequencedSubexpression Sequenced(*this);
14930 Region = LHSRegion;
14931 Visit(BO->getLHS());
14932 }
14933
14934 // C++11 [expr.log.and]p1:
14935 // [...] the second operand is not evaluated if the first operand is false.
14936 bool EvalResult = false;
14937 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14938 bool ShouldVisitRHS = !EvalOK || EvalResult;
14939 if (ShouldVisitRHS) {
14940 Region = RHSRegion;
14941 Visit(BO->getRHS());
14942 }
14943
14944 Region = OldRegion;
14945 Tree.merge(LHSRegion);
14946 Tree.merge(RHSRegion);
14947 }
14948
14949 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14950 // C++11 [expr.cond]p1:
14951 // [...] Every value computation and side effect associated with the first
14952 // expression is sequenced before every value computation and side effect
14953 // associated with the second or third expression.
14954 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14955
14956 // No sequencing is specified between the true and false expression.
14957 // However since exactly one of both is going to be evaluated we can
14958 // consider them to be sequenced. This is needed to avoid warning on
14959 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14960 // both the true and false expressions because we can't evaluate x.
14961 // This will still allow us to detect an expression like (pre C++17)
14962 // "(x ? y += 1 : y += 2) = y".
14963 //
14964 // We don't wrap the visitation of the true and false expression with
14965 // SequencedSubexpression because we don't want to downgrade modifications
14966 // as side effect in the true and false expressions after the visition
14967 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14968 // not warn between the two "y++", but we should warn between the "y++"
14969 // and the "y".
14970 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14971 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14972 SequenceTree::Seq OldRegion = Region;
14973
14974 EvaluationTracker Eval(*this);
14975 {
14976 SequencedSubexpression Sequenced(*this);
14977 Region = ConditionRegion;
14978 Visit(CO->getCond());
14979 }
14980
14981 // C++11 [expr.cond]p1:
14982 // [...] The first expression is contextually converted to bool (Clause 4).
14983 // It is evaluated and if it is true, the result of the conditional
14984 // expression is the value of the second expression, otherwise that of the
14985 // third expression. Only one of the second and third expressions is
14986 // evaluated. [...]
14987 bool EvalResult = false;
14988 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14989 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14990 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14991 if (ShouldVisitTrueExpr) {
14992 Region = TrueRegion;
14993 Visit(CO->getTrueExpr());
14994 }
14995 if (ShouldVisitFalseExpr) {
14996 Region = FalseRegion;
14997 Visit(CO->getFalseExpr());
14998 }
14999
15000 Region = OldRegion;
15001 Tree.merge(ConditionRegion);
15002 Tree.merge(TrueRegion);
15003 Tree.merge(FalseRegion);
15004 }
15005
15006 void VisitCallExpr(const CallExpr *CE) {
15007 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15008
15009 if (CE->isUnevaluatedBuiltinCall(Context))
15010 return;
15011
15012 // C++11 [intro.execution]p15:
15013 // When calling a function [...], every value computation and side effect
15014 // associated with any argument expression, or with the postfix expression
15015 // designating the called function, is sequenced before execution of every
15016 // expression or statement in the body of the function [and thus before
15017 // the value computation of its result].
15018 SequencedSubexpression Sequenced(*this);
15019 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15020 // C++17 [expr.call]p5
15021 // The postfix-expression is sequenced before each expression in the
15022 // expression-list and any default argument. [...]
15023 SequenceTree::Seq CalleeRegion;
15024 SequenceTree::Seq OtherRegion;
15025 if (SemaRef.getLangOpts().CPlusPlus17) {
15026 CalleeRegion = Tree.allocate(Region);
15027 OtherRegion = Tree.allocate(Region);
15028 } else {
15029 CalleeRegion = Region;
15030 OtherRegion = Region;
15031 }
15032 SequenceTree::Seq OldRegion = Region;
15033
15034 // Visit the callee expression first.
15035 Region = CalleeRegion;
15036 if (SemaRef.getLangOpts().CPlusPlus17) {
15037 SequencedSubexpression Sequenced(*this);
15038 Visit(CE->getCallee());
15039 } else {
15040 Visit(CE->getCallee());
15041 }
15042
15043 // Then visit the argument expressions.
15044 Region = OtherRegion;
15045 for (const Expr *Argument : CE->arguments())
15046 Visit(Argument);
15047
15048 Region = OldRegion;
15049 if (SemaRef.getLangOpts().CPlusPlus17) {
15050 Tree.merge(CalleeRegion);
15051 Tree.merge(OtherRegion);
15052 }
15053 });
15054 }
15055
15056 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15057 // C++17 [over.match.oper]p2:
15058 // [...] the operator notation is first transformed to the equivalent
15059 // function-call notation as summarized in Table 12 (where @ denotes one
15060 // of the operators covered in the specified subclause). However, the
15061 // operands are sequenced in the order prescribed for the built-in
15062 // operator (Clause 8).
15063 //
15064 // From the above only overloaded binary operators and overloaded call
15065 // operators have sequencing rules in C++17 that we need to handle
15066 // separately.
15067 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15068 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15069 return VisitCallExpr(CXXOCE);
15070
15071 enum {
15072 NoSequencing,
15073 LHSBeforeRHS,
15074 RHSBeforeLHS,
15075 LHSBeforeRest
15076 } SequencingKind;
15077 switch (CXXOCE->getOperator()) {
15078 case OO_Equal:
15079 case OO_PlusEqual:
15080 case OO_MinusEqual:
15081 case OO_StarEqual:
15082 case OO_SlashEqual:
15083 case OO_PercentEqual:
15084 case OO_CaretEqual:
15085 case OO_AmpEqual:
15086 case OO_PipeEqual:
15087 case OO_LessLessEqual:
15088 case OO_GreaterGreaterEqual:
15089 SequencingKind = RHSBeforeLHS;
15090 break;
15091
15092 case OO_LessLess:
15093 case OO_GreaterGreater:
15094 case OO_AmpAmp:
15095 case OO_PipePipe:
15096 case OO_Comma:
15097 case OO_ArrowStar:
15098 case OO_Subscript:
15099 SequencingKind = LHSBeforeRHS;
15100 break;
15101
15102 case OO_Call:
15103 SequencingKind = LHSBeforeRest;
15104 break;
15105
15106 default:
15107 SequencingKind = NoSequencing;
15108 break;
15109 }
15110
15111 if (SequencingKind == NoSequencing)
15112 return VisitCallExpr(CXXOCE);
15113
15114 // This is a call, so all subexpressions are sequenced before the result.
15115 SequencedSubexpression Sequenced(*this);
15116
15117 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15118 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15119 "Should only get there with C++17 and above!");
15120 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15121 "Should only get there with an overloaded binary operator"
15122 " or an overloaded call operator!");
15123
15124 if (SequencingKind == LHSBeforeRest) {
15125 assert(CXXOCE->getOperator() == OO_Call &&
15126 "We should only have an overloaded call operator here!");
15127
15128 // This is very similar to VisitCallExpr, except that we only have the
15129 // C++17 case. The postfix-expression is the first argument of the
15130 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15131 // are in the following arguments.
15132 //
15133 // Note that we intentionally do not visit the callee expression since
15134 // it is just a decayed reference to a function.
15135 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15136 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15137 SequenceTree::Seq OldRegion = Region;
15138
15139 assert(CXXOCE->getNumArgs() >= 1 &&
15140 "An overloaded call operator must have at least one argument"
15141 " for the postfix-expression!");
15142 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15143 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15144 CXXOCE->getNumArgs() - 1);
15145
15146 // Visit the postfix-expression first.
15147 {
15148 Region = PostfixExprRegion;
15149 SequencedSubexpression Sequenced(*this);
15150 Visit(PostfixExpr);
15151 }
15152
15153 // Then visit the argument expressions.
15154 Region = ArgsRegion;
15155 for (const Expr *Arg : Args)
15156 Visit(Arg);
15157
15158 Region = OldRegion;
15159 Tree.merge(PostfixExprRegion);
15160 Tree.merge(ArgsRegion);
15161 } else {
15162 assert(CXXOCE->getNumArgs() == 2 &&
15163 "Should only have two arguments here!");
15164 assert((SequencingKind == LHSBeforeRHS ||
15165 SequencingKind == RHSBeforeLHS) &&
15166 "Unexpected sequencing kind!");
15167
15168 // We do not visit the callee expression since it is just a decayed
15169 // reference to a function.
15170 const Expr *E1 = CXXOCE->getArg(0);
15171 const Expr *E2 = CXXOCE->getArg(1);
15172 if (SequencingKind == RHSBeforeLHS)
15173 std::swap(E1, E2);
15174
15175 return VisitSequencedExpressions(E1, E2);
15176 }
15177 });
15178 }
15179
15180 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15181 // This is a call, so all subexpressions are sequenced before the result.
15182 SequencedSubexpression Sequenced(*this);
15183
15184 if (!CCE->isListInitialization())
15185 return VisitExpr(CCE);
15186
15187 // In C++11, list initializations are sequenced.
15188 SequenceExpressionsInOrder(
15189 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15190 }
15191
15192 void VisitInitListExpr(const InitListExpr *ILE) {
15193 if (!SemaRef.getLangOpts().CPlusPlus11)
15194 return VisitExpr(ILE);
15195
15196 // In C++11, list initializations are sequenced.
15197 SequenceExpressionsInOrder(ILE->inits());
15198 }
15199
15200 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15201 // C++20 parenthesized list initializations are sequenced. See C++20
15202 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15203 SequenceExpressionsInOrder(PLIE->getInitExprs());
15204 }
15205
15206private:
15207 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15209 SequenceTree::Seq Parent = Region;
15210 for (const Expr *E : ExpressionList) {
15211 if (!E)
15212 continue;
15213 Region = Tree.allocate(Parent);
15214 Elts.push_back(Region);
15215 Visit(E);
15216 }
15217
15218 // Forget that the initializers are sequenced.
15219 Region = Parent;
15220 for (unsigned I = 0; I < Elts.size(); ++I)
15221 Tree.merge(Elts[I]);
15222 }
15223};
15224
15225SequenceChecker::UsageInfo::UsageInfo() = default;
15226
15227} // namespace
15228
15229void Sema::CheckUnsequencedOperations(const Expr *E) {
15230 SmallVector<const Expr *, 8> WorkList;
15231 WorkList.push_back(E);
15232 while (!WorkList.empty()) {
15233 const Expr *Item = WorkList.pop_back_val();
15234 SequenceChecker(*this, Item, WorkList);
15235 }
15236}
15237
15238void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15239 bool IsConstexpr) {
15240 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15241 IsConstexpr || isa<ConstantExpr>(E));
15242 CheckImplicitConversions(E, CheckLoc);
15243 if (!E->isInstantiationDependent())
15244 CheckUnsequencedOperations(E);
15245 if (!IsConstexpr && !E->isValueDependent())
15246 CheckForIntOverflow(E);
15247}
15248
15249void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15250 FieldDecl *BitField,
15251 Expr *Init) {
15252 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15253}
15254
15256 SourceLocation Loc) {
15257 if (!PType->isVariablyModifiedType())
15258 return;
15259 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15260 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15261 return;
15262 }
15263 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15264 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15265 return;
15266 }
15267 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15268 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15269 return;
15270 }
15271
15272 const ArrayType *AT = S.Context.getAsArrayType(PType);
15273 if (!AT)
15274 return;
15275
15278 return;
15279 }
15280
15281 S.Diag(Loc, diag::err_array_star_in_function_definition);
15282}
15283
15285 bool CheckParameterNames) {
15286 bool HasInvalidParm = false;
15287 for (ParmVarDecl *Param : Parameters) {
15288 assert(Param && "null in a parameter list");
15289 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15290 // function declarator that is part of a function definition of
15291 // that function shall not have incomplete type.
15292 //
15293 // C++23 [dcl.fct.def.general]/p2
15294 // The type of a parameter [...] for a function definition
15295 // shall not be a (possibly cv-qualified) class type that is incomplete
15296 // or abstract within the function body unless the function is deleted.
15297 if (!Param->isInvalidDecl() &&
15298 (RequireCompleteType(Param->getLocation(), Param->getType(),
15299 diag::err_typecheck_decl_incomplete_type) ||
15300 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15301 diag::err_abstract_type_in_decl,
15303 Param->setInvalidDecl();
15304 HasInvalidParm = true;
15305 }
15306
15307 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15308 // declaration of each parameter shall include an identifier.
15309 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15310 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15311 // Diagnose this as an extension in C17 and earlier.
15312 if (!getLangOpts().C23)
15313 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15314 }
15315
15316 // C99 6.7.5.3p12:
15317 // If the function declarator is not part of a definition of that
15318 // function, parameters may have incomplete type and may use the [*]
15319 // notation in their sequences of declarator specifiers to specify
15320 // variable length array types.
15321 QualType PType = Param->getOriginalType();
15322 // FIXME: This diagnostic should point the '[*]' if source-location
15323 // information is added for it.
15324 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15325
15326 // If the parameter is a c++ class type and it has to be destructed in the
15327 // callee function, declare the destructor so that it can be called by the
15328 // callee function. Do not perform any direct access check on the dtor here.
15329 if (!Param->isInvalidDecl()) {
15330 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15331 if (!ClassDecl->isInvalidDecl() &&
15332 !ClassDecl->hasIrrelevantDestructor() &&
15333 !ClassDecl->isDependentContext() &&
15334 ClassDecl->isParamDestroyedInCallee()) {
15336 MarkFunctionReferenced(Param->getLocation(), Destructor);
15337 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15338 }
15339 }
15340 }
15341
15342 // Parameters with the pass_object_size attribute only need to be marked
15343 // constant at function definitions. Because we lack information about
15344 // whether we're on a declaration or definition when we're instantiating the
15345 // attribute, we need to check for constness here.
15346 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15347 if (!Param->getType().isConstQualified())
15348 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15349 << Attr->getSpelling() << 1;
15350
15351 // Check for parameter names shadowing fields from the class.
15352 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15353 // The owning context for the parameter should be the function, but we
15354 // want to see if this function's declaration context is a record.
15355 DeclContext *DC = Param->getDeclContext();
15356 if (DC && DC->isFunctionOrMethod()) {
15357 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15358 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15359 RD, /*DeclIsField*/ false);
15360 }
15361 }
15362
15363 if (!Param->isInvalidDecl() &&
15364 Param->getOriginalType()->isWebAssemblyTableType()) {
15365 Param->setInvalidDecl();
15366 HasInvalidParm = true;
15367 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15368 }
15369 }
15370
15371 return HasInvalidParm;
15372}
15373
15374std::optional<std::pair<
15376 *E,
15378 &Ctx);
15379
15380/// Compute the alignment and offset of the base class object given the
15381/// derived-to-base cast expression and the alignment and offset of the derived
15382/// class object.
15383static std::pair<CharUnits, CharUnits>
15385 CharUnits BaseAlignment, CharUnits Offset,
15386 ASTContext &Ctx) {
15387 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15388 ++PathI) {
15389 const CXXBaseSpecifier *Base = *PathI;
15390 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15391 if (Base->isVirtual()) {
15392 // The complete object may have a lower alignment than the non-virtual
15393 // alignment of the base, in which case the base may be misaligned. Choose
15394 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15395 // conservative lower bound of the complete object alignment.
15396 CharUnits NonVirtualAlignment =
15398 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15399 Offset = CharUnits::Zero();
15400 } else {
15401 const ASTRecordLayout &RL =
15402 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15403 Offset += RL.getBaseClassOffset(BaseDecl);
15404 }
15405 DerivedType = Base->getType();
15406 }
15407
15408 return std::make_pair(BaseAlignment, Offset);
15409}
15410
15411/// Compute the alignment and offset of a binary additive operator.
15412static std::optional<std::pair<CharUnits, CharUnits>>
15414 bool IsSub, ASTContext &Ctx) {
15415 QualType PointeeType = PtrE->getType()->getPointeeType();
15416
15417 if (!PointeeType->isConstantSizeType())
15418 return std::nullopt;
15419
15420 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15421
15422 if (!P)
15423 return std::nullopt;
15424
15425 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15426 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15427 CharUnits Offset = EltSize * IdxRes->getExtValue();
15428 if (IsSub)
15429 Offset = -Offset;
15430 return std::make_pair(P->first, P->second + Offset);
15431 }
15432
15433 // If the integer expression isn't a constant expression, compute the lower
15434 // bound of the alignment using the alignment and offset of the pointer
15435 // expression and the element size.
15436 return std::make_pair(
15437 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15438 CharUnits::Zero());
15439}
15440
15441/// This helper function takes an lvalue expression and returns the alignment of
15442/// a VarDecl and a constant offset from the VarDecl.
15443std::optional<std::pair<
15444 CharUnits,
15446 ASTContext &Ctx) {
15447 E = E->IgnoreParens();
15448 switch (E->getStmtClass()) {
15449 default:
15450 break;
15451 case Stmt::CStyleCastExprClass:
15452 case Stmt::CXXStaticCastExprClass:
15453 case Stmt::ImplicitCastExprClass: {
15454 auto *CE = cast<CastExpr>(E);
15455 const Expr *From = CE->getSubExpr();
15456 switch (CE->getCastKind()) {
15457 default:
15458 break;
15459 case CK_NoOp:
15460 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15461 case CK_UncheckedDerivedToBase:
15462 case CK_DerivedToBase: {
15463 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15464 if (!P)
15465 break;
15466 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15467 P->second, Ctx);
15468 }
15469 }
15470 break;
15471 }
15472 case Stmt::ArraySubscriptExprClass: {
15473 auto *ASE = cast<ArraySubscriptExpr>(E);
15475 false, Ctx);
15476 }
15477 case Stmt::DeclRefExprClass: {
15478 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15479 // FIXME: If VD is captured by copy or is an escaping __block variable,
15480 // use the alignment of VD's type.
15481 if (!VD->getType()->isReferenceType()) {
15482 // Dependent alignment cannot be resolved -> bail out.
15483 if (VD->hasDependentAlignment())
15484 break;
15485 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15486 }
15487 if (VD->hasInit())
15488 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15489 }
15490 break;
15491 }
15492 case Stmt::MemberExprClass: {
15493 auto *ME = cast<MemberExpr>(E);
15494 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15495 if (!FD || FD->getType()->isReferenceType() ||
15496 FD->getParent()->isInvalidDecl())
15497 break;
15498 std::optional<std::pair<CharUnits, CharUnits>> P;
15499 if (ME->isArrow())
15500 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15501 else
15502 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15503 if (!P)
15504 break;
15505 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15506 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15507 return std::make_pair(P->first,
15508 P->second + CharUnits::fromQuantity(Offset));
15509 }
15510 case Stmt::UnaryOperatorClass: {
15511 auto *UO = cast<UnaryOperator>(E);
15512 switch (UO->getOpcode()) {
15513 default:
15514 break;
15515 case UO_Deref:
15517 }
15518 break;
15519 }
15520 case Stmt::BinaryOperatorClass: {
15521 auto *BO = cast<BinaryOperator>(E);
15522 auto Opcode = BO->getOpcode();
15523 switch (Opcode) {
15524 default:
15525 break;
15526 case BO_Comma:
15528 }
15529 break;
15530 }
15531 }
15532 return std::nullopt;
15533}
15534
15535/// This helper function takes a pointer expression and returns the alignment of
15536/// a VarDecl and a constant offset from the VarDecl.
15537std::optional<std::pair<
15539 *E,
15541 &Ctx) {
15542 E = E->IgnoreParens();
15543 switch (E->getStmtClass()) {
15544 default:
15545 break;
15546 case Stmt::CStyleCastExprClass:
15547 case Stmt::CXXStaticCastExprClass:
15548 case Stmt::ImplicitCastExprClass: {
15549 auto *CE = cast<CastExpr>(E);
15550 const Expr *From = CE->getSubExpr();
15551 switch (CE->getCastKind()) {
15552 default:
15553 break;
15554 case CK_NoOp:
15555 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15556 case CK_ArrayToPointerDecay:
15557 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15558 case CK_UncheckedDerivedToBase:
15559 case CK_DerivedToBase: {
15560 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15561 if (!P)
15562 break;
15564 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15565 }
15566 }
15567 break;
15568 }
15569 case Stmt::CXXThisExprClass: {
15570 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15572 return std::make_pair(Alignment, CharUnits::Zero());
15573 }
15574 case Stmt::UnaryOperatorClass: {
15575 auto *UO = cast<UnaryOperator>(E);
15576 if (UO->getOpcode() == UO_AddrOf)
15578 break;
15579 }
15580 case Stmt::BinaryOperatorClass: {
15581 auto *BO = cast<BinaryOperator>(E);
15582 auto Opcode = BO->getOpcode();
15583 switch (Opcode) {
15584 default:
15585 break;
15586 case BO_Add:
15587 case BO_Sub: {
15588 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15589 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15590 std::swap(LHS, RHS);
15591 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15592 Ctx);
15593 }
15594 case BO_Comma:
15595 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15596 }
15597 break;
15598 }
15599 }
15600 return std::nullopt;
15601}
15602
15604 // See if we can compute the alignment of a VarDecl and an offset from it.
15605 std::optional<std::pair<CharUnits, CharUnits>> P =
15607
15608 if (P)
15609 return P->first.alignmentAtOffset(P->second);
15610
15611 // If that failed, return the type's alignment.
15613}
15614
15616 // This is actually a lot of work to potentially be doing on every
15617 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15618 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15619 return;
15620
15621 // Ignore dependent types.
15622 if (T->isDependentType() || Op->getType()->isDependentType())
15623 return;
15624
15625 // Require that the destination be a pointer type.
15626 const PointerType *DestPtr = T->getAs<PointerType>();
15627 if (!DestPtr) return;
15628
15629 // If the destination has alignment 1, we're done.
15630 QualType DestPointee = DestPtr->getPointeeType();
15631 if (DestPointee->isIncompleteType()) return;
15632 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15633 if (DestAlign.isOne()) return;
15634
15635 // Require that the source be a pointer type.
15636 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15637 if (!SrcPtr) return;
15638 QualType SrcPointee = SrcPtr->getPointeeType();
15639
15640 // Explicitly allow casts from cv void*. We already implicitly
15641 // allowed casts to cv void*, since they have alignment 1.
15642 // Also allow casts involving incomplete types, which implicitly
15643 // includes 'void'.
15644 if (SrcPointee->isIncompleteType()) return;
15645
15646 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15647
15648 if (SrcAlign >= DestAlign) return;
15649
15650 Diag(TRange.getBegin(), diag::warn_cast_align)
15651 << Op->getType() << T
15652 << static_cast<unsigned>(SrcAlign.getQuantity())
15653 << static_cast<unsigned>(DestAlign.getQuantity())
15654 << TRange << Op->getSourceRange();
15655}
15656
15657void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15658 const ArraySubscriptExpr *ASE,
15659 bool AllowOnePastEnd, bool IndexNegated) {
15660 // Already diagnosed by the constant evaluator.
15662 return;
15663
15664 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15665 if (IndexExpr->isValueDependent())
15666 return;
15667
15668 const Type *EffectiveType =
15670 BaseExpr = BaseExpr->IgnoreParenCasts();
15671 const ConstantArrayType *ArrayTy =
15672 Context.getAsConstantArrayType(BaseExpr->getType());
15673
15675 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15676
15677 const Type *BaseType =
15678 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15679 bool IsUnboundedArray =
15680 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15681 Context, StrictFlexArraysLevel,
15682 /*IgnoreTemplateOrMacroSubstitution=*/true);
15683 if (EffectiveType->isDependentType() ||
15684 (!IsUnboundedArray && BaseType->isDependentType()))
15685 return;
15686
15688 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15689 return;
15690
15691 llvm::APSInt index = Result.Val.getInt();
15692 if (IndexNegated) {
15693 index.setIsUnsigned(false);
15694 index = -index;
15695 }
15696
15697 if (IsUnboundedArray) {
15698 if (EffectiveType->isFunctionType())
15699 return;
15700 if (index.isUnsigned() || !index.isNegative()) {
15701 const auto &ASTC = getASTContext();
15702 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15703 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15704 if (index.getBitWidth() < AddrBits)
15705 index = index.zext(AddrBits);
15706 std::optional<CharUnits> ElemCharUnits =
15707 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15708 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15709 // pointer) bounds-checking isn't meaningful.
15710 if (!ElemCharUnits || ElemCharUnits->isZero())
15711 return;
15712 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15713 // If index has more active bits than address space, we already know
15714 // we have a bounds violation to warn about. Otherwise, compute
15715 // address of (index + 1)th element, and warn about bounds violation
15716 // only if that address exceeds address space.
15717 if (index.getActiveBits() <= AddrBits) {
15718 bool Overflow;
15719 llvm::APInt Product(index);
15720 Product += 1;
15721 Product = Product.umul_ov(ElemBytes, Overflow);
15722 if (!Overflow && Product.getActiveBits() <= AddrBits)
15723 return;
15724 }
15725
15726 // Need to compute max possible elements in address space, since that
15727 // is included in diag message.
15728 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15729 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15730 MaxElems += 1;
15731 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15732 MaxElems = MaxElems.udiv(ElemBytes);
15733
15734 unsigned DiagID =
15735 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15736 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15737
15738 // Diag message shows element size in bits and in "bytes" (platform-
15739 // dependent CharUnits)
15740 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15741 PDiag(DiagID) << index << AddrBits
15742 << (unsigned)ASTC.toBits(*ElemCharUnits)
15743 << ElemBytes << MaxElems
15744 << MaxElems.getZExtValue()
15745 << IndexExpr->getSourceRange());
15746
15747 const NamedDecl *ND = nullptr;
15748 // Try harder to find a NamedDecl to point at in the note.
15749 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15750 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15751 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15752 ND = DRE->getDecl();
15753 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15754 ND = ME->getMemberDecl();
15755
15756 if (ND)
15757 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15758 PDiag(diag::note_array_declared_here) << ND);
15759 }
15760 return;
15761 }
15762
15763 if (index.isUnsigned() || !index.isNegative()) {
15764 // It is possible that the type of the base expression after
15765 // IgnoreParenCasts is incomplete, even though the type of the base
15766 // expression before IgnoreParenCasts is complete (see PR39746 for an
15767 // example). In this case we have no information about whether the array
15768 // access exceeds the array bounds. However we can still diagnose an array
15769 // access which precedes the array bounds.
15770 if (BaseType->isIncompleteType())
15771 return;
15772
15773 llvm::APInt size = ArrayTy->getSize();
15774
15775 if (BaseType != EffectiveType) {
15776 // Make sure we're comparing apples to apples when comparing index to
15777 // size.
15778 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15779 uint64_t array_typesize = Context.getTypeSize(BaseType);
15780
15781 // Handle ptrarith_typesize being zero, such as when casting to void*.
15782 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15783 if (!ptrarith_typesize)
15784 ptrarith_typesize = Context.getCharWidth();
15785
15786 if (ptrarith_typesize != array_typesize) {
15787 // There's a cast to a different size type involved.
15788 uint64_t ratio = array_typesize / ptrarith_typesize;
15789
15790 // TODO: Be smarter about handling cases where array_typesize is not a
15791 // multiple of ptrarith_typesize.
15792 if (ptrarith_typesize * ratio == array_typesize)
15793 size *= llvm::APInt(size.getBitWidth(), ratio);
15794 }
15795 }
15796
15797 if (size.getBitWidth() > index.getBitWidth())
15798 index = index.zext(size.getBitWidth());
15799 else if (size.getBitWidth() < index.getBitWidth())
15800 size = size.zext(index.getBitWidth());
15801
15802 // For array subscripting the index must be less than size, but for pointer
15803 // arithmetic also allow the index (offset) to be equal to size since
15804 // computing the next address after the end of the array is legal and
15805 // commonly done e.g. in C++ iterators and range-based for loops.
15806 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15807 return;
15808
15809 // Suppress the warning if the subscript expression (as identified by the
15810 // ']' location) and the index expression are both from macro expansions
15811 // within a system header.
15812 if (ASE) {
15813 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15814 ASE->getRBracketLoc());
15815 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15816 SourceLocation IndexLoc =
15817 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15818 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15819 return;
15820 }
15821 }
15822
15823 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15824 : diag::warn_ptr_arith_exceeds_bounds;
15825 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15826 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15827
15828 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15829 PDiag(DiagID)
15830 << index << ArrayTy->desugar() << CastMsg
15831 << CastMsgTy << IndexExpr->getSourceRange());
15832 } else {
15833 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15834 if (!ASE) {
15835 DiagID = diag::warn_ptr_arith_precedes_bounds;
15836 if (index.isNegative()) index = -index;
15837 }
15838
15839 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15840 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15841 }
15842
15843 const NamedDecl *ND = nullptr;
15844 // Try harder to find a NamedDecl to point at in the note.
15845 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15846 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15847 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15848 ND = DRE->getDecl();
15849 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15850 ND = ME->getMemberDecl();
15851
15852 if (ND)
15853 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15854 PDiag(diag::note_array_declared_here) << ND);
15855}
15856
15857void Sema::CheckArrayAccess(const Expr *expr) {
15858 int AllowOnePastEnd = 0;
15859 while (expr) {
15860 expr = expr->IgnoreParenImpCasts();
15861 switch (expr->getStmtClass()) {
15862 case Stmt::ArraySubscriptExprClass: {
15863 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15864 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15865 AllowOnePastEnd > 0);
15866 expr = ASE->getBase();
15867 break;
15868 }
15869 case Stmt::MemberExprClass: {
15870 expr = cast<MemberExpr>(expr)->getBase();
15871 break;
15872 }
15873 case Stmt::CXXMemberCallExprClass: {
15874 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
15875 break;
15876 }
15877 case Stmt::ArraySectionExprClass: {
15878 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15879 // FIXME: We should probably be checking all of the elements to the
15880 // 'length' here as well.
15881 if (ASE->getLowerBound())
15882 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15883 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15884 return;
15885 }
15886 case Stmt::UnaryOperatorClass: {
15887 // Only unwrap the * and & unary operators
15888 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15889 expr = UO->getSubExpr();
15890 switch (UO->getOpcode()) {
15891 case UO_AddrOf:
15892 AllowOnePastEnd++;
15893 break;
15894 case UO_Deref:
15895 AllowOnePastEnd--;
15896 break;
15897 default:
15898 return;
15899 }
15900 break;
15901 }
15902 case Stmt::ConditionalOperatorClass: {
15903 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15904 if (const Expr *lhs = cond->getLHS())
15905 CheckArrayAccess(lhs);
15906 if (const Expr *rhs = cond->getRHS())
15907 CheckArrayAccess(rhs);
15908 return;
15909 }
15910 case Stmt::CXXOperatorCallExprClass: {
15911 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15912 for (const auto *Arg : OCE->arguments())
15913 CheckArrayAccess(Arg);
15914 return;
15915 }
15916 default:
15917 return;
15918 }
15919 }
15920}
15921
15923 Expr *RHS, bool isProperty) {
15924 // Check if RHS is an Objective-C object literal, which also can get
15925 // immediately zapped in a weak reference. Note that we explicitly
15926 // allow ObjCStringLiterals, since those are designed to never really die.
15927 RHS = RHS->IgnoreParenImpCasts();
15928
15929 // This enum needs to match with the 'select' in
15930 // warn_objc_arc_literal_assign (off-by-1).
15932 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15933 return false;
15934
15935 S.Diag(Loc, diag::warn_arc_literal_assign)
15936 << (unsigned) Kind
15937 << (isProperty ? 0 : 1)
15938 << RHS->getSourceRange();
15939
15940 return true;
15941}
15942
15945 Expr *RHS, bool isProperty) {
15946 // Strip off any implicit cast added to get to the one ARC-specific.
15947 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15948 if (cast->getCastKind() == CK_ARCConsumeObject) {
15949 S.Diag(Loc, diag::warn_arc_retained_assign)
15951 << (isProperty ? 0 : 1)
15952 << RHS->getSourceRange();
15953 return true;
15954 }
15955 RHS = cast->getSubExpr();
15956 }
15957
15958 if (LT == Qualifiers::OCL_Weak &&
15959 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15960 return true;
15961
15962 return false;
15963}
15964
15966 QualType LHS, Expr *RHS) {
15968
15970 return false;
15971
15972 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15973 return true;
15974
15975 return false;
15976}
15977
15979 Expr *LHS, Expr *RHS) {
15980 QualType LHSType;
15981 // PropertyRef on LHS type need be directly obtained from
15982 // its declaration as it has a PseudoType.
15984 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15985 if (PRE && !PRE->isImplicitProperty()) {
15986 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15987 if (PD)
15988 LHSType = PD->getType();
15989 }
15990
15991 if (LHSType.isNull())
15992 LHSType = LHS->getType();
15993
15995
15996 if (LT == Qualifiers::OCL_Weak) {
15997 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15999 }
16000
16001 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16002 return;
16003
16004 // FIXME. Check for other life times.
16005 if (LT != Qualifiers::OCL_None)
16006 return;
16007
16008 if (PRE) {
16009 if (PRE->isImplicitProperty())
16010 return;
16011 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16012 if (!PD)
16013 return;
16014
16015 unsigned Attributes = PD->getPropertyAttributes();
16016 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16017 // when 'assign' attribute was not explicitly specified
16018 // by user, ignore it and rely on property type itself
16019 // for lifetime info.
16020 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16021 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16022 LHSType->isObjCRetainableType())
16023 return;
16024
16025 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16026 if (cast->getCastKind() == CK_ARCConsumeObject) {
16027 Diag(Loc, diag::warn_arc_retained_property_assign)
16028 << RHS->getSourceRange();
16029 return;
16030 }
16031 RHS = cast->getSubExpr();
16032 }
16033 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16034 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16035 return;
16036 }
16037 }
16038}
16039
16040//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16041
16042static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16043 SourceLocation StmtLoc,
16044 const NullStmt *Body) {
16045 // Do not warn if the body is a macro that expands to nothing, e.g:
16046 //
16047 // #define CALL(x)
16048 // if (condition)
16049 // CALL(0);
16050 if (Body->hasLeadingEmptyMacro())
16051 return false;
16052
16053 // Get line numbers of statement and body.
16054 bool StmtLineInvalid;
16055 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16056 &StmtLineInvalid);
16057 if (StmtLineInvalid)
16058 return false;
16059
16060 bool BodyLineInvalid;
16061 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16062 &BodyLineInvalid);
16063 if (BodyLineInvalid)
16064 return false;
16065
16066 // Warn if null statement and body are on the same line.
16067 if (StmtLine != BodyLine)
16068 return false;
16069
16070 return true;
16071}
16072
16074 const Stmt *Body,
16075 unsigned DiagID) {
16076 // Since this is a syntactic check, don't emit diagnostic for template
16077 // instantiations, this just adds noise.
16079 return;
16080
16081 // The body should be a null statement.
16082 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16083 if (!NBody)
16084 return;
16085
16086 // Do the usual checks.
16087 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16088 return;
16089
16090 Diag(NBody->getSemiLoc(), DiagID);
16091 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16092}
16093
16095 const Stmt *PossibleBody) {
16096 assert(!CurrentInstantiationScope); // Ensured by caller
16097
16098 SourceLocation StmtLoc;
16099 const Stmt *Body;
16100 unsigned DiagID;
16101 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16102 StmtLoc = FS->getRParenLoc();
16103 Body = FS->getBody();
16104 DiagID = diag::warn_empty_for_body;
16105 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16106 StmtLoc = WS->getRParenLoc();
16107 Body = WS->getBody();
16108 DiagID = diag::warn_empty_while_body;
16109 } else
16110 return; // Neither `for' nor `while'.
16111
16112 // The body should be a null statement.
16113 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16114 if (!NBody)
16115 return;
16116
16117 // Skip expensive checks if diagnostic is disabled.
16118 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16119 return;
16120
16121 // Do the usual checks.
16122 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16123 return;
16124
16125 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16126 // noise level low, emit diagnostics only if for/while is followed by a
16127 // CompoundStmt, e.g.:
16128 // for (int i = 0; i < n; i++);
16129 // {
16130 // a(i);
16131 // }
16132 // or if for/while is followed by a statement with more indentation
16133 // than for/while itself:
16134 // for (int i = 0; i < n; i++);
16135 // a(i);
16136 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16137 if (!ProbableTypo) {
16138 bool BodyColInvalid;
16139 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16140 PossibleBody->getBeginLoc(), &BodyColInvalid);
16141 if (BodyColInvalid)
16142 return;
16143
16144 bool StmtColInvalid;
16145 unsigned StmtCol =
16146 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16147 if (StmtColInvalid)
16148 return;
16149
16150 if (BodyCol > StmtCol)
16151 ProbableTypo = true;
16152 }
16153
16154 if (ProbableTypo) {
16155 Diag(NBody->getSemiLoc(), DiagID);
16156 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16157 }
16158}
16159
16160//===--- CHECK: Warn on self move with std::move. -------------------------===//
16161
16162void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16163 SourceLocation OpLoc) {
16164 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16165 return;
16166
16168 return;
16169
16170 // Strip parens and casts away.
16171 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16172 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16173
16174 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16175 // which we can treat as an inlined std::move
16176 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16177 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16178 RHSExpr = CE->getArg(0);
16179 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16180 CXXSCE && CXXSCE->isXValue())
16181 RHSExpr = CXXSCE->getSubExpr();
16182 else
16183 return;
16184
16185 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16186 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16187
16188 // Two DeclRefExpr's, check that the decls are the same.
16189 if (LHSDeclRef && RHSDeclRef) {
16190 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16191 return;
16192 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16193 RHSDeclRef->getDecl()->getCanonicalDecl())
16194 return;
16195
16196 auto D = Diag(OpLoc, diag::warn_self_move)
16197 << LHSExpr->getType() << LHSExpr->getSourceRange()
16198 << RHSExpr->getSourceRange();
16199 if (const FieldDecl *F =
16201 D << 1 << F
16202 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16203 else
16204 D << 0;
16205 return;
16206 }
16207
16208 // Member variables require a different approach to check for self moves.
16209 // MemberExpr's are the same if every nested MemberExpr refers to the same
16210 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16211 // the base Expr's are CXXThisExpr's.
16212 const Expr *LHSBase = LHSExpr;
16213 const Expr *RHSBase = RHSExpr;
16214 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16215 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16216 if (!LHSME || !RHSME)
16217 return;
16218
16219 while (LHSME && RHSME) {
16220 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16221 RHSME->getMemberDecl()->getCanonicalDecl())
16222 return;
16223
16224 LHSBase = LHSME->getBase();
16225 RHSBase = RHSME->getBase();
16226 LHSME = dyn_cast<MemberExpr>(LHSBase);
16227 RHSME = dyn_cast<MemberExpr>(RHSBase);
16228 }
16229
16230 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16231 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16232 if (LHSDeclRef && RHSDeclRef) {
16233 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16234 return;
16235 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16236 RHSDeclRef->getDecl()->getCanonicalDecl())
16237 return;
16238
16239 Diag(OpLoc, diag::warn_self_move)
16240 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16241 << RHSExpr->getSourceRange();
16242 return;
16243 }
16244
16245 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16246 Diag(OpLoc, diag::warn_self_move)
16247 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16248 << RHSExpr->getSourceRange();
16249}
16250
16251//===--- Layout compatibility ----------------------------------------------//
16252
16253static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16254
16255/// Check if two enumeration types are layout-compatible.
16256static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16257 const EnumDecl *ED2) {
16258 // C++11 [dcl.enum] p8:
16259 // Two enumeration types are layout-compatible if they have the same
16260 // underlying type.
16261 return ED1->isComplete() && ED2->isComplete() &&
16262 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16263}
16264
16265/// Check if two fields are layout-compatible.
16266/// Can be used on union members, which are exempt from alignment requirement
16267/// of common initial sequence.
16268static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16269 const FieldDecl *Field2,
16270 bool AreUnionMembers = false) {
16271#ifndef NDEBUG
16272 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16273 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16274 assert(((Field1Parent->isStructureOrClassType() &&
16275 Field2Parent->isStructureOrClassType()) ||
16276 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16277 "Can't evaluate layout compatibility between a struct field and a "
16278 "union field.");
16279 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16280 (AreUnionMembers && Field1Parent->isUnionType())) &&
16281 "AreUnionMembers should be 'true' for union fields (only).");
16282#endif
16283
16284 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16285 return false;
16286
16287 if (Field1->isBitField() != Field2->isBitField())
16288 return false;
16289
16290 if (Field1->isBitField()) {
16291 // Make sure that the bit-fields are the same length.
16292 unsigned Bits1 = Field1->getBitWidthValue();
16293 unsigned Bits2 = Field2->getBitWidthValue();
16294
16295 if (Bits1 != Bits2)
16296 return false;
16297 }
16298
16299 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16300 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16301 return false;
16302
16303 if (!AreUnionMembers &&
16304 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16305 return false;
16306
16307 return true;
16308}
16309
16310/// Check if two standard-layout structs are layout-compatible.
16311/// (C++11 [class.mem] p17)
16312static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16313 const RecordDecl *RD2) {
16314 // Get to the class where the fields are declared
16315 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16316 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16317
16318 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16319 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16320
16321 // Check the fields.
16322 return llvm::equal(RD1->fields(), RD2->fields(),
16323 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16324 return isLayoutCompatible(C, F1, F2);
16325 });
16326}
16327
16328/// Check if two standard-layout unions are layout-compatible.
16329/// (C++11 [class.mem] p18)
16330static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16331 const RecordDecl *RD2) {
16332 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16333 RD2->fields());
16334
16335 for (auto *Field1 : RD1->fields()) {
16336 auto I = UnmatchedFields.begin();
16337 auto E = UnmatchedFields.end();
16338
16339 for ( ; I != E; ++I) {
16340 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16341 bool Result = UnmatchedFields.erase(*I);
16342 (void) Result;
16343 assert(Result);
16344 break;
16345 }
16346 }
16347 if (I == E)
16348 return false;
16349 }
16350
16351 return UnmatchedFields.empty();
16352}
16353
16354static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16355 const RecordDecl *RD2) {
16356 if (RD1->isUnion() != RD2->isUnion())
16357 return false;
16358
16359 if (RD1->isUnion())
16360 return isLayoutCompatibleUnion(C, RD1, RD2);
16361 else
16362 return isLayoutCompatibleStruct(C, RD1, RD2);
16363}
16364
16365/// Check if two types are layout-compatible in C++11 sense.
16366static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16367 if (T1.isNull() || T2.isNull())
16368 return false;
16369
16370 // C++20 [basic.types] p11:
16371 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16372 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16373 // or layout-compatible standard-layout class types (11.4).
16376
16377 if (C.hasSameType(T1, T2))
16378 return true;
16379
16380 const Type::TypeClass TC1 = T1->getTypeClass();
16381 const Type::TypeClass TC2 = T2->getTypeClass();
16382
16383 if (TC1 != TC2)
16384 return false;
16385
16386 if (TC1 == Type::Enum)
16387 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16388 if (TC1 == Type::Record) {
16389 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16390 return false;
16391
16393 T2->castAsRecordDecl());
16394 }
16395
16396 return false;
16397}
16398
16400 return isLayoutCompatible(getASTContext(), T1, T2);
16401}
16402
16403//===-------------- Pointer interconvertibility ----------------------------//
16404
16406 const TypeSourceInfo *Derived) {
16407 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16408 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16409
16410 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16411 getASTContext().hasSameType(BaseT, DerivedT))
16412 return true;
16413
16414 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16415 return false;
16416
16417 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16418 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16419 return true;
16420
16421 return false;
16422}
16423
16424//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16425
16426/// Given a type tag expression find the type tag itself.
16427///
16428/// \param TypeExpr Type tag expression, as it appears in user's code.
16429///
16430/// \param VD Declaration of an identifier that appears in a type tag.
16431///
16432/// \param MagicValue Type tag magic value.
16433///
16434/// \param isConstantEvaluated whether the evalaution should be performed in
16435
16436/// constant context.
16437static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16438 const ValueDecl **VD, uint64_t *MagicValue,
16439 bool isConstantEvaluated) {
16440 while(true) {
16441 if (!TypeExpr)
16442 return false;
16443
16444 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16445
16446 switch (TypeExpr->getStmtClass()) {
16447 case Stmt::UnaryOperatorClass: {
16448 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16449 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16450 TypeExpr = UO->getSubExpr();
16451 continue;
16452 }
16453 return false;
16454 }
16455
16456 case Stmt::DeclRefExprClass: {
16457 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16458 *VD = DRE->getDecl();
16459 return true;
16460 }
16461
16462 case Stmt::IntegerLiteralClass: {
16463 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16464 llvm::APInt MagicValueAPInt = IL->getValue();
16465 if (MagicValueAPInt.getActiveBits() <= 64) {
16466 *MagicValue = MagicValueAPInt.getZExtValue();
16467 return true;
16468 } else
16469 return false;
16470 }
16471
16472 case Stmt::BinaryConditionalOperatorClass:
16473 case Stmt::ConditionalOperatorClass: {
16474 const AbstractConditionalOperator *ACO =
16476 bool Result;
16477 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16478 isConstantEvaluated)) {
16479 if (Result)
16480 TypeExpr = ACO->getTrueExpr();
16481 else
16482 TypeExpr = ACO->getFalseExpr();
16483 continue;
16484 }
16485 return false;
16486 }
16487
16488 case Stmt::BinaryOperatorClass: {
16489 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16490 if (BO->getOpcode() == BO_Comma) {
16491 TypeExpr = BO->getRHS();
16492 continue;
16493 }
16494 return false;
16495 }
16496
16497 default:
16498 return false;
16499 }
16500 }
16501}
16502
16503/// Retrieve the C type corresponding to type tag TypeExpr.
16504///
16505/// \param TypeExpr Expression that specifies a type tag.
16506///
16507/// \param MagicValues Registered magic values.
16508///
16509/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16510/// kind.
16511///
16512/// \param TypeInfo Information about the corresponding C type.
16513///
16514/// \param isConstantEvaluated whether the evalaution should be performed in
16515/// constant context.
16516///
16517/// \returns true if the corresponding C type was found.
16519 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16520 const ASTContext &Ctx,
16521 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16522 *MagicValues,
16523 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16524 bool isConstantEvaluated) {
16525 FoundWrongKind = false;
16526
16527 // Variable declaration that has type_tag_for_datatype attribute.
16528 const ValueDecl *VD = nullptr;
16529
16530 uint64_t MagicValue;
16531
16532 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16533 return false;
16534
16535 if (VD) {
16536 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16537 if (I->getArgumentKind() != ArgumentKind) {
16538 FoundWrongKind = true;
16539 return false;
16540 }
16541 TypeInfo.Type = I->getMatchingCType();
16542 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16543 TypeInfo.MustBeNull = I->getMustBeNull();
16544 return true;
16545 }
16546 return false;
16547 }
16548
16549 if (!MagicValues)
16550 return false;
16551
16552 llvm::DenseMap<Sema::TypeTagMagicValue,
16554 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16555 if (I == MagicValues->end())
16556 return false;
16557
16558 TypeInfo = I->second;
16559 return true;
16560}
16561
16563 uint64_t MagicValue, QualType Type,
16564 bool LayoutCompatible,
16565 bool MustBeNull) {
16566 if (!TypeTagForDatatypeMagicValues)
16567 TypeTagForDatatypeMagicValues.reset(
16568 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16569
16570 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16571 (*TypeTagForDatatypeMagicValues)[Magic] =
16572 TypeTagData(Type, LayoutCompatible, MustBeNull);
16573}
16574
16575static bool IsSameCharType(QualType T1, QualType T2) {
16576 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16577 if (!BT1)
16578 return false;
16579
16580 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16581 if (!BT2)
16582 return false;
16583
16584 BuiltinType::Kind T1Kind = BT1->getKind();
16585 BuiltinType::Kind T2Kind = BT2->getKind();
16586
16587 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16588 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16589 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16590 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16591}
16592
16593void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16594 const ArrayRef<const Expr *> ExprArgs,
16595 SourceLocation CallSiteLoc) {
16596 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16597 bool IsPointerAttr = Attr->getIsPointer();
16598
16599 // Retrieve the argument representing the 'type_tag'.
16600 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16601 if (TypeTagIdxAST >= ExprArgs.size()) {
16602 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16603 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16604 return;
16605 }
16606 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16607 bool FoundWrongKind;
16608 TypeTagData TypeInfo;
16609 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16610 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16611 TypeInfo, isConstantEvaluatedContext())) {
16612 if (FoundWrongKind)
16613 Diag(TypeTagExpr->getExprLoc(),
16614 diag::warn_type_tag_for_datatype_wrong_kind)
16615 << TypeTagExpr->getSourceRange();
16616 return;
16617 }
16618
16619 // Retrieve the argument representing the 'arg_idx'.
16620 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16621 if (ArgumentIdxAST >= ExprArgs.size()) {
16622 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16623 << 1 << Attr->getArgumentIdx().getSourceIndex();
16624 return;
16625 }
16626 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16627 if (IsPointerAttr) {
16628 // Skip implicit cast of pointer to `void *' (as a function argument).
16629 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16630 if (ICE->getType()->isVoidPointerType() &&
16631 ICE->getCastKind() == CK_BitCast)
16632 ArgumentExpr = ICE->getSubExpr();
16633 }
16634 QualType ArgumentType = ArgumentExpr->getType();
16635
16636 // Passing a `void*' pointer shouldn't trigger a warning.
16637 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16638 return;
16639
16640 if (TypeInfo.MustBeNull) {
16641 // Type tag with matching void type requires a null pointer.
16642 if (!ArgumentExpr->isNullPointerConstant(Context,
16644 Diag(ArgumentExpr->getExprLoc(),
16645 diag::warn_type_safety_null_pointer_required)
16646 << ArgumentKind->getName()
16647 << ArgumentExpr->getSourceRange()
16648 << TypeTagExpr->getSourceRange();
16649 }
16650 return;
16651 }
16652
16653 QualType RequiredType = TypeInfo.Type;
16654 if (IsPointerAttr)
16655 RequiredType = Context.getPointerType(RequiredType);
16656
16657 bool mismatch = false;
16658 if (!TypeInfo.LayoutCompatible) {
16659 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16660
16661 // C++11 [basic.fundamental] p1:
16662 // Plain char, signed char, and unsigned char are three distinct types.
16663 //
16664 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16665 // char' depending on the current char signedness mode.
16666 if (mismatch)
16667 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16668 RequiredType->getPointeeType())) ||
16669 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16670 mismatch = false;
16671 } else
16672 if (IsPointerAttr)
16673 mismatch = !isLayoutCompatible(Context,
16674 ArgumentType->getPointeeType(),
16675 RequiredType->getPointeeType());
16676 else
16677 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16678
16679 if (mismatch)
16680 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16681 << ArgumentType << ArgumentKind
16682 << TypeInfo.LayoutCompatible << RequiredType
16683 << ArgumentExpr->getSourceRange()
16684 << TypeTagExpr->getSourceRange();
16685}
16686
16687void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16688 CharUnits Alignment) {
16689 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16690 Alignment);
16691}
16692
16694 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16695 const NamedDecl *ND = m.RD;
16696 if (ND->getName().empty()) {
16697 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16698 ND = TD;
16699 }
16700 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16701 << m.MD << ND << m.E->getSourceRange();
16702 }
16704}
16705
16707 E = E->IgnoreParens();
16708 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16709 return;
16710 if (isa<UnaryOperator>(E) &&
16711 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16712 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16713 if (isa<MemberExpr>(Op)) {
16714 auto &MisalignedMembersForExpr =
16716 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16717 if (MA != MisalignedMembersForExpr.end() &&
16718 (T->isDependentType() || T->isIntegerType() ||
16719 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16720 Context.getTypeAlignInChars(
16721 T->getPointeeType()) <= MA->Alignment))))
16722 MisalignedMembersForExpr.erase(MA);
16723 }
16724 }
16725}
16726
16728 Expr *E,
16729 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16730 Action) {
16731 const auto *ME = dyn_cast<MemberExpr>(E);
16732 if (!ME)
16733 return;
16734
16735 // No need to check expressions with an __unaligned-qualified type.
16736 if (E->getType().getQualifiers().hasUnaligned())
16737 return;
16738
16739 // For a chain of MemberExpr like "a.b.c.d" this list
16740 // will keep FieldDecl's like [d, c, b].
16741 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16742 const MemberExpr *TopME = nullptr;
16743 bool AnyIsPacked = false;
16744 do {
16745 QualType BaseType = ME->getBase()->getType();
16746 if (BaseType->isDependentType())
16747 return;
16748 if (ME->isArrow())
16749 BaseType = BaseType->getPointeeType();
16750 auto *RD = BaseType->castAsRecordDecl();
16751 if (RD->isInvalidDecl())
16752 return;
16753
16754 ValueDecl *MD = ME->getMemberDecl();
16755 auto *FD = dyn_cast<FieldDecl>(MD);
16756 // We do not care about non-data members.
16757 if (!FD || FD->isInvalidDecl())
16758 return;
16759
16760 AnyIsPacked =
16761 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16762 ReverseMemberChain.push_back(FD);
16763
16764 TopME = ME;
16765 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16766 } while (ME);
16767 assert(TopME && "We did not compute a topmost MemberExpr!");
16768
16769 // Not the scope of this diagnostic.
16770 if (!AnyIsPacked)
16771 return;
16772
16773 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16774 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16775 // TODO: The innermost base of the member expression may be too complicated.
16776 // For now, just disregard these cases. This is left for future
16777 // improvement.
16778 if (!DRE && !isa<CXXThisExpr>(TopBase))
16779 return;
16780
16781 // Alignment expected by the whole expression.
16782 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16783
16784 // No need to do anything else with this case.
16785 if (ExpectedAlignment.isOne())
16786 return;
16787
16788 // Synthesize offset of the whole access.
16789 CharUnits Offset;
16790 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16791 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16792
16793 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16794 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16795 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16796
16797 // The base expression of the innermost MemberExpr may give
16798 // stronger guarantees than the class containing the member.
16799 if (DRE && !TopME->isArrow()) {
16800 const ValueDecl *VD = DRE->getDecl();
16801 if (!VD->getType()->isReferenceType())
16802 CompleteObjectAlignment =
16803 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16804 }
16805
16806 // Check if the synthesized offset fulfills the alignment.
16807 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16808 // It may fulfill the offset it but the effective alignment may still be
16809 // lower than the expected expression alignment.
16810 CompleteObjectAlignment < ExpectedAlignment) {
16811 // If this happens, we want to determine a sensible culprit of this.
16812 // Intuitively, watching the chain of member expressions from right to
16813 // left, we start with the required alignment (as required by the field
16814 // type) but some packed attribute in that chain has reduced the alignment.
16815 // It may happen that another packed structure increases it again. But if
16816 // we are here such increase has not been enough. So pointing the first
16817 // FieldDecl that either is packed or else its RecordDecl is,
16818 // seems reasonable.
16819 FieldDecl *FD = nullptr;
16820 CharUnits Alignment;
16821 for (FieldDecl *FDI : ReverseMemberChain) {
16822 if (FDI->hasAttr<PackedAttr>() ||
16823 FDI->getParent()->hasAttr<PackedAttr>()) {
16824 FD = FDI;
16825 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16826 Context.getTypeAlignInChars(
16827 Context.getCanonicalTagType(FD->getParent())));
16828 break;
16829 }
16830 }
16831 assert(FD && "We did not find a packed FieldDecl!");
16832 Action(E, FD->getParent(), FD, Alignment);
16833 }
16834}
16835
16836void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16837 using namespace std::placeholders;
16838
16840 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16841 _2, _3, _4));
16842}
16843
16845 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16846 if (checkArgCount(TheCall, 1))
16847 return true;
16848
16849 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16850 if (A.isInvalid())
16851 return true;
16852
16853 TheCall->setArg(0, A.get());
16854 QualType TyA = A.get()->getType();
16855
16856 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16857 ArgTyRestr, 1))
16858 return true;
16859
16860 TheCall->setType(TyA);
16861 return false;
16862}
16863
16864bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16865 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16866 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16867 TheCall->setType(*Res);
16868 return false;
16869 }
16870 return true;
16871}
16872
16874 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16875 if (!Res)
16876 return true;
16877
16878 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16879 TheCall->setType(VecTy0->getElementType());
16880 else
16881 TheCall->setType(*Res);
16882
16883 return false;
16884}
16885
16887 SourceLocation Loc) {
16889 R = RHS->getEnumCoercedType(S.Context);
16890 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16892 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16893 << LHS->getSourceRange() << RHS->getSourceRange()
16894 << /*Arithmetic Between*/ 0 << L << R;
16895 }
16896 return false;
16897}
16898
16899/// Check if all arguments have the same type. If the types don't match, emit an
16900/// error message and return true. Otherwise return false.
16901///
16902/// For scalars we directly compare their unqualified types. But even if we
16903/// compare unqualified vector types, a difference in qualifiers in the element
16904/// types can make the vector types be considered not equal. For example,
16905/// vector of 4 'const float' values vs vector of 4 'float' values.
16906/// So we compare unqualified types of their elements and number of elements.
16908 ArrayRef<Expr *> Args) {
16909 assert(!Args.empty() && "Should have at least one argument.");
16910
16911 Expr *Arg0 = Args.front();
16912 QualType Ty0 = Arg0->getType();
16913
16914 auto EmitError = [&](Expr *ArgI) {
16915 SemaRef.Diag(Arg0->getBeginLoc(),
16916 diag::err_typecheck_call_different_arg_types)
16917 << Arg0->getType() << ArgI->getType();
16918 };
16919
16920 // Compare scalar types.
16921 if (!Ty0->isVectorType()) {
16922 for (Expr *ArgI : Args.drop_front())
16923 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16924 EmitError(ArgI);
16925 return true;
16926 }
16927
16928 return false;
16929 }
16930
16931 // Compare vector types.
16932 const auto *Vec0 = Ty0->castAs<VectorType>();
16933 for (Expr *ArgI : Args.drop_front()) {
16934 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16935 if (!VecI ||
16936 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16937 VecI->getElementType()) ||
16938 Vec0->getNumElements() != VecI->getNumElements()) {
16939 EmitError(ArgI);
16940 return true;
16941 }
16942 }
16943
16944 return false;
16945}
16946
16947std::optional<QualType>
16949 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16950 if (checkArgCount(TheCall, 2))
16951 return std::nullopt;
16952
16954 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16955 return std::nullopt;
16956
16957 Expr *Args[2];
16958 for (int I = 0; I < 2; ++I) {
16959 ExprResult Converted =
16960 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16961 if (Converted.isInvalid())
16962 return std::nullopt;
16963 Args[I] = Converted.get();
16964 }
16965
16966 SourceLocation LocA = Args[0]->getBeginLoc();
16967 QualType TyA = Args[0]->getType();
16968
16969 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16970 return std::nullopt;
16971
16972 if (checkBuiltinVectorMathArgTypes(*this, Args))
16973 return std::nullopt;
16974
16975 TheCall->setArg(0, Args[0]);
16976 TheCall->setArg(1, Args[1]);
16977 return TyA;
16978}
16979
16981 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16982 if (checkArgCount(TheCall, 3))
16983 return true;
16984
16985 SourceLocation Loc = TheCall->getExprLoc();
16986 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16987 TheCall->getArg(1), Loc) ||
16988 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16989 TheCall->getArg(2), Loc))
16990 return true;
16991
16992 Expr *Args[3];
16993 for (int I = 0; I < 3; ++I) {
16994 ExprResult Converted =
16995 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16996 if (Converted.isInvalid())
16997 return true;
16998 Args[I] = Converted.get();
16999 }
17000
17001 int ArgOrdinal = 1;
17002 for (Expr *Arg : Args) {
17003 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17004 ArgTyRestr, ArgOrdinal++))
17005 return true;
17006 }
17007
17008 if (checkBuiltinVectorMathArgTypes(*this, Args))
17009 return true;
17010
17011 for (int I = 0; I < 3; ++I)
17012 TheCall->setArg(I, Args[I]);
17013
17014 TheCall->setType(Args[0]->getType());
17015 return false;
17016}
17017
17018bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17019 if (checkArgCount(TheCall, 1))
17020 return true;
17021
17022 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17023 if (A.isInvalid())
17024 return true;
17025
17026 TheCall->setArg(0, A.get());
17027 return false;
17028}
17029
17030bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17031 if (checkArgCount(TheCall, 1))
17032 return true;
17033
17034 ExprResult Arg = TheCall->getArg(0);
17035 QualType TyArg = Arg.get()->getType();
17036
17037 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17038 return Diag(TheCall->getArg(0)->getBeginLoc(),
17039 diag::err_builtin_invalid_arg_type)
17040 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17041
17042 TheCall->setType(TyArg);
17043 return false;
17044}
17045
17046ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17047 ExprResult CallResult) {
17048 if (checkArgCount(TheCall, 1))
17049 return ExprError();
17050
17051 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17052 if (MatrixArg.isInvalid())
17053 return MatrixArg;
17054 Expr *Matrix = MatrixArg.get();
17055
17056 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17057 if (!MType) {
17058 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17059 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17060 << Matrix->getType();
17061 return ExprError();
17062 }
17063
17064 // Create returned matrix type by swapping rows and columns of the argument
17065 // matrix type.
17066 QualType ResultType = Context.getConstantMatrixType(
17067 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17068
17069 // Change the return type to the type of the returned matrix.
17070 TheCall->setType(ResultType);
17071
17072 // Update call argument to use the possibly converted matrix argument.
17073 TheCall->setArg(0, Matrix);
17074 return CallResult;
17075}
17076
17077// Get and verify the matrix dimensions.
17078static std::optional<unsigned>
17080 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17081 if (!Value) {
17082 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17083 << Name;
17084 return {};
17085 }
17086 uint64_t Dim = Value->getZExtValue();
17087 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17088 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17089 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17090 return {};
17091 }
17092 return Dim;
17093}
17094
17095ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17096 ExprResult CallResult) {
17097 if (!getLangOpts().MatrixTypes) {
17098 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17099 return ExprError();
17100 }
17101
17102 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17104 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17105 << /*column*/ 1 << /*load*/ 0;
17106 return ExprError();
17107 }
17108
17109 if (checkArgCount(TheCall, 4))
17110 return ExprError();
17111
17112 unsigned PtrArgIdx = 0;
17113 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17114 Expr *RowsExpr = TheCall->getArg(1);
17115 Expr *ColumnsExpr = TheCall->getArg(2);
17116 Expr *StrideExpr = TheCall->getArg(3);
17117
17118 bool ArgError = false;
17119
17120 // Check pointer argument.
17121 {
17123 if (PtrConv.isInvalid())
17124 return PtrConv;
17125 PtrExpr = PtrConv.get();
17126 TheCall->setArg(0, PtrExpr);
17127 if (PtrExpr->isTypeDependent()) {
17128 TheCall->setType(Context.DependentTy);
17129 return TheCall;
17130 }
17131 }
17132
17133 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17134 QualType ElementTy;
17135 if (!PtrTy) {
17136 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17137 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17138 << PtrExpr->getType();
17139 ArgError = true;
17140 } else {
17141 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17142
17144 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17145 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17146 << /* no fp */ 0 << PtrExpr->getType();
17147 ArgError = true;
17148 }
17149 }
17150
17151 // Apply default Lvalue conversions and convert the expression to size_t.
17152 auto ApplyArgumentConversions = [this](Expr *E) {
17154 if (Conv.isInvalid())
17155 return Conv;
17156
17157 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17158 };
17159
17160 // Apply conversion to row and column expressions.
17161 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17162 if (!RowsConv.isInvalid()) {
17163 RowsExpr = RowsConv.get();
17164 TheCall->setArg(1, RowsExpr);
17165 } else
17166 RowsExpr = nullptr;
17167
17168 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17169 if (!ColumnsConv.isInvalid()) {
17170 ColumnsExpr = ColumnsConv.get();
17171 TheCall->setArg(2, ColumnsExpr);
17172 } else
17173 ColumnsExpr = nullptr;
17174
17175 // If any part of the result matrix type is still pending, just use
17176 // Context.DependentTy, until all parts are resolved.
17177 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17178 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17179 TheCall->setType(Context.DependentTy);
17180 return CallResult;
17181 }
17182
17183 // Check row and column dimensions.
17184 std::optional<unsigned> MaybeRows;
17185 if (RowsExpr)
17186 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17187
17188 std::optional<unsigned> MaybeColumns;
17189 if (ColumnsExpr)
17190 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17191
17192 // Check stride argument.
17193 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17194 if (StrideConv.isInvalid())
17195 return ExprError();
17196 StrideExpr = StrideConv.get();
17197 TheCall->setArg(3, StrideExpr);
17198
17199 if (MaybeRows) {
17200 if (std::optional<llvm::APSInt> Value =
17201 StrideExpr->getIntegerConstantExpr(Context)) {
17202 uint64_t Stride = Value->getZExtValue();
17203 if (Stride < *MaybeRows) {
17204 Diag(StrideExpr->getBeginLoc(),
17205 diag::err_builtin_matrix_stride_too_small);
17206 ArgError = true;
17207 }
17208 }
17209 }
17210
17211 if (ArgError || !MaybeRows || !MaybeColumns)
17212 return ExprError();
17213
17214 TheCall->setType(
17215 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17216 return CallResult;
17217}
17218
17219ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17220 ExprResult CallResult) {
17221 if (!getLangOpts().MatrixTypes) {
17222 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17223 return ExprError();
17224 }
17225
17226 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17228 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17229 << /*column*/ 1 << /*store*/ 1;
17230 return ExprError();
17231 }
17232
17233 if (checkArgCount(TheCall, 3))
17234 return ExprError();
17235
17236 unsigned PtrArgIdx = 1;
17237 Expr *MatrixExpr = TheCall->getArg(0);
17238 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17239 Expr *StrideExpr = TheCall->getArg(2);
17240
17241 bool ArgError = false;
17242
17243 {
17244 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17245 if (MatrixConv.isInvalid())
17246 return MatrixConv;
17247 MatrixExpr = MatrixConv.get();
17248 TheCall->setArg(0, MatrixExpr);
17249 }
17250 if (MatrixExpr->isTypeDependent()) {
17251 TheCall->setType(Context.DependentTy);
17252 return TheCall;
17253 }
17254
17255 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17256 if (!MatrixTy) {
17257 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17258 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17259 ArgError = true;
17260 }
17261
17262 {
17264 if (PtrConv.isInvalid())
17265 return PtrConv;
17266 PtrExpr = PtrConv.get();
17267 TheCall->setArg(1, PtrExpr);
17268 if (PtrExpr->isTypeDependent()) {
17269 TheCall->setType(Context.DependentTy);
17270 return TheCall;
17271 }
17272 }
17273
17274 // Check pointer argument.
17275 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17276 if (!PtrTy) {
17277 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17278 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17279 << PtrExpr->getType();
17280 ArgError = true;
17281 } else {
17282 QualType ElementTy = PtrTy->getPointeeType();
17283 if (ElementTy.isConstQualified()) {
17284 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17285 ArgError = true;
17286 }
17287 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17288 if (MatrixTy &&
17289 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17290 Diag(PtrExpr->getBeginLoc(),
17291 diag::err_builtin_matrix_pointer_arg_mismatch)
17292 << ElementTy << MatrixTy->getElementType();
17293 ArgError = true;
17294 }
17295 }
17296
17297 // Apply default Lvalue conversions and convert the stride expression to
17298 // size_t.
17299 {
17300 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17301 if (StrideConv.isInvalid())
17302 return StrideConv;
17303
17304 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17305 if (StrideConv.isInvalid())
17306 return StrideConv;
17307 StrideExpr = StrideConv.get();
17308 TheCall->setArg(2, StrideExpr);
17309 }
17310
17311 // Check stride argument.
17312 if (MatrixTy) {
17313 if (std::optional<llvm::APSInt> Value =
17314 StrideExpr->getIntegerConstantExpr(Context)) {
17315 uint64_t Stride = Value->getZExtValue();
17316 if (Stride < MatrixTy->getNumRows()) {
17317 Diag(StrideExpr->getBeginLoc(),
17318 diag::err_builtin_matrix_stride_too_small);
17319 ArgError = true;
17320 }
17321 }
17322 }
17323
17324 if (ArgError)
17325 return ExprError();
17326
17327 return CallResult;
17328}
17329
17331 const NamedDecl *Callee) {
17332 // This warning does not make sense in code that has no runtime behavior.
17334 return;
17335
17336 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17337
17338 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17339 return;
17340
17341 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17342 // all TCBs the callee is a part of.
17343 llvm::StringSet<> CalleeTCBs;
17344 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17345 CalleeTCBs.insert(A->getTCBName());
17346 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17347 CalleeTCBs.insert(A->getTCBName());
17348
17349 // Go through the TCBs the caller is a part of and emit warnings if Caller
17350 // is in a TCB that the Callee is not.
17351 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17352 StringRef CallerTCB = A->getTCBName();
17353 if (CalleeTCBs.count(CallerTCB) == 0) {
17354 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17355 << Callee << CallerTCB;
17356 }
17357 }
17358}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
llvm::json::Object Object
llvm::json::Array Array
static std::string 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 bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
__device__ __2f16 float __ockl_bool s
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * toString() const
const char * getStart() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:508
bool isVector() const
Definition APValue.h:491
APSInt & getComplexIntImag()
Definition APValue.h:546
bool isComplexInt() const
Definition APValue.h:488
bool isFloat() const
Definition APValue.h:486
bool isComplexFloat() const
Definition APValue.h:489
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
bool isInt() const
Definition APValue.h:485
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:606
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
bool isMatrix() const
Definition APValue.h:492
unsigned getMatrixNumElements() const
Definition APValue.h:603
bool isAddrLabelDiff() const
Definition APValue.h:497
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:229
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:807
Builtin::Context & BuiltinInfo
Definition ASTContext.h:809
const LangOptions & getLangOpts() const
Definition ASTContext.h:961
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:860
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:926
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:4356
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4534
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4540
SourceLocation getQuestionLoc() const
Definition Expr.h:4383
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4546
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:7297
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7301
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2724
SourceLocation getRBracketLoc() const
Definition Expr.h:2772
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2753
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3784
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3798
QualType getElementType() const
Definition TypeBase.h:3796
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6928
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7077
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7059
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:4041
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4174
Expr * getLHS() const
Definition Expr.h:4091
SourceLocation getOperatorLoc() const
Definition Expr.h:4083
SourceLocation getExprLoc() const
Definition Expr.h:4082
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2138
Expr * getRHS() const
Definition Expr.h:4093
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4127
Opcode getOpcode() const
Definition Expr.h:4086
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
BinaryOperatorKind Opcode
Definition Expr.h:4046
Pointer to a block type.
Definition TypeBase.h:3604
This class is used for builtin types like 'int'.
Definition TypeBase.h:3226
bool isInteger() const
Definition TypeBase.h:3287
bool isFloatingPoint() const
Definition TypeBase.h:3299
bool isSignedInteger() const
Definition TypeBase.h:3291
bool isUnsignedInteger() const
Definition TypeBase.h:3295
Kind getKind() const
Definition TypeBase.h:3274
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:383
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:3972
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:2952
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
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:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3163
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1597
arg_iterator arg_begin()
Definition Expr.h:3203
arg_iterator arg_end()
Definition Expr.h:3206
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
bool isCallToStdMove() const
Definition Expr.cpp:3649
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3239
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
arg_range arguments()
Definition Expr.h:3198
SourceLocation getEndLoc() const
Definition Expr.h:3299
SourceLocation getRParenLoc() const
Definition Expr.h:3277
Decl * getCalleeDecl()
Definition Expr.h:3123
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:1602
void setCallee(Expr *F)
Definition Expr.h:3095
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3182
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:3679
path_iterator path_begin()
Definition Expr.h:3749
CastKind getCastKind() const
Definition Expr.h:3723
path_iterator path_end()
Definition Expr.h:3750
Expr * getSubExpr()
Definition Expr.h:3729
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:4394
Expr * getLHS() const
Definition Expr.h:4428
Expr * getRHS() const
Definition Expr.h:4429
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3822
QualType desugar() const
Definition TypeBase.h:3923
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3878
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:355
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4449
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4471
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:5681
Expr * getOperand() const
Definition ExprCXX.h:5320
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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:493
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1366
ValueDecl * getDecl()
Definition Expr.h:1341
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1471
SourceLocation getBeginLoc() const
Definition Expr.h:1352
SourceLocation getLocation() const
Definition Expr.h:1349
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:450
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:561
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:991
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:2003
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3445
Represents an enum.
Definition Decl.h:4033
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4265
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4206
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3124
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:677
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:674
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3102
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3097
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3093
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:211
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4236
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3089
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:3695
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:805
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:814
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:817
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:807
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:4075
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:271
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:282
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:231
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:137
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4329
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4746
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3298
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
llvm::APFloat getValue() const
Definition Expr.h:1669
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2898
Represents a function declaration or definition.
Definition Decl.h:2018
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4547
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3736
param_iterator param_end()
Definition Decl.h:2805
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3839
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
param_iterator param_begin()
Definition Decl.h:2804
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3107
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4303
bool isStatic() const
Definition Decl.h:2947
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4118
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4104
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3800
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
unsigned getNumParams() const
Definition TypeBase.h:5647
QualType getParamType(unsigned i) const
Definition TypeBase.h:5649
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5773
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5658
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5768
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5654
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4874
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4870
QualType getReturnType() const
Definition TypeBase.h:4905
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:3856
Describes an C or C++ initializer list.
Definition Expr.h:5302
ArrayRef< Expr * > inits() const
Definition Expr.h:5355
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:980
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:1074
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1110
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:508
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1157
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:881
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:4399
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4420
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
bool isArrow() const
Definition Expr.h:3551
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3715
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
Represent a C++ namespace.
Definition Decl.h:592
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1713
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1727
SourceLocation getSemiLoc() const
Definition Stmt.h:1724
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:648
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:737
bool isImplicitProperty() const
Definition ExprObjC.h:734
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:84
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
Represents a parameter to a function.
Definition Decl.h:1808
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
QualType getPointeeType() const
Definition TypeBase.h:3400
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6804
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5196
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8529
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2962
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1229
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8445
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8485
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
void removeLocalVolatile()
Definition TypeBase.h:8561
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
void removeLocalConst()
Definition TypeBase.h:8553
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8518
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8566
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8491
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1457
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4347
bool hasFlexibleArrayMember() const
Definition Decl.h:4380
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4433
field_range fields() const
Definition Decl.h:4550
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4425
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:598
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1034
@ ArmStreaming
Intrinsic is only available in normal mode.
Definition SemaARM.h:37
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
Definition SemaARM.h:38
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1117
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:113
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:32
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp:30
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:535
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10409
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10414
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
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:13149
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
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:2755
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9465
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
bool FormatStringHasSArg(const StringLiteral *FExpr)
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7012
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:2077
SemaHexagon & Hexagon()
Definition Sema.h:1488
SemaSYCL & SYCL()
Definition Sema.h:1558
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:1725
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:838
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1578
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:1308
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:226
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
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:1518
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1373
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:759
ASTContext & getASTContext() const
Definition Sema.h:939
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:762
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2637
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:1212
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:2744
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:932
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:1463
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:1478
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:1306
static const uint64_t MaximumAlignment
Definition Sema.h:1235
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:957
SemaHLSL & HLSL()
Definition Sema.h:1483
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1503
SemaRISCV & RISCV()
Definition Sema.h:1548
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2810
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7048
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1737
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:1341
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:2717
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15532
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:2410
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:644
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:1446
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:1528
FormatArgumentPassingKind
Definition Sema.h:2647
@ FAPK_Elsewhere
Definition Sema.h:2651
@ FAPK_Fixed
Definition Sema.h:2648
@ FAPK_Variadic
Definition Sema.h:2649
@ FAPK_VAList
Definition Sema.h:2650
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14055
SourceManager & getSourceManager() const
Definition Sema.h:937
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:2639
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:1538
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:1267
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:1568
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:1311
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:788
DiagnosticsEngine & Diags
Definition Sema.h:1310
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:1513
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:631
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:6312
SemaSPIRV & SPIRV()
Definition Sema.h:1553
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:1493
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6500
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:1573
SemaARM & ARM()
Definition Sema.h:1453
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:4646
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp: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:1503
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:1802
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1976
bool isUTF8() const
Definition Expr.h:1921
bool isWide() const
Definition Expr.h:1920
bool isPascal() const
Definition Expr.h:1925
unsigned getLength() const
Definition Expr.h:1912
StringLiteralKind getKind() const
Definition Expr.h:1915
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition Expr.cpp:1331
bool isUTF32() const
Definition Expr.h:1923
unsigned getByteLength() const
Definition Expr.h:1911
StringRef getString() const
Definition Expr.h:1870
bool isUTF16() const
Definition Expr.h:1922
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:1977
bool isOrdinary() const
Definition Expr.h:1919
unsigned getCharByteWidth() const
Definition Expr.h:1913
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3860
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
bool isUnion() const
Definition Decl.h:3950
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
Definition TargetInfo.h:389
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:2735
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:6280
A container of type source information.
Definition TypeBase.h:8416
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:8427
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isBlockPointerType() const
Definition TypeBase.h:8702
bool isVoidType() const
Definition TypeBase.h:9048
bool isBooleanType() const
Definition TypeBase.h:9185
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9235
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2355
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
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:9215
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2119
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2517
bool isArrayType() const
Definition TypeBase.h:8781
bool isCharType() const
Definition Type.cpp:2193
bool isFunctionPointerType() const
Definition TypeBase.h:8749
bool isPointerType() const
Definition TypeBase.h:8682
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9092
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
bool isReferenceType() const
Definition TypeBase.h:8706
bool isEnumeralType() const
Definition TypeBase.h:8813
bool isScalarType() const
Definition TypeBase.h:9154
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1958
bool isVariableArrayType() const
Definition TypeBase.h:8793
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorType() const
Definition TypeBase.h:8825
bool isExtVectorBoolType() const
Definition TypeBase.h:8829
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2740
bool isBitIntType() const
Definition TypeBase.h:8957
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9017
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8805
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2844
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2310
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3181
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9228
bool isMemberPointerType() const
Definition TypeBase.h:8763
bool isAtomicType() const
Definition TypeBase.h:8874
bool isFunctionProtoType() const
Definition TypeBase.h:2661
bool isMatrixType() const
Definition TypeBase.h:8845
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3197
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:2862
bool isUnscopedEnumerationType() const
Definition Type.cpp:2186
bool isObjCObjectType() const
Definition TypeBase.h:8865
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9328
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9191
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
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:2527
bool isFunctionType() const
Definition TypeBase.h:8678
bool isObjCObjectPointerType() const
Definition TypeBase.h:8861
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2397
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isVectorType() const
Definition TypeBase.h:8821
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isFloatingType() const
Definition Type.cpp:2389
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:2332
bool isAnyPointerType() const
Definition TypeBase.h:8690
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2471
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
bool isNullPtrType() const
Definition TypeBase.h:9085
bool isRecordType() const
Definition TypeBase.h:8809
bool isObjCRetainableType() const
Definition Type.cpp:5417
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2663
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5148
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2728
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3584
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2628
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2365
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1035
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1123
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5575
Represents a variable declaration or definition.
Definition Decl.h:924
Represents a GCC generic vector type.
Definition TypeBase.h:4237
unsigned getNumElements() const
Definition TypeBase.h:4252
QualType getElementType() const
Definition TypeBase.h:4251
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:237
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1491
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1476
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1469
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1483
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2734
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1437
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1498
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:513
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Comparison
A comparison.
Definition Sema.h:667
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:24
@ Success
Annotation was successful.
Definition Parser.h:65
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
PointerAuthDiscArgKind
Definition Sema.h:594
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:258
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
Definition SemaARM.cpp:552
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:112
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:499
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:126
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:64
StringLiteralKind
Definition Expr.h:1766
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:4198
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5989
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5982
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
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:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
Extra information about a function prototype.
Definition TypeBase.h:5454
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:13328
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13354
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13344
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13295
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6906
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2659
#define log2(__x)
Definition tgmath.h:970