clang 23.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
80#include "clang/Sema/SemaWasm.h"
81#include "clang/Sema/SemaX86.h"
82#include "llvm/ADT/APFloat.h"
83#include "llvm/ADT/APInt.h"
84#include "llvm/ADT/APSInt.h"
85#include "llvm/ADT/ArrayRef.h"
86#include "llvm/ADT/DenseMap.h"
87#include "llvm/ADT/FoldingSet.h"
88#include "llvm/ADT/STLExtras.h"
89#include "llvm/ADT/STLForwardCompat.h"
90#include "llvm/ADT/SmallBitVector.h"
91#include "llvm/ADT/SmallPtrSet.h"
92#include "llvm/ADT/SmallString.h"
93#include "llvm/ADT/SmallVector.h"
94#include "llvm/ADT/StringExtras.h"
95#include "llvm/ADT/StringRef.h"
96#include "llvm/ADT/StringSet.h"
97#include "llvm/ADT/StringSwitch.h"
98#include "llvm/Support/AtomicOrdering.h"
99#include "llvm/Support/Compiler.h"
100#include "llvm/Support/ConvertUTF.h"
101#include "llvm/Support/ErrorHandling.h"
102#include "llvm/Support/Format.h"
103#include "llvm/Support/Locale.h"
104#include "llvm/Support/MathExtras.h"
105#include "llvm/Support/SaveAndRestore.h"
106#include "llvm/Support/raw_ostream.h"
107#include "llvm/TargetParser/RISCVTargetParser.h"
108#include "llvm/TargetParser/Triple.h"
109#include <algorithm>
110#include <cassert>
111#include <cctype>
112#include <cstddef>
113#include <cstdint>
114#include <functional>
115#include <limits>
116#include <optional>
117#include <string>
118#include <tuple>
119#include <utility>
120
121using namespace clang;
122using namespace sema;
123
125 unsigned ByteNo) const {
126 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
127 Context.getTargetInfo());
128}
129
130static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
132 return (A << 8) | B;
133}
134
135bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
136 unsigned ArgCount = Call->getNumArgs();
137 if (ArgCount >= MinArgCount)
138 return false;
139
140 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
141 << 0 /*function call*/ << MinArgCount << ArgCount
142 << /*is non object*/ 0 << Call->getSourceRange();
143}
144
145bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
146 unsigned ArgCount = Call->getNumArgs();
147 if (ArgCount <= MaxArgCount)
148 return false;
149 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
150 << 0 /*function call*/ << MaxArgCount << ArgCount
151 << /*is non object*/ 0 << Call->getSourceRange();
152}
153
154bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
155 unsigned MaxArgCount) {
156 return checkArgCountAtLeast(Call, MinArgCount) ||
157 checkArgCountAtMost(Call, MaxArgCount);
158}
159
160bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
161 unsigned ArgCount = Call->getNumArgs();
162 if (ArgCount == DesiredArgCount)
163 return false;
164
165 if (checkArgCountAtLeast(Call, DesiredArgCount))
166 return true;
167 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
168
169 // Highlight all the excess arguments.
170 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
171 Call->getArg(ArgCount - 1)->getEndLoc());
172
173 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
174 << 0 /*function call*/ << DesiredArgCount << ArgCount
175 << /*is non object*/ 0 << Range;
176}
177
179 bool HasError = false;
180
181 for (const Expr *Arg : Call->arguments()) {
182 if (Arg->isValueDependent())
183 continue;
184
185 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
186 int DiagMsgKind = -1;
187 // Arguments must be pointers to constant strings and cannot use '$'.
188 if (!ArgString.has_value())
189 DiagMsgKind = 0;
190 else if (ArgString->find('$') != std::string::npos)
191 DiagMsgKind = 1;
192
193 if (DiagMsgKind >= 0) {
194 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
195 << DiagMsgKind << Arg->getSourceRange();
196 HasError = true;
197 }
198 }
199
200 return !HasError;
201}
202
204 if (Value->isTypeDependent())
205 return false;
206
207 InitializedEntity Entity =
209 ExprResult Result =
211 if (Result.isInvalid())
212 return true;
213 Value = Result.get();
214 return false;
215}
216
217/// Check that the first argument to __builtin_annotation is an integer
218/// and the second argument is a non-wide string literal.
219static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
220 if (S.checkArgCount(TheCall, 2))
221 return true;
222
223 // First argument should be an integer.
224 Expr *ValArg = TheCall->getArg(0);
225 QualType Ty = ValArg->getType();
226 if (!Ty->isIntegerType()) {
227 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
228 << ValArg->getSourceRange();
229 return true;
230 }
231
232 // Second argument should be a constant string.
233 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
234 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
235 if (!Literal || !Literal->isOrdinary()) {
236 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
237 << StrArg->getSourceRange();
238 return true;
239 }
240
241 TheCall->setType(Ty);
242 return false;
243}
244
245static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
246 // We need at least one argument.
247 if (TheCall->getNumArgs() < 1) {
248 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
249 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
250 << TheCall->getCallee()->getSourceRange();
251 return true;
252 }
253
254 // All arguments should be wide string literals.
255 for (Expr *Arg : TheCall->arguments()) {
256 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
257 if (!Literal || !Literal->isWide()) {
258 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
259 << Arg->getSourceRange();
260 return true;
261 }
262 }
263
264 return false;
265}
266
267/// Check that the argument to __builtin_addressof is a glvalue, and set the
268/// result type to the corresponding pointer type.
269static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
270 if (S.checkArgCount(TheCall, 1))
271 return true;
272
273 ExprResult Arg(TheCall->getArg(0));
274 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
275 if (ResultType.isNull())
276 return true;
277
278 TheCall->setArg(0, Arg.get());
279 TheCall->setType(ResultType);
280 return false;
281}
282
283/// Check that the argument to __builtin_function_start is a function.
284static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
285 if (S.checkArgCount(TheCall, 1))
286 return true;
287
288 if (TheCall->getArg(0)->containsErrors())
289 return true;
290
292 if (Arg.isInvalid())
293 return true;
294
295 TheCall->setArg(0, Arg.get());
296 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
298
299 if (!FD) {
300 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
301 << TheCall->getSourceRange();
302 return true;
303 }
304
305 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
306 TheCall->getBeginLoc());
307}
308
309/// Check the number of arguments and set the result type to
310/// the argument type.
311static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
312 if (S.checkArgCount(TheCall, 1))
313 return true;
314
315 TheCall->setType(TheCall->getArg(0)->getType());
316 return false;
317}
318
319/// Check that the value argument for __builtin_is_aligned(value, alignment) and
320/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
321/// type (but not a function pointer) and that the alignment is a power-of-two.
322static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
323 if (S.checkArgCount(TheCall, 2))
324 return true;
325
326 clang::Expr *Source = TheCall->getArg(0);
327 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
328
329 auto IsValidIntegerType = [](QualType Ty) {
330 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
331 };
332 QualType SrcTy = Source->getType();
333 // We should also be able to use it with arrays (but not functions!).
334 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
335 SrcTy = S.Context.getDecayedType(SrcTy);
336 }
337 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
338 SrcTy->isFunctionPointerType()) {
339 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
340 << SrcTy;
341 if (SrcTy->isFloatingType())
342 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
343 else if (SrcTy->isMemberPointerType())
344 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
345 else if (SrcTy->isFunctionPointerType())
346 S.Diag(Source->getExprLoc(),
347 diag::note_alignment_invalid_function_pointer);
348 return true;
349 }
350
351 clang::Expr *AlignOp = TheCall->getArg(1);
352 if (!IsValidIntegerType(AlignOp->getType())) {
353 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
354 << AlignOp->getType();
355 return true;
356 }
357 Expr::EvalResult AlignResult;
358 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
359 // We can't check validity of alignment if it is value dependent.
360 if (!AlignOp->isValueDependent() &&
361 AlignOp->EvaluateAsInt(AlignResult, S.Context,
363 llvm::APSInt AlignValue = AlignResult.Val.getInt();
364 llvm::APSInt MaxValue(
365 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
366 if (AlignValue < 1) {
367 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
368 return true;
369 }
370 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
371 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
372 << toString(MaxValue, 10);
373 return true;
374 }
375 if (!AlignValue.isPowerOf2()) {
376 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
377 return true;
378 }
379 if (AlignValue == 1) {
380 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
381 << IsBooleanAlignBuiltin;
382 }
383 }
384
387 SourceLocation(), Source);
388 if (SrcArg.isInvalid())
389 return true;
390 TheCall->setArg(0, SrcArg.get());
391 ExprResult AlignArg =
393 S.Context, AlignOp->getType(), false),
394 SourceLocation(), AlignOp);
395 if (AlignArg.isInvalid())
396 return true;
397 TheCall->setArg(1, AlignArg.get());
398 // For align_up/align_down, the return type is the same as the (potentially
399 // decayed) argument type including qualifiers. For is_aligned(), the result
400 // is always bool.
401 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
402 return false;
403}
404
405static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
406 if (S.checkArgCount(TheCall, 3))
407 return true;
408
409 std::pair<unsigned, const char *> Builtins[] = {
410 { Builtin::BI__builtin_add_overflow, "ckd_add" },
411 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
412 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
413 };
414
415 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
416 const char *> &P) {
417 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
419 S.getSourceManager(), S.getLangOpts()) == P.second;
420 });
421
422 auto ValidCkdIntType = [](QualType QT) {
423 // A valid checked integer type is an integer type other than a plain char,
424 // bool, a bit-precise type, or an enumeration type.
425 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
426 return (BT->getKind() >= BuiltinType::Short &&
427 BT->getKind() <= BuiltinType::Int128) || (
428 BT->getKind() >= BuiltinType::UShort &&
429 BT->getKind() <= BuiltinType::UInt128) ||
430 BT->getKind() == BuiltinType::UChar ||
431 BT->getKind() == BuiltinType::SChar;
432 return false;
433 };
434
435 // First two arguments should be integers.
436 for (unsigned I = 0; I < 2; ++I) {
438 if (Arg.isInvalid()) return true;
439 TheCall->setArg(I, Arg.get());
440
441 QualType Ty = Arg.get()->getType();
442 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
443 if (!IsValid) {
444 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
445 << CkdOperation << Ty << Arg.get()->getSourceRange();
446 return true;
447 }
448 }
449
450 // Third argument should be a pointer to a non-const integer.
451 // IRGen correctly handles volatile, restrict, and address spaces, and
452 // the other qualifiers aren't possible.
453 {
455 if (Arg.isInvalid()) return true;
456 TheCall->setArg(2, Arg.get());
457
458 QualType Ty = Arg.get()->getType();
459 const auto *PtrTy = Ty->getAs<PointerType>();
460 if (!PtrTy ||
461 !PtrTy->getPointeeType()->isIntegerType() ||
462 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
463 PtrTy->getPointeeType().isConstQualified()) {
464 S.Diag(Arg.get()->getBeginLoc(),
465 diag::err_overflow_builtin_must_be_ptr_int)
466 << CkdOperation << Ty << Arg.get()->getSourceRange();
467 return true;
468 }
469 }
470
471 // Disallow signed bit-precise integer args larger than 128 bits to mul
472 // function until we improve backend support.
473 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
474 for (unsigned I = 0; I < 3; ++I) {
475 const auto Arg = TheCall->getArg(I);
476 // Third argument will be a pointer.
477 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
478 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
479 S.getASTContext().getIntWidth(Ty) > 128)
480 return S.Diag(Arg->getBeginLoc(),
481 diag::err_overflow_builtin_bit_int_max_size)
482 << 128;
483 }
484 }
485
486 return false;
487}
488
489namespace {
490struct BuiltinDumpStructGenerator {
491 Sema &S;
492 CallExpr *TheCall;
493 SourceLocation Loc = TheCall->getBeginLoc();
494 SmallVector<Expr *, 32> Actions;
495 DiagnosticErrorTrap ErrorTracker;
496 PrintingPolicy Policy;
497
498 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
499 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
500 Policy(S.Context.getPrintingPolicy()) {
501 Policy.AnonymousTagNameStyle =
502 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
503 }
504
505 Expr *makeOpaqueValueExpr(Expr *Inner) {
506 auto *OVE = new (S.Context)
507 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
508 Inner->getObjectKind(), Inner);
509 Actions.push_back(OVE);
510 return OVE;
511 }
512
513 Expr *getStringLiteral(llvm::StringRef Str) {
515 // Wrap the literal in parentheses to attach a source location.
516 return new (S.Context) ParenExpr(Loc, Loc, Lit);
517 }
518
519 bool callPrintFunction(llvm::StringRef Format,
520 llvm::ArrayRef<Expr *> Exprs = {}) {
521 SmallVector<Expr *, 8> Args;
522 assert(TheCall->getNumArgs() >= 2);
523 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
524 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
525 Args.push_back(getStringLiteral(Format));
526 llvm::append_range(Args, Exprs);
527
528 // Register a note to explain why we're performing the call.
529 Sema::CodeSynthesisContext Ctx;
531 Ctx.PointOfInstantiation = Loc;
532 Ctx.CallArgs = Args.data();
533 Ctx.NumCallArgs = Args.size();
535
536 ExprResult RealCall =
537 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
538 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
539
541 if (!RealCall.isInvalid())
542 Actions.push_back(RealCall.get());
543 // Bail out if we've hit any errors, even if we managed to build the
544 // call. We don't want to produce more than one error.
545 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
546 }
547
548 Expr *getIndentString(unsigned Depth) {
549 if (!Depth)
550 return nullptr;
551
552 llvm::SmallString<32> Indent;
553 Indent.resize(Depth * Policy.Indentation, ' ');
554 return getStringLiteral(Indent);
555 }
556
557 Expr *getTypeString(QualType T) {
558 return getStringLiteral(T.getAsString(Policy));
559 }
560
561 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
562 llvm::raw_svector_ostream OS(Str);
563
564 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
565 // than trying to print a single character.
566 if (auto *BT = T->getAs<BuiltinType>()) {
567 switch (BT->getKind()) {
568 case BuiltinType::Bool:
569 OS << "%d";
570 return true;
571 case BuiltinType::Char_U:
572 case BuiltinType::UChar:
573 OS << "%hhu";
574 return true;
575 case BuiltinType::Char_S:
576 case BuiltinType::SChar:
577 OS << "%hhd";
578 return true;
579 default:
580 break;
581 }
582 }
583
584 analyze_printf::PrintfSpecifier Specifier;
585 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
586 // We were able to guess how to format this.
587 if (Specifier.getConversionSpecifier().getKind() ==
588 analyze_printf::PrintfConversionSpecifier::sArg) {
589 // Wrap double-quotes around a '%s' specifier and limit its maximum
590 // length. Ideally we'd also somehow escape special characters in the
591 // contents but printf doesn't support that.
592 // FIXME: '%s' formatting is not safe in general.
593 OS << '"';
594 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
595 Specifier.toString(OS);
596 OS << '"';
597 // FIXME: It would be nice to include a '...' if the string doesn't fit
598 // in the length limit.
599 } else {
600 Specifier.toString(OS);
601 }
602 return true;
603 }
604
605 if (T->isPointerType()) {
606 // Format all pointers with '%p'.
607 OS << "%p";
608 return true;
609 }
610
611 return false;
612 }
613
614 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
615 Expr *IndentLit = getIndentString(Depth);
616 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
617 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
618 : callPrintFunction("%s", {TypeLit}))
619 return true;
620
621 return dumpRecordValue(RD, E, IndentLit, Depth);
622 }
623
624 // Dump a record value. E should be a pointer or lvalue referring to an RD.
625 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
626 unsigned Depth) {
627 // FIXME: Decide what to do if RD is a union. At least we should probably
628 // turn off printing `const char*` members with `%s`, because that is very
629 // likely to crash if that's not the active member. Whatever we decide, we
630 // should document it.
631
632 // Build an OpaqueValueExpr so we can refer to E more than once without
633 // triggering re-evaluation.
634 Expr *RecordArg = makeOpaqueValueExpr(E);
635 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
636
637 if (callPrintFunction(" {\n"))
638 return true;
639
640 // Dump each base class, regardless of whether they're aggregates.
641 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
642 for (const auto &Base : CXXRD->bases()) {
643 QualType BaseType =
644 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
645 : S.Context.getLValueReferenceType(Base.getType());
647 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
648 RecordArg);
649 if (BasePtr.isInvalid() ||
650 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
651 Depth + 1))
652 return true;
653 }
654 }
655
656 Expr *FieldIndentArg = getIndentString(Depth + 1);
657
658 // Dump each field.
659 for (auto *D : RD->decls()) {
660 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
661 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
662 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
663 continue;
664
665 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
666 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
667 getTypeString(FD->getType()),
668 getStringLiteral(FD->getName())};
669
670 if (FD->isBitField()) {
671 Format += ": %zu ";
672 QualType SizeT = S.Context.getSizeType();
673 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
674 FD->getBitWidthValue());
675 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
676 }
677
678 Format += "=";
679
682 CXXScopeSpec(), Loc, IFD,
683 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
685 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
687 DeclarationNameInfo(FD->getDeclName(), Loc));
688 if (Field.isInvalid())
689 return true;
690
691 auto *InnerRD = FD->getType()->getAsRecordDecl();
692 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
693 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
694 // Recursively print the values of members of aggregate record type.
695 if (callPrintFunction(Format, Args) ||
696 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
697 return true;
698 } else {
699 Format += " ";
700 if (appendFormatSpecifier(FD->getType(), Format)) {
701 // We know how to print this field.
702 Args.push_back(Field.get());
703 } else {
704 // We don't know how to print this field. Print out its address
705 // with a format specifier that a smart tool will be able to
706 // recognize and treat specially.
707 Format += "*%p";
708 ExprResult FieldAddr =
709 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
710 if (FieldAddr.isInvalid())
711 return true;
712 Args.push_back(FieldAddr.get());
713 }
714 Format += "\n";
715 if (callPrintFunction(Format, Args))
716 return true;
717 }
718 }
719
720 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
721 : callPrintFunction("}\n");
722 }
723
724 Expr *buildWrapper() {
725 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
727 TheCall->setType(Wrapper->getType());
728 TheCall->setValueKind(Wrapper->getValueKind());
729 return Wrapper;
730 }
731};
732} // namespace
733
735 if (S.checkArgCountAtLeast(TheCall, 2))
736 return ExprError();
737
738 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
739 if (PtrArgResult.isInvalid())
740 return ExprError();
741 TheCall->setArg(0, PtrArgResult.get());
742
743 // First argument should be a pointer to a struct.
744 QualType PtrArgType = PtrArgResult.get()->getType();
745 if (!PtrArgType->isPointerType() ||
746 !PtrArgType->getPointeeType()->isRecordType()) {
747 S.Diag(PtrArgResult.get()->getBeginLoc(),
748 diag::err_expected_struct_pointer_argument)
749 << 1 << TheCall->getDirectCallee() << PtrArgType;
750 return ExprError();
751 }
752 QualType Pointee = PtrArgType->getPointeeType();
753 const RecordDecl *RD = Pointee->getAsRecordDecl();
754 // Try to instantiate the class template as appropriate; otherwise, access to
755 // its data() may lead to a crash.
756 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
757 diag::err_incomplete_type))
758 return ExprError();
759 // Second argument is a callable, but we can't fully validate it until we try
760 // calling it.
761 QualType FnArgType = TheCall->getArg(1)->getType();
762 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
763 !FnArgType->isBlockPointerType() &&
764 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
765 auto *BT = FnArgType->getAs<BuiltinType>();
766 switch (BT ? BT->getKind() : BuiltinType::Void) {
767 case BuiltinType::Dependent:
768 case BuiltinType::Overload:
769 case BuiltinType::BoundMember:
770 case BuiltinType::PseudoObject:
771 case BuiltinType::UnknownAny:
772 case BuiltinType::BuiltinFn:
773 // This might be a callable.
774 break;
775
776 default:
777 S.Diag(TheCall->getArg(1)->getBeginLoc(),
778 diag::err_expected_callable_argument)
779 << 2 << TheCall->getDirectCallee() << FnArgType;
780 return ExprError();
781 }
782 }
783
784 BuiltinDumpStructGenerator Generator(S, TheCall);
785
786 // Wrap parentheses around the given pointer. This is not necessary for
787 // correct code generation, but it means that when we pretty-print the call
788 // arguments in our diagnostics we will produce '(&s)->n' instead of the
789 // incorrect '&s->n'.
790 Expr *PtrArg = PtrArgResult.get();
791 PtrArg = new (S.Context)
792 ParenExpr(PtrArg->getBeginLoc(),
793 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
794 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
795 return ExprError();
796
797 return Generator.buildWrapper();
798}
799
800static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
801 if (S.checkArgCount(BuiltinCall, 2))
802 return true;
803
804 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
805 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
806 Expr *Call = BuiltinCall->getArg(0);
807 Expr *Chain = BuiltinCall->getArg(1);
808
809 if (Call->getStmtClass() != Stmt::CallExprClass) {
810 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
811 << Call->getSourceRange();
812 return true;
813 }
814
815 auto CE = cast<CallExpr>(Call);
816 if (CE->getCallee()->getType()->isBlockPointerType()) {
817 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
818 << Call->getSourceRange();
819 return true;
820 }
821
822 const Decl *TargetDecl = CE->getCalleeDecl();
823 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
824 if (FD->getBuiltinID()) {
825 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
826 << Call->getSourceRange();
827 return true;
828 }
829
830 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
831 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
832 << Call->getSourceRange();
833 return true;
834 }
835
836 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
837 if (ChainResult.isInvalid())
838 return true;
839 if (!ChainResult.get()->getType()->isPointerType()) {
840 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
841 << Chain->getSourceRange();
842 return true;
843 }
844
845 QualType ReturnTy = CE->getCallReturnType(S.Context);
846 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
847 QualType BuiltinTy = S.Context.getFunctionType(
848 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
849 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
850
851 Builtin =
852 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
853
854 BuiltinCall->setType(CE->getType());
855 BuiltinCall->setValueKind(CE->getValueKind());
856 BuiltinCall->setObjectKind(CE->getObjectKind());
857 BuiltinCall->setCallee(Builtin);
858 BuiltinCall->setArg(1, ChainResult.get());
859
860 return false;
861}
862
863namespace {
864
865class ScanfDiagnosticFormatHandler
867 // Accepts the argument index (relative to the first destination index) of the
868 // argument whose size we want.
869 using ComputeSizeFunction =
870 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
871
872 // Accepts the argument index (relative to the first destination index), the
873 // destination size, and the source size).
874 using DiagnoseFunction =
875 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
876
877 ComputeSizeFunction ComputeSizeArgument;
878 DiagnoseFunction Diagnose;
879
880public:
881 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
882 DiagnoseFunction Diagnose)
883 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
884
885 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
886 const char *StartSpecifier,
887 unsigned specifierLen) override {
888 if (!FS.consumesDataArgument())
889 return true;
890
891 unsigned NulByte = 0;
892 switch ((FS.getConversionSpecifier().getKind())) {
893 default:
894 return true;
897 NulByte = 1;
898 break;
900 break;
901 }
902
903 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
904 if (FW.getHowSpecified() !=
905 analyze_format_string::OptionalAmount::HowSpecified::Constant)
906 return true;
907
908 unsigned SourceSize = FW.getConstantAmount() + NulByte;
909
910 std::optional<llvm::APSInt> DestSizeAPS =
911 ComputeSizeArgument(FS.getArgIndex());
912 if (!DestSizeAPS)
913 return true;
914
915 unsigned DestSize = DestSizeAPS->getZExtValue();
916
917 if (DestSize < SourceSize)
918 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
919
920 return true;
921 }
922};
923
924class EstimateSizeFormatHandler
926 size_t Size;
927 /// Whether the format string contains Linux kernel's format specifier
928 /// extension.
929 bool IsKernelCompatible = true;
930
931public:
932 EstimateSizeFormatHandler(StringRef Format)
933 : Size(std::min(Format.find(0), Format.size()) +
934 1 /* null byte always written by sprintf */) {}
935
936 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
937 const char *, unsigned SpecifierLen,
938 const TargetInfo &) override {
939
940 const size_t FieldWidth = computeFieldWidth(FS);
941 const size_t Precision = computePrecision(FS);
942
943 // The actual format.
944 switch (FS.getConversionSpecifier().getKind()) {
945 // Just a char.
948 Size += std::max(FieldWidth, (size_t)1);
949 break;
950 // Just an integer.
960 Size += std::max(FieldWidth, Precision);
961 break;
962
963 // %g style conversion switches between %f or %e style dynamically.
964 // %g removes trailing zeros, and does not print decimal point if there are
965 // no digits that follow it. Thus %g can print a single digit.
966 // FIXME: If it is alternative form:
967 // For g and G conversions, trailing zeros are not removed from the result.
970 Size += 1;
971 break;
972
973 // Floating point number in the form '[+]ddd.ddd'.
976 Size += std::max(FieldWidth, 1 /* integer part */ +
977 (Precision ? 1 + Precision
978 : 0) /* period + decimal */);
979 break;
980
981 // Floating point number in the form '[-]d.ddde[+-]dd'.
984 Size +=
985 std::max(FieldWidth,
986 1 /* integer part */ +
987 (Precision ? 1 + Precision : 0) /* period + decimal */ +
988 1 /* e or E letter */ + 2 /* exponent */);
989 break;
990
991 // Floating point number in the form '[-]0xh.hhhhp±dd'.
994 Size +=
995 std::max(FieldWidth,
996 2 /* 0x */ + 1 /* integer part */ +
997 (Precision ? 1 + Precision : 0) /* period + decimal */ +
998 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
999 break;
1000
1001 // Just a string.
1004 Size += FieldWidth;
1005 break;
1006
1007 // Just a pointer in the form '0xddd'.
1009 // Linux kernel has its own extesion for `%p` specifier.
1010 // Kernel Document:
1011 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1012 IsKernelCompatible = false;
1013 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1014 break;
1015
1016 // A plain percent.
1018 Size += 1;
1019 break;
1020
1021 default:
1022 break;
1023 }
1024
1025 // If field width is specified, the sign/space is already accounted for
1026 // within the field width, so no additional size is needed.
1027 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1028 Size += 1;
1029
1030 if (FS.hasAlternativeForm()) {
1031 switch (FS.getConversionSpecifier().getKind()) {
1032 // For o conversion, it increases the precision, if and only if necessary,
1033 // to force the first digit of the result to be a zero
1034 // (if the value and precision are both 0, a single 0 is printed)
1036 // For b conversion, a nonzero result has 0b prefixed to it.
1038 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1039 // it.
1042 // Note: even when the prefix is added, if
1043 // (prefix_width <= FieldWidth - formatted_length) holds,
1044 // the prefix does not increase the format
1045 // size. e.g.(("%#3x", 0xf) is "0xf")
1046
1047 // If the result is zero, o, b, x, X adds nothing.
1048 break;
1049 // For a, A, e, E, f, F, g, and G conversions,
1050 // the result of converting a floating-point number always contains a
1051 // decimal-point
1060 Size += (Precision ? 0 : 1);
1061 break;
1062 // For other conversions, the behavior is undefined.
1063 default:
1064 break;
1065 }
1066 }
1067 assert(SpecifierLen <= Size && "no underflow");
1068 Size -= SpecifierLen;
1069 return true;
1070 }
1071
1072 size_t getSizeLowerBound() const { return Size; }
1073 bool isKernelCompatible() const { return IsKernelCompatible; }
1074
1075private:
1076 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1077 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1078 size_t FieldWidth = 0;
1080 FieldWidth = FW.getConstantAmount();
1081 return FieldWidth;
1082 }
1083
1084 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1085 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1086 size_t Precision = 0;
1087
1088 // See man 3 printf for default precision value based on the specifier.
1089 switch (FW.getHowSpecified()) {
1091 switch (FS.getConversionSpecifier().getKind()) {
1092 default:
1093 break;
1097 Precision = 1;
1098 break;
1105 Precision = 1;
1106 break;
1113 Precision = 6;
1114 break;
1116 Precision = 1;
1117 break;
1118 }
1119 break;
1121 Precision = FW.getConstantAmount();
1122 break;
1123 default:
1124 break;
1125 }
1126 return Precision;
1127 }
1128};
1129
1130} // namespace
1131
1132static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1133 StringRef &FormatStrRef, size_t &StrLen,
1134 ASTContext &Context) {
1135 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1136 Format && (Format->isOrdinary() || Format->isUTF8())) {
1137 FormatStrRef = Format->getString();
1138 const ConstantArrayType *T =
1139 Context.getAsConstantArrayType(Format->getType());
1140 assert(T && "String literal not of constant array type!");
1141 size_t TypeSize = T->getZExtSize();
1142 // In case there's a null byte somewhere.
1143 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1144 return true;
1145 }
1146 return false;
1147}
1148
1149void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1150 CallExpr *TheCall) {
1151 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1153 return;
1154
1155 bool UseDABAttr = false;
1156 const FunctionDecl *UseDecl = FD;
1157
1158 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1159 if (DABAttr) {
1160 UseDecl = DABAttr->getFunction();
1161 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1162 UseDABAttr = true;
1163 }
1164
1165 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1166
1167 if (!BuiltinID)
1168 return;
1169
1170 const TargetInfo &TI = getASTContext().getTargetInfo();
1171 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1172
1173 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1174 // If we refer to a diagnose_as_builtin attribute, we need to change the
1175 // argument index to refer to the arguments of the called function. Unless
1176 // the index is out of bounds, which presumably means it's a variadic
1177 // function.
1178 if (!UseDABAttr)
1179 return Index;
1180 unsigned DABIndices = DABAttr->argIndices_size();
1181 unsigned NewIndex = Index < DABIndices
1182 ? DABAttr->argIndices_begin()[Index]
1183 : Index - DABIndices + FD->getNumParams();
1184 if (NewIndex >= TheCall->getNumArgs())
1185 return std::nullopt;
1186 return NewIndex;
1187 };
1188
1189 auto ComputeExplicitObjectSizeArgument =
1190 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1191 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1192 if (!IndexOptional)
1193 return std::nullopt;
1194 unsigned NewIndex = *IndexOptional;
1195 Expr::EvalResult Result;
1196 Expr *SizeArg = TheCall->getArg(NewIndex);
1197 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1198 return std::nullopt;
1199 llvm::APSInt Integer = Result.Val.getInt();
1200 Integer.setIsUnsigned(true);
1201 return Integer;
1202 };
1203
1204 auto ComputeSizeArgument =
1205 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1206 // If the parameter has a pass_object_size attribute, then we should use its
1207 // (potentially) more strict checking mode. Otherwise, conservatively assume
1208 // type 0.
1209 int BOSType = 0;
1210 // This check can fail for variadic functions.
1211 if (Index < FD->getNumParams()) {
1212 if (const auto *POS =
1213 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1214 BOSType = POS->getType();
1215 }
1216
1217 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1218 if (!IndexOptional)
1219 return std::nullopt;
1220 unsigned NewIndex = *IndexOptional;
1221
1222 if (NewIndex >= TheCall->getNumArgs())
1223 return std::nullopt;
1224
1225 const Expr *ObjArg = TheCall->getArg(NewIndex);
1226 if (std::optional<uint64_t> ObjSize =
1227 ObjArg->tryEvaluateObjectSize(getASTContext(), BOSType)) {
1228 // Get the object size in the target's size_t width.
1229 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1230 }
1231 return std::nullopt;
1232 };
1233
1234 auto ComputeStrLenArgument =
1235 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1236 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1237 if (!IndexOptional)
1238 return std::nullopt;
1239 unsigned NewIndex = *IndexOptional;
1240
1241 const Expr *ObjArg = TheCall->getArg(NewIndex);
1242
1243 if (std::optional<uint64_t> Result =
1244 ObjArg->tryEvaluateStrLen(getASTContext())) {
1245 // Add 1 for null byte.
1246 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1247 }
1248 return std::nullopt;
1249 };
1250
1251 std::optional<llvm::APSInt> SourceSize;
1252 std::optional<llvm::APSInt> DestinationSize;
1253 unsigned DiagID = 0;
1254 bool IsChkVariant = false;
1255
1256 auto GetFunctionName = [&]() {
1257 std::string FunctionNameStr =
1258 getASTContext().BuiltinInfo.getName(BuiltinID);
1259 llvm::StringRef FunctionName = FunctionNameStr;
1260 // Skim off the details of whichever builtin was called to produce a better
1261 // diagnostic, as it's unlikely that the user wrote the __builtin
1262 // explicitly.
1263 if (IsChkVariant) {
1264 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1265 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1266 } else {
1267 FunctionName.consume_front("__builtin_");
1268 }
1269 return FunctionName.str();
1270 };
1271
1272 switch (BuiltinID) {
1273 default:
1274 return;
1275 case Builtin::BI__builtin_strcat:
1276 case Builtin::BIstrcat:
1277 case Builtin::BI__builtin_stpcpy:
1278 case Builtin::BIstpcpy:
1279 case Builtin::BI__builtin_strcpy:
1280 case Builtin::BIstrcpy: {
1281 DiagID = diag::warn_fortify_strlen_overflow;
1282 SourceSize = ComputeStrLenArgument(1);
1283 DestinationSize = ComputeSizeArgument(0);
1284 break;
1285 }
1286
1287 case Builtin::BI__builtin___strcat_chk:
1288 case Builtin::BI__builtin___stpcpy_chk:
1289 case Builtin::BI__builtin___strcpy_chk: {
1290 DiagID = diag::warn_fortify_strlen_overflow;
1291 SourceSize = ComputeStrLenArgument(1);
1292 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1293 IsChkVariant = true;
1294 break;
1295 }
1296
1297 case Builtin::BIscanf:
1298 case Builtin::BIfscanf:
1299 case Builtin::BIsscanf: {
1300 unsigned FormatIndex = 1;
1301 unsigned DataIndex = 2;
1302 if (BuiltinID == Builtin::BIscanf) {
1303 FormatIndex = 0;
1304 DataIndex = 1;
1305 }
1306
1307 const auto *FormatExpr =
1308 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1309
1310 StringRef FormatStrRef;
1311 size_t StrLen;
1312 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1313 return;
1314
1315 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1316 unsigned SourceSize) {
1317 DiagID = diag::warn_fortify_scanf_overflow;
1318 unsigned Index = ArgIndex + DataIndex;
1319 std::string FunctionName = GetFunctionName();
1320 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1321 PDiag(DiagID) << FunctionName << (Index + 1)
1322 << DestSize << SourceSize);
1323 };
1324
1325 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1326 return ComputeSizeArgument(Index + DataIndex);
1327 };
1328 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1329 const char *FormatBytes = FormatStrRef.data();
1331 FormatBytes + StrLen, getLangOpts(),
1332 Context.getTargetInfo());
1333
1334 // Unlike the other cases, in this one we have already issued the diagnostic
1335 // here, so no need to continue (because unlike the other cases, here the
1336 // diagnostic refers to the argument number).
1337 return;
1338 }
1339
1340 case Builtin::BIsprintf:
1341 case Builtin::BI__builtin___sprintf_chk: {
1342 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1343 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1344
1345 StringRef FormatStrRef;
1346 size_t StrLen;
1347 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1348 EstimateSizeFormatHandler H(FormatStrRef);
1349 const char *FormatBytes = FormatStrRef.data();
1351 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1352 Context.getTargetInfo(), false)) {
1353 DiagID = H.isKernelCompatible()
1354 ? diag::warn_format_overflow
1355 : diag::warn_format_overflow_non_kprintf;
1356 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1357 .extOrTrunc(SizeTypeWidth);
1358 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1359 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1360 IsChkVariant = true;
1361 } else {
1362 DestinationSize = ComputeSizeArgument(0);
1363 }
1364 break;
1365 }
1366 }
1367 return;
1368 }
1369 case Builtin::BI__builtin___memcpy_chk:
1370 case Builtin::BI__builtin___memmove_chk:
1371 case Builtin::BI__builtin___memset_chk:
1372 case Builtin::BI__builtin___strlcat_chk:
1373 case Builtin::BI__builtin___strlcpy_chk:
1374 case Builtin::BI__builtin___strncat_chk:
1375 case Builtin::BI__builtin___strncpy_chk:
1376 case Builtin::BI__builtin___stpncpy_chk:
1377 case Builtin::BI__builtin___memccpy_chk:
1378 case Builtin::BI__builtin___mempcpy_chk: {
1379 DiagID = diag::warn_builtin_chk_overflow;
1380 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1381 DestinationSize =
1382 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1383 IsChkVariant = true;
1384 break;
1385 }
1386
1387 case Builtin::BI__builtin___snprintf_chk:
1388 case Builtin::BI__builtin___vsnprintf_chk: {
1389 DiagID = diag::warn_builtin_chk_overflow;
1390 SourceSize = ComputeExplicitObjectSizeArgument(1);
1391 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1392 IsChkVariant = true;
1393 break;
1394 }
1395
1396 case Builtin::BIstrncat:
1397 case Builtin::BI__builtin_strncat:
1398 case Builtin::BIstrncpy:
1399 case Builtin::BI__builtin_strncpy:
1400 case Builtin::BIstpncpy:
1401 case Builtin::BI__builtin_stpncpy: {
1402 // Whether these functions overflow depends on the runtime strlen of the
1403 // string, not just the buffer size, so emitting the "always overflow"
1404 // diagnostic isn't quite right. We should still diagnose passing a buffer
1405 // size larger than the destination buffer though; this is a runtime abort
1406 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1407 DiagID = diag::warn_fortify_source_size_mismatch;
1408 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1409 DestinationSize = ComputeSizeArgument(0);
1410 break;
1411 }
1412
1413 case Builtin::BIbzero:
1414 case Builtin::BI__builtin_bzero:
1415 case Builtin::BImemcpy:
1416 case Builtin::BI__builtin_memcpy:
1417 case Builtin::BImemmove:
1418 case Builtin::BI__builtin_memmove:
1419 case Builtin::BImemset:
1420 case Builtin::BI__builtin_memset:
1421 case Builtin::BImempcpy:
1422 case Builtin::BI__builtin_mempcpy: {
1423 DiagID = diag::warn_fortify_source_overflow;
1424 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1425 DestinationSize = ComputeSizeArgument(0);
1426 break;
1427 }
1428 case Builtin::BIbcopy:
1429 case Builtin::BI__builtin_bcopy: {
1430 DiagID = diag::warn_fortify_source_overflow;
1431 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1432 DestinationSize = ComputeSizeArgument(1);
1433 break;
1434 }
1435 case Builtin::BIsnprintf:
1436 case Builtin::BI__builtin_snprintf:
1437 case Builtin::BIvsnprintf:
1438 case Builtin::BI__builtin_vsnprintf: {
1439 DiagID = diag::warn_fortify_source_size_mismatch;
1440 SourceSize = ComputeExplicitObjectSizeArgument(1);
1441 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1442 StringRef FormatStrRef;
1443 size_t StrLen;
1444 if (SourceSize &&
1445 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1446 EstimateSizeFormatHandler H(FormatStrRef);
1447 const char *FormatBytes = FormatStrRef.data();
1449 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1450 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1451 llvm::APSInt FormatSize =
1452 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1453 .extOrTrunc(SizeTypeWidth);
1454 if (FormatSize > *SourceSize && *SourceSize != 0) {
1455 unsigned TruncationDiagID =
1456 H.isKernelCompatible() ? diag::warn_format_truncation
1457 : diag::warn_format_truncation_non_kprintf;
1458 SmallString<16> SpecifiedSizeStr;
1459 SmallString<16> FormatSizeStr;
1460 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1461 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1462 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1463 PDiag(TruncationDiagID)
1464 << GetFunctionName() << SpecifiedSizeStr
1465 << FormatSizeStr);
1466 }
1467 }
1468 }
1469 DestinationSize = ComputeSizeArgument(0);
1470 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1471 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1472 IdentifierInfo *FnInfo = FD->getIdentifier();
1473 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1474 }
1475 }
1476
1477 if (!SourceSize || !DestinationSize ||
1478 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1479 return;
1480
1481 std::string FunctionName = GetFunctionName();
1482
1483 SmallString<16> DestinationStr;
1484 SmallString<16> SourceStr;
1485 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1486 SourceSize->toString(SourceStr, /*Radix=*/10);
1487 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1488 PDiag(DiagID)
1489 << FunctionName << DestinationStr << SourceStr);
1490}
1491
1492static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1493 Scope::ScopeFlags NeededScopeFlags,
1494 unsigned DiagID) {
1495 // Scopes aren't available during instantiation. Fortunately, builtin
1496 // functions cannot be template args so they cannot be formed through template
1497 // instantiation. Therefore checking once during the parse is sufficient.
1498 if (SemaRef.inTemplateInstantiation())
1499 return false;
1500
1501 Scope *S = SemaRef.getCurScope();
1502 while (S && !S->isSEHExceptScope())
1503 S = S->getParent();
1504 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1505 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1506 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1507 << DRE->getDecl()->getIdentifier();
1508 return true;
1509 }
1510
1511 return false;
1512}
1513
1514// In OpenCL, __builtin_alloca_* should return a pointer to address space
1515// that corresponds to the stack address space i.e private address space.
1516static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1517 QualType RT = TheCall->getType();
1518 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1519 "__builtin_alloca has invalid address space");
1520
1521 RT = RT->getPointeeType();
1523 TheCall->setType(S.Context.getPointerType(RT));
1524}
1525
1526static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1527 if (S.checkArgCountAtLeast(TheCall, 1))
1528 return true;
1529
1530 for (Expr *Arg : TheCall->arguments()) {
1531 // If argument is dependent on a template parameter, we can't resolve now.
1532 if (Arg->isTypeDependent() || Arg->isValueDependent())
1533 continue;
1534 // Reject void types.
1535 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1536 if (ArgTy->isVoidType())
1537 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1538 }
1539
1540 TheCall->setType(S.Context.getSizeType());
1541 return false;
1542}
1543
1544namespace {
1545enum PointerAuthOpKind {
1546 PAO_Strip,
1547 PAO_Sign,
1548 PAO_Auth,
1549 PAO_SignGeneric,
1550 PAO_Discriminator,
1551 PAO_BlendPointer,
1552 PAO_BlendInteger
1553};
1554}
1555
1557 if (getLangOpts().PointerAuthIntrinsics)
1558 return false;
1559
1560 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1561 return true;
1562}
1563
1564static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1566}
1567
1568static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1569 // Convert it to type 'int'.
1570 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1571 return true;
1572
1573 // Value-dependent expressions are okay; wait for template instantiation.
1574 if (Arg->isValueDependent())
1575 return false;
1576
1577 unsigned KeyValue;
1578 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1579}
1580
1582 // Attempt to constant-evaluate the expression.
1583 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1584 if (!KeyValue) {
1585 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1586 << 0 << Arg->getSourceRange();
1587 return true;
1588 }
1589
1590 // Ask the target to validate the key parameter.
1591 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1593 {
1594 llvm::raw_svector_ostream Str(Value);
1595 Str << *KeyValue;
1596 }
1597
1598 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1599 << Value << Arg->getSourceRange();
1600 return true;
1601 }
1602
1603 Result = KeyValue->getZExtValue();
1604 return false;
1605}
1606
1609 unsigned &IntVal) {
1610 if (!Arg) {
1611 IntVal = 0;
1612 return true;
1613 }
1614
1615 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1616 if (!Result) {
1617 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1618 return false;
1619 }
1620
1621 unsigned Max;
1622 bool IsAddrDiscArg = false;
1623
1624 switch (Kind) {
1626 Max = 1;
1627 IsAddrDiscArg = true;
1628 break;
1631 break;
1632 };
1633
1635 if (IsAddrDiscArg)
1636 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1637 << Result->getExtValue();
1638 else
1639 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1640 << Result->getExtValue() << Max;
1641
1642 return false;
1643 };
1644
1645 IntVal = Result->getZExtValue();
1646 return true;
1647}
1648
1649static std::pair<const ValueDecl *, CharUnits>
1651 // Must evaluate as a pointer.
1652 Expr::EvalResult Result;
1653 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1654 return {nullptr, CharUnits()};
1655
1656 const auto *BaseDecl =
1657 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1658 if (!BaseDecl)
1659 return {nullptr, CharUnits()};
1660
1661 return {BaseDecl, Result.Val.getLValueOffset()};
1662}
1663
1664static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1665 bool RequireConstant = false) {
1666 if (Arg->hasPlaceholderType()) {
1668 if (R.isInvalid())
1669 return true;
1670 Arg = R.get();
1671 }
1672
1673 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1674 return OpKind != PAO_BlendInteger;
1675 };
1676 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1677 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1678 OpKind == PAO_SignGeneric;
1679 };
1680
1681 // Require the value to have the right range of type.
1682 QualType ExpectedTy;
1683 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1684 ExpectedTy = Arg->getType().getUnqualifiedType();
1685 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1686 ExpectedTy = S.Context.VoidPtrTy;
1687 } else if (AllowsInteger(OpKind) &&
1689 ExpectedTy = S.Context.getUIntPtrType();
1690
1691 } else {
1692 // Diagnose the failures.
1693 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1694 << unsigned(OpKind == PAO_Discriminator ? 1
1695 : OpKind == PAO_BlendPointer ? 2
1696 : OpKind == PAO_BlendInteger ? 3
1697 : 0)
1698 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1699 << Arg->getType() << Arg->getSourceRange();
1700 return true;
1701 }
1702
1703 // Convert to that type. This should just be an lvalue-to-rvalue
1704 // conversion.
1705 if (convertArgumentToType(S, Arg, ExpectedTy))
1706 return true;
1707
1708 if (!RequireConstant) {
1709 // Warn about null pointers for non-generic sign and auth operations.
1710 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1712 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1713 ? diag::warn_ptrauth_sign_null_pointer
1714 : diag::warn_ptrauth_auth_null_pointer)
1715 << Arg->getSourceRange();
1716 }
1717
1718 return false;
1719 }
1720
1721 // Perform special checking on the arguments to ptrauth_sign_constant.
1722
1723 // The main argument.
1724 if (OpKind == PAO_Sign) {
1725 // Require the value we're signing to have a special form.
1726 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1727 bool Invalid;
1728
1729 // Must be rooted in a declaration reference.
1730 if (!BaseDecl)
1731 Invalid = true;
1732
1733 // If it's a function declaration, we can't have an offset.
1734 else if (isa<FunctionDecl>(BaseDecl))
1735 Invalid = !Offset.isZero();
1736
1737 // Otherwise we're fine.
1738 else
1739 Invalid = false;
1740
1741 if (Invalid)
1742 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1743 return Invalid;
1744 }
1745
1746 // The discriminator argument.
1747 assert(OpKind == PAO_Discriminator);
1748
1749 // Must be a pointer or integer or blend thereof.
1750 Expr *Pointer = nullptr;
1751 Expr *Integer = nullptr;
1752 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1753 if (Call->getBuiltinCallee() ==
1754 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1755 Pointer = Call->getArg(0);
1756 Integer = Call->getArg(1);
1757 }
1758 }
1759 if (!Pointer && !Integer) {
1760 if (Arg->getType()->isPointerType())
1761 Pointer = Arg;
1762 else
1763 Integer = Arg;
1764 }
1765
1766 // Check the pointer.
1767 bool Invalid = false;
1768 if (Pointer) {
1769 assert(Pointer->getType()->isPointerType());
1770
1771 // TODO: if we're initializing a global, check that the address is
1772 // somehow related to what we're initializing. This probably will
1773 // never really be feasible and we'll have to catch it at link-time.
1774 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1775 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1776 Invalid = true;
1777 }
1778
1779 // Check the integer.
1780 if (Integer) {
1781 assert(Integer->getType()->isIntegerType());
1782 if (!Integer->isEvaluatable(S.Context))
1783 Invalid = true;
1784 }
1785
1786 if (Invalid)
1787 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1788 return Invalid;
1789}
1790
1792 if (S.checkArgCount(Call, 2))
1793 return ExprError();
1795 return ExprError();
1796 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1797 checkPointerAuthKey(S, Call->getArgs()[1]))
1798 return ExprError();
1799
1800 Call->setType(Call->getArgs()[0]->getType());
1801 return Call;
1802}
1803
1805 if (S.checkArgCount(Call, 2))
1806 return ExprError();
1808 return ExprError();
1809 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1810 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1811 return ExprError();
1812
1813 Call->setType(S.Context.getUIntPtrType());
1814 return Call;
1815}
1816
1818 if (S.checkArgCount(Call, 2))
1819 return ExprError();
1821 return ExprError();
1822 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1823 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1824 return ExprError();
1825
1826 Call->setType(S.Context.getUIntPtrType());
1827 return Call;
1828}
1829
1831 PointerAuthOpKind OpKind,
1832 bool RequireConstant) {
1833 if (S.checkArgCount(Call, 3))
1834 return ExprError();
1836 return ExprError();
1837 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1838 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1839 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1840 RequireConstant))
1841 return ExprError();
1842
1843 Call->setType(Call->getArgs()[0]->getType());
1844 return Call;
1845}
1846
1848 if (S.checkArgCount(Call, 5))
1849 return ExprError();
1851 return ExprError();
1852 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1853 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1854 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1855 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1856 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1857 return ExprError();
1858
1859 Call->setType(Call->getArgs()[0]->getType());
1860 return Call;
1861}
1862
1864 if (S.checkArgCount(Call, 6))
1865 return ExprError();
1867 return ExprError();
1868 const Expr *AddendExpr = Call->getArg(5);
1869 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
1870 if (!AddendIsConstInt) {
1871 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
1872 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
1873 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1874 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
1875 << FDecl->getDeclName() << Arg->getSourceRange();
1876 }
1877 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1878 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1879 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1880 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1881 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
1882 !AddendIsConstInt)
1883 return ExprError();
1884
1885 Call->setType(Call->getArgs()[0]->getType());
1886 return Call;
1887}
1888
1891 return ExprError();
1892
1893 // We've already performed normal call type-checking.
1894 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1895
1896 // Operand must be an ordinary or UTF-8 string literal.
1897 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1898 if (!Literal || Literal->getCharByteWidth() != 1) {
1899 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1900 << (Literal ? 1 : 0) << Arg->getSourceRange();
1901 return ExprError();
1902 }
1903
1904 return Call;
1905}
1906
1908 if (S.checkArgCount(Call, 1))
1909 return ExprError();
1910 Expr *FirstArg = Call->getArg(0);
1911 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1912 if (FirstValue.isInvalid())
1913 return ExprError();
1914 Call->setArg(0, FirstValue.get());
1915 QualType FirstArgType = FirstArg->getType();
1916 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1917 FirstArgType = S.Context.getDecayedType(FirstArgType);
1918
1919 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1920 if (!FirstArgRecord) {
1921 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1922 << /*isPolymorphic=*/0 << FirstArgType;
1923 return ExprError();
1924 }
1925 if (S.RequireCompleteType(
1926 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1927 diag::err_get_vtable_pointer_requires_complete_type)) {
1928 return ExprError();
1929 }
1930
1931 if (!FirstArgRecord->isPolymorphic()) {
1932 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1933 << /*isPolymorphic=*/1 << FirstArgRecord;
1934 return ExprError();
1935 }
1937 Call->setType(ReturnType);
1938 return Call;
1939}
1940
1942 if (S.checkArgCount(TheCall, 1))
1943 return ExprError();
1944
1945 // Compute __builtin_launder's parameter type from the argument.
1946 // The parameter type is:
1947 // * The type of the argument if it's not an array or function type,
1948 // Otherwise,
1949 // * The decayed argument type.
1950 QualType ParamTy = [&]() {
1951 QualType ArgTy = TheCall->getArg(0)->getType();
1952 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1953 return S.Context.getPointerType(Ty->getElementType());
1954 if (ArgTy->isFunctionType()) {
1955 return S.Context.getPointerType(ArgTy);
1956 }
1957 return ArgTy;
1958 }();
1959
1960 TheCall->setType(ParamTy);
1961
1962 auto DiagSelect = [&]() -> std::optional<unsigned> {
1963 if (!ParamTy->isPointerType())
1964 return 0;
1965 if (ParamTy->isFunctionPointerType())
1966 return 1;
1967 if (ParamTy->isVoidPointerType())
1968 return 2;
1969 return std::optional<unsigned>{};
1970 }();
1971 if (DiagSelect) {
1972 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1973 << *DiagSelect << TheCall->getSourceRange();
1974 return ExprError();
1975 }
1976
1977 // We either have an incomplete class type, or we have a class template
1978 // whose instantiation has not been forced. Example:
1979 //
1980 // template <class T> struct Foo { T value; };
1981 // Foo<int> *p = nullptr;
1982 // auto *d = __builtin_launder(p);
1983 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1984 diag::err_incomplete_type))
1985 return ExprError();
1986
1987 assert(ParamTy->getPointeeType()->isObjectType() &&
1988 "Unhandled non-object pointer case");
1989
1990 InitializedEntity Entity =
1992 ExprResult Arg =
1993 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1994 if (Arg.isInvalid())
1995 return ExprError();
1996 TheCall->setArg(0, Arg.get());
1997
1998 return TheCall;
1999}
2000
2002 if (S.checkArgCount(TheCall, 1))
2003 return ExprError();
2004
2006 if (Arg.isInvalid())
2007 return ExprError();
2008 QualType ParamTy = Arg.get()->getType();
2009 TheCall->setArg(0, Arg.get());
2010 TheCall->setType(S.Context.BoolTy);
2011
2012 // Only accept pointers to objects as arguments, which should have object
2013 // pointer or void pointer types.
2014 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2015 // LWG4138: Function pointer types not allowed
2016 if (PT->getPointeeType()->isFunctionType()) {
2017 S.Diag(TheCall->getArg(0)->getExprLoc(),
2018 diag::err_builtin_is_within_lifetime_invalid_arg)
2019 << 1;
2020 return ExprError();
2021 }
2022 // Disallow VLAs too since those shouldn't be able to
2023 // be a template parameter for `std::is_within_lifetime`
2024 if (PT->getPointeeType()->isVariableArrayType()) {
2025 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2026 << 1 << "__builtin_is_within_lifetime";
2027 return ExprError();
2028 }
2029 } else {
2030 S.Diag(TheCall->getArg(0)->getExprLoc(),
2031 diag::err_builtin_is_within_lifetime_invalid_arg)
2032 << 0;
2033 return ExprError();
2034 }
2035 return TheCall;
2036}
2037
2039 if (S.checkArgCount(TheCall, 3))
2040 return ExprError();
2041
2042 QualType Dest = TheCall->getArg(0)->getType();
2043 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2044 S.Diag(TheCall->getArg(0)->getExprLoc(),
2045 diag::err_builtin_trivially_relocate_invalid_arg_type)
2046 << /*a pointer*/ 0;
2047 return ExprError();
2048 }
2049
2050 QualType T = Dest->getPointeeType();
2051 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2052 diag::err_incomplete_type))
2053 return ExprError();
2054
2055 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2056 T->isIncompleteArrayType()) {
2057 S.Diag(TheCall->getArg(0)->getExprLoc(),
2058 diag::err_builtin_trivially_relocate_invalid_arg_type)
2059 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2060 return ExprError();
2061 }
2062
2063 TheCall->setType(Dest);
2064
2065 QualType Src = TheCall->getArg(1)->getType();
2066 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2067 S.Diag(TheCall->getArg(1)->getExprLoc(),
2068 diag::err_builtin_trivially_relocate_invalid_arg_type)
2069 << /*the same*/ 3;
2070 return ExprError();
2071 }
2072
2073 Expr *SizeExpr = TheCall->getArg(2);
2074 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2075 if (Size.isInvalid())
2076 return ExprError();
2077
2078 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2079 if (Size.isInvalid())
2080 return ExprError();
2081 SizeExpr = Size.get();
2082 TheCall->setArg(2, SizeExpr);
2083
2084 return TheCall;
2085}
2086
2087// Emit an error and return true if the current object format type is in the
2088// list of unsupported types.
2090 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2091 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2092 llvm::Triple::ObjectFormatType CurObjFormat =
2093 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2094 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2095 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2096 << TheCall->getSourceRange();
2097 return true;
2098 }
2099 return false;
2100}
2101
2102// Emit an error and return true if the current architecture is not in the list
2103// of supported architectures.
2104static bool
2106 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2107 llvm::Triple::ArchType CurArch =
2108 S.getASTContext().getTargetInfo().getTriple().getArch();
2109 if (llvm::is_contained(SupportedArchs, CurArch))
2110 return false;
2111 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2112 << TheCall->getSourceRange();
2113 return true;
2114}
2115
2116static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2117 SourceLocation CallSiteLoc);
2118
2119bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2120 CallExpr *TheCall) {
2121 switch (TI.getTriple().getArch()) {
2122 default:
2123 // Some builtins don't require additional checking, so just consider these
2124 // acceptable.
2125 return false;
2126 case llvm::Triple::arm:
2127 case llvm::Triple::armeb:
2128 case llvm::Triple::thumb:
2129 case llvm::Triple::thumbeb:
2130 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2131 case llvm::Triple::aarch64:
2132 case llvm::Triple::aarch64_32:
2133 case llvm::Triple::aarch64_be:
2134 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2135 case llvm::Triple::bpfeb:
2136 case llvm::Triple::bpfel:
2137 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2138 case llvm::Triple::dxil:
2139 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2140 case llvm::Triple::hexagon:
2141 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2142 case llvm::Triple::mips:
2143 case llvm::Triple::mipsel:
2144 case llvm::Triple::mips64:
2145 case llvm::Triple::mips64el:
2146 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2147 case llvm::Triple::spirv:
2148 case llvm::Triple::spirv32:
2149 case llvm::Triple::spirv64:
2150 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2151 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2152 return false;
2153 case llvm::Triple::systemz:
2154 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2155 case llvm::Triple::x86:
2156 case llvm::Triple::x86_64:
2157 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2158 case llvm::Triple::ppc:
2159 case llvm::Triple::ppcle:
2160 case llvm::Triple::ppc64:
2161 case llvm::Triple::ppc64le:
2162 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2163 case llvm::Triple::amdgcn:
2164 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2165 case llvm::Triple::riscv32:
2166 case llvm::Triple::riscv64:
2167 case llvm::Triple::riscv32be:
2168 case llvm::Triple::riscv64be:
2169 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2170 case llvm::Triple::loongarch32:
2171 case llvm::Triple::loongarch64:
2172 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2173 TheCall);
2174 case llvm::Triple::wasm32:
2175 case llvm::Triple::wasm64:
2176 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2177 case llvm::Triple::nvptx:
2178 case llvm::Triple::nvptx64:
2179 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2180 }
2181}
2182
2184 return T->isDependentType() ||
2185 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2186}
2187
2188// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2189// not a valid type, emit an error message and return true. Otherwise return
2190// false.
2191static bool
2194 int ArgOrdinal) {
2195 clang::QualType EltTy =
2196 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2197 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2198 : ArgTy;
2199
2200 switch (ArgTyRestr) {
2202 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2203 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2204 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2205 << ArgTy;
2206 }
2207 break;
2209 if (!EltTy->isRealFloatingType()) {
2210 // FIXME: make diagnostic's wording correct for matrices
2211 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2212 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2213 << /* floating-point */ 1 << ArgTy;
2214 }
2215 break;
2217 if (!EltTy->isIntegerType()) {
2218 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2219 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2220 << /* no fp */ 0 << ArgTy;
2221 }
2222 break;
2224 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2225 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2226 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2227 << /* or fp */ 1 << ArgTy;
2228 }
2229 break;
2230 }
2231
2232 return false;
2233}
2234
2235/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2236/// This checks that the target supports the builtin and that the string
2237/// argument is constant and valid.
2238static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2239 const TargetInfo *AuxTI, unsigned BuiltinID) {
2240 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2241 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2242 "Expecting __builtin_cpu_...");
2243
2244 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2245 const TargetInfo *TheTI = &TI;
2246 auto SupportsBI = [=](const TargetInfo *TInfo) {
2247 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2248 (!IsCPUSupports && TInfo->supportsCpuIs()));
2249 };
2250 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2251 TheTI = AuxTI;
2252
2253 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2254 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2255 return S.Diag(TheCall->getBeginLoc(),
2256 TI.getTriple().isOSAIX()
2257 ? diag::err_builtin_aix_os_unsupported
2258 : diag::err_builtin_target_unsupported)
2259 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2260
2261 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2262 // Check if the argument is a string literal.
2263 if (!isa<StringLiteral>(Arg))
2264 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2265 << Arg->getSourceRange();
2266
2267 // Check the contents of the string.
2268 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2269 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2270 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2271 << Arg->getSourceRange();
2272 return false;
2273 }
2274 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2275 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2276 << Arg->getSourceRange();
2277 return false;
2278}
2279
2280/// Checks that __builtin_bswapg was called with a single argument, which is an
2281/// unsigned integer, and overrides the return value type to the integer type.
2282static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2283 if (S.checkArgCount(TheCall, 1))
2284 return true;
2285 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2286 if (ArgRes.isInvalid())
2287 return true;
2288
2289 Expr *Arg = ArgRes.get();
2290 TheCall->setArg(0, Arg);
2291 if (Arg->isTypeDependent())
2292 return false;
2293
2294 QualType ArgTy = Arg->getType();
2295
2296 if (!ArgTy->isIntegerType()) {
2297 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2298 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2299 << ArgTy;
2300 return true;
2301 }
2302 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2303 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2304 BT->getNumBits() != 1) {
2305 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2306 << ArgTy << BT->getNumBits();
2307 return true;
2308 }
2309 }
2310 TheCall->setType(ArgTy);
2311 return false;
2312}
2313
2314/// Checks that __builtin_bitreverseg was called with a single argument, which
2315/// is an integer
2316static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2317 if (S.checkArgCount(TheCall, 1))
2318 return true;
2319 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2320 if (ArgRes.isInvalid())
2321 return true;
2322
2323 Expr *Arg = ArgRes.get();
2324 TheCall->setArg(0, Arg);
2325 if (Arg->isTypeDependent())
2326 return false;
2327
2328 QualType ArgTy = Arg->getType();
2329
2330 if (!ArgTy->isIntegerType()) {
2331 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2332 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2333 << ArgTy;
2334 return true;
2335 }
2336 TheCall->setType(ArgTy);
2337 return false;
2338}
2339
2340/// Checks that __builtin_popcountg was called with a single argument, which is
2341/// an unsigned integer.
2342static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2343 if (S.checkArgCount(TheCall, 1))
2344 return true;
2345
2346 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2347 if (ArgRes.isInvalid())
2348 return true;
2349
2350 Expr *Arg = ArgRes.get();
2351 TheCall->setArg(0, Arg);
2352
2353 QualType ArgTy = Arg->getType();
2354
2355 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2356 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2357 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2358 << ArgTy;
2359 return true;
2360 }
2361 return false;
2362}
2363
2364/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2365/// argument and return either int, bool, or the argument type.
2366static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2367 QualType ReturnType) {
2368 if (S.checkArgCount(TheCall, 1))
2369 return true;
2370
2371 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2372 if (ArgRes.isInvalid())
2373 return true;
2374
2375 Expr *Arg = ArgRes.get();
2376 TheCall->setArg(0, Arg);
2377
2378 QualType ArgTy = Arg->getType();
2379 // C23 stdbit.h functions do not permit bool or enumeration types.
2380 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2381 return S.Diag(Arg->getBeginLoc(),
2382 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2383 << 1 /*1st argument*/ << ArgTy;
2384 if (!ArgTy->isUnsignedIntegerType())
2385 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2386 << 1 /*1st argument*/ << ArgTy;
2387
2388 // For builtins returning unsigned int, verify the argument's bit width fits.
2389 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2390 // produce a count that overflows the return type.
2391 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2392 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2393 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2394 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2395 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2396 << ArgTy;
2397 }
2398
2399 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2400 return false;
2401}
2402
2403/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2404/// an unsigned integer, and an optional second argument, which is promoted to
2405/// an 'int'.
2406static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2407 if (S.checkArgCountRange(TheCall, 1, 2))
2408 return true;
2409
2410 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2411 if (Arg0Res.isInvalid())
2412 return true;
2413
2414 Expr *Arg0 = Arg0Res.get();
2415 TheCall->setArg(0, Arg0);
2416
2417 QualType Arg0Ty = Arg0->getType();
2418
2419 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2420 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2421 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2422 << Arg0Ty;
2423 return true;
2424 }
2425
2426 if (TheCall->getNumArgs() > 1) {
2427 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2428 if (Arg1Res.isInvalid())
2429 return true;
2430
2431 Expr *Arg1 = Arg1Res.get();
2432 TheCall->setArg(1, Arg1);
2433
2434 QualType Arg1Ty = Arg1->getType();
2435
2436 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2437 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2438 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2439 return true;
2440 }
2441 }
2442
2443 return false;
2444}
2445
2447 unsigned ArgIndex;
2448 bool OnlyUnsigned;
2449
2451 QualType T) {
2452 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2453 << ArgIndex << /*scalar*/ 1
2454 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2455 << /*no fp*/ 0 << T;
2456 }
2457
2458public:
2459 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2460 : ContextualImplicitConverter(/*Suppress=*/false,
2461 /*SuppressConversion=*/true),
2462 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2463
2464 bool match(QualType T) override {
2465 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2466 }
2467
2469 QualType T) override {
2470 return emitError(S, Loc, T);
2471 }
2472
2474 QualType T) override {
2475 return emitError(S, Loc, T);
2476 }
2477
2479 QualType T,
2480 QualType ConvTy) override {
2481 return emitError(S, Loc, T);
2482 }
2483
2485 QualType ConvTy) override {
2486 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2487 }
2488
2490 QualType T) override {
2491 return emitError(S, Loc, T);
2492 }
2493
2495 QualType ConvTy) override {
2496 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2497 }
2498
2500 QualType T,
2501 QualType ConvTy) override {
2502 llvm_unreachable("conversion functions are permitted");
2503 }
2504};
2505
2506/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2507/// arguments, that the first argument is an unsigned integer type, and that
2508/// the second argument is an integer type.
2509static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2510 if (S.checkArgCount(TheCall, 2))
2511 return true;
2512
2513 // First argument (value to rotate) must be unsigned integer type.
2514 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2516 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2517 if (Arg0Res.isInvalid())
2518 return true;
2519
2520 Expr *Arg0 = Arg0Res.get();
2521 TheCall->setArg(0, Arg0);
2522
2523 QualType Arg0Ty = Arg0->getType();
2524 if (!Arg0Ty->isUnsignedIntegerType())
2525 return true;
2526
2527 // Second argument (rotation count) must be integer type.
2528 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2530 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2531 if (Arg1Res.isInvalid())
2532 return true;
2533
2534 Expr *Arg1 = Arg1Res.get();
2535 TheCall->setArg(1, Arg1);
2536
2537 QualType Arg1Ty = Arg1->getType();
2538 if (!Arg1Ty->isIntegerType())
2539 return true;
2540
2541 TheCall->setType(Arg0Ty);
2542 return false;
2543}
2544
2545static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2546 unsigned Pos, bool AllowConst,
2547 bool AllowAS) {
2548 QualType MaskTy = MaskArg->getType();
2549 if (!MaskTy->isExtVectorBoolType())
2550 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2551 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2552 << MaskTy;
2553
2554 QualType PtrTy = PtrArg->getType();
2555 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2556 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2557 << Pos << "scalar pointer";
2558
2559 QualType PointeeTy = PtrTy->getPointeeType();
2560 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2561 (!AllowConst && PointeeTy.isConstQualified()) ||
2562 (!AllowAS && PointeeTy.hasAddressSpace())) {
2565 return S.Diag(PtrArg->getExprLoc(),
2566 diag::err_typecheck_convert_incompatible)
2567 << PtrTy << Target << /*different qualifiers=*/5
2568 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2569 << PtrTy << Target;
2570 }
2571 return false;
2572}
2573
2574static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2575 bool TypeDependent = false;
2576 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2577 ExprResult Converted =
2579 if (Converted.isInvalid())
2580 return true;
2581 TheCall->setArg(Arg, Converted.get());
2582 TypeDependent |= Converted.get()->isTypeDependent();
2583 }
2584
2585 if (TypeDependent)
2586 TheCall->setType(S.Context.DependentTy);
2587 return false;
2588}
2589
2591 if (S.checkArgCountRange(TheCall, 2, 3))
2592 return ExprError();
2593
2594 if (ConvertMaskedBuiltinArgs(S, TheCall))
2595 return ExprError();
2596
2597 Expr *MaskArg = TheCall->getArg(0);
2598 Expr *PtrArg = TheCall->getArg(1);
2599 if (TheCall->isTypeDependent())
2600 return TheCall;
2601
2602 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2603 TheCall->getBuiltinCallee() ==
2604 Builtin::BI__builtin_masked_load))
2605 return ExprError();
2606
2607 QualType MaskTy = MaskArg->getType();
2608 QualType PtrTy = PtrArg->getType();
2609 QualType PointeeTy = PtrTy->getPointeeType();
2610 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2611
2613 MaskVecTy->getNumElements());
2614 if (TheCall->getNumArgs() == 3) {
2615 Expr *PassThruArg = TheCall->getArg(2);
2616 QualType PassThruTy = PassThruArg->getType();
2617 if (!S.Context.hasSameType(PassThruTy, RetTy))
2618 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2619 << /* third argument */ 3 << RetTy;
2620 }
2621
2622 TheCall->setType(RetTy);
2623 return TheCall;
2624}
2625
2627 if (S.checkArgCount(TheCall, 3))
2628 return ExprError();
2629
2630 if (ConvertMaskedBuiltinArgs(S, TheCall))
2631 return ExprError();
2632
2633 Expr *MaskArg = TheCall->getArg(0);
2634 Expr *ValArg = TheCall->getArg(1);
2635 Expr *PtrArg = TheCall->getArg(2);
2636 if (TheCall->isTypeDependent())
2637 return TheCall;
2638
2639 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2640 TheCall->getBuiltinCallee() ==
2641 Builtin::BI__builtin_masked_store))
2642 return ExprError();
2643
2644 QualType MaskTy = MaskArg->getType();
2645 QualType PtrTy = PtrArg->getType();
2646 QualType ValTy = ValArg->getType();
2647 if (!ValTy->isVectorType())
2648 return ExprError(
2649 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2650 << 2 << "vector");
2651
2652 QualType PointeeTy = PtrTy->getPointeeType();
2653 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2654 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2655 MaskVecTy->getNumElements());
2656 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2657 MemoryTy.getUnqualifiedType()))
2658 return ExprError(S.Diag(TheCall->getBeginLoc(),
2659 diag::err_vec_builtin_incompatible_vector)
2660 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2661 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2662 TheCall->getArg(1)->getEndLoc()));
2663
2664 TheCall->setType(S.Context.VoidTy);
2665 return TheCall;
2666}
2667
2669 if (S.checkArgCountRange(TheCall, 3, 4))
2670 return ExprError();
2671
2672 if (ConvertMaskedBuiltinArgs(S, TheCall))
2673 return ExprError();
2674
2675 Expr *MaskArg = TheCall->getArg(0);
2676 Expr *IdxArg = TheCall->getArg(1);
2677 Expr *PtrArg = TheCall->getArg(2);
2678 if (TheCall->isTypeDependent())
2679 return TheCall;
2680
2681 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2682 /*AllowAS=*/true))
2683 return ExprError();
2684
2685 QualType IdxTy = IdxArg->getType();
2686 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2687 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2688 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2689 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2690 << IdxTy;
2691
2692 QualType MaskTy = MaskArg->getType();
2693 QualType PtrTy = PtrArg->getType();
2694 QualType PointeeTy = PtrTy->getPointeeType();
2695 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2696 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2697 return ExprError(
2698 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2700 TheCall->getBuiltinCallee())
2701 << MaskTy << IdxTy);
2702
2704 MaskVecTy->getNumElements());
2705 if (TheCall->getNumArgs() == 4) {
2706 Expr *PassThruArg = TheCall->getArg(3);
2707 QualType PassThruTy = PassThruArg->getType();
2708 if (!S.Context.hasSameType(PassThruTy, RetTy))
2709 return S.Diag(PassThruArg->getExprLoc(),
2710 diag::err_vec_masked_load_store_ptr)
2711 << /* fourth argument */ 4 << RetTy;
2712 }
2713
2714 TheCall->setType(RetTy);
2715 return TheCall;
2716}
2717
2719 if (S.checkArgCount(TheCall, 4))
2720 return ExprError();
2721
2722 if (ConvertMaskedBuiltinArgs(S, TheCall))
2723 return ExprError();
2724
2725 Expr *MaskArg = TheCall->getArg(0);
2726 Expr *IdxArg = TheCall->getArg(1);
2727 Expr *ValArg = TheCall->getArg(2);
2728 Expr *PtrArg = TheCall->getArg(3);
2729 if (TheCall->isTypeDependent())
2730 return TheCall;
2731
2732 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2733 /*AllowAS=*/true))
2734 return ExprError();
2735
2736 QualType IdxTy = IdxArg->getType();
2737 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2738 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2739 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2740 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2741 << IdxTy;
2742
2743 QualType ValTy = ValArg->getType();
2744 QualType MaskTy = MaskArg->getType();
2745 QualType PtrTy = PtrArg->getType();
2746 QualType PointeeTy = PtrTy->getPointeeType();
2747
2748 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2749 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2750 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2751 return ExprError(
2752 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2754 TheCall->getBuiltinCallee())
2755 << MaskTy << IdxTy);
2756 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2757 return ExprError(
2758 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2760 TheCall->getBuiltinCallee())
2761 << MaskTy << ValTy);
2762
2764 MaskVecTy->getNumElements());
2765 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2766 return ExprError(S.Diag(TheCall->getBeginLoc(),
2767 diag::err_vec_builtin_incompatible_vector)
2768 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2769 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2770 TheCall->getArg(1)->getEndLoc()));
2771
2772 TheCall->setType(S.Context.VoidTy);
2773 return TheCall;
2774}
2775
2777 SourceLocation Loc = TheCall->getBeginLoc();
2778 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2779 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2780
2781 if (Args.size() == 0) {
2782 S.Diag(TheCall->getBeginLoc(),
2783 diag::err_typecheck_call_too_few_args_at_least)
2784 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2785 << /*is_non_object=*/0 << TheCall->getSourceRange();
2786 return ExprError();
2787 }
2788
2789 QualType FuncT = Args[0]->getType();
2790
2791 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2792 if (Args.size() < 2) {
2793 S.Diag(TheCall->getBeginLoc(),
2794 diag::err_typecheck_call_too_few_args_at_least)
2795 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2796 << /*is_non_object=*/0 << TheCall->getSourceRange();
2797 return ExprError();
2798 }
2799
2800 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2801 QualType ObjectT = Args[1]->getType();
2802
2803 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2804 return ExprError();
2805
2806 ExprResult ObjectArg = [&]() -> ExprResult {
2807 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2808 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2809 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2810 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2811 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2812 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2813 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2814 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2815 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2816 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2817 return Args[1];
2818 }
2819
2820 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2821 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2822 // reference_wrapper;
2823 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2824 if (RD->isInStdNamespace() &&
2825 RD->getDeclName().getAsString() == "reference_wrapper") {
2826 CXXScopeSpec SS;
2827 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2828 UnqualifiedId GetID;
2829 GetID.setIdentifier(GetName, Loc);
2830
2832 S.getCurScope(), Args[1], Loc, tok::period, SS,
2833 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2834
2835 if (MemExpr.isInvalid())
2836 return ExprError();
2837
2838 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2839 }
2840 }
2841
2842 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2843 // class T and t1 does not satisfy the previous two items;
2844
2845 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2846 }();
2847
2848 if (ObjectArg.isInvalid())
2849 return ExprError();
2850
2851 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2852 tok::periodstar, ObjectArg.get(), Args[0]);
2853 if (BinOp.isInvalid())
2854 return ExprError();
2855
2856 if (MPT->isMemberDataPointer())
2857 return BinOp;
2858
2859 auto *MemCall = new (S.Context)
2861
2862 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2863 Args.drop_front(2), TheCall->getRParenLoc());
2864 }
2865 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2866 Args.drop_front(), TheCall->getRParenLoc());
2867}
2868
2869// Performs a similar job to Sema::UsualUnaryConversions, but without any
2870// implicit promotion of integral/enumeration types.
2872 // First, convert to an r-value.
2874 if (Res.isInvalid())
2875 return ExprError();
2876
2877 // Promote floating-point types.
2878 return S.UsualUnaryFPConversions(Res.get());
2879}
2880
2882 if (const auto *TyA = VecTy->getAs<VectorType>())
2883 return TyA->getElementType();
2884 if (VecTy->isSizelessVectorType())
2885 return VecTy->getSizelessVectorEltType(Context);
2886 return QualType();
2887}
2888
2890Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2891 CallExpr *TheCall) {
2892 ExprResult TheCallResult(TheCall);
2893
2894 // Find out if any arguments are required to be integer constant expressions.
2895 unsigned ICEArguments = 0;
2897 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2899 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2900
2901 // If any arguments are required to be ICE's, check and diagnose.
2902 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2903 // Skip arguments not required to be ICE's.
2904 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2905
2906 llvm::APSInt Result;
2907 // If we don't have enough arguments, continue so we can issue better
2908 // diagnostic in checkArgCount(...)
2909 if (ArgNo < TheCall->getNumArgs() &&
2910 BuiltinConstantArg(TheCall, ArgNo, Result))
2911 return true;
2912 ICEArguments &= ~(1 << ArgNo);
2913 }
2914
2915 FPOptions FPO;
2916 switch (BuiltinID) {
2917 case Builtin::BI__builtin_cpu_supports:
2918 case Builtin::BI__builtin_cpu_is:
2919 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2920 Context.getAuxTargetInfo(), BuiltinID))
2921 return ExprError();
2922 break;
2923 case Builtin::BI__builtin_cpu_init:
2924 if (!Context.getTargetInfo().supportsCpuInit()) {
2925 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2926 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2927 return ExprError();
2928 }
2929 break;
2930 case Builtin::BI__builtin___CFStringMakeConstantString:
2931 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2932 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2934 *this, BuiltinID, TheCall,
2935 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2936 return ExprError();
2937 assert(TheCall->getNumArgs() == 1 &&
2938 "Wrong # arguments to builtin CFStringMakeConstantString");
2939 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2940 return ExprError();
2941 break;
2942 case Builtin::BI__builtin_ms_va_start:
2943 case Builtin::BI__builtin_stdarg_start:
2944 case Builtin::BI__builtin_va_start:
2945 case Builtin::BI__builtin_c23_va_start:
2946 if (BuiltinVAStart(BuiltinID, TheCall))
2947 return ExprError();
2948 break;
2949 case Builtin::BI__va_start: {
2950 switch (Context.getTargetInfo().getTriple().getArch()) {
2951 case llvm::Triple::aarch64:
2952 case llvm::Triple::arm:
2953 case llvm::Triple::thumb:
2954 if (BuiltinVAStartARMMicrosoft(TheCall))
2955 return ExprError();
2956 break;
2957 default:
2958 if (BuiltinVAStart(BuiltinID, TheCall))
2959 return ExprError();
2960 break;
2961 }
2962 break;
2963 }
2964
2965 // The acquire, release, and no fence variants are ARM and AArch64 only.
2966 case Builtin::BI_interlockedbittestandset_acq:
2967 case Builtin::BI_interlockedbittestandset_rel:
2968 case Builtin::BI_interlockedbittestandset_nf:
2969 case Builtin::BI_interlockedbittestandreset_acq:
2970 case Builtin::BI_interlockedbittestandreset_rel:
2971 case Builtin::BI_interlockedbittestandreset_nf:
2973 *this, TheCall,
2974 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2975 return ExprError();
2976 break;
2977
2978 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2979 case Builtin::BI_bittest64:
2980 case Builtin::BI_bittestandcomplement64:
2981 case Builtin::BI_bittestandreset64:
2982 case Builtin::BI_bittestandset64:
2983 case Builtin::BI_interlockedbittestandreset64:
2984 case Builtin::BI_interlockedbittestandset64:
2986 *this, TheCall,
2987 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2988 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2989 return ExprError();
2990 break;
2991
2992 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2993 case Builtin::BI_interlockedbittestandreset64_acq:
2994 case Builtin::BI_interlockedbittestandreset64_rel:
2995 case Builtin::BI_interlockedbittestandreset64_nf:
2996 case Builtin::BI_interlockedbittestandset64_acq:
2997 case Builtin::BI_interlockedbittestandset64_rel:
2998 case Builtin::BI_interlockedbittestandset64_nf:
2999 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3000 return ExprError();
3001 break;
3002
3003 case Builtin::BI__builtin_set_flt_rounds:
3005 *this, TheCall,
3006 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3007 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
3008 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3009 llvm::Triple::ppc64le}))
3010 return ExprError();
3011 break;
3012
3013 case Builtin::BI__builtin_isgreater:
3014 case Builtin::BI__builtin_isgreaterequal:
3015 case Builtin::BI__builtin_isless:
3016 case Builtin::BI__builtin_islessequal:
3017 case Builtin::BI__builtin_islessgreater:
3018 case Builtin::BI__builtin_isunordered:
3019 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3020 return ExprError();
3021 break;
3022 case Builtin::BI__builtin_fpclassify:
3023 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3024 return ExprError();
3025 break;
3026 case Builtin::BI__builtin_isfpclass:
3027 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3028 return ExprError();
3029 break;
3030 case Builtin::BI__builtin_isfinite:
3031 case Builtin::BI__builtin_isinf:
3032 case Builtin::BI__builtin_isinf_sign:
3033 case Builtin::BI__builtin_isnan:
3034 case Builtin::BI__builtin_issignaling:
3035 case Builtin::BI__builtin_isnormal:
3036 case Builtin::BI__builtin_issubnormal:
3037 case Builtin::BI__builtin_iszero:
3038 case Builtin::BI__builtin_signbit:
3039 case Builtin::BI__builtin_signbitf:
3040 case Builtin::BI__builtin_signbitl:
3041 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3042 return ExprError();
3043 break;
3044 case Builtin::BI__builtin_shufflevector:
3045 return BuiltinShuffleVector(TheCall);
3046 // TheCall will be freed by the smart pointer here, but that's fine, since
3047 // BuiltinShuffleVector guts it, but then doesn't release it.
3048 case Builtin::BI__builtin_masked_load:
3049 case Builtin::BI__builtin_masked_expand_load:
3050 return BuiltinMaskedLoad(*this, TheCall);
3051 case Builtin::BI__builtin_masked_store:
3052 case Builtin::BI__builtin_masked_compress_store:
3053 return BuiltinMaskedStore(*this, TheCall);
3054 case Builtin::BI__builtin_masked_gather:
3055 return BuiltinMaskedGather(*this, TheCall);
3056 case Builtin::BI__builtin_masked_scatter:
3057 return BuiltinMaskedScatter(*this, TheCall);
3058 case Builtin::BI__builtin_invoke:
3059 return BuiltinInvoke(*this, TheCall);
3060 case Builtin::BI__builtin_prefetch:
3061 if (BuiltinPrefetch(TheCall))
3062 return ExprError();
3063 break;
3064 case Builtin::BI__builtin_alloca_with_align:
3065 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3066 if (BuiltinAllocaWithAlign(TheCall))
3067 return ExprError();
3068 [[fallthrough]];
3069 case Builtin::BI__builtin_alloca:
3070 case Builtin::BI__builtin_alloca_uninitialized:
3071 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3072 << TheCall->getDirectCallee();
3073 if (getLangOpts().OpenCL) {
3074 builtinAllocaAddrSpace(*this, TheCall);
3075 }
3076 break;
3077 case Builtin::BI__builtin_infer_alloc_token:
3078 if (checkBuiltinInferAllocToken(*this, TheCall))
3079 return ExprError();
3080 break;
3081 case Builtin::BI__arithmetic_fence:
3082 if (BuiltinArithmeticFence(TheCall))
3083 return ExprError();
3084 break;
3085 case Builtin::BI__assume:
3086 case Builtin::BI__builtin_assume:
3087 if (BuiltinAssume(TheCall))
3088 return ExprError();
3089 break;
3090 case Builtin::BI__builtin_assume_aligned:
3091 if (BuiltinAssumeAligned(TheCall))
3092 return ExprError();
3093 break;
3094 case Builtin::BI__builtin_dynamic_object_size:
3095 case Builtin::BI__builtin_object_size:
3096 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3097 return ExprError();
3098 break;
3099 case Builtin::BI__builtin_longjmp:
3100 if (BuiltinLongjmp(TheCall))
3101 return ExprError();
3102 break;
3103 case Builtin::BI__builtin_setjmp:
3104 if (BuiltinSetjmp(TheCall))
3105 return ExprError();
3106 break;
3107 case Builtin::BI__builtin_complex:
3108 if (BuiltinComplex(TheCall))
3109 return ExprError();
3110 break;
3111 case Builtin::BI__builtin_classify_type:
3112 case Builtin::BI__builtin_constant_p: {
3113 if (checkArgCount(TheCall, 1))
3114 return true;
3116 if (Arg.isInvalid()) return true;
3117 TheCall->setArg(0, Arg.get());
3118 TheCall->setType(Context.IntTy);
3119 break;
3120 }
3121 case Builtin::BI__builtin_launder:
3122 return BuiltinLaunder(*this, TheCall);
3123 case Builtin::BI__builtin_is_within_lifetime:
3124 return BuiltinIsWithinLifetime(*this, TheCall);
3125 case Builtin::BI__builtin_trivially_relocate:
3126 return BuiltinTriviallyRelocate(*this, TheCall);
3127
3128 case Builtin::BI__sync_fetch_and_add:
3129 case Builtin::BI__sync_fetch_and_add_1:
3130 case Builtin::BI__sync_fetch_and_add_2:
3131 case Builtin::BI__sync_fetch_and_add_4:
3132 case Builtin::BI__sync_fetch_and_add_8:
3133 case Builtin::BI__sync_fetch_and_add_16:
3134 case Builtin::BI__sync_fetch_and_sub:
3135 case Builtin::BI__sync_fetch_and_sub_1:
3136 case Builtin::BI__sync_fetch_and_sub_2:
3137 case Builtin::BI__sync_fetch_and_sub_4:
3138 case Builtin::BI__sync_fetch_and_sub_8:
3139 case Builtin::BI__sync_fetch_and_sub_16:
3140 case Builtin::BI__sync_fetch_and_or:
3141 case Builtin::BI__sync_fetch_and_or_1:
3142 case Builtin::BI__sync_fetch_and_or_2:
3143 case Builtin::BI__sync_fetch_and_or_4:
3144 case Builtin::BI__sync_fetch_and_or_8:
3145 case Builtin::BI__sync_fetch_and_or_16:
3146 case Builtin::BI__sync_fetch_and_and:
3147 case Builtin::BI__sync_fetch_and_and_1:
3148 case Builtin::BI__sync_fetch_and_and_2:
3149 case Builtin::BI__sync_fetch_and_and_4:
3150 case Builtin::BI__sync_fetch_and_and_8:
3151 case Builtin::BI__sync_fetch_and_and_16:
3152 case Builtin::BI__sync_fetch_and_xor:
3153 case Builtin::BI__sync_fetch_and_xor_1:
3154 case Builtin::BI__sync_fetch_and_xor_2:
3155 case Builtin::BI__sync_fetch_and_xor_4:
3156 case Builtin::BI__sync_fetch_and_xor_8:
3157 case Builtin::BI__sync_fetch_and_xor_16:
3158 case Builtin::BI__sync_fetch_and_nand:
3159 case Builtin::BI__sync_fetch_and_nand_1:
3160 case Builtin::BI__sync_fetch_and_nand_2:
3161 case Builtin::BI__sync_fetch_and_nand_4:
3162 case Builtin::BI__sync_fetch_and_nand_8:
3163 case Builtin::BI__sync_fetch_and_nand_16:
3164 case Builtin::BI__sync_add_and_fetch:
3165 case Builtin::BI__sync_add_and_fetch_1:
3166 case Builtin::BI__sync_add_and_fetch_2:
3167 case Builtin::BI__sync_add_and_fetch_4:
3168 case Builtin::BI__sync_add_and_fetch_8:
3169 case Builtin::BI__sync_add_and_fetch_16:
3170 case Builtin::BI__sync_sub_and_fetch:
3171 case Builtin::BI__sync_sub_and_fetch_1:
3172 case Builtin::BI__sync_sub_and_fetch_2:
3173 case Builtin::BI__sync_sub_and_fetch_4:
3174 case Builtin::BI__sync_sub_and_fetch_8:
3175 case Builtin::BI__sync_sub_and_fetch_16:
3176 case Builtin::BI__sync_and_and_fetch:
3177 case Builtin::BI__sync_and_and_fetch_1:
3178 case Builtin::BI__sync_and_and_fetch_2:
3179 case Builtin::BI__sync_and_and_fetch_4:
3180 case Builtin::BI__sync_and_and_fetch_8:
3181 case Builtin::BI__sync_and_and_fetch_16:
3182 case Builtin::BI__sync_or_and_fetch:
3183 case Builtin::BI__sync_or_and_fetch_1:
3184 case Builtin::BI__sync_or_and_fetch_2:
3185 case Builtin::BI__sync_or_and_fetch_4:
3186 case Builtin::BI__sync_or_and_fetch_8:
3187 case Builtin::BI__sync_or_and_fetch_16:
3188 case Builtin::BI__sync_xor_and_fetch:
3189 case Builtin::BI__sync_xor_and_fetch_1:
3190 case Builtin::BI__sync_xor_and_fetch_2:
3191 case Builtin::BI__sync_xor_and_fetch_4:
3192 case Builtin::BI__sync_xor_and_fetch_8:
3193 case Builtin::BI__sync_xor_and_fetch_16:
3194 case Builtin::BI__sync_nand_and_fetch:
3195 case Builtin::BI__sync_nand_and_fetch_1:
3196 case Builtin::BI__sync_nand_and_fetch_2:
3197 case Builtin::BI__sync_nand_and_fetch_4:
3198 case Builtin::BI__sync_nand_and_fetch_8:
3199 case Builtin::BI__sync_nand_and_fetch_16:
3200 case Builtin::BI__sync_val_compare_and_swap:
3201 case Builtin::BI__sync_val_compare_and_swap_1:
3202 case Builtin::BI__sync_val_compare_and_swap_2:
3203 case Builtin::BI__sync_val_compare_and_swap_4:
3204 case Builtin::BI__sync_val_compare_and_swap_8:
3205 case Builtin::BI__sync_val_compare_and_swap_16:
3206 case Builtin::BI__sync_bool_compare_and_swap:
3207 case Builtin::BI__sync_bool_compare_and_swap_1:
3208 case Builtin::BI__sync_bool_compare_and_swap_2:
3209 case Builtin::BI__sync_bool_compare_and_swap_4:
3210 case Builtin::BI__sync_bool_compare_and_swap_8:
3211 case Builtin::BI__sync_bool_compare_and_swap_16:
3212 case Builtin::BI__sync_lock_test_and_set:
3213 case Builtin::BI__sync_lock_test_and_set_1:
3214 case Builtin::BI__sync_lock_test_and_set_2:
3215 case Builtin::BI__sync_lock_test_and_set_4:
3216 case Builtin::BI__sync_lock_test_and_set_8:
3217 case Builtin::BI__sync_lock_test_and_set_16:
3218 case Builtin::BI__sync_lock_release:
3219 case Builtin::BI__sync_lock_release_1:
3220 case Builtin::BI__sync_lock_release_2:
3221 case Builtin::BI__sync_lock_release_4:
3222 case Builtin::BI__sync_lock_release_8:
3223 case Builtin::BI__sync_lock_release_16:
3224 case Builtin::BI__sync_swap:
3225 case Builtin::BI__sync_swap_1:
3226 case Builtin::BI__sync_swap_2:
3227 case Builtin::BI__sync_swap_4:
3228 case Builtin::BI__sync_swap_8:
3229 case Builtin::BI__sync_swap_16:
3230 return BuiltinAtomicOverloaded(TheCallResult);
3231 case Builtin::BI__sync_synchronize:
3232 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3233 << TheCall->getCallee()->getSourceRange();
3234 break;
3235 case Builtin::BI__builtin_nontemporal_load:
3236 case Builtin::BI__builtin_nontemporal_store:
3237 return BuiltinNontemporalOverloaded(TheCallResult);
3238 case Builtin::BI__builtin_memcpy_inline: {
3239 clang::Expr *SizeOp = TheCall->getArg(2);
3240 // We warn about copying to or from `nullptr` pointers when `size` is
3241 // greater than 0. When `size` is value dependent we cannot evaluate its
3242 // value so we bail out.
3243 if (SizeOp->isValueDependent())
3244 break;
3245 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3246 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3247 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3248 }
3249 break;
3250 }
3251 case Builtin::BI__builtin_memset_inline: {
3252 clang::Expr *SizeOp = TheCall->getArg(2);
3253 // We warn about filling to `nullptr` pointers when `size` is greater than
3254 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3255 // out.
3256 if (SizeOp->isValueDependent())
3257 break;
3258 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3259 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3260 break;
3261 }
3262#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3263 case Builtin::BI##ID: \
3264 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3265#include "clang/Basic/Builtins.inc"
3266 case Builtin::BI__annotation:
3267 if (BuiltinMSVCAnnotation(*this, TheCall))
3268 return ExprError();
3269 break;
3270 case Builtin::BI__builtin_annotation:
3271 if (BuiltinAnnotation(*this, TheCall))
3272 return ExprError();
3273 break;
3274 case Builtin::BI__builtin_addressof:
3275 if (BuiltinAddressof(*this, TheCall))
3276 return ExprError();
3277 break;
3278 case Builtin::BI__builtin_function_start:
3279 if (BuiltinFunctionStart(*this, TheCall))
3280 return ExprError();
3281 break;
3282 case Builtin::BI__builtin_is_aligned:
3283 case Builtin::BI__builtin_align_up:
3284 case Builtin::BI__builtin_align_down:
3285 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3286 return ExprError();
3287 break;
3288 case Builtin::BI__builtin_add_overflow:
3289 case Builtin::BI__builtin_sub_overflow:
3290 case Builtin::BI__builtin_mul_overflow:
3291 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3292 return ExprError();
3293 break;
3294 case Builtin::BI__builtin_operator_new:
3295 case Builtin::BI__builtin_operator_delete: {
3296 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3297 ExprResult Res =
3298 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3299 return Res;
3300 }
3301 case Builtin::BI__builtin_dump_struct:
3302 return BuiltinDumpStruct(*this, TheCall);
3303 case Builtin::BI__builtin_expect_with_probability: {
3304 // We first want to ensure we are called with 3 arguments
3305 if (checkArgCount(TheCall, 3))
3306 return ExprError();
3307 // then check probability is constant float in range [0.0, 1.0]
3308 const Expr *ProbArg = TheCall->getArg(2);
3309 SmallVector<PartialDiagnosticAt, 8> Notes;
3310 Expr::EvalResult Eval;
3311 Eval.Diag = &Notes;
3312 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3313 !Eval.Val.isFloat()) {
3314 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3315 << ProbArg->getSourceRange();
3316 for (const PartialDiagnosticAt &PDiag : Notes)
3317 Diag(PDiag.first, PDiag.second);
3318 return ExprError();
3319 }
3320 llvm::APFloat Probability = Eval.Val.getFloat();
3321 bool LoseInfo = false;
3322 Probability.convert(llvm::APFloat::IEEEdouble(),
3323 llvm::RoundingMode::Dynamic, &LoseInfo);
3324 if (!(Probability >= llvm::APFloat(0.0) &&
3325 Probability <= llvm::APFloat(1.0))) {
3326 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3327 << ProbArg->getSourceRange();
3328 return ExprError();
3329 }
3330 break;
3331 }
3332 case Builtin::BI__builtin_preserve_access_index:
3333 if (BuiltinPreserveAI(*this, TheCall))
3334 return ExprError();
3335 break;
3336 case Builtin::BI__builtin_call_with_static_chain:
3337 if (BuiltinCallWithStaticChain(*this, TheCall))
3338 return ExprError();
3339 break;
3340 case Builtin::BI__exception_code:
3341 case Builtin::BI_exception_code:
3342 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3343 diag::err_seh___except_block))
3344 return ExprError();
3345 break;
3346 case Builtin::BI__exception_info:
3347 case Builtin::BI_exception_info:
3348 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3349 diag::err_seh___except_filter))
3350 return ExprError();
3351 break;
3352 case Builtin::BI__GetExceptionInfo:
3353 if (checkArgCount(TheCall, 1))
3354 return ExprError();
3355
3357 TheCall->getBeginLoc(),
3358 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3359 TheCall))
3360 return ExprError();
3361
3362 TheCall->setType(Context.VoidPtrTy);
3363 break;
3364 case Builtin::BIaddressof:
3365 case Builtin::BI__addressof:
3366 case Builtin::BIforward:
3367 case Builtin::BIforward_like:
3368 case Builtin::BImove:
3369 case Builtin::BImove_if_noexcept:
3370 case Builtin::BIas_const: {
3371 // These are all expected to be of the form
3372 // T &/&&/* f(U &/&&)
3373 // where T and U only differ in qualification.
3374 if (checkArgCount(TheCall, 1))
3375 return ExprError();
3376 QualType Param = FDecl->getParamDecl(0)->getType();
3377 QualType Result = FDecl->getReturnType();
3378 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3379 BuiltinID == Builtin::BI__addressof;
3380 if (!(Param->isReferenceType() &&
3381 (ReturnsPointer ? Result->isAnyPointerType()
3382 : Result->isReferenceType()) &&
3383 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3384 Result->getPointeeType()))) {
3385 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3386 << FDecl;
3387 return ExprError();
3388 }
3389 break;
3390 }
3391 case Builtin::BI__builtin_ptrauth_strip:
3392 return PointerAuthStrip(*this, TheCall);
3393 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3394 return PointerAuthBlendDiscriminator(*this, TheCall);
3395 case Builtin::BI__builtin_ptrauth_sign_constant:
3396 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3397 /*RequireConstant=*/true);
3398 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3399 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3400 /*RequireConstant=*/false);
3401 case Builtin::BI__builtin_ptrauth_auth:
3402 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3403 /*RequireConstant=*/false);
3404 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3405 return PointerAuthSignGenericData(*this, TheCall);
3406 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3407 return PointerAuthAuthAndResign(*this, TheCall);
3408 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3409 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3410 case Builtin::BI__builtin_ptrauth_string_discriminator:
3411 return PointerAuthStringDiscriminator(*this, TheCall);
3412
3413 case Builtin::BI__builtin_get_vtable_pointer:
3414 return GetVTablePointer(*this, TheCall);
3415
3416 // OpenCL v2.0, s6.13.16 - Pipe functions
3417 case Builtin::BIread_pipe:
3418 case Builtin::BIwrite_pipe:
3419 // Since those two functions are declared with var args, we need a semantic
3420 // check for the argument.
3421 if (OpenCL().checkBuiltinRWPipe(TheCall))
3422 return ExprError();
3423 break;
3424 case Builtin::BIreserve_read_pipe:
3425 case Builtin::BIreserve_write_pipe:
3426 case Builtin::BIwork_group_reserve_read_pipe:
3427 case Builtin::BIwork_group_reserve_write_pipe:
3428 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3429 return ExprError();
3430 break;
3431 case Builtin::BIsub_group_reserve_read_pipe:
3432 case Builtin::BIsub_group_reserve_write_pipe:
3433 if (OpenCL().checkSubgroupExt(TheCall) ||
3434 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3435 return ExprError();
3436 break;
3437 case Builtin::BIcommit_read_pipe:
3438 case Builtin::BIcommit_write_pipe:
3439 case Builtin::BIwork_group_commit_read_pipe:
3440 case Builtin::BIwork_group_commit_write_pipe:
3441 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3442 return ExprError();
3443 break;
3444 case Builtin::BIsub_group_commit_read_pipe:
3445 case Builtin::BIsub_group_commit_write_pipe:
3446 if (OpenCL().checkSubgroupExt(TheCall) ||
3447 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3448 return ExprError();
3449 break;
3450 case Builtin::BIget_pipe_num_packets:
3451 case Builtin::BIget_pipe_max_packets:
3452 if (OpenCL().checkBuiltinPipePackets(TheCall))
3453 return ExprError();
3454 break;
3455 case Builtin::BIto_global:
3456 case Builtin::BIto_local:
3457 case Builtin::BIto_private:
3458 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3459 return ExprError();
3460 break;
3461 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3462 case Builtin::BIenqueue_kernel:
3463 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3464 return ExprError();
3465 break;
3466 case Builtin::BIget_kernel_work_group_size:
3467 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3468 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3469 return ExprError();
3470 break;
3471 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3472 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3473 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3474 return ExprError();
3475 break;
3476 case Builtin::BI__builtin_os_log_format:
3477 Cleanup.setExprNeedsCleanups(true);
3478 [[fallthrough]];
3479 case Builtin::BI__builtin_os_log_format_buffer_size:
3480 if (BuiltinOSLogFormat(TheCall))
3481 return ExprError();
3482 break;
3483 case Builtin::BI__builtin_frame_address:
3484 case Builtin::BI__builtin_return_address: {
3485 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3486 return ExprError();
3487
3488 // -Wframe-address warning if non-zero passed to builtin
3489 // return/frame address.
3490 Expr::EvalResult Result;
3491 if (!TheCall->getArg(0)->isValueDependent() &&
3492 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3493 Result.Val.getInt() != 0)
3494 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3495 << ((BuiltinID == Builtin::BI__builtin_return_address)
3496 ? "__builtin_return_address"
3497 : "__builtin_frame_address")
3498 << TheCall->getSourceRange();
3499 break;
3500 }
3501
3502 case Builtin::BI__builtin_nondeterministic_value: {
3503 if (BuiltinNonDeterministicValue(TheCall))
3504 return ExprError();
3505 break;
3506 }
3507
3508 // __builtin_elementwise_abs restricts the element type to signed integers or
3509 // floating point types only.
3510 case Builtin::BI__builtin_elementwise_abs:
3513 return ExprError();
3514 break;
3515
3516 // These builtins restrict the element type to floating point
3517 // types only.
3518 case Builtin::BI__builtin_elementwise_acos:
3519 case Builtin::BI__builtin_elementwise_asin:
3520 case Builtin::BI__builtin_elementwise_atan:
3521 case Builtin::BI__builtin_elementwise_ceil:
3522 case Builtin::BI__builtin_elementwise_cos:
3523 case Builtin::BI__builtin_elementwise_cosh:
3524 case Builtin::BI__builtin_elementwise_exp:
3525 case Builtin::BI__builtin_elementwise_exp2:
3526 case Builtin::BI__builtin_elementwise_exp10:
3527 case Builtin::BI__builtin_elementwise_floor:
3528 case Builtin::BI__builtin_elementwise_log:
3529 case Builtin::BI__builtin_elementwise_log2:
3530 case Builtin::BI__builtin_elementwise_log10:
3531 case Builtin::BI__builtin_elementwise_roundeven:
3532 case Builtin::BI__builtin_elementwise_round:
3533 case Builtin::BI__builtin_elementwise_rint:
3534 case Builtin::BI__builtin_elementwise_nearbyint:
3535 case Builtin::BI__builtin_elementwise_sin:
3536 case Builtin::BI__builtin_elementwise_sinh:
3537 case Builtin::BI__builtin_elementwise_sqrt:
3538 case Builtin::BI__builtin_elementwise_tan:
3539 case Builtin::BI__builtin_elementwise_tanh:
3540 case Builtin::BI__builtin_elementwise_trunc:
3541 case Builtin::BI__builtin_elementwise_canonicalize:
3544 return ExprError();
3545 break;
3546 case Builtin::BI__builtin_elementwise_fma:
3547 if (BuiltinElementwiseTernaryMath(TheCall))
3548 return ExprError();
3549 break;
3550
3551 case Builtin::BI__builtin_elementwise_ldexp: {
3552 if (checkArgCount(TheCall, 2))
3553 return ExprError();
3554
3555 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3556 if (A.isInvalid())
3557 return ExprError();
3558 QualType TyA = A.get()->getType();
3559 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3561 return ExprError();
3562
3563 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3564 if (Exp.isInvalid())
3565 return ExprError();
3566 QualType TyExp = Exp.get()->getType();
3567 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3569 2))
3570 return ExprError();
3571
3572 // Check the two arguments are either scalars or vectors of equal length.
3573 const auto *Vec0 = TyA->getAs<VectorType>();
3574 const auto *Vec1 = TyExp->getAs<VectorType>();
3575 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3576 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3577 if (Arg0Length != Arg1Length) {
3578 Diag(Exp.get()->getBeginLoc(),
3579 diag::err_typecheck_vector_lengths_not_equal)
3580 << TyA << TyExp << A.get()->getSourceRange()
3581 << Exp.get()->getSourceRange();
3582 return ExprError();
3583 }
3584
3585 TheCall->setArg(0, A.get());
3586 TheCall->setArg(1, Exp.get());
3587 TheCall->setType(TyA);
3588 break;
3589 }
3590
3591 // These builtins restrict the element type to floating point
3592 // types only, and take in two arguments.
3593 case Builtin::BI__builtin_elementwise_minnum:
3594 case Builtin::BI__builtin_elementwise_maxnum:
3595 case Builtin::BI__builtin_elementwise_minimum:
3596 case Builtin::BI__builtin_elementwise_maximum:
3597 case Builtin::BI__builtin_elementwise_minimumnum:
3598 case Builtin::BI__builtin_elementwise_maximumnum:
3599 case Builtin::BI__builtin_elementwise_atan2:
3600 case Builtin::BI__builtin_elementwise_fmod:
3601 case Builtin::BI__builtin_elementwise_pow:
3602 if (BuiltinElementwiseMath(TheCall,
3604 return ExprError();
3605 break;
3606 // These builtins restrict the element type to integer
3607 // types only.
3608 case Builtin::BI__builtin_elementwise_add_sat:
3609 case Builtin::BI__builtin_elementwise_sub_sat:
3610 if (BuiltinElementwiseMath(TheCall,
3612 return ExprError();
3613 break;
3614 case Builtin::BI__builtin_elementwise_fshl:
3615 case Builtin::BI__builtin_elementwise_fshr:
3618 return ExprError();
3619 break;
3620 case Builtin::BI__builtin_elementwise_min:
3621 case Builtin::BI__builtin_elementwise_max: {
3622 if (BuiltinElementwiseMath(TheCall))
3623 return ExprError();
3624 Expr *Arg0 = TheCall->getArg(0);
3625 Expr *Arg1 = TheCall->getArg(1);
3626 QualType Ty0 = Arg0->getType();
3627 QualType Ty1 = Arg1->getType();
3628 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3629 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3630 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3631 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3632 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3633 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3634 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3635 break;
3636 }
3637 case Builtin::BI__builtin_elementwise_popcount:
3638 case Builtin::BI__builtin_elementwise_bitreverse:
3641 return ExprError();
3642 break;
3643 case Builtin::BI__builtin_elementwise_copysign: {
3644 if (checkArgCount(TheCall, 2))
3645 return ExprError();
3646
3647 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3648 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3649 if (Magnitude.isInvalid() || Sign.isInvalid())
3650 return ExprError();
3651
3652 QualType MagnitudeTy = Magnitude.get()->getType();
3653 QualType SignTy = Sign.get()->getType();
3655 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3658 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3660 return ExprError();
3661 }
3662
3663 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3664 return Diag(Sign.get()->getBeginLoc(),
3665 diag::err_typecheck_call_different_arg_types)
3666 << MagnitudeTy << SignTy;
3667 }
3668
3669 TheCall->setArg(0, Magnitude.get());
3670 TheCall->setArg(1, Sign.get());
3671 TheCall->setType(Magnitude.get()->getType());
3672 break;
3673 }
3674 case Builtin::BI__builtin_elementwise_clzg:
3675 case Builtin::BI__builtin_elementwise_ctzg:
3676 // These builtins can be unary or binary. Note for empty calls we call the
3677 // unary checker in order to not emit an error that says the function
3678 // expects 2 arguments, which would be misleading.
3679 if (TheCall->getNumArgs() <= 1) {
3682 return ExprError();
3683 } else if (BuiltinElementwiseMath(
3685 return ExprError();
3686 break;
3687 case Builtin::BI__builtin_reduce_max:
3688 case Builtin::BI__builtin_reduce_min: {
3689 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3690 return ExprError();
3691
3692 const Expr *Arg = TheCall->getArg(0);
3693 const auto *TyA = Arg->getType()->getAs<VectorType>();
3694
3695 QualType ElTy;
3696 if (TyA)
3697 ElTy = TyA->getElementType();
3698 else if (Arg->getType()->isSizelessVectorType())
3700
3701 if (ElTy.isNull()) {
3702 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3703 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3704 << Arg->getType();
3705 return ExprError();
3706 }
3707
3708 TheCall->setType(ElTy);
3709 break;
3710 }
3711 case Builtin::BI__builtin_reduce_maximum:
3712 case Builtin::BI__builtin_reduce_minimum: {
3713 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3714 return ExprError();
3715
3716 const Expr *Arg = TheCall->getArg(0);
3717 const auto *TyA = Arg->getType()->getAs<VectorType>();
3718
3719 QualType ElTy;
3720 if (TyA)
3721 ElTy = TyA->getElementType();
3722 else if (Arg->getType()->isSizelessVectorType())
3724
3725 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3726 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3727 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3728 << Arg->getType();
3729 return ExprError();
3730 }
3731
3732 TheCall->setType(ElTy);
3733 break;
3734 }
3735
3736 // These builtins support vectors of integers only.
3737 // TODO: ADD/MUL should support floating-point types.
3738 case Builtin::BI__builtin_reduce_add:
3739 case Builtin::BI__builtin_reduce_mul:
3740 case Builtin::BI__builtin_reduce_xor:
3741 case Builtin::BI__builtin_reduce_or:
3742 case Builtin::BI__builtin_reduce_and: {
3743 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3744 return ExprError();
3745
3746 const Expr *Arg = TheCall->getArg(0);
3747
3748 QualType ElTy = getVectorElementType(Context, Arg->getType());
3749 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3750 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3751 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3752 << Arg->getType();
3753 return ExprError();
3754 }
3755
3756 TheCall->setType(ElTy);
3757 break;
3758 }
3759
3760 case Builtin::BI__builtin_reduce_assoc_fadd:
3761 case Builtin::BI__builtin_reduce_in_order_fadd: {
3762 // For in-order reductions require the user to specify the start value.
3763 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3764 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
3765 return ExprError();
3766
3767 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
3768 if (Vec.isInvalid())
3769 return ExprError();
3770
3771 TheCall->setArg(0, Vec.get());
3772
3773 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
3774 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3775 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3776 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3777 << Vec.get()->getType();
3778 return ExprError();
3779 }
3780
3781 if (TheCall->getNumArgs() == 2) {
3782 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
3783 if (StartValue.isInvalid())
3784 return ExprError();
3785
3786 if (!StartValue.get()->getType()->isRealFloatingType()) {
3787 Diag(StartValue.get()->getBeginLoc(),
3788 diag::err_builtin_invalid_arg_type)
3789 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3790 << StartValue.get()->getType();
3791 return ExprError();
3792 }
3793 TheCall->setArg(1, StartValue.get());
3794 }
3795
3796 TheCall->setType(ElTy);
3797 break;
3798 }
3799
3800 case Builtin::BI__builtin_matrix_transpose:
3801 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3802
3803 case Builtin::BI__builtin_matrix_column_major_load:
3804 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3805
3806 case Builtin::BI__builtin_matrix_column_major_store:
3807 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3808
3809 case Builtin::BI__builtin_verbose_trap:
3810 if (!checkBuiltinVerboseTrap(TheCall, *this))
3811 return ExprError();
3812 break;
3813
3814 case Builtin::BI__builtin_get_device_side_mangled_name: {
3815 auto Check = [](CallExpr *TheCall) {
3816 if (TheCall->getNumArgs() != 1)
3817 return false;
3818 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3819 if (!DRE)
3820 return false;
3821 auto *D = DRE->getDecl();
3822 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3823 return false;
3824 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3825 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3826 };
3827 if (!Check(TheCall)) {
3828 Diag(TheCall->getBeginLoc(),
3829 diag::err_hip_invalid_args_builtin_mangled_name);
3830 return ExprError();
3831 }
3832 break;
3833 }
3834 case Builtin::BI__builtin_bswapg:
3835 if (BuiltinBswapg(*this, TheCall))
3836 return ExprError();
3837 break;
3838 case Builtin::BI__builtin_bitreverseg:
3839 if (BuiltinBitreverseg(*this, TheCall))
3840 return ExprError();
3841 break;
3842 case Builtin::BI__builtin_popcountg:
3843 if (BuiltinPopcountg(*this, TheCall))
3844 return ExprError();
3845 break;
3846 case Builtin::BI__builtin_clzg:
3847 case Builtin::BI__builtin_ctzg:
3848 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3849 return ExprError();
3850 break;
3851
3852 case Builtin::BI__builtin_stdc_rotate_left:
3853 case Builtin::BI__builtin_stdc_rotate_right:
3854 if (BuiltinRotateGeneric(*this, TheCall))
3855 return ExprError();
3856 break;
3857
3858 case Builtin::BI__builtin_stdc_bit_floor:
3859 case Builtin::BI__builtin_stdc_bit_ceil:
3860 case Builtin::BIstdc_bit_floor:
3861 case Builtin::BIstdc_bit_ceil:
3862 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
3863 return ExprError();
3864 break;
3865 case Builtin::BI__builtin_stdc_has_single_bit:
3866 case Builtin::BIstdc_has_single_bit:
3867 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
3868 return ExprError();
3869 break;
3870 case Builtin::BI__builtin_stdc_leading_zeros:
3871 case Builtin::BI__builtin_stdc_leading_ones:
3872 case Builtin::BI__builtin_stdc_trailing_zeros:
3873 case Builtin::BI__builtin_stdc_trailing_ones:
3874 case Builtin::BI__builtin_stdc_first_leading_zero:
3875 case Builtin::BI__builtin_stdc_first_leading_one:
3876 case Builtin::BI__builtin_stdc_first_trailing_zero:
3877 case Builtin::BI__builtin_stdc_first_trailing_one:
3878 case Builtin::BI__builtin_stdc_count_zeros:
3879 case Builtin::BI__builtin_stdc_count_ones:
3880 case Builtin::BI__builtin_stdc_bit_width:
3881 case Builtin::BIstdc_leading_zeros:
3882 case Builtin::BIstdc_leading_ones:
3883 case Builtin::BIstdc_trailing_zeros:
3884 case Builtin::BIstdc_trailing_ones:
3885 case Builtin::BIstdc_first_leading_zero:
3886 case Builtin::BIstdc_first_leading_one:
3887 case Builtin::BIstdc_first_trailing_zero:
3888 case Builtin::BIstdc_first_trailing_one:
3889 case Builtin::BIstdc_count_zeros:
3890 case Builtin::BIstdc_count_ones:
3891 case Builtin::BIstdc_bit_width:
3892 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
3893 return ExprError();
3894 break;
3895
3896 case Builtin::BI__builtin_allow_runtime_check: {
3897 Expr *Arg = TheCall->getArg(0);
3898 // Check if the argument is a string literal.
3900 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3901 << Arg->getSourceRange();
3902 return ExprError();
3903 }
3904 break;
3905 }
3906
3907 case Builtin::BI__builtin_allow_sanitize_check: {
3908 if (checkArgCount(TheCall, 1))
3909 return ExprError();
3910
3911 Expr *Arg = TheCall->getArg(0);
3912 // Check if the argument is a string literal.
3913 const StringLiteral *SanitizerName =
3914 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
3915 if (!SanitizerName) {
3916 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3917 << Arg->getSourceRange();
3918 return ExprError();
3919 }
3920 // Validate the sanitizer name.
3921 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3922 .Cases({"address", "thread", "memory", "hwaddress",
3923 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3924 true)
3925 .Default(false)) {
3926 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
3927 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3928 << Arg->getSourceRange();
3929 return ExprError();
3930 }
3931 break;
3932 }
3933 case Builtin::BI__builtin_counted_by_ref:
3934 if (BuiltinCountedByRef(TheCall))
3935 return ExprError();
3936 break;
3937 }
3938
3939 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3940 return ExprError();
3941
3942 // Since the target specific builtins for each arch overlap, only check those
3943 // of the arch we are compiling for.
3944 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3945 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3946 assert(Context.getAuxTargetInfo() &&
3947 "Aux Target Builtin, but not an aux target?");
3948
3949 if (CheckTSBuiltinFunctionCall(
3950 *Context.getAuxTargetInfo(),
3951 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3952 return ExprError();
3953 } else {
3954 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3955 TheCall))
3956 return ExprError();
3957 }
3958 }
3959
3960 return TheCallResult;
3961}
3962
3963bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3964 llvm::APSInt Result;
3965 // We can't check the value of a dependent argument.
3966 Expr *Arg = TheCall->getArg(ArgNum);
3967 if (Arg->isTypeDependent() || Arg->isValueDependent())
3968 return false;
3969
3970 // Check constant-ness first.
3971 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3972 return true;
3973
3974 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3975 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3976 return false;
3977
3978 return Diag(TheCall->getBeginLoc(),
3979 diag::err_argument_not_contiguous_bit_field)
3980 << ArgNum << Arg->getSourceRange();
3981}
3982
3983bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3984 unsigned FirstArg, FormatStringInfo *FSI) {
3985 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3986 bool IsVariadic = false;
3987 if (const FunctionType *FnTy = D->getFunctionType())
3988 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3989 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3990 IsVariadic = BD->isVariadic();
3991 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3992 IsVariadic = OMD->isVariadic();
3993
3994 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3995 IsVariadic, FSI);
3996}
3997
3998bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3999 bool HasImplicitThisParam, bool IsVariadic,
4000 FormatStringInfo *FSI) {
4001 if (FirstArg == 0)
4003 else if (IsVariadic)
4005 else
4007 FSI->FormatIdx = FormatIdx - 1;
4008 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4009
4010 // The way the format attribute works in GCC, the implicit this argument
4011 // of member functions is counted. However, it doesn't appear in our own
4012 // lists, so decrement format_idx in that case.
4013 if (HasImplicitThisParam) {
4014 if(FSI->FormatIdx == 0)
4015 return false;
4016 --FSI->FormatIdx;
4017 if (FSI->FirstDataArg != 0)
4018 --FSI->FirstDataArg;
4019 }
4020 return true;
4021}
4022
4023/// Checks if a the given expression evaluates to null.
4024///
4025/// Returns true if the value evaluates to null.
4026static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4027 // Treat (smart) pointers constructed from nullptr as null, whether we can
4028 // const-evaluate them or not.
4029 // This must happen first: the smart pointer expr might have _Nonnull type!
4033 return true;
4034
4035 // If the expression has non-null type, it doesn't evaluate to null.
4036 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4037 if (*nullability == NullabilityKind::NonNull)
4038 return false;
4039 }
4040
4041 // As a special case, transparent unions initialized with zero are
4042 // considered null for the purposes of the nonnull attribute.
4043 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4044 UT &&
4045 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4046 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4047 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4048 Expr = ILE->getInit(0);
4049 }
4050
4051 bool Result;
4052 return (!Expr->isValueDependent() &&
4054 !Result);
4055}
4056
4058 const Expr *ArgExpr,
4059 SourceLocation CallSiteLoc) {
4060 if (CheckNonNullExpr(S, ArgExpr))
4061 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4062 S.PDiag(diag::warn_null_arg)
4063 << ArgExpr->getSourceRange());
4064}
4065
4066/// Determine whether the given type has a non-null nullability annotation.
4068 if (auto nullability = type->getNullability())
4069 return *nullability == NullabilityKind::NonNull;
4070
4071 return false;
4072}
4073
4075 const NamedDecl *FDecl,
4076 const FunctionProtoType *Proto,
4078 SourceLocation CallSiteLoc) {
4079 assert((FDecl || Proto) && "Need a function declaration or prototype");
4080
4081 // Already checked by constant evaluator.
4083 return;
4084 // Check the attributes attached to the method/function itself.
4085 llvm::SmallBitVector NonNullArgs;
4086 if (FDecl) {
4087 // Handle the nonnull attribute on the function/method declaration itself.
4088 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4089 if (!NonNull->args_size()) {
4090 // Easy case: all pointer arguments are nonnull.
4091 for (const auto *Arg : Args)
4092 if (S.isValidPointerAttrType(Arg->getType()))
4093 CheckNonNullArgument(S, Arg, CallSiteLoc);
4094 return;
4095 }
4096
4097 for (const ParamIdx &Idx : NonNull->args()) {
4098 unsigned IdxAST = Idx.getASTIndex();
4099 if (IdxAST >= Args.size())
4100 continue;
4101 if (NonNullArgs.empty())
4102 NonNullArgs.resize(Args.size());
4103 NonNullArgs.set(IdxAST);
4104 }
4105 }
4106 }
4107
4108 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4109 // Handle the nonnull attribute on the parameters of the
4110 // function/method.
4112 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4113 parms = FD->parameters();
4114 else
4115 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4116
4117 unsigned ParamIndex = 0;
4118 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4119 I != E; ++I, ++ParamIndex) {
4120 const ParmVarDecl *PVD = *I;
4121 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4122 if (NonNullArgs.empty())
4123 NonNullArgs.resize(Args.size());
4124
4125 NonNullArgs.set(ParamIndex);
4126 }
4127 }
4128 } else {
4129 // If we have a non-function, non-method declaration but no
4130 // function prototype, try to dig out the function prototype.
4131 if (!Proto) {
4132 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4133 QualType type = VD->getType().getNonReferenceType();
4134 if (auto pointerType = type->getAs<PointerType>())
4135 type = pointerType->getPointeeType();
4136 else if (auto blockType = type->getAs<BlockPointerType>())
4137 type = blockType->getPointeeType();
4138 // FIXME: data member pointers?
4139
4140 // Dig out the function prototype, if there is one.
4141 Proto = type->getAs<FunctionProtoType>();
4142 }
4143 }
4144
4145 // Fill in non-null argument information from the nullability
4146 // information on the parameter types (if we have them).
4147 if (Proto) {
4148 unsigned Index = 0;
4149 for (auto paramType : Proto->getParamTypes()) {
4150 if (isNonNullType(paramType)) {
4151 if (NonNullArgs.empty())
4152 NonNullArgs.resize(Args.size());
4153
4154 NonNullArgs.set(Index);
4155 }
4156
4157 ++Index;
4158 }
4159 }
4160 }
4161
4162 // Check for non-null arguments.
4163 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4164 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4165 if (NonNullArgs[ArgIndex])
4166 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4167 }
4168}
4169
4170void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4171 StringRef ParamName, QualType ArgTy,
4172 QualType ParamTy) {
4173
4174 // If a function accepts a pointer or reference type
4175 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4176 return;
4177
4178 // If the parameter is a pointer type, get the pointee type for the
4179 // argument too. If the parameter is a reference type, don't try to get
4180 // the pointee type for the argument.
4181 if (ParamTy->isPointerType())
4182 ArgTy = ArgTy->getPointeeType();
4183
4184 // Remove reference or pointer
4185 ParamTy = ParamTy->getPointeeType();
4186
4187 // Find expected alignment, and the actual alignment of the passed object.
4188 // getTypeAlignInChars requires complete types
4189 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4190 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4191 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4192 return;
4193
4194 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4195 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4196
4197 // If the argument is less aligned than the parameter, there is a
4198 // potential alignment issue.
4199 if (ArgAlign < ParamAlign)
4200 Diag(Loc, diag::warn_param_mismatched_alignment)
4201 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4202 << ParamName << (FDecl != nullptr) << FDecl;
4203}
4204
4205void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4206 const Expr *ThisArg,
4208 if (!FD || Args.empty())
4209 return;
4210 auto GetArgAt = [&](int Idx) -> const Expr * {
4211 if (Idx == LifetimeCaptureByAttr::Global ||
4212 Idx == LifetimeCaptureByAttr::Unknown)
4213 return nullptr;
4214 if (IsMemberFunction && Idx == 0)
4215 return ThisArg;
4216 return Args[Idx - IsMemberFunction];
4217 };
4218 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4219 unsigned ArgIdx) {
4220 if (!Attr)
4221 return;
4222
4223 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4224 for (int CapturingParamIdx : Attr->params()) {
4225 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4226 // initialization codepath.
4227 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4229 continue;
4230 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4231 CapturingEntity CE{Capturing};
4232 // Ensure that 'Captured' outlives the 'Capturing' entity.
4233 checkCaptureByLifetime(*this, CE, Captured);
4234 }
4235 };
4236 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4237 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4238 I + IsMemberFunction);
4239 // Check when the implicit object param is captured.
4240 if (IsMemberFunction) {
4241 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4242 if (!TSI)
4243 return;
4245 for (TypeLoc TL = TSI->getTypeLoc();
4246 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4247 TL = ATL.getModifiedLoc())
4248 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4249 }
4250}
4251
4253 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4254 bool IsMemberFunction, SourceLocation Loc,
4255 SourceRange Range, VariadicCallType CallType) {
4256
4257 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4258 llvm::any_of(Args, [](const Expr *E) {
4259 return E && E->isInstantiationDependent();
4260 }))
4261 return;
4262
4263 // Printf and scanf checking.
4264 llvm::SmallBitVector CheckedVarArgs;
4265 if (FDecl) {
4266 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4267 // Only create vector if there are format attributes.
4268 CheckedVarArgs.resize(Args.size());
4269 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4270 CheckedVarArgs);
4271 }
4272
4273 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4274 CheckedVarArgs.resize(Args.size());
4275 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4276 CheckedVarArgs);
4277 }
4278 }
4279
4280 // Refuse POD arguments that weren't caught by the format string
4281 // checks above.
4282 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4283 if (CallType != VariadicCallType::DoesNotApply &&
4284 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4285 unsigned NumParams = Proto ? Proto->getNumParams()
4286 : isa_and_nonnull<FunctionDecl>(FDecl)
4287 ? cast<FunctionDecl>(FDecl)->getNumParams()
4288 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4289 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4290 : 0;
4291
4292 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4293 // Args[ArgIdx] can be null in malformed code.
4294 if (const Expr *Arg = Args[ArgIdx]) {
4295 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4296 checkVariadicArgument(Arg, CallType);
4297 }
4298 }
4299 }
4300 if (FD)
4301 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4302 if (FDecl || Proto) {
4303 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4304
4305 // Type safety checking.
4306 if (FDecl) {
4307 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4308 CheckArgumentWithTypeTag(I, Args, Loc);
4309 }
4310 }
4311
4312 // Check that passed arguments match the alignment of original arguments.
4313 // Try to get the missing prototype from the declaration.
4314 if (!Proto && FDecl) {
4315 const auto *FT = FDecl->getFunctionType();
4316 if (isa_and_nonnull<FunctionProtoType>(FT))
4317 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4318 }
4319 if (Proto) {
4320 // For variadic functions, we may have more args than parameters.
4321 // For some K&R functions, we may have less args than parameters.
4322 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4323 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4324 bool IsScalableArg = false;
4325 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4326 // Args[ArgIdx] can be null in malformed code.
4327 if (const Expr *Arg = Args[ArgIdx]) {
4328 if (Arg->containsErrors())
4329 continue;
4330
4331 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4332 FDecl->hasLinkage() &&
4333 FDecl->getFormalLinkage() != Linkage::Internal &&
4335 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4336
4337 QualType ParamTy = Proto->getParamType(ArgIdx);
4338 if (ParamTy->isSizelessVectorType())
4339 IsScalableArg = true;
4340 QualType ArgTy = Arg->getType();
4341 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4342 ArgTy, ParamTy);
4343 }
4344 }
4345
4346 // If the callee has an AArch64 SME attribute to indicate that it is an
4347 // __arm_streaming function, then the caller requires SME to be available.
4350 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4351 llvm::StringMap<bool> CallerFeatureMap;
4352 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4353 if (!CallerFeatureMap.contains("sme"))
4354 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4355 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4356 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4357 }
4358 }
4359
4360 // If the call requires a streaming-mode change and has scalable vector
4361 // arguments or return values, then warn the user that the streaming and
4362 // non-streaming vector lengths may be different.
4363 // When both streaming and non-streaming vector lengths are defined and
4364 // mismatched, produce an error.
4365 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4366 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4367 (IsScalableArg || IsScalableRet)) {
4368 bool IsCalleeStreaming =
4370 bool IsCalleeStreamingCompatible =
4371 ExtInfo.AArch64SMEAttributes &
4373 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4374 if (!IsCalleeStreamingCompatible &&
4375 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4376 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4377 const LangOptions &LO = getLangOpts();
4378 unsigned VL = LO.VScaleMin * 128;
4379 unsigned SVL = LO.VScaleStreamingMin * 128;
4380 bool IsVLMismatch = VL && SVL && VL != SVL;
4381
4382 auto EmitDiag = [&](bool IsArg) {
4383 if (IsVLMismatch) {
4384 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4385 // Emit warning for streaming-compatible callers
4386 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4387 << IsArg << IsCalleeStreaming << SVL << VL;
4388 else
4389 // Emit error otherwise
4390 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4391 << IsArg << SVL << VL;
4392 } else
4393 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4394 << IsArg;
4395 };
4396
4397 if (IsScalableArg)
4398 EmitDiag(true);
4399 if (IsScalableRet)
4400 EmitDiag(false);
4401 }
4402 }
4403
4404 FunctionType::ArmStateValue CalleeArmZAState =
4406 FunctionType::ArmStateValue CalleeArmZT0State =
4408 if (CalleeArmZAState != FunctionType::ARM_None ||
4409 CalleeArmZT0State != FunctionType::ARM_None) {
4410 bool CallerHasZAState = false;
4411 bool CallerHasZT0State = false;
4412 if (CallerFD) {
4413 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4414 if (Attr && Attr->isNewZA())
4415 CallerHasZAState = true;
4416 if (Attr && Attr->isNewZT0())
4417 CallerHasZT0State = true;
4418 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4419 CallerHasZAState |=
4421 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4423 CallerHasZT0State |=
4425 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4427 }
4428 }
4429
4430 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4431 Diag(Loc, diag::err_sme_za_call_no_za_state);
4432
4433 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4434 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4435
4436 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4437 CalleeArmZT0State != FunctionType::ARM_None) {
4438 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4439 Diag(Loc, diag::note_sme_use_preserves_za);
4440 }
4441 }
4442 }
4443
4444 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4445 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4446 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4447 if (!Arg->isValueDependent()) {
4448 Expr::EvalResult Align;
4449 if (Arg->EvaluateAsInt(Align, Context)) {
4450 const llvm::APSInt &I = Align.Val.getInt();
4451 if (!I.isPowerOf2())
4452 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4453 << Arg->getSourceRange();
4454
4455 if (I > Sema::MaximumAlignment)
4456 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4457 << Arg->getSourceRange() << Sema::MaximumAlignment;
4458 }
4459 }
4460 }
4461
4462 if (FD)
4463 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4464}
4465
4466void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4467 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4468 DiagnoseUseOfDecl(Decl, Loc);
4469 }
4470}
4471
4472void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4474 const FunctionProtoType *Proto,
4475 SourceLocation Loc) {
4476 VariadicCallType CallType = Proto->isVariadic()
4479
4480 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4481 CheckArgAlignment(
4482 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4483 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4484
4485 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4486 Loc, SourceRange(), CallType);
4487}
4488
4490 const FunctionProtoType *Proto) {
4491 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4492 isa<CXXMethodDecl>(FDecl);
4493 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4494 IsMemberOperatorCall;
4495 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4496 TheCall->getCallee());
4497 Expr** Args = TheCall->getArgs();
4498 unsigned NumArgs = TheCall->getNumArgs();
4499
4500 Expr *ImplicitThis = nullptr;
4501 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4502 // If this is a call to a member operator, hide the first
4503 // argument from checkCall.
4504 // FIXME: Our choice of AST representation here is less than ideal.
4505 ImplicitThis = Args[0];
4506 ++Args;
4507 --NumArgs;
4508 } else if (IsMemberFunction && !FDecl->isStatic() &&
4510 ImplicitThis =
4511 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4512
4513 if (ImplicitThis) {
4514 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4515 // used.
4516 QualType ThisType = ImplicitThis->getType();
4517 if (!ThisType->isPointerType()) {
4518 assert(!ThisType->isReferenceType());
4519 ThisType = Context.getPointerType(ThisType);
4520 }
4521
4522 QualType ThisTypeFromDecl = Context.getPointerType(
4523 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4524
4525 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4526 ThisTypeFromDecl);
4527 }
4528
4529 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4530 IsMemberFunction, TheCall->getRParenLoc(),
4531 TheCall->getCallee()->getSourceRange(), CallType);
4532
4533 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4534 // None of the checks below are needed for functions that don't have
4535 // simple names (e.g., C++ conversion functions).
4536 if (!FnInfo)
4537 return false;
4538
4539 // Enforce TCB except for builtin calls, which are always allowed.
4540 if (FDecl->getBuiltinID() == 0)
4541 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4542
4543 CheckAbsoluteValueFunction(TheCall, FDecl);
4544 CheckMaxUnsignedZero(TheCall, FDecl);
4545 CheckInfNaNFunction(TheCall, FDecl);
4546
4547 if (getLangOpts().ObjC)
4548 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4549
4550 unsigned CMId = FDecl->getMemoryFunctionKind();
4551
4552 // Handle memory setting and copying functions.
4553 switch (CMId) {
4554 case 0:
4555 return false;
4556 case Builtin::BIstrlcpy: // fallthrough
4557 case Builtin::BIstrlcat:
4558 CheckStrlcpycatArguments(TheCall, FnInfo);
4559 break;
4560 case Builtin::BIstrncat:
4561 CheckStrncatArguments(TheCall, FnInfo);
4562 break;
4563 case Builtin::BIfree:
4564 CheckFreeArguments(TheCall);
4565 break;
4566 default:
4567 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4568 }
4569
4570 return false;
4571}
4572
4573bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4574 const FunctionProtoType *Proto) {
4575 QualType Ty;
4576 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4577 Ty = V->getType().getNonReferenceType();
4578 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4579 Ty = F->getType().getNonReferenceType();
4580 else
4581 return false;
4582
4583 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4584 !Ty->isFunctionProtoType())
4585 return false;
4586
4587 VariadicCallType CallType;
4588 if (!Proto || !Proto->isVariadic()) {
4590 } else if (Ty->isBlockPointerType()) {
4591 CallType = VariadicCallType::Block;
4592 } else { // Ty->isFunctionPointerType()
4593 CallType = VariadicCallType::Function;
4594 }
4595
4596 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4597 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4598 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4599 TheCall->getCallee()->getSourceRange(), CallType);
4600
4601 return false;
4602}
4603
4604bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4605 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4606 TheCall->getCallee());
4607 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4608 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4609 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4610 TheCall->getCallee()->getSourceRange(), CallType);
4611
4612 return false;
4613}
4614
4615static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4616 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4617 return false;
4618
4619 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4620 switch (Op) {
4621 case AtomicExpr::AO__c11_atomic_init:
4622 case AtomicExpr::AO__opencl_atomic_init:
4623 llvm_unreachable("There is no ordering argument for an init");
4624
4625 case AtomicExpr::AO__c11_atomic_load:
4626 case AtomicExpr::AO__opencl_atomic_load:
4627 case AtomicExpr::AO__hip_atomic_load:
4628 case AtomicExpr::AO__atomic_load_n:
4629 case AtomicExpr::AO__atomic_load:
4630 case AtomicExpr::AO__scoped_atomic_load_n:
4631 case AtomicExpr::AO__scoped_atomic_load:
4632 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4633 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4634
4635 case AtomicExpr::AO__c11_atomic_store:
4636 case AtomicExpr::AO__opencl_atomic_store:
4637 case AtomicExpr::AO__hip_atomic_store:
4638 case AtomicExpr::AO__atomic_store:
4639 case AtomicExpr::AO__atomic_store_n:
4640 case AtomicExpr::AO__scoped_atomic_store:
4641 case AtomicExpr::AO__scoped_atomic_store_n:
4642 case AtomicExpr::AO__atomic_clear:
4643 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4644 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4645 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4646
4647 default:
4648 return true;
4649 }
4650}
4651
4652ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4654 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4655 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4656 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4657 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4658 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4659 Op);
4660}
4661
4662/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4663/// equivalents. Provide a fixit when the scope is a compile-time constant and
4664/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4665/// compare_exchange builtins differ in how they accept the desired value, so
4666/// only a warning (without a fixit) is emitted for those.
4668 MultiExprArg Args,
4670 StringRef OldName;
4671 StringRef NewName;
4672 bool CanFixIt;
4673
4674 switch (Op) {
4675#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4676 case AtomicExpr::AO__hip_atomic_##hip: \
4677 OldName = "__hip_atomic_" #hip; \
4678 NewName = "__scoped_atomic_" #scoped; \
4679 CanFixIt = true; \
4680 break;
4681 HIP_ATOMIC_FIXABLE(load, load_n)
4682 HIP_ATOMIC_FIXABLE(store, store_n)
4683 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4684 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4685 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4686 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4687 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4688 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4689 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4690 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4691#undef HIP_ATOMIC_FIXABLE
4692 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4693 OldName = "__hip_atomic_compare_exchange_weak";
4694 NewName = "__scoped_atomic_compare_exchange";
4695 CanFixIt = false;
4696 break;
4697 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4698 OldName = "__hip_atomic_compare_exchange_strong";
4699 NewName = "__scoped_atomic_compare_exchange";
4700 CanFixIt = false;
4701 break;
4702 default:
4703 llvm_unreachable("unhandled HIP atomic op");
4704 }
4705
4706 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4707 << OldName << NewName;
4708 if (!CanFixIt)
4709 return;
4710
4711 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4712
4713 Expr *Scope = Args[Args.size() - 1];
4714 std::optional<llvm::APSInt> ScopeVal =
4715 Scope->getIntegerConstantExpr(S.Context);
4716 if (!ScopeVal)
4717 return;
4718
4719 StringRef ScopeName;
4720 switch (ScopeVal->getZExtValue()) {
4722 ScopeName = "__MEMORY_SCOPE_SINGLE";
4723 break;
4725 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4726 break;
4728 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4729 break;
4731 ScopeName = "__MEMORY_SCOPE_DEVICE";
4732 break;
4734 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4735 break;
4737 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4738 break;
4739 default:
4740 return;
4741 }
4742
4744 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
4745}
4746
4748 SourceLocation RParenLoc, MultiExprArg Args,
4750 AtomicArgumentOrder ArgOrder) {
4751 // All the non-OpenCL operations take one of the following forms.
4752 // The OpenCL operations take the __c11 forms with one extra argument for
4753 // synchronization scope.
4754 enum {
4755 // C __c11_atomic_init(A *, C)
4756 Init,
4757
4758 // C __c11_atomic_load(A *, int)
4759 Load,
4760
4761 // void __atomic_load(A *, CP, int)
4762 LoadCopy,
4763
4764 // void __atomic_store(A *, CP, int)
4765 Copy,
4766
4767 // C __c11_atomic_add(A *, M, int)
4768 Arithmetic,
4769
4770 // C __atomic_exchange_n(A *, CP, int)
4771 Xchg,
4772
4773 // void __atomic_exchange(A *, C *, CP, int)
4774 GNUXchg,
4775
4776 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4777 C11CmpXchg,
4778
4779 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4780 GNUCmpXchg,
4781
4782 // bool __atomic_test_and_set(A *, int)
4783 TestAndSetByte,
4784
4785 // void __atomic_clear(A *, int)
4786 ClearByte,
4787 } Form = Init;
4788
4789 const unsigned NumForm = ClearByte + 1;
4790 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4791 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4792 // where:
4793 // C is an appropriate type,
4794 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4795 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4796 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4797 // the int parameters are for orderings.
4798
4799 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4800 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4801 "need to update code for modified forms");
4802 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4803 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4804 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4805 "need to update code for modified C11 atomics");
4806 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4807 Op <= AtomicExpr::AO__opencl_atomic_store;
4808 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4809 Op <= AtomicExpr::AO__hip_atomic_store;
4810 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4811 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4812 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4813 Op <= AtomicExpr::AO__c11_atomic_store) ||
4814 IsOpenCL;
4815 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4816 Op == AtomicExpr::AO__atomic_store_n ||
4817 Op == AtomicExpr::AO__atomic_exchange_n ||
4818 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4819 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4820 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4821 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4822 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4823 // Bit mask for extra allowed value types other than integers for atomic
4824 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4825 // allow floating point.
4826 enum ArithOpExtraValueType {
4827 AOEVT_None = 0,
4828 AOEVT_Pointer = 1,
4829 AOEVT_FP = 2,
4830 };
4831 unsigned ArithAllows = AOEVT_None;
4832
4833 switch (Op) {
4834 case AtomicExpr::AO__c11_atomic_init:
4835 case AtomicExpr::AO__opencl_atomic_init:
4836 Form = Init;
4837 break;
4838
4839 case AtomicExpr::AO__c11_atomic_load:
4840 case AtomicExpr::AO__opencl_atomic_load:
4841 case AtomicExpr::AO__hip_atomic_load:
4842 case AtomicExpr::AO__atomic_load_n:
4843 case AtomicExpr::AO__scoped_atomic_load_n:
4844 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4845 Form = Load;
4846 break;
4847
4848 case AtomicExpr::AO__atomic_load:
4849 case AtomicExpr::AO__scoped_atomic_load:
4850 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4851 Form = LoadCopy;
4852 break;
4853
4854 case AtomicExpr::AO__c11_atomic_store:
4855 case AtomicExpr::AO__opencl_atomic_store:
4856 case AtomicExpr::AO__hip_atomic_store:
4857 case AtomicExpr::AO__atomic_store:
4858 case AtomicExpr::AO__atomic_store_n:
4859 case AtomicExpr::AO__scoped_atomic_store:
4860 case AtomicExpr::AO__scoped_atomic_store_n:
4861 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4862 Form = Copy;
4863 break;
4864 case AtomicExpr::AO__atomic_fetch_add:
4865 case AtomicExpr::AO__atomic_fetch_sub:
4866 case AtomicExpr::AO__atomic_add_fetch:
4867 case AtomicExpr::AO__atomic_sub_fetch:
4868 case AtomicExpr::AO__scoped_atomic_fetch_add:
4869 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4870 case AtomicExpr::AO__scoped_atomic_add_fetch:
4871 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4872 case AtomicExpr::AO__c11_atomic_fetch_add:
4873 case AtomicExpr::AO__c11_atomic_fetch_sub:
4874 case AtomicExpr::AO__opencl_atomic_fetch_add:
4875 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4876 case AtomicExpr::AO__hip_atomic_fetch_add:
4877 case AtomicExpr::AO__hip_atomic_fetch_sub:
4878 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4879 Form = Arithmetic;
4880 break;
4881 case AtomicExpr::AO__atomic_fetch_max:
4882 case AtomicExpr::AO__atomic_fetch_min:
4883 case AtomicExpr::AO__atomic_max_fetch:
4884 case AtomicExpr::AO__atomic_min_fetch:
4885 case AtomicExpr::AO__scoped_atomic_fetch_max:
4886 case AtomicExpr::AO__scoped_atomic_fetch_min:
4887 case AtomicExpr::AO__scoped_atomic_max_fetch:
4888 case AtomicExpr::AO__scoped_atomic_min_fetch:
4889 case AtomicExpr::AO__c11_atomic_fetch_max:
4890 case AtomicExpr::AO__c11_atomic_fetch_min:
4891 case AtomicExpr::AO__opencl_atomic_fetch_max:
4892 case AtomicExpr::AO__opencl_atomic_fetch_min:
4893 case AtomicExpr::AO__hip_atomic_fetch_max:
4894 case AtomicExpr::AO__hip_atomic_fetch_min:
4895 ArithAllows = AOEVT_FP;
4896 Form = Arithmetic;
4897 break;
4898 case AtomicExpr::AO__c11_atomic_fetch_and:
4899 case AtomicExpr::AO__c11_atomic_fetch_or:
4900 case AtomicExpr::AO__c11_atomic_fetch_xor:
4901 case AtomicExpr::AO__hip_atomic_fetch_and:
4902 case AtomicExpr::AO__hip_atomic_fetch_or:
4903 case AtomicExpr::AO__hip_atomic_fetch_xor:
4904 case AtomicExpr::AO__c11_atomic_fetch_nand:
4905 case AtomicExpr::AO__opencl_atomic_fetch_and:
4906 case AtomicExpr::AO__opencl_atomic_fetch_or:
4907 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4908 case AtomicExpr::AO__atomic_fetch_and:
4909 case AtomicExpr::AO__atomic_fetch_or:
4910 case AtomicExpr::AO__atomic_fetch_xor:
4911 case AtomicExpr::AO__atomic_fetch_nand:
4912 case AtomicExpr::AO__atomic_and_fetch:
4913 case AtomicExpr::AO__atomic_or_fetch:
4914 case AtomicExpr::AO__atomic_xor_fetch:
4915 case AtomicExpr::AO__atomic_nand_fetch:
4916 case AtomicExpr::AO__atomic_fetch_uinc:
4917 case AtomicExpr::AO__atomic_fetch_udec:
4918 case AtomicExpr::AO__scoped_atomic_fetch_and:
4919 case AtomicExpr::AO__scoped_atomic_fetch_or:
4920 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4921 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4922 case AtomicExpr::AO__scoped_atomic_and_fetch:
4923 case AtomicExpr::AO__scoped_atomic_or_fetch:
4924 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4925 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4926 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4927 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4928 Form = Arithmetic;
4929 break;
4930
4931 case AtomicExpr::AO__c11_atomic_exchange:
4932 case AtomicExpr::AO__hip_atomic_exchange:
4933 case AtomicExpr::AO__opencl_atomic_exchange:
4934 case AtomicExpr::AO__atomic_exchange_n:
4935 case AtomicExpr::AO__scoped_atomic_exchange_n:
4936 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4937 Form = Xchg;
4938 break;
4939
4940 case AtomicExpr::AO__atomic_exchange:
4941 case AtomicExpr::AO__scoped_atomic_exchange:
4942 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4943 Form = GNUXchg;
4944 break;
4945
4946 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4947 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4948 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4949 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4950 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4951 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4952 Form = C11CmpXchg;
4953 break;
4954
4955 case AtomicExpr::AO__atomic_compare_exchange:
4956 case AtomicExpr::AO__atomic_compare_exchange_n:
4957 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4958 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4959 ArithAllows = AOEVT_Pointer;
4960 Form = GNUCmpXchg;
4961 break;
4962
4963 case AtomicExpr::AO__atomic_test_and_set:
4964 Form = TestAndSetByte;
4965 break;
4966
4967 case AtomicExpr::AO__atomic_clear:
4968 Form = ClearByte;
4969 break;
4970 }
4971
4972 unsigned AdjustedNumArgs = NumArgs[Form];
4973 if ((IsOpenCL || IsHIP || IsScoped) &&
4974 Op != AtomicExpr::AO__opencl_atomic_init)
4975 ++AdjustedNumArgs;
4976 // Check we have the right number of arguments.
4977 if (Args.size() < AdjustedNumArgs) {
4978 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4979 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4980 << /*is non object*/ 0 << ExprRange;
4981 return ExprError();
4982 } else if (Args.size() > AdjustedNumArgs) {
4983 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4984 diag::err_typecheck_call_too_many_args)
4985 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4986 << /*is non object*/ 0 << ExprRange;
4987 return ExprError();
4988 }
4989
4990 // Inspect the first argument of the atomic operation.
4991 Expr *Ptr = Args[0];
4993 if (ConvertedPtr.isInvalid())
4994 return ExprError();
4995
4996 Ptr = ConvertedPtr.get();
4997 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4998 if (!pointerType) {
4999 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5000 << Ptr->getType() << 0 << Ptr->getSourceRange();
5001 return ExprError();
5002 }
5003
5004 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5005 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5006 QualType ValType = AtomTy; // 'C'
5007 if (IsC11) {
5008 if (!AtomTy->isAtomicType()) {
5009 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5010 << Ptr->getType() << Ptr->getSourceRange();
5011 return ExprError();
5012 }
5013 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5015 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5016 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5017 << Ptr->getSourceRange();
5018 return ExprError();
5019 }
5020 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5021 } else if (Form != Load && Form != LoadCopy) {
5022 if (ValType.isConstQualified()) {
5023 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5024 << Ptr->getType() << Ptr->getSourceRange();
5025 return ExprError();
5026 }
5027 }
5028
5029 if (Form != TestAndSetByte && Form != ClearByte) {
5030 // Pointer to object of size zero is not allowed.
5031 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5032 diag::err_incomplete_type))
5033 return ExprError();
5034
5035 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5036 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5037 << Ptr->getType() << 1 << Ptr->getSourceRange();
5038 return ExprError();
5039 }
5040 } else {
5041 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5042 // non-const pointer type, including void* and pointers to incomplete
5043 // structs, but only access the first byte.
5044 AtomTy = Context.CharTy;
5045 AtomTy = AtomTy.withCVRQualifiers(
5046 pointerType->getPointeeType().getCVRQualifiers());
5047 QualType PointerQT = Context.getPointerType(AtomTy);
5048 pointerType = PointerQT->getAs<PointerType>();
5049 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5050 ValType = AtomTy;
5051 }
5052
5053 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5054 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5055 Diag(ExprRange.getBegin(),
5056 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5057 << 0 << Ptr->getType() << Ptr->getSourceRange();
5058 return ExprError();
5059 }
5060
5061 // For an arithmetic operation, the implied arithmetic must be well-formed.
5062 // For _n operations, the value type must also be a valid atomic type.
5063 if (Form == Arithmetic || IsN) {
5064 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5065 // trivial type errors.
5066 auto IsAllowedValueType = [&](QualType ValType,
5067 unsigned AllowedType) -> bool {
5068 bool IsX87LongDouble =
5069 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5070 &Context.getTargetInfo().getLongDoubleFormat() ==
5071 &llvm::APFloat::x87DoubleExtended();
5072 if (ValType->isIntegerType())
5073 return true;
5074 if (ValType->isPointerType())
5075 return AllowedType & AOEVT_Pointer;
5076 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5077 return false;
5078 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5079 if (IsX87LongDouble)
5080 return false;
5081 return true;
5082 };
5083 if (!IsAllowedValueType(ValType, ArithAllows)) {
5084 auto DID = ArithAllows & AOEVT_FP
5085 ? (ArithAllows & AOEVT_Pointer
5086 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5087 : diag::err_atomic_op_needs_atomic_int_or_fp)
5088 : (ArithAllows & AOEVT_Pointer
5089 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5090 : diag::err_atomic_op_needs_atomic_int);
5091 Diag(ExprRange.getBegin(), DID)
5092 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5093 return ExprError();
5094 }
5095 if (IsC11 && ValType->isPointerType() &&
5097 diag::err_incomplete_type)) {
5098 return ExprError();
5099 }
5100 }
5101
5102 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5103 !AtomTy->isScalarType()) {
5104 // For GNU atomics, require a trivially-copyable type. This is not part of
5105 // the GNU atomics specification but we enforce it for consistency with
5106 // other atomics which generally all require a trivially-copyable type. This
5107 // is because atomics just copy bits.
5108 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5109 << Ptr->getType() << Ptr->getSourceRange();
5110 return ExprError();
5111 }
5112
5113 switch (ValType.getObjCLifetime()) {
5116 // okay
5117 break;
5118
5122 // FIXME: Can this happen? By this point, ValType should be known
5123 // to be trivially copyable.
5124 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5125 << ValType << Ptr->getSourceRange();
5126 return ExprError();
5127 }
5128
5129 // All atomic operations have an overload which takes a pointer to a volatile
5130 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5131 // into the result or the other operands. Similarly atomic_load takes a
5132 // pointer to a const 'A'.
5133 ValType.removeLocalVolatile();
5134 ValType.removeLocalConst();
5135 QualType ResultType = ValType;
5136 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5137 Form == ClearByte)
5138 ResultType = Context.VoidTy;
5139 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5140 ResultType = Context.BoolTy;
5141
5142 // The type of a parameter passed 'by value'. In the GNU atomics, such
5143 // arguments are actually passed as pointers.
5144 QualType ByValType = ValType; // 'CP'
5145 bool IsPassedByAddress = false;
5146 if (!IsC11 && !IsHIP && !IsN) {
5147 ByValType = Ptr->getType();
5148 IsPassedByAddress = true;
5149 }
5150
5151 SmallVector<Expr *, 5> APIOrderedArgs;
5152 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5153 APIOrderedArgs.push_back(Args[0]);
5154 switch (Form) {
5155 case Init:
5156 case Load:
5157 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5158 break;
5159 case LoadCopy:
5160 case Copy:
5161 case Arithmetic:
5162 case Xchg:
5163 APIOrderedArgs.push_back(Args[2]); // Val1
5164 APIOrderedArgs.push_back(Args[1]); // Order
5165 break;
5166 case GNUXchg:
5167 APIOrderedArgs.push_back(Args[2]); // Val1
5168 APIOrderedArgs.push_back(Args[3]); // Val2
5169 APIOrderedArgs.push_back(Args[1]); // Order
5170 break;
5171 case C11CmpXchg:
5172 APIOrderedArgs.push_back(Args[2]); // Val1
5173 APIOrderedArgs.push_back(Args[4]); // Val2
5174 APIOrderedArgs.push_back(Args[1]); // Order
5175 APIOrderedArgs.push_back(Args[3]); // OrderFail
5176 break;
5177 case GNUCmpXchg:
5178 APIOrderedArgs.push_back(Args[2]); // Val1
5179 APIOrderedArgs.push_back(Args[4]); // Val2
5180 APIOrderedArgs.push_back(Args[5]); // Weak
5181 APIOrderedArgs.push_back(Args[1]); // Order
5182 APIOrderedArgs.push_back(Args[3]); // OrderFail
5183 break;
5184 case TestAndSetByte:
5185 case ClearByte:
5186 APIOrderedArgs.push_back(Args[1]); // Order
5187 break;
5188 }
5189 } else
5190 APIOrderedArgs.append(Args.begin(), Args.end());
5191
5192 // The first argument's non-CV pointer type is used to deduce the type of
5193 // subsequent arguments, except for:
5194 // - weak flag (always converted to bool)
5195 // - memory order (always converted to int)
5196 // - scope (always converted to int)
5197 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5198 QualType Ty;
5199 if (i < NumVals[Form] + 1) {
5200 switch (i) {
5201 case 0:
5202 // The first argument is always a pointer. It has a fixed type.
5203 // It is always dereferenced, a nullptr is undefined.
5204 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5205 // Nothing else to do: we already know all we want about this pointer.
5206 continue;
5207 case 1:
5208 // The second argument is the non-atomic operand. For arithmetic, this
5209 // is always passed by value, and for a compare_exchange it is always
5210 // passed by address. For the rest, GNU uses by-address and C11 uses
5211 // by-value.
5212 assert(Form != Load);
5213 if (Form == Arithmetic && ValType->isPointerType())
5214 Ty = Context.getPointerDiffType();
5215 else if (Form == Init || Form == Arithmetic)
5216 Ty = ValType;
5217 else if (Form == Copy || Form == Xchg) {
5218 if (IsPassedByAddress) {
5219 // The value pointer is always dereferenced, a nullptr is undefined.
5220 CheckNonNullArgument(*this, APIOrderedArgs[i],
5221 ExprRange.getBegin());
5222 }
5223 Ty = ByValType;
5224 } else {
5225 Expr *ValArg = APIOrderedArgs[i];
5226 // The value pointer is always dereferenced, a nullptr is undefined.
5227 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5229 // Keep address space of non-atomic pointer type.
5230 if (const PointerType *PtrTy =
5231 ValArg->getType()->getAs<PointerType>()) {
5232 AS = PtrTy->getPointeeType().getAddressSpace();
5233 }
5234 Ty = Context.getPointerType(
5235 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5236 }
5237 break;
5238 case 2:
5239 // The third argument to compare_exchange / GNU exchange is the desired
5240 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5241 if (IsPassedByAddress)
5242 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5243 Ty = ByValType;
5244 break;
5245 case 3:
5246 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5247 Ty = Context.BoolTy;
5248 break;
5249 }
5250 } else {
5251 // The order(s) and scope are always converted to int.
5252 Ty = Context.IntTy;
5253 }
5254
5255 InitializedEntity Entity =
5257 ExprResult Arg = APIOrderedArgs[i];
5258 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5259 if (Arg.isInvalid())
5260 return true;
5261 APIOrderedArgs[i] = Arg.get();
5262 }
5263
5264 // Permute the arguments into a 'consistent' order.
5265 SmallVector<Expr*, 5> SubExprs;
5266 SubExprs.push_back(Ptr);
5267 switch (Form) {
5268 case Init:
5269 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5270 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5271 break;
5272 case Load:
5273 case TestAndSetByte:
5274 case ClearByte:
5275 SubExprs.push_back(APIOrderedArgs[1]); // Order
5276 break;
5277 case LoadCopy:
5278 case Copy:
5279 case Arithmetic:
5280 case Xchg:
5281 SubExprs.push_back(APIOrderedArgs[2]); // Order
5282 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5283 break;
5284 case GNUXchg:
5285 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5286 SubExprs.push_back(APIOrderedArgs[3]); // Order
5287 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5288 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5289 break;
5290 case C11CmpXchg:
5291 SubExprs.push_back(APIOrderedArgs[3]); // Order
5292 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5293 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5294 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5295 break;
5296 case GNUCmpXchg:
5297 SubExprs.push_back(APIOrderedArgs[4]); // Order
5298 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5299 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5300 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5301 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5302 break;
5303 }
5304
5305 // If the memory orders are constants, check they are valid.
5306 if (SubExprs.size() >= 2 && Form != Init) {
5307 std::optional<llvm::APSInt> Success =
5308 SubExprs[1]->getIntegerConstantExpr(Context);
5309 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5310 Diag(SubExprs[1]->getBeginLoc(),
5311 diag::warn_atomic_op_has_invalid_memory_order)
5312 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5313 << SubExprs[1]->getSourceRange();
5314 }
5315 if (SubExprs.size() >= 5) {
5316 if (std::optional<llvm::APSInt> Failure =
5317 SubExprs[3]->getIntegerConstantExpr(Context)) {
5318 if (!llvm::is_contained(
5319 {llvm::AtomicOrderingCABI::relaxed,
5320 llvm::AtomicOrderingCABI::consume,
5321 llvm::AtomicOrderingCABI::acquire,
5322 llvm::AtomicOrderingCABI::seq_cst},
5323 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5324 Diag(SubExprs[3]->getBeginLoc(),
5325 diag::warn_atomic_op_has_invalid_memory_order)
5326 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5327 }
5328 }
5329 }
5330 }
5331
5332 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5333 auto *Scope = Args[Args.size() - 1];
5334 if (std::optional<llvm::APSInt> Result =
5335 Scope->getIntegerConstantExpr(Context)) {
5336 if (!ScopeModel->isValid(Result->getZExtValue()))
5337 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5338 << Scope->getSourceRange();
5339 }
5340 SubExprs.push_back(Scope);
5341 }
5342
5343 if (IsHIP)
5344 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5345
5346 AtomicExpr *AE = new (Context)
5347 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5348
5349 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5350 Op == AtomicExpr::AO__c11_atomic_store ||
5351 Op == AtomicExpr::AO__opencl_atomic_load ||
5352 Op == AtomicExpr::AO__hip_atomic_load ||
5353 Op == AtomicExpr::AO__opencl_atomic_store ||
5354 Op == AtomicExpr::AO__hip_atomic_store) &&
5355 Context.AtomicUsesUnsupportedLibcall(AE))
5356 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5357 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5358 Op == AtomicExpr::AO__opencl_atomic_load ||
5359 Op == AtomicExpr::AO__hip_atomic_load)
5360 ? 0
5361 : 1);
5362
5363 if (ValType->isBitIntType()) {
5364 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5365 return ExprError();
5366 }
5367
5368 return AE;
5369}
5370
5371/// checkBuiltinArgument - Given a call to a builtin function, perform
5372/// normal type-checking on the given argument, updating the call in
5373/// place. This is useful when a builtin function requires custom
5374/// type-checking for some of its arguments but not necessarily all of
5375/// them.
5376///
5377/// Returns true on error.
5378static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5379 FunctionDecl *Fn = E->getDirectCallee();
5380 assert(Fn && "builtin call without direct callee!");
5381
5382 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5383 InitializedEntity Entity =
5385
5386 ExprResult Arg = E->getArg(ArgIndex);
5387 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5388 if (Arg.isInvalid())
5389 return true;
5390
5391 E->setArg(ArgIndex, Arg.get());
5392 return false;
5393}
5394
5395ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5396 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5397 Expr *Callee = TheCall->getCallee();
5398 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5399 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5400
5401 // Ensure that we have at least one argument to do type inference from.
5402 if (TheCall->getNumArgs() < 1) {
5403 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5404 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5405 << Callee->getSourceRange();
5406 return ExprError();
5407 }
5408
5409 // Inspect the first argument of the atomic builtin. This should always be
5410 // a pointer type, whose element is an integral scalar or pointer type.
5411 // Because it is a pointer type, we don't have to worry about any implicit
5412 // casts here.
5413 // FIXME: We don't allow floating point scalars as input.
5414 Expr *FirstArg = TheCall->getArg(0);
5415 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5416 if (FirstArgResult.isInvalid())
5417 return ExprError();
5418 FirstArg = FirstArgResult.get();
5419 TheCall->setArg(0, FirstArg);
5420
5421 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5422 if (!pointerType) {
5423 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5424 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5425 return ExprError();
5426 }
5427
5428 QualType ValType = pointerType->getPointeeType();
5429 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5430 !ValType->isBlockPointerType()) {
5431 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5432 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5433 return ExprError();
5434 }
5435 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5436 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5437 Diag(FirstArg->getBeginLoc(),
5438 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5439 << 1 << ValType << FirstArg->getSourceRange();
5440 return ExprError();
5441 }
5442
5443 if (ValType.isConstQualified()) {
5444 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5445 << FirstArg->getType() << FirstArg->getSourceRange();
5446 return ExprError();
5447 }
5448
5449 switch (ValType.getObjCLifetime()) {
5452 // okay
5453 break;
5454
5458 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5459 << ValType << FirstArg->getSourceRange();
5460 return ExprError();
5461 }
5462
5463 // Strip any qualifiers off ValType.
5464 ValType = ValType.getUnqualifiedType();
5465
5466 // The majority of builtins return a value, but a few have special return
5467 // types, so allow them to override appropriately below.
5468 QualType ResultType = ValType;
5469
5470 // We need to figure out which concrete builtin this maps onto. For example,
5471 // __sync_fetch_and_add with a 2 byte object turns into
5472 // __sync_fetch_and_add_2.
5473#define BUILTIN_ROW(x) \
5474 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5475 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5476
5477 static const unsigned BuiltinIndices[][5] = {
5478 BUILTIN_ROW(__sync_fetch_and_add),
5479 BUILTIN_ROW(__sync_fetch_and_sub),
5480 BUILTIN_ROW(__sync_fetch_and_or),
5481 BUILTIN_ROW(__sync_fetch_and_and),
5482 BUILTIN_ROW(__sync_fetch_and_xor),
5483 BUILTIN_ROW(__sync_fetch_and_nand),
5484
5485 BUILTIN_ROW(__sync_add_and_fetch),
5486 BUILTIN_ROW(__sync_sub_and_fetch),
5487 BUILTIN_ROW(__sync_and_and_fetch),
5488 BUILTIN_ROW(__sync_or_and_fetch),
5489 BUILTIN_ROW(__sync_xor_and_fetch),
5490 BUILTIN_ROW(__sync_nand_and_fetch),
5491
5492 BUILTIN_ROW(__sync_val_compare_and_swap),
5493 BUILTIN_ROW(__sync_bool_compare_and_swap),
5494 BUILTIN_ROW(__sync_lock_test_and_set),
5495 BUILTIN_ROW(__sync_lock_release),
5496 BUILTIN_ROW(__sync_swap)
5497 };
5498#undef BUILTIN_ROW
5499
5500 // Determine the index of the size.
5501 unsigned SizeIndex;
5502 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5503 case 1: SizeIndex = 0; break;
5504 case 2: SizeIndex = 1; break;
5505 case 4: SizeIndex = 2; break;
5506 case 8: SizeIndex = 3; break;
5507 case 16: SizeIndex = 4; break;
5508 default:
5509 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5510 << FirstArg->getType() << FirstArg->getSourceRange();
5511 return ExprError();
5512 }
5513
5514 // Each of these builtins has one pointer argument, followed by some number of
5515 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5516 // that we ignore. Find out which row of BuiltinIndices to read from as well
5517 // as the number of fixed args.
5518 unsigned BuiltinID = FDecl->getBuiltinID();
5519 unsigned BuiltinIndex, NumFixed = 1;
5520 bool WarnAboutSemanticsChange = false;
5521 switch (BuiltinID) {
5522 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5523 case Builtin::BI__sync_fetch_and_add:
5524 case Builtin::BI__sync_fetch_and_add_1:
5525 case Builtin::BI__sync_fetch_and_add_2:
5526 case Builtin::BI__sync_fetch_and_add_4:
5527 case Builtin::BI__sync_fetch_and_add_8:
5528 case Builtin::BI__sync_fetch_and_add_16:
5529 BuiltinIndex = 0;
5530 break;
5531
5532 case Builtin::BI__sync_fetch_and_sub:
5533 case Builtin::BI__sync_fetch_and_sub_1:
5534 case Builtin::BI__sync_fetch_and_sub_2:
5535 case Builtin::BI__sync_fetch_and_sub_4:
5536 case Builtin::BI__sync_fetch_and_sub_8:
5537 case Builtin::BI__sync_fetch_and_sub_16:
5538 BuiltinIndex = 1;
5539 break;
5540
5541 case Builtin::BI__sync_fetch_and_or:
5542 case Builtin::BI__sync_fetch_and_or_1:
5543 case Builtin::BI__sync_fetch_and_or_2:
5544 case Builtin::BI__sync_fetch_and_or_4:
5545 case Builtin::BI__sync_fetch_and_or_8:
5546 case Builtin::BI__sync_fetch_and_or_16:
5547 BuiltinIndex = 2;
5548 break;
5549
5550 case Builtin::BI__sync_fetch_and_and:
5551 case Builtin::BI__sync_fetch_and_and_1:
5552 case Builtin::BI__sync_fetch_and_and_2:
5553 case Builtin::BI__sync_fetch_and_and_4:
5554 case Builtin::BI__sync_fetch_and_and_8:
5555 case Builtin::BI__sync_fetch_and_and_16:
5556 BuiltinIndex = 3;
5557 break;
5558
5559 case Builtin::BI__sync_fetch_and_xor:
5560 case Builtin::BI__sync_fetch_and_xor_1:
5561 case Builtin::BI__sync_fetch_and_xor_2:
5562 case Builtin::BI__sync_fetch_and_xor_4:
5563 case Builtin::BI__sync_fetch_and_xor_8:
5564 case Builtin::BI__sync_fetch_and_xor_16:
5565 BuiltinIndex = 4;
5566 break;
5567
5568 case Builtin::BI__sync_fetch_and_nand:
5569 case Builtin::BI__sync_fetch_and_nand_1:
5570 case Builtin::BI__sync_fetch_and_nand_2:
5571 case Builtin::BI__sync_fetch_and_nand_4:
5572 case Builtin::BI__sync_fetch_and_nand_8:
5573 case Builtin::BI__sync_fetch_and_nand_16:
5574 BuiltinIndex = 5;
5575 WarnAboutSemanticsChange = true;
5576 break;
5577
5578 case Builtin::BI__sync_add_and_fetch:
5579 case Builtin::BI__sync_add_and_fetch_1:
5580 case Builtin::BI__sync_add_and_fetch_2:
5581 case Builtin::BI__sync_add_and_fetch_4:
5582 case Builtin::BI__sync_add_and_fetch_8:
5583 case Builtin::BI__sync_add_and_fetch_16:
5584 BuiltinIndex = 6;
5585 break;
5586
5587 case Builtin::BI__sync_sub_and_fetch:
5588 case Builtin::BI__sync_sub_and_fetch_1:
5589 case Builtin::BI__sync_sub_and_fetch_2:
5590 case Builtin::BI__sync_sub_and_fetch_4:
5591 case Builtin::BI__sync_sub_and_fetch_8:
5592 case Builtin::BI__sync_sub_and_fetch_16:
5593 BuiltinIndex = 7;
5594 break;
5595
5596 case Builtin::BI__sync_and_and_fetch:
5597 case Builtin::BI__sync_and_and_fetch_1:
5598 case Builtin::BI__sync_and_and_fetch_2:
5599 case Builtin::BI__sync_and_and_fetch_4:
5600 case Builtin::BI__sync_and_and_fetch_8:
5601 case Builtin::BI__sync_and_and_fetch_16:
5602 BuiltinIndex = 8;
5603 break;
5604
5605 case Builtin::BI__sync_or_and_fetch:
5606 case Builtin::BI__sync_or_and_fetch_1:
5607 case Builtin::BI__sync_or_and_fetch_2:
5608 case Builtin::BI__sync_or_and_fetch_4:
5609 case Builtin::BI__sync_or_and_fetch_8:
5610 case Builtin::BI__sync_or_and_fetch_16:
5611 BuiltinIndex = 9;
5612 break;
5613
5614 case Builtin::BI__sync_xor_and_fetch:
5615 case Builtin::BI__sync_xor_and_fetch_1:
5616 case Builtin::BI__sync_xor_and_fetch_2:
5617 case Builtin::BI__sync_xor_and_fetch_4:
5618 case Builtin::BI__sync_xor_and_fetch_8:
5619 case Builtin::BI__sync_xor_and_fetch_16:
5620 BuiltinIndex = 10;
5621 break;
5622
5623 case Builtin::BI__sync_nand_and_fetch:
5624 case Builtin::BI__sync_nand_and_fetch_1:
5625 case Builtin::BI__sync_nand_and_fetch_2:
5626 case Builtin::BI__sync_nand_and_fetch_4:
5627 case Builtin::BI__sync_nand_and_fetch_8:
5628 case Builtin::BI__sync_nand_and_fetch_16:
5629 BuiltinIndex = 11;
5630 WarnAboutSemanticsChange = true;
5631 break;
5632
5633 case Builtin::BI__sync_val_compare_and_swap:
5634 case Builtin::BI__sync_val_compare_and_swap_1:
5635 case Builtin::BI__sync_val_compare_and_swap_2:
5636 case Builtin::BI__sync_val_compare_and_swap_4:
5637 case Builtin::BI__sync_val_compare_and_swap_8:
5638 case Builtin::BI__sync_val_compare_and_swap_16:
5639 BuiltinIndex = 12;
5640 NumFixed = 2;
5641 break;
5642
5643 case Builtin::BI__sync_bool_compare_and_swap:
5644 case Builtin::BI__sync_bool_compare_and_swap_1:
5645 case Builtin::BI__sync_bool_compare_and_swap_2:
5646 case Builtin::BI__sync_bool_compare_and_swap_4:
5647 case Builtin::BI__sync_bool_compare_and_swap_8:
5648 case Builtin::BI__sync_bool_compare_and_swap_16:
5649 BuiltinIndex = 13;
5650 NumFixed = 2;
5651 ResultType = Context.BoolTy;
5652 break;
5653
5654 case Builtin::BI__sync_lock_test_and_set:
5655 case Builtin::BI__sync_lock_test_and_set_1:
5656 case Builtin::BI__sync_lock_test_and_set_2:
5657 case Builtin::BI__sync_lock_test_and_set_4:
5658 case Builtin::BI__sync_lock_test_and_set_8:
5659 case Builtin::BI__sync_lock_test_and_set_16:
5660 BuiltinIndex = 14;
5661 break;
5662
5663 case Builtin::BI__sync_lock_release:
5664 case Builtin::BI__sync_lock_release_1:
5665 case Builtin::BI__sync_lock_release_2:
5666 case Builtin::BI__sync_lock_release_4:
5667 case Builtin::BI__sync_lock_release_8:
5668 case Builtin::BI__sync_lock_release_16:
5669 BuiltinIndex = 15;
5670 NumFixed = 0;
5671 ResultType = Context.VoidTy;
5672 break;
5673
5674 case Builtin::BI__sync_swap:
5675 case Builtin::BI__sync_swap_1:
5676 case Builtin::BI__sync_swap_2:
5677 case Builtin::BI__sync_swap_4:
5678 case Builtin::BI__sync_swap_8:
5679 case Builtin::BI__sync_swap_16:
5680 BuiltinIndex = 16;
5681 break;
5682 }
5683
5684 // Now that we know how many fixed arguments we expect, first check that we
5685 // have at least that many.
5686 if (TheCall->getNumArgs() < 1+NumFixed) {
5687 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5688 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5689 << Callee->getSourceRange();
5690 return ExprError();
5691 }
5692
5693 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5694 << Callee->getSourceRange();
5695
5696 if (WarnAboutSemanticsChange) {
5697 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5698 << Callee->getSourceRange();
5699 }
5700
5701 // Get the decl for the concrete builtin from this, we can tell what the
5702 // concrete integer type we should convert to is.
5703 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5704 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5705 FunctionDecl *NewBuiltinDecl;
5706 if (NewBuiltinID == BuiltinID)
5707 NewBuiltinDecl = FDecl;
5708 else {
5709 // Perform builtin lookup to avoid redeclaring it.
5710 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5711 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5712 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5713 assert(Res.getFoundDecl());
5714 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5715 if (!NewBuiltinDecl)
5716 return ExprError();
5717 }
5718
5719 // The first argument --- the pointer --- has a fixed type; we
5720 // deduce the types of the rest of the arguments accordingly. Walk
5721 // the remaining arguments, converting them to the deduced value type.
5722 for (unsigned i = 0; i != NumFixed; ++i) {
5723 ExprResult Arg = TheCall->getArg(i+1);
5724
5725 // GCC does an implicit conversion to the pointer or integer ValType. This
5726 // can fail in some cases (1i -> int**), check for this error case now.
5727 // Initialize the argument.
5728 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5729 ValType, /*consume*/ false);
5730 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5731 if (Arg.isInvalid())
5732 return ExprError();
5733
5734 // Okay, we have something that *can* be converted to the right type. Check
5735 // to see if there is a potentially weird extension going on here. This can
5736 // happen when you do an atomic operation on something like an char* and
5737 // pass in 42. The 42 gets converted to char. This is even more strange
5738 // for things like 45.123 -> char, etc.
5739 // FIXME: Do this check.
5740 TheCall->setArg(i+1, Arg.get());
5741 }
5742
5743 // Create a new DeclRefExpr to refer to the new decl.
5744 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5745 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5746 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5747 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5748
5749 // Set the callee in the CallExpr.
5750 // FIXME: This loses syntactic information.
5751 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5752 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5753 CK_BuiltinFnToFnPtr);
5754 TheCall->setCallee(PromotedCall.get());
5755
5756 // Change the result type of the call to match the original value type. This
5757 // is arbitrary, but the codegen for these builtins ins design to handle it
5758 // gracefully.
5759 TheCall->setType(ResultType);
5760
5761 // Prohibit problematic uses of bit-precise integer types with atomic
5762 // builtins. The arguments would have already been converted to the first
5763 // argument's type, so only need to check the first argument.
5764 const auto *BitIntValType = ValType->getAs<BitIntType>();
5765 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5766 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5767 return ExprError();
5768 }
5769
5770 return TheCallResult;
5771}
5772
5773ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5774 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5775 DeclRefExpr *DRE =
5777 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5778 unsigned BuiltinID = FDecl->getBuiltinID();
5779 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5780 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5781 "Unexpected nontemporal load/store builtin!");
5782 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5783 unsigned numArgs = isStore ? 2 : 1;
5784
5785 // Ensure that we have the proper number of arguments.
5786 if (checkArgCount(TheCall, numArgs))
5787 return ExprError();
5788
5789 // Inspect the last argument of the nontemporal builtin. This should always
5790 // be a pointer type, from which we imply the type of the memory access.
5791 // Because it is a pointer type, we don't have to worry about any implicit
5792 // casts here.
5793 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5794 ExprResult PointerArgResult =
5796
5797 if (PointerArgResult.isInvalid())
5798 return ExprError();
5799 PointerArg = PointerArgResult.get();
5800 TheCall->setArg(numArgs - 1, PointerArg);
5801
5802 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5803 if (!pointerType) {
5804 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5805 << PointerArg->getType() << PointerArg->getSourceRange();
5806 return ExprError();
5807 }
5808
5809 QualType ValType = pointerType->getPointeeType();
5810
5811 // Strip any qualifiers off ValType.
5812 ValType = ValType.getUnqualifiedType();
5813 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5814 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5815 !ValType->isVectorType()) {
5816 Diag(DRE->getBeginLoc(),
5817 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5818 << PointerArg->getType() << PointerArg->getSourceRange();
5819 return ExprError();
5820 }
5821
5822 if (!isStore) {
5823 TheCall->setType(ValType);
5824 return TheCallResult;
5825 }
5826
5827 ExprResult ValArg = TheCall->getArg(0);
5828 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5829 Context, ValType, /*consume*/ false);
5830 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5831 if (ValArg.isInvalid())
5832 return ExprError();
5833
5834 TheCall->setArg(0, ValArg.get());
5835 TheCall->setType(Context.VoidTy);
5836 return TheCallResult;
5837}
5838
5839/// CheckObjCString - Checks that the format string argument to the os_log()
5840/// and os_trace() functions is correct, and converts it to const char *.
5841ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5842 Arg = Arg->IgnoreParenCasts();
5843 auto *Literal = dyn_cast<StringLiteral>(Arg);
5844 if (!Literal) {
5845 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5846 Literal = ObjcLiteral->getString();
5847 }
5848 }
5849
5850 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5851 return ExprError(
5852 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5853 << Arg->getSourceRange());
5854 }
5855
5856 ExprResult Result(Literal);
5857 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5858 InitializedEntity Entity =
5860 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5861 return Result;
5862}
5863
5864/// Check that the user is calling the appropriate va_start builtin for the
5865/// target and calling convention.
5866static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5867 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5868 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5869 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5870 TT.getArch() == llvm::Triple::aarch64_32);
5871 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5872 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5873 if (IsX64 || IsAArch64) {
5874 CallingConv CC = CC_C;
5875 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5876 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5877 if (IsMSVAStart) {
5878 // Don't allow this in System V ABI functions.
5879 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5880 return S.Diag(Fn->getBeginLoc(),
5881 diag::err_ms_va_start_used_in_sysv_function);
5882 } else {
5883 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5884 // On x64 Windows, don't allow this in System V ABI functions.
5885 // (Yes, that means there's no corresponding way to support variadic
5886 // System V ABI functions on Windows.)
5887 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5888 (!IsWindowsOrUEFI && CC == CC_Win64))
5889 return S.Diag(Fn->getBeginLoc(),
5890 diag::err_va_start_used_in_wrong_abi_function)
5891 << !IsWindowsOrUEFI;
5892 }
5893 return false;
5894 }
5895
5896 if (IsMSVAStart)
5897 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5898 return false;
5899}
5900
5902 ParmVarDecl **LastParam = nullptr) {
5903 // Determine whether the current function, block, or obj-c method is variadic
5904 // and get its parameter list.
5905 bool IsVariadic = false;
5907 DeclContext *Caller = S.CurContext;
5908 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5909 IsVariadic = Block->isVariadic();
5910 Params = Block->parameters();
5911 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5912 IsVariadic = FD->isVariadic();
5913 Params = FD->parameters();
5914 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5915 IsVariadic = MD->isVariadic();
5916 // FIXME: This isn't correct for methods (results in bogus warning).
5917 Params = MD->parameters();
5918 } else if (isa<CapturedDecl>(Caller)) {
5919 // We don't support va_start in a CapturedDecl.
5920 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5921 return true;
5922 } else {
5923 // This must be some other declcontext that parses exprs.
5924 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5925 return true;
5926 }
5927
5928 if (!IsVariadic) {
5929 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5930 return true;
5931 }
5932
5933 if (LastParam)
5934 *LastParam = Params.empty() ? nullptr : Params.back();
5935
5936 return false;
5937}
5938
5939bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5940 Expr *Fn = TheCall->getCallee();
5941 if (checkVAStartABI(*this, BuiltinID, Fn))
5942 return true;
5943
5944 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5945 // This builtin requires one argument (the va_list), allows two arguments,
5946 // but diagnoses more than two arguments. e.g.,
5947 // __builtin_c23_va_start(); // error
5948 // __builtin_c23_va_start(list); // ok
5949 // __builtin_c23_va_start(list, param); // ok
5950 // __builtin_c23_va_start(list, anything, anything); // error
5951 // This differs from the GCC behavior in that they accept the last case
5952 // with a warning, but it doesn't seem like a useful behavior to allow.
5953 if (checkArgCountRange(TheCall, 1, 2))
5954 return true;
5955 } else {
5956 // In C23 mode, va_start only needs one argument. However, the builtin still
5957 // requires two arguments (which matches the behavior of the GCC builtin),
5958 // <stdarg.h> passes `0` as the second argument in C23 mode.
5959 if (checkArgCount(TheCall, 2))
5960 return true;
5961 }
5962
5963 // Type-check the first argument normally.
5964 if (checkBuiltinArgument(*this, TheCall, 0))
5965 return true;
5966
5967 // Check that the current function is variadic, and get its last parameter.
5968 ParmVarDecl *LastParam;
5969 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5970 return true;
5971
5972 // Verify that the second argument to the builtin is the last non-variadic
5973 // argument of the current function or method. In C23 mode, if the call is
5974 // not to __builtin_c23_va_start, and the second argument is an integer
5975 // constant expression with value 0, then we don't bother with this check.
5976 // For __builtin_c23_va_start, we only perform the check for the second
5977 // argument being the last argument to the current function if there is a
5978 // second argument present.
5979 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5980 TheCall->getNumArgs() < 2) {
5981 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5982 return false;
5983 }
5984
5985 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5986 if (std::optional<llvm::APSInt> Val =
5988 Val && LangOpts.C23 && *Val == 0 &&
5989 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5990 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5991 return false;
5992 }
5993
5994 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5995 // next block.
5996 QualType Type;
5997 SourceLocation ParamLoc;
5998 bool IsCRegister = false;
5999 bool SecondArgIsLastNonVariadicArgument = false;
6000 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6001 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6002 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6003
6004 Type = PV->getType();
6005 ParamLoc = PV->getLocation();
6006 IsCRegister =
6007 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6008 }
6009 }
6010
6011 if (!SecondArgIsLastNonVariadicArgument)
6012 Diag(TheCall->getArg(1)->getBeginLoc(),
6013 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6014 else if (IsCRegister || Type->isReferenceType() ||
6015 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6016 // Promotable integers are UB, but enumerations need a bit of
6017 // extra checking to see what their promotable type actually is.
6018 if (!Context.isPromotableIntegerType(Type))
6019 return false;
6020 const auto *ED = Type->getAsEnumDecl();
6021 if (!ED)
6022 return true;
6023 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6024 }()) {
6025 unsigned Reason = 0;
6026 if (Type->isReferenceType()) Reason = 1;
6027 else if (IsCRegister) Reason = 2;
6028 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6029 Diag(ParamLoc, diag::note_parameter_type) << Type;
6030 }
6031
6032 return false;
6033}
6034
6035bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6036 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6037 const LangOptions &LO = getLangOpts();
6038
6039 if (LO.CPlusPlus)
6040 return Arg->getType()
6042 .getTypePtr()
6043 ->getPointeeType()
6045
6046 // In C, allow aliasing through `char *`, this is required for AArch64 at
6047 // least.
6048 return true;
6049 };
6050
6051 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6052 // const char *named_addr);
6053
6054 Expr *Func = Call->getCallee();
6055
6056 if (Call->getNumArgs() < 3)
6057 return Diag(Call->getEndLoc(),
6058 diag::err_typecheck_call_too_few_args_at_least)
6059 << 0 /*function call*/ << 3 << Call->getNumArgs()
6060 << /*is non object*/ 0;
6061
6062 // Type-check the first argument normally.
6063 if (checkBuiltinArgument(*this, Call, 0))
6064 return true;
6065
6066 // Check that the current function is variadic.
6068 return true;
6069
6070 // __va_start on Windows does not validate the parameter qualifiers
6071
6072 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6073 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6074
6075 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6076 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6077
6078 const QualType &ConstCharPtrTy =
6079 Context.getPointerType(Context.CharTy.withConst());
6080 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6081 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6082 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6083 << 0 /* qualifier difference */
6084 << 3 /* parameter mismatch */
6085 << 2 << Arg1->getType() << ConstCharPtrTy;
6086
6087 const QualType SizeTy = Context.getSizeType();
6088 if (!Context.hasSameType(
6090 SizeTy))
6091 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6092 << Arg2->getType() << SizeTy << 1 /* different class */
6093 << 0 /* qualifier difference */
6094 << 3 /* parameter mismatch */
6095 << 3 << Arg2->getType() << SizeTy;
6096
6097 return false;
6098}
6099
6100bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6101 if (checkArgCount(TheCall, 2))
6102 return true;
6103
6104 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6105 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6106 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6107 << 1 << 0 << TheCall->getSourceRange();
6108
6109 ExprResult OrigArg0 = TheCall->getArg(0);
6110 ExprResult OrigArg1 = TheCall->getArg(1);
6111
6112 // Do standard promotions between the two arguments, returning their common
6113 // type.
6114 QualType Res = UsualArithmeticConversions(
6115 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6116 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6117 return true;
6118
6119 // Make sure any conversions are pushed back into the call; this is
6120 // type safe since unordered compare builtins are declared as "_Bool
6121 // foo(...)".
6122 TheCall->setArg(0, OrigArg0.get());
6123 TheCall->setArg(1, OrigArg1.get());
6124
6125 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6126 return false;
6127
6128 // If the common type isn't a real floating type, then the arguments were
6129 // invalid for this operation.
6130 if (Res.isNull() || !Res->isRealFloatingType())
6131 return Diag(OrigArg0.get()->getBeginLoc(),
6132 diag::err_typecheck_call_invalid_ordered_compare)
6133 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6134 << SourceRange(OrigArg0.get()->getBeginLoc(),
6135 OrigArg1.get()->getEndLoc());
6136
6137 return false;
6138}
6139
6140bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6141 unsigned BuiltinID) {
6142 if (checkArgCount(TheCall, NumArgs))
6143 return true;
6144
6145 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6146 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6147 BuiltinID == Builtin::BI__builtin_isinf ||
6148 BuiltinID == Builtin::BI__builtin_isinf_sign))
6149 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6150 << 0 << 0 << TheCall->getSourceRange();
6151
6152 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6153 BuiltinID == Builtin::BI__builtin_isunordered))
6154 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6155 << 1 << 0 << TheCall->getSourceRange();
6156
6157 bool IsFPClass = NumArgs == 2;
6158
6159 // Find out position of floating-point argument.
6160 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6161
6162 // We can count on all parameters preceding the floating-point just being int.
6163 // Try all of those.
6164 for (unsigned i = 0; i < FPArgNo; ++i) {
6165 Expr *Arg = TheCall->getArg(i);
6166
6167 if (Arg->isTypeDependent())
6168 return false;
6169
6172
6173 if (Res.isInvalid())
6174 return true;
6175 TheCall->setArg(i, Res.get());
6176 }
6177
6178 Expr *OrigArg = TheCall->getArg(FPArgNo);
6179
6180 if (OrigArg->isTypeDependent())
6181 return false;
6182
6183 // Usual Unary Conversions will convert half to float, which we want for
6184 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6185 // type how it is, but do normal L->Rvalue conversions.
6186 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6187 ExprResult Res = UsualUnaryConversions(OrigArg);
6188
6189 if (!Res.isUsable())
6190 return true;
6191 OrigArg = Res.get();
6192 } else {
6194
6195 if (!Res.isUsable())
6196 return true;
6197 OrigArg = Res.get();
6198 }
6199 TheCall->setArg(FPArgNo, OrigArg);
6200
6201 QualType VectorResultTy;
6202 QualType ElementTy = OrigArg->getType();
6203 // TODO: When all classification function are implemented with is_fpclass,
6204 // vector argument can be supported in all of them.
6205 if (ElementTy->isVectorType() && IsFPClass) {
6206 VectorResultTy = GetSignedVectorType(ElementTy);
6207 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6208 }
6209
6210 // This operation requires a non-_Complex floating-point number.
6211 if (!ElementTy->isRealFloatingType())
6212 return Diag(OrigArg->getBeginLoc(),
6213 diag::err_typecheck_call_invalid_unary_fp)
6214 << OrigArg->getType() << OrigArg->getSourceRange();
6215
6216 // __builtin_isfpclass has integer parameter that specify test mask. It is
6217 // passed in (...), so it should be analyzed completely here.
6218 if (IsFPClass)
6219 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6220 return true;
6221
6222 // TODO: enable this code to all classification functions.
6223 if (IsFPClass) {
6224 QualType ResultTy;
6225 if (!VectorResultTy.isNull())
6226 ResultTy = VectorResultTy;
6227 else
6228 ResultTy = Context.IntTy;
6229 TheCall->setType(ResultTy);
6230 }
6231
6232 return false;
6233}
6234
6235bool Sema::BuiltinComplex(CallExpr *TheCall) {
6236 if (checkArgCount(TheCall, 2))
6237 return true;
6238
6239 bool Dependent = false;
6240 for (unsigned I = 0; I != 2; ++I) {
6241 Expr *Arg = TheCall->getArg(I);
6242 QualType T = Arg->getType();
6243 if (T->isDependentType()) {
6244 Dependent = true;
6245 continue;
6246 }
6247
6248 // Despite supporting _Complex int, GCC requires a real floating point type
6249 // for the operands of __builtin_complex.
6250 if (!T->isRealFloatingType()) {
6251 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6252 << Arg->getType() << Arg->getSourceRange();
6253 }
6254
6255 ExprResult Converted = DefaultLvalueConversion(Arg);
6256 if (Converted.isInvalid())
6257 return true;
6258 TheCall->setArg(I, Converted.get());
6259 }
6260
6261 if (Dependent) {
6262 TheCall->setType(Context.DependentTy);
6263 return false;
6264 }
6265
6266 Expr *Real = TheCall->getArg(0);
6267 Expr *Imag = TheCall->getArg(1);
6268 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6269 return Diag(Real->getBeginLoc(),
6270 diag::err_typecheck_call_different_arg_types)
6271 << Real->getType() << Imag->getType()
6272 << Real->getSourceRange() << Imag->getSourceRange();
6273 }
6274
6275 TheCall->setType(Context.getComplexType(Real->getType()));
6276 return false;
6277}
6278
6279/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6280// This is declared to take (...), so we have to check everything.
6282 unsigned NumArgs = TheCall->getNumArgs();
6283 if (NumArgs < 2)
6284 return ExprError(Diag(TheCall->getEndLoc(),
6285 diag::err_typecheck_call_too_few_args_at_least)
6286 << 0 /*function call*/ << 2 << NumArgs
6287 << /*is non object*/ 0 << TheCall->getSourceRange());
6288
6289 // Determine which of the following types of shufflevector we're checking:
6290 // 1) unary, vector mask: (lhs, mask)
6291 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6292 QualType ResType = TheCall->getArg(0)->getType();
6293 unsigned NumElements = 0;
6294
6295 if (!TheCall->getArg(0)->isTypeDependent() &&
6296 !TheCall->getArg(1)->isTypeDependent()) {
6297 QualType LHSType = TheCall->getArg(0)->getType();
6298 QualType RHSType = TheCall->getArg(1)->getType();
6299
6300 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6301 return ExprError(
6302 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6303 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6304 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6305 TheCall->getArg(1)->getEndLoc()));
6306
6307 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6308 unsigned NumResElements = NumArgs - 2;
6309
6310 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6311 // with mask. If so, verify that RHS is an integer vector type with the
6312 // same number of elts as lhs.
6313 if (NumArgs == 2) {
6314 if (!RHSType->hasIntegerRepresentation() ||
6315 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6316 return ExprError(Diag(TheCall->getBeginLoc(),
6317 diag::err_vec_builtin_incompatible_vector)
6318 << TheCall->getDirectCallee()
6319 << /*isMoreThanTwoArgs*/ false
6320 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6321 TheCall->getArg(1)->getEndLoc()));
6322 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6323 return ExprError(Diag(TheCall->getBeginLoc(),
6324 diag::err_vec_builtin_incompatible_vector)
6325 << TheCall->getDirectCallee()
6326 << /*isMoreThanTwoArgs*/ false
6327 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6328 TheCall->getArg(1)->getEndLoc()));
6329 } else if (NumElements != NumResElements) {
6330 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6331 ResType = ResType->isExtVectorType()
6332 ? Context.getExtVectorType(EltType, NumResElements)
6333 : Context.getVectorType(EltType, NumResElements,
6335 }
6336 }
6337
6338 for (unsigned I = 2; I != NumArgs; ++I) {
6339 Expr *Arg = TheCall->getArg(I);
6340 if (Arg->isTypeDependent() || Arg->isValueDependent())
6341 continue;
6342
6343 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6344 if (!Result)
6345 return ExprError(Diag(TheCall->getBeginLoc(),
6346 diag::err_shufflevector_nonconstant_argument)
6347 << Arg->getSourceRange());
6348
6349 // Allow -1 which will be translated to undef in the IR.
6350 if (Result->isSigned() && Result->isAllOnes())
6351 ;
6352 else if (Result->getActiveBits() > 64 ||
6353 Result->getZExtValue() >= NumElements * 2)
6354 return ExprError(Diag(TheCall->getBeginLoc(),
6355 diag::err_shufflevector_argument_too_large)
6356 << Arg->getSourceRange());
6357
6358 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6359 }
6360
6361 auto *Result = new (Context) ShuffleVectorExpr(
6362 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6363 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6364
6365 // All moved to Result.
6366 TheCall->shrinkNumArgs(0);
6367 return Result;
6368}
6369
6371 SourceLocation BuiltinLoc,
6372 SourceLocation RParenLoc) {
6375 QualType DstTy = TInfo->getType();
6376 QualType SrcTy = E->getType();
6377
6378 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6379 return ExprError(Diag(BuiltinLoc,
6380 diag::err_convertvector_non_vector)
6381 << E->getSourceRange());
6382 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6383 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6384 << "second"
6385 << "__builtin_convertvector");
6386
6387 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6388 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6389 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6390 if (SrcElts != DstElts)
6391 return ExprError(Diag(BuiltinLoc,
6392 diag::err_convertvector_incompatible_vector)
6393 << E->getSourceRange());
6394 }
6395
6396 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6397 RParenLoc, CurFPFeatureOverrides());
6398}
6399
6400bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6401 unsigned NumArgs = TheCall->getNumArgs();
6402
6403 if (NumArgs > 3)
6404 return Diag(TheCall->getEndLoc(),
6405 diag::err_typecheck_call_too_many_args_at_most)
6406 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6407 << TheCall->getSourceRange();
6408
6409 // Argument 0 is checked for us and the remaining arguments must be
6410 // constant integers.
6411 for (unsigned i = 1; i != NumArgs; ++i)
6412 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6413 return true;
6414
6415 return false;
6416}
6417
6418bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6419 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6420 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6421 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6422 if (checkArgCount(TheCall, 1))
6423 return true;
6424 Expr *Arg = TheCall->getArg(0);
6425 if (Arg->isInstantiationDependent())
6426 return false;
6427
6428 QualType ArgTy = Arg->getType();
6429 if (!ArgTy->hasFloatingRepresentation())
6430 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6431 << ArgTy;
6432 if (Arg->isLValue()) {
6433 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6434 TheCall->setArg(0, FirstArg.get());
6435 }
6436 TheCall->setType(TheCall->getArg(0)->getType());
6437 return false;
6438}
6439
6440bool Sema::BuiltinAssume(CallExpr *TheCall) {
6441 Expr *Arg = TheCall->getArg(0);
6442 if (Arg->isInstantiationDependent()) return false;
6443
6444 if (Arg->HasSideEffects(Context))
6445 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6446 << Arg->getSourceRange()
6447 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6448
6449 return false;
6450}
6451
6452bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6453 // The alignment must be a constant integer.
6454 Expr *Arg = TheCall->getArg(1);
6455
6456 // We can't check the value of a dependent argument.
6457 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6458 if (const auto *UE =
6459 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6460 if (UE->getKind() == UETT_AlignOf ||
6461 UE->getKind() == UETT_PreferredAlignOf)
6462 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6463 << Arg->getSourceRange();
6464
6465 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6466
6467 if (!Result.isPowerOf2())
6468 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6469 << Arg->getSourceRange();
6470
6471 if (Result < Context.getCharWidth())
6472 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6473 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6474
6475 if (Result > std::numeric_limits<int32_t>::max())
6476 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6477 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6478 }
6479
6480 return false;
6481}
6482
6483bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6484 if (checkArgCountRange(TheCall, 2, 3))
6485 return true;
6486
6487 unsigned NumArgs = TheCall->getNumArgs();
6488 Expr *FirstArg = TheCall->getArg(0);
6489
6490 {
6491 ExprResult FirstArgResult =
6493 if (!FirstArgResult.get()->getType()->isPointerType()) {
6494 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6495 << TheCall->getSourceRange();
6496 return true;
6497 }
6498 TheCall->setArg(0, FirstArgResult.get());
6499 }
6500
6501 // The alignment must be a constant integer.
6502 Expr *SecondArg = TheCall->getArg(1);
6503
6504 // We can't check the value of a dependent argument.
6505 if (!SecondArg->isValueDependent()) {
6506 llvm::APSInt Result;
6507 if (BuiltinConstantArg(TheCall, 1, Result))
6508 return true;
6509
6510 if (!Result.isPowerOf2())
6511 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6512 << SecondArg->getSourceRange();
6513
6515 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6516 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6517
6518 TheCall->setArg(1,
6520 }
6521
6522 if (NumArgs > 2) {
6523 Expr *ThirdArg = TheCall->getArg(2);
6524 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6525 return true;
6526 TheCall->setArg(2, ThirdArg);
6527 }
6528
6529 return false;
6530}
6531
6532bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6533 unsigned BuiltinID =
6534 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6535 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6536
6537 unsigned NumArgs = TheCall->getNumArgs();
6538 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6539 if (NumArgs < NumRequiredArgs) {
6540 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6541 << 0 /* function call */ << NumRequiredArgs << NumArgs
6542 << /*is non object*/ 0 << TheCall->getSourceRange();
6543 }
6544 if (NumArgs >= NumRequiredArgs + 0x100) {
6545 return Diag(TheCall->getEndLoc(),
6546 diag::err_typecheck_call_too_many_args_at_most)
6547 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6548 << /*is non object*/ 0 << TheCall->getSourceRange();
6549 }
6550 unsigned i = 0;
6551
6552 // For formatting call, check buffer arg.
6553 if (!IsSizeCall) {
6554 ExprResult Arg(TheCall->getArg(i));
6555 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6556 Context, Context.VoidPtrTy, false);
6557 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6558 if (Arg.isInvalid())
6559 return true;
6560 TheCall->setArg(i, Arg.get());
6561 i++;
6562 }
6563
6564 // Check string literal arg.
6565 unsigned FormatIdx = i;
6566 {
6567 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6568 if (Arg.isInvalid())
6569 return true;
6570 TheCall->setArg(i, Arg.get());
6571 i++;
6572 }
6573
6574 // Make sure variadic args are scalar.
6575 unsigned FirstDataArg = i;
6576 while (i < NumArgs) {
6578 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6579 if (Arg.isInvalid())
6580 return true;
6581 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6582 if (ArgSize.getQuantity() >= 0x100) {
6583 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6584 << i << (int)ArgSize.getQuantity() << 0xff
6585 << TheCall->getSourceRange();
6586 }
6587 TheCall->setArg(i, Arg.get());
6588 i++;
6589 }
6590
6591 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6592 // call to avoid duplicate diagnostics.
6593 if (!IsSizeCall) {
6594 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6595 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6596 bool Success = CheckFormatArguments(
6597 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6599 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6600 if (!Success)
6601 return true;
6602 }
6603
6604 if (IsSizeCall) {
6605 TheCall->setType(Context.getSizeType());
6606 } else {
6607 TheCall->setType(Context.VoidPtrTy);
6608 }
6609 return false;
6610}
6611
6612bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6613 llvm::APSInt &Result) {
6614 Expr *Arg = TheCall->getArg(ArgNum);
6615
6616 if (Arg->isTypeDependent() || Arg->isValueDependent())
6617 return false;
6618
6619 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6620 if (!R) {
6621 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6622 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6623 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6624 << FDecl->getDeclName() << Arg->getSourceRange();
6625 }
6626 Result = *R;
6627
6628 return false;
6629}
6630
6631bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6632 int High, bool RangeIsError) {
6634 return false;
6635 llvm::APSInt Result;
6636
6637 // We can't check the value of a dependent argument.
6638 Expr *Arg = TheCall->getArg(ArgNum);
6639 if (Arg->isTypeDependent() || Arg->isValueDependent())
6640 return false;
6641
6642 // Check constant-ness first.
6643 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6644 return true;
6645
6646 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6647 if (RangeIsError)
6648 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6649 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6650 else
6651 // Defer the warning until we know if the code will be emitted so that
6652 // dead code can ignore this.
6653 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6654 PDiag(diag::warn_argument_invalid_range)
6655 << toString(Result, 10) << Low << High
6656 << Arg->getSourceRange());
6657 }
6658
6659 return false;
6660}
6661
6662bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6663 unsigned Num) {
6664 llvm::APSInt Result;
6665
6666 // We can't check the value of a dependent argument.
6667 Expr *Arg = TheCall->getArg(ArgNum);
6668 if (Arg->isTypeDependent() || Arg->isValueDependent())
6669 return false;
6670
6671 // Check constant-ness first.
6672 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6673 return true;
6674
6675 if (Result.getSExtValue() % Num != 0)
6676 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6677 << Num << Arg->getSourceRange();
6678
6679 return false;
6680}
6681
6682bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6683 llvm::APSInt Result;
6684
6685 // We can't check the value of a dependent argument.
6686 Expr *Arg = TheCall->getArg(ArgNum);
6687 if (Arg->isTypeDependent() || Arg->isValueDependent())
6688 return false;
6689
6690 // Check constant-ness first.
6691 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6692 return true;
6693
6694 if (Result.isPowerOf2())
6695 return false;
6696
6697 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6698 << Arg->getSourceRange();
6699}
6700
6701static bool IsShiftedByte(llvm::APSInt Value) {
6702 if (Value.isNegative())
6703 return false;
6704
6705 // Check if it's a shifted byte, by shifting it down
6706 while (true) {
6707 // If the value fits in the bottom byte, the check passes.
6708 if (Value < 0x100)
6709 return true;
6710
6711 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6712 // fails.
6713 if ((Value & 0xFF) != 0)
6714 return false;
6715
6716 // If the bottom 8 bits are all 0, but something above that is nonzero,
6717 // then shifting the value right by 8 bits won't affect whether it's a
6718 // shifted byte or not. So do that, and go round again.
6719 Value >>= 8;
6720 }
6721}
6722
6723bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6724 unsigned ArgBits) {
6725 llvm::APSInt Result;
6726
6727 // We can't check the value of a dependent argument.
6728 Expr *Arg = TheCall->getArg(ArgNum);
6729 if (Arg->isTypeDependent() || Arg->isValueDependent())
6730 return false;
6731
6732 // Check constant-ness first.
6733 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6734 return true;
6735
6736 // Truncate to the given size.
6737 Result = Result.getLoBits(ArgBits);
6738 Result.setIsUnsigned(true);
6739
6740 if (IsShiftedByte(Result))
6741 return false;
6742
6743 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6744 << Arg->getSourceRange();
6745}
6746
6748 unsigned ArgNum,
6749 unsigned ArgBits) {
6750 llvm::APSInt Result;
6751
6752 // We can't check the value of a dependent argument.
6753 Expr *Arg = TheCall->getArg(ArgNum);
6754 if (Arg->isTypeDependent() || Arg->isValueDependent())
6755 return false;
6756
6757 // Check constant-ness first.
6758 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6759 return true;
6760
6761 // Truncate to the given size.
6762 Result = Result.getLoBits(ArgBits);
6763 Result.setIsUnsigned(true);
6764
6765 // Check to see if it's in either of the required forms.
6766 if (IsShiftedByte(Result) ||
6767 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6768 return false;
6769
6770 return Diag(TheCall->getBeginLoc(),
6771 diag::err_argument_not_shifted_byte_or_xxff)
6772 << Arg->getSourceRange();
6773}
6774
6775bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6776 if (!Context.getTargetInfo().hasSjLjLowering())
6777 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6778 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6779
6780 Expr *Arg = TheCall->getArg(1);
6781 llvm::APSInt Result;
6782
6783 // TODO: This is less than ideal. Overload this to take a value.
6784 if (BuiltinConstantArg(TheCall, 1, Result))
6785 return true;
6786
6787 if (Result != 1)
6788 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6789 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6790
6791 return false;
6792}
6793
6794bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6795 if (!Context.getTargetInfo().hasSjLjLowering())
6796 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6797 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6798 return false;
6799}
6800
6801bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6802 if (checkArgCount(TheCall, 1))
6803 return true;
6804
6805 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6806 if (ArgRes.isInvalid())
6807 return true;
6808
6809 // For simplicity, we support only limited expressions for the argument.
6810 // Specifically a flexible array member or a pointer with counted_by:
6811 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6812 // complex casting, which really shouldn't be a huge problem.
6813 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6814 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6815 return Diag(Arg->getBeginLoc(),
6816 diag::err_builtin_counted_by_ref_invalid_arg)
6817 << Arg->getSourceRange();
6818
6819 if (Arg->HasSideEffects(Context))
6820 return Diag(Arg->getBeginLoc(),
6821 diag::err_builtin_counted_by_ref_has_side_effects)
6822 << Arg->getSourceRange();
6823
6824 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6825 const auto *CATy =
6826 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6827
6828 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6829 // Member has counted_by attribute - return pointer to count field
6830 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6831 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6832 TheCall->setType(Context.getPointerType(CountFD->getType()));
6833 return false;
6834 }
6835 }
6836
6837 // FAMs and pointers without counted_by return void*
6838 QualType MemberTy = ME->getMemberDecl()->getType();
6839 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6840 return Diag(Arg->getBeginLoc(),
6841 diag::err_builtin_counted_by_ref_invalid_arg)
6842 << Arg->getSourceRange();
6843 } else {
6844 return Diag(Arg->getBeginLoc(),
6845 diag::err_builtin_counted_by_ref_invalid_arg)
6846 << Arg->getSourceRange();
6847 }
6848
6849 TheCall->setType(Context.getPointerType(Context.VoidTy));
6850 return false;
6851}
6852
6853/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6854/// It allows leaking and modification of bounds safety information.
6855bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6857 const CallExpr *CE =
6858 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6859 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6860 return false;
6861
6862 switch (K) {
6865 Diag(E->getExprLoc(),
6866 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6867 << 0 << E->getSourceRange();
6868 break;
6870 Diag(E->getExprLoc(),
6871 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6872 << 1 << E->getSourceRange();
6873 break;
6875 Diag(E->getExprLoc(),
6876 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6877 << 2 << E->getSourceRange();
6878 break;
6880 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6881 << 0 << E->getSourceRange();
6882 break;
6884 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6885 << 1 << E->getSourceRange();
6886 break;
6887 }
6888
6889 return true;
6890}
6891
6892namespace {
6893
6894class UncoveredArgHandler {
6895 enum { Unknown = -1, AllCovered = -2 };
6896
6897 signed FirstUncoveredArg = Unknown;
6898 SmallVector<const Expr *, 4> DiagnosticExprs;
6899
6900public:
6901 UncoveredArgHandler() = default;
6902
6903 bool hasUncoveredArg() const {
6904 return (FirstUncoveredArg >= 0);
6905 }
6906
6907 unsigned getUncoveredArg() const {
6908 assert(hasUncoveredArg() && "no uncovered argument");
6909 return FirstUncoveredArg;
6910 }
6911
6912 void setAllCovered() {
6913 // A string has been found with all arguments covered, so clear out
6914 // the diagnostics.
6915 DiagnosticExprs.clear();
6916 FirstUncoveredArg = AllCovered;
6917 }
6918
6919 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6920 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6921
6922 // Don't update if a previous string covers all arguments.
6923 if (FirstUncoveredArg == AllCovered)
6924 return;
6925
6926 // UncoveredArgHandler tracks the highest uncovered argument index
6927 // and with it all the strings that match this index.
6928 if (NewFirstUncoveredArg == FirstUncoveredArg)
6929 DiagnosticExprs.push_back(StrExpr);
6930 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6931 DiagnosticExprs.clear();
6932 DiagnosticExprs.push_back(StrExpr);
6933 FirstUncoveredArg = NewFirstUncoveredArg;
6934 }
6935 }
6936
6937 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6938};
6939
6940enum StringLiteralCheckType {
6941 SLCT_NotALiteral,
6942 SLCT_UncheckedLiteral,
6943 SLCT_CheckedLiteral
6944};
6945
6946} // namespace
6947
6948static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6949 BinaryOperatorKind BinOpKind,
6950 bool AddendIsRight) {
6951 unsigned BitWidth = Offset.getBitWidth();
6952 unsigned AddendBitWidth = Addend.getBitWidth();
6953 // There might be negative interim results.
6954 if (Addend.isUnsigned()) {
6955 Addend = Addend.zext(++AddendBitWidth);
6956 Addend.setIsSigned(true);
6957 }
6958 // Adjust the bit width of the APSInts.
6959 if (AddendBitWidth > BitWidth) {
6960 Offset = Offset.sext(AddendBitWidth);
6961 BitWidth = AddendBitWidth;
6962 } else if (BitWidth > AddendBitWidth) {
6963 Addend = Addend.sext(BitWidth);
6964 }
6965
6966 bool Ov = false;
6967 llvm::APSInt ResOffset = Offset;
6968 if (BinOpKind == BO_Add)
6969 ResOffset = Offset.sadd_ov(Addend, Ov);
6970 else {
6971 assert(AddendIsRight && BinOpKind == BO_Sub &&
6972 "operator must be add or sub with addend on the right");
6973 ResOffset = Offset.ssub_ov(Addend, Ov);
6974 }
6975
6976 // We add an offset to a pointer here so we should support an offset as big as
6977 // possible.
6978 if (Ov) {
6979 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6980 "index (intermediate) result too big");
6981 Offset = Offset.sext(2 * BitWidth);
6982 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6983 return;
6984 }
6985
6986 Offset = std::move(ResOffset);
6987}
6988
6989namespace {
6990
6991// This is a wrapper class around StringLiteral to support offsetted string
6992// literals as format strings. It takes the offset into account when returning
6993// the string and its length or the source locations to display notes correctly.
6994class FormatStringLiteral {
6995 const StringLiteral *FExpr;
6996 int64_t Offset;
6997
6998public:
6999 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7000 : FExpr(fexpr), Offset(Offset) {}
7001
7002 const StringLiteral *getFormatString() const { return FExpr; }
7003
7004 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7005
7006 unsigned getByteLength() const {
7007 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7008 }
7009
7010 unsigned getLength() const { return FExpr->getLength() - Offset; }
7011 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7012
7013 StringLiteralKind getKind() const { return FExpr->getKind(); }
7014
7015 QualType getType() const { return FExpr->getType(); }
7016
7017 bool isAscii() const { return FExpr->isOrdinary(); }
7018 bool isWide() const { return FExpr->isWide(); }
7019 bool isUTF8() const { return FExpr->isUTF8(); }
7020 bool isUTF16() const { return FExpr->isUTF16(); }
7021 bool isUTF32() const { return FExpr->isUTF32(); }
7022 bool isPascal() const { return FExpr->isPascal(); }
7023
7024 SourceLocation getLocationOfByte(
7025 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7026 const TargetInfo &Target, unsigned *StartToken = nullptr,
7027 unsigned *StartTokenByteOffset = nullptr) const {
7028 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7029 StartToken, StartTokenByteOffset);
7030 }
7031
7032 SourceLocation getBeginLoc() const LLVM_READONLY {
7033 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7034 }
7035
7036 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7037};
7038
7039} // namespace
7040
7041static void CheckFormatString(
7042 Sema &S, const FormatStringLiteral *FExpr,
7043 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7045 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7046 bool inFunctionCall, VariadicCallType CallType,
7047 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7048 bool IgnoreStringsWithoutSpecifiers);
7049
7050static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7051 const Expr *E);
7052
7053// Determine if an expression is a string literal or constant string.
7054// If this function returns false on the arguments to a function expecting a
7055// format string, we will usually need to emit a warning.
7056// True string literals are then checked by CheckFormatString.
7057static StringLiteralCheckType
7058checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7059 const Expr *E, ArrayRef<const Expr *> Args,
7060 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7061 unsigned firstDataArg, FormatStringType Type,
7062 VariadicCallType CallType, bool InFunctionCall,
7063 llvm::SmallBitVector &CheckedVarArgs,
7064 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7065 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7066 bool IgnoreStringsWithoutSpecifiers = false) {
7068 return SLCT_NotALiteral;
7069tryAgain:
7070 assert(Offset.isSigned() && "invalid offset");
7071
7072 if (E->isTypeDependent() || E->isValueDependent())
7073 return SLCT_NotALiteral;
7074
7075 E = E->IgnoreParenCasts();
7076
7078 // Technically -Wformat-nonliteral does not warn about this case.
7079 // The behavior of printf and friends in this case is implementation
7080 // dependent. Ideally if the format string cannot be null then
7081 // it should have a 'nonnull' attribute in the function prototype.
7082 return SLCT_UncheckedLiteral;
7083
7084 switch (E->getStmtClass()) {
7085 case Stmt::InitListExprClass:
7086 // Handle expressions like {"foobar"}.
7087 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7088 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7089 format_idx, firstDataArg, Type, CallType,
7090 /*InFunctionCall*/ false, CheckedVarArgs,
7091 UncoveredArg, Offset, CallerFormatParamIdx,
7092 IgnoreStringsWithoutSpecifiers);
7093 }
7094 return SLCT_NotALiteral;
7095 case Stmt::BinaryConditionalOperatorClass:
7096 case Stmt::ConditionalOperatorClass: {
7097 // The expression is a literal if both sub-expressions were, and it was
7098 // completely checked only if both sub-expressions were checked.
7101
7102 // Determine whether it is necessary to check both sub-expressions, for
7103 // example, because the condition expression is a constant that can be
7104 // evaluated at compile time.
7105 bool CheckLeft = true, CheckRight = true;
7106
7107 bool Cond;
7108 if (C->getCond()->EvaluateAsBooleanCondition(
7110 if (Cond)
7111 CheckRight = false;
7112 else
7113 CheckLeft = false;
7114 }
7115
7116 // We need to maintain the offsets for the right and the left hand side
7117 // separately to check if every possible indexed expression is a valid
7118 // string literal. They might have different offsets for different string
7119 // literals in the end.
7120 StringLiteralCheckType Left;
7121 if (!CheckLeft)
7122 Left = SLCT_UncheckedLiteral;
7123 else {
7124 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7125 Args, APK, format_idx, firstDataArg, Type,
7126 CallType, InFunctionCall, CheckedVarArgs,
7127 UncoveredArg, Offset, CallerFormatParamIdx,
7128 IgnoreStringsWithoutSpecifiers);
7129 if (Left == SLCT_NotALiteral || !CheckRight) {
7130 return Left;
7131 }
7132 }
7133
7134 StringLiteralCheckType Right = checkFormatStringExpr(
7135 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7136 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7137 UncoveredArg, Offset, CallerFormatParamIdx,
7138 IgnoreStringsWithoutSpecifiers);
7139
7140 return (CheckLeft && Left < Right) ? Left : Right;
7141 }
7142
7143 case Stmt::ImplicitCastExprClass:
7144 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7145 goto tryAgain;
7146
7147 case Stmt::OpaqueValueExprClass:
7148 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7149 E = src;
7150 goto tryAgain;
7151 }
7152 return SLCT_NotALiteral;
7153
7154 case Stmt::PredefinedExprClass:
7155 // While __func__, etc., are technically not string literals, they
7156 // cannot contain format specifiers and thus are not a security
7157 // liability.
7158 return SLCT_UncheckedLiteral;
7159
7160 case Stmt::DeclRefExprClass: {
7161 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7162
7163 // As an exception, do not flag errors for variables binding to
7164 // const string literals.
7165 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7166 bool isConstant = false;
7167 QualType T = DR->getType();
7168
7169 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7170 isConstant = AT->getElementType().isConstant(S.Context);
7171 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7172 isConstant = T.isConstant(S.Context) &&
7173 PT->getPointeeType().isConstant(S.Context);
7174 } else if (T->isObjCObjectPointerType()) {
7175 // In ObjC, there is usually no "const ObjectPointer" type,
7176 // so don't check if the pointee type is constant.
7177 isConstant = T.isConstant(S.Context);
7178 }
7179
7180 if (isConstant) {
7181 if (const Expr *Init = VD->getAnyInitializer()) {
7182 // Look through initializers like const char c[] = { "foo" }
7183 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7184 if (InitList->isStringLiteralInit())
7185 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7186 }
7187 return checkFormatStringExpr(
7188 S, ReferenceFormatString, Init, Args, APK, format_idx,
7189 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7190 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7191 }
7192 }
7193
7194 // When the format argument is an argument of this function, and this
7195 // function also has the format attribute, there are several interactions
7196 // for which there shouldn't be a warning. For instance, when calling
7197 // v*printf from a function that has the printf format attribute, we
7198 // should not emit a warning about using `fmt`, even though it's not
7199 // constant, because the arguments have already been checked for the
7200 // caller of `logmessage`:
7201 //
7202 // __attribute__((format(printf, 1, 2)))
7203 // void logmessage(char const *fmt, ...) {
7204 // va_list ap;
7205 // va_start(ap, fmt);
7206 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7207 // ...
7208 // }
7209 //
7210 // Another interaction that we need to support is using a format string
7211 // specified by the format_matches attribute:
7212 //
7213 // __attribute__((format_matches(printf, 1, "%s %d")))
7214 // void logmessage(char const *fmt, const char *a, int b) {
7215 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7216 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7217 // ...
7218 // }
7219 //
7220 // Yet another interaction that we need to support is calling a variadic
7221 // format function from a format function that has fixed arguments. For
7222 // instance:
7223 //
7224 // __attribute__((format(printf, 1, 2)))
7225 // void logstring(char const *fmt, char const *str) {
7226 // printf(fmt, str); /* do not emit a warning about "fmt" */
7227 // }
7228 //
7229 // Same (and perhaps more relatably) for the variadic template case:
7230 //
7231 // template<typename... Args>
7232 // __attribute__((format(printf, 1, 2)))
7233 // void log(const char *fmt, Args&&... args) {
7234 // printf(fmt, forward<Args>(args)...);
7235 // /* do not emit a warning about "fmt" */
7236 // }
7237 //
7238 // Due to implementation difficulty, we only check the format, not the
7239 // format arguments, in all cases.
7240 //
7241 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7242 if (CallerFormatParamIdx)
7243 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7244 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7245 for (const auto *PVFormatMatches :
7246 D->specific_attrs<FormatMatchesAttr>()) {
7247 Sema::FormatStringInfo CalleeFSI;
7248 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7249 0, &CalleeFSI))
7250 continue;
7251 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7252 // If using the wrong type of format string, emit a diagnostic
7253 // here and stop checking to avoid irrelevant diagnostics.
7254 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7255 S.Diag(Args[format_idx]->getBeginLoc(),
7256 diag::warn_format_string_type_incompatible)
7257 << PVFormatMatches->getType()->getName()
7259 if (!InFunctionCall) {
7260 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7261 diag::note_format_string_defined);
7262 }
7263 return SLCT_UncheckedLiteral;
7264 }
7265 return checkFormatStringExpr(
7266 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7267 Args, APK, format_idx, firstDataArg, Type, CallType,
7268 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7269 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7270 }
7271 }
7272
7273 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7274 Sema::FormatStringInfo CallerFSI;
7275 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7276 PVFormat->getFirstArg(), &CallerFSI))
7277 continue;
7278 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7279 // We also check if the formats are compatible.
7280 // We can't pass a 'scanf' string to a 'printf' function.
7281 if (Type != S.GetFormatStringType(PVFormat)) {
7282 S.Diag(Args[format_idx]->getBeginLoc(),
7283 diag::warn_format_string_type_incompatible)
7284 << PVFormat->getType()->getName()
7286 if (!InFunctionCall) {
7287 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7288 }
7289 return SLCT_UncheckedLiteral;
7290 }
7291 // Lastly, check that argument passing kinds transition in a
7292 // way that makes sense:
7293 // from a caller with FAPK_VAList, allow FAPK_VAList
7294 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7295 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7296 // from a caller with FAPK_Variadic, allow FAPK_VAList
7297 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7302 return SLCT_UncheckedLiteral;
7303 }
7304 }
7305 }
7306 }
7307 }
7308 }
7309
7310 return SLCT_NotALiteral;
7311 }
7312
7313 case Stmt::CallExprClass:
7314 case Stmt::CXXMemberCallExprClass: {
7315 const CallExpr *CE = cast<CallExpr>(E);
7316 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7317 bool IsFirst = true;
7318 StringLiteralCheckType CommonResult;
7319 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7320 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7321 StringLiteralCheckType Result = checkFormatStringExpr(
7322 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7323 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7324 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7325 if (IsFirst) {
7326 CommonResult = Result;
7327 IsFirst = false;
7328 }
7329 }
7330 if (!IsFirst)
7331 return CommonResult;
7332
7333 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7334 unsigned BuiltinID = FD->getBuiltinID();
7335 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7336 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7337 const Expr *Arg = CE->getArg(0);
7338 return checkFormatStringExpr(
7339 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7340 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7341 UncoveredArg, Offset, CallerFormatParamIdx,
7342 IgnoreStringsWithoutSpecifiers);
7343 }
7344 }
7345 }
7346 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7347 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7348 format_idx, firstDataArg, Type, CallType,
7349 /*InFunctionCall*/ false, CheckedVarArgs,
7350 UncoveredArg, Offset, CallerFormatParamIdx,
7351 IgnoreStringsWithoutSpecifiers);
7352 return SLCT_NotALiteral;
7353 }
7354 case Stmt::ObjCMessageExprClass: {
7355 const auto *ME = cast<ObjCMessageExpr>(E);
7356 if (const auto *MD = ME->getMethodDecl()) {
7357 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7358 // As a special case heuristic, if we're using the method -[NSBundle
7359 // localizedStringForKey:value:table:], ignore any key strings that lack
7360 // format specifiers. The idea is that if the key doesn't have any
7361 // format specifiers then its probably just a key to map to the
7362 // localized strings. If it does have format specifiers though, then its
7363 // likely that the text of the key is the format string in the
7364 // programmer's language, and should be checked.
7365 const ObjCInterfaceDecl *IFace;
7366 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7367 IFace->getIdentifier()->isStr("NSBundle") &&
7368 MD->getSelector().isKeywordSelector(
7369 {"localizedStringForKey", "value", "table"})) {
7370 IgnoreStringsWithoutSpecifiers = true;
7371 }
7372
7373 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7374 return checkFormatStringExpr(
7375 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7376 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7377 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7378 }
7379 }
7380
7381 return SLCT_NotALiteral;
7382 }
7383 case Stmt::ObjCStringLiteralClass:
7384 case Stmt::StringLiteralClass: {
7385 const StringLiteral *StrE = nullptr;
7386
7387 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7388 StrE = ObjCFExpr->getString();
7389 else
7390 StrE = cast<StringLiteral>(E);
7391
7392 if (StrE) {
7393 if (Offset.isNegative() || Offset > StrE->getLength()) {
7394 // TODO: It would be better to have an explicit warning for out of
7395 // bounds literals.
7396 return SLCT_NotALiteral;
7397 }
7398 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7399 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7400 format_idx, firstDataArg, Type, InFunctionCall,
7401 CallType, CheckedVarArgs, UncoveredArg,
7402 IgnoreStringsWithoutSpecifiers);
7403 return SLCT_CheckedLiteral;
7404 }
7405
7406 return SLCT_NotALiteral;
7407 }
7408 case Stmt::BinaryOperatorClass: {
7409 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7410
7411 // A string literal + an int offset is still a string literal.
7412 if (BinOp->isAdditiveOp()) {
7413 Expr::EvalResult LResult, RResult;
7414
7415 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7416 LResult, S.Context, Expr::SE_NoSideEffects,
7418 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7419 RResult, S.Context, Expr::SE_NoSideEffects,
7421
7422 if (LIsInt != RIsInt) {
7423 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7424
7425 if (LIsInt) {
7426 if (BinOpKind == BO_Add) {
7427 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7428 E = BinOp->getRHS();
7429 goto tryAgain;
7430 }
7431 } else {
7432 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7433 E = BinOp->getLHS();
7434 goto tryAgain;
7435 }
7436 }
7437 }
7438
7439 return SLCT_NotALiteral;
7440 }
7441 case Stmt::UnaryOperatorClass: {
7442 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7443 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7444 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7445 Expr::EvalResult IndexResult;
7446 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7449 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7450 /*RHS is int*/ true);
7451 E = ASE->getBase();
7452 goto tryAgain;
7453 }
7454 }
7455
7456 return SLCT_NotALiteral;
7457 }
7458
7459 default:
7460 return SLCT_NotALiteral;
7461 }
7462}
7463
7464// If this expression can be evaluated at compile-time,
7465// check if the result is a StringLiteral and return it
7466// otherwise return nullptr
7468 const Expr *E) {
7469 Expr::EvalResult Result;
7470 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7471 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7472 if (isa_and_nonnull<StringLiteral>(LVE))
7473 return LVE;
7474 }
7475 return nullptr;
7476}
7477
7479 switch (FST) {
7481 return "scanf";
7483 return "printf";
7485 return "NSString";
7487 return "strftime";
7489 return "strfmon";
7491 return "kprintf";
7493 return "freebsd_kprintf";
7495 return "os_log";
7496 default:
7497 return "<unknown>";
7498 }
7499}
7500
7502 return llvm::StringSwitch<FormatStringType>(Flavor)
7503 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7504 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7506 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7507 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7508 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7509 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7511 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7512 .Case("os_trace", FormatStringType::OSLog)
7513 .Case("os_log", FormatStringType::OSLog)
7514 .Default(FormatStringType::Unknown);
7515}
7516
7518 return GetFormatStringType(Format->getType()->getName());
7519}
7520
7521FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7522 return GetFormatStringType(Format->getType()->getName());
7523}
7524
7525bool Sema::CheckFormatArguments(const FormatAttr *Format,
7526 ArrayRef<const Expr *> Args, bool IsCXXMember,
7527 VariadicCallType CallType, SourceLocation Loc,
7528 SourceRange Range,
7529 llvm::SmallBitVector &CheckedVarArgs) {
7530 FormatStringInfo FSI;
7531 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7532 IsCXXMember,
7533 CallType != VariadicCallType::DoesNotApply, &FSI))
7534 return CheckFormatArguments(
7535 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7536 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7537 return false;
7538}
7539
7540bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7541 ArrayRef<const Expr *> Args, bool IsCXXMember,
7542 VariadicCallType CallType, SourceLocation Loc,
7543 SourceRange Range,
7544 llvm::SmallBitVector &CheckedVarArgs) {
7545 FormatStringInfo FSI;
7546 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7547 &FSI)) {
7548 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7549 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7550 Format->getFormatString(), FSI.FormatIdx,
7551 FSI.FirstDataArg, GetFormatStringType(Format),
7552 CallType, Loc, Range, CheckedVarArgs);
7553 }
7554 return false;
7555}
7556
7559 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7560 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7561 SourceLocation Loc) {
7562 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7563 return false;
7564
7565 DeclContext *DC = S->CurContext;
7566 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7567 return false;
7568 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7569
7570 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7571
7572 // Find the offset to convert between attribute and parameter indexes.
7573 unsigned CallerArgumentIndexOffset =
7574 hasImplicitObjectParameter(Caller) ? 2 : 1;
7575
7576 unsigned FirstArgumentIndex = -1;
7577 switch (APK) {
7580 // As an extension, clang allows the format attribute on non-variadic
7581 // functions.
7582 // Caller must have fixed arguments to pass them to a fixed or variadic
7583 // function. Try to match caller and callee arguments. If successful, then
7584 // emit a diag with the caller idx, otherwise we can't determine the callee
7585 // arguments.
7586 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7587 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7588 // There aren't enough arguments in the caller to pass to callee.
7589 return false;
7590 }
7591 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7592 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7593 const auto *Arg =
7594 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7595 if (!Arg)
7596 return false;
7597 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7598 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7599 return false;
7600 }
7601 FirstArgumentIndex =
7602 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7603 break;
7604 }
7606 // Caller arguments are either variadic or a va_list.
7607 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7608 ? (NumCallerParams + CallerArgumentIndexOffset)
7609 : 0;
7610 break;
7612 // The callee has a format_matches attribute. We will emit that instead.
7613 if (!ReferenceFormatString)
7614 return false;
7615 break;
7616 }
7617
7618 // Emit the diagnostic and fixit.
7619 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7620 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7621 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7622 do {
7623 std::string Attr, Fixit;
7624 llvm::raw_string_ostream AttrOS(Attr);
7626 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7627 << FirstArgumentIndex << ")";
7628 } else {
7629 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7630 << ", \"";
7631 AttrOS.write_escaped(ReferenceFormatString->getString());
7632 AttrOS << "\")";
7633 }
7634 AttrOS.flush();
7635 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7636 if (ND)
7637 DB << ND;
7638 else
7639 DB << "block";
7640
7641 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7642 if (isa<BlockDecl>(Caller))
7643 break;
7644
7645 SourceLocation SL;
7646 llvm::raw_string_ostream IS(Fixit);
7647 // The attribute goes at the start of the declaration in C/C++ functions
7648 // and methods, but after the declaration for Objective-C methods.
7649 if (isa<ObjCMethodDecl>(Caller)) {
7650 IS << ' ';
7651 SL = Caller->getEndLoc();
7652 }
7653 const LangOptions &LO = S->getLangOpts();
7654 if (LO.C23 || LO.CPlusPlus11)
7655 IS << "[[gnu::" << Attr << "]]";
7656 else if (LO.ObjC || LO.GNUMode)
7657 IS << "__attribute__((" << Attr << "))";
7658 else
7659 break;
7660 if (!isa<ObjCMethodDecl>(Caller)) {
7661 IS << ' ';
7662 SL = Caller->getBeginLoc();
7663 }
7664 IS.flush();
7665
7666 DB << FixItHint::CreateInsertion(SL, Fixit);
7667 } while (false);
7668
7669 // Add implicit format or format_matches attribute.
7671 Caller->addAttr(FormatAttr::CreateImplicit(
7672 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7673 FormatStringIndex, FirstArgumentIndex));
7674 } else {
7675 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7676 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7677 FormatStringIndex, ReferenceFormatString));
7678 }
7679
7680 {
7681 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7682 if (ND)
7683 DB << ND;
7684 else
7685 DB << "block";
7686 }
7687 return true;
7688}
7689
7690bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7692 StringLiteral *ReferenceFormatString,
7693 unsigned format_idx, unsigned firstDataArg,
7695 VariadicCallType CallType, SourceLocation Loc,
7696 SourceRange Range,
7697 llvm::SmallBitVector &CheckedVarArgs) {
7698 // CHECK: printf/scanf-like function is called with no format string.
7699 if (format_idx >= Args.size()) {
7700 Diag(Loc, diag::warn_missing_format_string) << Range;
7701 return false;
7702 }
7703
7704 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7705
7706 // CHECK: format string is not a string literal.
7707 //
7708 // Dynamically generated format strings are difficult to
7709 // automatically vet at compile time. Requiring that format strings
7710 // are string literals: (1) permits the checking of format strings by
7711 // the compiler and thereby (2) can practically remove the source of
7712 // many format string exploits.
7713
7714 // Format string can be either ObjC string (e.g. @"%d") or
7715 // C string (e.g. "%d")
7716 // ObjC string uses the same format specifiers as C string, so we can use
7717 // the same format string checking logic for both ObjC and C strings.
7718 UncoveredArgHandler UncoveredArg;
7719 std::optional<unsigned> CallerParamIdx;
7720 StringLiteralCheckType CT = checkFormatStringExpr(
7721 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7722 firstDataArg, Type, CallType,
7723 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7724 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7725
7726 // Generate a diagnostic where an uncovered argument is detected.
7727 if (UncoveredArg.hasUncoveredArg()) {
7728 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7729 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7730 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7731 }
7732
7733 if (CT != SLCT_NotALiteral)
7734 // Literal format string found, check done!
7735 return CT == SLCT_CheckedLiteral;
7736
7737 // Do not emit diag when the string param is a macro expansion and the
7738 // format is either NSString or CFString. This is a hack to prevent
7739 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7740 // which are usually used in place of NS and CF string literals.
7741 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7743 SourceMgr.isInSystemMacro(FormatLoc))
7744 return false;
7745
7746 if (CallerParamIdx && CheckMissingFormatAttribute(
7747 this, Args, APK, ReferenceFormatString, format_idx,
7748 firstDataArg, Type, *CallerParamIdx, Loc))
7749 return false;
7750
7751 // Strftime is particular as it always uses a single 'time' argument,
7752 // so it is safe to pass a non-literal string.
7754 return false;
7755
7756 // If there are no arguments specified, warn with -Wformat-security, otherwise
7757 // warn only with -Wformat-nonliteral.
7758 if (Args.size() == firstDataArg) {
7759 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7760 << OrigFormatExpr->getSourceRange();
7761 switch (Type) {
7762 default:
7763 break;
7767 Diag(FormatLoc, diag::note_format_security_fixit)
7768 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7769 break;
7771 Diag(FormatLoc, diag::note_format_security_fixit)
7772 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7773 break;
7774 }
7775 } else {
7776 Diag(FormatLoc, diag::warn_format_nonliteral)
7777 << OrigFormatExpr->getSourceRange();
7778 }
7779 return false;
7780}
7781
7782namespace {
7783
7784class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7785protected:
7786 Sema &S;
7787 const FormatStringLiteral *FExpr;
7788 const Expr *OrigFormatExpr;
7789 const FormatStringType FSType;
7790 const unsigned FirstDataArg;
7791 const unsigned NumDataArgs;
7792 const char *Beg; // Start of format string.
7793 const Sema::FormatArgumentPassingKind ArgPassingKind;
7794 ArrayRef<const Expr *> Args;
7795 unsigned FormatIdx;
7796 llvm::SmallBitVector CoveredArgs;
7797 bool usesPositionalArgs = false;
7798 bool atFirstArg = true;
7799 bool inFunctionCall;
7800 VariadicCallType CallType;
7801 llvm::SmallBitVector &CheckedVarArgs;
7802 UncoveredArgHandler &UncoveredArg;
7803
7804public:
7805 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7806 const Expr *origFormatExpr, const FormatStringType type,
7807 unsigned firstDataArg, unsigned numDataArgs,
7808 const char *beg, Sema::FormatArgumentPassingKind APK,
7809 ArrayRef<const Expr *> Args, unsigned formatIdx,
7810 bool inFunctionCall, VariadicCallType callType,
7811 llvm::SmallBitVector &CheckedVarArgs,
7812 UncoveredArgHandler &UncoveredArg)
7813 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7814 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7815 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7816 inFunctionCall(inFunctionCall), CallType(callType),
7817 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7818 CoveredArgs.resize(numDataArgs);
7819 CoveredArgs.reset();
7820 }
7821
7822 bool HasFormatArguments() const {
7823 return ArgPassingKind == Sema::FAPK_Fixed ||
7824 ArgPassingKind == Sema::FAPK_Variadic;
7825 }
7826
7827 void DoneProcessing();
7828
7829 void HandleIncompleteSpecifier(const char *startSpecifier,
7830 unsigned specifierLen) override;
7831
7832 void HandleInvalidLengthModifier(
7833 const analyze_format_string::FormatSpecifier &FS,
7834 const analyze_format_string::ConversionSpecifier &CS,
7835 const char *startSpecifier, unsigned specifierLen,
7836 unsigned DiagID);
7837
7838 void HandleNonStandardLengthModifier(
7839 const analyze_format_string::FormatSpecifier &FS,
7840 const char *startSpecifier, unsigned specifierLen);
7841
7842 void HandleNonStandardConversionSpecifier(
7843 const analyze_format_string::ConversionSpecifier &CS,
7844 const char *startSpecifier, unsigned specifierLen);
7845
7846 void HandlePosition(const char *startPos, unsigned posLen) override;
7847
7848 void HandleInvalidPosition(const char *startSpecifier,
7849 unsigned specifierLen,
7851
7852 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7853
7854 void HandleNullChar(const char *nullCharacter) override;
7855
7856 template <typename Range>
7857 static void
7858 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7859 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7860 bool IsStringLocation, Range StringRange,
7861 ArrayRef<FixItHint> Fixit = {});
7862
7863protected:
7864 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7865 const char *startSpec,
7866 unsigned specifierLen,
7867 const char *csStart, unsigned csLen);
7868
7869 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7870 const char *startSpec,
7871 unsigned specifierLen);
7872
7873 SourceRange getFormatStringRange();
7874 CharSourceRange getSpecifierRange(const char *startSpecifier,
7875 unsigned specifierLen);
7876 SourceLocation getLocationOfByte(const char *x);
7877
7878 const Expr *getDataArg(unsigned i) const;
7879
7880 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7881 const analyze_format_string::ConversionSpecifier &CS,
7882 const char *startSpecifier, unsigned specifierLen,
7883 unsigned argIndex);
7884
7885 template <typename Range>
7886 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7887 bool IsStringLocation, Range StringRange,
7888 ArrayRef<FixItHint> Fixit = {});
7889};
7890
7891} // namespace
7892
7893SourceRange CheckFormatHandler::getFormatStringRange() {
7894 return OrigFormatExpr->getSourceRange();
7895}
7896
7897CharSourceRange CheckFormatHandler::
7898getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7899 SourceLocation Start = getLocationOfByte(startSpecifier);
7900 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7901
7902 // Advance the end SourceLocation by one due to half-open ranges.
7903 End = End.getLocWithOffset(1);
7904
7905 return CharSourceRange::getCharRange(Start, End);
7906}
7907
7908SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7909 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7911}
7912
7913void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7914 unsigned specifierLen){
7915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7916 getLocationOfByte(startSpecifier),
7917 /*IsStringLocation*/true,
7918 getSpecifierRange(startSpecifier, specifierLen));
7919}
7920
7921void CheckFormatHandler::HandleInvalidLengthModifier(
7924 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7925 using namespace analyze_format_string;
7926
7927 const LengthModifier &LM = FS.getLengthModifier();
7928 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7929
7930 // See if we know how to fix this length modifier.
7931 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7932 if (FixedLM) {
7933 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7934 getLocationOfByte(LM.getStart()),
7935 /*IsStringLocation*/true,
7936 getSpecifierRange(startSpecifier, specifierLen));
7937
7938 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7939 << FixedLM->toString()
7940 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7941
7942 } else {
7943 FixItHint Hint;
7944 if (DiagID == diag::warn_format_nonsensical_length)
7945 Hint = FixItHint::CreateRemoval(LMRange);
7946
7947 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7948 getLocationOfByte(LM.getStart()),
7949 /*IsStringLocation*/true,
7950 getSpecifierRange(startSpecifier, specifierLen),
7951 Hint);
7952 }
7953}
7954
7955void CheckFormatHandler::HandleNonStandardLengthModifier(
7957 const char *startSpecifier, unsigned specifierLen) {
7958 using namespace analyze_format_string;
7959
7960 const LengthModifier &LM = FS.getLengthModifier();
7961 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7962
7963 // See if we know how to fix this length modifier.
7964 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7965 if (FixedLM) {
7966 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7967 << LM.toString() << 0,
7968 getLocationOfByte(LM.getStart()),
7969 /*IsStringLocation*/true,
7970 getSpecifierRange(startSpecifier, specifierLen));
7971
7972 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7973 << FixedLM->toString()
7974 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7975
7976 } else {
7977 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7978 << LM.toString() << 0,
7979 getLocationOfByte(LM.getStart()),
7980 /*IsStringLocation*/true,
7981 getSpecifierRange(startSpecifier, specifierLen));
7982 }
7983}
7984
7985void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7987 const char *startSpecifier, unsigned specifierLen) {
7988 using namespace analyze_format_string;
7989
7990 // See if we know how to fix this conversion specifier.
7991 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7992 if (FixedCS) {
7993 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7994 << CS.toString() << /*conversion specifier*/1,
7995 getLocationOfByte(CS.getStart()),
7996 /*IsStringLocation*/true,
7997 getSpecifierRange(startSpecifier, specifierLen));
7998
7999 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8000 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8001 << FixedCS->toString()
8002 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8003 } else {
8004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8005 << CS.toString() << /*conversion specifier*/1,
8006 getLocationOfByte(CS.getStart()),
8007 /*IsStringLocation*/true,
8008 getSpecifierRange(startSpecifier, specifierLen));
8009 }
8010}
8011
8012void CheckFormatHandler::HandlePosition(const char *startPos,
8013 unsigned posLen) {
8014 if (!S.getDiagnostics().isIgnored(
8015 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8016 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8017 getLocationOfByte(startPos),
8018 /*IsStringLocation*/ true,
8019 getSpecifierRange(startPos, posLen));
8020}
8021
8022void CheckFormatHandler::HandleInvalidPosition(
8023 const char *startSpecifier, unsigned specifierLen,
8025 if (!S.getDiagnostics().isIgnored(
8026 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8027 EmitFormatDiagnostic(
8028 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8029 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8030 getSpecifierRange(startSpecifier, specifierLen));
8031}
8032
8033void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8034 unsigned posLen) {
8035 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8036 SourceLocation()))
8037 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8038 getLocationOfByte(startPos),
8039 /*IsStringLocation*/ true,
8040 getSpecifierRange(startPos, posLen));
8041}
8042
8043void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8044 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8045 // The presence of a null character is likely an error.
8046 EmitFormatDiagnostic(
8047 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8048 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8049 getFormatStringRange());
8050 }
8051}
8052
8053// Note that this may return NULL if there was an error parsing or building
8054// one of the argument expressions.
8055const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8056 return Args[FirstDataArg + i];
8057}
8058
8059void CheckFormatHandler::DoneProcessing() {
8060 // Does the number of data arguments exceed the number of
8061 // format conversions in the format string?
8062 if (HasFormatArguments()) {
8063 // Find any arguments that weren't covered.
8064 CoveredArgs.flip();
8065 signed notCoveredArg = CoveredArgs.find_first();
8066 if (notCoveredArg >= 0) {
8067 assert((unsigned)notCoveredArg < NumDataArgs);
8068 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8069 } else {
8070 UncoveredArg.setAllCovered();
8071 }
8072 }
8073}
8074
8075void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8076 const Expr *ArgExpr) {
8077 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
8078 "Invalid state");
8079
8080 if (!ArgExpr)
8081 return;
8082
8083 SourceLocation Loc = ArgExpr->getBeginLoc();
8084
8085 if (S.getSourceManager().isInSystemMacro(Loc))
8086 return;
8087
8088 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8089 for (auto E : DiagnosticExprs)
8090 PDiag << E->getSourceRange();
8091
8092 CheckFormatHandler::EmitFormatDiagnostic(
8093 S, IsFunctionCall, DiagnosticExprs[0],
8094 PDiag, Loc, /*IsStringLocation*/false,
8095 DiagnosticExprs[0]->getSourceRange());
8096}
8097
8098bool
8099CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8100 SourceLocation Loc,
8101 const char *startSpec,
8102 unsigned specifierLen,
8103 const char *csStart,
8104 unsigned csLen) {
8105 bool keepGoing = true;
8106 if (argIndex < NumDataArgs) {
8107 // Consider the argument coverered, even though the specifier doesn't
8108 // make sense.
8109 CoveredArgs.set(argIndex);
8110 }
8111 else {
8112 // If argIndex exceeds the number of data arguments we
8113 // don't issue a warning because that is just a cascade of warnings (and
8114 // they may have intended '%%' anyway). We don't want to continue processing
8115 // the format string after this point, however, as we will like just get
8116 // gibberish when trying to match arguments.
8117 keepGoing = false;
8118 }
8119
8120 StringRef Specifier(csStart, csLen);
8121
8122 // If the specifier in non-printable, it could be the first byte of a UTF-8
8123 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8124 // hex value.
8125 std::string CodePointStr;
8126 if (!llvm::sys::locale::isPrint(*csStart)) {
8127 llvm::UTF32 CodePoint;
8128 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8129 const llvm::UTF8 *E =
8130 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8131 llvm::ConversionResult Result =
8132 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8133
8134 if (Result != llvm::conversionOK) {
8135 unsigned char FirstChar = *csStart;
8136 CodePoint = (llvm::UTF32)FirstChar;
8137 }
8138
8139 llvm::raw_string_ostream OS(CodePointStr);
8140 if (CodePoint < 256)
8141 OS << "\\x" << llvm::format("%02x", CodePoint);
8142 else if (CodePoint <= 0xFFFF)
8143 OS << "\\u" << llvm::format("%04x", CodePoint);
8144 else
8145 OS << "\\U" << llvm::format("%08x", CodePoint);
8146 Specifier = CodePointStr;
8147 }
8148
8149 EmitFormatDiagnostic(
8150 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8151 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8152
8153 return keepGoing;
8154}
8155
8156void
8157CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8158 const char *startSpec,
8159 unsigned specifierLen) {
8160 EmitFormatDiagnostic(
8161 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8162 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8163}
8164
8165bool
8166CheckFormatHandler::CheckNumArgs(
8169 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8170
8171 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8173 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8174 << (argIndex+1) << NumDataArgs)
8175 : S.PDiag(diag::warn_printf_insufficient_data_args);
8176 EmitFormatDiagnostic(
8177 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8178 getSpecifierRange(startSpecifier, specifierLen));
8179
8180 // Since more arguments than conversion tokens are given, by extension
8181 // all arguments are covered, so mark this as so.
8182 UncoveredArg.setAllCovered();
8183 return false;
8184 }
8185 return true;
8186}
8187
8188template<typename Range>
8189void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8190 SourceLocation Loc,
8191 bool IsStringLocation,
8192 Range StringRange,
8193 ArrayRef<FixItHint> FixIt) {
8194 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8195 Loc, IsStringLocation, StringRange, FixIt);
8196}
8197
8198/// If the format string is not within the function call, emit a note
8199/// so that the function call and string are in diagnostic messages.
8200///
8201/// \param InFunctionCall if true, the format string is within the function
8202/// call and only one diagnostic message will be produced. Otherwise, an
8203/// extra note will be emitted pointing to location of the format string.
8204///
8205/// \param ArgumentExpr the expression that is passed as the format string
8206/// argument in the function call. Used for getting locations when two
8207/// diagnostics are emitted.
8208///
8209/// \param PDiag the callee should already have provided any strings for the
8210/// diagnostic message. This function only adds locations and fixits
8211/// to diagnostics.
8212///
8213/// \param Loc primary location for diagnostic. If two diagnostics are
8214/// required, one will be at Loc and a new SourceLocation will be created for
8215/// the other one.
8216///
8217/// \param IsStringLocation if true, Loc points to the format string should be
8218/// used for the note. Otherwise, Loc points to the argument list and will
8219/// be used with PDiag.
8220///
8221/// \param StringRange some or all of the string to highlight. This is
8222/// templated so it can accept either a CharSourceRange or a SourceRange.
8223///
8224/// \param FixIt optional fix it hint for the format string.
8225template <typename Range>
8226void CheckFormatHandler::EmitFormatDiagnostic(
8227 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8228 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8229 Range StringRange, ArrayRef<FixItHint> FixIt) {
8230 if (InFunctionCall) {
8231 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8232 D << StringRange;
8233 D << FixIt;
8234 } else {
8235 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8236 << ArgumentExpr->getSourceRange();
8237
8239 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8240 diag::note_format_string_defined);
8241
8242 Note << StringRange;
8243 Note << FixIt;
8244 }
8245}
8246
8247//===--- CHECK: Printf format string checking -----------------------------===//
8248
8249namespace {
8250
8251class CheckPrintfHandler : public CheckFormatHandler {
8252public:
8253 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8254 const Expr *origFormatExpr, const FormatStringType type,
8255 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8256 const char *beg, Sema::FormatArgumentPassingKind APK,
8257 ArrayRef<const Expr *> Args, unsigned formatIdx,
8258 bool inFunctionCall, VariadicCallType CallType,
8259 llvm::SmallBitVector &CheckedVarArgs,
8260 UncoveredArgHandler &UncoveredArg)
8261 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8262 numDataArgs, beg, APK, Args, formatIdx,
8263 inFunctionCall, CallType, CheckedVarArgs,
8264 UncoveredArg) {}
8265
8266 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8267
8268 /// Returns true if '%@' specifiers are allowed in the format string.
8269 bool allowsObjCArg() const {
8270 return FSType == FormatStringType::NSString ||
8271 FSType == FormatStringType::OSLog ||
8272 FSType == FormatStringType::OSTrace;
8273 }
8274
8275 bool HandleInvalidPrintfConversionSpecifier(
8276 const analyze_printf::PrintfSpecifier &FS,
8277 const char *startSpecifier,
8278 unsigned specifierLen) override;
8279
8280 void handleInvalidMaskType(StringRef MaskType) override;
8281
8282 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8283 const char *startSpecifier, unsigned specifierLen,
8284 const TargetInfo &Target) override;
8285 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8286 const char *StartSpecifier,
8287 unsigned SpecifierLen,
8288 const Expr *E);
8289
8290 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8291 const char *startSpecifier, unsigned specifierLen);
8292 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8293 const analyze_printf::OptionalAmount &Amt,
8294 unsigned type,
8295 const char *startSpecifier, unsigned specifierLen);
8296 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8297 const analyze_printf::OptionalFlag &flag,
8298 const char *startSpecifier, unsigned specifierLen);
8299 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8300 const analyze_printf::OptionalFlag &ignoredFlag,
8301 const analyze_printf::OptionalFlag &flag,
8302 const char *startSpecifier, unsigned specifierLen);
8303 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8304 const Expr *E);
8305
8306 void HandleEmptyObjCModifierFlag(const char *startFlag,
8307 unsigned flagLen) override;
8308
8309 void HandleInvalidObjCModifierFlag(const char *startFlag,
8310 unsigned flagLen) override;
8311
8312 void
8313 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8314 const char *flagsEnd,
8315 const char *conversionPosition) override;
8316};
8317
8318/// Keeps around the information needed to verify that two specifiers are
8319/// compatible.
8320class EquatableFormatArgument {
8321public:
8322 enum SpecifierSensitivity : unsigned {
8323 SS_None,
8324 SS_Private,
8325 SS_Public,
8326 SS_Sensitive
8327 };
8328
8329 enum FormatArgumentRole : unsigned {
8330 FAR_Data,
8331 FAR_FieldWidth,
8332 FAR_Precision,
8333 FAR_Auxiliary, // FreeBSD kernel %b and %D
8334 };
8335
8336private:
8337 analyze_format_string::ArgType ArgType;
8339 StringRef SpecifierLetter;
8340 CharSourceRange Range;
8341 SourceLocation ElementLoc;
8342 FormatArgumentRole Role : 2;
8343 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8344 unsigned Position : 14;
8345 unsigned ModifierFor : 14; // not set for FAR_Data
8346
8347 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8348 bool InFunctionCall) const;
8349
8350public:
8351 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8353 StringRef SpecifierLetter,
8354 analyze_format_string::ArgType ArgType,
8355 FormatArgumentRole Role,
8356 SpecifierSensitivity Sensitivity, unsigned Position,
8357 unsigned ModifierFor)
8358 : ArgType(ArgType), LengthMod(LengthMod),
8359 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8360 Role(Role), Sensitivity(Sensitivity), Position(Position),
8361 ModifierFor(ModifierFor) {}
8362
8363 unsigned getPosition() const { return Position; }
8364 SourceLocation getSourceLocation() const { return ElementLoc; }
8365 CharSourceRange getSourceRange() const { return Range; }
8366 analyze_format_string::LengthModifier getLengthModifier() const {
8367 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8368 }
8369 void setModifierFor(unsigned V) { ModifierFor = V; }
8370
8371 std::string buildFormatSpecifier() const {
8372 std::string result;
8373 llvm::raw_string_ostream(result)
8374 << getLengthModifier().toString() << SpecifierLetter;
8375 return result;
8376 }
8377
8378 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8379 const Expr *FmtExpr, bool InFunctionCall) const;
8380};
8381
8382/// Turns format strings into lists of EquatableSpecifier objects.
8383class DecomposePrintfHandler : public CheckPrintfHandler {
8384 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8385 bool HadError;
8386
8387 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8388 const Expr *origFormatExpr,
8389 const FormatStringType type, unsigned firstDataArg,
8390 unsigned numDataArgs, bool isObjC, const char *beg,
8392 ArrayRef<const Expr *> Args, unsigned formatIdx,
8393 bool inFunctionCall, VariadicCallType CallType,
8394 llvm::SmallBitVector &CheckedVarArgs,
8395 UncoveredArgHandler &UncoveredArg,
8396 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8397 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8398 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8399 inFunctionCall, CallType, CheckedVarArgs,
8400 UncoveredArg),
8401 Specs(Specs), HadError(false) {}
8402
8403public:
8404 static bool
8405 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8406 FormatStringType type, bool IsObjC, bool InFunctionCall,
8407 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8408
8409 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8410 const char *startSpecifier,
8411 unsigned specifierLen,
8412 const TargetInfo &Target) override;
8413};
8414
8415} // namespace
8416
8417bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8418 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8419 unsigned specifierLen) {
8422
8423 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8424 getLocationOfByte(CS.getStart()),
8425 startSpecifier, specifierLen,
8426 CS.getStart(), CS.getLength());
8427}
8428
8429void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8430 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8431}
8432
8433// Error out if struct or complex type argments are passed to os_log.
8435 QualType T) {
8436 if (FSType != FormatStringType::OSLog)
8437 return false;
8438 return T->isRecordType() || T->isComplexType();
8439}
8440
8441bool CheckPrintfHandler::HandleAmount(
8442 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8443 const char *startSpecifier, unsigned specifierLen) {
8444 if (Amt.hasDataArgument()) {
8445 if (HasFormatArguments()) {
8446 unsigned argIndex = Amt.getArgIndex();
8447 if (argIndex >= NumDataArgs) {
8448 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8449 << k,
8450 getLocationOfByte(Amt.getStart()),
8451 /*IsStringLocation*/ true,
8452 getSpecifierRange(startSpecifier, specifierLen));
8453 // Don't do any more checking. We will just emit
8454 // spurious errors.
8455 return false;
8456 }
8457
8458 // Type check the data argument. It should be an 'int'.
8459 // Although not in conformance with C99, we also allow the argument to be
8460 // an 'unsigned int' as that is a reasonably safe case. GCC also
8461 // doesn't emit a warning for that case.
8462 CoveredArgs.set(argIndex);
8463 const Expr *Arg = getDataArg(argIndex);
8464 if (!Arg)
8465 return false;
8466
8467 QualType T = Arg->getType();
8468
8469 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8470 assert(AT.isValid());
8471
8472 if (!AT.matchesType(S.Context, T)) {
8473 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8474 ? diag::err_printf_asterisk_wrong_type
8475 : diag::warn_printf_asterisk_wrong_type;
8476 EmitFormatDiagnostic(S.PDiag(DiagID)
8478 << T << Arg->getSourceRange(),
8479 getLocationOfByte(Amt.getStart()),
8480 /*IsStringLocation*/ true,
8481 getSpecifierRange(startSpecifier, specifierLen));
8482 // Don't do any more checking. We will just emit
8483 // spurious errors.
8484 return false;
8485 }
8486 }
8487 }
8488 return true;
8489}
8490
8491void CheckPrintfHandler::HandleInvalidAmount(
8494 unsigned type,
8495 const char *startSpecifier,
8496 unsigned specifierLen) {
8499
8500 FixItHint fixit =
8502 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8503 Amt.getConstantLength()))
8504 : FixItHint();
8505
8506 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8507 << type << CS.toString(),
8508 getLocationOfByte(Amt.getStart()),
8509 /*IsStringLocation*/true,
8510 getSpecifierRange(startSpecifier, specifierLen),
8511 fixit);
8512}
8513
8514void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8515 const analyze_printf::OptionalFlag &flag,
8516 const char *startSpecifier,
8517 unsigned specifierLen) {
8518 // Warn about pointless flag with a fixit removal.
8521 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8522 << flag.toString() << CS.toString(),
8523 getLocationOfByte(flag.getPosition()),
8524 /*IsStringLocation*/true,
8525 getSpecifierRange(startSpecifier, specifierLen),
8527 getSpecifierRange(flag.getPosition(), 1)));
8528}
8529
8530void CheckPrintfHandler::HandleIgnoredFlag(
8532 const analyze_printf::OptionalFlag &ignoredFlag,
8533 const analyze_printf::OptionalFlag &flag,
8534 const char *startSpecifier,
8535 unsigned specifierLen) {
8536 // Warn about ignored flag with a fixit removal.
8537 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8538 << ignoredFlag.toString() << flag.toString(),
8539 getLocationOfByte(ignoredFlag.getPosition()),
8540 /*IsStringLocation*/true,
8541 getSpecifierRange(startSpecifier, specifierLen),
8543 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8544}
8545
8546void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8547 unsigned flagLen) {
8548 // Warn about an empty flag.
8549 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8550 getLocationOfByte(startFlag),
8551 /*IsStringLocation*/true,
8552 getSpecifierRange(startFlag, flagLen));
8553}
8554
8555void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8556 unsigned flagLen) {
8557 // Warn about an invalid flag.
8558 auto Range = getSpecifierRange(startFlag, flagLen);
8559 StringRef flag(startFlag, flagLen);
8560 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8561 getLocationOfByte(startFlag),
8562 /*IsStringLocation*/true,
8563 Range, FixItHint::CreateRemoval(Range));
8564}
8565
8566void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8567 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8568 // Warn about using '[...]' without a '@' conversion.
8569 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8570 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8571 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8572 getLocationOfByte(conversionPosition),
8573 /*IsStringLocation*/ true, Range,
8575}
8576
8577void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8578 const Expr *FmtExpr,
8579 bool InFunctionCall) const {
8580 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8581 ElementLoc, true, Range);
8582}
8583
8584bool EquatableFormatArgument::VerifyCompatible(
8585 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8586 bool InFunctionCall) const {
8588 if (Role != Other.Role) {
8589 // diagnose and stop
8590 EmitDiagnostic(
8591 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8592 FmtExpr, InFunctionCall);
8593 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8594 return false;
8595 }
8596
8597 if (Role != FAR_Data) {
8598 if (ModifierFor != Other.ModifierFor) {
8599 // diagnose and stop
8600 EmitDiagnostic(S,
8601 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8602 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8603 FmtExpr, InFunctionCall);
8604 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8605 return false;
8606 }
8607 return true;
8608 }
8609
8610 bool HadError = false;
8611 if (Sensitivity != Other.Sensitivity) {
8612 // diagnose and continue
8613 EmitDiagnostic(S,
8614 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8615 << Sensitivity << Other.Sensitivity,
8616 FmtExpr, InFunctionCall);
8617 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8618 << 0 << Other.Range;
8619 }
8620
8621 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8622 case MK::Match:
8623 break;
8624
8625 case MK::MatchPromotion:
8626 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8627 // MatchPromotion is treated as a failure by format_matches.
8628 case MK::NoMatch:
8629 case MK::NoMatchTypeConfusion:
8630 case MK::NoMatchPromotionTypeConfusion:
8631 EmitDiagnostic(S,
8632 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8633 << buildFormatSpecifier()
8634 << Other.buildFormatSpecifier(),
8635 FmtExpr, InFunctionCall);
8636 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8637 << 0 << Other.Range;
8638 break;
8639
8640 case MK::NoMatchPedantic:
8641 EmitDiagnostic(S,
8642 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8643 << buildFormatSpecifier()
8644 << Other.buildFormatSpecifier(),
8645 FmtExpr, InFunctionCall);
8646 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8647 << 0 << Other.Range;
8648 break;
8649
8650 case MK::NoMatchSignedness:
8651 EmitDiagnostic(S,
8652 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8653 << buildFormatSpecifier()
8654 << Other.buildFormatSpecifier(),
8655 FmtExpr, InFunctionCall);
8656 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8657 << 0 << Other.Range;
8658 break;
8659 }
8660 return !HadError;
8661}
8662
8663bool DecomposePrintfHandler::GetSpecifiers(
8664 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8665 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8667 StringRef Data = FSL->getString();
8668 const char *Str = Data.data();
8669 llvm::SmallBitVector BV;
8670 UncoveredArgHandler UA;
8671 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8672 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8673 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8674 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8675 UA, Args);
8676
8678 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8680 H.DoneProcessing();
8681 if (H.HadError)
8682 return false;
8683
8684 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8685 const EquatableFormatArgument &B) {
8686 return A.getPosition() < B.getPosition();
8687 });
8688 return true;
8689}
8690
8691bool DecomposePrintfHandler::HandlePrintfSpecifier(
8692 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8693 unsigned specifierLen, const TargetInfo &Target) {
8694 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8695 specifierLen, Target)) {
8696 HadError = true;
8697 return false;
8698 }
8699
8700 // Do not add any specifiers to the list for %%. This is possibly incorrect
8701 // if using a precision/width with a data argument, but that combination is
8702 // meaningless and we wouldn't know which format to attach the
8703 // precision/width to.
8704 const auto &CS = FS.getConversionSpecifier();
8706 return true;
8707
8708 // have to patch these to have the right ModifierFor if they are used
8709 const unsigned Unset = ~0;
8710 unsigned FieldWidthIndex = Unset;
8711 unsigned PrecisionIndex = Unset;
8712
8713 // field width?
8714 const auto &FieldWidth = FS.getFieldWidth();
8715 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8716 FieldWidthIndex = Specs.size();
8717 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8718 getLocationOfByte(FieldWidth.getStart()),
8720 FieldWidth.getArgType(S.Context),
8721 EquatableFormatArgument::FAR_FieldWidth,
8722 EquatableFormatArgument::SS_None,
8723 FieldWidth.usesPositionalArg()
8724 ? FieldWidth.getPositionalArgIndex() - 1
8725 : FieldWidthIndex,
8726 0);
8727 }
8728 // precision?
8729 const auto &Precision = FS.getPrecision();
8730 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8731 PrecisionIndex = Specs.size();
8732 Specs.emplace_back(
8733 getSpecifierRange(startSpecifier, specifierLen),
8734 getLocationOfByte(Precision.getStart()),
8736 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8737 EquatableFormatArgument::SS_None,
8738 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8739 : PrecisionIndex,
8740 0);
8741 }
8742
8743 // this specifier
8744 unsigned SpecIndex =
8745 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8746 if (FieldWidthIndex != Unset)
8747 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8748 if (PrecisionIndex != Unset)
8749 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8750
8751 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8752 if (FS.isPrivate())
8753 Sensitivity = EquatableFormatArgument::SS_Private;
8754 else if (FS.isPublic())
8755 Sensitivity = EquatableFormatArgument::SS_Public;
8756 else if (FS.isSensitive())
8757 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8758 else
8759 Sensitivity = EquatableFormatArgument::SS_None;
8760
8761 Specs.emplace_back(
8762 getSpecifierRange(startSpecifier, specifierLen),
8763 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8764 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8765 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8766
8767 // auxiliary argument?
8770 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8771 getLocationOfByte(CS.getStart()),
8773 CS.getCharacters(),
8775 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8776 SpecIndex + 1, SpecIndex);
8777 }
8778 return true;
8779}
8780
8781// Determines if the specified is a C++ class or struct containing
8782// a member with the specified name and kind (e.g. a CXXMethodDecl named
8783// "c_str()").
8784template<typename MemberKind>
8786CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8787 auto *RD = Ty->getAsCXXRecordDecl();
8789
8790 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8791 return Results;
8792
8793 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8795 R.suppressDiagnostics();
8796
8797 // We just need to include all members of the right kind turned up by the
8798 // filter, at this point.
8799 if (S.LookupQualifiedName(R, RD))
8800 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8801 NamedDecl *decl = (*I)->getUnderlyingDecl();
8802 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8803 Results.insert(FK);
8804 }
8805 return Results;
8806}
8807
8808/// Check if we could call '.c_str()' on an object.
8809///
8810/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8811/// allow the call, or if it would be ambiguous).
8813 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8814
8815 MethodSet Results =
8816 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8817 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8818 MI != ME; ++MI)
8819 if ((*MI)->getMinRequiredArguments() == 0)
8820 return true;
8821 return false;
8822}
8823
8824// Check if a (w)string was passed when a (w)char* was needed, and offer a
8825// better diagnostic if so. AT is assumed to be valid.
8826// Returns true when a c_str() conversion method is found.
8827bool CheckPrintfHandler::checkForCStrMembers(
8828 const analyze_printf::ArgType &AT, const Expr *E) {
8829 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8830
8831 MethodSet Results =
8833
8834 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8835 MI != ME; ++MI) {
8836 const CXXMethodDecl *Method = *MI;
8837 if (Method->getMinRequiredArguments() == 0 &&
8838 AT.matchesType(S.Context, Method->getReturnType())) {
8839 // FIXME: Suggest parens if the expression needs them.
8841 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8842 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8843 return true;
8844 }
8845 }
8846
8847 return false;
8848}
8849
8850bool CheckPrintfHandler::HandlePrintfSpecifier(
8851 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8852 unsigned specifierLen, const TargetInfo &Target) {
8853 using namespace analyze_format_string;
8854 using namespace analyze_printf;
8855
8856 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8857
8858 if (FS.consumesDataArgument()) {
8859 if (atFirstArg) {
8860 atFirstArg = false;
8861 usesPositionalArgs = FS.usesPositionalArg();
8862 }
8863 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8864 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8865 startSpecifier, specifierLen);
8866 return false;
8867 }
8868 }
8869
8870 // First check if the field width, precision, and conversion specifier
8871 // have matching data arguments.
8872 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8873 startSpecifier, specifierLen)) {
8874 return false;
8875 }
8876
8877 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8878 startSpecifier, specifierLen)) {
8879 return false;
8880 }
8881
8882 if (!CS.consumesDataArgument()) {
8883 // FIXME: Technically specifying a precision or field width here
8884 // makes no sense. Worth issuing a warning at some point.
8885 return true;
8886 }
8887
8888 // Consume the argument.
8889 unsigned argIndex = FS.getArgIndex();
8890 if (argIndex < NumDataArgs) {
8891 // The check to see if the argIndex is valid will come later.
8892 // We set the bit here because we may exit early from this
8893 // function if we encounter some other error.
8894 CoveredArgs.set(argIndex);
8895 }
8896
8897 // FreeBSD kernel extensions.
8898 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8899 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8900 // We need at least two arguments.
8901 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8902 return false;
8903
8904 if (HasFormatArguments()) {
8905 // Claim the second argument.
8906 CoveredArgs.set(argIndex + 1);
8907
8908 // Type check the first argument (int for %b, pointer for %D)
8909 const Expr *Ex = getDataArg(argIndex);
8910 const analyze_printf::ArgType &AT =
8911 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8912 ? ArgType(S.Context.IntTy)
8913 : ArgType::CPointerTy;
8914 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8915 EmitFormatDiagnostic(
8916 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8917 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8918 << false << Ex->getSourceRange(),
8919 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8920 getSpecifierRange(startSpecifier, specifierLen));
8921
8922 // Type check the second argument (char * for both %b and %D)
8923 Ex = getDataArg(argIndex + 1);
8925 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8926 EmitFormatDiagnostic(
8927 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8928 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8929 << false << Ex->getSourceRange(),
8930 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8931 getSpecifierRange(startSpecifier, specifierLen));
8932 }
8933 return true;
8934 }
8935
8936 // Check for using an Objective-C specific conversion specifier
8937 // in a non-ObjC literal.
8938 if (!allowsObjCArg() && CS.isObjCArg()) {
8939 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8940 specifierLen);
8941 }
8942
8943 // %P can only be used with os_log.
8944 if (FSType != FormatStringType::OSLog &&
8945 CS.getKind() == ConversionSpecifier::PArg) {
8946 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8947 specifierLen);
8948 }
8949
8950 // %n is not allowed with os_log.
8951 if (FSType == FormatStringType::OSLog &&
8952 CS.getKind() == ConversionSpecifier::nArg) {
8953 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8954 getLocationOfByte(CS.getStart()),
8955 /*IsStringLocation*/ false,
8956 getSpecifierRange(startSpecifier, specifierLen));
8957
8958 return true;
8959 }
8960
8961 // Only scalars are allowed for os_trace.
8962 if (FSType == FormatStringType::OSTrace &&
8963 (CS.getKind() == ConversionSpecifier::PArg ||
8964 CS.getKind() == ConversionSpecifier::sArg ||
8965 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8966 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8967 specifierLen);
8968 }
8969
8970 // Check for use of public/private annotation outside of os_log().
8971 if (FSType != FormatStringType::OSLog) {
8972 if (FS.isPublic().isSet()) {
8973 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8974 << "public",
8975 getLocationOfByte(FS.isPublic().getPosition()),
8976 /*IsStringLocation*/ false,
8977 getSpecifierRange(startSpecifier, specifierLen));
8978 }
8979 if (FS.isPrivate().isSet()) {
8980 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8981 << "private",
8982 getLocationOfByte(FS.isPrivate().getPosition()),
8983 /*IsStringLocation*/ false,
8984 getSpecifierRange(startSpecifier, specifierLen));
8985 }
8986 }
8987
8988 const llvm::Triple &Triple = Target.getTriple();
8989 if (CS.getKind() == ConversionSpecifier::nArg &&
8990 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8991 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8992 getLocationOfByte(CS.getStart()),
8993 /*IsStringLocation*/ false,
8994 getSpecifierRange(startSpecifier, specifierLen));
8995 }
8996
8997 // Check for invalid use of field width
8998 if (!FS.hasValidFieldWidth()) {
8999 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9000 startSpecifier, specifierLen);
9001 }
9002
9003 // Check for invalid use of precision
9004 if (!FS.hasValidPrecision()) {
9005 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9006 startSpecifier, specifierLen);
9007 }
9008
9009 // Precision is mandatory for %P specifier.
9010 if (CS.getKind() == ConversionSpecifier::PArg &&
9012 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9013 getLocationOfByte(startSpecifier),
9014 /*IsStringLocation*/ false,
9015 getSpecifierRange(startSpecifier, specifierLen));
9016 }
9017
9018 // Check each flag does not conflict with any other component.
9020 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9021 if (!FS.hasValidLeadingZeros())
9022 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9023 if (!FS.hasValidPlusPrefix())
9024 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9025 if (!FS.hasValidSpacePrefix())
9026 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9027 if (!FS.hasValidAlternativeForm())
9028 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9029 if (!FS.hasValidLeftJustified())
9030 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9031
9032 // Check that flags are not ignored by another flag
9033 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9034 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9035 startSpecifier, specifierLen);
9036 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9037 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9038 startSpecifier, specifierLen);
9039
9040 // Check the length modifier is valid with the given conversion specifier.
9042 S.getLangOpts()))
9043 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9044 diag::warn_format_nonsensical_length);
9045 else if (!FS.hasStandardLengthModifier())
9046 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9048 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9049 diag::warn_format_non_standard_conversion_spec);
9050
9052 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9053
9054 // The remaining checks depend on the data arguments.
9055 if (!HasFormatArguments())
9056 return true;
9057
9058 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9059 return false;
9060
9061 const Expr *Arg = getDataArg(argIndex);
9062 if (!Arg)
9063 return true;
9064
9065 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9066}
9067
9068static bool requiresParensToAddCast(const Expr *E) {
9069 // FIXME: We should have a general way to reason about operator
9070 // precedence and whether parens are actually needed here.
9071 // Take care of a few common cases where they aren't.
9072 const Expr *Inside = E->IgnoreImpCasts();
9073 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9074 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9075
9076 switch (Inside->getStmtClass()) {
9077 case Stmt::ArraySubscriptExprClass:
9078 case Stmt::CallExprClass:
9079 case Stmt::CharacterLiteralClass:
9080 case Stmt::CXXBoolLiteralExprClass:
9081 case Stmt::DeclRefExprClass:
9082 case Stmt::FloatingLiteralClass:
9083 case Stmt::IntegerLiteralClass:
9084 case Stmt::MemberExprClass:
9085 case Stmt::ObjCArrayLiteralClass:
9086 case Stmt::ObjCBoolLiteralExprClass:
9087 case Stmt::ObjCBoxedExprClass:
9088 case Stmt::ObjCDictionaryLiteralClass:
9089 case Stmt::ObjCEncodeExprClass:
9090 case Stmt::ObjCIvarRefExprClass:
9091 case Stmt::ObjCMessageExprClass:
9092 case Stmt::ObjCPropertyRefExprClass:
9093 case Stmt::ObjCStringLiteralClass:
9094 case Stmt::ObjCSubscriptRefExprClass:
9095 case Stmt::ParenExprClass:
9096 case Stmt::StringLiteralClass:
9097 case Stmt::UnaryOperatorClass:
9098 return false;
9099 default:
9100 return true;
9101 }
9102}
9103
9104static std::pair<QualType, StringRef>
9106 QualType IntendedTy,
9107 const Expr *E) {
9108 // Use a 'while' to peel off layers of typedefs.
9109 QualType TyTy = IntendedTy;
9110 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9111 StringRef Name = UserTy->getDecl()->getName();
9112 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9113 .Case("CFIndex", Context.getNSIntegerType())
9114 .Case("NSInteger", Context.getNSIntegerType())
9115 .Case("NSUInteger", Context.getNSUIntegerType())
9116 .Case("SInt32", Context.IntTy)
9117 .Case("UInt32", Context.UnsignedIntTy)
9118 .Default(QualType());
9119
9120 if (!CastTy.isNull())
9121 return std::make_pair(CastTy, Name);
9122
9123 TyTy = UserTy->desugar();
9124 }
9125
9126 // Strip parens if necessary.
9127 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9128 return shouldNotPrintDirectly(Context,
9129 PE->getSubExpr()->getType(),
9130 PE->getSubExpr());
9131
9132 // If this is a conditional expression, then its result type is constructed
9133 // via usual arithmetic conversions and thus there might be no necessary
9134 // typedef sugar there. Recurse to operands to check for NSInteger &
9135 // Co. usage condition.
9136 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9137 QualType TrueTy, FalseTy;
9138 StringRef TrueName, FalseName;
9139
9140 std::tie(TrueTy, TrueName) =
9141 shouldNotPrintDirectly(Context,
9142 CO->getTrueExpr()->getType(),
9143 CO->getTrueExpr());
9144 std::tie(FalseTy, FalseName) =
9145 shouldNotPrintDirectly(Context,
9146 CO->getFalseExpr()->getType(),
9147 CO->getFalseExpr());
9148
9149 if (TrueTy == FalseTy)
9150 return std::make_pair(TrueTy, TrueName);
9151 else if (TrueTy.isNull())
9152 return std::make_pair(FalseTy, FalseName);
9153 else if (FalseTy.isNull())
9154 return std::make_pair(TrueTy, TrueName);
9155 }
9156
9157 return std::make_pair(QualType(), StringRef());
9158}
9159
9160/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9161/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9162/// type do not count.
9163static bool
9165 QualType From = ICE->getSubExpr()->getType();
9166 QualType To = ICE->getType();
9167 // It's an integer promotion if the destination type is the promoted
9168 // source type.
9169 if (ICE->getCastKind() == CK_IntegralCast &&
9171 S.Context.getPromotedIntegerType(From) == To)
9172 return true;
9173 // Look through vector types, since we do default argument promotion for
9174 // those in OpenCL.
9175 if (const auto *VecTy = From->getAs<ExtVectorType>())
9176 From = VecTy->getElementType();
9177 if (const auto *VecTy = To->getAs<ExtVectorType>())
9178 To = VecTy->getElementType();
9179 // It's a floating promotion if the source type is a lower rank.
9180 return ICE->getCastKind() == CK_FloatingCast &&
9181 S.Context.getFloatingTypeOrder(From, To) < 0;
9182}
9183
9186 DiagnosticsEngine &Diags, SourceLocation Loc) {
9188 if (Diags.isIgnored(
9189 diag::warn_format_conversion_argument_type_mismatch_signedness,
9190 Loc) ||
9191 Diags.isIgnored(
9192 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9193 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9195 }
9196 }
9197 return Match;
9198}
9199
9200bool
9201CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9202 const char *StartSpecifier,
9203 unsigned SpecifierLen,
9204 const Expr *E) {
9205 using namespace analyze_format_string;
9206 using namespace analyze_printf;
9207
9208 // Now type check the data expression that matches the
9209 // format specifier.
9210 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9211 if (!AT.isValid())
9212 return true;
9213
9214 QualType ExprTy = E->getType();
9215 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9216 ExprTy = TET->getUnderlyingExpr()->getType();
9217 }
9218
9219 if (const OverflowBehaviorType *OBT =
9220 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9221 ExprTy = OBT->getUnderlyingType();
9222
9223 // When using the format attribute in C++, you can receive a function or an
9224 // array that will necessarily decay to a pointer when passed to the final
9225 // format consumer. Apply decay before type comparison.
9226 if (ExprTy->canDecayToPointerType())
9227 ExprTy = S.Context.getDecayedType(ExprTy);
9228
9229 // Diagnose attempts to print a boolean value as a character. Unlike other
9230 // -Wformat diagnostics, this is fine from a type perspective, but it still
9231 // doesn't make sense.
9234 const CharSourceRange &CSR =
9235 getSpecifierRange(StartSpecifier, SpecifierLen);
9236 SmallString<4> FSString;
9237 llvm::raw_svector_ostream os(FSString);
9238 FS.toString(os);
9239 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9240 << FSString,
9241 E->getExprLoc(), false, CSR);
9242 return true;
9243 }
9244
9245 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9246 // dumping raw class data (like is-a pointer), not actual data.
9248 ExprTy->isObjCObjectPointerType()) {
9249 const CharSourceRange &CSR =
9250 getSpecifierRange(StartSpecifier, SpecifierLen);
9251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9252 E->getExprLoc(), false, CSR);
9253 return true;
9254 }
9255
9256 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9258 ArgType::MatchKind OrigMatch = Match;
9259
9261 if (Match == ArgType::Match)
9262 return true;
9263
9264 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9265 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9266
9267 // Look through argument promotions for our error message's reported type.
9268 // This includes the integral and floating promotions, but excludes array
9269 // and function pointer decay (seeing that an argument intended to be a
9270 // string has type 'char [6]' is probably more confusing than 'char *') and
9271 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9272 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9273 if (isArithmeticArgumentPromotion(S, ICE)) {
9274 E = ICE->getSubExpr();
9275 ExprTy = E->getType();
9276
9277 // Check if we didn't match because of an implicit cast from a 'char'
9278 // or 'short' to an 'int'. This is done because printf is a varargs
9279 // function.
9280 if (ICE->getType() == S.Context.IntTy ||
9281 ICE->getType() == S.Context.UnsignedIntTy) {
9282 // All further checking is done on the subexpression
9283 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9284 if (OrigMatch == ArgType::NoMatchSignedness &&
9285 ImplicitMatch != ArgType::NoMatchSignedness)
9286 // If the original match was a signedness match this match on the
9287 // implicit cast type also need to be signedness match otherwise we
9288 // might introduce new unexpected warnings from -Wformat-signedness.
9289 return true;
9290 ImplicitMatch = handleFormatSignedness(
9291 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9292 if (ImplicitMatch == ArgType::Match)
9293 return true;
9294 }
9295 }
9296 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9297 // Special case for 'a', which has type 'int' in C.
9298 // Note, however, that we do /not/ want to treat multibyte constants like
9299 // 'MooV' as characters! This form is deprecated but still exists. In
9300 // addition, don't treat expressions as of type 'char' if one byte length
9301 // modifier is provided.
9302 if (ExprTy == S.Context.IntTy &&
9304 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9305 ExprTy = S.Context.CharTy;
9306 // To improve check results, we consider a character literal in C
9307 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9308 // more likely a type confusion situation, so we will suggest to
9309 // use '%hhd' instead by discarding the MatchPromotion.
9310 if (Match == ArgType::MatchPromotion)
9312 }
9313 }
9314 if (Match == ArgType::MatchPromotion) {
9315 // WG14 N2562 only clarified promotions in *printf
9316 // For NSLog in ObjC, just preserve -Wformat behavior
9317 if (!S.getLangOpts().ObjC &&
9318 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9319 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9320 return true;
9322 }
9323 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9324 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9325 Match = ImplicitMatch;
9326 assert(Match != ArgType::MatchPromotion);
9327
9328 // Look through unscoped enums to their underlying type.
9329 bool IsEnum = false;
9330 bool IsScopedEnum = false;
9331 QualType IntendedTy = ExprTy;
9332 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9333 IntendedTy = ED->getIntegerType();
9334 if (!ED->isScoped()) {
9335 ExprTy = IntendedTy;
9336 // This controls whether we're talking about the underlying type or not,
9337 // which we only want to do when it's an unscoped enum.
9338 IsEnum = true;
9339 } else {
9340 IsScopedEnum = true;
9341 }
9342 }
9343
9344 // %C in an Objective-C context prints a unichar, not a wchar_t.
9345 // If the argument is an integer of some kind, believe the %C and suggest
9346 // a cast instead of changing the conversion specifier.
9347 if (isObjCContext() &&
9350 !ExprTy->isCharType()) {
9351 // 'unichar' is defined as a typedef of unsigned short, but we should
9352 // prefer using the typedef if it is visible.
9353 IntendedTy = S.Context.UnsignedShortTy;
9354
9355 // While we are here, check if the value is an IntegerLiteral that happens
9356 // to be within the valid range.
9357 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9358 const llvm::APInt &V = IL->getValue();
9359 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9360 return true;
9361 }
9362
9363 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9365 if (S.LookupName(Result, S.getCurScope())) {
9366 NamedDecl *ND = Result.getFoundDecl();
9367 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9368 if (TD->getUnderlyingType() == IntendedTy)
9369 IntendedTy =
9371 /*Qualifier=*/std::nullopt, TD);
9372 }
9373 }
9374 }
9375
9376 // Special-case some of Darwin's platform-independence types by suggesting
9377 // casts to primitive types that are known to be large enough.
9378 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9379 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9380 QualType CastTy;
9381 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9382 if (!CastTy.isNull()) {
9383 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9384 // (long in ASTContext). Only complain to pedants or when they're the
9385 // underlying type of a scoped enum (which always needs a cast).
9386 if (!IsScopedEnum &&
9387 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9388 (AT.isSizeT() || AT.isPtrdiffT()) &&
9389 AT.matchesType(S.Context, CastTy))
9391 IntendedTy = CastTy;
9392 ShouldNotPrintDirectly = true;
9393 }
9394 }
9395
9396 // We may be able to offer a FixItHint if it is a supported type.
9397 PrintfSpecifier fixedFS = FS;
9398 bool Success =
9399 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9400
9401 if (Success) {
9402 // Get the fix string from the fixed format specifier
9403 SmallString<16> buf;
9404 llvm::raw_svector_ostream os(buf);
9405 fixedFS.toString(os);
9406
9407 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9408
9409 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9410 unsigned Diag;
9411 switch (Match) {
9412 case ArgType::Match:
9415 llvm_unreachable("expected non-matching");
9417 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9418 break;
9420 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9421 break;
9423 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9424 break;
9425 case ArgType::NoMatch:
9426 Diag = diag::warn_format_conversion_argument_type_mismatch;
9427 break;
9428 }
9429
9430 // In this case, the specifier is wrong and should be changed to match
9431 // the argument.
9432 EmitFormatDiagnostic(S.PDiag(Diag)
9434 << IntendedTy << IsEnum << E->getSourceRange(),
9435 E->getBeginLoc(),
9436 /*IsStringLocation*/ false, SpecRange,
9437 FixItHint::CreateReplacement(SpecRange, os.str()));
9438 } else {
9439 // The canonical type for formatting this value is different from the
9440 // actual type of the expression. (This occurs, for example, with Darwin's
9441 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9442 // should be printed as 'long' for 64-bit compatibility.)
9443 // Rather than emitting a normal format/argument mismatch, we want to
9444 // add a cast to the recommended type (and correct the format string
9445 // if necessary). We should also do so for scoped enumerations.
9446 SmallString<16> CastBuf;
9447 llvm::raw_svector_ostream CastFix(CastBuf);
9448 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9449 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9450 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9451
9453 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9454 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9455 E->getExprLoc());
9456 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9457 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9458
9459 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9460 // If there's already a cast present, just replace it.
9461 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9462 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9463
9464 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9465 // If the expression has high enough precedence,
9466 // just write the C-style cast.
9467 Hints.push_back(
9468 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9469 } else {
9470 // Otherwise, add parens around the expression as well as the cast.
9471 CastFix << "(";
9472 Hints.push_back(
9473 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9474
9475 // We don't use getLocForEndOfToken because it returns invalid source
9476 // locations for macro expansions (by design).
9480 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9481 }
9482
9483 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9484 // The expression has a type that should not be printed directly.
9485 // We extract the name from the typedef because we don't want to show
9486 // the underlying type in the diagnostic.
9487 StringRef Name;
9488 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9489 Name = TypedefTy->getDecl()->getName();
9490 else
9491 Name = CastTyName;
9492 unsigned Diag = Match == ArgType::NoMatchPedantic
9493 ? diag::warn_format_argument_needs_cast_pedantic
9494 : diag::warn_format_argument_needs_cast;
9495 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9496 << E->getSourceRange(),
9497 E->getBeginLoc(), /*IsStringLocation=*/false,
9498 SpecRange, Hints);
9499 } else {
9500 // In this case, the expression could be printed using a different
9501 // specifier, but we've decided that the specifier is probably correct
9502 // and we should cast instead. Just use the normal warning message.
9503
9504 unsigned Diag =
9505 IsScopedEnum
9506 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9507 : diag::warn_format_conversion_argument_type_mismatch;
9508
9509 EmitFormatDiagnostic(
9510 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9511 << IsEnum << E->getSourceRange(),
9512 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9513 }
9514 }
9515 } else {
9516 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9517 SpecifierLen);
9518 // Since the warning for passing non-POD types to variadic functions
9519 // was deferred until now, we emit a warning for non-POD
9520 // arguments here.
9521 bool EmitTypeMismatch = false;
9522 switch (S.isValidVarArgType(ExprTy)) {
9523 case VarArgKind::Valid:
9525 unsigned Diag;
9526 switch (Match) {
9527 case ArgType::Match:
9530 llvm_unreachable("expected non-matching");
9532 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9533 break;
9535 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9536 break;
9538 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9539 break;
9540 case ArgType::NoMatch:
9541 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9542 ? diag::err_format_conversion_argument_type_mismatch
9543 : diag::warn_format_conversion_argument_type_mismatch;
9544 break;
9545 }
9546
9547 EmitFormatDiagnostic(
9548 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9549 << IsEnum << CSR << E->getSourceRange(),
9550 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9551 break;
9552 }
9555 if (CallType == VariadicCallType::DoesNotApply) {
9556 EmitTypeMismatch = true;
9557 } else {
9558 EmitFormatDiagnostic(
9559 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9560 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9561 << AT.getRepresentativeTypeName(S.Context) << CSR
9562 << E->getSourceRange(),
9563 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9564 checkForCStrMembers(AT, E);
9565 }
9566 break;
9567
9569 if (CallType == VariadicCallType::DoesNotApply)
9570 EmitTypeMismatch = true;
9571 else if (ExprTy->isObjCObjectType())
9572 EmitFormatDiagnostic(
9573 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9574 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9575 << AT.getRepresentativeTypeName(S.Context) << CSR
9576 << E->getSourceRange(),
9577 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9578 else
9579 // FIXME: If this is an initializer list, suggest removing the braces
9580 // or inserting a cast to the target type.
9581 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9582 << isa<InitListExpr>(E) << ExprTy << CallType
9584 break;
9585 }
9586
9587 if (EmitTypeMismatch) {
9588 // The function is not variadic, so we do not generate warnings about
9589 // being allowed to pass that object as a variadic argument. Instead,
9590 // since there are inherently no printf specifiers for types which cannot
9591 // be passed as variadic arguments, emit a plain old specifier mismatch
9592 // argument.
9593 EmitFormatDiagnostic(
9594 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9595 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9596 << E->getSourceRange(),
9597 E->getBeginLoc(), false, CSR);
9598 }
9599
9600 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9601 "format string specifier index out of range");
9602 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9603 }
9604
9605 return true;
9606}
9607
9608//===--- CHECK: Scanf format string checking ------------------------------===//
9609
9610namespace {
9611
9612class CheckScanfHandler : public CheckFormatHandler {
9613public:
9614 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9615 const Expr *origFormatExpr, FormatStringType type,
9616 unsigned firstDataArg, unsigned numDataArgs,
9617 const char *beg, Sema::FormatArgumentPassingKind APK,
9618 ArrayRef<const Expr *> Args, unsigned formatIdx,
9619 bool inFunctionCall, VariadicCallType CallType,
9620 llvm::SmallBitVector &CheckedVarArgs,
9621 UncoveredArgHandler &UncoveredArg)
9622 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9623 numDataArgs, beg, APK, Args, formatIdx,
9624 inFunctionCall, CallType, CheckedVarArgs,
9625 UncoveredArg) {}
9626
9627 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9628 const char *startSpecifier,
9629 unsigned specifierLen) override;
9630
9631 bool HandleInvalidScanfConversionSpecifier(
9632 const analyze_scanf::ScanfSpecifier &FS,
9633 const char *startSpecifier,
9634 unsigned specifierLen) override;
9635
9636 void HandleIncompleteScanList(const char *start, const char *end) override;
9637};
9638
9639} // namespace
9640
9641void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9642 const char *end) {
9643 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9644 getLocationOfByte(end), /*IsStringLocation*/true,
9645 getSpecifierRange(start, end - start));
9646}
9647
9648bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9650 const char *startSpecifier,
9651 unsigned specifierLen) {
9654
9655 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9656 getLocationOfByte(CS.getStart()),
9657 startSpecifier, specifierLen,
9658 CS.getStart(), CS.getLength());
9659}
9660
9661bool CheckScanfHandler::HandleScanfSpecifier(
9663 const char *startSpecifier,
9664 unsigned specifierLen) {
9665 using namespace analyze_scanf;
9666 using namespace analyze_format_string;
9667
9668 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9669
9670 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9671 // be used to decide if we are using positional arguments consistently.
9672 if (FS.consumesDataArgument()) {
9673 if (atFirstArg) {
9674 atFirstArg = false;
9675 usesPositionalArgs = FS.usesPositionalArg();
9676 }
9677 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9678 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9679 startSpecifier, specifierLen);
9680 return false;
9681 }
9682 }
9683
9684 // Check if the field with is non-zero.
9685 const OptionalAmount &Amt = FS.getFieldWidth();
9687 if (Amt.getConstantAmount() == 0) {
9688 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9689 Amt.getConstantLength());
9690 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9691 getLocationOfByte(Amt.getStart()),
9692 /*IsStringLocation*/true, R,
9694 }
9695 }
9696
9697 if (!FS.consumesDataArgument()) {
9698 // FIXME: Technically specifying a precision or field width here
9699 // makes no sense. Worth issuing a warning at some point.
9700 return true;
9701 }
9702
9703 // Consume the argument.
9704 unsigned argIndex = FS.getArgIndex();
9705 if (argIndex < NumDataArgs) {
9706 // The check to see if the argIndex is valid will come later.
9707 // We set the bit here because we may exit early from this
9708 // function if we encounter some other error.
9709 CoveredArgs.set(argIndex);
9710 }
9711
9712 // Check the length modifier is valid with the given conversion specifier.
9714 S.getLangOpts()))
9715 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9716 diag::warn_format_nonsensical_length);
9717 else if (!FS.hasStandardLengthModifier())
9718 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9720 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9721 diag::warn_format_non_standard_conversion_spec);
9722
9724 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9725
9726 // The remaining checks depend on the data arguments.
9727 if (!HasFormatArguments())
9728 return true;
9729
9730 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9731 return false;
9732
9733 // Check that the argument type matches the format specifier.
9734 const Expr *Ex = getDataArg(argIndex);
9735 if (!Ex)
9736 return true;
9737
9739
9740 if (!AT.isValid()) {
9741 return true;
9742 }
9743
9745 AT.matchesType(S.Context, Ex->getType());
9748 return true;
9751
9752 ScanfSpecifier fixedFS = FS;
9753 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9754 S.getLangOpts(), S.Context);
9755
9756 unsigned Diag =
9757 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9758 : Signedness
9759 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9760 : diag::warn_format_conversion_argument_type_mismatch;
9761
9762 if (Success) {
9763 // Get the fix string from the fixed format specifier.
9764 SmallString<128> buf;
9765 llvm::raw_svector_ostream os(buf);
9766 fixedFS.toString(os);
9767
9768 EmitFormatDiagnostic(
9770 << Ex->getType() << false << Ex->getSourceRange(),
9771 Ex->getBeginLoc(),
9772 /*IsStringLocation*/ false,
9773 getSpecifierRange(startSpecifier, specifierLen),
9775 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9776 } else {
9777 EmitFormatDiagnostic(S.PDiag(Diag)
9779 << Ex->getType() << false << Ex->getSourceRange(),
9780 Ex->getBeginLoc(),
9781 /*IsStringLocation*/ false,
9782 getSpecifierRange(startSpecifier, specifierLen));
9783 }
9784
9785 return true;
9786}
9787
9788static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9790 const StringLiteral *Fmt,
9792 const Expr *FmtExpr, bool InFunctionCall) {
9793 bool HadError = false;
9794 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9795 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9796 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9797 // In positional-style format strings, the same specifier can appear
9798 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9799 // are sorted by getPosition(), and we process each range of equal
9800 // getPosition() values as one group.
9801 // RefArgs are taken from a string literal that was given to
9802 // attribute(format_matches), and if we got this far, we have already
9803 // verified that if it has positional specifiers that appear in multiple
9804 // locations, then they are all mutually compatible. What's left for us to
9805 // do is verify that all specifiers with the same position in FmtArgs are
9806 // compatible with the RefArgs specifiers. We check each specifier from
9807 // FmtArgs against the first member of the RefArgs group.
9808 for (; FmtIter < FmtEnd; ++FmtIter) {
9809 // Clang does not diagnose missing format specifiers in positional-style
9810 // strings (TODO: which it probably should do, as it is UB to skip over a
9811 // format argument). Skip specifiers if needed.
9812 if (FmtIter->getPosition() < RefIter->getPosition())
9813 continue;
9814
9815 // Delimits a new getPosition() value.
9816 if (FmtIter->getPosition() > RefIter->getPosition())
9817 break;
9818
9819 HadError |=
9820 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9821 }
9822
9823 // Jump RefIter to the start of the next group.
9824 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9825 return Arg.getPosition() != RefIter->getPosition();
9826 });
9827 }
9828
9829 if (FmtIter < FmtEnd) {
9830 CheckFormatHandler::EmitFormatDiagnostic(
9831 S, InFunctionCall, FmtExpr,
9832 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9833 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9834 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9835 } else if (RefIter < RefEnd) {
9836 CheckFormatHandler::EmitFormatDiagnostic(
9837 S, InFunctionCall, FmtExpr,
9838 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9839 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9840 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9841 << 1 << RefIter->getSourceRange();
9842 }
9843 return !HadError;
9844}
9845
9847 Sema &S, const FormatStringLiteral *FExpr,
9848 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9850 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9851 bool inFunctionCall, VariadicCallType CallType,
9852 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9853 bool IgnoreStringsWithoutSpecifiers) {
9854 // CHECK: is the format string a wide literal?
9855 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9856 CheckFormatHandler::EmitFormatDiagnostic(
9857 S, inFunctionCall, Args[format_idx],
9858 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9859 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9860 return;
9861 }
9862
9863 // Str - The format string. NOTE: this is NOT null-terminated!
9864 StringRef StrRef = FExpr->getString();
9865 const char *Str = StrRef.data();
9866 // Account for cases where the string literal is truncated in a declaration.
9867 const ConstantArrayType *T =
9868 S.Context.getAsConstantArrayType(FExpr->getType());
9869 assert(T && "String literal not of constant array type!");
9870 size_t TypeSize = T->getZExtSize();
9871 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9872 const unsigned numDataArgs = Args.size() - firstDataArg;
9873
9874 if (IgnoreStringsWithoutSpecifiers &&
9876 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9877 return;
9878
9879 // Emit a warning if the string literal is truncated and does not contain an
9880 // embedded null character.
9881 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9882 CheckFormatHandler::EmitFormatDiagnostic(
9883 S, inFunctionCall, Args[format_idx],
9884 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9885 FExpr->getBeginLoc(),
9886 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9887 return;
9888 }
9889
9890 // CHECK: empty format string?
9891 if (StrLen == 0 && numDataArgs > 0) {
9892 CheckFormatHandler::EmitFormatDiagnostic(
9893 S, inFunctionCall, Args[format_idx],
9894 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9895 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9896 return;
9897 }
9898
9903 bool IsObjC =
9905 if (ReferenceFormatString == nullptr) {
9906 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9907 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9908 inFunctionCall, CallType, CheckedVarArgs,
9909 UncoveredArg);
9910
9912 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9915 H.DoneProcessing();
9916 } else {
9918 Type, ReferenceFormatString, FExpr->getFormatString(),
9919 inFunctionCall ? nullptr : Args[format_idx]);
9920 }
9921 } else if (Type == FormatStringType::Scanf) {
9922 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9923 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9924 CallType, CheckedVarArgs, UncoveredArg);
9925
9927 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9928 H.DoneProcessing();
9929 } // TODO: handle other formats
9930}
9931
9933 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9934 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9939 return true;
9940
9941 bool IsObjC =
9944 FormatStringLiteral RefLit = AuthoritativeFormatString;
9945 FormatStringLiteral TestLit = TestedFormatString;
9946 const Expr *Arg;
9947 bool DiagAtStringLiteral;
9948 if (FunctionCallArg) {
9949 Arg = FunctionCallArg;
9950 DiagAtStringLiteral = false;
9951 } else {
9952 Arg = TestedFormatString;
9953 DiagAtStringLiteral = true;
9954 }
9955 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9956 AuthoritativeFormatString, Type,
9957 IsObjC, true, RefArgs) &&
9958 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9959 DiagAtStringLiteral, FmtArgs)) {
9960 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9961 TestedFormatString, FmtArgs, Arg,
9962 DiagAtStringLiteral);
9963 }
9964 return false;
9965}
9966
9968 const StringLiteral *Str) {
9973 return true;
9974
9975 FormatStringLiteral RefLit = Str;
9977 bool IsObjC =
9979 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9980 true, Args))
9981 return false;
9982
9983 // Group arguments by getPosition() value, and check that each member of the
9984 // group is compatible with the first member. This verifies that when
9985 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9986 // are mutually compatible. As an optimization, don't test the first member
9987 // against itself.
9988 bool HadError = false;
9989 auto Iter = Args.begin();
9990 auto End = Args.end();
9991 while (Iter != End) {
9992 const auto &FirstInGroup = *Iter;
9993 for (++Iter;
9994 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9995 ++Iter) {
9996 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9997 }
9998 }
9999 return !HadError;
10000}
10001
10003 // Str - The format string. NOTE: this is NOT null-terminated!
10004 StringRef StrRef = FExpr->getString();
10005 const char *Str = StrRef.data();
10006 // Account for cases where the string literal is truncated in a declaration.
10007 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10008 assert(T && "String literal not of constant array type!");
10009 size_t TypeSize = T->getZExtSize();
10010 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10011 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
10012 getLangOpts(),
10013 Context.getTargetInfo());
10014}
10015
10016//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10017
10018// Returns the related absolute value function that is larger, of 0 if one
10019// does not exist.
10020static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10021 switch (AbsFunction) {
10022 default:
10023 return 0;
10024
10025 case Builtin::BI__builtin_abs:
10026 return Builtin::BI__builtin_labs;
10027 case Builtin::BI__builtin_labs:
10028 return Builtin::BI__builtin_llabs;
10029 case Builtin::BI__builtin_llabs:
10030 return 0;
10031
10032 case Builtin::BI__builtin_fabsf:
10033 return Builtin::BI__builtin_fabs;
10034 case Builtin::BI__builtin_fabs:
10035 return Builtin::BI__builtin_fabsl;
10036 case Builtin::BI__builtin_fabsl:
10037 return 0;
10038
10039 case Builtin::BI__builtin_cabsf:
10040 return Builtin::BI__builtin_cabs;
10041 case Builtin::BI__builtin_cabs:
10042 return Builtin::BI__builtin_cabsl;
10043 case Builtin::BI__builtin_cabsl:
10044 return 0;
10045
10046 case Builtin::BIabs:
10047 return Builtin::BIlabs;
10048 case Builtin::BIlabs:
10049 return Builtin::BIllabs;
10050 case Builtin::BIllabs:
10051 return 0;
10052
10053 case Builtin::BIfabsf:
10054 return Builtin::BIfabs;
10055 case Builtin::BIfabs:
10056 return Builtin::BIfabsl;
10057 case Builtin::BIfabsl:
10058 return 0;
10059
10060 case Builtin::BIcabsf:
10061 return Builtin::BIcabs;
10062 case Builtin::BIcabs:
10063 return Builtin::BIcabsl;
10064 case Builtin::BIcabsl:
10065 return 0;
10066 }
10067}
10068
10069// Returns the argument type of the absolute value function.
10071 unsigned AbsType) {
10072 if (AbsType == 0)
10073 return QualType();
10074
10076 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10078 return QualType();
10079
10081 if (!FT)
10082 return QualType();
10083
10084 if (FT->getNumParams() != 1)
10085 return QualType();
10086
10087 return FT->getParamType(0);
10088}
10089
10090// Returns the best absolute value function, or zero, based on type and
10091// current absolute value function.
10092static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10093 unsigned AbsFunctionKind) {
10094 unsigned BestKind = 0;
10095 uint64_t ArgSize = Context.getTypeSize(ArgType);
10096 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10097 Kind = getLargerAbsoluteValueFunction(Kind)) {
10098 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10099 if (Context.getTypeSize(ParamType) >= ArgSize) {
10100 if (BestKind == 0)
10101 BestKind = Kind;
10102 else if (Context.hasSameType(ParamType, ArgType)) {
10103 BestKind = Kind;
10104 break;
10105 }
10106 }
10107 }
10108 return BestKind;
10109}
10110
10116
10118 if (T->isIntegralOrEnumerationType())
10119 return AVK_Integer;
10120 if (T->isRealFloatingType())
10121 return AVK_Floating;
10122 if (T->isAnyComplexType())
10123 return AVK_Complex;
10124
10125 llvm_unreachable("Type not integer, floating, or complex");
10126}
10127
10128// Changes the absolute value function to a different type. Preserves whether
10129// the function is a builtin.
10130static unsigned changeAbsFunction(unsigned AbsKind,
10131 AbsoluteValueKind ValueKind) {
10132 switch (ValueKind) {
10133 case AVK_Integer:
10134 switch (AbsKind) {
10135 default:
10136 return 0;
10137 case Builtin::BI__builtin_fabsf:
10138 case Builtin::BI__builtin_fabs:
10139 case Builtin::BI__builtin_fabsl:
10140 case Builtin::BI__builtin_cabsf:
10141 case Builtin::BI__builtin_cabs:
10142 case Builtin::BI__builtin_cabsl:
10143 return Builtin::BI__builtin_abs;
10144 case Builtin::BIfabsf:
10145 case Builtin::BIfabs:
10146 case Builtin::BIfabsl:
10147 case Builtin::BIcabsf:
10148 case Builtin::BIcabs:
10149 case Builtin::BIcabsl:
10150 return Builtin::BIabs;
10151 }
10152 case AVK_Floating:
10153 switch (AbsKind) {
10154 default:
10155 return 0;
10156 case Builtin::BI__builtin_abs:
10157 case Builtin::BI__builtin_labs:
10158 case Builtin::BI__builtin_llabs:
10159 case Builtin::BI__builtin_cabsf:
10160 case Builtin::BI__builtin_cabs:
10161 case Builtin::BI__builtin_cabsl:
10162 return Builtin::BI__builtin_fabsf;
10163 case Builtin::BIabs:
10164 case Builtin::BIlabs:
10165 case Builtin::BIllabs:
10166 case Builtin::BIcabsf:
10167 case Builtin::BIcabs:
10168 case Builtin::BIcabsl:
10169 return Builtin::BIfabsf;
10170 }
10171 case AVK_Complex:
10172 switch (AbsKind) {
10173 default:
10174 return 0;
10175 case Builtin::BI__builtin_abs:
10176 case Builtin::BI__builtin_labs:
10177 case Builtin::BI__builtin_llabs:
10178 case Builtin::BI__builtin_fabsf:
10179 case Builtin::BI__builtin_fabs:
10180 case Builtin::BI__builtin_fabsl:
10181 return Builtin::BI__builtin_cabsf;
10182 case Builtin::BIabs:
10183 case Builtin::BIlabs:
10184 case Builtin::BIllabs:
10185 case Builtin::BIfabsf:
10186 case Builtin::BIfabs:
10187 case Builtin::BIfabsl:
10188 return Builtin::BIcabsf;
10189 }
10190 }
10191 llvm_unreachable("Unable to convert function");
10192}
10193
10194static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10195 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10196 if (!FnInfo)
10197 return 0;
10198
10199 switch (FDecl->getBuiltinID()) {
10200 default:
10201 return 0;
10202 case Builtin::BI__builtin_abs:
10203 case Builtin::BI__builtin_fabs:
10204 case Builtin::BI__builtin_fabsf:
10205 case Builtin::BI__builtin_fabsl:
10206 case Builtin::BI__builtin_labs:
10207 case Builtin::BI__builtin_llabs:
10208 case Builtin::BI__builtin_cabs:
10209 case Builtin::BI__builtin_cabsf:
10210 case Builtin::BI__builtin_cabsl:
10211 case Builtin::BIabs:
10212 case Builtin::BIlabs:
10213 case Builtin::BIllabs:
10214 case Builtin::BIfabs:
10215 case Builtin::BIfabsf:
10216 case Builtin::BIfabsl:
10217 case Builtin::BIcabs:
10218 case Builtin::BIcabsf:
10219 case Builtin::BIcabsl:
10220 return FDecl->getBuiltinID();
10221 }
10222 llvm_unreachable("Unknown Builtin type");
10223}
10224
10225// If the replacement is valid, emit a note with replacement function.
10226// Additionally, suggest including the proper header if not already included.
10228 unsigned AbsKind, QualType ArgType) {
10229 bool EmitHeaderHint = true;
10230 const char *HeaderName = nullptr;
10231 std::string FunctionName;
10232 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10233 FunctionName = "std::abs";
10234 if (ArgType->isIntegralOrEnumerationType()) {
10235 HeaderName = "cstdlib";
10236 } else if (ArgType->isRealFloatingType()) {
10237 HeaderName = "cmath";
10238 } else {
10239 llvm_unreachable("Invalid Type");
10240 }
10241
10242 // Lookup all std::abs
10243 if (NamespaceDecl *Std = S.getStdNamespace()) {
10244 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10245 R.suppressDiagnostics();
10246 S.LookupQualifiedName(R, Std);
10247
10248 for (const auto *I : R) {
10249 const FunctionDecl *FDecl = nullptr;
10250 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10251 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10252 } else {
10253 FDecl = dyn_cast<FunctionDecl>(I);
10254 }
10255 if (!FDecl)
10256 continue;
10257
10258 // Found std::abs(), check that they are the right ones.
10259 if (FDecl->getNumParams() != 1)
10260 continue;
10261
10262 // Check that the parameter type can handle the argument.
10263 QualType ParamType = FDecl->getParamDecl(0)->getType();
10264 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10265 S.Context.getTypeSize(ArgType) <=
10266 S.Context.getTypeSize(ParamType)) {
10267 // Found a function, don't need the header hint.
10268 EmitHeaderHint = false;
10269 break;
10270 }
10271 }
10272 }
10273 } else {
10274 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10275 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10276
10277 if (HeaderName) {
10278 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10279 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10280 R.suppressDiagnostics();
10281 S.LookupName(R, S.getCurScope());
10282
10283 if (R.isSingleResult()) {
10284 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10285 if (FD && FD->getBuiltinID() == AbsKind) {
10286 EmitHeaderHint = false;
10287 } else {
10288 return;
10289 }
10290 } else if (!R.empty()) {
10291 return;
10292 }
10293 }
10294 }
10295
10296 S.Diag(Loc, diag::note_replace_abs_function)
10297 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10298
10299 if (!HeaderName)
10300 return;
10301
10302 if (!EmitHeaderHint)
10303 return;
10304
10305 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10306 << FunctionName;
10307}
10308
10309template <std::size_t StrLen>
10310static bool IsStdFunction(const FunctionDecl *FDecl,
10311 const char (&Str)[StrLen]) {
10312 if (!FDecl)
10313 return false;
10314 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10315 return false;
10316 if (!FDecl->isInStdNamespace())
10317 return false;
10318
10319 return true;
10320}
10321
10322enum class MathCheck { NaN, Inf };
10323static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10324 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10325 return llvm::is_contained(names, calleeName);
10326 };
10327
10328 switch (Check) {
10329 case MathCheck::NaN:
10330 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10331 "__builtin_nanf16", "__builtin_nanf128"});
10332 case MathCheck::Inf:
10333 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10334 "__builtin_inff16", "__builtin_inff128"});
10335 }
10336 llvm_unreachable("unknown MathCheck");
10337}
10338
10339static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10340 if (FDecl->getName() != "infinity")
10341 return false;
10342
10343 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10344 const CXXRecordDecl *RDecl = MDecl->getParent();
10345 if (RDecl->getName() != "numeric_limits")
10346 return false;
10347
10348 if (const NamespaceDecl *NSDecl =
10349 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10350 return NSDecl->isStdNamespace();
10351 }
10352
10353 return false;
10354}
10355
10356void Sema::CheckInfNaNFunction(const CallExpr *Call,
10357 const FunctionDecl *FDecl) {
10358 if (!FDecl->getIdentifier())
10359 return;
10360
10361 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10362 if (FPO.getNoHonorNaNs() &&
10363 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10365 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10366 << 1 << 0 << Call->getSourceRange();
10367 return;
10368 }
10369
10370 if (FPO.getNoHonorInfs() &&
10371 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10372 IsInfinityFunction(FDecl) ||
10374 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10375 << 0 << 0 << Call->getSourceRange();
10376 }
10377}
10378
10379void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10380 const FunctionDecl *FDecl) {
10381 if (Call->getNumArgs() != 1)
10382 return;
10383
10384 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10385 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10386 if (AbsKind == 0 && !IsStdAbs)
10387 return;
10388
10389 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10390 QualType ParamType = Call->getArg(0)->getType();
10391
10392 // Unsigned types cannot be negative. Suggest removing the absolute value
10393 // function call.
10394 if (ArgType->isUnsignedIntegerType()) {
10395 std::string FunctionName =
10396 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10397 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10398 Diag(Call->getExprLoc(), diag::note_remove_abs)
10399 << FunctionName
10400 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10401 return;
10402 }
10403
10404 // Taking the absolute value of a pointer is very suspicious, they probably
10405 // wanted to index into an array, dereference a pointer, call a function, etc.
10406 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10407 unsigned DiagType = 0;
10408 if (ArgType->isFunctionType())
10409 DiagType = 1;
10410 else if (ArgType->isArrayType())
10411 DiagType = 2;
10412
10413 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10414 return;
10415 }
10416
10417 // std::abs has overloads which prevent most of the absolute value problems
10418 // from occurring.
10419 if (IsStdAbs)
10420 return;
10421
10422 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10423 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10424
10425 // The argument and parameter are the same kind. Check if they are the right
10426 // size.
10427 if (ArgValueKind == ParamValueKind) {
10428 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10429 return;
10430
10431 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10432 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10433 << FDecl << ArgType << ParamType;
10434
10435 if (NewAbsKind == 0)
10436 return;
10437
10438 emitReplacement(*this, Call->getExprLoc(),
10439 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10440 return;
10441 }
10442
10443 // ArgValueKind != ParamValueKind
10444 // The wrong type of absolute value function was used. Attempt to find the
10445 // proper one.
10446 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10447 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10448 if (NewAbsKind == 0)
10449 return;
10450
10451 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10452 << FDecl << ParamValueKind << ArgValueKind;
10453
10454 emitReplacement(*this, Call->getExprLoc(),
10455 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10456}
10457
10458//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10459void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10460 const FunctionDecl *FDecl) {
10461 if (!Call || !FDecl) return;
10462
10463 // Ignore template specializations and macros.
10464 if (inTemplateInstantiation()) return;
10465 if (Call->getExprLoc().isMacroID()) return;
10466
10467 // Only care about the one template argument, two function parameter std::max
10468 if (Call->getNumArgs() != 2) return;
10469 if (!IsStdFunction(FDecl, "max")) return;
10470 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10471 if (!ArgList) return;
10472 if (ArgList->size() != 1) return;
10473
10474 // Check that template type argument is unsigned integer.
10475 const auto& TA = ArgList->get(0);
10476 if (TA.getKind() != TemplateArgument::Type) return;
10477 QualType ArgType = TA.getAsType();
10478 if (!ArgType->isUnsignedIntegerType()) return;
10479
10480 // See if either argument is a literal zero.
10481 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10482 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10483 if (!MTE) return false;
10484 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10485 if (!Num) return false;
10486 if (Num->getValue() != 0) return false;
10487 return true;
10488 };
10489
10490 const Expr *FirstArg = Call->getArg(0);
10491 const Expr *SecondArg = Call->getArg(1);
10492 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10493 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10494
10495 // Only warn when exactly one argument is zero.
10496 if (IsFirstArgZero == IsSecondArgZero) return;
10497
10498 SourceRange FirstRange = FirstArg->getSourceRange();
10499 SourceRange SecondRange = SecondArg->getSourceRange();
10500
10501 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10502
10503 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10504 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10505
10506 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10507 SourceRange RemovalRange;
10508 if (IsFirstArgZero) {
10509 RemovalRange = SourceRange(FirstRange.getBegin(),
10510 SecondRange.getBegin().getLocWithOffset(-1));
10511 } else {
10512 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10513 SecondRange.getEnd());
10514 }
10515
10516 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10517 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10518 << FixItHint::CreateRemoval(RemovalRange);
10519}
10520
10521//===--- CHECK: Standard memory functions ---------------------------------===//
10522
10523/// Takes the expression passed to the size_t parameter of functions
10524/// such as memcmp, strncat, etc and warns if it's a comparison.
10525///
10526/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10528 const IdentifierInfo *FnName,
10529 SourceLocation FnLoc,
10530 SourceLocation RParenLoc) {
10531 const auto *Size = dyn_cast<BinaryOperator>(E);
10532 if (!Size)
10533 return false;
10534
10535 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10536 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10537 return false;
10538
10539 SourceRange SizeRange = Size->getSourceRange();
10540 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10541 << SizeRange << FnName;
10542 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10543 << FnName
10545 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10546 << FixItHint::CreateRemoval(RParenLoc);
10547 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10548 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10550 ")");
10551
10552 return true;
10553}
10554
10555/// Determine whether the given type is or contains a dynamic class type
10556/// (e.g., whether it has a vtable).
10558 bool &IsContained) {
10559 // Look through array types while ignoring qualifiers.
10560 const Type *Ty = T->getBaseElementTypeUnsafe();
10561 IsContained = false;
10562
10563 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10564 RD = RD ? RD->getDefinition() : nullptr;
10565 if (!RD || RD->isInvalidDecl())
10566 return nullptr;
10567
10568 if (RD->isDynamicClass())
10569 return RD;
10570
10571 // Check all the fields. If any bases were dynamic, the class is dynamic.
10572 // It's impossible for a class to transitively contain itself by value, so
10573 // infinite recursion is impossible.
10574 for (auto *FD : RD->fields()) {
10575 bool SubContained;
10576 if (const CXXRecordDecl *ContainedRD =
10577 getContainedDynamicClass(FD->getType(), SubContained)) {
10578 IsContained = true;
10579 return ContainedRD;
10580 }
10581 }
10582
10583 return nullptr;
10584}
10585
10587 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10588 if (Unary->getKind() == UETT_SizeOf)
10589 return Unary;
10590 return nullptr;
10591}
10592
10593/// If E is a sizeof expression, returns its argument expression,
10594/// otherwise returns NULL.
10595static const Expr *getSizeOfExprArg(const Expr *E) {
10597 if (!SizeOf->isArgumentType())
10598 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10599 return nullptr;
10600}
10601
10602/// If E is a sizeof expression, returns its argument type.
10605 return SizeOf->getTypeOfArgument();
10606 return QualType();
10607}
10608
10609namespace {
10610
10611struct SearchNonTrivialToInitializeField
10612 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10613 using Super =
10614 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10615
10616 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10617
10618 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10619 SourceLocation SL) {
10620 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10621 asDerived().visitArray(PDIK, AT, SL);
10622 return;
10623 }
10624
10625 Super::visitWithKind(PDIK, FT, SL);
10626 }
10627
10628 void visitARCStrong(QualType FT, SourceLocation SL) {
10629 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10630 }
10631 void visitARCWeak(QualType FT, SourceLocation SL) {
10632 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10633 }
10634 void visitStruct(QualType FT, SourceLocation SL) {
10635 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10636 visit(FD->getType(), FD->getLocation());
10637 }
10638 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10639 const ArrayType *AT, SourceLocation SL) {
10640 visit(getContext().getBaseElementType(AT), SL);
10641 }
10642 void visitTrivial(QualType FT, SourceLocation SL) {}
10643
10644 static void diag(QualType RT, const Expr *E, Sema &S) {
10645 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10646 }
10647
10648 ASTContext &getContext() { return S.getASTContext(); }
10649
10650 const Expr *E;
10651 Sema &S;
10652};
10653
10654struct SearchNonTrivialToCopyField
10655 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10656 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10657
10658 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10659
10660 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10661 SourceLocation SL) {
10662 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10663 asDerived().visitArray(PCK, AT, SL);
10664 return;
10665 }
10666
10667 Super::visitWithKind(PCK, FT, SL);
10668 }
10669
10670 void visitARCStrong(QualType FT, SourceLocation SL) {
10671 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10672 }
10673 void visitARCWeak(QualType FT, SourceLocation SL) {
10674 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10675 }
10676 void visitPtrAuth(QualType FT, SourceLocation SL) {
10677 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10678 }
10679 void visitStruct(QualType FT, SourceLocation SL) {
10680 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10681 visit(FD->getType(), FD->getLocation());
10682 }
10683 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10684 SourceLocation SL) {
10685 visit(getContext().getBaseElementType(AT), SL);
10686 }
10687 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10688 SourceLocation SL) {}
10689 void visitTrivial(QualType FT, SourceLocation SL) {}
10690 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10691
10692 static void diag(QualType RT, const Expr *E, Sema &S) {
10693 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10694 }
10695
10696 ASTContext &getContext() { return S.getASTContext(); }
10697
10698 const Expr *E;
10699 Sema &S;
10700};
10701
10702}
10703
10704/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10705static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10706 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10707
10708 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10709 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10710 return false;
10711
10712 return doesExprLikelyComputeSize(BO->getLHS()) ||
10713 doesExprLikelyComputeSize(BO->getRHS());
10714 }
10715
10716 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10717}
10718
10719/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10720///
10721/// \code
10722/// #define MACRO 0
10723/// foo(MACRO);
10724/// foo(0);
10725/// \endcode
10726///
10727/// This should return true for the first call to foo, but not for the second
10728/// (regardless of whether foo is a macro or function).
10730 SourceLocation CallLoc,
10731 SourceLocation ArgLoc) {
10732 if (!CallLoc.isMacroID())
10733 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10734
10735 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10736 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10737}
10738
10739/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10740/// last two arguments transposed.
10741static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10742 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10743 return;
10744
10745 const Expr *SizeArg =
10746 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10747
10748 auto isLiteralZero = [](const Expr *E) {
10749 return (isa<IntegerLiteral>(E) &&
10750 cast<IntegerLiteral>(E)->getValue() == 0) ||
10752 cast<CharacterLiteral>(E)->getValue() == 0);
10753 };
10754
10755 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10756 SourceLocation CallLoc = Call->getRParenLoc();
10758 if (isLiteralZero(SizeArg) &&
10759 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10760
10761 SourceLocation DiagLoc = SizeArg->getExprLoc();
10762
10763 // Some platforms #define bzero to __builtin_memset. See if this is the
10764 // case, and if so, emit a better diagnostic.
10765 if (BId == Builtin::BIbzero ||
10767 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10768 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10769 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10770 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10771 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10772 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10773 }
10774 return;
10775 }
10776
10777 // If the second argument to a memset is a sizeof expression and the third
10778 // isn't, this is also likely an error. This should catch
10779 // 'memset(buf, sizeof(buf), 0xff)'.
10780 if (BId == Builtin::BImemset &&
10781 doesExprLikelyComputeSize(Call->getArg(1)) &&
10782 !doesExprLikelyComputeSize(Call->getArg(2))) {
10783 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10784 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10785 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10786 return;
10787 }
10788}
10789
10790void Sema::CheckMemaccessArguments(const CallExpr *Call,
10791 unsigned BId,
10792 IdentifierInfo *FnName) {
10793 assert(BId != 0);
10794
10795 // It is possible to have a non-standard definition of memset. Validate
10796 // we have enough arguments, and if not, abort further checking.
10797 unsigned ExpectedNumArgs =
10798 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10799 if (Call->getNumArgs() < ExpectedNumArgs)
10800 return;
10801
10802 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10803 BId == Builtin::BIstrndup ? 1 : 2);
10804 unsigned LenArg =
10805 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10806 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10807
10808 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10809 Call->getBeginLoc(), Call->getRParenLoc()))
10810 return;
10811
10812 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10813 CheckMemaccessSize(*this, BId, Call);
10814
10815 // We have special checking when the length is a sizeof expression.
10816 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10817
10818 // Although widely used, 'bzero' is not a standard function. Be more strict
10819 // with the argument types before allowing diagnostics and only allow the
10820 // form bzero(ptr, sizeof(...)).
10821 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10822 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10823 return;
10824
10825 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10826 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10827 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10828
10829 QualType DestTy = Dest->getType();
10830 QualType PointeeTy;
10831 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10832 PointeeTy = DestPtrTy->getPointeeType();
10833
10834 // Never warn about void type pointers. This can be used to suppress
10835 // false positives.
10836 if (PointeeTy->isVoidType())
10837 continue;
10838
10839 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10840 // actually comparing the expressions for equality. Because computing the
10841 // expression IDs can be expensive, we only do this if the diagnostic is
10842 // enabled.
10843 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
10844 break;
10845
10846 // Also check for cases where the sizeof argument is the exact same
10847 // type as the memory argument, and where it points to a user-defined
10848 // record type.
10849 if (SizeOfArgTy != QualType()) {
10850 if (PointeeTy->isRecordType() &&
10851 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10852 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10853 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10854 << FnName << SizeOfArgTy << ArgIdx
10855 << PointeeTy << Dest->getSourceRange()
10856 << LenExpr->getSourceRange());
10857 break;
10858 }
10859 }
10860 } else if (DestTy->isArrayType()) {
10861 PointeeTy = DestTy;
10862 }
10863
10864 if (PointeeTy == QualType())
10865 continue;
10866
10867 // Always complain about dynamic classes.
10868 bool IsContained;
10869 if (const CXXRecordDecl *ContainedRD =
10870 getContainedDynamicClass(PointeeTy, IsContained)) {
10871
10872 unsigned OperationType = 0;
10873 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10874 // "overwritten" if we're warning about the destination for any call
10875 // but memcmp; otherwise a verb appropriate to the call.
10876 if (ArgIdx != 0 || IsCmp) {
10877 if (BId == Builtin::BImemcpy)
10878 OperationType = 1;
10879 else if(BId == Builtin::BImemmove)
10880 OperationType = 2;
10881 else if (IsCmp)
10882 OperationType = 3;
10883 }
10884
10885 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10886 PDiag(diag::warn_dyn_class_memaccess)
10887 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10888 << IsContained << ContainedRD << OperationType
10889 << Call->getCallee()->getSourceRange());
10890 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10891 BId != Builtin::BImemset)
10893 Dest->getExprLoc(), Dest,
10894 PDiag(diag::warn_arc_object_memaccess)
10895 << ArgIdx << FnName << PointeeTy
10896 << Call->getCallee()->getSourceRange());
10897 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10898
10899 // FIXME: Do not consider incomplete types even though they may be
10900 // completed later. GCC does not diagnose such code, but we may want to
10901 // consider diagnosing it in the future, perhaps under a different, but
10902 // related, diagnostic group.
10903 bool NonTriviallyCopyableCXXRecord =
10904 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10905 !PointeeTy.isTriviallyCopyableType(Context);
10906
10907 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10909 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10910 PDiag(diag::warn_cstruct_memaccess)
10911 << ArgIdx << FnName << PointeeTy << 0);
10912 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10913 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10914 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10915 // FIXME: Limiting this warning to dest argument until we decide
10916 // whether it's valid for source argument too.
10917 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10918 PDiag(diag::warn_cxxstruct_memaccess)
10919 << FnName << PointeeTy);
10920 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10922 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10923 PDiag(diag::warn_cstruct_memaccess)
10924 << ArgIdx << FnName << PointeeTy << 1);
10925 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10926 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10927 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10928 // FIXME: Limiting this warning to dest argument until we decide
10929 // whether it's valid for source argument too.
10930 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10931 PDiag(diag::warn_cxxstruct_memaccess)
10932 << FnName << PointeeTy);
10933 } else {
10934 continue;
10935 }
10936 } else
10937 continue;
10938
10940 Dest->getExprLoc(), Dest,
10941 PDiag(diag::note_bad_memaccess_silence)
10942 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10943 break;
10944 }
10945}
10946
10947bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10948 IdentifierInfo *FnName) {
10949 llvm::FoldingSetNodeID SizeOfArgID;
10950 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10951 if (!SizeOfArg)
10952 return false;
10953 // Computing this warning is expensive, so we only do so if the warning is
10954 // enabled.
10955 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10956 SizeOfArg->getExprLoc()))
10957 return false;
10958 QualType DestTy = Dest->getType();
10959 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10960 if (!DestPtrTy)
10961 return false;
10962
10963 QualType PointeeTy = DestPtrTy->getPointeeType();
10964
10965 if (SizeOfArgID == llvm::FoldingSetNodeID())
10966 SizeOfArg->Profile(SizeOfArgID, Context, true);
10967
10968 llvm::FoldingSetNodeID DestID;
10969 Dest->Profile(DestID, Context, true);
10970 if (DestID == SizeOfArgID) {
10971 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10972 // over sizeof(src) as well.
10973 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10974 StringRef ReadableName = FnName->getName();
10975
10976 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
10977 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
10978 ActionIdx = 1; // If its an address-of operator, just remove it.
10979 if (!PointeeTy->isIncompleteType() &&
10980 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10981 ActionIdx = 2; // If the pointee's size is sizeof(char),
10982 // suggest an explicit length.
10983
10984 // If the function is defined as a builtin macro, do not show macro
10985 // expansion.
10986 SourceLocation SL = SizeOfArg->getExprLoc();
10987 SourceRange DSR = Dest->getSourceRange();
10988 SourceRange SSR = SizeOfArg->getSourceRange();
10989 SourceManager &SM = getSourceManager();
10990
10991 if (SM.isMacroArgExpansion(SL)) {
10992 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10993 SL = SM.getSpellingLoc(SL);
10994 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10995 SM.getSpellingLoc(DSR.getEnd()));
10996 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10997 SM.getSpellingLoc(SSR.getEnd()));
10998 }
10999
11000 DiagRuntimeBehavior(SL, SizeOfArg,
11001 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11002 << ReadableName << PointeeTy << DestTy << DSR
11003 << SSR);
11004 DiagRuntimeBehavior(SL, SizeOfArg,
11005 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11006 << ActionIdx << SSR);
11007 return true;
11008 }
11009 return false;
11010}
11011
11012// A little helper routine: ignore addition and subtraction of integer literals.
11013// This intentionally does not ignore all integer constant expressions because
11014// we don't want to remove sizeof().
11015static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11016 Ex = Ex->IgnoreParenCasts();
11017
11018 while (true) {
11019 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11020 if (!BO || !BO->isAdditiveOp())
11021 break;
11022
11023 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11024 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11025
11026 if (isa<IntegerLiteral>(RHS))
11027 Ex = LHS;
11028 else if (isa<IntegerLiteral>(LHS))
11029 Ex = RHS;
11030 else
11031 break;
11032 }
11033
11034 return Ex;
11035}
11036
11038 ASTContext &Context) {
11039 // Only handle constant-sized or VLAs, but not flexible members.
11040 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11041 // Only issue the FIXIT for arrays of size > 1.
11042 if (CAT->getZExtSize() <= 1)
11043 return false;
11044 } else if (!Ty->isVariableArrayType()) {
11045 return false;
11046 }
11047 return true;
11048}
11049
11050void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11051 IdentifierInfo *FnName) {
11052
11053 // Don't crash if the user has the wrong number of arguments
11054 unsigned NumArgs = Call->getNumArgs();
11055 if ((NumArgs != 3) && (NumArgs != 4))
11056 return;
11057
11058 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11059 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11060 const Expr *CompareWithSrc = nullptr;
11061
11062 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11063 Call->getBeginLoc(), Call->getRParenLoc()))
11064 return;
11065
11066 // Look for 'strlcpy(dst, x, sizeof(x))'
11067 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11068 CompareWithSrc = Ex;
11069 else {
11070 // Look for 'strlcpy(dst, x, strlen(x))'
11071 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11072 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11073 SizeCall->getNumArgs() == 1)
11074 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11075 }
11076 }
11077
11078 if (!CompareWithSrc)
11079 return;
11080
11081 // Determine if the argument to sizeof/strlen is equal to the source
11082 // argument. In principle there's all kinds of things you could do
11083 // here, for instance creating an == expression and evaluating it with
11084 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11085 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11086 if (!SrcArgDRE)
11087 return;
11088
11089 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11090 if (!CompareWithSrcDRE ||
11091 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11092 return;
11093
11094 const Expr *OriginalSizeArg = Call->getArg(2);
11095 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11096 << OriginalSizeArg->getSourceRange() << FnName;
11097
11098 // Output a FIXIT hint if the destination is an array (rather than a
11099 // pointer to an array). This could be enhanced to handle some
11100 // pointers if we know the actual size, like if DstArg is 'array+2'
11101 // we could say 'sizeof(array)-2'.
11102 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11104 return;
11105
11106 SmallString<128> sizeString;
11107 llvm::raw_svector_ostream OS(sizeString);
11108 OS << "sizeof(";
11109 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11110 OS << ")";
11111
11112 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11113 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11114 OS.str());
11115}
11116
11117/// Check if two expressions refer to the same declaration.
11118static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11119 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11120 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11121 return D1->getDecl() == D2->getDecl();
11122 return false;
11123}
11124
11125static const Expr *getStrlenExprArg(const Expr *E) {
11126 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11127 const FunctionDecl *FD = CE->getDirectCallee();
11128 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11129 return nullptr;
11130 return CE->getArg(0)->IgnoreParenCasts();
11131 }
11132 return nullptr;
11133}
11134
11135void Sema::CheckStrncatArguments(const CallExpr *CE,
11136 const IdentifierInfo *FnName) {
11137 // Don't crash if the user has the wrong number of arguments.
11138 if (CE->getNumArgs() < 3)
11139 return;
11140 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11141 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11142 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11143
11144 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11145 CE->getRParenLoc()))
11146 return;
11147
11148 // Identify common expressions, which are wrongly used as the size argument
11149 // to strncat and may lead to buffer overflows.
11150 unsigned PatternType = 0;
11151 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11152 // - sizeof(dst)
11153 if (referToTheSameDecl(SizeOfArg, DstArg))
11154 PatternType = 1;
11155 // - sizeof(src)
11156 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11157 PatternType = 2;
11158 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11159 if (BE->getOpcode() == BO_Sub) {
11160 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11161 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11162 // - sizeof(dst) - strlen(dst)
11163 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11165 PatternType = 1;
11166 // - sizeof(src) - (anything)
11167 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11168 PatternType = 2;
11169 }
11170 }
11171
11172 if (PatternType == 0)
11173 return;
11174
11175 // Generate the diagnostic.
11176 SourceLocation SL = LenArg->getBeginLoc();
11177 SourceRange SR = LenArg->getSourceRange();
11178 SourceManager &SM = getSourceManager();
11179
11180 // If the function is defined as a builtin macro, do not show macro expansion.
11181 if (SM.isMacroArgExpansion(SL)) {
11182 SL = SM.getSpellingLoc(SL);
11183 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11184 SM.getSpellingLoc(SR.getEnd()));
11185 }
11186
11187 // Check if the destination is an array (rather than a pointer to an array).
11188 QualType DstTy = DstArg->getType();
11189 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11190 Context);
11191 if (!isKnownSizeArray) {
11192 if (PatternType == 1)
11193 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11194 else
11195 Diag(SL, diag::warn_strncat_src_size) << SR;
11196 return;
11197 }
11198
11199 if (PatternType == 1)
11200 Diag(SL, diag::warn_strncat_large_size) << SR;
11201 else
11202 Diag(SL, diag::warn_strncat_src_size) << SR;
11203
11204 SmallString<128> sizeString;
11205 llvm::raw_svector_ostream OS(sizeString);
11206 OS << "sizeof(";
11207 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11208 OS << ") - ";
11209 OS << "strlen(";
11210 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11211 OS << ") - 1";
11212
11213 Diag(SL, diag::note_strncat_wrong_size)
11214 << FixItHint::CreateReplacement(SR, OS.str());
11215}
11216
11217namespace {
11218void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11219 const UnaryOperator *UnaryExpr, const Decl *D) {
11221 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11222 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11223 return;
11224 }
11225}
11226
11227void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11228 const UnaryOperator *UnaryExpr) {
11229 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11230 const Decl *D = Lvalue->getDecl();
11231 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11232 if (!DD->getType()->isReferenceType())
11233 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11234 }
11235 }
11236
11237 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11238 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11239 Lvalue->getMemberDecl());
11240}
11241
11242void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11243 const UnaryOperator *UnaryExpr) {
11244 const auto *Lambda = dyn_cast<LambdaExpr>(
11246 if (!Lambda)
11247 return;
11248
11249 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11250 << CalleeName << 2 /*object: lambda expression*/;
11251}
11252
11253void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11254 const DeclRefExpr *Lvalue) {
11255 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11256 if (Var == nullptr)
11257 return;
11258
11259 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11260 << CalleeName << 0 /*object: */ << Var;
11261}
11262
11263void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11264 const CastExpr *Cast) {
11265 SmallString<128> SizeString;
11266 llvm::raw_svector_ostream OS(SizeString);
11267
11268 clang::CastKind Kind = Cast->getCastKind();
11269 if (Kind == clang::CK_BitCast &&
11270 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11271 return;
11272 if (Kind == clang::CK_IntegralToPointer &&
11274 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11275 return;
11276
11277 switch (Cast->getCastKind()) {
11278 case clang::CK_BitCast:
11279 case clang::CK_IntegralToPointer:
11280 case clang::CK_FunctionToPointerDecay:
11281 OS << '\'';
11282 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11283 OS << '\'';
11284 break;
11285 default:
11286 return;
11287 }
11288
11289 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11290 << CalleeName << 0 /*object: */ << OS.str();
11291}
11292} // namespace
11293
11294void Sema::CheckFreeArguments(const CallExpr *E) {
11295 const std::string CalleeName =
11296 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11297
11298 { // Prefer something that doesn't involve a cast to make things simpler.
11299 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11300 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11301 switch (UnaryExpr->getOpcode()) {
11302 case UnaryOperator::Opcode::UO_AddrOf:
11303 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11304 case UnaryOperator::Opcode::UO_Plus:
11305 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11306 default:
11307 break;
11308 }
11309
11310 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11311 if (Lvalue->getType()->isArrayType())
11312 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11313
11314 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11315 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11316 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11317 return;
11318 }
11319
11320 if (isa<BlockExpr>(Arg)) {
11321 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11322 << CalleeName << 1 /*object: block*/;
11323 return;
11324 }
11325 }
11326 // Maybe the cast was important, check after the other cases.
11327 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11328 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11329}
11330
11331void
11332Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11333 SourceLocation ReturnLoc,
11334 bool isObjCMethod,
11335 const AttrVec *Attrs,
11336 const FunctionDecl *FD) {
11337 // Check if the return value is null but should not be.
11338 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11339 (!isObjCMethod && isNonNullType(lhsType))) &&
11340 CheckNonNullExpr(*this, RetValExp))
11341 Diag(ReturnLoc, diag::warn_null_ret)
11342 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11343
11344 // C++11 [basic.stc.dynamic.allocation]p4:
11345 // If an allocation function declared with a non-throwing
11346 // exception-specification fails to allocate storage, it shall return
11347 // a null pointer. Any other allocation function that fails to allocate
11348 // storage shall indicate failure only by throwing an exception [...]
11349 if (FD) {
11351 if (Op == OO_New || Op == OO_Array_New) {
11352 const FunctionProtoType *Proto
11353 = FD->getType()->castAs<FunctionProtoType>();
11354 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11355 CheckNonNullExpr(*this, RetValExp))
11356 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11357 << FD << getLangOpts().CPlusPlus11;
11358 }
11359 }
11360
11361 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11362 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11363 }
11364
11365 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11366 // here prevent the user from using a PPC MMA type as trailing return type.
11367 if (Context.getTargetInfo().getTriple().isPPC64())
11368 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11369}
11370
11372 const Expr *RHS, BinaryOperatorKind Opcode) {
11373 if (!BinaryOperator::isEqualityOp(Opcode))
11374 return;
11375
11376 // Match and capture subexpressions such as "(float) X == 0.1".
11377 const FloatingLiteral *FPLiteral;
11378 const CastExpr *FPCast;
11379 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11380 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11381 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11382 return FPLiteral && FPCast;
11383 };
11384
11385 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11386 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11387 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11388 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11389 TargetTy->isFloatingPoint()) {
11390 bool Lossy;
11391 llvm::APFloat TargetC = FPLiteral->getValue();
11392 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11393 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11394 if (Lossy) {
11395 // If the literal cannot be represented in the source type, then a
11396 // check for == is always false and check for != is always true.
11397 Diag(Loc, diag::warn_float_compare_literal)
11398 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11399 << LHS->getSourceRange() << RHS->getSourceRange();
11400 return;
11401 }
11402 }
11403 }
11404
11405 // Match a more general floating-point equality comparison (-Wfloat-equal).
11406 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11407 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11408
11409 // Special case: check for x == x (which is OK).
11410 // Do not emit warnings for such cases.
11411 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11412 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11413 if (DRL->getDecl() == DRR->getDecl())
11414 return;
11415
11416 // Special case: check for comparisons against literals that can be exactly
11417 // represented by APFloat. In such cases, do not emit a warning. This
11418 // is a heuristic: often comparison against such literals are used to
11419 // detect if a value in a variable has not changed. This clearly can
11420 // lead to false negatives.
11421 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11422 if (FLL->isExact())
11423 return;
11424 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11425 if (FLR->isExact())
11426 return;
11427
11428 // Check for comparisons with builtin types.
11429 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11430 CL && CL->getBuiltinCallee())
11431 return;
11432
11433 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11434 CR && CR->getBuiltinCallee())
11435 return;
11436
11437 // Emit the diagnostic.
11438 Diag(Loc, diag::warn_floatingpoint_eq)
11439 << LHS->getSourceRange() << RHS->getSourceRange();
11440}
11441
11442//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11443//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11444
11445namespace {
11446
11447/// Structure recording the 'active' range of an integer-valued
11448/// expression.
11449struct IntRange {
11450 /// The number of bits active in the int. Note that this includes exactly one
11451 /// sign bit if !NonNegative.
11452 unsigned Width;
11453
11454 /// True if the int is known not to have negative values. If so, all leading
11455 /// bits before Width are known zero, otherwise they are known to be the
11456 /// same as the MSB within Width.
11457 bool NonNegative;
11458
11459 IntRange(unsigned Width, bool NonNegative)
11460 : Width(Width), NonNegative(NonNegative) {}
11461
11462 /// Number of bits excluding the sign bit.
11463 unsigned valueBits() const {
11464 return NonNegative ? Width : Width - 1;
11465 }
11466
11467 /// Returns the range of the bool type.
11468 static IntRange forBoolType() {
11469 return IntRange(1, true);
11470 }
11471
11472 /// Returns the range of an opaque value of the given integral type.
11473 static IntRange forValueOfType(ASTContext &C, QualType T) {
11474 return forValueOfCanonicalType(C,
11476 }
11477
11478 /// Returns the range of an opaque value of a canonical integral type.
11479 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11480 assert(T->isCanonicalUnqualified());
11481
11482 if (const auto *VT = dyn_cast<VectorType>(T))
11483 T = VT->getElementType().getTypePtr();
11484 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11485 T = MT->getElementType().getTypePtr();
11486 if (const auto *CT = dyn_cast<ComplexType>(T))
11487 T = CT->getElementType().getTypePtr();
11488 if (const auto *AT = dyn_cast<AtomicType>(T))
11489 T = AT->getValueType().getTypePtr();
11490 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11491 T = OBT->getUnderlyingType().getTypePtr();
11492
11493 if (!C.getLangOpts().CPlusPlus) {
11494 // For enum types in C code, use the underlying datatype.
11495 if (const auto *ED = T->getAsEnumDecl())
11496 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11497 } else if (auto *Enum = T->getAsEnumDecl()) {
11498 // For enum types in C++, use the known bit width of the enumerators.
11499 // In C++11, enums can have a fixed underlying type. Use this type to
11500 // compute the range.
11501 if (Enum->isFixed()) {
11502 return IntRange(C.getIntWidth(QualType(T, 0)),
11503 !Enum->getIntegerType()->isSignedIntegerType());
11504 }
11505
11506 unsigned NumPositive = Enum->getNumPositiveBits();
11507 unsigned NumNegative = Enum->getNumNegativeBits();
11508
11509 if (NumNegative == 0)
11510 return IntRange(NumPositive, true/*NonNegative*/);
11511 else
11512 return IntRange(std::max(NumPositive + 1, NumNegative),
11513 false/*NonNegative*/);
11514 }
11515
11516 if (const auto *EIT = dyn_cast<BitIntType>(T))
11517 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11518
11519 const BuiltinType *BT = cast<BuiltinType>(T);
11520 assert(BT->isInteger());
11521
11522 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11523 }
11524
11525 /// Returns the "target" range of a canonical integral type, i.e.
11526 /// the range of values expressible in the type.
11527 ///
11528 /// This matches forValueOfCanonicalType except that enums have the
11529 /// full range of their type, not the range of their enumerators.
11530 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11531 assert(T->isCanonicalUnqualified());
11532
11533 if (const VectorType *VT = dyn_cast<VectorType>(T))
11534 T = VT->getElementType().getTypePtr();
11535 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11536 T = MT->getElementType().getTypePtr();
11537 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11538 T = CT->getElementType().getTypePtr();
11539 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11540 T = AT->getValueType().getTypePtr();
11541 if (const auto *ED = T->getAsEnumDecl())
11542 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11543 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11544 T = OBT->getUnderlyingType().getTypePtr();
11545
11546 if (const auto *EIT = dyn_cast<BitIntType>(T))
11547 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11548
11549 const BuiltinType *BT = cast<BuiltinType>(T);
11550 assert(BT->isInteger());
11551
11552 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11553 }
11554
11555 /// Returns the supremum of two ranges: i.e. their conservative merge.
11556 static IntRange join(IntRange L, IntRange R) {
11557 bool Unsigned = L.NonNegative && R.NonNegative;
11558 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11559 L.NonNegative && R.NonNegative);
11560 }
11561
11562 /// Return the range of a bitwise-AND of the two ranges.
11563 static IntRange bit_and(IntRange L, IntRange R) {
11564 unsigned Bits = std::max(L.Width, R.Width);
11565 bool NonNegative = false;
11566 if (L.NonNegative) {
11567 Bits = std::min(Bits, L.Width);
11568 NonNegative = true;
11569 }
11570 if (R.NonNegative) {
11571 Bits = std::min(Bits, R.Width);
11572 NonNegative = true;
11573 }
11574 return IntRange(Bits, NonNegative);
11575 }
11576
11577 /// Return the range of a sum of the two ranges.
11578 static IntRange sum(IntRange L, IntRange R) {
11579 bool Unsigned = L.NonNegative && R.NonNegative;
11580 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11581 Unsigned);
11582 }
11583
11584 /// Return the range of a difference of the two ranges.
11585 static IntRange difference(IntRange L, IntRange R) {
11586 // We need a 1-bit-wider range if:
11587 // 1) LHS can be negative: least value can be reduced.
11588 // 2) RHS can be negative: greatest value can be increased.
11589 bool CanWiden = !L.NonNegative || !R.NonNegative;
11590 bool Unsigned = L.NonNegative && R.Width == 0;
11591 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11592 !Unsigned,
11593 Unsigned);
11594 }
11595
11596 /// Return the range of a product of the two ranges.
11597 static IntRange product(IntRange L, IntRange R) {
11598 // If both LHS and RHS can be negative, we can form
11599 // -2^L * -2^R = 2^(L + R)
11600 // which requires L + R + 1 value bits to represent.
11601 bool CanWiden = !L.NonNegative && !R.NonNegative;
11602 bool Unsigned = L.NonNegative && R.NonNegative;
11603 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11604 Unsigned);
11605 }
11606
11607 /// Return the range of a remainder operation between the two ranges.
11608 static IntRange rem(IntRange L, IntRange R) {
11609 // The result of a remainder can't be larger than the result of
11610 // either side. The sign of the result is the sign of the LHS.
11611 bool Unsigned = L.NonNegative;
11612 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11613 Unsigned);
11614 }
11615};
11616
11617} // namespace
11618
11619static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11620 if (value.isSigned() && value.isNegative())
11621 return IntRange(value.getSignificantBits(), false);
11622
11623 if (value.getBitWidth() > MaxWidth)
11624 value = value.trunc(MaxWidth);
11625
11626 // isNonNegative() just checks the sign bit without considering
11627 // signedness.
11628 return IntRange(value.getActiveBits(), true);
11629}
11630
11631static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11632 if (result.isInt())
11633 return GetValueRange(result.getInt(), MaxWidth);
11634
11635 if (result.isVector()) {
11636 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11637 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11638 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11639 R = IntRange::join(R, El);
11640 }
11641 return R;
11642 }
11643
11644 if (result.isComplexInt()) {
11645 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11646 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11647 return IntRange::join(R, I);
11648 }
11649
11650 // This can happen with lossless casts to intptr_t of "based" lvalues.
11651 // Assume it might use arbitrary bits.
11652 // FIXME: The only reason we need to pass the type in here is to get
11653 // the sign right on this one case. It would be nice if APValue
11654 // preserved this.
11655 assert(result.isLValue() || result.isAddrLabelDiff());
11656 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11657}
11658
11659static QualType GetExprType(const Expr *E) {
11660 QualType Ty = E->getType();
11661 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11662 Ty = AtomicRHS->getValueType();
11663 return Ty;
11664}
11665
11666/// Attempts to estimate an approximate range for the given integer expression.
11667/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11668/// reliable estimation cannot be determined.
11669///
11670/// \param MaxWidth The width to which the value will be truncated.
11671/// \param InConstantContext If \c true, interpret the expression within a
11672/// constant context.
11673/// \param Approximate If \c true, provide a likely range of values by assuming
11674/// that arithmetic on narrower types remains within those types.
11675/// If \c false, return a range that includes all possible values
11676/// resulting from the expression.
11677/// \returns A range of values that the expression might take, or
11678/// std::nullopt if a reliable estimation cannot be determined.
11679static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11680 unsigned MaxWidth,
11681 bool InConstantContext,
11682 bool Approximate) {
11683 E = E->IgnoreParens();
11684
11685 // Try a full evaluation first.
11686 Expr::EvalResult result;
11687 if (E->EvaluateAsRValue(result, C, InConstantContext))
11688 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11689
11690 // I think we only want to look through implicit casts here; if the
11691 // user has an explicit widening cast, we should treat the value as
11692 // being of the new, wider type.
11693 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11694 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11695 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11696 Approximate);
11697
11698 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11699
11700 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11701 CE->getCastKind() == CK_BooleanToSignedIntegral;
11702
11703 // Assume that non-integer casts can span the full range of the type.
11704 if (!isIntegerCast)
11705 return OutputTypeRange;
11706
11707 std::optional<IntRange> SubRange = TryGetExprRange(
11708 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11709 InConstantContext, Approximate);
11710 if (!SubRange)
11711 return std::nullopt;
11712
11713 // Bail out if the subexpr's range is as wide as the cast type.
11714 if (SubRange->Width >= OutputTypeRange.Width)
11715 return OutputTypeRange;
11716
11717 // Otherwise, we take the smaller width, and we're non-negative if
11718 // either the output type or the subexpr is.
11719 return IntRange(SubRange->Width,
11720 SubRange->NonNegative || OutputTypeRange.NonNegative);
11721 }
11722
11723 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11724 // If we can fold the condition, just take that operand.
11725 bool CondResult;
11726 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11727 return TryGetExprRange(
11728 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11729 InConstantContext, Approximate);
11730
11731 // Otherwise, conservatively merge.
11732 // TryGetExprRange requires an integer expression, but a throw expression
11733 // results in a void type.
11734 Expr *TrueExpr = CO->getTrueExpr();
11735 if (TrueExpr->getType()->isVoidType())
11736 return std::nullopt;
11737
11738 std::optional<IntRange> L =
11739 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11740 if (!L)
11741 return std::nullopt;
11742
11743 Expr *FalseExpr = CO->getFalseExpr();
11744 if (FalseExpr->getType()->isVoidType())
11745 return std::nullopt;
11746
11747 std::optional<IntRange> R =
11748 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11749 if (!R)
11750 return std::nullopt;
11751
11752 return IntRange::join(*L, *R);
11753 }
11754
11755 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11756 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11757
11758 switch (BO->getOpcode()) {
11759 case BO_Cmp:
11760 llvm_unreachable("builtin <=> should have class type");
11761
11762 // Boolean-valued operations are single-bit and positive.
11763 case BO_LAnd:
11764 case BO_LOr:
11765 case BO_LT:
11766 case BO_GT:
11767 case BO_LE:
11768 case BO_GE:
11769 case BO_EQ:
11770 case BO_NE:
11771 return IntRange::forBoolType();
11772
11773 // The type of the assignments is the type of the LHS, so the RHS
11774 // is not necessarily the same type.
11775 case BO_MulAssign:
11776 case BO_DivAssign:
11777 case BO_RemAssign:
11778 case BO_AddAssign:
11779 case BO_SubAssign:
11780 case BO_XorAssign:
11781 case BO_OrAssign:
11782 // TODO: bitfields?
11783 return IntRange::forValueOfType(C, GetExprType(E));
11784
11785 // Simple assignments just pass through the RHS, which will have
11786 // been coerced to the LHS type.
11787 case BO_Assign:
11788 // TODO: bitfields?
11789 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11790 Approximate);
11791
11792 // Operations with opaque sources are black-listed.
11793 case BO_PtrMemD:
11794 case BO_PtrMemI:
11795 return IntRange::forValueOfType(C, GetExprType(E));
11796
11797 // Bitwise-and uses the *infinum* of the two source ranges.
11798 case BO_And:
11799 case BO_AndAssign:
11800 Combine = IntRange::bit_and;
11801 break;
11802
11803 // Left shift gets black-listed based on a judgement call.
11804 case BO_Shl:
11805 // ...except that we want to treat '1 << (blah)' as logically
11806 // positive. It's an important idiom.
11807 if (IntegerLiteral *I
11808 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11809 if (I->getValue() == 1) {
11810 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11811 return IntRange(R.Width, /*NonNegative*/ true);
11812 }
11813 }
11814 [[fallthrough]];
11815
11816 case BO_ShlAssign:
11817 return IntRange::forValueOfType(C, GetExprType(E));
11818
11819 // Right shift by a constant can narrow its left argument.
11820 case BO_Shr:
11821 case BO_ShrAssign: {
11822 std::optional<IntRange> L = TryGetExprRange(
11823 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11824 if (!L)
11825 return std::nullopt;
11826
11827 // If the shift amount is a positive constant, drop the width by
11828 // that much.
11829 if (std::optional<llvm::APSInt> shift =
11830 BO->getRHS()->getIntegerConstantExpr(C)) {
11831 if (shift->isNonNegative()) {
11832 if (shift->uge(L->Width))
11833 L->Width = (L->NonNegative ? 0 : 1);
11834 else
11835 L->Width -= shift->getZExtValue();
11836 }
11837 }
11838
11839 return L;
11840 }
11841
11842 // Comma acts as its right operand.
11843 case BO_Comma:
11844 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11845 Approximate);
11846
11847 case BO_Add:
11848 if (!Approximate)
11849 Combine = IntRange::sum;
11850 break;
11851
11852 case BO_Sub:
11853 if (BO->getLHS()->getType()->isPointerType())
11854 return IntRange::forValueOfType(C, GetExprType(E));
11855 if (!Approximate)
11856 Combine = IntRange::difference;
11857 break;
11858
11859 case BO_Mul:
11860 if (!Approximate)
11861 Combine = IntRange::product;
11862 break;
11863
11864 // The width of a division result is mostly determined by the size
11865 // of the LHS.
11866 case BO_Div: {
11867 // Don't 'pre-truncate' the operands.
11868 unsigned opWidth = C.getIntWidth(GetExprType(E));
11869 std::optional<IntRange> L = TryGetExprRange(
11870 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11871 if (!L)
11872 return std::nullopt;
11873
11874 // If the divisor is constant, use that.
11875 if (std::optional<llvm::APSInt> divisor =
11876 BO->getRHS()->getIntegerConstantExpr(C)) {
11877 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11878 if (log2 >= L->Width)
11879 L->Width = (L->NonNegative ? 0 : 1);
11880 else
11881 L->Width = std::min(L->Width - log2, MaxWidth);
11882 return L;
11883 }
11884
11885 // Otherwise, just use the LHS's width.
11886 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11887 // could be -1.
11888 std::optional<IntRange> R = TryGetExprRange(
11889 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11890 if (!R)
11891 return std::nullopt;
11892
11893 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11894 }
11895
11896 case BO_Rem:
11897 Combine = IntRange::rem;
11898 break;
11899
11900 // The default behavior is okay for these.
11901 case BO_Xor:
11902 case BO_Or:
11903 break;
11904 }
11905
11906 // Combine the two ranges, but limit the result to the type in which we
11907 // performed the computation.
11908 QualType T = GetExprType(E);
11909 unsigned opWidth = C.getIntWidth(T);
11910 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11911 InConstantContext, Approximate);
11912 if (!L)
11913 return std::nullopt;
11914
11915 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11916 InConstantContext, Approximate);
11917 if (!R)
11918 return std::nullopt;
11919
11920 IntRange C = Combine(*L, *R);
11921 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11922 C.Width = std::min(C.Width, MaxWidth);
11923 return C;
11924 }
11925
11926 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11927 switch (UO->getOpcode()) {
11928 // Boolean-valued operations are white-listed.
11929 case UO_LNot:
11930 return IntRange::forBoolType();
11931
11932 // Operations with opaque sources are black-listed.
11933 case UO_Deref:
11934 case UO_AddrOf: // should be impossible
11935 return IntRange::forValueOfType(C, GetExprType(E));
11936
11937 case UO_Minus: {
11938 if (E->getType()->isUnsignedIntegerType()) {
11939 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11940 Approximate);
11941 }
11942
11943 std::optional<IntRange> SubRange = TryGetExprRange(
11944 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11945
11946 if (!SubRange)
11947 return std::nullopt;
11948
11949 // If the range was previously non-negative, we need an extra bit for the
11950 // sign bit. Otherwise, we need an extra bit because the negation of the
11951 // most-negative value is one bit wider than that value.
11952 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11953 }
11954
11955 case UO_Not: {
11956 if (E->getType()->isUnsignedIntegerType()) {
11957 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11958 Approximate);
11959 }
11960
11961 std::optional<IntRange> SubRange = TryGetExprRange(
11962 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11963
11964 if (!SubRange)
11965 return std::nullopt;
11966
11967 // The width increments by 1 if the sub-expression cannot be negative
11968 // since it now can be.
11969 return IntRange(
11970 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11971 false);
11972 }
11973
11974 default:
11975 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11976 Approximate);
11977 }
11978 }
11979
11980 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11981 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11982 Approximate);
11983
11984 if (const auto *BitField = E->getSourceBitField())
11985 return IntRange(BitField->getBitWidthValue(),
11986 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11987
11988 if (GetExprType(E)->isVoidType())
11989 return std::nullopt;
11990
11991 return IntRange::forValueOfType(C, GetExprType(E));
11992}
11993
11994static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11995 bool InConstantContext,
11996 bool Approximate) {
11997 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11998 Approximate);
11999}
12000
12001/// Checks whether the given value, which currently has the given
12002/// source semantics, has the same value when coerced through the
12003/// target semantics.
12004static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12005 const llvm::fltSemantics &Src,
12006 const llvm::fltSemantics &Tgt) {
12007 llvm::APFloat truncated = value;
12008
12009 bool ignored;
12010 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12011 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12012
12013 return truncated.bitwiseIsEqual(value);
12014}
12015
12016/// Checks whether the given value, which currently has the given
12017/// source semantics, has the same value when coerced through the
12018/// target semantics.
12019///
12020/// The value might be a vector of floats (or a complex number).
12021static bool IsSameFloatAfterCast(const APValue &value,
12022 const llvm::fltSemantics &Src,
12023 const llvm::fltSemantics &Tgt) {
12024 if (value.isFloat())
12025 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12026
12027 if (value.isVector()) {
12028 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12029 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12030 return false;
12031 return true;
12032 }
12033
12034 if (value.isMatrix()) {
12035 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12036 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12037 return false;
12038 return true;
12039 }
12040
12041 assert(value.isComplexFloat());
12042 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12043 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12044}
12045
12046static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12047 bool IsListInit = false);
12048
12049static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12050 // Suppress cases where we are comparing against an enum constant.
12051 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12052 if (isa<EnumConstantDecl>(DR->getDecl()))
12053 return true;
12054
12055 // Suppress cases where the value is expanded from a macro, unless that macro
12056 // is how a language represents a boolean literal. This is the case in both C
12057 // and Objective-C.
12058 SourceLocation BeginLoc = E->getBeginLoc();
12059 if (BeginLoc.isMacroID()) {
12060 StringRef MacroName = Lexer::getImmediateMacroName(
12061 BeginLoc, S.getSourceManager(), S.getLangOpts());
12062 return MacroName != "YES" && MacroName != "NO" &&
12063 MacroName != "true" && MacroName != "false";
12064 }
12065
12066 return false;
12067}
12068
12069static bool isKnownToHaveUnsignedValue(const Expr *E) {
12070 return E->getType()->isIntegerType() &&
12071 (!E->getType()->isSignedIntegerType() ||
12073}
12074
12075namespace {
12076/// The promoted range of values of a type. In general this has the
12077/// following structure:
12078///
12079/// |-----------| . . . |-----------|
12080/// ^ ^ ^ ^
12081/// Min HoleMin HoleMax Max
12082///
12083/// ... where there is only a hole if a signed type is promoted to unsigned
12084/// (in which case Min and Max are the smallest and largest representable
12085/// values).
12086struct PromotedRange {
12087 // Min, or HoleMax if there is a hole.
12088 llvm::APSInt PromotedMin;
12089 // Max, or HoleMin if there is a hole.
12090 llvm::APSInt PromotedMax;
12091
12092 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12093 if (R.Width == 0)
12094 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12095 else if (R.Width >= BitWidth && !Unsigned) {
12096 // Promotion made the type *narrower*. This happens when promoting
12097 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12098 // Treat all values of 'signed int' as being in range for now.
12099 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12100 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12101 } else {
12102 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12103 .extOrTrunc(BitWidth);
12104 PromotedMin.setIsUnsigned(Unsigned);
12105
12106 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12107 .extOrTrunc(BitWidth);
12108 PromotedMax.setIsUnsigned(Unsigned);
12109 }
12110 }
12111
12112 // Determine whether this range is contiguous (has no hole).
12113 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12114
12115 // Where a constant value is within the range.
12116 enum ComparisonResult {
12117 LT = 0x1,
12118 LE = 0x2,
12119 GT = 0x4,
12120 GE = 0x8,
12121 EQ = 0x10,
12122 NE = 0x20,
12123 InRangeFlag = 0x40,
12124
12125 Less = LE | LT | NE,
12126 Min = LE | InRangeFlag,
12127 InRange = InRangeFlag,
12128 Max = GE | InRangeFlag,
12129 Greater = GE | GT | NE,
12130
12131 OnlyValue = LE | GE | EQ | InRangeFlag,
12132 InHole = NE
12133 };
12134
12135 ComparisonResult compare(const llvm::APSInt &Value) const {
12136 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12137 Value.isUnsigned() == PromotedMin.isUnsigned());
12138 if (!isContiguous()) {
12139 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12140 if (Value.isMinValue()) return Min;
12141 if (Value.isMaxValue()) return Max;
12142 if (Value >= PromotedMin) return InRange;
12143 if (Value <= PromotedMax) return InRange;
12144 return InHole;
12145 }
12146
12147 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12148 case -1: return Less;
12149 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12150 case 1:
12151 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12152 case -1: return InRange;
12153 case 0: return Max;
12154 case 1: return Greater;
12155 }
12156 }
12157
12158 llvm_unreachable("impossible compare result");
12159 }
12160
12161 static std::optional<StringRef>
12162 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12163 if (Op == BO_Cmp) {
12164 ComparisonResult LTFlag = LT, GTFlag = GT;
12165 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12166
12167 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12168 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12169 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12170 return std::nullopt;
12171 }
12172
12173 ComparisonResult TrueFlag, FalseFlag;
12174 if (Op == BO_EQ) {
12175 TrueFlag = EQ;
12176 FalseFlag = NE;
12177 } else if (Op == BO_NE) {
12178 TrueFlag = NE;
12179 FalseFlag = EQ;
12180 } else {
12181 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12182 TrueFlag = LT;
12183 FalseFlag = GE;
12184 } else {
12185 TrueFlag = GT;
12186 FalseFlag = LE;
12187 }
12188 if (Op == BO_GE || Op == BO_LE)
12189 std::swap(TrueFlag, FalseFlag);
12190 }
12191 if (R & TrueFlag)
12192 return StringRef("true");
12193 if (R & FalseFlag)
12194 return StringRef("false");
12195 return std::nullopt;
12196 }
12197};
12198}
12199
12200static bool HasEnumType(const Expr *E) {
12201 // Strip off implicit integral promotions.
12202 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12203 if (ICE->getCastKind() != CK_IntegralCast &&
12204 ICE->getCastKind() != CK_NoOp)
12205 break;
12206 E = ICE->getSubExpr();
12207 }
12208
12209 return E->getType()->isEnumeralType();
12210}
12211
12212static int classifyConstantValue(Expr *Constant) {
12213 // The values of this enumeration are used in the diagnostics
12214 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12215 enum ConstantValueKind {
12216 Miscellaneous = 0,
12217 LiteralTrue,
12218 LiteralFalse
12219 };
12220 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12221 return BL->getValue() ? ConstantValueKind::LiteralTrue
12222 : ConstantValueKind::LiteralFalse;
12223 return ConstantValueKind::Miscellaneous;
12224}
12225
12227 Expr *Constant, Expr *Other,
12228 const llvm::APSInt &Value,
12229 bool RhsConstant) {
12231 return false;
12232
12233 Expr *OriginalOther = Other;
12234
12235 Constant = Constant->IgnoreParenImpCasts();
12236 Other = Other->IgnoreParenImpCasts();
12237
12238 // Suppress warnings on tautological comparisons between values of the same
12239 // enumeration type. There are only two ways we could warn on this:
12240 // - If the constant is outside the range of representable values of
12241 // the enumeration. In such a case, we should warn about the cast
12242 // to enumeration type, not about the comparison.
12243 // - If the constant is the maximum / minimum in-range value. For an
12244 // enumeratin type, such comparisons can be meaningful and useful.
12245 if (Constant->getType()->isEnumeralType() &&
12246 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12247 return false;
12248
12249 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12250 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12251 if (!OtherValueRange)
12252 return false;
12253
12254 QualType OtherT = Other->getType();
12255 if (const auto *AT = OtherT->getAs<AtomicType>())
12256 OtherT = AT->getValueType();
12257 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12258
12259 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12260 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12261 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12262 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12263 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12264
12265 // Whether we're treating Other as being a bool because of the form of
12266 // expression despite it having another type (typically 'int' in C).
12267 bool OtherIsBooleanDespiteType =
12268 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12269 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12270 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12271
12272 // Check if all values in the range of possible values of this expression
12273 // lead to the same comparison outcome.
12274 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12275 Value.isUnsigned());
12276 auto Cmp = OtherPromotedValueRange.compare(Value);
12277 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12278 if (!Result)
12279 return false;
12280
12281 // Also consider the range determined by the type alone. This allows us to
12282 // classify the warning under the proper diagnostic group.
12283 bool TautologicalTypeCompare = false;
12284 {
12285 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12286 Value.isUnsigned());
12287 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12288 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12289 RhsConstant)) {
12290 TautologicalTypeCompare = true;
12291 Cmp = TypeCmp;
12292 Result = TypeResult;
12293 }
12294 }
12295
12296 // Don't warn if the non-constant operand actually always evaluates to the
12297 // same value.
12298 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12299 return false;
12300
12301 // Suppress the diagnostic for an in-range comparison if the constant comes
12302 // from a macro or enumerator. We don't want to diagnose
12303 //
12304 // some_long_value <= INT_MAX
12305 //
12306 // when sizeof(int) == sizeof(long).
12307 bool InRange = Cmp & PromotedRange::InRangeFlag;
12308 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12309 return false;
12310
12311 // A comparison of an unsigned bit-field against 0 is really a type problem,
12312 // even though at the type level the bit-field might promote to 'signed int'.
12313 if (Other->refersToBitField() && InRange && Value == 0 &&
12314 Other->getType()->isUnsignedIntegerOrEnumerationType())
12315 TautologicalTypeCompare = true;
12316
12317 // If this is a comparison to an enum constant, include that
12318 // constant in the diagnostic.
12319 const EnumConstantDecl *ED = nullptr;
12320 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12321 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12322
12323 // Should be enough for uint128 (39 decimal digits)
12324 SmallString<64> PrettySourceValue;
12325 llvm::raw_svector_ostream OS(PrettySourceValue);
12326 if (ED) {
12327 OS << '\'' << *ED << "' (" << Value << ")";
12328 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12329 Constant->IgnoreParenImpCasts())) {
12330 OS << (BL->getValue() ? "YES" : "NO");
12331 } else {
12332 OS << Value;
12333 }
12334
12335 if (!TautologicalTypeCompare) {
12336 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12337 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12338 << E->getOpcodeStr() << OS.str() << *Result
12339 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12340 return true;
12341 }
12342
12343 if (IsObjCSignedCharBool) {
12345 S.PDiag(diag::warn_tautological_compare_objc_bool)
12346 << OS.str() << *Result);
12347 return true;
12348 }
12349
12350 // FIXME: We use a somewhat different formatting for the in-range cases and
12351 // cases involving boolean values for historical reasons. We should pick a
12352 // consistent way of presenting these diagnostics.
12353 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12354
12356 E->getOperatorLoc(), E,
12357 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12358 : diag::warn_tautological_bool_compare)
12359 << OS.str() << classifyConstantValue(Constant) << OtherT
12360 << OtherIsBooleanDespiteType << *Result
12361 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12362 } else {
12363 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12364 unsigned Diag =
12365 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12366 ? (HasEnumType(OriginalOther)
12367 ? diag::warn_unsigned_enum_always_true_comparison
12368 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12369 : diag::warn_unsigned_always_true_comparison)
12370 : diag::warn_tautological_constant_compare;
12371
12372 S.Diag(E->getOperatorLoc(), Diag)
12373 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12374 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12375 }
12376
12377 return true;
12378}
12379
12380/// Analyze the operands of the given comparison. Implements the
12381/// fallback case from AnalyzeComparison.
12386
12387/// Implements -Wsign-compare.
12388///
12389/// \param E the binary operator to check for warnings
12391 // The type the comparison is being performed in.
12392 QualType T = E->getLHS()->getType();
12393
12394 // Only analyze comparison operators where both sides have been converted to
12395 // the same type.
12396 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12397 return AnalyzeImpConvsInComparison(S, E);
12398
12399 // Don't analyze value-dependent comparisons directly.
12400 if (E->isValueDependent())
12401 return AnalyzeImpConvsInComparison(S, E);
12402
12403 Expr *LHS = E->getLHS();
12404 Expr *RHS = E->getRHS();
12405
12406 if (T->isIntegralType(S.Context)) {
12407 std::optional<llvm::APSInt> RHSValue =
12409 std::optional<llvm::APSInt> LHSValue =
12411
12412 // We don't care about expressions whose result is a constant.
12413 if (RHSValue && LHSValue)
12414 return AnalyzeImpConvsInComparison(S, E);
12415
12416 // We only care about expressions where just one side is literal
12417 if ((bool)RHSValue ^ (bool)LHSValue) {
12418 // Is the constant on the RHS or LHS?
12419 const bool RhsConstant = (bool)RHSValue;
12420 Expr *Const = RhsConstant ? RHS : LHS;
12421 Expr *Other = RhsConstant ? LHS : RHS;
12422 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12423
12424 // Check whether an integer constant comparison results in a value
12425 // of 'true' or 'false'.
12426 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12427 return AnalyzeImpConvsInComparison(S, E);
12428 }
12429 }
12430
12431 if (!T->hasUnsignedIntegerRepresentation()) {
12432 // We don't do anything special if this isn't an unsigned integral
12433 // comparison: we're only interested in integral comparisons, and
12434 // signed comparisons only happen in cases we don't care to warn about.
12435 return AnalyzeImpConvsInComparison(S, E);
12436 }
12437
12438 LHS = LHS->IgnoreParenImpCasts();
12439 RHS = RHS->IgnoreParenImpCasts();
12440
12441 if (!S.getLangOpts().CPlusPlus) {
12442 // Avoid warning about comparison of integers with different signs when
12443 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12444 // the type of `E`.
12445 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12446 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12447 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12448 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12449 }
12450
12451 // Check to see if one of the (unmodified) operands is of different
12452 // signedness.
12453 Expr *signedOperand, *unsignedOperand;
12455 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12456 "unsigned comparison between two signed integer expressions?");
12457 signedOperand = LHS;
12458 unsignedOperand = RHS;
12459 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12460 signedOperand = RHS;
12461 unsignedOperand = LHS;
12462 } else {
12463 return AnalyzeImpConvsInComparison(S, E);
12464 }
12465
12466 // Otherwise, calculate the effective range of the signed operand.
12467 std::optional<IntRange> signedRange =
12469 /*Approximate=*/true);
12470 if (!signedRange)
12471 return;
12472
12473 // Go ahead and analyze implicit conversions in the operands. Note
12474 // that we skip the implicit conversions on both sides.
12477
12478 // If the signed range is non-negative, -Wsign-compare won't fire.
12479 if (signedRange->NonNegative)
12480 return;
12481
12482 // For (in)equality comparisons, if the unsigned operand is a
12483 // constant which cannot collide with a overflowed signed operand,
12484 // then reinterpreting the signed operand as unsigned will not
12485 // change the result of the comparison.
12486 if (E->isEqualityOp()) {
12487 unsigned comparisonWidth = S.Context.getIntWidth(T);
12488 std::optional<IntRange> unsignedRange = TryGetExprRange(
12489 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12490 /*Approximate=*/true);
12491 if (!unsignedRange)
12492 return;
12493
12494 // We should never be unable to prove that the unsigned operand is
12495 // non-negative.
12496 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12497
12498 if (unsignedRange->Width < comparisonWidth)
12499 return;
12500 }
12501
12503 S.PDiag(diag::warn_mixed_sign_comparison)
12504 << LHS->getType() << RHS->getType()
12505 << LHS->getSourceRange() << RHS->getSourceRange());
12506}
12507
12508/// Analyzes an attempt to assign the given value to a bitfield.
12509///
12510/// Returns true if there was something fishy about the attempt.
12512 SourceLocation InitLoc) {
12513 assert(Bitfield->isBitField());
12514 if (Bitfield->isInvalidDecl())
12515 return false;
12516
12517 // White-list bool bitfields.
12518 QualType BitfieldType = Bitfield->getType();
12519 if (BitfieldType->isBooleanType())
12520 return false;
12521
12522 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12523 // If the underlying enum type was not explicitly specified as an unsigned
12524 // type and the enum contain only positive values, MSVC++ will cause an
12525 // inconsistency by storing this as a signed type.
12526 if (S.getLangOpts().CPlusPlus11 &&
12527 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12528 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12529 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12530 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12531 << BitfieldEnumDecl;
12532 }
12533 }
12534
12535 // Ignore value- or type-dependent expressions.
12536 if (Bitfield->getBitWidth()->isValueDependent() ||
12537 Bitfield->getBitWidth()->isTypeDependent() ||
12538 Init->isValueDependent() ||
12539 Init->isTypeDependent())
12540 return false;
12541
12542 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12543 unsigned FieldWidth = Bitfield->getBitWidthValue();
12544
12545 Expr::EvalResult Result;
12546 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12548 // The RHS is not constant. If the RHS has an enum type, make sure the
12549 // bitfield is wide enough to hold all the values of the enum without
12550 // truncation.
12551 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12552 const PreferredTypeAttr *PTAttr = nullptr;
12553 if (!ED) {
12554 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12555 if (PTAttr)
12556 ED = PTAttr->getType()->getAsEnumDecl();
12557 }
12558 if (ED) {
12559 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12560
12561 // Enum types are implicitly signed on Windows, so check if there are any
12562 // negative enumerators to see if the enum was intended to be signed or
12563 // not.
12564 bool SignedEnum = ED->getNumNegativeBits() > 0;
12565
12566 // Check for surprising sign changes when assigning enum values to a
12567 // bitfield of different signedness. If the bitfield is signed and we
12568 // have exactly the right number of bits to store this unsigned enum,
12569 // suggest changing the enum to an unsigned type. This typically happens
12570 // on Windows where unfixed enums always use an underlying type of 'int'.
12571 unsigned DiagID = 0;
12572 if (SignedEnum && !SignedBitfield) {
12573 DiagID =
12574 PTAttr == nullptr
12575 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12576 : diag::
12577 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12578 } else if (SignedBitfield && !SignedEnum &&
12579 ED->getNumPositiveBits() == FieldWidth) {
12580 DiagID =
12581 PTAttr == nullptr
12582 ? diag::warn_signed_bitfield_enum_conversion
12583 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12584 }
12585 if (DiagID) {
12586 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12587 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12588 SourceRange TypeRange =
12589 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12590 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12591 << SignedEnum << TypeRange;
12592 if (PTAttr)
12593 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12594 << ED;
12595 }
12596
12597 // Compute the required bitwidth. If the enum has negative values, we need
12598 // one more bit than the normal number of positive bits to represent the
12599 // sign bit.
12600 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12601 ED->getNumNegativeBits())
12602 : ED->getNumPositiveBits();
12603
12604 // Check the bitwidth.
12605 if (BitsNeeded > FieldWidth) {
12606 Expr *WidthExpr = Bitfield->getBitWidth();
12607 auto DiagID =
12608 PTAttr == nullptr
12609 ? diag::warn_bitfield_too_small_for_enum
12610 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12611 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12612 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12613 << BitsNeeded << ED << WidthExpr->getSourceRange();
12614 if (PTAttr)
12615 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12616 << ED;
12617 }
12618 }
12619
12620 return false;
12621 }
12622
12623 llvm::APSInt Value = Result.Val.getInt();
12624
12625 unsigned OriginalWidth = Value.getBitWidth();
12626
12627 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12628 // false positives where the user is demonstrating they intend to use the
12629 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12630 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12631 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12632 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12633 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12634 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12635 S.findMacroSpelling(MaybeMacroLoc, "true"))
12636 return false;
12637 }
12638
12639 if (!Value.isSigned() || Value.isNegative())
12640 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12641 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12642 OriginalWidth = Value.getSignificantBits();
12643
12644 if (OriginalWidth <= FieldWidth)
12645 return false;
12646
12647 // Compute the value which the bitfield will contain.
12648 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12649 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12650
12651 // Check whether the stored value is equal to the original value.
12652 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12653 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12654 return false;
12655
12656 std::string PrettyValue = toString(Value, 10);
12657 std::string PrettyTrunc = toString(TruncatedValue, 10);
12658
12659 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12660 ? diag::warn_impcast_single_bit_bitield_precision_constant
12661 : diag::warn_impcast_bitfield_precision_constant)
12662 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12663 << Init->getSourceRange();
12664
12665 return true;
12666}
12667
12668/// Analyze the given simple or compound assignment for warning-worthy
12669/// operations.
12671 // Just recurse on the LHS.
12673
12674 // We want to recurse on the RHS as normal unless we're assigning to
12675 // a bitfield.
12676 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12677 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12678 E->getOperatorLoc())) {
12679 // Recurse, ignoring any implicit conversions on the RHS.
12681 E->getOperatorLoc());
12682 }
12683 }
12684
12685 // Set context flag for overflow behavior type assignment analysis, use RAII
12686 // pattern to handle nested assignments.
12687 llvm::SaveAndRestore OBTAssignmentContext(
12689
12691
12692 // Diagnose implicitly sequentially-consistent atomic assignment.
12693 if (E->getLHS()->getType()->isAtomicType())
12694 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12695}
12696
12697/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12698static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12699 QualType T, SourceLocation CContext, unsigned diag,
12700 bool PruneControlFlow = false) {
12701 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12702 // address space annotations isn't really useful. The warnings aren't because
12703 // you're converting a `private int` to `unsigned int`, it is because you're
12704 // conerting `int` to `unsigned int`.
12705 if (SourceType.hasAddressSpace())
12706 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12707 if (T.hasAddressSpace())
12709 if (PruneControlFlow) {
12711 S.PDiag(diag)
12712 << SourceType << T << E->getSourceRange()
12713 << SourceRange(CContext));
12714 return;
12715 }
12716 S.Diag(E->getExprLoc(), diag)
12717 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12718}
12719
12720/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12721static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12722 SourceLocation CContext, unsigned diag,
12723 bool PruneControlFlow = false) {
12724 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12725}
12726
12727/// Diagnose an implicit cast from a floating point value to an integer value.
12728static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12729 SourceLocation CContext) {
12730 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12731 bool PruneWarnings = S.inTemplateInstantiation();
12732
12733 const Expr *InnerE = E->IgnoreParenImpCasts();
12734 // We also want to warn on, e.g., "int i = -1.234"
12735 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12736 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12737 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12738
12739 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12740
12741 llvm::APFloat Value(0.0);
12742 bool IsConstant =
12744 if (!IsConstant) {
12745 if (S.ObjC().isSignedCharBool(T)) {
12747 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12748 << E->getType());
12749 }
12750
12751 return DiagnoseImpCast(S, E, T, CContext,
12752 diag::warn_impcast_float_integer, PruneWarnings);
12753 }
12754
12755 bool isExact = false;
12756
12757 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12758 T->hasUnsignedIntegerRepresentation());
12759 llvm::APFloat::opStatus Result = Value.convertToInteger(
12760 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12761
12762 // FIXME: Force the precision of the source value down so we don't print
12763 // digits which are usually useless (we don't really care here if we
12764 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12765 // would automatically print the shortest representation, but it's a bit
12766 // tricky to implement.
12767 SmallString<16> PrettySourceValue;
12768 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12769 precision = (precision * 59 + 195) / 196;
12770 Value.toString(PrettySourceValue, precision);
12771
12772 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12774 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12775 << PrettySourceValue);
12776 }
12777
12778 if (Result == llvm::APFloat::opOK && isExact) {
12779 if (IsLiteral) return;
12780 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12781 PruneWarnings);
12782 }
12783
12784 // Conversion of a floating-point value to a non-bool integer where the
12785 // integral part cannot be represented by the integer type is undefined.
12786 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12787 return DiagnoseImpCast(
12788 S, E, T, CContext,
12789 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12790 : diag::warn_impcast_float_to_integer_out_of_range,
12791 PruneWarnings);
12792
12793 unsigned DiagID = 0;
12794 if (IsLiteral) {
12795 // Warn on floating point literal to integer.
12796 DiagID = diag::warn_impcast_literal_float_to_integer;
12797 } else if (IntegerValue == 0) {
12798 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12799 return DiagnoseImpCast(S, E, T, CContext,
12800 diag::warn_impcast_float_integer, PruneWarnings);
12801 }
12802 // Warn on non-zero to zero conversion.
12803 DiagID = diag::warn_impcast_float_to_integer_zero;
12804 } else {
12805 if (IntegerValue.isUnsigned()) {
12806 if (!IntegerValue.isMaxValue()) {
12807 return DiagnoseImpCast(S, E, T, CContext,
12808 diag::warn_impcast_float_integer, PruneWarnings);
12809 }
12810 } else { // IntegerValue.isSigned()
12811 if (!IntegerValue.isMaxSignedValue() &&
12812 !IntegerValue.isMinSignedValue()) {
12813 return DiagnoseImpCast(S, E, T, CContext,
12814 diag::warn_impcast_float_integer, PruneWarnings);
12815 }
12816 }
12817 // Warn on evaluatable floating point expression to integer conversion.
12818 DiagID = diag::warn_impcast_float_to_integer;
12819 }
12820
12821 SmallString<16> PrettyTargetValue;
12822 if (IsBool)
12823 PrettyTargetValue = Value.isZero() ? "false" : "true";
12824 else
12825 IntegerValue.toString(PrettyTargetValue);
12826
12827 if (PruneWarnings) {
12829 S.PDiag(DiagID)
12830 << E->getType() << T.getUnqualifiedType()
12831 << PrettySourceValue << PrettyTargetValue
12832 << E->getSourceRange() << SourceRange(CContext));
12833 } else {
12834 S.Diag(E->getExprLoc(), DiagID)
12835 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12836 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12837 }
12838}
12839
12840/// Analyze the given compound assignment for the possible losing of
12841/// floating-point precision.
12843 assert(isa<CompoundAssignOperator>(E) &&
12844 "Must be compound assignment operation");
12845 // Recurse on the LHS and RHS in here
12848
12849 if (E->getLHS()->getType()->isAtomicType())
12850 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12851
12852 // Now check the outermost expression
12853 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12854 const auto *RBT = cast<CompoundAssignOperator>(E)
12855 ->getComputationResultType()
12856 ->getAs<BuiltinType>();
12857
12858 // The below checks assume source is floating point.
12859 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12860
12861 // If source is floating point but target is an integer.
12862 if (ResultBT->isInteger())
12863 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12864 E->getExprLoc(), diag::warn_impcast_float_integer);
12865
12866 if (!ResultBT->isFloatingPoint())
12867 return;
12868
12869 // If both source and target are floating points, warn about losing precision.
12871 QualType(ResultBT, 0), QualType(RBT, 0));
12872 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12873 // warn about dropping FP rank.
12874 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12875 diag::warn_impcast_float_result_precision);
12876}
12877
12878static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12879 IntRange Range) {
12880 if (!Range.Width) return "0";
12881
12882 llvm::APSInt ValueInRange = Value;
12883 ValueInRange.setIsSigned(!Range.NonNegative);
12884 ValueInRange = ValueInRange.trunc(Range.Width);
12885 return toString(ValueInRange, 10);
12886}
12887
12888static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12889 bool ToBool) {
12890 if (!isa<ImplicitCastExpr>(Ex))
12891 return false;
12892
12893 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12895 const Type *Source =
12897 if (Target->isDependentType())
12898 return false;
12899
12900 const auto *FloatCandidateBT =
12901 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12902 const Type *BoolCandidateType = ToBool ? Target : Source;
12903
12904 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12905 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12906}
12907
12908static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12909 SourceLocation CC) {
12910 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12911 const Expr *CurrA = TheCall->getArg(I);
12912 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12913 continue;
12914
12915 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12916 S, TheCall->getArg(I - 1), false));
12917 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12918 S, TheCall->getArg(I + 1), false));
12919 if (IsSwapped) {
12920 // Warn on this floating-point to bool conversion.
12922 CurrA->getType(), CC,
12923 diag::warn_impcast_floating_point_to_bool);
12924 }
12925 }
12926}
12927
12929 SourceLocation CC) {
12930 // Don't warn on functions which have return type nullptr_t.
12931 if (isa<CallExpr>(E))
12932 return;
12933
12934 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12935 const Expr *NewE = E->IgnoreParenImpCasts();
12936 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12937 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12938 if (!IsGNUNullExpr && !HasNullPtrType)
12939 return;
12940
12941 // Return if target type is a safe conversion.
12942 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12943 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12944 return;
12945
12946 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12947 E->getExprLoc()))
12948 return;
12949
12951
12952 // Venture through the macro stacks to get to the source of macro arguments.
12953 // The new location is a better location than the complete location that was
12954 // passed in.
12955 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12957
12958 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12959 if (IsGNUNullExpr && Loc.isMacroID()) {
12960 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12961 Loc, S.SourceMgr, S.getLangOpts());
12962 if (MacroName == "NULL")
12964 }
12965
12966 // Only warn if the null and context location are in the same macro expansion.
12967 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12968 return;
12969
12970 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12971 << HasNullPtrType << T << SourceRange(CC)
12973 S.getFixItZeroLiteralForType(T, Loc));
12974}
12975
12976// Helper function to filter out cases for constant width constant conversion.
12977// Don't warn on char array initialization or for non-decimal values.
12979 SourceLocation CC) {
12980 // If initializing from a constant, and the constant starts with '0',
12981 // then it is a binary, octal, or hexadecimal. Allow these constants
12982 // to fill all the bits, even if there is a sign change.
12983 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12984 const char FirstLiteralCharacter =
12985 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12986 if (FirstLiteralCharacter == '0')
12987 return false;
12988 }
12989
12990 // If the CC location points to a '{', and the type is char, then assume
12991 // assume it is an array initialization.
12992 if (CC.isValid() && T->isCharType()) {
12993 const char FirstContextCharacter =
12995 if (FirstContextCharacter == '{')
12996 return false;
12997 }
12998
12999 return true;
13000}
13001
13003 const auto *IL = dyn_cast<IntegerLiteral>(E);
13004 if (!IL) {
13005 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13006 if (UO->getOpcode() == UO_Minus)
13007 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13008 }
13009 }
13010
13011 return IL;
13012}
13013
13015 E = E->IgnoreParenImpCasts();
13016 SourceLocation ExprLoc = E->getExprLoc();
13017
13018 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13019 BinaryOperator::Opcode Opc = BO->getOpcode();
13020 Expr::EvalResult Result;
13021 // Do not diagnose unsigned shifts.
13022 if (Opc == BO_Shl) {
13023 const auto *LHS = getIntegerLiteral(BO->getLHS());
13024 const auto *RHS = getIntegerLiteral(BO->getRHS());
13025 if (LHS && LHS->getValue() == 0)
13026 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13027 else if (!E->isValueDependent() && LHS && RHS &&
13028 RHS->getValue().isNonNegative() &&
13030 S.Diag(ExprLoc, diag::warn_left_shift_always)
13031 << (Result.Val.getInt() != 0);
13032 else if (E->getType()->isSignedIntegerType())
13033 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13036 ") != 0");
13037 }
13038 }
13039
13040 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13041 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13042 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13043 if (!LHS || !RHS)
13044 return;
13045 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13046 (RHS->getValue() == 0 || RHS->getValue() == 1))
13047 // Do not diagnose common idioms.
13048 return;
13049 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13050 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13051 }
13052}
13053
13055 const Type *Target, Expr *E,
13056 QualType T,
13057 SourceLocation CC) {
13058 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13059 Source != Target);
13060
13061 // Lone surrogates have a distinct representation in UTF-32.
13062 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13063 // so don't warn on such conversion.
13064 if (Source->isChar16Type() && Target->isChar32Type())
13065 return;
13066
13067 Expr::EvalResult Result;
13070 llvm::APSInt Value(32);
13071 Value = Result.Val.getInt();
13072 bool IsASCII = Value <= 0x7F;
13073 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13074 bool ConversionPreservesSemantics =
13075 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13076
13077 if (!ConversionPreservesSemantics) {
13078 auto IsSingleCodeUnitCP = [](const QualType &T,
13079 const llvm::APSInt &Value) {
13080 if (T->isChar8Type())
13081 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13082 if (T->isChar16Type())
13083 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13084 assert(T->isChar32Type());
13085 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13086 };
13087
13088 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13089 << E->getType() << T
13090 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13091 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13092 }
13093 } else {
13094 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13096 DiagnoseImpCast(S, E, T, CC,
13097 LosesPrecision ? diag::warn_impcast_unicode_precision
13098 : diag::warn_impcast_unicode_char_type);
13099 }
13100}
13101
13103 From = Context.getCanonicalType(From);
13104 To = Context.getCanonicalType(To);
13105 QualType MaybePointee = From->getPointeeType();
13106 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13107 From = MaybePointee;
13108 MaybePointee = To->getPointeeType();
13109 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13110 To = MaybePointee;
13111
13112 if (const auto *FromFn = From->getAs<FunctionType>()) {
13113 if (const auto *ToFn = To->getAs<FunctionType>()) {
13114 if (FromFn->getCFIUncheckedCalleeAttr() &&
13115 !ToFn->getCFIUncheckedCalleeAttr())
13116 return true;
13117 }
13118 }
13119 return false;
13120}
13121
13123 bool *ICContext, bool IsListInit) {
13124 if (E->isTypeDependent() || E->isValueDependent()) return;
13125
13126 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13127 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13128 if (Source == Target) return;
13129 if (Target->isDependentType()) return;
13130
13131 // If the conversion context location is invalid don't complain. We also
13132 // don't want to emit a warning if the issue occurs from the expansion of
13133 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13134 // delay this check as long as possible. Once we detect we are in that
13135 // scenario, we just return.
13136 if (CC.isInvalid())
13137 return;
13138
13139 if (Source->isAtomicType())
13140 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13141
13142 // Diagnose implicit casts to bool.
13143 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13144 if (isa<StringLiteral>(E))
13145 // Warn on string literal to bool. Checks for string literals in logical
13146 // and expressions, for instance, assert(0 && "error here"), are
13147 // prevented by a check in AnalyzeImplicitConversions().
13148 return DiagnoseImpCast(*this, E, T, CC,
13149 diag::warn_impcast_string_literal_to_bool);
13152 // This covers the literal expressions that evaluate to Objective-C
13153 // objects.
13154 return DiagnoseImpCast(*this, E, T, CC,
13155 diag::warn_impcast_objective_c_literal_to_bool);
13156 }
13157 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13158 // Warn on pointer to bool conversion that is always true.
13160 SourceRange(CC));
13161 }
13162 }
13163
13165
13166 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13167 // is a typedef for signed char (macOS), then that constant value has to be 1
13168 // or 0.
13169 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13172 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13174 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13175 << toString(Result.Val.getInt(), 10));
13176 }
13177 return;
13178 }
13179 }
13180
13181 // Check implicit casts from Objective-C collection literals to specialized
13182 // collection types, e.g., NSArray<NSString *> *.
13183 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13184 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13185 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13186 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13187
13188 // Strip complex types.
13189 if (isa<ComplexType>(Source)) {
13190 if (!isa<ComplexType>(Target)) {
13191 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13192 return;
13193
13194 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13195 return DiagnoseImpCast(*this, E, T, CC,
13196 diag::err_impcast_incompatible_type);
13197 }
13198
13199 return DiagnoseImpCast(*this, E, T, CC,
13201 ? diag::err_impcast_complex_scalar
13202 : diag::warn_impcast_complex_scalar);
13203 }
13204
13205 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13206 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13207 }
13208
13209 // Strip vector types.
13210 if (isa<VectorType>(Source)) {
13211 if (Target->isSveVLSBuiltinType() &&
13212 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13213 QualType(Source, 0)) ||
13214 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13215 QualType(Source, 0))))
13216 return;
13217
13218 if (Target->isRVVVLSBuiltinType() &&
13219 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13220 QualType(Source, 0)) ||
13221 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13222 QualType(Source, 0))))
13223 return;
13224
13225 if (!isa<VectorType>(Target)) {
13226 if (SourceMgr.isInSystemMacro(CC))
13227 return;
13228 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13229 }
13230 if (getLangOpts().HLSL &&
13231 Target->castAs<VectorType>()->getNumElements() <
13232 Source->castAs<VectorType>()->getNumElements()) {
13233 // Diagnose vector truncation but don't return. We may also want to
13234 // diagnose an element conversion.
13235 DiagnoseImpCast(*this, E, T, CC,
13236 diag::warn_hlsl_impcast_vector_truncation);
13237 }
13238
13239 // If the vector cast is cast between two vectors of the same size, it is
13240 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13241 if (!getLangOpts().HLSL &&
13242 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13243 return;
13244
13245 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13246 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13247 }
13248 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13249 Target = VecTy->getElementType().getTypePtr();
13250
13251 // Strip matrix types.
13252 if (isa<ConstantMatrixType>(Source)) {
13253 if (Target->isScalarType())
13254 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13255
13258 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13259 // Diagnose Matrix truncation but don't return. We may also want to
13260 // diagnose an element conversion.
13261 DiagnoseImpCast(*this, E, T, CC,
13262 diag::warn_hlsl_impcast_matrix_truncation);
13263 }
13264
13265 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13266 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13267 }
13268 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13269 Target = MatTy->getElementType().getTypePtr();
13270
13271 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13272 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13273
13274 // Strip SVE vector types
13275 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13276 // Need the original target type for vector type checks
13277 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13278 // Handle conversion from scalable to fixed when msve-vector-bits is
13279 // specified
13280 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13281 QualType(Source, 0)) ||
13282 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13283 QualType(Source, 0)))
13284 return;
13285
13286 // If the vector cast is cast between two vectors of the same size, it is
13287 // a bitcast, not a conversion.
13288 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13289 return;
13290
13291 Source = SourceBT->getSveEltType(Context).getTypePtr();
13292 }
13293
13294 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13295 Target = TargetBT->getSveEltType(Context).getTypePtr();
13296
13297 // If the source is floating point...
13298 if (SourceBT && SourceBT->isFloatingPoint()) {
13299 // ...and the target is floating point...
13300 if (TargetBT && TargetBT->isFloatingPoint()) {
13301 // ...then warn if we're dropping FP rank.
13302
13304 QualType(SourceBT, 0), QualType(TargetBT, 0));
13305 if (Order > 0) {
13306 // Don't warn about float constants that are precisely
13307 // representable in the target type.
13308 Expr::EvalResult result;
13309 if (E->EvaluateAsRValue(result, Context)) {
13310 // Value might be a float, a float vector, or a float complex.
13312 result.Val,
13313 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13314 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13315 return;
13316 }
13317
13318 if (SourceMgr.isInSystemMacro(CC))
13319 return;
13320
13321 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13322 }
13323 // ... or possibly if we're increasing rank, too
13324 else if (Order < 0) {
13325 if (SourceMgr.isInSystemMacro(CC))
13326 return;
13327
13328 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13329 }
13330 return;
13331 }
13332
13333 // If the target is integral, always warn.
13334 if (TargetBT && TargetBT->isInteger()) {
13335 if (SourceMgr.isInSystemMacro(CC))
13336 return;
13337
13338 DiagnoseFloatingImpCast(*this, E, T, CC);
13339 }
13340
13341 // Detect the case where a call result is converted from floating-point to
13342 // to bool, and the final argument to the call is converted from bool, to
13343 // discover this typo:
13344 //
13345 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13346 //
13347 // FIXME: This is an incredibly special case; is there some more general
13348 // way to detect this class of misplaced-parentheses bug?
13349 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13350 // Check last argument of function call to see if it is an
13351 // implicit cast from a type matching the type the result
13352 // is being cast to.
13353 CallExpr *CEx = cast<CallExpr>(E);
13354 if (unsigned NumArgs = CEx->getNumArgs()) {
13355 Expr *LastA = CEx->getArg(NumArgs - 1);
13356 Expr *InnerE = LastA->IgnoreParenImpCasts();
13357 if (isa<ImplicitCastExpr>(LastA) &&
13358 InnerE->getType()->isBooleanType()) {
13359 // Warn on this floating-point to bool conversion
13360 DiagnoseImpCast(*this, E, T, CC,
13361 diag::warn_impcast_floating_point_to_bool);
13362 }
13363 }
13364 }
13365 return;
13366 }
13367
13368 // Valid casts involving fixed point types should be accounted for here.
13369 if (Source->isFixedPointType()) {
13370 if (Target->isUnsaturatedFixedPointType()) {
13374 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13375 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13376 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13377 if (Value > MaxVal || Value < MinVal) {
13379 PDiag(diag::warn_impcast_fixed_point_range)
13380 << Value.toString() << T
13381 << E->getSourceRange()
13382 << clang::SourceRange(CC));
13383 return;
13384 }
13385 }
13386 } else if (Target->isIntegerType()) {
13390 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13391
13392 bool Overflowed;
13393 llvm::APSInt IntResult = FXResult.convertToInt(
13394 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13395 &Overflowed);
13396
13397 if (Overflowed) {
13399 PDiag(diag::warn_impcast_fixed_point_range)
13400 << FXResult.toString() << T
13401 << E->getSourceRange()
13402 << clang::SourceRange(CC));
13403 return;
13404 }
13405 }
13406 }
13407 } else if (Target->isUnsaturatedFixedPointType()) {
13408 if (Source->isIntegerType()) {
13412 llvm::APSInt Value = Result.Val.getInt();
13413
13414 bool Overflowed;
13415 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13416 Value, Context.getFixedPointSemantics(T), &Overflowed);
13417
13418 if (Overflowed) {
13420 PDiag(diag::warn_impcast_fixed_point_range)
13421 << toString(Value, /*Radix=*/10) << T
13422 << E->getSourceRange()
13423 << clang::SourceRange(CC));
13424 return;
13425 }
13426 }
13427 }
13428 }
13429
13430 // If we are casting an integer type to a floating point type without
13431 // initialization-list syntax, we might lose accuracy if the floating
13432 // point type has a narrower significand than the integer type.
13433 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13434 TargetBT->isFloatingType() && !IsListInit) {
13435 // Determine the number of precision bits in the source integer type.
13436 std::optional<IntRange> SourceRange =
13438 /*Approximate=*/true);
13439 if (!SourceRange)
13440 return;
13441 unsigned int SourcePrecision = SourceRange->Width;
13442
13443 // Determine the number of precision bits in the
13444 // target floating point type.
13445 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13446 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13447
13448 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13449 SourcePrecision > TargetPrecision) {
13450
13451 if (std::optional<llvm::APSInt> SourceInt =
13453 // If the source integer is a constant, convert it to the target
13454 // floating point type. Issue a warning if the value changes
13455 // during the whole conversion.
13456 llvm::APFloat TargetFloatValue(
13457 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13458 llvm::APFloat::opStatus ConversionStatus =
13459 TargetFloatValue.convertFromAPInt(
13460 *SourceInt, SourceBT->isSignedInteger(),
13461 llvm::APFloat::rmNearestTiesToEven);
13462
13463 if (ConversionStatus != llvm::APFloat::opOK) {
13464 SmallString<32> PrettySourceValue;
13465 SourceInt->toString(PrettySourceValue, 10);
13466 SmallString<32> PrettyTargetValue;
13467 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13468
13470 E->getExprLoc(), E,
13471 PDiag(diag::warn_impcast_integer_float_precision_constant)
13472 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13473 << E->getSourceRange() << clang::SourceRange(CC));
13474 }
13475 } else {
13476 // Otherwise, the implicit conversion may lose precision.
13477 DiagnoseImpCast(*this, E, T, CC,
13478 diag::warn_impcast_integer_float_precision);
13479 }
13480 }
13481 }
13482
13483 DiagnoseNullConversion(*this, E, T, CC);
13484
13486
13487 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13488 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13489 return;
13490 }
13491
13492 if (Target->isBooleanType())
13493 DiagnoseIntInBoolContext(*this, E);
13494
13496 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13497 << QualType(Source, 0) << QualType(Target, 0);
13498 }
13499
13500 if (!Source->isIntegerType() || !Target->isIntegerType())
13501 return;
13502
13503 // TODO: remove this early return once the false positives for constant->bool
13504 // in templates, macros, etc, are reduced or removed.
13505 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13506 return;
13507
13508 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13509 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13511 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13512 << E->getType());
13513 }
13514 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13515 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13516 if (!LikelySourceRange)
13517 return;
13518
13519 IntRange SourceTypeRange =
13520 IntRange::forTargetOfCanonicalType(Context, Source);
13521 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13522
13523 if (LikelySourceRange->Width > TargetRange.Width) {
13524 // Check if target is a wrapping OBT - if so, don't warn about constant
13525 // conversion as this type may be used intentionally with implicit
13526 // truncation, especially during assignments.
13527 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13528 if (TargetOBT->isWrapKind()) {
13529 return;
13530 }
13531 }
13532
13533 // Check if source expression has an explicit __ob_wrap cast because if so,
13534 // wrapping was explicitly requested and we shouldn't warn
13535 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13536 if (SourceOBT->isWrapKind()) {
13537 return;
13538 }
13539 }
13540
13541 // If the source is a constant, use a default-on diagnostic.
13542 // TODO: this should happen for bitfield stores, too.
13546 llvm::APSInt Value(32);
13547 Value = Result.Val.getInt();
13548
13549 if (SourceMgr.isInSystemMacro(CC))
13550 return;
13551
13552 std::string PrettySourceValue = toString(Value, 10);
13553 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13554
13556 PDiag(diag::warn_impcast_integer_precision_constant)
13557 << PrettySourceValue << PrettyTargetValue
13558 << E->getType() << T << E->getSourceRange()
13559 << SourceRange(CC));
13560 return;
13561 }
13562
13563 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13564 if (SourceMgr.isInSystemMacro(CC))
13565 return;
13566
13567 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13568 if (UO->getOpcode() == UO_Minus)
13569 return DiagnoseImpCast(
13570 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13571 }
13572
13573 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13574 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13575 /* pruneControlFlow */ true);
13576 return DiagnoseImpCast(*this, E, T, CC,
13577 diag::warn_impcast_integer_precision);
13578 }
13579
13580 if (TargetRange.Width > SourceTypeRange.Width) {
13581 if (auto *UO = dyn_cast<UnaryOperator>(E))
13582 if (UO->getOpcode() == UO_Minus)
13583 if (Source->isUnsignedIntegerType()) {
13584 if (Target->isUnsignedIntegerType())
13585 return DiagnoseImpCast(*this, E, T, CC,
13586 diag::warn_impcast_high_order_zero_bits);
13587 if (Target->isSignedIntegerType())
13588 return DiagnoseImpCast(*this, E, T, CC,
13589 diag::warn_impcast_nonnegative_result);
13590 }
13591 }
13592
13593 if (TargetRange.Width == LikelySourceRange->Width &&
13594 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13595 Source->isSignedIntegerType()) {
13596 // Warn when doing a signed to signed conversion, warn if the positive
13597 // source value is exactly the width of the target type, which will
13598 // cause a negative value to be stored.
13599
13602 !SourceMgr.isInSystemMacro(CC)) {
13603 llvm::APSInt Value = Result.Val.getInt();
13604 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13605 std::string PrettySourceValue = toString(Value, 10);
13606 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13607
13608 Diag(E->getExprLoc(),
13609 PDiag(diag::warn_impcast_integer_precision_constant)
13610 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13611 << E->getSourceRange() << SourceRange(CC));
13612 return;
13613 }
13614 }
13615
13616 // Fall through for non-constants to give a sign conversion warning.
13617 }
13618
13619 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13620 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13621 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13622 LikelySourceRange->Width == TargetRange.Width))) {
13623 if (SourceMgr.isInSystemMacro(CC))
13624 return;
13625
13626 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13627 TargetBT->isInteger() &&
13628 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13629 return;
13630 }
13631
13632 unsigned DiagID = diag::warn_impcast_integer_sign;
13633
13634 // Traditionally, gcc has warned about this under -Wsign-compare.
13635 // We also want to warn about it in -Wconversion.
13636 // So if -Wconversion is off, use a completely identical diagnostic
13637 // in the sign-compare group.
13638 // The conditional-checking code will
13639 if (ICContext) {
13640 DiagID = diag::warn_impcast_integer_sign_conditional;
13641 *ICContext = true;
13642 }
13643
13644 DiagnoseImpCast(*this, E, T, CC, DiagID);
13645 }
13646
13647 // If we're implicitly converting from an integer into an enumeration, that
13648 // is valid in C but invalid in C++.
13649 QualType SourceType = E->getEnumCoercedType(Context);
13650 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13651 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13652 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13653
13654 // Diagnose conversions between different enumeration types.
13655 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13656 // type, to give us better diagnostics.
13657 Source = Context.getCanonicalType(SourceType).getTypePtr();
13658
13659 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13660 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13661 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13662 TargetEnum->getDecl()->hasNameForLinkage() &&
13663 SourceEnum != TargetEnum) {
13664 if (SourceMgr.isInSystemMacro(CC))
13665 return;
13666
13667 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13668 diag::warn_impcast_different_enum_types);
13669 }
13670}
13671
13673 SourceLocation CC, QualType T);
13674
13676 SourceLocation CC, bool &ICContext) {
13677 E = E->IgnoreParenImpCasts();
13678 // Diagnose incomplete type for second or third operand in C.
13679 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13680 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13681
13682 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13683 return CheckConditionalOperator(S, CO, CC, T);
13684
13686 if (E->getType() != T)
13687 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13688}
13689
13691 SourceLocation CC, QualType T) {
13693
13694 Expr *TrueExpr = E->getTrueExpr();
13695 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13696 TrueExpr = BCO->getCommon();
13697
13698 bool Suspicious = false;
13699 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13700 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13701
13702 if (T->isBooleanType())
13704
13705 // If -Wconversion would have warned about either of the candidates
13706 // for a signedness conversion to the context type...
13707 if (!Suspicious) return;
13708
13709 // ...but it's currently ignored...
13710 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13711 return;
13712
13713 // ...then check whether it would have warned about either of the
13714 // candidates for a signedness conversion to the condition type.
13715 if (E->getType() == T) return;
13716
13717 Suspicious = false;
13718 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13719 &Suspicious);
13720 if (!Suspicious)
13722 E->getType(), CC, &Suspicious);
13723}
13724
13725/// Check conversion of given expression to boolean.
13726/// Input argument E is a logical expression.
13728 // Run the bool-like conversion checks only for C since there bools are
13729 // still not used as the return type from "boolean" operators or as the input
13730 // type for conditional operators.
13731 if (S.getLangOpts().CPlusPlus)
13732 return;
13734 return;
13736}
13737
13738namespace {
13739struct AnalyzeImplicitConversionsWorkItem {
13740 Expr *E;
13741 SourceLocation CC;
13742 bool IsListInit;
13743};
13744}
13745
13747 Sema &S, Expr *E, QualType T, SourceLocation CC,
13748 bool ExtraCheckForImplicitConversion,
13750 E = E->IgnoreParenImpCasts();
13751 WorkList.push_back({E, CC, false});
13752
13753 if (ExtraCheckForImplicitConversion && E->getType() != T)
13754 S.CheckImplicitConversion(E, T, CC);
13755}
13756
13757/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13758/// that should be visited are added to WorkList.
13760 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13762 Expr *OrigE = Item.E;
13763 SourceLocation CC = Item.CC;
13764
13765 QualType T = OrigE->getType();
13766 Expr *E = OrigE->IgnoreParenImpCasts();
13767
13768 // Propagate whether we are in a C++ list initialization expression.
13769 // If so, we do not issue warnings for implicit int-float conversion
13770 // precision loss, because C++11 narrowing already handles it.
13771 //
13772 // HLSL's initialization lists are special, so they shouldn't observe the C++
13773 // behavior here.
13774 bool IsListInit =
13775 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13776 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13777
13778 if (E->isTypeDependent() || E->isValueDependent())
13779 return;
13780
13781 Expr *SourceExpr = E;
13782 // Examine, but don't traverse into the source expression of an
13783 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13784 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13785 // evaluate it in the context of checking the specific conversion to T though.
13786 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13787 if (auto *Src = OVE->getSourceExpr())
13788 SourceExpr = Src;
13789
13790 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13791 if (UO->getOpcode() == UO_Not &&
13792 UO->getSubExpr()->isKnownToHaveBooleanValue())
13793 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13794 << OrigE->getSourceRange() << T->isBooleanType()
13795 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13796
13797 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13798 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13799 BO->getLHS()->isKnownToHaveBooleanValue() &&
13800 BO->getRHS()->isKnownToHaveBooleanValue() &&
13801 BO->getLHS()->HasSideEffects(S.Context) &&
13802 BO->getRHS()->HasSideEffects(S.Context)) {
13804 const LangOptions &LO = S.getLangOpts();
13805 SourceLocation BLoc = BO->getOperatorLoc();
13806 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13807 StringRef SR = clang::Lexer::getSourceText(
13808 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13809 // To reduce false positives, only issue the diagnostic if the operator
13810 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13811 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13812 // in C, along with other macro spellings the user might invent.
13813 if (SR.str() == "&" || SR.str() == "|") {
13814
13815 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13816 << (BO->getOpcode() == BO_And ? "&" : "|")
13817 << OrigE->getSourceRange()
13819 BO->getOperatorLoc(),
13820 (BO->getOpcode() == BO_And ? "&&" : "||"));
13821 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13822 }
13823 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13824 /// Analyze the given comma operator. The basic idea behind the analysis
13825 /// is to analyze the left and right operands slightly differently. The
13826 /// left operand needs to check whether the operand itself has an implicit
13827 /// conversion, but not whether the left operand induces an implicit
13828 /// conversion for the entire comma expression itself. This is similar to
13829 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13830 /// were directly used for the implicit conversion check.
13831 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13832 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13833 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13834 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13835 return;
13836 }
13837 }
13838
13839 // For conditional operators, we analyze the arguments as if they
13840 // were being fed directly into the output.
13841 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13842 CheckConditionalOperator(S, CO, CC, T);
13843 return;
13844 }
13845
13846 // Check implicit argument conversions for function calls.
13847 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13849
13850 // Go ahead and check any implicit conversions we might have skipped.
13851 // The non-canonical typecheck is just an optimization;
13852 // CheckImplicitConversion will filter out dead implicit conversions.
13853 if (SourceExpr->getType() != T)
13854 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13855
13856 // Now continue drilling into this expression.
13857
13858 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13859 // The bound subexpressions in a PseudoObjectExpr are not reachable
13860 // as transitive children.
13861 // FIXME: Use a more uniform representation for this.
13862 for (auto *SE : POE->semantics())
13863 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13864 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13865 }
13866
13867 // Skip past explicit casts.
13868 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13869 E = CE->getSubExpr();
13870 // In the special case of a C++ function-style cast with braces,
13871 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13872 // initializer. This InitListExpr basically belongs to the cast itself, so
13873 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13875 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13876 if (InitListE->getNumInits() == 1) {
13877 E = InitListE->getInit(0);
13878 }
13879 }
13880 }
13881 E = E->IgnoreParenImpCasts();
13882 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13883 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13884 WorkList.push_back({E, CC, IsListInit});
13885 return;
13886 }
13887
13888 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13889 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13890 // The base expression is only used to initialize the parameter for
13891 // arguments to `inout` parameters, so we only traverse down the base
13892 // expression for `inout` cases.
13893 if (OutArgE->isInOut())
13894 WorkList.push_back(
13895 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13896 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13897 return;
13898 }
13899
13900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13901 // Do a somewhat different check with comparison operators.
13902 if (BO->isComparisonOp())
13903 return AnalyzeComparison(S, BO);
13904
13905 // And with simple assignments.
13906 if (BO->getOpcode() == BO_Assign)
13907 return AnalyzeAssignment(S, BO);
13908 // And with compound assignments.
13909 if (BO->isAssignmentOp())
13910 return AnalyzeCompoundAssignment(S, BO);
13911 }
13912
13913 // These break the otherwise-useful invariant below. Fortunately,
13914 // we don't really need to recurse into them, because any internal
13915 // expressions should have been analyzed already when they were
13916 // built into statements.
13917 if (isa<StmtExpr>(E)) return;
13918
13919 // Don't descend into unevaluated contexts.
13920 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13921
13922 // Now just recurse over the expression's children.
13923 CC = E->getExprLoc();
13924 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13925 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13926 for (Stmt *SubStmt : E->children()) {
13927 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13928 if (!ChildExpr)
13929 continue;
13930
13931 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13932 if (ChildExpr == CSE->getOperand())
13933 // Do not recurse over a CoroutineSuspendExpr's operand.
13934 // The operand is also a subexpression of getCommonExpr(), and
13935 // recursing into it directly would produce duplicate diagnostics.
13936 continue;
13937
13938 if (IsLogicalAndOperator &&
13940 // Ignore checking string literals that are in logical and operators.
13941 // This is a common pattern for asserts.
13942 continue;
13943 WorkList.push_back({ChildExpr, CC, IsListInit});
13944 }
13945
13946 if (BO && BO->isLogicalOp()) {
13947 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13948 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13949 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13950
13951 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13952 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13953 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13954 }
13955
13956 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13957 if (U->getOpcode() == UO_LNot) {
13958 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13959 } else if (U->getOpcode() != UO_AddrOf) {
13960 if (U->getSubExpr()->getType()->isAtomicType())
13961 S.Diag(U->getSubExpr()->getBeginLoc(),
13962 diag::warn_atomic_implicit_seq_cst);
13963 }
13964 }
13965}
13966
13967/// AnalyzeImplicitConversions - Find and report any interesting
13968/// implicit conversions in the given expression. There are a couple
13969/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13971 bool IsListInit/*= false*/) {
13973 WorkList.push_back({OrigE, CC, IsListInit});
13974 while (!WorkList.empty())
13975 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13976}
13977
13978// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13979// Returns true when emitting a warning about taking the address of a reference.
13980static bool CheckForReference(Sema &SemaRef, const Expr *E,
13981 const PartialDiagnostic &PD) {
13982 E = E->IgnoreParenImpCasts();
13983
13984 const FunctionDecl *FD = nullptr;
13985
13986 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13987 if (!DRE->getDecl()->getType()->isReferenceType())
13988 return false;
13989 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13990 if (!M->getMemberDecl()->getType()->isReferenceType())
13991 return false;
13992 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13993 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13994 return false;
13995 FD = Call->getDirectCallee();
13996 } else {
13997 return false;
13998 }
13999
14000 SemaRef.Diag(E->getExprLoc(), PD);
14001
14002 // If possible, point to location of function.
14003 if (FD) {
14004 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14005 }
14006
14007 return true;
14008}
14009
14010// Returns true if the SourceLocation is expanded from any macro body.
14011// Returns false if the SourceLocation is invalid, is from not in a macro
14012// expansion, or is from expanded from a top-level macro argument.
14014 if (Loc.isInvalid())
14015 return false;
14016
14017 while (Loc.isMacroID()) {
14018 if (SM.isMacroBodyExpansion(Loc))
14019 return true;
14020 Loc = SM.getImmediateMacroCallerLoc(Loc);
14021 }
14022
14023 return false;
14024}
14025
14028 bool IsEqual, SourceRange Range) {
14029 if (!E)
14030 return;
14031
14032 // Don't warn inside macros.
14033 if (E->getExprLoc().isMacroID()) {
14035 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14036 IsInAnyMacroBody(SM, Range.getBegin()))
14037 return;
14038 }
14039 E = E->IgnoreImpCasts();
14040
14041 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14042
14043 if (isa<CXXThisExpr>(E)) {
14044 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14045 : diag::warn_this_bool_conversion;
14046 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14047 return;
14048 }
14049
14050 bool IsAddressOf = false;
14051
14052 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14053 if (UO->getOpcode() != UO_AddrOf)
14054 return;
14055 IsAddressOf = true;
14056 E = UO->getSubExpr();
14057 }
14058
14059 if (IsAddressOf) {
14060 unsigned DiagID = IsCompare
14061 ? diag::warn_address_of_reference_null_compare
14062 : diag::warn_address_of_reference_bool_conversion;
14063 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14064 << IsEqual;
14065 if (CheckForReference(*this, E, PD)) {
14066 return;
14067 }
14068 }
14069
14070 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14071 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14072 std::string Str;
14073 llvm::raw_string_ostream S(Str);
14074 E->printPretty(S, nullptr, getPrintingPolicy());
14075 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14076 : diag::warn_cast_nonnull_to_bool;
14077 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14078 << E->getSourceRange() << Range << IsEqual;
14079 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14080 };
14081
14082 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14083 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14084 if (auto *Callee = Call->getDirectCallee()) {
14085 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14086 ComplainAboutNonnullParamOrCall(A);
14087 return;
14088 }
14089 }
14090 }
14091
14092 // Complain if we are converting a lambda expression to a boolean value
14093 // outside of instantiation.
14094 if (!inTemplateInstantiation()) {
14095 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14096 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14097 MRecordDecl && MRecordDecl->isLambda()) {
14098 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14099 << /*LambdaPointerConversionOperatorType=*/3
14100 << MRecordDecl->getSourceRange() << Range << IsEqual;
14101 return;
14102 }
14103 }
14104 }
14105
14106 // Expect to find a single Decl. Skip anything more complicated.
14107 ValueDecl *D = nullptr;
14108 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14109 D = R->getDecl();
14110 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14111 D = M->getMemberDecl();
14112 }
14113
14114 // Weak Decls can be null.
14115 if (!D || D->isWeak())
14116 return;
14117
14118 // Check for parameter decl with nonnull attribute
14119 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14120 if (getCurFunction() &&
14121 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14122 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14123 ComplainAboutNonnullParamOrCall(A);
14124 return;
14125 }
14126
14127 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14128 // Skip function template not specialized yet.
14130 return;
14131 auto ParamIter = llvm::find(FD->parameters(), PV);
14132 assert(ParamIter != FD->param_end());
14133 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14134
14135 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14136 if (!NonNull->args_size()) {
14137 ComplainAboutNonnullParamOrCall(NonNull);
14138 return;
14139 }
14140
14141 for (const ParamIdx &ArgNo : NonNull->args()) {
14142 if (ArgNo.getASTIndex() == ParamNo) {
14143 ComplainAboutNonnullParamOrCall(NonNull);
14144 return;
14145 }
14146 }
14147 }
14148 }
14149 }
14150 }
14151
14152 QualType T = D->getType();
14153 const bool IsArray = T->isArrayType();
14154 const bool IsFunction = T->isFunctionType();
14155
14156 // Address of function is used to silence the function warning.
14157 if (IsAddressOf && IsFunction) {
14158 return;
14159 }
14160
14161 // Found nothing.
14162 if (!IsAddressOf && !IsFunction && !IsArray)
14163 return;
14164
14165 // Pretty print the expression for the diagnostic.
14166 std::string Str;
14167 llvm::raw_string_ostream S(Str);
14168 E->printPretty(S, nullptr, getPrintingPolicy());
14169
14170 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14171 : diag::warn_impcast_pointer_to_bool;
14172 enum {
14173 AddressOf,
14174 FunctionPointer,
14175 ArrayPointer
14176 } DiagType;
14177 if (IsAddressOf)
14178 DiagType = AddressOf;
14179 else if (IsFunction)
14180 DiagType = FunctionPointer;
14181 else if (IsArray)
14182 DiagType = ArrayPointer;
14183 else
14184 llvm_unreachable("Could not determine diagnostic.");
14185 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14186 << Range << IsEqual;
14187
14188 if (!IsFunction)
14189 return;
14190
14191 // Suggest '&' to silence the function warning.
14192 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14194
14195 // Check to see if '()' fixit should be emitted.
14196 QualType ReturnType;
14197 UnresolvedSet<4> NonTemplateOverloads;
14198 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14199 if (ReturnType.isNull())
14200 return;
14201
14202 if (IsCompare) {
14203 // There are two cases here. If there is null constant, the only suggest
14204 // for a pointer return type. If the null is 0, then suggest if the return
14205 // type is a pointer or an integer type.
14206 if (!ReturnType->isPointerType()) {
14207 if (NullKind == Expr::NPCK_ZeroExpression ||
14208 NullKind == Expr::NPCK_ZeroLiteral) {
14209 if (!ReturnType->isIntegerType())
14210 return;
14211 } else {
14212 return;
14213 }
14214 }
14215 } else { // !IsCompare
14216 // For function to bool, only suggest if the function pointer has bool
14217 // return type.
14218 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14219 return;
14220 }
14221 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14223}
14224
14226 SourceLocation CC) {
14227 QualType Source = E->getType();
14228 QualType Target = T;
14229
14230 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14231 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14232 // Overflow behavior type is being stripped - issue warning
14233 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14234 Target->isUnsignedIntegerType()) {
14235 // For unsigned wrap to unsigned conversions, use pedantic version
14236 unsigned DiagId =
14238 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14239 : diag::warn_impcast_overflow_behavior_pedantic;
14240 DiagnoseImpCast(*this, E, T, CC, DiagId);
14241 } else {
14242 unsigned DiagId = InOverflowBehaviorAssignmentContext
14243 ? diag::warn_impcast_overflow_behavior_assignment
14244 : diag::warn_impcast_overflow_behavior;
14245 DiagnoseImpCast(*this, E, T, CC, DiagId);
14246 }
14247 }
14248 }
14249
14250 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14251 if (TargetOBT->isWrapKind()) {
14252 return true;
14253 }
14254 }
14255
14256 return false;
14257}
14258
14259void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14260 // Don't diagnose in unevaluated contexts.
14262 return;
14263
14264 // Don't diagnose for value- or type-dependent expressions.
14265 if (E->isTypeDependent() || E->isValueDependent())
14266 return;
14267
14268 // Check for array bounds violations in cases where the check isn't triggered
14269 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14270 // ArraySubscriptExpr is on the RHS of a variable initialization.
14271 CheckArrayAccess(E);
14272
14273 // This is not the right CC for (e.g.) a variable initialization.
14274 AnalyzeImplicitConversions(*this, E, CC);
14275}
14276
14277void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14278 ::CheckBoolLikeConversion(*this, E, CC);
14279}
14280
14281void Sema::CheckForIntOverflow (const Expr *E) {
14282 // Use a work list to deal with nested struct initializers.
14283 SmallVector<const Expr *, 2> Exprs(1, E);
14284
14285 do {
14286 const Expr *OriginalE = Exprs.pop_back_val();
14287 const Expr *E = OriginalE->IgnoreParenCasts();
14288
14291 continue;
14292 }
14293
14294 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14295 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14296 else if (isa<ObjCBoxedExpr>(OriginalE))
14298 else if (const auto *Call = dyn_cast<CallExpr>(E))
14299 Exprs.append(Call->arg_begin(), Call->arg_end());
14300 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14301 Exprs.append(Message->arg_begin(), Message->arg_end());
14302 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14303 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14304 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14305 Exprs.push_back(Temporary->getSubExpr());
14306 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14307 Exprs.push_back(Array->getIdx());
14308 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14309 Exprs.push_back(Compound->getInitializer());
14310 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14311 New && New->isArray()) {
14312 if (auto ArraySize = New->getArraySize())
14313 Exprs.push_back(*ArraySize);
14314 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14315 Exprs.push_back(MTE->getSubExpr());
14316 } while (!Exprs.empty());
14317}
14318
14319namespace {
14320
14321/// Visitor for expressions which looks for unsequenced operations on the
14322/// same object.
14323class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14324 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14325
14326 /// A tree of sequenced regions within an expression. Two regions are
14327 /// unsequenced if one is an ancestor or a descendent of the other. When we
14328 /// finish processing an expression with sequencing, such as a comma
14329 /// expression, we fold its tree nodes into its parent, since they are
14330 /// unsequenced with respect to nodes we will visit later.
14331 class SequenceTree {
14332 struct Value {
14333 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14334 unsigned Parent : 31;
14335 LLVM_PREFERRED_TYPE(bool)
14336 unsigned Merged : 1;
14337 };
14338 SmallVector<Value, 8> Values;
14339
14340 public:
14341 /// A region within an expression which may be sequenced with respect
14342 /// to some other region.
14343 class Seq {
14344 friend class SequenceTree;
14345
14346 unsigned Index;
14347
14348 explicit Seq(unsigned N) : Index(N) {}
14349
14350 public:
14351 Seq() : Index(0) {}
14352 };
14353
14354 SequenceTree() { Values.push_back(Value(0)); }
14355 Seq root() const { return Seq(0); }
14356
14357 /// Create a new sequence of operations, which is an unsequenced
14358 /// subset of \p Parent. This sequence of operations is sequenced with
14359 /// respect to other children of \p Parent.
14360 Seq allocate(Seq Parent) {
14361 Values.push_back(Value(Parent.Index));
14362 return Seq(Values.size() - 1);
14363 }
14364
14365 /// Merge a sequence of operations into its parent.
14366 void merge(Seq S) {
14367 Values[S.Index].Merged = true;
14368 }
14369
14370 /// Determine whether two operations are unsequenced. This operation
14371 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14372 /// should have been merged into its parent as appropriate.
14373 bool isUnsequenced(Seq Cur, Seq Old) {
14374 unsigned C = representative(Cur.Index);
14375 unsigned Target = representative(Old.Index);
14376 while (C >= Target) {
14377 if (C == Target)
14378 return true;
14379 C = Values[C].Parent;
14380 }
14381 return false;
14382 }
14383
14384 private:
14385 /// Pick a representative for a sequence.
14386 unsigned representative(unsigned K) {
14387 if (Values[K].Merged)
14388 // Perform path compression as we go.
14389 return Values[K].Parent = representative(Values[K].Parent);
14390 return K;
14391 }
14392 };
14393
14394 /// An object for which we can track unsequenced uses.
14395 using Object = const NamedDecl *;
14396
14397 /// Different flavors of object usage which we track. We only track the
14398 /// least-sequenced usage of each kind.
14399 enum UsageKind {
14400 /// A read of an object. Multiple unsequenced reads are OK.
14401 UK_Use,
14402
14403 /// A modification of an object which is sequenced before the value
14404 /// computation of the expression, such as ++n in C++.
14405 UK_ModAsValue,
14406
14407 /// A modification of an object which is not sequenced before the value
14408 /// computation of the expression, such as n++.
14409 UK_ModAsSideEffect,
14410
14411 UK_Count = UK_ModAsSideEffect + 1
14412 };
14413
14414 /// Bundle together a sequencing region and the expression corresponding
14415 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14416 struct Usage {
14417 const Expr *UsageExpr = nullptr;
14418 SequenceTree::Seq Seq;
14419
14420 Usage() = default;
14421 };
14422
14423 struct UsageInfo {
14424 Usage Uses[UK_Count];
14425
14426 /// Have we issued a diagnostic for this object already?
14427 bool Diagnosed = false;
14428
14429 UsageInfo();
14430 };
14431 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14432
14433 Sema &SemaRef;
14434
14435 /// Sequenced regions within the expression.
14436 SequenceTree Tree;
14437
14438 /// Declaration modifications and references which we have seen.
14439 UsageInfoMap UsageMap;
14440
14441 /// The region we are currently within.
14442 SequenceTree::Seq Region;
14443
14444 /// Filled in with declarations which were modified as a side-effect
14445 /// (that is, post-increment operations).
14446 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14447
14448 /// Expressions to check later. We defer checking these to reduce
14449 /// stack usage.
14450 SmallVectorImpl<const Expr *> &WorkList;
14451
14452 /// RAII object wrapping the visitation of a sequenced subexpression of an
14453 /// expression. At the end of this process, the side-effects of the evaluation
14454 /// become sequenced with respect to the value computation of the result, so
14455 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14456 /// UK_ModAsValue.
14457 struct SequencedSubexpression {
14458 SequencedSubexpression(SequenceChecker &Self)
14459 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14460 Self.ModAsSideEffect = &ModAsSideEffect;
14461 }
14462
14463 ~SequencedSubexpression() {
14464 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14465 // Add a new usage with usage kind UK_ModAsValue, and then restore
14466 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14467 // the previous one was empty).
14468 UsageInfo &UI = Self.UsageMap[M.first];
14469 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14470 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14471 SideEffectUsage = M.second;
14472 }
14473 Self.ModAsSideEffect = OldModAsSideEffect;
14474 }
14475
14476 SequenceChecker &Self;
14477 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14478 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14479 };
14480
14481 /// RAII object wrapping the visitation of a subexpression which we might
14482 /// choose to evaluate as a constant. If any subexpression is evaluated and
14483 /// found to be non-constant, this allows us to suppress the evaluation of
14484 /// the outer expression.
14485 class EvaluationTracker {
14486 public:
14487 EvaluationTracker(SequenceChecker &Self)
14488 : Self(Self), Prev(Self.EvalTracker) {
14489 Self.EvalTracker = this;
14490 }
14491
14492 ~EvaluationTracker() {
14493 Self.EvalTracker = Prev;
14494 if (Prev)
14495 Prev->EvalOK &= EvalOK;
14496 }
14497
14498 bool evaluate(const Expr *E, bool &Result) {
14499 if (!EvalOK || E->isValueDependent())
14500 return false;
14501 EvalOK = E->EvaluateAsBooleanCondition(
14502 Result, Self.SemaRef.Context,
14503 Self.SemaRef.isConstantEvaluatedContext());
14504 return EvalOK;
14505 }
14506
14507 private:
14508 SequenceChecker &Self;
14509 EvaluationTracker *Prev;
14510 bool EvalOK = true;
14511 } *EvalTracker = nullptr;
14512
14513 /// Find the object which is produced by the specified expression,
14514 /// if any.
14515 Object getObject(const Expr *E, bool Mod) const {
14516 E = E->IgnoreParenCasts();
14517 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14518 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14519 return getObject(UO->getSubExpr(), Mod);
14520 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14521 if (BO->getOpcode() == BO_Comma)
14522 return getObject(BO->getRHS(), Mod);
14523 if (Mod && BO->isAssignmentOp())
14524 return getObject(BO->getLHS(), Mod);
14525 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14526 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14527 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14528 return ME->getMemberDecl();
14529 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14530 // FIXME: If this is a reference, map through to its value.
14531 return DRE->getDecl();
14532 return nullptr;
14533 }
14534
14535 /// Note that an object \p O was modified or used by an expression
14536 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14537 /// the object \p O as obtained via the \p UsageMap.
14538 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14539 // Get the old usage for the given object and usage kind.
14540 Usage &U = UI.Uses[UK];
14541 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14542 // If we have a modification as side effect and are in a sequenced
14543 // subexpression, save the old Usage so that we can restore it later
14544 // in SequencedSubexpression::~SequencedSubexpression.
14545 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14546 ModAsSideEffect->push_back(std::make_pair(O, U));
14547 // Then record the new usage with the current sequencing region.
14548 U.UsageExpr = UsageExpr;
14549 U.Seq = Region;
14550 }
14551 }
14552
14553 /// Check whether a modification or use of an object \p O in an expression
14554 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14555 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14556 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14557 /// usage and false we are checking for a mod-use unsequenced usage.
14558 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14559 UsageKind OtherKind, bool IsModMod) {
14560 if (UI.Diagnosed)
14561 return;
14562
14563 const Usage &U = UI.Uses[OtherKind];
14564 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14565 return;
14566
14567 const Expr *Mod = U.UsageExpr;
14568 const Expr *ModOrUse = UsageExpr;
14569 if (OtherKind == UK_Use)
14570 std::swap(Mod, ModOrUse);
14571
14572 SemaRef.DiagRuntimeBehavior(
14573 Mod->getExprLoc(), {Mod, ModOrUse},
14574 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14575 : diag::warn_unsequenced_mod_use)
14576 << O << SourceRange(ModOrUse->getExprLoc()));
14577 UI.Diagnosed = true;
14578 }
14579
14580 // A note on note{Pre, Post}{Use, Mod}:
14581 //
14582 // (It helps to follow the algorithm with an expression such as
14583 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14584 // operations before C++17 and both are well-defined in C++17).
14585 //
14586 // When visiting a node which uses/modify an object we first call notePreUse
14587 // or notePreMod before visiting its sub-expression(s). At this point the
14588 // children of the current node have not yet been visited and so the eventual
14589 // uses/modifications resulting from the children of the current node have not
14590 // been recorded yet.
14591 //
14592 // We then visit the children of the current node. After that notePostUse or
14593 // notePostMod is called. These will 1) detect an unsequenced modification
14594 // as side effect (as in "k++ + k") and 2) add a new usage with the
14595 // appropriate usage kind.
14596 //
14597 // We also have to be careful that some operation sequences modification as
14598 // side effect as well (for example: || or ,). To account for this we wrap
14599 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14600 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14601 // which record usages which are modifications as side effect, and then
14602 // downgrade them (or more accurately restore the previous usage which was a
14603 // modification as side effect) when exiting the scope of the sequenced
14604 // subexpression.
14605
14606 void notePreUse(Object O, const Expr *UseExpr) {
14607 UsageInfo &UI = UsageMap[O];
14608 // Uses conflict with other modifications.
14609 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14610 }
14611
14612 void notePostUse(Object O, const Expr *UseExpr) {
14613 UsageInfo &UI = UsageMap[O];
14614 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14615 /*IsModMod=*/false);
14616 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14617 }
14618
14619 void notePreMod(Object O, const Expr *ModExpr) {
14620 UsageInfo &UI = UsageMap[O];
14621 // Modifications conflict with other modifications and with uses.
14622 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14623 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14624 }
14625
14626 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14627 UsageInfo &UI = UsageMap[O];
14628 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14629 /*IsModMod=*/true);
14630 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14631 }
14632
14633public:
14634 SequenceChecker(Sema &S, const Expr *E,
14635 SmallVectorImpl<const Expr *> &WorkList)
14636 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14637 Visit(E);
14638 // Silence a -Wunused-private-field since WorkList is now unused.
14639 // TODO: Evaluate if it can be used, and if not remove it.
14640 (void)this->WorkList;
14641 }
14642
14643 void VisitStmt(const Stmt *S) {
14644 // Skip all statements which aren't expressions for now.
14645 }
14646
14647 void VisitExpr(const Expr *E) {
14648 // By default, just recurse to evaluated subexpressions.
14649 Base::VisitStmt(E);
14650 }
14651
14652 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14653 for (auto *Sub : CSE->children()) {
14654 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14655 if (!ChildExpr)
14656 continue;
14657
14658 if (ChildExpr == CSE->getOperand())
14659 // Do not recurse over a CoroutineSuspendExpr's operand.
14660 // The operand is also a subexpression of getCommonExpr(), and
14661 // recursing into it directly could confuse object management
14662 // for the sake of sequence tracking.
14663 continue;
14664
14665 Visit(Sub);
14666 }
14667 }
14668
14669 void VisitCastExpr(const CastExpr *E) {
14670 Object O = Object();
14671 if (E->getCastKind() == CK_LValueToRValue)
14672 O = getObject(E->getSubExpr(), false);
14673
14674 if (O)
14675 notePreUse(O, E);
14676 VisitExpr(E);
14677 if (O)
14678 notePostUse(O, E);
14679 }
14680
14681 void VisitSequencedExpressions(const Expr *SequencedBefore,
14682 const Expr *SequencedAfter) {
14683 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14684 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14685 SequenceTree::Seq OldRegion = Region;
14686
14687 {
14688 SequencedSubexpression SeqBefore(*this);
14689 Region = BeforeRegion;
14690 Visit(SequencedBefore);
14691 }
14692
14693 Region = AfterRegion;
14694 Visit(SequencedAfter);
14695
14696 Region = OldRegion;
14697
14698 Tree.merge(BeforeRegion);
14699 Tree.merge(AfterRegion);
14700 }
14701
14702 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14703 // C++17 [expr.sub]p1:
14704 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14705 // expression E1 is sequenced before the expression E2.
14706 if (SemaRef.getLangOpts().CPlusPlus17)
14707 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14708 else {
14709 Visit(ASE->getLHS());
14710 Visit(ASE->getRHS());
14711 }
14712 }
14713
14714 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14715 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14716 void VisitBinPtrMem(const BinaryOperator *BO) {
14717 // C++17 [expr.mptr.oper]p4:
14718 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14719 // the expression E1 is sequenced before the expression E2.
14720 if (SemaRef.getLangOpts().CPlusPlus17)
14721 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14722 else {
14723 Visit(BO->getLHS());
14724 Visit(BO->getRHS());
14725 }
14726 }
14727
14728 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14729 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14730 void VisitBinShlShr(const BinaryOperator *BO) {
14731 // C++17 [expr.shift]p4:
14732 // The expression E1 is sequenced before the expression E2.
14733 if (SemaRef.getLangOpts().CPlusPlus17)
14734 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14735 else {
14736 Visit(BO->getLHS());
14737 Visit(BO->getRHS());
14738 }
14739 }
14740
14741 void VisitBinComma(const BinaryOperator *BO) {
14742 // C++11 [expr.comma]p1:
14743 // Every value computation and side effect associated with the left
14744 // expression is sequenced before every value computation and side
14745 // effect associated with the right expression.
14746 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14747 }
14748
14749 void VisitBinAssign(const BinaryOperator *BO) {
14750 SequenceTree::Seq RHSRegion;
14751 SequenceTree::Seq LHSRegion;
14752 if (SemaRef.getLangOpts().CPlusPlus17) {
14753 RHSRegion = Tree.allocate(Region);
14754 LHSRegion = Tree.allocate(Region);
14755 } else {
14756 RHSRegion = Region;
14757 LHSRegion = Region;
14758 }
14759 SequenceTree::Seq OldRegion = Region;
14760
14761 // C++11 [expr.ass]p1:
14762 // [...] the assignment is sequenced after the value computation
14763 // of the right and left operands, [...]
14764 //
14765 // so check it before inspecting the operands and update the
14766 // map afterwards.
14767 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14768 if (O)
14769 notePreMod(O, BO);
14770
14771 if (SemaRef.getLangOpts().CPlusPlus17) {
14772 // C++17 [expr.ass]p1:
14773 // [...] The right operand is sequenced before the left operand. [...]
14774 {
14775 SequencedSubexpression SeqBefore(*this);
14776 Region = RHSRegion;
14777 Visit(BO->getRHS());
14778 }
14779
14780 Region = LHSRegion;
14781 Visit(BO->getLHS());
14782
14783 if (O && isa<CompoundAssignOperator>(BO))
14784 notePostUse(O, BO);
14785
14786 } else {
14787 // C++11 does not specify any sequencing between the LHS and RHS.
14788 Region = LHSRegion;
14789 Visit(BO->getLHS());
14790
14791 if (O && isa<CompoundAssignOperator>(BO))
14792 notePostUse(O, BO);
14793
14794 Region = RHSRegion;
14795 Visit(BO->getRHS());
14796 }
14797
14798 // C++11 [expr.ass]p1:
14799 // the assignment is sequenced [...] before the value computation of the
14800 // assignment expression.
14801 // C11 6.5.16/3 has no such rule.
14802 Region = OldRegion;
14803 if (O)
14804 notePostMod(O, BO,
14805 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14806 : UK_ModAsSideEffect);
14807 if (SemaRef.getLangOpts().CPlusPlus17) {
14808 Tree.merge(RHSRegion);
14809 Tree.merge(LHSRegion);
14810 }
14811 }
14812
14813 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14814 VisitBinAssign(CAO);
14815 }
14816
14817 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14818 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14819 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14820 Object O = getObject(UO->getSubExpr(), true);
14821 if (!O)
14822 return VisitExpr(UO);
14823
14824 notePreMod(O, UO);
14825 Visit(UO->getSubExpr());
14826 // C++11 [expr.pre.incr]p1:
14827 // the expression ++x is equivalent to x+=1
14828 notePostMod(O, UO,
14829 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14830 : UK_ModAsSideEffect);
14831 }
14832
14833 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14834 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14835 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14836 Object O = getObject(UO->getSubExpr(), true);
14837 if (!O)
14838 return VisitExpr(UO);
14839
14840 notePreMod(O, UO);
14841 Visit(UO->getSubExpr());
14842 notePostMod(O, UO, UK_ModAsSideEffect);
14843 }
14844
14845 void VisitBinLOr(const BinaryOperator *BO) {
14846 // C++11 [expr.log.or]p2:
14847 // If the second expression is evaluated, every value computation and
14848 // side effect associated with the first expression is sequenced before
14849 // every value computation and side effect associated with the
14850 // second expression.
14851 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14852 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14853 SequenceTree::Seq OldRegion = Region;
14854
14855 EvaluationTracker Eval(*this);
14856 {
14857 SequencedSubexpression Sequenced(*this);
14858 Region = LHSRegion;
14859 Visit(BO->getLHS());
14860 }
14861
14862 // C++11 [expr.log.or]p1:
14863 // [...] the second operand is not evaluated if the first operand
14864 // evaluates to true.
14865 bool EvalResult = false;
14866 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14867 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14868 if (ShouldVisitRHS) {
14869 Region = RHSRegion;
14870 Visit(BO->getRHS());
14871 }
14872
14873 Region = OldRegion;
14874 Tree.merge(LHSRegion);
14875 Tree.merge(RHSRegion);
14876 }
14877
14878 void VisitBinLAnd(const BinaryOperator *BO) {
14879 // C++11 [expr.log.and]p2:
14880 // If the second expression is evaluated, every value computation and
14881 // side effect associated with the first expression is sequenced before
14882 // every value computation and side effect associated with the
14883 // second expression.
14884 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14885 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14886 SequenceTree::Seq OldRegion = Region;
14887
14888 EvaluationTracker Eval(*this);
14889 {
14890 SequencedSubexpression Sequenced(*this);
14891 Region = LHSRegion;
14892 Visit(BO->getLHS());
14893 }
14894
14895 // C++11 [expr.log.and]p1:
14896 // [...] the second operand is not evaluated if the first operand is false.
14897 bool EvalResult = false;
14898 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14899 bool ShouldVisitRHS = !EvalOK || EvalResult;
14900 if (ShouldVisitRHS) {
14901 Region = RHSRegion;
14902 Visit(BO->getRHS());
14903 }
14904
14905 Region = OldRegion;
14906 Tree.merge(LHSRegion);
14907 Tree.merge(RHSRegion);
14908 }
14909
14910 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14911 // C++11 [expr.cond]p1:
14912 // [...] Every value computation and side effect associated with the first
14913 // expression is sequenced before every value computation and side effect
14914 // associated with the second or third expression.
14915 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14916
14917 // No sequencing is specified between the true and false expression.
14918 // However since exactly one of both is going to be evaluated we can
14919 // consider them to be sequenced. This is needed to avoid warning on
14920 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14921 // both the true and false expressions because we can't evaluate x.
14922 // This will still allow us to detect an expression like (pre C++17)
14923 // "(x ? y += 1 : y += 2) = y".
14924 //
14925 // We don't wrap the visitation of the true and false expression with
14926 // SequencedSubexpression because we don't want to downgrade modifications
14927 // as side effect in the true and false expressions after the visition
14928 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14929 // not warn between the two "y++", but we should warn between the "y++"
14930 // and the "y".
14931 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14932 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14933 SequenceTree::Seq OldRegion = Region;
14934
14935 EvaluationTracker Eval(*this);
14936 {
14937 SequencedSubexpression Sequenced(*this);
14938 Region = ConditionRegion;
14939 Visit(CO->getCond());
14940 }
14941
14942 // C++11 [expr.cond]p1:
14943 // [...] The first expression is contextually converted to bool (Clause 4).
14944 // It is evaluated and if it is true, the result of the conditional
14945 // expression is the value of the second expression, otherwise that of the
14946 // third expression. Only one of the second and third expressions is
14947 // evaluated. [...]
14948 bool EvalResult = false;
14949 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14950 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14951 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14952 if (ShouldVisitTrueExpr) {
14953 Region = TrueRegion;
14954 Visit(CO->getTrueExpr());
14955 }
14956 if (ShouldVisitFalseExpr) {
14957 Region = FalseRegion;
14958 Visit(CO->getFalseExpr());
14959 }
14960
14961 Region = OldRegion;
14962 Tree.merge(ConditionRegion);
14963 Tree.merge(TrueRegion);
14964 Tree.merge(FalseRegion);
14965 }
14966
14967 void VisitCallExpr(const CallExpr *CE) {
14968 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14969
14970 if (CE->isUnevaluatedBuiltinCall(Context))
14971 return;
14972
14973 // C++11 [intro.execution]p15:
14974 // When calling a function [...], every value computation and side effect
14975 // associated with any argument expression, or with the postfix expression
14976 // designating the called function, is sequenced before execution of every
14977 // expression or statement in the body of the function [and thus before
14978 // the value computation of its result].
14979 SequencedSubexpression Sequenced(*this);
14980 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14981 // C++17 [expr.call]p5
14982 // The postfix-expression is sequenced before each expression in the
14983 // expression-list and any default argument. [...]
14984 SequenceTree::Seq CalleeRegion;
14985 SequenceTree::Seq OtherRegion;
14986 if (SemaRef.getLangOpts().CPlusPlus17) {
14987 CalleeRegion = Tree.allocate(Region);
14988 OtherRegion = Tree.allocate(Region);
14989 } else {
14990 CalleeRegion = Region;
14991 OtherRegion = Region;
14992 }
14993 SequenceTree::Seq OldRegion = Region;
14994
14995 // Visit the callee expression first.
14996 Region = CalleeRegion;
14997 if (SemaRef.getLangOpts().CPlusPlus17) {
14998 SequencedSubexpression Sequenced(*this);
14999 Visit(CE->getCallee());
15000 } else {
15001 Visit(CE->getCallee());
15002 }
15003
15004 // Then visit the argument expressions.
15005 Region = OtherRegion;
15006 for (const Expr *Argument : CE->arguments())
15007 Visit(Argument);
15008
15009 Region = OldRegion;
15010 if (SemaRef.getLangOpts().CPlusPlus17) {
15011 Tree.merge(CalleeRegion);
15012 Tree.merge(OtherRegion);
15013 }
15014 });
15015 }
15016
15017 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15018 // C++17 [over.match.oper]p2:
15019 // [...] the operator notation is first transformed to the equivalent
15020 // function-call notation as summarized in Table 12 (where @ denotes one
15021 // of the operators covered in the specified subclause). However, the
15022 // operands are sequenced in the order prescribed for the built-in
15023 // operator (Clause 8).
15024 //
15025 // From the above only overloaded binary operators and overloaded call
15026 // operators have sequencing rules in C++17 that we need to handle
15027 // separately.
15028 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15029 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15030 return VisitCallExpr(CXXOCE);
15031
15032 enum {
15033 NoSequencing,
15034 LHSBeforeRHS,
15035 RHSBeforeLHS,
15036 LHSBeforeRest
15037 } SequencingKind;
15038 switch (CXXOCE->getOperator()) {
15039 case OO_Equal:
15040 case OO_PlusEqual:
15041 case OO_MinusEqual:
15042 case OO_StarEqual:
15043 case OO_SlashEqual:
15044 case OO_PercentEqual:
15045 case OO_CaretEqual:
15046 case OO_AmpEqual:
15047 case OO_PipeEqual:
15048 case OO_LessLessEqual:
15049 case OO_GreaterGreaterEqual:
15050 SequencingKind = RHSBeforeLHS;
15051 break;
15052
15053 case OO_LessLess:
15054 case OO_GreaterGreater:
15055 case OO_AmpAmp:
15056 case OO_PipePipe:
15057 case OO_Comma:
15058 case OO_ArrowStar:
15059 case OO_Subscript:
15060 SequencingKind = LHSBeforeRHS;
15061 break;
15062
15063 case OO_Call:
15064 SequencingKind = LHSBeforeRest;
15065 break;
15066
15067 default:
15068 SequencingKind = NoSequencing;
15069 break;
15070 }
15071
15072 if (SequencingKind == NoSequencing)
15073 return VisitCallExpr(CXXOCE);
15074
15075 // This is a call, so all subexpressions are sequenced before the result.
15076 SequencedSubexpression Sequenced(*this);
15077
15078 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15079 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15080 "Should only get there with C++17 and above!");
15081 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15082 "Should only get there with an overloaded binary operator"
15083 " or an overloaded call operator!");
15084
15085 if (SequencingKind == LHSBeforeRest) {
15086 assert(CXXOCE->getOperator() == OO_Call &&
15087 "We should only have an overloaded call operator here!");
15088
15089 // This is very similar to VisitCallExpr, except that we only have the
15090 // C++17 case. The postfix-expression is the first argument of the
15091 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15092 // are in the following arguments.
15093 //
15094 // Note that we intentionally do not visit the callee expression since
15095 // it is just a decayed reference to a function.
15096 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15097 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15098 SequenceTree::Seq OldRegion = Region;
15099
15100 assert(CXXOCE->getNumArgs() >= 1 &&
15101 "An overloaded call operator must have at least one argument"
15102 " for the postfix-expression!");
15103 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15104 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15105 CXXOCE->getNumArgs() - 1);
15106
15107 // Visit the postfix-expression first.
15108 {
15109 Region = PostfixExprRegion;
15110 SequencedSubexpression Sequenced(*this);
15111 Visit(PostfixExpr);
15112 }
15113
15114 // Then visit the argument expressions.
15115 Region = ArgsRegion;
15116 for (const Expr *Arg : Args)
15117 Visit(Arg);
15118
15119 Region = OldRegion;
15120 Tree.merge(PostfixExprRegion);
15121 Tree.merge(ArgsRegion);
15122 } else {
15123 assert(CXXOCE->getNumArgs() == 2 &&
15124 "Should only have two arguments here!");
15125 assert((SequencingKind == LHSBeforeRHS ||
15126 SequencingKind == RHSBeforeLHS) &&
15127 "Unexpected sequencing kind!");
15128
15129 // We do not visit the callee expression since it is just a decayed
15130 // reference to a function.
15131 const Expr *E1 = CXXOCE->getArg(0);
15132 const Expr *E2 = CXXOCE->getArg(1);
15133 if (SequencingKind == RHSBeforeLHS)
15134 std::swap(E1, E2);
15135
15136 return VisitSequencedExpressions(E1, E2);
15137 }
15138 });
15139 }
15140
15141 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15142 // This is a call, so all subexpressions are sequenced before the result.
15143 SequencedSubexpression Sequenced(*this);
15144
15145 if (!CCE->isListInitialization())
15146 return VisitExpr(CCE);
15147
15148 // In C++11, list initializations are sequenced.
15149 SequenceExpressionsInOrder(
15150 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15151 }
15152
15153 void VisitInitListExpr(const InitListExpr *ILE) {
15154 if (!SemaRef.getLangOpts().CPlusPlus11)
15155 return VisitExpr(ILE);
15156
15157 // In C++11, list initializations are sequenced.
15158 SequenceExpressionsInOrder(ILE->inits());
15159 }
15160
15161 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15162 // C++20 parenthesized list initializations are sequenced. See C++20
15163 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15164 SequenceExpressionsInOrder(PLIE->getInitExprs());
15165 }
15166
15167private:
15168 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15170 SequenceTree::Seq Parent = Region;
15171 for (const Expr *E : ExpressionList) {
15172 if (!E)
15173 continue;
15174 Region = Tree.allocate(Parent);
15175 Elts.push_back(Region);
15176 Visit(E);
15177 }
15178
15179 // Forget that the initializers are sequenced.
15180 Region = Parent;
15181 for (unsigned I = 0; I < Elts.size(); ++I)
15182 Tree.merge(Elts[I]);
15183 }
15184};
15185
15186SequenceChecker::UsageInfo::UsageInfo() = default;
15187
15188} // namespace
15189
15190void Sema::CheckUnsequencedOperations(const Expr *E) {
15191 SmallVector<const Expr *, 8> WorkList;
15192 WorkList.push_back(E);
15193 while (!WorkList.empty()) {
15194 const Expr *Item = WorkList.pop_back_val();
15195 SequenceChecker(*this, Item, WorkList);
15196 }
15197}
15198
15199void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15200 bool IsConstexpr) {
15201 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15202 IsConstexpr || isa<ConstantExpr>(E));
15203 CheckImplicitConversions(E, CheckLoc);
15204 if (!E->isInstantiationDependent())
15205 CheckUnsequencedOperations(E);
15206 if (!IsConstexpr && !E->isValueDependent())
15207 CheckForIntOverflow(E);
15208}
15209
15210void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15211 FieldDecl *BitField,
15212 Expr *Init) {
15213 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15214}
15215
15217 SourceLocation Loc) {
15218 if (!PType->isVariablyModifiedType())
15219 return;
15220 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15221 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15222 return;
15223 }
15224 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15225 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15226 return;
15227 }
15228 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15229 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15230 return;
15231 }
15232
15233 const ArrayType *AT = S.Context.getAsArrayType(PType);
15234 if (!AT)
15235 return;
15236
15239 return;
15240 }
15241
15242 S.Diag(Loc, diag::err_array_star_in_function_definition);
15243}
15244
15246 bool CheckParameterNames) {
15247 bool HasInvalidParm = false;
15248 for (ParmVarDecl *Param : Parameters) {
15249 assert(Param && "null in a parameter list");
15250 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15251 // function declarator that is part of a function definition of
15252 // that function shall not have incomplete type.
15253 //
15254 // C++23 [dcl.fct.def.general]/p2
15255 // The type of a parameter [...] for a function definition
15256 // shall not be a (possibly cv-qualified) class type that is incomplete
15257 // or abstract within the function body unless the function is deleted.
15258 if (!Param->isInvalidDecl() &&
15259 (RequireCompleteType(Param->getLocation(), Param->getType(),
15260 diag::err_typecheck_decl_incomplete_type) ||
15261 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15262 diag::err_abstract_type_in_decl,
15264 Param->setInvalidDecl();
15265 HasInvalidParm = true;
15266 }
15267
15268 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15269 // declaration of each parameter shall include an identifier.
15270 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15271 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15272 // Diagnose this as an extension in C17 and earlier.
15273 if (!getLangOpts().C23)
15274 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15275 }
15276
15277 // C99 6.7.5.3p12:
15278 // If the function declarator is not part of a definition of that
15279 // function, parameters may have incomplete type and may use the [*]
15280 // notation in their sequences of declarator specifiers to specify
15281 // variable length array types.
15282 QualType PType = Param->getOriginalType();
15283 // FIXME: This diagnostic should point the '[*]' if source-location
15284 // information is added for it.
15285 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15286
15287 // If the parameter is a c++ class type and it has to be destructed in the
15288 // callee function, declare the destructor so that it can be called by the
15289 // callee function. Do not perform any direct access check on the dtor here.
15290 if (!Param->isInvalidDecl()) {
15291 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15292 if (!ClassDecl->isInvalidDecl() &&
15293 !ClassDecl->hasIrrelevantDestructor() &&
15294 !ClassDecl->isDependentContext() &&
15295 ClassDecl->isParamDestroyedInCallee()) {
15297 MarkFunctionReferenced(Param->getLocation(), Destructor);
15298 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15299 }
15300 }
15301 }
15302
15303 // Parameters with the pass_object_size attribute only need to be marked
15304 // constant at function definitions. Because we lack information about
15305 // whether we're on a declaration or definition when we're instantiating the
15306 // attribute, we need to check for constness here.
15307 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15308 if (!Param->getType().isConstQualified())
15309 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15310 << Attr->getSpelling() << 1;
15311
15312 // Check for parameter names shadowing fields from the class.
15313 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15314 // The owning context for the parameter should be the function, but we
15315 // want to see if this function's declaration context is a record.
15316 DeclContext *DC = Param->getDeclContext();
15317 if (DC && DC->isFunctionOrMethod()) {
15318 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15319 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15320 RD, /*DeclIsField*/ false);
15321 }
15322 }
15323
15324 if (!Param->isInvalidDecl() &&
15325 Param->getOriginalType()->isWebAssemblyTableType()) {
15326 Param->setInvalidDecl();
15327 HasInvalidParm = true;
15328 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15329 }
15330 }
15331
15332 return HasInvalidParm;
15333}
15334
15335std::optional<std::pair<
15337 *E,
15339 &Ctx);
15340
15341/// Compute the alignment and offset of the base class object given the
15342/// derived-to-base cast expression and the alignment and offset of the derived
15343/// class object.
15344static std::pair<CharUnits, CharUnits>
15346 CharUnits BaseAlignment, CharUnits Offset,
15347 ASTContext &Ctx) {
15348 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15349 ++PathI) {
15350 const CXXBaseSpecifier *Base = *PathI;
15351 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15352 if (Base->isVirtual()) {
15353 // The complete object may have a lower alignment than the non-virtual
15354 // alignment of the base, in which case the base may be misaligned. Choose
15355 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15356 // conservative lower bound of the complete object alignment.
15357 CharUnits NonVirtualAlignment =
15359 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15360 Offset = CharUnits::Zero();
15361 } else {
15362 const ASTRecordLayout &RL =
15363 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15364 Offset += RL.getBaseClassOffset(BaseDecl);
15365 }
15366 DerivedType = Base->getType();
15367 }
15368
15369 return std::make_pair(BaseAlignment, Offset);
15370}
15371
15372/// Compute the alignment and offset of a binary additive operator.
15373static std::optional<std::pair<CharUnits, CharUnits>>
15375 bool IsSub, ASTContext &Ctx) {
15376 QualType PointeeType = PtrE->getType()->getPointeeType();
15377
15378 if (!PointeeType->isConstantSizeType())
15379 return std::nullopt;
15380
15381 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15382
15383 if (!P)
15384 return std::nullopt;
15385
15386 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15387 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15388 CharUnits Offset = EltSize * IdxRes->getExtValue();
15389 if (IsSub)
15390 Offset = -Offset;
15391 return std::make_pair(P->first, P->second + Offset);
15392 }
15393
15394 // If the integer expression isn't a constant expression, compute the lower
15395 // bound of the alignment using the alignment and offset of the pointer
15396 // expression and the element size.
15397 return std::make_pair(
15398 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15399 CharUnits::Zero());
15400}
15401
15402/// This helper function takes an lvalue expression and returns the alignment of
15403/// a VarDecl and a constant offset from the VarDecl.
15404std::optional<std::pair<
15405 CharUnits,
15407 ASTContext &Ctx) {
15408 E = E->IgnoreParens();
15409 switch (E->getStmtClass()) {
15410 default:
15411 break;
15412 case Stmt::CStyleCastExprClass:
15413 case Stmt::CXXStaticCastExprClass:
15414 case Stmt::ImplicitCastExprClass: {
15415 auto *CE = cast<CastExpr>(E);
15416 const Expr *From = CE->getSubExpr();
15417 switch (CE->getCastKind()) {
15418 default:
15419 break;
15420 case CK_NoOp:
15421 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15422 case CK_UncheckedDerivedToBase:
15423 case CK_DerivedToBase: {
15424 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15425 if (!P)
15426 break;
15427 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15428 P->second, Ctx);
15429 }
15430 }
15431 break;
15432 }
15433 case Stmt::ArraySubscriptExprClass: {
15434 auto *ASE = cast<ArraySubscriptExpr>(E);
15436 false, Ctx);
15437 }
15438 case Stmt::DeclRefExprClass: {
15439 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15440 // FIXME: If VD is captured by copy or is an escaping __block variable,
15441 // use the alignment of VD's type.
15442 if (!VD->getType()->isReferenceType()) {
15443 // Dependent alignment cannot be resolved -> bail out.
15444 if (VD->hasDependentAlignment())
15445 break;
15446 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15447 }
15448 if (VD->hasInit())
15449 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15450 }
15451 break;
15452 }
15453 case Stmt::MemberExprClass: {
15454 auto *ME = cast<MemberExpr>(E);
15455 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15456 if (!FD || FD->getType()->isReferenceType() ||
15457 FD->getParent()->isInvalidDecl())
15458 break;
15459 std::optional<std::pair<CharUnits, CharUnits>> P;
15460 if (ME->isArrow())
15461 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15462 else
15463 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15464 if (!P)
15465 break;
15466 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15467 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15468 return std::make_pair(P->first,
15469 P->second + CharUnits::fromQuantity(Offset));
15470 }
15471 case Stmt::UnaryOperatorClass: {
15472 auto *UO = cast<UnaryOperator>(E);
15473 switch (UO->getOpcode()) {
15474 default:
15475 break;
15476 case UO_Deref:
15478 }
15479 break;
15480 }
15481 case Stmt::BinaryOperatorClass: {
15482 auto *BO = cast<BinaryOperator>(E);
15483 auto Opcode = BO->getOpcode();
15484 switch (Opcode) {
15485 default:
15486 break;
15487 case BO_Comma:
15489 }
15490 break;
15491 }
15492 }
15493 return std::nullopt;
15494}
15495
15496/// This helper function takes a pointer expression and returns the alignment of
15497/// a VarDecl and a constant offset from the VarDecl.
15498std::optional<std::pair<
15500 *E,
15502 &Ctx) {
15503 E = E->IgnoreParens();
15504 switch (E->getStmtClass()) {
15505 default:
15506 break;
15507 case Stmt::CStyleCastExprClass:
15508 case Stmt::CXXStaticCastExprClass:
15509 case Stmt::ImplicitCastExprClass: {
15510 auto *CE = cast<CastExpr>(E);
15511 const Expr *From = CE->getSubExpr();
15512 switch (CE->getCastKind()) {
15513 default:
15514 break;
15515 case CK_NoOp:
15516 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15517 case CK_ArrayToPointerDecay:
15518 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15519 case CK_UncheckedDerivedToBase:
15520 case CK_DerivedToBase: {
15521 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15522 if (!P)
15523 break;
15525 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15526 }
15527 }
15528 break;
15529 }
15530 case Stmt::CXXThisExprClass: {
15531 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15533 return std::make_pair(Alignment, CharUnits::Zero());
15534 }
15535 case Stmt::UnaryOperatorClass: {
15536 auto *UO = cast<UnaryOperator>(E);
15537 if (UO->getOpcode() == UO_AddrOf)
15539 break;
15540 }
15541 case Stmt::BinaryOperatorClass: {
15542 auto *BO = cast<BinaryOperator>(E);
15543 auto Opcode = BO->getOpcode();
15544 switch (Opcode) {
15545 default:
15546 break;
15547 case BO_Add:
15548 case BO_Sub: {
15549 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15550 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15551 std::swap(LHS, RHS);
15552 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15553 Ctx);
15554 }
15555 case BO_Comma:
15556 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15557 }
15558 break;
15559 }
15560 }
15561 return std::nullopt;
15562}
15563
15565 // See if we can compute the alignment of a VarDecl and an offset from it.
15566 std::optional<std::pair<CharUnits, CharUnits>> P =
15568
15569 if (P)
15570 return P->first.alignmentAtOffset(P->second);
15571
15572 // If that failed, return the type's alignment.
15574}
15575
15577 // This is actually a lot of work to potentially be doing on every
15578 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15579 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15580 return;
15581
15582 // Ignore dependent types.
15583 if (T->isDependentType() || Op->getType()->isDependentType())
15584 return;
15585
15586 // Require that the destination be a pointer type.
15587 const PointerType *DestPtr = T->getAs<PointerType>();
15588 if (!DestPtr) return;
15589
15590 // If the destination has alignment 1, we're done.
15591 QualType DestPointee = DestPtr->getPointeeType();
15592 if (DestPointee->isIncompleteType()) return;
15593 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15594 if (DestAlign.isOne()) return;
15595
15596 // Require that the source be a pointer type.
15597 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15598 if (!SrcPtr) return;
15599 QualType SrcPointee = SrcPtr->getPointeeType();
15600
15601 // Explicitly allow casts from cv void*. We already implicitly
15602 // allowed casts to cv void*, since they have alignment 1.
15603 // Also allow casts involving incomplete types, which implicitly
15604 // includes 'void'.
15605 if (SrcPointee->isIncompleteType()) return;
15606
15607 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15608
15609 if (SrcAlign >= DestAlign) return;
15610
15611 Diag(TRange.getBegin(), diag::warn_cast_align)
15612 << Op->getType() << T
15613 << static_cast<unsigned>(SrcAlign.getQuantity())
15614 << static_cast<unsigned>(DestAlign.getQuantity())
15615 << TRange << Op->getSourceRange();
15616}
15617
15618void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15619 const ArraySubscriptExpr *ASE,
15620 bool AllowOnePastEnd, bool IndexNegated) {
15621 // Already diagnosed by the constant evaluator.
15623 return;
15624
15625 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15626 if (IndexExpr->isValueDependent())
15627 return;
15628
15629 const Type *EffectiveType =
15631 BaseExpr = BaseExpr->IgnoreParenCasts();
15632 const ConstantArrayType *ArrayTy =
15633 Context.getAsConstantArrayType(BaseExpr->getType());
15634
15636 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15637
15638 const Type *BaseType =
15639 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15640 bool IsUnboundedArray =
15641 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15642 Context, StrictFlexArraysLevel,
15643 /*IgnoreTemplateOrMacroSubstitution=*/true);
15644 if (EffectiveType->isDependentType() ||
15645 (!IsUnboundedArray && BaseType->isDependentType()))
15646 return;
15647
15649 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15650 return;
15651
15652 llvm::APSInt index = Result.Val.getInt();
15653 if (IndexNegated) {
15654 index.setIsUnsigned(false);
15655 index = -index;
15656 }
15657
15658 if (IsUnboundedArray) {
15659 if (EffectiveType->isFunctionType())
15660 return;
15661 if (index.isUnsigned() || !index.isNegative()) {
15662 const auto &ASTC = getASTContext();
15663 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15664 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15665 if (index.getBitWidth() < AddrBits)
15666 index = index.zext(AddrBits);
15667 std::optional<CharUnits> ElemCharUnits =
15668 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15669 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15670 // pointer) bounds-checking isn't meaningful.
15671 if (!ElemCharUnits || ElemCharUnits->isZero())
15672 return;
15673 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15674 // If index has more active bits than address space, we already know
15675 // we have a bounds violation to warn about. Otherwise, compute
15676 // address of (index + 1)th element, and warn about bounds violation
15677 // only if that address exceeds address space.
15678 if (index.getActiveBits() <= AddrBits) {
15679 bool Overflow;
15680 llvm::APInt Product(index);
15681 Product += 1;
15682 Product = Product.umul_ov(ElemBytes, Overflow);
15683 if (!Overflow && Product.getActiveBits() <= AddrBits)
15684 return;
15685 }
15686
15687 // Need to compute max possible elements in address space, since that
15688 // is included in diag message.
15689 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15690 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15691 MaxElems += 1;
15692 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15693 MaxElems = MaxElems.udiv(ElemBytes);
15694
15695 unsigned DiagID =
15696 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15697 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15698
15699 // Diag message shows element size in bits and in "bytes" (platform-
15700 // dependent CharUnits)
15701 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15702 PDiag(DiagID) << index << AddrBits
15703 << (unsigned)ASTC.toBits(*ElemCharUnits)
15704 << ElemBytes << MaxElems
15705 << MaxElems.getZExtValue()
15706 << IndexExpr->getSourceRange());
15707
15708 const NamedDecl *ND = nullptr;
15709 // Try harder to find a NamedDecl to point at in the note.
15710 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15711 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15712 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15713 ND = DRE->getDecl();
15714 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15715 ND = ME->getMemberDecl();
15716
15717 if (ND)
15718 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15719 PDiag(diag::note_array_declared_here) << ND);
15720 }
15721 return;
15722 }
15723
15724 if (index.isUnsigned() || !index.isNegative()) {
15725 // It is possible that the type of the base expression after
15726 // IgnoreParenCasts is incomplete, even though the type of the base
15727 // expression before IgnoreParenCasts is complete (see PR39746 for an
15728 // example). In this case we have no information about whether the array
15729 // access exceeds the array bounds. However we can still diagnose an array
15730 // access which precedes the array bounds.
15731 if (BaseType->isIncompleteType())
15732 return;
15733
15734 llvm::APInt size = ArrayTy->getSize();
15735
15736 if (BaseType != EffectiveType) {
15737 // Make sure we're comparing apples to apples when comparing index to
15738 // size.
15739 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15740 uint64_t array_typesize = Context.getTypeSize(BaseType);
15741
15742 // Handle ptrarith_typesize being zero, such as when casting to void*.
15743 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15744 if (!ptrarith_typesize)
15745 ptrarith_typesize = Context.getCharWidth();
15746
15747 if (ptrarith_typesize != array_typesize) {
15748 // There's a cast to a different size type involved.
15749 uint64_t ratio = array_typesize / ptrarith_typesize;
15750
15751 // TODO: Be smarter about handling cases where array_typesize is not a
15752 // multiple of ptrarith_typesize.
15753 if (ptrarith_typesize * ratio == array_typesize)
15754 size *= llvm::APInt(size.getBitWidth(), ratio);
15755 }
15756 }
15757
15758 if (size.getBitWidth() > index.getBitWidth())
15759 index = index.zext(size.getBitWidth());
15760 else if (size.getBitWidth() < index.getBitWidth())
15761 size = size.zext(index.getBitWidth());
15762
15763 // For array subscripting the index must be less than size, but for pointer
15764 // arithmetic also allow the index (offset) to be equal to size since
15765 // computing the next address after the end of the array is legal and
15766 // commonly done e.g. in C++ iterators and range-based for loops.
15767 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15768 return;
15769
15770 // Suppress the warning if the subscript expression (as identified by the
15771 // ']' location) and the index expression are both from macro expansions
15772 // within a system header.
15773 if (ASE) {
15774 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15775 ASE->getRBracketLoc());
15776 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15777 SourceLocation IndexLoc =
15778 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15779 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15780 return;
15781 }
15782 }
15783
15784 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15785 : diag::warn_ptr_arith_exceeds_bounds;
15786 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15787 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15788
15789 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15790 PDiag(DiagID)
15791 << index << ArrayTy->desugar() << CastMsg
15792 << CastMsgTy << IndexExpr->getSourceRange());
15793 } else {
15794 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15795 if (!ASE) {
15796 DiagID = diag::warn_ptr_arith_precedes_bounds;
15797 if (index.isNegative()) index = -index;
15798 }
15799
15800 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15801 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15802 }
15803
15804 const NamedDecl *ND = nullptr;
15805 // Try harder to find a NamedDecl to point at in the note.
15806 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15807 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15808 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15809 ND = DRE->getDecl();
15810 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15811 ND = ME->getMemberDecl();
15812
15813 if (ND)
15814 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15815 PDiag(diag::note_array_declared_here) << ND);
15816}
15817
15818void Sema::CheckArrayAccess(const Expr *expr) {
15819 int AllowOnePastEnd = 0;
15820 while (expr) {
15821 expr = expr->IgnoreParenImpCasts();
15822 switch (expr->getStmtClass()) {
15823 case Stmt::ArraySubscriptExprClass: {
15824 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15825 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15826 AllowOnePastEnd > 0);
15827 expr = ASE->getBase();
15828 break;
15829 }
15830 case Stmt::MemberExprClass: {
15831 expr = cast<MemberExpr>(expr)->getBase();
15832 break;
15833 }
15834 case Stmt::CXXMemberCallExprClass: {
15835 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
15836 break;
15837 }
15838 case Stmt::ArraySectionExprClass: {
15839 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15840 // FIXME: We should probably be checking all of the elements to the
15841 // 'length' here as well.
15842 if (ASE->getLowerBound())
15843 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15844 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15845 return;
15846 }
15847 case Stmt::UnaryOperatorClass: {
15848 // Only unwrap the * and & unary operators
15849 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15850 expr = UO->getSubExpr();
15851 switch (UO->getOpcode()) {
15852 case UO_AddrOf:
15853 AllowOnePastEnd++;
15854 break;
15855 case UO_Deref:
15856 AllowOnePastEnd--;
15857 break;
15858 default:
15859 return;
15860 }
15861 break;
15862 }
15863 case Stmt::ConditionalOperatorClass: {
15864 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15865 if (const Expr *lhs = cond->getLHS())
15866 CheckArrayAccess(lhs);
15867 if (const Expr *rhs = cond->getRHS())
15868 CheckArrayAccess(rhs);
15869 return;
15870 }
15871 case Stmt::CXXOperatorCallExprClass: {
15872 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15873 for (const auto *Arg : OCE->arguments())
15874 CheckArrayAccess(Arg);
15875 return;
15876 }
15877 default:
15878 return;
15879 }
15880 }
15881}
15882
15884 Expr *RHS, bool isProperty) {
15885 // Check if RHS is an Objective-C object literal, which also can get
15886 // immediately zapped in a weak reference. Note that we explicitly
15887 // allow ObjCStringLiterals, since those are designed to never really die.
15888 RHS = RHS->IgnoreParenImpCasts();
15889
15890 // This enum needs to match with the 'select' in
15891 // warn_objc_arc_literal_assign (off-by-1).
15893 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15894 return false;
15895
15896 S.Diag(Loc, diag::warn_arc_literal_assign)
15897 << (unsigned) Kind
15898 << (isProperty ? 0 : 1)
15899 << RHS->getSourceRange();
15900
15901 return true;
15902}
15903
15906 Expr *RHS, bool isProperty) {
15907 // Strip off any implicit cast added to get to the one ARC-specific.
15908 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15909 if (cast->getCastKind() == CK_ARCConsumeObject) {
15910 S.Diag(Loc, diag::warn_arc_retained_assign)
15912 << (isProperty ? 0 : 1)
15913 << RHS->getSourceRange();
15914 return true;
15915 }
15916 RHS = cast->getSubExpr();
15917 }
15918
15919 if (LT == Qualifiers::OCL_Weak &&
15920 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15921 return true;
15922
15923 return false;
15924}
15925
15927 QualType LHS, Expr *RHS) {
15929
15931 return false;
15932
15933 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15934 return true;
15935
15936 return false;
15937}
15938
15940 Expr *LHS, Expr *RHS) {
15941 QualType LHSType;
15942 // PropertyRef on LHS type need be directly obtained from
15943 // its declaration as it has a PseudoType.
15945 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15946 if (PRE && !PRE->isImplicitProperty()) {
15947 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15948 if (PD)
15949 LHSType = PD->getType();
15950 }
15951
15952 if (LHSType.isNull())
15953 LHSType = LHS->getType();
15954
15956
15957 if (LT == Qualifiers::OCL_Weak) {
15958 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15960 }
15961
15962 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15963 return;
15964
15965 // FIXME. Check for other life times.
15966 if (LT != Qualifiers::OCL_None)
15967 return;
15968
15969 if (PRE) {
15970 if (PRE->isImplicitProperty())
15971 return;
15972 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15973 if (!PD)
15974 return;
15975
15976 unsigned Attributes = PD->getPropertyAttributes();
15977 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15978 // when 'assign' attribute was not explicitly specified
15979 // by user, ignore it and rely on property type itself
15980 // for lifetime info.
15981 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15982 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15983 LHSType->isObjCRetainableType())
15984 return;
15985
15986 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15987 if (cast->getCastKind() == CK_ARCConsumeObject) {
15988 Diag(Loc, diag::warn_arc_retained_property_assign)
15989 << RHS->getSourceRange();
15990 return;
15991 }
15992 RHS = cast->getSubExpr();
15993 }
15994 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15995 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15996 return;
15997 }
15998 }
15999}
16000
16001//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16002
16003static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16004 SourceLocation StmtLoc,
16005 const NullStmt *Body) {
16006 // Do not warn if the body is a macro that expands to nothing, e.g:
16007 //
16008 // #define CALL(x)
16009 // if (condition)
16010 // CALL(0);
16011 if (Body->hasLeadingEmptyMacro())
16012 return false;
16013
16014 // Get line numbers of statement and body.
16015 bool StmtLineInvalid;
16016 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16017 &StmtLineInvalid);
16018 if (StmtLineInvalid)
16019 return false;
16020
16021 bool BodyLineInvalid;
16022 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16023 &BodyLineInvalid);
16024 if (BodyLineInvalid)
16025 return false;
16026
16027 // Warn if null statement and body are on the same line.
16028 if (StmtLine != BodyLine)
16029 return false;
16030
16031 return true;
16032}
16033
16035 const Stmt *Body,
16036 unsigned DiagID) {
16037 // Since this is a syntactic check, don't emit diagnostic for template
16038 // instantiations, this just adds noise.
16040 return;
16041
16042 // The body should be a null statement.
16043 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16044 if (!NBody)
16045 return;
16046
16047 // Do the usual checks.
16048 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16049 return;
16050
16051 Diag(NBody->getSemiLoc(), DiagID);
16052 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16053}
16054
16056 const Stmt *PossibleBody) {
16057 assert(!CurrentInstantiationScope); // Ensured by caller
16058
16059 SourceLocation StmtLoc;
16060 const Stmt *Body;
16061 unsigned DiagID;
16062 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16063 StmtLoc = FS->getRParenLoc();
16064 Body = FS->getBody();
16065 DiagID = diag::warn_empty_for_body;
16066 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16067 StmtLoc = WS->getRParenLoc();
16068 Body = WS->getBody();
16069 DiagID = diag::warn_empty_while_body;
16070 } else
16071 return; // Neither `for' nor `while'.
16072
16073 // The body should be a null statement.
16074 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16075 if (!NBody)
16076 return;
16077
16078 // Skip expensive checks if diagnostic is disabled.
16079 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16080 return;
16081
16082 // Do the usual checks.
16083 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16084 return;
16085
16086 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16087 // noise level low, emit diagnostics only if for/while is followed by a
16088 // CompoundStmt, e.g.:
16089 // for (int i = 0; i < n; i++);
16090 // {
16091 // a(i);
16092 // }
16093 // or if for/while is followed by a statement with more indentation
16094 // than for/while itself:
16095 // for (int i = 0; i < n; i++);
16096 // a(i);
16097 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16098 if (!ProbableTypo) {
16099 bool BodyColInvalid;
16100 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16101 PossibleBody->getBeginLoc(), &BodyColInvalid);
16102 if (BodyColInvalid)
16103 return;
16104
16105 bool StmtColInvalid;
16106 unsigned StmtCol =
16107 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16108 if (StmtColInvalid)
16109 return;
16110
16111 if (BodyCol > StmtCol)
16112 ProbableTypo = true;
16113 }
16114
16115 if (ProbableTypo) {
16116 Diag(NBody->getSemiLoc(), DiagID);
16117 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16118 }
16119}
16120
16121//===--- CHECK: Warn on self move with std::move. -------------------------===//
16122
16123void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16124 SourceLocation OpLoc) {
16125 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16126 return;
16127
16129 return;
16130
16131 // Strip parens and casts away.
16132 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16133 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16134
16135 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16136 // which we can treat as an inlined std::move
16137 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16138 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16139 RHSExpr = CE->getArg(0);
16140 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16141 CXXSCE && CXXSCE->isXValue())
16142 RHSExpr = CXXSCE->getSubExpr();
16143 else
16144 return;
16145
16146 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16147 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16148
16149 // Two DeclRefExpr's, check that the decls are the same.
16150 if (LHSDeclRef && RHSDeclRef) {
16151 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16152 return;
16153 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16154 RHSDeclRef->getDecl()->getCanonicalDecl())
16155 return;
16156
16157 auto D = Diag(OpLoc, diag::warn_self_move)
16158 << LHSExpr->getType() << LHSExpr->getSourceRange()
16159 << RHSExpr->getSourceRange();
16160 if (const FieldDecl *F =
16162 D << 1 << F
16163 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16164 else
16165 D << 0;
16166 return;
16167 }
16168
16169 // Member variables require a different approach to check for self moves.
16170 // MemberExpr's are the same if every nested MemberExpr refers to the same
16171 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16172 // the base Expr's are CXXThisExpr's.
16173 const Expr *LHSBase = LHSExpr;
16174 const Expr *RHSBase = RHSExpr;
16175 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16176 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16177 if (!LHSME || !RHSME)
16178 return;
16179
16180 while (LHSME && RHSME) {
16181 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16182 RHSME->getMemberDecl()->getCanonicalDecl())
16183 return;
16184
16185 LHSBase = LHSME->getBase();
16186 RHSBase = RHSME->getBase();
16187 LHSME = dyn_cast<MemberExpr>(LHSBase);
16188 RHSME = dyn_cast<MemberExpr>(RHSBase);
16189 }
16190
16191 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16192 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16193 if (LHSDeclRef && RHSDeclRef) {
16194 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16195 return;
16196 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16197 RHSDeclRef->getDecl()->getCanonicalDecl())
16198 return;
16199
16200 Diag(OpLoc, diag::warn_self_move)
16201 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16202 << RHSExpr->getSourceRange();
16203 return;
16204 }
16205
16206 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16207 Diag(OpLoc, diag::warn_self_move)
16208 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16209 << RHSExpr->getSourceRange();
16210}
16211
16212//===--- Layout compatibility ----------------------------------------------//
16213
16214static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16215
16216/// Check if two enumeration types are layout-compatible.
16217static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16218 const EnumDecl *ED2) {
16219 // C++11 [dcl.enum] p8:
16220 // Two enumeration types are layout-compatible if they have the same
16221 // underlying type.
16222 return ED1->isComplete() && ED2->isComplete() &&
16223 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16224}
16225
16226/// Check if two fields are layout-compatible.
16227/// Can be used on union members, which are exempt from alignment requirement
16228/// of common initial sequence.
16229static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16230 const FieldDecl *Field2,
16231 bool AreUnionMembers = false) {
16232#ifndef NDEBUG
16233 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16234 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16235 assert(((Field1Parent->isStructureOrClassType() &&
16236 Field2Parent->isStructureOrClassType()) ||
16237 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16238 "Can't evaluate layout compatibility between a struct field and a "
16239 "union field.");
16240 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16241 (AreUnionMembers && Field1Parent->isUnionType())) &&
16242 "AreUnionMembers should be 'true' for union fields (only).");
16243#endif
16244
16245 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16246 return false;
16247
16248 if (Field1->isBitField() != Field2->isBitField())
16249 return false;
16250
16251 if (Field1->isBitField()) {
16252 // Make sure that the bit-fields are the same length.
16253 unsigned Bits1 = Field1->getBitWidthValue();
16254 unsigned Bits2 = Field2->getBitWidthValue();
16255
16256 if (Bits1 != Bits2)
16257 return false;
16258 }
16259
16260 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16261 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16262 return false;
16263
16264 if (!AreUnionMembers &&
16265 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16266 return false;
16267
16268 return true;
16269}
16270
16271/// Check if two standard-layout structs are layout-compatible.
16272/// (C++11 [class.mem] p17)
16273static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16274 const RecordDecl *RD2) {
16275 // Get to the class where the fields are declared
16276 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16277 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16278
16279 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16280 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16281
16282 // Check the fields.
16283 return llvm::equal(RD1->fields(), RD2->fields(),
16284 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16285 return isLayoutCompatible(C, F1, F2);
16286 });
16287}
16288
16289/// Check if two standard-layout unions are layout-compatible.
16290/// (C++11 [class.mem] p18)
16291static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16292 const RecordDecl *RD2) {
16293 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16294 RD2->fields());
16295
16296 for (auto *Field1 : RD1->fields()) {
16297 auto I = UnmatchedFields.begin();
16298 auto E = UnmatchedFields.end();
16299
16300 for ( ; I != E; ++I) {
16301 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16302 bool Result = UnmatchedFields.erase(*I);
16303 (void) Result;
16304 assert(Result);
16305 break;
16306 }
16307 }
16308 if (I == E)
16309 return false;
16310 }
16311
16312 return UnmatchedFields.empty();
16313}
16314
16315static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16316 const RecordDecl *RD2) {
16317 if (RD1->isUnion() != RD2->isUnion())
16318 return false;
16319
16320 if (RD1->isUnion())
16321 return isLayoutCompatibleUnion(C, RD1, RD2);
16322 else
16323 return isLayoutCompatibleStruct(C, RD1, RD2);
16324}
16325
16326/// Check if two types are layout-compatible in C++11 sense.
16327static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16328 if (T1.isNull() || T2.isNull())
16329 return false;
16330
16331 // C++20 [basic.types] p11:
16332 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16333 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16334 // or layout-compatible standard-layout class types (11.4).
16337
16338 if (C.hasSameType(T1, T2))
16339 return true;
16340
16341 const Type::TypeClass TC1 = T1->getTypeClass();
16342 const Type::TypeClass TC2 = T2->getTypeClass();
16343
16344 if (TC1 != TC2)
16345 return false;
16346
16347 if (TC1 == Type::Enum)
16348 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16349 if (TC1 == Type::Record) {
16350 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16351 return false;
16352
16354 T2->castAsRecordDecl());
16355 }
16356
16357 return false;
16358}
16359
16361 return isLayoutCompatible(getASTContext(), T1, T2);
16362}
16363
16364//===-------------- Pointer interconvertibility ----------------------------//
16365
16367 const TypeSourceInfo *Derived) {
16368 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16369 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16370
16371 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16372 getASTContext().hasSameType(BaseT, DerivedT))
16373 return true;
16374
16375 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16376 return false;
16377
16378 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16379 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16380 return true;
16381
16382 return false;
16383}
16384
16385//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16386
16387/// Given a type tag expression find the type tag itself.
16388///
16389/// \param TypeExpr Type tag expression, as it appears in user's code.
16390///
16391/// \param VD Declaration of an identifier that appears in a type tag.
16392///
16393/// \param MagicValue Type tag magic value.
16394///
16395/// \param isConstantEvaluated whether the evalaution should be performed in
16396
16397/// constant context.
16398static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16399 const ValueDecl **VD, uint64_t *MagicValue,
16400 bool isConstantEvaluated) {
16401 while(true) {
16402 if (!TypeExpr)
16403 return false;
16404
16405 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16406
16407 switch (TypeExpr->getStmtClass()) {
16408 case Stmt::UnaryOperatorClass: {
16409 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16410 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16411 TypeExpr = UO->getSubExpr();
16412 continue;
16413 }
16414 return false;
16415 }
16416
16417 case Stmt::DeclRefExprClass: {
16418 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16419 *VD = DRE->getDecl();
16420 return true;
16421 }
16422
16423 case Stmt::IntegerLiteralClass: {
16424 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16425 llvm::APInt MagicValueAPInt = IL->getValue();
16426 if (MagicValueAPInt.getActiveBits() <= 64) {
16427 *MagicValue = MagicValueAPInt.getZExtValue();
16428 return true;
16429 } else
16430 return false;
16431 }
16432
16433 case Stmt::BinaryConditionalOperatorClass:
16434 case Stmt::ConditionalOperatorClass: {
16435 const AbstractConditionalOperator *ACO =
16437 bool Result;
16438 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16439 isConstantEvaluated)) {
16440 if (Result)
16441 TypeExpr = ACO->getTrueExpr();
16442 else
16443 TypeExpr = ACO->getFalseExpr();
16444 continue;
16445 }
16446 return false;
16447 }
16448
16449 case Stmt::BinaryOperatorClass: {
16450 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16451 if (BO->getOpcode() == BO_Comma) {
16452 TypeExpr = BO->getRHS();
16453 continue;
16454 }
16455 return false;
16456 }
16457
16458 default:
16459 return false;
16460 }
16461 }
16462}
16463
16464/// Retrieve the C type corresponding to type tag TypeExpr.
16465///
16466/// \param TypeExpr Expression that specifies a type tag.
16467///
16468/// \param MagicValues Registered magic values.
16469///
16470/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16471/// kind.
16472///
16473/// \param TypeInfo Information about the corresponding C type.
16474///
16475/// \param isConstantEvaluated whether the evalaution should be performed in
16476/// constant context.
16477///
16478/// \returns true if the corresponding C type was found.
16480 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16481 const ASTContext &Ctx,
16482 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16483 *MagicValues,
16484 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16485 bool isConstantEvaluated) {
16486 FoundWrongKind = false;
16487
16488 // Variable declaration that has type_tag_for_datatype attribute.
16489 const ValueDecl *VD = nullptr;
16490
16491 uint64_t MagicValue;
16492
16493 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16494 return false;
16495
16496 if (VD) {
16497 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16498 if (I->getArgumentKind() != ArgumentKind) {
16499 FoundWrongKind = true;
16500 return false;
16501 }
16502 TypeInfo.Type = I->getMatchingCType();
16503 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16504 TypeInfo.MustBeNull = I->getMustBeNull();
16505 return true;
16506 }
16507 return false;
16508 }
16509
16510 if (!MagicValues)
16511 return false;
16512
16513 llvm::DenseMap<Sema::TypeTagMagicValue,
16515 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16516 if (I == MagicValues->end())
16517 return false;
16518
16519 TypeInfo = I->second;
16520 return true;
16521}
16522
16524 uint64_t MagicValue, QualType Type,
16525 bool LayoutCompatible,
16526 bool MustBeNull) {
16527 if (!TypeTagForDatatypeMagicValues)
16528 TypeTagForDatatypeMagicValues.reset(
16529 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16530
16531 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16532 (*TypeTagForDatatypeMagicValues)[Magic] =
16533 TypeTagData(Type, LayoutCompatible, MustBeNull);
16534}
16535
16536static bool IsSameCharType(QualType T1, QualType T2) {
16537 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16538 if (!BT1)
16539 return false;
16540
16541 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16542 if (!BT2)
16543 return false;
16544
16545 BuiltinType::Kind T1Kind = BT1->getKind();
16546 BuiltinType::Kind T2Kind = BT2->getKind();
16547
16548 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16549 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16550 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16551 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16552}
16553
16554void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16555 const ArrayRef<const Expr *> ExprArgs,
16556 SourceLocation CallSiteLoc) {
16557 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16558 bool IsPointerAttr = Attr->getIsPointer();
16559
16560 // Retrieve the argument representing the 'type_tag'.
16561 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16562 if (TypeTagIdxAST >= ExprArgs.size()) {
16563 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16564 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16565 return;
16566 }
16567 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16568 bool FoundWrongKind;
16569 TypeTagData TypeInfo;
16570 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16571 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16572 TypeInfo, isConstantEvaluatedContext())) {
16573 if (FoundWrongKind)
16574 Diag(TypeTagExpr->getExprLoc(),
16575 diag::warn_type_tag_for_datatype_wrong_kind)
16576 << TypeTagExpr->getSourceRange();
16577 return;
16578 }
16579
16580 // Retrieve the argument representing the 'arg_idx'.
16581 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16582 if (ArgumentIdxAST >= ExprArgs.size()) {
16583 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16584 << 1 << Attr->getArgumentIdx().getSourceIndex();
16585 return;
16586 }
16587 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16588 if (IsPointerAttr) {
16589 // Skip implicit cast of pointer to `void *' (as a function argument).
16590 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16591 if (ICE->getType()->isVoidPointerType() &&
16592 ICE->getCastKind() == CK_BitCast)
16593 ArgumentExpr = ICE->getSubExpr();
16594 }
16595 QualType ArgumentType = ArgumentExpr->getType();
16596
16597 // Passing a `void*' pointer shouldn't trigger a warning.
16598 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16599 return;
16600
16601 if (TypeInfo.MustBeNull) {
16602 // Type tag with matching void type requires a null pointer.
16603 if (!ArgumentExpr->isNullPointerConstant(Context,
16605 Diag(ArgumentExpr->getExprLoc(),
16606 diag::warn_type_safety_null_pointer_required)
16607 << ArgumentKind->getName()
16608 << ArgumentExpr->getSourceRange()
16609 << TypeTagExpr->getSourceRange();
16610 }
16611 return;
16612 }
16613
16614 QualType RequiredType = TypeInfo.Type;
16615 if (IsPointerAttr)
16616 RequiredType = Context.getPointerType(RequiredType);
16617
16618 bool mismatch = false;
16619 if (!TypeInfo.LayoutCompatible) {
16620 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16621
16622 // C++11 [basic.fundamental] p1:
16623 // Plain char, signed char, and unsigned char are three distinct types.
16624 //
16625 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16626 // char' depending on the current char signedness mode.
16627 if (mismatch)
16628 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16629 RequiredType->getPointeeType())) ||
16630 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16631 mismatch = false;
16632 } else
16633 if (IsPointerAttr)
16634 mismatch = !isLayoutCompatible(Context,
16635 ArgumentType->getPointeeType(),
16636 RequiredType->getPointeeType());
16637 else
16638 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16639
16640 if (mismatch)
16641 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16642 << ArgumentType << ArgumentKind
16643 << TypeInfo.LayoutCompatible << RequiredType
16644 << ArgumentExpr->getSourceRange()
16645 << TypeTagExpr->getSourceRange();
16646}
16647
16648void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16649 CharUnits Alignment) {
16650 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16651 Alignment);
16652}
16653
16655 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16656 const NamedDecl *ND = m.RD;
16657 if (ND->getName().empty()) {
16658 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16659 ND = TD;
16660 }
16661 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16662 << m.MD << ND << m.E->getSourceRange();
16663 }
16665}
16666
16668 E = E->IgnoreParens();
16669 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16670 return;
16671 if (isa<UnaryOperator>(E) &&
16672 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16673 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16674 if (isa<MemberExpr>(Op)) {
16675 auto &MisalignedMembersForExpr =
16677 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16678 if (MA != MisalignedMembersForExpr.end() &&
16679 (T->isDependentType() || T->isIntegerType() ||
16680 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16681 Context.getTypeAlignInChars(
16682 T->getPointeeType()) <= MA->Alignment))))
16683 MisalignedMembersForExpr.erase(MA);
16684 }
16685 }
16686}
16687
16689 Expr *E,
16690 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16691 Action) {
16692 const auto *ME = dyn_cast<MemberExpr>(E);
16693 if (!ME)
16694 return;
16695
16696 // No need to check expressions with an __unaligned-qualified type.
16697 if (E->getType().getQualifiers().hasUnaligned())
16698 return;
16699
16700 // For a chain of MemberExpr like "a.b.c.d" this list
16701 // will keep FieldDecl's like [d, c, b].
16702 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16703 const MemberExpr *TopME = nullptr;
16704 bool AnyIsPacked = false;
16705 do {
16706 QualType BaseType = ME->getBase()->getType();
16707 if (BaseType->isDependentType())
16708 return;
16709 if (ME->isArrow())
16710 BaseType = BaseType->getPointeeType();
16711 auto *RD = BaseType->castAsRecordDecl();
16712 if (RD->isInvalidDecl())
16713 return;
16714
16715 ValueDecl *MD = ME->getMemberDecl();
16716 auto *FD = dyn_cast<FieldDecl>(MD);
16717 // We do not care about non-data members.
16718 if (!FD || FD->isInvalidDecl())
16719 return;
16720
16721 AnyIsPacked =
16722 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16723 ReverseMemberChain.push_back(FD);
16724
16725 TopME = ME;
16726 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16727 } while (ME);
16728 assert(TopME && "We did not compute a topmost MemberExpr!");
16729
16730 // Not the scope of this diagnostic.
16731 if (!AnyIsPacked)
16732 return;
16733
16734 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16735 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16736 // TODO: The innermost base of the member expression may be too complicated.
16737 // For now, just disregard these cases. This is left for future
16738 // improvement.
16739 if (!DRE && !isa<CXXThisExpr>(TopBase))
16740 return;
16741
16742 // Alignment expected by the whole expression.
16743 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16744
16745 // No need to do anything else with this case.
16746 if (ExpectedAlignment.isOne())
16747 return;
16748
16749 // Synthesize offset of the whole access.
16750 CharUnits Offset;
16751 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16752 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16753
16754 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16755 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16756 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16757
16758 // The base expression of the innermost MemberExpr may give
16759 // stronger guarantees than the class containing the member.
16760 if (DRE && !TopME->isArrow()) {
16761 const ValueDecl *VD = DRE->getDecl();
16762 if (!VD->getType()->isReferenceType())
16763 CompleteObjectAlignment =
16764 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16765 }
16766
16767 // Check if the synthesized offset fulfills the alignment.
16768 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16769 // It may fulfill the offset it but the effective alignment may still be
16770 // lower than the expected expression alignment.
16771 CompleteObjectAlignment < ExpectedAlignment) {
16772 // If this happens, we want to determine a sensible culprit of this.
16773 // Intuitively, watching the chain of member expressions from right to
16774 // left, we start with the required alignment (as required by the field
16775 // type) but some packed attribute in that chain has reduced the alignment.
16776 // It may happen that another packed structure increases it again. But if
16777 // we are here such increase has not been enough. So pointing the first
16778 // FieldDecl that either is packed or else its RecordDecl is,
16779 // seems reasonable.
16780 FieldDecl *FD = nullptr;
16781 CharUnits Alignment;
16782 for (FieldDecl *FDI : ReverseMemberChain) {
16783 if (FDI->hasAttr<PackedAttr>() ||
16784 FDI->getParent()->hasAttr<PackedAttr>()) {
16785 FD = FDI;
16786 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16787 Context.getTypeAlignInChars(
16788 Context.getCanonicalTagType(FD->getParent())));
16789 break;
16790 }
16791 }
16792 assert(FD && "We did not find a packed FieldDecl!");
16793 Action(E, FD->getParent(), FD, Alignment);
16794 }
16795}
16796
16797void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16798 using namespace std::placeholders;
16799
16801 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16802 _2, _3, _4));
16803}
16804
16806 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16807 if (checkArgCount(TheCall, 1))
16808 return true;
16809
16810 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16811 if (A.isInvalid())
16812 return true;
16813
16814 TheCall->setArg(0, A.get());
16815 QualType TyA = A.get()->getType();
16816
16817 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16818 ArgTyRestr, 1))
16819 return true;
16820
16821 TheCall->setType(TyA);
16822 return false;
16823}
16824
16825bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16826 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16827 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16828 TheCall->setType(*Res);
16829 return false;
16830 }
16831 return true;
16832}
16833
16835 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16836 if (!Res)
16837 return true;
16838
16839 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16840 TheCall->setType(VecTy0->getElementType());
16841 else
16842 TheCall->setType(*Res);
16843
16844 return false;
16845}
16846
16848 SourceLocation Loc) {
16850 R = RHS->getEnumCoercedType(S.Context);
16851 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16853 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16854 << LHS->getSourceRange() << RHS->getSourceRange()
16855 << /*Arithmetic Between*/ 0 << L << R;
16856 }
16857 return false;
16858}
16859
16860/// Check if all arguments have the same type. If the types don't match, emit an
16861/// error message and return true. Otherwise return false.
16862///
16863/// For scalars we directly compare their unqualified types. But even if we
16864/// compare unqualified vector types, a difference in qualifiers in the element
16865/// types can make the vector types be considered not equal. For example,
16866/// vector of 4 'const float' values vs vector of 4 'float' values.
16867/// So we compare unqualified types of their elements and number of elements.
16869 ArrayRef<Expr *> Args) {
16870 assert(!Args.empty() && "Should have at least one argument.");
16871
16872 Expr *Arg0 = Args.front();
16873 QualType Ty0 = Arg0->getType();
16874
16875 auto EmitError = [&](Expr *ArgI) {
16876 SemaRef.Diag(Arg0->getBeginLoc(),
16877 diag::err_typecheck_call_different_arg_types)
16878 << Arg0->getType() << ArgI->getType();
16879 };
16880
16881 // Compare scalar types.
16882 if (!Ty0->isVectorType()) {
16883 for (Expr *ArgI : Args.drop_front())
16884 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16885 EmitError(ArgI);
16886 return true;
16887 }
16888
16889 return false;
16890 }
16891
16892 // Compare vector types.
16893 const auto *Vec0 = Ty0->castAs<VectorType>();
16894 for (Expr *ArgI : Args.drop_front()) {
16895 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16896 if (!VecI ||
16897 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16898 VecI->getElementType()) ||
16899 Vec0->getNumElements() != VecI->getNumElements()) {
16900 EmitError(ArgI);
16901 return true;
16902 }
16903 }
16904
16905 return false;
16906}
16907
16908std::optional<QualType>
16910 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16911 if (checkArgCount(TheCall, 2))
16912 return std::nullopt;
16913
16915 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16916 return std::nullopt;
16917
16918 Expr *Args[2];
16919 for (int I = 0; I < 2; ++I) {
16920 ExprResult Converted =
16921 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16922 if (Converted.isInvalid())
16923 return std::nullopt;
16924 Args[I] = Converted.get();
16925 }
16926
16927 SourceLocation LocA = Args[0]->getBeginLoc();
16928 QualType TyA = Args[0]->getType();
16929
16930 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16931 return std::nullopt;
16932
16933 if (checkBuiltinVectorMathArgTypes(*this, Args))
16934 return std::nullopt;
16935
16936 TheCall->setArg(0, Args[0]);
16937 TheCall->setArg(1, Args[1]);
16938 return TyA;
16939}
16940
16942 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16943 if (checkArgCount(TheCall, 3))
16944 return true;
16945
16946 SourceLocation Loc = TheCall->getExprLoc();
16947 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16948 TheCall->getArg(1), Loc) ||
16949 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16950 TheCall->getArg(2), Loc))
16951 return true;
16952
16953 Expr *Args[3];
16954 for (int I = 0; I < 3; ++I) {
16955 ExprResult Converted =
16956 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16957 if (Converted.isInvalid())
16958 return true;
16959 Args[I] = Converted.get();
16960 }
16961
16962 int ArgOrdinal = 1;
16963 for (Expr *Arg : Args) {
16964 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16965 ArgTyRestr, ArgOrdinal++))
16966 return true;
16967 }
16968
16969 if (checkBuiltinVectorMathArgTypes(*this, Args))
16970 return true;
16971
16972 for (int I = 0; I < 3; ++I)
16973 TheCall->setArg(I, Args[I]);
16974
16975 TheCall->setType(Args[0]->getType());
16976 return false;
16977}
16978
16979bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16980 if (checkArgCount(TheCall, 1))
16981 return true;
16982
16983 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16984 if (A.isInvalid())
16985 return true;
16986
16987 TheCall->setArg(0, A.get());
16988 return false;
16989}
16990
16991bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16992 if (checkArgCount(TheCall, 1))
16993 return true;
16994
16995 ExprResult Arg = TheCall->getArg(0);
16996 QualType TyArg = Arg.get()->getType();
16997
16998 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16999 return Diag(TheCall->getArg(0)->getBeginLoc(),
17000 diag::err_builtin_invalid_arg_type)
17001 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17002
17003 TheCall->setType(TyArg);
17004 return false;
17005}
17006
17007ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17008 ExprResult CallResult) {
17009 if (checkArgCount(TheCall, 1))
17010 return ExprError();
17011
17012 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17013 if (MatrixArg.isInvalid())
17014 return MatrixArg;
17015 Expr *Matrix = MatrixArg.get();
17016
17017 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17018 if (!MType) {
17019 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17020 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17021 << Matrix->getType();
17022 return ExprError();
17023 }
17024
17025 // Create returned matrix type by swapping rows and columns of the argument
17026 // matrix type.
17027 QualType ResultType = Context.getConstantMatrixType(
17028 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17029
17030 // Change the return type to the type of the returned matrix.
17031 TheCall->setType(ResultType);
17032
17033 // Update call argument to use the possibly converted matrix argument.
17034 TheCall->setArg(0, Matrix);
17035 return CallResult;
17036}
17037
17038// Get and verify the matrix dimensions.
17039static std::optional<unsigned>
17041 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17042 if (!Value) {
17043 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17044 << Name;
17045 return {};
17046 }
17047 uint64_t Dim = Value->getZExtValue();
17048 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17049 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17050 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17051 return {};
17052 }
17053 return Dim;
17054}
17055
17056ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17057 ExprResult CallResult) {
17058 if (!getLangOpts().MatrixTypes) {
17059 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17060 return ExprError();
17061 }
17062
17063 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17065 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17066 << /*column*/ 1 << /*load*/ 0;
17067 return ExprError();
17068 }
17069
17070 if (checkArgCount(TheCall, 4))
17071 return ExprError();
17072
17073 unsigned PtrArgIdx = 0;
17074 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17075 Expr *RowsExpr = TheCall->getArg(1);
17076 Expr *ColumnsExpr = TheCall->getArg(2);
17077 Expr *StrideExpr = TheCall->getArg(3);
17078
17079 bool ArgError = false;
17080
17081 // Check pointer argument.
17082 {
17084 if (PtrConv.isInvalid())
17085 return PtrConv;
17086 PtrExpr = PtrConv.get();
17087 TheCall->setArg(0, PtrExpr);
17088 if (PtrExpr->isTypeDependent()) {
17089 TheCall->setType(Context.DependentTy);
17090 return TheCall;
17091 }
17092 }
17093
17094 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17095 QualType ElementTy;
17096 if (!PtrTy) {
17097 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17098 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17099 << PtrExpr->getType();
17100 ArgError = true;
17101 } else {
17102 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17103
17105 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17106 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17107 << /* no fp */ 0 << PtrExpr->getType();
17108 ArgError = true;
17109 }
17110 }
17111
17112 // Apply default Lvalue conversions and convert the expression to size_t.
17113 auto ApplyArgumentConversions = [this](Expr *E) {
17115 if (Conv.isInvalid())
17116 return Conv;
17117
17118 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17119 };
17120
17121 // Apply conversion to row and column expressions.
17122 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17123 if (!RowsConv.isInvalid()) {
17124 RowsExpr = RowsConv.get();
17125 TheCall->setArg(1, RowsExpr);
17126 } else
17127 RowsExpr = nullptr;
17128
17129 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17130 if (!ColumnsConv.isInvalid()) {
17131 ColumnsExpr = ColumnsConv.get();
17132 TheCall->setArg(2, ColumnsExpr);
17133 } else
17134 ColumnsExpr = nullptr;
17135
17136 // If any part of the result matrix type is still pending, just use
17137 // Context.DependentTy, until all parts are resolved.
17138 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17139 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17140 TheCall->setType(Context.DependentTy);
17141 return CallResult;
17142 }
17143
17144 // Check row and column dimensions.
17145 std::optional<unsigned> MaybeRows;
17146 if (RowsExpr)
17147 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17148
17149 std::optional<unsigned> MaybeColumns;
17150 if (ColumnsExpr)
17151 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17152
17153 // Check stride argument.
17154 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17155 if (StrideConv.isInvalid())
17156 return ExprError();
17157 StrideExpr = StrideConv.get();
17158 TheCall->setArg(3, StrideExpr);
17159
17160 if (MaybeRows) {
17161 if (std::optional<llvm::APSInt> Value =
17162 StrideExpr->getIntegerConstantExpr(Context)) {
17163 uint64_t Stride = Value->getZExtValue();
17164 if (Stride < *MaybeRows) {
17165 Diag(StrideExpr->getBeginLoc(),
17166 diag::err_builtin_matrix_stride_too_small);
17167 ArgError = true;
17168 }
17169 }
17170 }
17171
17172 if (ArgError || !MaybeRows || !MaybeColumns)
17173 return ExprError();
17174
17175 TheCall->setType(
17176 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17177 return CallResult;
17178}
17179
17180ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17181 ExprResult CallResult) {
17182 if (!getLangOpts().MatrixTypes) {
17183 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17184 return ExprError();
17185 }
17186
17187 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17189 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17190 << /*column*/ 1 << /*store*/ 1;
17191 return ExprError();
17192 }
17193
17194 if (checkArgCount(TheCall, 3))
17195 return ExprError();
17196
17197 unsigned PtrArgIdx = 1;
17198 Expr *MatrixExpr = TheCall->getArg(0);
17199 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17200 Expr *StrideExpr = TheCall->getArg(2);
17201
17202 bool ArgError = false;
17203
17204 {
17205 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17206 if (MatrixConv.isInvalid())
17207 return MatrixConv;
17208 MatrixExpr = MatrixConv.get();
17209 TheCall->setArg(0, MatrixExpr);
17210 }
17211 if (MatrixExpr->isTypeDependent()) {
17212 TheCall->setType(Context.DependentTy);
17213 return TheCall;
17214 }
17215
17216 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17217 if (!MatrixTy) {
17218 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17219 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17220 ArgError = true;
17221 }
17222
17223 {
17225 if (PtrConv.isInvalid())
17226 return PtrConv;
17227 PtrExpr = PtrConv.get();
17228 TheCall->setArg(1, PtrExpr);
17229 if (PtrExpr->isTypeDependent()) {
17230 TheCall->setType(Context.DependentTy);
17231 return TheCall;
17232 }
17233 }
17234
17235 // Check pointer argument.
17236 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17237 if (!PtrTy) {
17238 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17239 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17240 << PtrExpr->getType();
17241 ArgError = true;
17242 } else {
17243 QualType ElementTy = PtrTy->getPointeeType();
17244 if (ElementTy.isConstQualified()) {
17245 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17246 ArgError = true;
17247 }
17248 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17249 if (MatrixTy &&
17250 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17251 Diag(PtrExpr->getBeginLoc(),
17252 diag::err_builtin_matrix_pointer_arg_mismatch)
17253 << ElementTy << MatrixTy->getElementType();
17254 ArgError = true;
17255 }
17256 }
17257
17258 // Apply default Lvalue conversions and convert the stride expression to
17259 // size_t.
17260 {
17261 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17262 if (StrideConv.isInvalid())
17263 return StrideConv;
17264
17265 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17266 if (StrideConv.isInvalid())
17267 return StrideConv;
17268 StrideExpr = StrideConv.get();
17269 TheCall->setArg(2, StrideExpr);
17270 }
17271
17272 // Check stride argument.
17273 if (MatrixTy) {
17274 if (std::optional<llvm::APSInt> Value =
17275 StrideExpr->getIntegerConstantExpr(Context)) {
17276 uint64_t Stride = Value->getZExtValue();
17277 if (Stride < MatrixTy->getNumRows()) {
17278 Diag(StrideExpr->getBeginLoc(),
17279 diag::err_builtin_matrix_stride_too_small);
17280 ArgError = true;
17281 }
17282 }
17283 }
17284
17285 if (ArgError)
17286 return ExprError();
17287
17288 return CallResult;
17289}
17290
17292 const NamedDecl *Callee) {
17293 // This warning does not make sense in code that has no runtime behavior.
17295 return;
17296
17297 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17298
17299 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17300 return;
17301
17302 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17303 // all TCBs the callee is a part of.
17304 llvm::StringSet<> CalleeTCBs;
17305 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17306 CalleeTCBs.insert(A->getTCBName());
17307 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17308 CalleeTCBs.insert(A->getTCBName());
17309
17310 // Go through the TCBs the caller is a part of and emit warnings if Caller
17311 // is in a TCB that the Callee is not.
17312 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17313 StringRef CallerTCB = A->getTCBName();
17314 if (CalleeTCBs.count(CallerTCB) == 0) {
17315 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17316 << Callee << CallerTCB;
17317 }
17318 }
17319}
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.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
llvm::json::Object Object
llvm::json::Array Array
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 functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
__device__ __2f16 float __ockl_bool s
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * toString() const
const char * getStart() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
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:226
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:798
Builtin::Context & BuiltinInfo
Definition ASTContext.h:800
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
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:851
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:917
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:7296
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7300
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:3772
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3784
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6927
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7076
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7058
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:2133
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:3592
This class is used for builtin types like 'int'.
Definition TypeBase.h:3214
bool isInteger() const
Definition TypeBase.h:3275
bool isFloatingPoint() const
Definition TypeBase.h:3287
bool isSignedInteger() const
Definition TypeBase.h:3279
bool isUnsignedInteger() const
Definition TypeBase.h:3283
Kind getKind() const
Definition TypeBase.h:3262
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:382
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h: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:2959
Represents a C++ destructor within a class.
Definition DeclCXX.h:2889
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
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:74
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:1592
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:3642
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:1597
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:3810
QualType desugar() const
Definition TypeBase.h:3911
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3866
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4459
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:5673
Expr * getOperand() const
Definition ExprCXX.h:5324
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h: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:488
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:2001
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:3438
Represents an enum.
Definition Decl.h:4028
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4260
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4201
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
@ 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:3095
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:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3078
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:3086
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:206
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:4229
@ 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:3074
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3082
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:3688
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:3070
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:4068
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:266
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:277
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:226
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:4317
Represents a member of a struct/union/class.
Definition Decl.h:3175
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3278
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4754
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3411
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3291
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:2894
Represents a function declaration or definition.
Definition Decl.h:2015
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4555
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3764
param_iterator param_end()
Definition Decl.h:2802
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3867
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
param_iterator param_begin()
Definition Decl.h:2801
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3135
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4331
bool isStatic() const
Definition Decl.h:2944
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4146
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4132
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3828
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
unsigned getNumParams() const
Definition TypeBase.h:5635
QualType getParamType(unsigned i) const
Definition TypeBase.h:5637
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5761
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5756
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5642
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4862
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4858
QualType getReturnType() const
Definition TypeBase.h:4893
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()
Definition Expr.h:5352
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:975
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:1052
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1088
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:509
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1135
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:859
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:4387
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4408
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:3703
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:1709
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1723
SourceLocation getSemiLoc() const
Definition Stmt.h:1720
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:1805
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:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6803
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5188
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2914
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1459
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1220
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:8431
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
void removeLocalVolatile()
Definition TypeBase.h:8547
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1185
void removeLocalConst()
Definition TypeBase.h:8539
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8552
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1684
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8477
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1448
@ 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:4342
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4428
field_range fields() const
Definition Decl.h:4545
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4420
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:616
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1027
@ 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:1110
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)
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:10404
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10409
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:13148
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:2728
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9460
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:7009
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
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:7045
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:15531
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:2383
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:8261
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:14060
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:6309
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:6497
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:1499
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:1326
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:3853
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3833
bool isUnion() const
Definition Decl.h:3943
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:6268
A container of type source information.
Definition TypeBase.h:8402
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:8413
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isBlockPointerType() const
Definition TypeBase.h:8688
bool isVoidType() const
Definition TypeBase.h:9034
bool isBooleanType() const
Definition TypeBase.h:9171
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9221
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:789
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2308
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2138
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:9201
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:2084
bool isVoidPointerType() const
Definition Type.cpp:714
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2470
bool isArrayType() const
Definition TypeBase.h:8767
bool isCharType() const
Definition Type.cpp:2158
bool isFunctionPointerType() const
Definition TypeBase.h:8735
bool isPointerType() const
Definition TypeBase.h:8668
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isScalarType() const
Definition TypeBase.h:9140
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:1923
bool isVariableArrayType() const
Definition TypeBase.h:8779
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2654
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isExtVectorType() const
Definition TypeBase.h:8811
bool isExtVectorBoolType() const
Definition TypeBase.h:8815
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2693
bool isBitIntType() const
Definition TypeBase.h:8943
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9003
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8791
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
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:2275
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3169
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2604
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9214
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isAtomicType() const
Definition TypeBase.h:8860
bool isFunctionProtoType() const
Definition TypeBase.h:2649
bool isMatrixType() const
Definition TypeBase.h:8831
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3149
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:2850
bool isUnscopedEnumerationType() const
Definition Type.cpp:2151
bool isObjCObjectType() const
Definition TypeBase.h:8851
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9314
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2558
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:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isObjCObjectPointerType() const
Definition TypeBase.h:8847
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2350
bool isStructureOrClassType() const
Definition Type.cpp:708
bool isVectorType() const
Definition TypeBase.h:8807
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isFloatingType() const
Definition Type.cpp:2342
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:2285
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2459
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
bool isObjCRetainableType() const
Definition Type.cpp:5369
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2616
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5100
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2681
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3577
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:1033
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1121
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3415
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:5583
Represents a variable declaration or definition.
Definition Decl.h:926
Represents a GCC generic vector type.
Definition TypeBase.h:4225
unsigned getNumElements() const
Definition TypeBase.h:4240
QualType getElementType() const
Definition TypeBase.h:4239
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2703
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:216
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1446
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1431
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1424
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1438
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2738
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1392
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1453
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:545
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
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:4186
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5977
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1761
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:5442
unsigned Indentation
The number of spaces to use to indent each line.
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13330
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13356
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13346
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13297
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6903
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2659
#define log2(__x)
Definition tgmath.h:970