clang 23.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any errors, even if we managed to build the
545 // call. We don't want to produce more than one error.
546 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1151 CallExpr *TheCall) {
1152 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1154 return;
1155
1156 bool UseDABAttr = false;
1157 const FunctionDecl *UseDecl = FD;
1158
1159 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1160 if (DABAttr) {
1161 UseDecl = DABAttr->getFunction();
1162 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1163 UseDABAttr = true;
1164 }
1165
1166 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1167
1168 if (!BuiltinID)
1169 return;
1170
1171 const TargetInfo &TI = getASTContext().getTargetInfo();
1172 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1173
1174 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1175 // If we refer to a diagnose_as_builtin attribute, we need to change the
1176 // argument index to refer to the arguments of the called function. Unless
1177 // the index is out of bounds, which presumably means it's a variadic
1178 // function.
1179 if (!UseDABAttr)
1180 return Index;
1181 unsigned DABIndices = DABAttr->argIndices_size();
1182 unsigned NewIndex = Index < DABIndices
1183 ? DABAttr->argIndices_begin()[Index]
1184 : Index - DABIndices + FD->getNumParams();
1185 if (NewIndex >= TheCall->getNumArgs())
1186 return std::nullopt;
1187 return NewIndex;
1188 };
1189
1190 auto ComputeExplicitObjectSizeArgument =
1191 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1192 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1193 if (!IndexOptional)
1194 return std::nullopt;
1195 unsigned NewIndex = *IndexOptional;
1196 Expr::EvalResult Result;
1197 Expr *SizeArg = TheCall->getArg(NewIndex);
1198 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1199 return std::nullopt;
1200 llvm::APSInt Integer = Result.Val.getInt();
1201 Integer.setIsUnsigned(true);
1202 return Integer;
1203 };
1204
1205 auto ComputeSizeArgument =
1206 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1207 // If the parameter has a pass_object_size attribute, then we should use its
1208 // (potentially) more strict checking mode. Otherwise, conservatively assume
1209 // type 0.
1210 int BOSType = 0;
1211 // This check can fail for variadic functions.
1212 if (Index < FD->getNumParams()) {
1213 if (const auto *POS =
1214 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1215 BOSType = POS->getType();
1216 }
1217
1218 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1219 if (!IndexOptional)
1220 return std::nullopt;
1221 unsigned NewIndex = *IndexOptional;
1222
1223 if (NewIndex >= TheCall->getNumArgs())
1224 return std::nullopt;
1225
1226 const Expr *ObjArg = TheCall->getArg(NewIndex);
1227 if (std::optional<uint64_t> ObjSize =
1228 ObjArg->tryEvaluateObjectSize(getASTContext(), BOSType)) {
1229 // Get the object size in the target's size_t width.
1230 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1231 }
1232 return std::nullopt;
1233 };
1234
1235 auto ComputeStrLenArgument =
1236 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1237 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1238 if (!IndexOptional)
1239 return std::nullopt;
1240 unsigned NewIndex = *IndexOptional;
1241
1242 const Expr *ObjArg = TheCall->getArg(NewIndex);
1243
1244 if (std::optional<uint64_t> Result =
1245 ObjArg->tryEvaluateStrLen(getASTContext())) {
1246 // Add 1 for null byte.
1247 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1248 }
1249 return std::nullopt;
1250 };
1251
1252 std::optional<llvm::APSInt> SourceSize;
1253 std::optional<llvm::APSInt> DestinationSize;
1254 unsigned DiagID = 0;
1255 bool IsChkVariant = false;
1256
1257 auto GetFunctionName = [&]() {
1258 std::string FunctionNameStr =
1259 getASTContext().BuiltinInfo.getName(BuiltinID);
1260 llvm::StringRef FunctionName = FunctionNameStr;
1261 // Skim off the details of whichever builtin was called to produce a better
1262 // diagnostic, as it's unlikely that the user wrote the __builtin
1263 // explicitly.
1264 if (IsChkVariant) {
1265 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1266 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1267 } else {
1268 FunctionName.consume_front("__builtin_");
1269 }
1270 return FunctionName.str();
1271 };
1272
1273 switch (BuiltinID) {
1274 default:
1275 return;
1276 case Builtin::BI__builtin_strcat:
1277 case Builtin::BIstrcat:
1278 case Builtin::BI__builtin_stpcpy:
1279 case Builtin::BIstpcpy:
1280 case Builtin::BI__builtin_strcpy:
1281 case Builtin::BIstrcpy: {
1282 DiagID = diag::warn_fortify_strlen_overflow;
1283 SourceSize = ComputeStrLenArgument(1);
1284 DestinationSize = ComputeSizeArgument(0);
1285 break;
1286 }
1287
1288 case Builtin::BI__builtin___strcat_chk:
1289 case Builtin::BI__builtin___stpcpy_chk:
1290 case Builtin::BI__builtin___strcpy_chk: {
1291 DiagID = diag::warn_fortify_strlen_overflow;
1292 SourceSize = ComputeStrLenArgument(1);
1293 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1294 IsChkVariant = true;
1295 break;
1296 }
1297
1298 case Builtin::BIscanf:
1299 case Builtin::BIfscanf:
1300 case Builtin::BIsscanf: {
1301 unsigned FormatIndex = 1;
1302 unsigned DataIndex = 2;
1303 if (BuiltinID == Builtin::BIscanf) {
1304 FormatIndex = 0;
1305 DataIndex = 1;
1306 }
1307
1308 const auto *FormatExpr =
1309 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1310
1311 StringRef FormatStrRef;
1312 size_t StrLen;
1313 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1314 return;
1315
1316 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1317 unsigned SourceSize) {
1318 DiagID = diag::warn_fortify_scanf_overflow;
1319 unsigned Index = ArgIndex + DataIndex;
1320 std::string FunctionName = GetFunctionName();
1321 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1322 PDiag(DiagID) << FunctionName << (Index + 1)
1323 << DestSize << SourceSize);
1324 };
1325
1326 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1327 return ComputeSizeArgument(Index + DataIndex);
1328 };
1329 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1330 const char *FormatBytes = FormatStrRef.data();
1332 FormatBytes + StrLen, getLangOpts(),
1333 Context.getTargetInfo());
1334
1335 // Unlike the other cases, in this one we have already issued the diagnostic
1336 // here, so no need to continue (because unlike the other cases, here the
1337 // diagnostic refers to the argument number).
1338 return;
1339 }
1340
1341 case Builtin::BIsprintf:
1342 case Builtin::BI__builtin___sprintf_chk: {
1343 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1344 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1345
1346 StringRef FormatStrRef;
1347 size_t StrLen;
1348 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1349 EstimateSizeFormatHandler H(FormatStrRef);
1350 const char *FormatBytes = FormatStrRef.data();
1352 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1353 Context.getTargetInfo(), false)) {
1354 DiagID = H.isKernelCompatible()
1355 ? diag::warn_format_overflow
1356 : diag::warn_format_overflow_non_kprintf;
1357 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1358 .extOrTrunc(SizeTypeWidth);
1359 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1360 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1361 IsChkVariant = true;
1362 } else {
1363 DestinationSize = ComputeSizeArgument(0);
1364 }
1365 break;
1366 }
1367 }
1368 return;
1369 }
1370 case Builtin::BI__builtin___memcpy_chk:
1371 case Builtin::BI__builtin___memmove_chk:
1372 case Builtin::BI__builtin___memset_chk:
1373 case Builtin::BI__builtin___strlcat_chk:
1374 case Builtin::BI__builtin___strlcpy_chk:
1375 case Builtin::BI__builtin___strncat_chk:
1376 case Builtin::BI__builtin___strncpy_chk:
1377 case Builtin::BI__builtin___stpncpy_chk:
1378 case Builtin::BI__builtin___memccpy_chk:
1379 case Builtin::BI__builtin___mempcpy_chk: {
1380 DiagID = diag::warn_builtin_chk_overflow;
1381 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1382 DestinationSize =
1383 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1384 IsChkVariant = true;
1385 break;
1386 }
1387
1388 case Builtin::BI__builtin___snprintf_chk:
1389 case Builtin::BI__builtin___vsnprintf_chk: {
1390 DiagID = diag::warn_builtin_chk_overflow;
1391 SourceSize = ComputeExplicitObjectSizeArgument(1);
1392 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1393 IsChkVariant = true;
1394 break;
1395 }
1396
1397 case Builtin::BIstrncat:
1398 case Builtin::BI__builtin_strncat:
1399 case Builtin::BIstrncpy:
1400 case Builtin::BI__builtin_strncpy:
1401 case Builtin::BIstpncpy:
1402 case Builtin::BI__builtin_stpncpy: {
1403 // Whether these functions overflow depends on the runtime strlen of the
1404 // string, not just the buffer size, so emitting the "always overflow"
1405 // diagnostic isn't quite right. We should still diagnose passing a buffer
1406 // size larger than the destination buffer though; this is a runtime abort
1407 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1408 DiagID = diag::warn_fortify_source_size_mismatch;
1409 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1410 DestinationSize = ComputeSizeArgument(0);
1411 break;
1412 }
1413
1414 case Builtin::BIbzero:
1415 case Builtin::BI__builtin_bzero:
1416 case Builtin::BImemcpy:
1417 case Builtin::BI__builtin_memcpy:
1418 case Builtin::BImemmove:
1419 case Builtin::BI__builtin_memmove:
1420 case Builtin::BImemset:
1421 case Builtin::BI__builtin_memset:
1422 case Builtin::BImempcpy:
1423 case Builtin::BI__builtin_mempcpy: {
1424 DiagID = diag::warn_fortify_source_overflow;
1425 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1426 DestinationSize = ComputeSizeArgument(0);
1427 break;
1428 }
1429 case Builtin::BIbcopy:
1430 case Builtin::BI__builtin_bcopy: {
1431 DiagID = diag::warn_fortify_source_overflow;
1432 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1433 DestinationSize = ComputeSizeArgument(1);
1434 break;
1435 }
1436 case Builtin::BIsnprintf:
1437 case Builtin::BI__builtin_snprintf:
1438 case Builtin::BIvsnprintf:
1439 case Builtin::BI__builtin_vsnprintf: {
1440 DiagID = diag::warn_fortify_source_size_mismatch;
1441 SourceSize = ComputeExplicitObjectSizeArgument(1);
1442 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1443 StringRef FormatStrRef;
1444 size_t StrLen;
1445 if (SourceSize &&
1446 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1447 EstimateSizeFormatHandler H(FormatStrRef);
1448 const char *FormatBytes = FormatStrRef.data();
1450 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1451 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1452 llvm::APSInt FormatSize =
1453 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1454 .extOrTrunc(SizeTypeWidth);
1455 if (FormatSize > *SourceSize && *SourceSize != 0) {
1456 unsigned TruncationDiagID =
1457 H.isKernelCompatible() ? diag::warn_format_truncation
1458 : diag::warn_format_truncation_non_kprintf;
1459 SmallString<16> SpecifiedSizeStr;
1460 SmallString<16> FormatSizeStr;
1461 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1462 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1463 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1464 PDiag(TruncationDiagID)
1465 << GetFunctionName() << SpecifiedSizeStr
1466 << FormatSizeStr);
1467 }
1468 }
1469 }
1470 DestinationSize = ComputeSizeArgument(0);
1471 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1472 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1473 IdentifierInfo *FnInfo = FD->getIdentifier();
1474 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1475 }
1476 }
1477
1478 if (!SourceSize || !DestinationSize ||
1479 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1480 return;
1481
1482 std::string FunctionName = GetFunctionName();
1483
1484 SmallString<16> DestinationStr;
1485 SmallString<16> SourceStr;
1486 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1487 SourceSize->toString(SourceStr, /*Radix=*/10);
1488 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1489 PDiag(DiagID)
1490 << FunctionName << DestinationStr << SourceStr);
1491}
1492
1493static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1494 Scope::ScopeFlags NeededScopeFlags,
1495 unsigned DiagID) {
1496 // Scopes aren't available during instantiation. Fortunately, builtin
1497 // functions cannot be template args so they cannot be formed through template
1498 // instantiation. Therefore checking once during the parse is sufficient.
1499 if (SemaRef.inTemplateInstantiation())
1500 return false;
1501
1502 Scope *S = SemaRef.getCurScope();
1503 while (S && !S->isSEHExceptScope())
1504 S = S->getParent();
1505 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1506 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1507 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1508 << DRE->getDecl()->getIdentifier();
1509 return true;
1510 }
1511
1512 return false;
1513}
1514
1515// In OpenCL, __builtin_alloca_* should return a pointer to address space
1516// that corresponds to the stack address space i.e private address space.
1517static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1518 QualType RT = TheCall->getType();
1519 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1520 "__builtin_alloca has invalid address space");
1521
1522 RT = RT->getPointeeType();
1524 TheCall->setType(S.Context.getPointerType(RT));
1525}
1526
1527static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1528 if (S.checkArgCountAtLeast(TheCall, 1))
1529 return true;
1530
1531 for (Expr *Arg : TheCall->arguments()) {
1532 // If argument is dependent on a template parameter, we can't resolve now.
1533 if (Arg->isTypeDependent() || Arg->isValueDependent())
1534 continue;
1535 // Reject void types.
1536 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1537 if (ArgTy->isVoidType())
1538 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1539 }
1540
1541 TheCall->setType(S.Context.getSizeType());
1542 return false;
1543}
1544
1545namespace {
1546enum PointerAuthOpKind {
1547 PAO_Strip,
1548 PAO_Sign,
1549 PAO_Auth,
1550 PAO_SignGeneric,
1551 PAO_Discriminator,
1552 PAO_BlendPointer,
1553 PAO_BlendInteger
1554};
1555}
1556
1558 if (getLangOpts().PointerAuthIntrinsics)
1559 return false;
1560
1561 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1562 return true;
1563}
1564
1565static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1567}
1568
1569static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1570 // Convert it to type 'int'.
1571 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1572 return true;
1573
1574 // Value-dependent expressions are okay; wait for template instantiation.
1575 if (Arg->isValueDependent())
1576 return false;
1577
1578 unsigned KeyValue;
1579 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1580}
1581
1583 // Attempt to constant-evaluate the expression.
1584 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1585 if (!KeyValue) {
1586 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1587 << 0 << Arg->getSourceRange();
1588 return true;
1589 }
1590
1591 // Ask the target to validate the key parameter.
1592 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1594 {
1595 llvm::raw_svector_ostream Str(Value);
1596 Str << *KeyValue;
1597 }
1598
1599 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1600 << Value << Arg->getSourceRange();
1601 return true;
1602 }
1603
1604 Result = KeyValue->getZExtValue();
1605 return false;
1606}
1607
1610 unsigned &IntVal) {
1611 if (!Arg) {
1612 IntVal = 0;
1613 return true;
1614 }
1615
1616 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1617 if (!Result) {
1618 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1619 return false;
1620 }
1621
1622 unsigned Max;
1623 bool IsAddrDiscArg = false;
1624
1625 switch (Kind) {
1627 Max = 1;
1628 IsAddrDiscArg = true;
1629 break;
1632 break;
1633 };
1634
1636 if (IsAddrDiscArg)
1637 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1638 << Result->getExtValue();
1639 else
1640 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1641 << Result->getExtValue() << Max;
1642
1643 return false;
1644 };
1645
1646 IntVal = Result->getZExtValue();
1647 return true;
1648}
1649
1650static std::pair<const ValueDecl *, CharUnits>
1652 // Must evaluate as a pointer.
1654 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1655 return {nullptr, CharUnits()};
1656
1657 const auto *BaseDecl =
1658 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1659 if (!BaseDecl)
1660 return {nullptr, CharUnits()};
1661
1662 return {BaseDecl, Result.Val.getLValueOffset()};
1663}
1664
1665static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1666 bool RequireConstant = false) {
1667 if (Arg->hasPlaceholderType()) {
1669 if (R.isInvalid())
1670 return true;
1671 Arg = R.get();
1672 }
1673
1674 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1675 return OpKind != PAO_BlendInteger;
1676 };
1677 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1678 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1679 OpKind == PAO_SignGeneric;
1680 };
1681
1682 // Require the value to have the right range of type.
1683 QualType ExpectedTy;
1684 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1685 ExpectedTy = Arg->getType().getUnqualifiedType();
1686 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1687 ExpectedTy = S.Context.VoidPtrTy;
1688 } else if (AllowsInteger(OpKind) &&
1690 ExpectedTy = S.Context.getUIntPtrType();
1691
1692 } else {
1693 // Diagnose the failures.
1694 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1695 << unsigned(OpKind == PAO_Discriminator ? 1
1696 : OpKind == PAO_BlendPointer ? 2
1697 : OpKind == PAO_BlendInteger ? 3
1698 : 0)
1699 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1700 << Arg->getType() << Arg->getSourceRange();
1701 return true;
1702 }
1703
1704 // Convert to that type. This should just be an lvalue-to-rvalue
1705 // conversion.
1706 if (convertArgumentToType(S, Arg, ExpectedTy))
1707 return true;
1708
1709 if (!RequireConstant) {
1710 // Warn about null pointers for non-generic sign and auth operations.
1711 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1713 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1714 ? diag::warn_ptrauth_sign_null_pointer
1715 : diag::warn_ptrauth_auth_null_pointer)
1716 << Arg->getSourceRange();
1717 }
1718
1719 return false;
1720 }
1721
1722 // Perform special checking on the arguments to ptrauth_sign_constant.
1723
1724 // The main argument.
1725 if (OpKind == PAO_Sign) {
1726 // Require the value we're signing to have a special form.
1727 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1728 bool Invalid;
1729
1730 // Must be rooted in a declaration reference.
1731 if (!BaseDecl)
1732 Invalid = true;
1733
1734 // If it's a function declaration, we can't have an offset.
1735 else if (isa<FunctionDecl>(BaseDecl))
1736 Invalid = !Offset.isZero();
1737
1738 // Otherwise we're fine.
1739 else
1740 Invalid = false;
1741
1742 if (Invalid)
1743 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1744 return Invalid;
1745 }
1746
1747 // The discriminator argument.
1748 assert(OpKind == PAO_Discriminator);
1749
1750 // Must be a pointer or integer or blend thereof.
1751 Expr *Pointer = nullptr;
1752 Expr *Integer = nullptr;
1753 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1754 if (Call->getBuiltinCallee() ==
1755 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1756 Pointer = Call->getArg(0);
1757 Integer = Call->getArg(1);
1758 }
1759 }
1760 if (!Pointer && !Integer) {
1761 if (Arg->getType()->isPointerType())
1762 Pointer = Arg;
1763 else
1764 Integer = Arg;
1765 }
1766
1767 // Check the pointer.
1768 bool Invalid = false;
1769 if (Pointer) {
1770 assert(Pointer->getType()->isPointerType());
1771
1772 // TODO: if we're initializing a global, check that the address is
1773 // somehow related to what we're initializing. This probably will
1774 // never really be feasible and we'll have to catch it at link-time.
1775 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1776 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1777 Invalid = true;
1778 }
1779
1780 // Check the integer.
1781 if (Integer) {
1782 assert(Integer->getType()->isIntegerType());
1783 if (!Integer->isEvaluatable(S.Context))
1784 Invalid = true;
1785 }
1786
1787 if (Invalid)
1788 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1789 return Invalid;
1790}
1791
1793 if (S.checkArgCount(Call, 2))
1794 return ExprError();
1796 return ExprError();
1797 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1798 checkPointerAuthKey(S, Call->getArgs()[1]))
1799 return ExprError();
1800
1801 Call->setType(Call->getArgs()[0]->getType());
1802 return Call;
1803}
1804
1806 if (S.checkArgCount(Call, 2))
1807 return ExprError();
1809 return ExprError();
1810 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1811 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1812 return ExprError();
1813
1814 Call->setType(S.Context.getUIntPtrType());
1815 return Call;
1816}
1817
1819 if (S.checkArgCount(Call, 2))
1820 return ExprError();
1822 return ExprError();
1823 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1824 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1825 return ExprError();
1826
1827 Call->setType(S.Context.getUIntPtrType());
1828 return Call;
1829}
1830
1832 PointerAuthOpKind OpKind,
1833 bool RequireConstant) {
1834 if (S.checkArgCount(Call, 3))
1835 return ExprError();
1837 return ExprError();
1838 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1839 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1840 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1841 RequireConstant))
1842 return ExprError();
1843
1844 Call->setType(Call->getArgs()[0]->getType());
1845 return Call;
1846}
1847
1849 if (S.checkArgCount(Call, 5))
1850 return ExprError();
1852 return ExprError();
1853 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1854 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1855 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1856 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1857 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1858 return ExprError();
1859
1860 Call->setType(Call->getArgs()[0]->getType());
1861 return Call;
1862}
1863
1865 if (S.checkArgCount(Call, 6))
1866 return ExprError();
1868 return ExprError();
1869 const Expr *AddendExpr = Call->getArg(5);
1870 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
1871 if (!AddendIsConstInt) {
1872 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
1873 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
1874 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1875 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
1876 << FDecl->getDeclName() << Arg->getSourceRange();
1877 }
1878 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1879 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1880 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1881 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1882 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
1883 !AddendIsConstInt)
1884 return ExprError();
1885
1886 Call->setType(Call->getArgs()[0]->getType());
1887 return Call;
1888}
1889
1892 return ExprError();
1893
1894 // We've already performed normal call type-checking.
1895 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
1896
1897 // Operand must be an ordinary or UTF-8 string literal.
1898 const auto *Literal = dyn_cast<StringLiteral>(Arg);
1899 if (!Literal || Literal->getCharByteWidth() != 1) {
1900 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
1901 << (Literal ? 1 : 0) << Arg->getSourceRange();
1902 return ExprError();
1903 }
1904
1905 return Call;
1906}
1907
1909 if (S.checkArgCount(Call, 1))
1910 return ExprError();
1911 Expr *FirstArg = Call->getArg(0);
1912 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
1913 if (FirstValue.isInvalid())
1914 return ExprError();
1915 Call->setArg(0, FirstValue.get());
1916 QualType FirstArgType = FirstArg->getType();
1917 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1918 FirstArgType = S.Context.getDecayedType(FirstArgType);
1919
1920 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1921 if (!FirstArgRecord) {
1922 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1923 << /*isPolymorphic=*/0 << FirstArgType;
1924 return ExprError();
1925 }
1926 if (S.RequireCompleteType(
1927 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
1928 diag::err_get_vtable_pointer_requires_complete_type)) {
1929 return ExprError();
1930 }
1931
1932 if (!FirstArgRecord->isPolymorphic()) {
1933 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
1934 << /*isPolymorphic=*/1 << FirstArgRecord;
1935 return ExprError();
1936 }
1938 Call->setType(ReturnType);
1939 return Call;
1940}
1941
1943 if (S.checkArgCount(TheCall, 1))
1944 return ExprError();
1945
1946 // Compute __builtin_launder's parameter type from the argument.
1947 // The parameter type is:
1948 // * The type of the argument if it's not an array or function type,
1949 // Otherwise,
1950 // * The decayed argument type.
1951 QualType ParamTy = [&]() {
1952 QualType ArgTy = TheCall->getArg(0)->getType();
1953 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1954 return S.Context.getPointerType(Ty->getElementType());
1955 if (ArgTy->isFunctionType()) {
1956 return S.Context.getPointerType(ArgTy);
1957 }
1958 return ArgTy;
1959 }();
1960
1961 TheCall->setType(ParamTy);
1962
1963 auto DiagSelect = [&]() -> std::optional<unsigned> {
1964 if (!ParamTy->isPointerType())
1965 return 0;
1966 if (ParamTy->isFunctionPointerType())
1967 return 1;
1968 if (ParamTy->isVoidPointerType())
1969 return 2;
1970 return std::optional<unsigned>{};
1971 }();
1972 if (DiagSelect) {
1973 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1974 << *DiagSelect << TheCall->getSourceRange();
1975 return ExprError();
1976 }
1977
1978 // We either have an incomplete class type, or we have a class template
1979 // whose instantiation has not been forced. Example:
1980 //
1981 // template <class T> struct Foo { T value; };
1982 // Foo<int> *p = nullptr;
1983 // auto *d = __builtin_launder(p);
1984 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1985 diag::err_incomplete_type))
1986 return ExprError();
1987
1988 assert(ParamTy->getPointeeType()->isObjectType() &&
1989 "Unhandled non-object pointer case");
1990
1991 InitializedEntity Entity =
1993 ExprResult Arg =
1994 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1995 if (Arg.isInvalid())
1996 return ExprError();
1997 TheCall->setArg(0, Arg.get());
1998
1999 return TheCall;
2000}
2001
2003 if (S.checkArgCount(TheCall, 1))
2004 return ExprError();
2005
2007 if (Arg.isInvalid())
2008 return ExprError();
2009 QualType ParamTy = Arg.get()->getType();
2010 TheCall->setArg(0, Arg.get());
2011 TheCall->setType(S.Context.BoolTy);
2012
2013 // Only accept pointers to objects as arguments, which should have object
2014 // pointer or void pointer types.
2015 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2016 // LWG4138: Function pointer types not allowed
2017 if (PT->getPointeeType()->isFunctionType()) {
2018 S.Diag(TheCall->getArg(0)->getExprLoc(),
2019 diag::err_builtin_is_within_lifetime_invalid_arg)
2020 << 1;
2021 return ExprError();
2022 }
2023 // Disallow VLAs too since those shouldn't be able to
2024 // be a template parameter for `std::is_within_lifetime`
2025 if (PT->getPointeeType()->isVariableArrayType()) {
2026 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2027 << 1 << "__builtin_is_within_lifetime";
2028 return ExprError();
2029 }
2030 } else {
2031 S.Diag(TheCall->getArg(0)->getExprLoc(),
2032 diag::err_builtin_is_within_lifetime_invalid_arg)
2033 << 0;
2034 return ExprError();
2035 }
2036 return TheCall;
2037}
2038
2040 if (S.checkArgCount(TheCall, 3))
2041 return ExprError();
2042
2043 QualType Dest = TheCall->getArg(0)->getType();
2044 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2045 S.Diag(TheCall->getArg(0)->getExprLoc(),
2046 diag::err_builtin_trivially_relocate_invalid_arg_type)
2047 << /*a pointer*/ 0;
2048 return ExprError();
2049 }
2050
2051 QualType T = Dest->getPointeeType();
2052 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2053 diag::err_incomplete_type))
2054 return ExprError();
2055
2056 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2057 T->isIncompleteArrayType()) {
2058 S.Diag(TheCall->getArg(0)->getExprLoc(),
2059 diag::err_builtin_trivially_relocate_invalid_arg_type)
2060 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2061 return ExprError();
2062 }
2063
2064 TheCall->setType(Dest);
2065
2066 QualType Src = TheCall->getArg(1)->getType();
2067 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2068 S.Diag(TheCall->getArg(1)->getExprLoc(),
2069 diag::err_builtin_trivially_relocate_invalid_arg_type)
2070 << /*the same*/ 3;
2071 return ExprError();
2072 }
2073
2074 Expr *SizeExpr = TheCall->getArg(2);
2075 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2076 if (Size.isInvalid())
2077 return ExprError();
2078
2079 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2080 if (Size.isInvalid())
2081 return ExprError();
2082 SizeExpr = Size.get();
2083 TheCall->setArg(2, SizeExpr);
2084
2085 return TheCall;
2086}
2087
2088// Emit an error and return true if the current object format type is in the
2089// list of unsupported types.
2091 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2092 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2093 llvm::Triple::ObjectFormatType CurObjFormat =
2094 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2095 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2096 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2097 << TheCall->getSourceRange();
2098 return true;
2099 }
2100 return false;
2101}
2102
2103// Emit an error and return true if the current architecture is not in the list
2104// of supported architectures.
2105static bool
2107 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2108 llvm::Triple::ArchType CurArch =
2109 S.getASTContext().getTargetInfo().getTriple().getArch();
2110 if (llvm::is_contained(SupportedArchs, CurArch))
2111 return false;
2112 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2113 << TheCall->getSourceRange();
2114 return true;
2115}
2116
2117static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2118 SourceLocation CallSiteLoc);
2119
2120bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2121 CallExpr *TheCall) {
2122 switch (TI.getTriple().getArch()) {
2123 default:
2124 // Some builtins don't require additional checking, so just consider these
2125 // acceptable.
2126 return false;
2127 case llvm::Triple::arm:
2128 case llvm::Triple::armeb:
2129 case llvm::Triple::thumb:
2130 case llvm::Triple::thumbeb:
2131 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2132 case llvm::Triple::aarch64:
2133 case llvm::Triple::aarch64_32:
2134 case llvm::Triple::aarch64_be:
2135 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2136 case llvm::Triple::bpfeb:
2137 case llvm::Triple::bpfel:
2138 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2139 case llvm::Triple::dxil:
2140 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2141 case llvm::Triple::hexagon:
2142 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2143 case llvm::Triple::mips:
2144 case llvm::Triple::mipsel:
2145 case llvm::Triple::mips64:
2146 case llvm::Triple::mips64el:
2147 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2148 case llvm::Triple::spirv:
2149 case llvm::Triple::spirv32:
2150 case llvm::Triple::spirv64:
2151 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2152 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2153 return false;
2154 case llvm::Triple::systemz:
2155 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2156 case llvm::Triple::x86:
2157 case llvm::Triple::x86_64:
2158 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2159 case llvm::Triple::ppc:
2160 case llvm::Triple::ppcle:
2161 case llvm::Triple::ppc64:
2162 case llvm::Triple::ppc64le:
2163 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2164 case llvm::Triple::amdgcn:
2165 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2166 case llvm::Triple::riscv32:
2167 case llvm::Triple::riscv64:
2168 case llvm::Triple::riscv32be:
2169 case llvm::Triple::riscv64be:
2170 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2171 case llvm::Triple::loongarch32:
2172 case llvm::Triple::loongarch64:
2173 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2174 TheCall);
2175 case llvm::Triple::wasm32:
2176 case llvm::Triple::wasm64:
2177 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2178 case llvm::Triple::nvptx:
2179 case llvm::Triple::nvptx64:
2180 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2181 }
2182}
2183
2185 return T->isDependentType() ||
2186 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2187}
2188
2189// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2190// not a valid type, emit an error message and return true. Otherwise return
2191// false.
2192static bool
2195 int ArgOrdinal) {
2196 clang::QualType EltTy =
2197 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2198 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2199 : ArgTy;
2200
2201 switch (ArgTyRestr) {
2203 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(ArgTy)) {
2204 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2205 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2206 << ArgTy;
2207 }
2208 break;
2210 if (!EltTy->isRealFloatingType()) {
2211 // FIXME: make diagnostic's wording correct for matrices
2212 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2213 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2214 << /* floating-point */ 1 << ArgTy;
2215 }
2216 break;
2218 if (!EltTy->isIntegerType()) {
2219 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2220 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2221 << /* no fp */ 0 << ArgTy;
2222 }
2223 break;
2225 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2226 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2227 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2228 << /* or fp */ 1 << ArgTy;
2229 }
2230 break;
2231 }
2232
2233 return false;
2234}
2235
2236/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2237/// This checks that the target supports the builtin and that the string
2238/// argument is constant and valid.
2239static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2240 const TargetInfo *AuxTI, unsigned BuiltinID) {
2241 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2242 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2243 "Expecting __builtin_cpu_...");
2244
2245 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2246 const TargetInfo *TheTI = &TI;
2247 auto SupportsBI = [=](const TargetInfo *TInfo) {
2248 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2249 (!IsCPUSupports && TInfo->supportsCpuIs()));
2250 };
2251 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2252 TheTI = AuxTI;
2253
2254 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2255 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2256 return S.Diag(TheCall->getBeginLoc(),
2257 TI.getTriple().isOSAIX()
2258 ? diag::err_builtin_aix_os_unsupported
2259 : diag::err_builtin_target_unsupported)
2260 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2261
2262 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2263 // Check if the argument is a string literal.
2264 if (!isa<StringLiteral>(Arg))
2265 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2266 << Arg->getSourceRange();
2267
2268 // Check the contents of the string.
2269 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2270 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2271 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2272 << Arg->getSourceRange();
2273 return false;
2274 }
2275 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2276 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2277 << Arg->getSourceRange();
2278 return false;
2279}
2280
2281/// Checks that __builtin_bswapg was called with a single argument, which is an
2282/// unsigned integer, and overrides the return value type to the integer type.
2283static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2284 if (S.checkArgCount(TheCall, 1))
2285 return true;
2286 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2287 if (ArgRes.isInvalid())
2288 return true;
2289
2290 Expr *Arg = ArgRes.get();
2291 TheCall->setArg(0, Arg);
2292 if (Arg->isTypeDependent())
2293 return false;
2294
2295 QualType ArgTy = Arg->getType();
2296
2297 if (!ArgTy->isIntegerType()) {
2298 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2299 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2300 << ArgTy;
2301 return true;
2302 }
2303 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2304 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2305 BT->getNumBits() != 1) {
2306 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2307 << ArgTy << BT->getNumBits();
2308 return true;
2309 }
2310 }
2311 TheCall->setType(ArgTy);
2312 return false;
2313}
2314
2315/// Checks that __builtin_bitreverseg was called with a single argument, which
2316/// is an integer
2317static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2318 if (S.checkArgCount(TheCall, 1))
2319 return true;
2320 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2321 if (ArgRes.isInvalid())
2322 return true;
2323
2324 Expr *Arg = ArgRes.get();
2325 TheCall->setArg(0, Arg);
2326 if (Arg->isTypeDependent())
2327 return false;
2328
2329 QualType ArgTy = Arg->getType();
2330
2331 if (!ArgTy->isIntegerType()) {
2332 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2333 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2334 << ArgTy;
2335 return true;
2336 }
2337 TheCall->setType(ArgTy);
2338 return false;
2339}
2340
2341/// Checks that __builtin_popcountg was called with a single argument, which is
2342/// an unsigned integer.
2343static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2344 if (S.checkArgCount(TheCall, 1))
2345 return true;
2346
2347 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2348 if (ArgRes.isInvalid())
2349 return true;
2350
2351 Expr *Arg = ArgRes.get();
2352 TheCall->setArg(0, Arg);
2353
2354 QualType ArgTy = Arg->getType();
2355
2356 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2357 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2358 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2359 << ArgTy;
2360 return true;
2361 }
2362 return false;
2363}
2364
2365/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2366/// argument and return either int, bool, or the argument type.
2367static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2368 QualType ReturnType) {
2369 if (S.checkArgCount(TheCall, 1))
2370 return true;
2371
2372 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2373 if (ArgRes.isInvalid())
2374 return true;
2375
2376 Expr *Arg = ArgRes.get();
2377 TheCall->setArg(0, Arg);
2378
2379 QualType ArgTy = Arg->getType();
2380 // C23 stdbit.h functions do not permit bool or enumeration types.
2381 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2382 return S.Diag(Arg->getBeginLoc(),
2383 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2384 << 1 /*1st argument*/ << ArgTy;
2385 if (!ArgTy->isUnsignedIntegerType())
2386 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2387 << 1 /*1st argument*/ << ArgTy;
2388
2389 // For builtins returning unsigned int, verify the argument's bit width fits.
2390 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2391 // produce a count that overflows the return type.
2392 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2393 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2394 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2395 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2396 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2397 << ArgTy;
2398 }
2399
2400 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2401 return false;
2402}
2403
2404/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2405/// an unsigned integer, and an optional second argument, which is promoted to
2406/// an 'int'.
2407static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2408 if (S.checkArgCountRange(TheCall, 1, 2))
2409 return true;
2410
2411 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2412 if (Arg0Res.isInvalid())
2413 return true;
2414
2415 Expr *Arg0 = Arg0Res.get();
2416 TheCall->setArg(0, Arg0);
2417
2418 QualType Arg0Ty = Arg0->getType();
2419
2420 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2421 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2422 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2423 << Arg0Ty;
2424 return true;
2425 }
2426
2427 if (TheCall->getNumArgs() > 1) {
2428 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2429 if (Arg1Res.isInvalid())
2430 return true;
2431
2432 Expr *Arg1 = Arg1Res.get();
2433 TheCall->setArg(1, Arg1);
2434
2435 QualType Arg1Ty = Arg1->getType();
2436
2437 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2438 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2439 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2440 return true;
2441 }
2442 }
2443
2444 return false;
2445}
2446
2448 unsigned ArgIndex;
2449 bool OnlyUnsigned;
2450
2452 QualType T) {
2453 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2454 << ArgIndex << /*scalar*/ 1
2455 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2456 << /*no fp*/ 0 << T;
2457 }
2458
2459public:
2460 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2461 : ContextualImplicitConverter(/*Suppress=*/false,
2462 /*SuppressConversion=*/true),
2463 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2464
2465 bool match(QualType T) override {
2466 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2467 }
2468
2470 QualType T) override {
2471 return emitError(S, Loc, T);
2472 }
2473
2475 QualType T) override {
2476 return emitError(S, Loc, T);
2477 }
2478
2480 QualType T,
2481 QualType ConvTy) override {
2482 return emitError(S, Loc, T);
2483 }
2484
2486 QualType ConvTy) override {
2487 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2488 }
2489
2491 QualType T) override {
2492 return emitError(S, Loc, T);
2493 }
2494
2496 QualType ConvTy) override {
2497 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2498 }
2499
2501 QualType T,
2502 QualType ConvTy) override {
2503 llvm_unreachable("conversion functions are permitted");
2504 }
2505};
2506
2507/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2508/// arguments, that the first argument is an unsigned integer type, and that
2509/// the second argument is an integer type.
2510static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2511 if (S.checkArgCount(TheCall, 2))
2512 return true;
2513
2514 // First argument (value to rotate) must be unsigned integer type.
2515 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2517 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2518 if (Arg0Res.isInvalid())
2519 return true;
2520
2521 Expr *Arg0 = Arg0Res.get();
2522 TheCall->setArg(0, Arg0);
2523
2524 QualType Arg0Ty = Arg0->getType();
2525 if (!Arg0Ty->isUnsignedIntegerType())
2526 return true;
2527
2528 // Second argument (rotation count) must be integer type.
2529 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2531 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2532 if (Arg1Res.isInvalid())
2533 return true;
2534
2535 Expr *Arg1 = Arg1Res.get();
2536 TheCall->setArg(1, Arg1);
2537
2538 QualType Arg1Ty = Arg1->getType();
2539 if (!Arg1Ty->isIntegerType())
2540 return true;
2541
2542 TheCall->setType(Arg0Ty);
2543 return false;
2544}
2545
2546static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2547 unsigned Pos, bool AllowConst,
2548 bool AllowAS) {
2549 QualType MaskTy = MaskArg->getType();
2550 if (!MaskTy->isExtVectorBoolType())
2551 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2552 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2553 << MaskTy;
2554
2555 QualType PtrTy = PtrArg->getType();
2556 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2557 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2558 << Pos << "scalar pointer";
2559
2560 QualType PointeeTy = PtrTy->getPointeeType();
2561 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2562 (!AllowConst && PointeeTy.isConstQualified()) ||
2563 (!AllowAS && PointeeTy.hasAddressSpace())) {
2566 return S.Diag(PtrArg->getExprLoc(),
2567 diag::err_typecheck_convert_incompatible)
2568 << PtrTy << Target << /*different qualifiers=*/5
2569 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2570 << PtrTy << Target;
2571 }
2572 return false;
2573}
2574
2575static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2576 bool TypeDependent = false;
2577 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2578 ExprResult Converted =
2580 if (Converted.isInvalid())
2581 return true;
2582 TheCall->setArg(Arg, Converted.get());
2583 TypeDependent |= Converted.get()->isTypeDependent();
2584 }
2585
2586 if (TypeDependent)
2587 TheCall->setType(S.Context.DependentTy);
2588 return false;
2589}
2590
2592 if (S.checkArgCountRange(TheCall, 2, 3))
2593 return ExprError();
2594
2595 if (ConvertMaskedBuiltinArgs(S, TheCall))
2596 return ExprError();
2597
2598 Expr *MaskArg = TheCall->getArg(0);
2599 Expr *PtrArg = TheCall->getArg(1);
2600 if (TheCall->isTypeDependent())
2601 return TheCall;
2602
2603 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2604 TheCall->getBuiltinCallee() ==
2605 Builtin::BI__builtin_masked_load))
2606 return ExprError();
2607
2608 QualType MaskTy = MaskArg->getType();
2609 QualType PtrTy = PtrArg->getType();
2610 QualType PointeeTy = PtrTy->getPointeeType();
2611 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2612
2614 MaskVecTy->getNumElements());
2615 if (TheCall->getNumArgs() == 3) {
2616 Expr *PassThruArg = TheCall->getArg(2);
2617 QualType PassThruTy = PassThruArg->getType();
2618 if (!S.Context.hasSameType(PassThruTy, RetTy))
2619 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2620 << /* third argument */ 3 << RetTy;
2621 }
2622
2623 TheCall->setType(RetTy);
2624 return TheCall;
2625}
2626
2628 if (S.checkArgCount(TheCall, 3))
2629 return ExprError();
2630
2631 if (ConvertMaskedBuiltinArgs(S, TheCall))
2632 return ExprError();
2633
2634 Expr *MaskArg = TheCall->getArg(0);
2635 Expr *ValArg = TheCall->getArg(1);
2636 Expr *PtrArg = TheCall->getArg(2);
2637 if (TheCall->isTypeDependent())
2638 return TheCall;
2639
2640 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2641 TheCall->getBuiltinCallee() ==
2642 Builtin::BI__builtin_masked_store))
2643 return ExprError();
2644
2645 QualType MaskTy = MaskArg->getType();
2646 QualType PtrTy = PtrArg->getType();
2647 QualType ValTy = ValArg->getType();
2648 if (!ValTy->isVectorType())
2649 return ExprError(
2650 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2651 << 2 << "vector");
2652
2653 QualType PointeeTy = PtrTy->getPointeeType();
2654 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2655 QualType MemoryTy = S.Context.getExtVectorType(PointeeTy.getUnqualifiedType(),
2656 MaskVecTy->getNumElements());
2657 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(),
2658 MemoryTy.getUnqualifiedType()))
2659 return ExprError(S.Diag(TheCall->getBeginLoc(),
2660 diag::err_vec_builtin_incompatible_vector)
2661 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2662 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2663 TheCall->getArg(1)->getEndLoc()));
2664
2665 TheCall->setType(S.Context.VoidTy);
2666 return TheCall;
2667}
2668
2670 if (S.checkArgCountRange(TheCall, 3, 4))
2671 return ExprError();
2672
2673 if (ConvertMaskedBuiltinArgs(S, TheCall))
2674 return ExprError();
2675
2676 Expr *MaskArg = TheCall->getArg(0);
2677 Expr *IdxArg = TheCall->getArg(1);
2678 Expr *PtrArg = TheCall->getArg(2);
2679 if (TheCall->isTypeDependent())
2680 return TheCall;
2681
2682 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2683 /*AllowAS=*/true))
2684 return ExprError();
2685
2686 QualType IdxTy = IdxArg->getType();
2687 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2688 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2689 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2690 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2691 << IdxTy;
2692
2693 QualType MaskTy = MaskArg->getType();
2694 QualType PtrTy = PtrArg->getType();
2695 QualType PointeeTy = PtrTy->getPointeeType();
2696 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2697 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2698 return ExprError(
2699 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2701 TheCall->getBuiltinCallee())
2702 << MaskTy << IdxTy);
2703
2705 MaskVecTy->getNumElements());
2706 if (TheCall->getNumArgs() == 4) {
2707 Expr *PassThruArg = TheCall->getArg(3);
2708 QualType PassThruTy = PassThruArg->getType();
2709 if (!S.Context.hasSameType(PassThruTy, RetTy))
2710 return S.Diag(PassThruArg->getExprLoc(),
2711 diag::err_vec_masked_load_store_ptr)
2712 << /* fourth argument */ 4 << RetTy;
2713 }
2714
2715 TheCall->setType(RetTy);
2716 return TheCall;
2717}
2718
2720 if (S.checkArgCount(TheCall, 4))
2721 return ExprError();
2722
2723 if (ConvertMaskedBuiltinArgs(S, TheCall))
2724 return ExprError();
2725
2726 Expr *MaskArg = TheCall->getArg(0);
2727 Expr *IdxArg = TheCall->getArg(1);
2728 Expr *ValArg = TheCall->getArg(2);
2729 Expr *PtrArg = TheCall->getArg(3);
2730 if (TheCall->isTypeDependent())
2731 return TheCall;
2732
2733 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2734 /*AllowAS=*/true))
2735 return ExprError();
2736
2737 QualType IdxTy = IdxArg->getType();
2738 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2739 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2740 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2741 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2742 << IdxTy;
2743
2744 QualType ValTy = ValArg->getType();
2745 QualType MaskTy = MaskArg->getType();
2746 QualType PtrTy = PtrArg->getType();
2747 QualType PointeeTy = PtrTy->getPointeeType();
2748
2749 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2750 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2751 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2752 return ExprError(
2753 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2755 TheCall->getBuiltinCallee())
2756 << MaskTy << IdxTy);
2757 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2758 return ExprError(
2759 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2761 TheCall->getBuiltinCallee())
2762 << MaskTy << ValTy);
2763
2765 MaskVecTy->getNumElements());
2766 if (!S.Context.hasSameType(ValTy.getUnqualifiedType(), ArgTy))
2767 return ExprError(S.Diag(TheCall->getBeginLoc(),
2768 diag::err_vec_builtin_incompatible_vector)
2769 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2770 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2771 TheCall->getArg(1)->getEndLoc()));
2772
2773 TheCall->setType(S.Context.VoidTy);
2774 return TheCall;
2775}
2776
2778 SourceLocation Loc = TheCall->getBeginLoc();
2779 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2780 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2781
2782 if (Args.size() == 0) {
2783 S.Diag(TheCall->getBeginLoc(),
2784 diag::err_typecheck_call_too_few_args_at_least)
2785 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2786 << /*is_non_object=*/0 << TheCall->getSourceRange();
2787 return ExprError();
2788 }
2789
2790 QualType FuncT = Args[0]->getType();
2791
2792 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2793 if (Args.size() < 2) {
2794 S.Diag(TheCall->getBeginLoc(),
2795 diag::err_typecheck_call_too_few_args_at_least)
2796 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2797 << /*is_non_object=*/0 << TheCall->getSourceRange();
2798 return ExprError();
2799 }
2800
2801 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2802 QualType ObjectT = Args[1]->getType();
2803
2804 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2805 return ExprError();
2806
2807 ExprResult ObjectArg = [&]() -> ExprResult {
2808 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2809 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2810 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2811 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2812 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2813 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2814 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2815 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2816 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2817 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2818 return Args[1];
2819 }
2820
2821 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2822 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2823 // reference_wrapper;
2824 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2825 if (RD->isInStdNamespace() &&
2826 RD->getDeclName().getAsString() == "reference_wrapper") {
2827 CXXScopeSpec SS;
2828 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2829 UnqualifiedId GetID;
2830 GetID.setIdentifier(GetName, Loc);
2831
2833 S.getCurScope(), Args[1], Loc, tok::period, SS,
2834 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2835
2836 if (MemExpr.isInvalid())
2837 return ExprError();
2838
2839 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
2840 }
2841 }
2842
2843 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2844 // class T and t1 does not satisfy the previous two items;
2845
2846 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
2847 }();
2848
2849 if (ObjectArg.isInvalid())
2850 return ExprError();
2851
2852 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
2853 tok::periodstar, ObjectArg.get(), Args[0]);
2854 if (BinOp.isInvalid())
2855 return ExprError();
2856
2857 if (MPT->isMemberDataPointer())
2858 return BinOp;
2859
2860 auto *MemCall = new (S.Context)
2862
2863 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
2864 Args.drop_front(2), TheCall->getRParenLoc());
2865 }
2866 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
2867 Args.drop_front(), TheCall->getRParenLoc());
2868}
2869
2870// Performs a similar job to Sema::UsualUnaryConversions, but without any
2871// implicit promotion of integral/enumeration types.
2873 // First, convert to an r-value.
2875 if (Res.isInvalid())
2876 return ExprError();
2877
2878 // Promote floating-point types.
2879 return S.UsualUnaryFPConversions(Res.get());
2880}
2881
2883 if (const auto *TyA = VecTy->getAs<VectorType>())
2884 return TyA->getElementType();
2885 if (VecTy->isSizelessVectorType())
2886 return VecTy->getSizelessVectorEltType(Context);
2887 return QualType();
2888}
2889
2891Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2892 CallExpr *TheCall) {
2893 ExprResult TheCallResult(TheCall);
2894
2895 // Find out if any arguments are required to be integer constant expressions.
2896 unsigned ICEArguments = 0;
2898 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2900 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2901
2902 // If any arguments are required to be ICE's, check and diagnose.
2903 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2904 // Skip arguments not required to be ICE's.
2905 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2906
2907 llvm::APSInt Result;
2908 // If we don't have enough arguments, continue so we can issue better
2909 // diagnostic in checkArgCount(...)
2910 if (ArgNo < TheCall->getNumArgs() &&
2911 BuiltinConstantArg(TheCall, ArgNo, Result))
2912 return true;
2913 ICEArguments &= ~(1 << ArgNo);
2914 }
2915
2916 FPOptions FPO;
2917 switch (BuiltinID) {
2918 case Builtin::BI__builtin_cpu_supports:
2919 case Builtin::BI__builtin_cpu_is:
2920 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2921 Context.getAuxTargetInfo(), BuiltinID))
2922 return ExprError();
2923 break;
2924 case Builtin::BI__builtin_cpu_init:
2925 if (!Context.getTargetInfo().supportsCpuInit()) {
2926 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2927 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2928 return ExprError();
2929 }
2930 break;
2931 case Builtin::BI__builtin___CFStringMakeConstantString:
2932 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2933 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2935 *this, BuiltinID, TheCall,
2936 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2937 return ExprError();
2938 assert(TheCall->getNumArgs() == 1 &&
2939 "Wrong # arguments to builtin CFStringMakeConstantString");
2940 if (ObjC().CheckObjCString(TheCall->getArg(0)))
2941 return ExprError();
2942 break;
2943 case Builtin::BI__builtin_ms_va_start:
2944 case Builtin::BI__builtin_stdarg_start:
2945 case Builtin::BI__builtin_va_start:
2946 case Builtin::BI__builtin_c23_va_start:
2947 if (BuiltinVAStart(BuiltinID, TheCall))
2948 return ExprError();
2949 break;
2950 case Builtin::BI__va_start: {
2951 switch (Context.getTargetInfo().getTriple().getArch()) {
2952 case llvm::Triple::aarch64:
2953 case llvm::Triple::arm:
2954 case llvm::Triple::thumb:
2955 if (BuiltinVAStartARMMicrosoft(TheCall))
2956 return ExprError();
2957 break;
2958 default:
2959 if (BuiltinVAStart(BuiltinID, TheCall))
2960 return ExprError();
2961 break;
2962 }
2963 break;
2964 }
2965
2966 // The acquire, release, and no fence variants are ARM and AArch64 only.
2967 case Builtin::BI_interlockedbittestandset_acq:
2968 case Builtin::BI_interlockedbittestandset_rel:
2969 case Builtin::BI_interlockedbittestandset_nf:
2970 case Builtin::BI_interlockedbittestandreset_acq:
2971 case Builtin::BI_interlockedbittestandreset_rel:
2972 case Builtin::BI_interlockedbittestandreset_nf:
2974 *this, TheCall,
2975 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2976 return ExprError();
2977 break;
2978
2979 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2980 case Builtin::BI_bittest64:
2981 case Builtin::BI_bittestandcomplement64:
2982 case Builtin::BI_bittestandreset64:
2983 case Builtin::BI_bittestandset64:
2984 case Builtin::BI_interlockedbittestandreset64:
2985 case Builtin::BI_interlockedbittestandset64:
2987 *this, TheCall,
2988 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2989 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2990 return ExprError();
2991 break;
2992
2993 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2994 case Builtin::BI_interlockedbittestandreset64_acq:
2995 case Builtin::BI_interlockedbittestandreset64_rel:
2996 case Builtin::BI_interlockedbittestandreset64_nf:
2997 case Builtin::BI_interlockedbittestandset64_acq:
2998 case Builtin::BI_interlockedbittestandset64_rel:
2999 case Builtin::BI_interlockedbittestandset64_nf:
3000 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3001 return ExprError();
3002 break;
3003
3004 case Builtin::BI__builtin_set_flt_rounds:
3006 *this, TheCall,
3007 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3008 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
3009 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3010 llvm::Triple::ppc64le}))
3011 return ExprError();
3012 break;
3013
3014 case Builtin::BI__builtin_isgreater:
3015 case Builtin::BI__builtin_isgreaterequal:
3016 case Builtin::BI__builtin_isless:
3017 case Builtin::BI__builtin_islessequal:
3018 case Builtin::BI__builtin_islessgreater:
3019 case Builtin::BI__builtin_isunordered:
3020 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3021 return ExprError();
3022 break;
3023 case Builtin::BI__builtin_fpclassify:
3024 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3025 return ExprError();
3026 break;
3027 case Builtin::BI__builtin_isfpclass:
3028 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3029 return ExprError();
3030 break;
3031 case Builtin::BI__builtin_isfinite:
3032 case Builtin::BI__builtin_isinf:
3033 case Builtin::BI__builtin_isinf_sign:
3034 case Builtin::BI__builtin_isnan:
3035 case Builtin::BI__builtin_issignaling:
3036 case Builtin::BI__builtin_isnormal:
3037 case Builtin::BI__builtin_issubnormal:
3038 case Builtin::BI__builtin_iszero:
3039 case Builtin::BI__builtin_signbit:
3040 case Builtin::BI__builtin_signbitf:
3041 case Builtin::BI__builtin_signbitl:
3042 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3043 return ExprError();
3044 break;
3045 case Builtin::BI__builtin_shufflevector:
3046 return BuiltinShuffleVector(TheCall);
3047 // TheCall will be freed by the smart pointer here, but that's fine, since
3048 // BuiltinShuffleVector guts it, but then doesn't release it.
3049 case Builtin::BI__builtin_masked_load:
3050 case Builtin::BI__builtin_masked_expand_load:
3051 return BuiltinMaskedLoad(*this, TheCall);
3052 case Builtin::BI__builtin_masked_store:
3053 case Builtin::BI__builtin_masked_compress_store:
3054 return BuiltinMaskedStore(*this, TheCall);
3055 case Builtin::BI__builtin_masked_gather:
3056 return BuiltinMaskedGather(*this, TheCall);
3057 case Builtin::BI__builtin_masked_scatter:
3058 return BuiltinMaskedScatter(*this, TheCall);
3059 case Builtin::BI__builtin_invoke:
3060 return BuiltinInvoke(*this, TheCall);
3061 case Builtin::BI__builtin_prefetch:
3062 if (BuiltinPrefetch(TheCall))
3063 return ExprError();
3064 break;
3065 case Builtin::BI__builtin_alloca_with_align:
3066 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3067 if (BuiltinAllocaWithAlign(TheCall))
3068 return ExprError();
3069 [[fallthrough]];
3070 case Builtin::BI__builtin_alloca:
3071 case Builtin::BI__builtin_alloca_uninitialized:
3072 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3073 << TheCall->getDirectCallee();
3074 if (getLangOpts().OpenCL) {
3075 builtinAllocaAddrSpace(*this, TheCall);
3076 }
3077 break;
3078 case Builtin::BI__builtin_infer_alloc_token:
3079 if (checkBuiltinInferAllocToken(*this, TheCall))
3080 return ExprError();
3081 break;
3082 case Builtin::BI__arithmetic_fence:
3083 if (BuiltinArithmeticFence(TheCall))
3084 return ExprError();
3085 break;
3086 case Builtin::BI__assume:
3087 case Builtin::BI__builtin_assume:
3088 if (BuiltinAssume(TheCall))
3089 return ExprError();
3090 break;
3091 case Builtin::BI__builtin_assume_aligned:
3092 if (BuiltinAssumeAligned(TheCall))
3093 return ExprError();
3094 break;
3095 case Builtin::BI__builtin_dynamic_object_size:
3096 case Builtin::BI__builtin_object_size:
3097 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3098 return ExprError();
3099 break;
3100 case Builtin::BI__builtin_longjmp:
3101 if (BuiltinLongjmp(TheCall))
3102 return ExprError();
3103 break;
3104 case Builtin::BI__builtin_setjmp:
3105 if (BuiltinSetjmp(TheCall))
3106 return ExprError();
3107 break;
3108 case Builtin::BI__builtin_complex:
3109 if (BuiltinComplex(TheCall))
3110 return ExprError();
3111 break;
3112 case Builtin::BI__builtin_classify_type:
3113 case Builtin::BI__builtin_constant_p: {
3114 if (checkArgCount(TheCall, 1))
3115 return true;
3117 if (Arg.isInvalid()) return true;
3118 TheCall->setArg(0, Arg.get());
3119 TheCall->setType(Context.IntTy);
3120 break;
3121 }
3122 case Builtin::BI__builtin_launder:
3123 return BuiltinLaunder(*this, TheCall);
3124 case Builtin::BI__builtin_is_within_lifetime:
3125 return BuiltinIsWithinLifetime(*this, TheCall);
3126 case Builtin::BI__builtin_trivially_relocate:
3127 return BuiltinTriviallyRelocate(*this, TheCall);
3128
3129 case Builtin::BI__sync_fetch_and_add:
3130 case Builtin::BI__sync_fetch_and_add_1:
3131 case Builtin::BI__sync_fetch_and_add_2:
3132 case Builtin::BI__sync_fetch_and_add_4:
3133 case Builtin::BI__sync_fetch_and_add_8:
3134 case Builtin::BI__sync_fetch_and_add_16:
3135 case Builtin::BI__sync_fetch_and_sub:
3136 case Builtin::BI__sync_fetch_and_sub_1:
3137 case Builtin::BI__sync_fetch_and_sub_2:
3138 case Builtin::BI__sync_fetch_and_sub_4:
3139 case Builtin::BI__sync_fetch_and_sub_8:
3140 case Builtin::BI__sync_fetch_and_sub_16:
3141 case Builtin::BI__sync_fetch_and_or:
3142 case Builtin::BI__sync_fetch_and_or_1:
3143 case Builtin::BI__sync_fetch_and_or_2:
3144 case Builtin::BI__sync_fetch_and_or_4:
3145 case Builtin::BI__sync_fetch_and_or_8:
3146 case Builtin::BI__sync_fetch_and_or_16:
3147 case Builtin::BI__sync_fetch_and_and:
3148 case Builtin::BI__sync_fetch_and_and_1:
3149 case Builtin::BI__sync_fetch_and_and_2:
3150 case Builtin::BI__sync_fetch_and_and_4:
3151 case Builtin::BI__sync_fetch_and_and_8:
3152 case Builtin::BI__sync_fetch_and_and_16:
3153 case Builtin::BI__sync_fetch_and_xor:
3154 case Builtin::BI__sync_fetch_and_xor_1:
3155 case Builtin::BI__sync_fetch_and_xor_2:
3156 case Builtin::BI__sync_fetch_and_xor_4:
3157 case Builtin::BI__sync_fetch_and_xor_8:
3158 case Builtin::BI__sync_fetch_and_xor_16:
3159 case Builtin::BI__sync_fetch_and_nand:
3160 case Builtin::BI__sync_fetch_and_nand_1:
3161 case Builtin::BI__sync_fetch_and_nand_2:
3162 case Builtin::BI__sync_fetch_and_nand_4:
3163 case Builtin::BI__sync_fetch_and_nand_8:
3164 case Builtin::BI__sync_fetch_and_nand_16:
3165 case Builtin::BI__sync_add_and_fetch:
3166 case Builtin::BI__sync_add_and_fetch_1:
3167 case Builtin::BI__sync_add_and_fetch_2:
3168 case Builtin::BI__sync_add_and_fetch_4:
3169 case Builtin::BI__sync_add_and_fetch_8:
3170 case Builtin::BI__sync_add_and_fetch_16:
3171 case Builtin::BI__sync_sub_and_fetch:
3172 case Builtin::BI__sync_sub_and_fetch_1:
3173 case Builtin::BI__sync_sub_and_fetch_2:
3174 case Builtin::BI__sync_sub_and_fetch_4:
3175 case Builtin::BI__sync_sub_and_fetch_8:
3176 case Builtin::BI__sync_sub_and_fetch_16:
3177 case Builtin::BI__sync_and_and_fetch:
3178 case Builtin::BI__sync_and_and_fetch_1:
3179 case Builtin::BI__sync_and_and_fetch_2:
3180 case Builtin::BI__sync_and_and_fetch_4:
3181 case Builtin::BI__sync_and_and_fetch_8:
3182 case Builtin::BI__sync_and_and_fetch_16:
3183 case Builtin::BI__sync_or_and_fetch:
3184 case Builtin::BI__sync_or_and_fetch_1:
3185 case Builtin::BI__sync_or_and_fetch_2:
3186 case Builtin::BI__sync_or_and_fetch_4:
3187 case Builtin::BI__sync_or_and_fetch_8:
3188 case Builtin::BI__sync_or_and_fetch_16:
3189 case Builtin::BI__sync_xor_and_fetch:
3190 case Builtin::BI__sync_xor_and_fetch_1:
3191 case Builtin::BI__sync_xor_and_fetch_2:
3192 case Builtin::BI__sync_xor_and_fetch_4:
3193 case Builtin::BI__sync_xor_and_fetch_8:
3194 case Builtin::BI__sync_xor_and_fetch_16:
3195 case Builtin::BI__sync_nand_and_fetch:
3196 case Builtin::BI__sync_nand_and_fetch_1:
3197 case Builtin::BI__sync_nand_and_fetch_2:
3198 case Builtin::BI__sync_nand_and_fetch_4:
3199 case Builtin::BI__sync_nand_and_fetch_8:
3200 case Builtin::BI__sync_nand_and_fetch_16:
3201 case Builtin::BI__sync_val_compare_and_swap:
3202 case Builtin::BI__sync_val_compare_and_swap_1:
3203 case Builtin::BI__sync_val_compare_and_swap_2:
3204 case Builtin::BI__sync_val_compare_and_swap_4:
3205 case Builtin::BI__sync_val_compare_and_swap_8:
3206 case Builtin::BI__sync_val_compare_and_swap_16:
3207 case Builtin::BI__sync_bool_compare_and_swap:
3208 case Builtin::BI__sync_bool_compare_and_swap_1:
3209 case Builtin::BI__sync_bool_compare_and_swap_2:
3210 case Builtin::BI__sync_bool_compare_and_swap_4:
3211 case Builtin::BI__sync_bool_compare_and_swap_8:
3212 case Builtin::BI__sync_bool_compare_and_swap_16:
3213 case Builtin::BI__sync_lock_test_and_set:
3214 case Builtin::BI__sync_lock_test_and_set_1:
3215 case Builtin::BI__sync_lock_test_and_set_2:
3216 case Builtin::BI__sync_lock_test_and_set_4:
3217 case Builtin::BI__sync_lock_test_and_set_8:
3218 case Builtin::BI__sync_lock_test_and_set_16:
3219 case Builtin::BI__sync_lock_release:
3220 case Builtin::BI__sync_lock_release_1:
3221 case Builtin::BI__sync_lock_release_2:
3222 case Builtin::BI__sync_lock_release_4:
3223 case Builtin::BI__sync_lock_release_8:
3224 case Builtin::BI__sync_lock_release_16:
3225 case Builtin::BI__sync_swap:
3226 case Builtin::BI__sync_swap_1:
3227 case Builtin::BI__sync_swap_2:
3228 case Builtin::BI__sync_swap_4:
3229 case Builtin::BI__sync_swap_8:
3230 case Builtin::BI__sync_swap_16:
3231 return BuiltinAtomicOverloaded(TheCallResult);
3232 case Builtin::BI__sync_synchronize:
3233 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3234 << TheCall->getCallee()->getSourceRange();
3235 break;
3236 case Builtin::BI__builtin_nontemporal_load:
3237 case Builtin::BI__builtin_nontemporal_store:
3238 return BuiltinNontemporalOverloaded(TheCallResult);
3239 case Builtin::BI__builtin_memcpy_inline: {
3240 clang::Expr *SizeOp = TheCall->getArg(2);
3241 // We warn about copying to or from `nullptr` pointers when `size` is
3242 // greater than 0. When `size` is value dependent we cannot evaluate its
3243 // value so we bail out.
3244 if (SizeOp->isValueDependent())
3245 break;
3246 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3247 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3248 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3249 }
3250 break;
3251 }
3252 case Builtin::BI__builtin_memset_inline: {
3253 clang::Expr *SizeOp = TheCall->getArg(2);
3254 // We warn about filling to `nullptr` pointers when `size` is greater than
3255 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3256 // out.
3257 if (SizeOp->isValueDependent())
3258 break;
3259 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3260 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3261 break;
3262 }
3263#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3264 case Builtin::BI##ID: \
3265 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3266#include "clang/Basic/Builtins.inc"
3267 case Builtin::BI__annotation: {
3268 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3269 if (!TT.isOSWindows() && !TT.isUEFI()) {
3270 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3271 << TheCall->getSourceRange();
3272 return ExprError();
3273 }
3274 if (BuiltinMSVCAnnotation(*this, TheCall))
3275 return ExprError();
3276 break;
3277 }
3278 case Builtin::BI__builtin_annotation:
3279 if (BuiltinAnnotation(*this, TheCall))
3280 return ExprError();
3281 break;
3282 case Builtin::BI__builtin_addressof:
3283 if (BuiltinAddressof(*this, TheCall))
3284 return ExprError();
3285 break;
3286 case Builtin::BI__builtin_function_start:
3287 if (BuiltinFunctionStart(*this, TheCall))
3288 return ExprError();
3289 break;
3290 case Builtin::BI__builtin_is_aligned:
3291 case Builtin::BI__builtin_align_up:
3292 case Builtin::BI__builtin_align_down:
3293 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3294 return ExprError();
3295 break;
3296 case Builtin::BI__builtin_add_overflow:
3297 case Builtin::BI__builtin_sub_overflow:
3298 case Builtin::BI__builtin_mul_overflow:
3299 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3300 return ExprError();
3301 break;
3302 case Builtin::BI__builtin_operator_new:
3303 case Builtin::BI__builtin_operator_delete: {
3304 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3305 ExprResult Res =
3306 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3307 return Res;
3308 }
3309 case Builtin::BI__builtin_dump_struct:
3310 return BuiltinDumpStruct(*this, TheCall);
3311 case Builtin::BI__builtin_expect_with_probability: {
3312 // We first want to ensure we are called with 3 arguments
3313 if (checkArgCount(TheCall, 3))
3314 return ExprError();
3315 // then check probability is constant float in range [0.0, 1.0]
3316 const Expr *ProbArg = TheCall->getArg(2);
3317 SmallVector<PartialDiagnosticAt, 8> Notes;
3318 Expr::EvalResult Eval;
3319 Eval.Diag = &Notes;
3320 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3321 !Eval.Val.isFloat()) {
3322 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3323 << ProbArg->getSourceRange();
3324 for (const PartialDiagnosticAt &PDiag : Notes)
3325 Diag(PDiag.first, PDiag.second);
3326 return ExprError();
3327 }
3328 llvm::APFloat Probability = Eval.Val.getFloat();
3329 bool LoseInfo = false;
3330 Probability.convert(llvm::APFloat::IEEEdouble(),
3331 llvm::RoundingMode::Dynamic, &LoseInfo);
3332 if (!(Probability >= llvm::APFloat(0.0) &&
3333 Probability <= llvm::APFloat(1.0))) {
3334 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3335 << ProbArg->getSourceRange();
3336 return ExprError();
3337 }
3338 break;
3339 }
3340 case Builtin::BI__builtin_preserve_access_index:
3341 if (BuiltinPreserveAI(*this, TheCall))
3342 return ExprError();
3343 break;
3344 case Builtin::BI__builtin_call_with_static_chain:
3345 if (BuiltinCallWithStaticChain(*this, TheCall))
3346 return ExprError();
3347 break;
3348 case Builtin::BI__exception_code:
3349 case Builtin::BI_exception_code:
3350 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3351 diag::err_seh___except_block))
3352 return ExprError();
3353 break;
3354 case Builtin::BI__exception_info:
3355 case Builtin::BI_exception_info:
3356 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3357 diag::err_seh___except_filter))
3358 return ExprError();
3359 break;
3360 case Builtin::BI__GetExceptionInfo:
3361 if (checkArgCount(TheCall, 1))
3362 return ExprError();
3363
3365 TheCall->getBeginLoc(),
3366 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3367 TheCall))
3368 return ExprError();
3369
3370 TheCall->setType(Context.VoidPtrTy);
3371 break;
3372 case Builtin::BIaddressof:
3373 case Builtin::BI__addressof:
3374 case Builtin::BIforward:
3375 case Builtin::BIforward_like:
3376 case Builtin::BImove:
3377 case Builtin::BImove_if_noexcept:
3378 case Builtin::BIas_const: {
3379 // These are all expected to be of the form
3380 // T &/&&/* f(U &/&&)
3381 // where T and U only differ in qualification.
3382 if (checkArgCount(TheCall, 1))
3383 return ExprError();
3384 QualType Param = FDecl->getParamDecl(0)->getType();
3385 QualType Result = FDecl->getReturnType();
3386 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3387 BuiltinID == Builtin::BI__addressof;
3388 if (!(Param->isReferenceType() &&
3389 (ReturnsPointer ? Result->isAnyPointerType()
3390 : Result->isReferenceType()) &&
3391 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3392 Result->getPointeeType()))) {
3393 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3394 << FDecl;
3395 return ExprError();
3396 }
3397 break;
3398 }
3399 case Builtin::BI__builtin_ptrauth_strip:
3400 return PointerAuthStrip(*this, TheCall);
3401 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3402 return PointerAuthBlendDiscriminator(*this, TheCall);
3403 case Builtin::BI__builtin_ptrauth_sign_constant:
3404 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3405 /*RequireConstant=*/true);
3406 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3407 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3408 /*RequireConstant=*/false);
3409 case Builtin::BI__builtin_ptrauth_auth:
3410 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3411 /*RequireConstant=*/false);
3412 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3413 return PointerAuthSignGenericData(*this, TheCall);
3414 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3415 return PointerAuthAuthAndResign(*this, TheCall);
3416 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3417 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3418 case Builtin::BI__builtin_ptrauth_string_discriminator:
3419 return PointerAuthStringDiscriminator(*this, TheCall);
3420
3421 case Builtin::BI__builtin_get_vtable_pointer:
3422 return GetVTablePointer(*this, TheCall);
3423
3424 // OpenCL v2.0, s6.13.16 - Pipe functions
3425 case Builtin::BIread_pipe:
3426 case Builtin::BIwrite_pipe:
3427 // Since those two functions are declared with var args, we need a semantic
3428 // check for the argument.
3429 if (OpenCL().checkBuiltinRWPipe(TheCall))
3430 return ExprError();
3431 break;
3432 case Builtin::BIreserve_read_pipe:
3433 case Builtin::BIreserve_write_pipe:
3434 case Builtin::BIwork_group_reserve_read_pipe:
3435 case Builtin::BIwork_group_reserve_write_pipe:
3436 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3437 return ExprError();
3438 break;
3439 case Builtin::BIsub_group_reserve_read_pipe:
3440 case Builtin::BIsub_group_reserve_write_pipe:
3441 if (OpenCL().checkSubgroupExt(TheCall) ||
3442 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3443 return ExprError();
3444 break;
3445 case Builtin::BIcommit_read_pipe:
3446 case Builtin::BIcommit_write_pipe:
3447 case Builtin::BIwork_group_commit_read_pipe:
3448 case Builtin::BIwork_group_commit_write_pipe:
3449 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3450 return ExprError();
3451 break;
3452 case Builtin::BIsub_group_commit_read_pipe:
3453 case Builtin::BIsub_group_commit_write_pipe:
3454 if (OpenCL().checkSubgroupExt(TheCall) ||
3455 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3456 return ExprError();
3457 break;
3458 case Builtin::BIget_pipe_num_packets:
3459 case Builtin::BIget_pipe_max_packets:
3460 if (OpenCL().checkBuiltinPipePackets(TheCall))
3461 return ExprError();
3462 break;
3463 case Builtin::BIto_global:
3464 case Builtin::BIto_local:
3465 case Builtin::BIto_private:
3466 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3467 return ExprError();
3468 break;
3469 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3470 case Builtin::BIenqueue_kernel:
3471 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3472 return ExprError();
3473 break;
3474 case Builtin::BIget_kernel_work_group_size:
3475 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3476 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3477 return ExprError();
3478 break;
3479 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3480 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3481 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3482 return ExprError();
3483 break;
3484 case Builtin::BI__builtin_os_log_format:
3485 Cleanup.setExprNeedsCleanups(true);
3486 [[fallthrough]];
3487 case Builtin::BI__builtin_os_log_format_buffer_size:
3488 if (BuiltinOSLogFormat(TheCall))
3489 return ExprError();
3490 break;
3491 case Builtin::BI__builtin_frame_address:
3492 case Builtin::BI__builtin_return_address: {
3493 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3494 return ExprError();
3495
3496 // -Wframe-address warning if non-zero passed to builtin
3497 // return/frame address.
3498 Expr::EvalResult Result;
3499 if (!TheCall->getArg(0)->isValueDependent() &&
3500 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3501 Result.Val.getInt() != 0)
3502 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3503 << ((BuiltinID == Builtin::BI__builtin_return_address)
3504 ? "__builtin_return_address"
3505 : "__builtin_frame_address")
3506 << TheCall->getSourceRange();
3507 break;
3508 }
3509
3510 case Builtin::BI__builtin_nondeterministic_value: {
3511 if (BuiltinNonDeterministicValue(TheCall))
3512 return ExprError();
3513 break;
3514 }
3515
3516 // __builtin_elementwise_abs restricts the element type to signed integers or
3517 // floating point types only.
3518 case Builtin::BI__builtin_elementwise_abs:
3521 return ExprError();
3522 break;
3523
3524 // These builtins restrict the element type to floating point
3525 // types only.
3526 case Builtin::BI__builtin_elementwise_acos:
3527 case Builtin::BI__builtin_elementwise_asin:
3528 case Builtin::BI__builtin_elementwise_atan:
3529 case Builtin::BI__builtin_elementwise_ceil:
3530 case Builtin::BI__builtin_elementwise_cos:
3531 case Builtin::BI__builtin_elementwise_cosh:
3532 case Builtin::BI__builtin_elementwise_exp:
3533 case Builtin::BI__builtin_elementwise_exp2:
3534 case Builtin::BI__builtin_elementwise_exp10:
3535 case Builtin::BI__builtin_elementwise_floor:
3536 case Builtin::BI__builtin_elementwise_log:
3537 case Builtin::BI__builtin_elementwise_log2:
3538 case Builtin::BI__builtin_elementwise_log10:
3539 case Builtin::BI__builtin_elementwise_roundeven:
3540 case Builtin::BI__builtin_elementwise_round:
3541 case Builtin::BI__builtin_elementwise_rint:
3542 case Builtin::BI__builtin_elementwise_nearbyint:
3543 case Builtin::BI__builtin_elementwise_sin:
3544 case Builtin::BI__builtin_elementwise_sinh:
3545 case Builtin::BI__builtin_elementwise_sqrt:
3546 case Builtin::BI__builtin_elementwise_tan:
3547 case Builtin::BI__builtin_elementwise_tanh:
3548 case Builtin::BI__builtin_elementwise_trunc:
3549 case Builtin::BI__builtin_elementwise_canonicalize:
3552 return ExprError();
3553 break;
3554 case Builtin::BI__builtin_elementwise_fma:
3555 if (BuiltinElementwiseTernaryMath(TheCall))
3556 return ExprError();
3557 break;
3558
3559 case Builtin::BI__builtin_elementwise_ldexp: {
3560 if (checkArgCount(TheCall, 2))
3561 return ExprError();
3562
3563 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3564 if (A.isInvalid())
3565 return ExprError();
3566 QualType TyA = A.get()->getType();
3567 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3569 return ExprError();
3570
3571 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3572 if (Exp.isInvalid())
3573 return ExprError();
3574 QualType TyExp = Exp.get()->getType();
3575 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3577 2))
3578 return ExprError();
3579
3580 // Check the two arguments are either scalars or vectors of equal length.
3581 const auto *Vec0 = TyA->getAs<VectorType>();
3582 const auto *Vec1 = TyExp->getAs<VectorType>();
3583 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3584 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3585 if (Arg0Length != Arg1Length) {
3586 Diag(Exp.get()->getBeginLoc(),
3587 diag::err_typecheck_vector_lengths_not_equal)
3588 << TyA << TyExp << A.get()->getSourceRange()
3589 << Exp.get()->getSourceRange();
3590 return ExprError();
3591 }
3592
3593 TheCall->setArg(0, A.get());
3594 TheCall->setArg(1, Exp.get());
3595 TheCall->setType(TyA);
3596 break;
3597 }
3598
3599 // These builtins restrict the element type to floating point
3600 // types only, and take in two arguments.
3601 case Builtin::BI__builtin_elementwise_minnum:
3602 case Builtin::BI__builtin_elementwise_maxnum:
3603 case Builtin::BI__builtin_elementwise_minimum:
3604 case Builtin::BI__builtin_elementwise_maximum:
3605 case Builtin::BI__builtin_elementwise_minimumnum:
3606 case Builtin::BI__builtin_elementwise_maximumnum:
3607 case Builtin::BI__builtin_elementwise_atan2:
3608 case Builtin::BI__builtin_elementwise_fmod:
3609 case Builtin::BI__builtin_elementwise_pow:
3610 if (BuiltinElementwiseMath(TheCall,
3612 return ExprError();
3613 break;
3614 // These builtins restrict the element type to integer
3615 // types only.
3616 case Builtin::BI__builtin_elementwise_add_sat:
3617 case Builtin::BI__builtin_elementwise_sub_sat:
3618 if (BuiltinElementwiseMath(TheCall,
3620 return ExprError();
3621 break;
3622 case Builtin::BI__builtin_elementwise_fshl:
3623 case Builtin::BI__builtin_elementwise_fshr:
3626 return ExprError();
3627 break;
3628 case Builtin::BI__builtin_elementwise_min:
3629 case Builtin::BI__builtin_elementwise_max: {
3630 if (BuiltinElementwiseMath(TheCall))
3631 return ExprError();
3632 Expr *Arg0 = TheCall->getArg(0);
3633 Expr *Arg1 = TheCall->getArg(1);
3634 QualType Ty0 = Arg0->getType();
3635 QualType Ty1 = Arg1->getType();
3636 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3637 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3638 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3639 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3640 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3641 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3642 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3643 break;
3644 }
3645 case Builtin::BI__builtin_elementwise_popcount:
3646 case Builtin::BI__builtin_elementwise_bitreverse:
3649 return ExprError();
3650 break;
3651 case Builtin::BI__builtin_elementwise_copysign: {
3652 if (checkArgCount(TheCall, 2))
3653 return ExprError();
3654
3655 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3656 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3657 if (Magnitude.isInvalid() || Sign.isInvalid())
3658 return ExprError();
3659
3660 QualType MagnitudeTy = Magnitude.get()->getType();
3661 QualType SignTy = Sign.get()->getType();
3663 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3666 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3668 return ExprError();
3669 }
3670
3671 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3672 return Diag(Sign.get()->getBeginLoc(),
3673 diag::err_typecheck_call_different_arg_types)
3674 << MagnitudeTy << SignTy;
3675 }
3676
3677 TheCall->setArg(0, Magnitude.get());
3678 TheCall->setArg(1, Sign.get());
3679 TheCall->setType(Magnitude.get()->getType());
3680 break;
3681 }
3682 case Builtin::BI__builtin_elementwise_clzg:
3683 case Builtin::BI__builtin_elementwise_ctzg:
3684 // These builtins can be unary or binary. Note for empty calls we call the
3685 // unary checker in order to not emit an error that says the function
3686 // expects 2 arguments, which would be misleading.
3687 if (TheCall->getNumArgs() <= 1) {
3690 return ExprError();
3691 } else if (BuiltinElementwiseMath(
3693 return ExprError();
3694 break;
3695 case Builtin::BI__builtin_reduce_max:
3696 case Builtin::BI__builtin_reduce_min: {
3697 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3698 return ExprError();
3699
3700 const Expr *Arg = TheCall->getArg(0);
3701 const auto *TyA = Arg->getType()->getAs<VectorType>();
3702
3703 QualType ElTy;
3704 if (TyA)
3705 ElTy = TyA->getElementType();
3706 else if (Arg->getType()->isSizelessVectorType())
3708
3709 if (ElTy.isNull()) {
3710 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3711 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3712 << Arg->getType();
3713 return ExprError();
3714 }
3715
3716 TheCall->setType(ElTy);
3717 break;
3718 }
3719 case Builtin::BI__builtin_reduce_maximum:
3720 case Builtin::BI__builtin_reduce_minimum: {
3721 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3722 return ExprError();
3723
3724 const Expr *Arg = TheCall->getArg(0);
3725 const auto *TyA = Arg->getType()->getAs<VectorType>();
3726
3727 QualType ElTy;
3728 if (TyA)
3729 ElTy = TyA->getElementType();
3730 else if (Arg->getType()->isSizelessVectorType())
3732
3733 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3734 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3735 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3736 << Arg->getType();
3737 return ExprError();
3738 }
3739
3740 TheCall->setType(ElTy);
3741 break;
3742 }
3743
3744 // These builtins support vectors of integers only.
3745 // TODO: ADD/MUL should support floating-point types.
3746 case Builtin::BI__builtin_reduce_add:
3747 case Builtin::BI__builtin_reduce_mul:
3748 case Builtin::BI__builtin_reduce_xor:
3749 case Builtin::BI__builtin_reduce_or:
3750 case Builtin::BI__builtin_reduce_and: {
3751 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3752 return ExprError();
3753
3754 const Expr *Arg = TheCall->getArg(0);
3755
3756 QualType ElTy = getVectorElementType(Context, Arg->getType());
3757 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3758 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3759 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3760 << Arg->getType();
3761 return ExprError();
3762 }
3763
3764 TheCall->setType(ElTy);
3765 break;
3766 }
3767
3768 case Builtin::BI__builtin_reduce_assoc_fadd:
3769 case Builtin::BI__builtin_reduce_in_order_fadd: {
3770 // For in-order reductions require the user to specify the start value.
3771 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3772 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
3773 return ExprError();
3774
3775 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
3776 if (Vec.isInvalid())
3777 return ExprError();
3778
3779 TheCall->setArg(0, Vec.get());
3780
3781 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
3782 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3783 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3784 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3785 << Vec.get()->getType();
3786 return ExprError();
3787 }
3788
3789 if (TheCall->getNumArgs() == 2) {
3790 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
3791 if (StartValue.isInvalid())
3792 return ExprError();
3793
3794 if (!StartValue.get()->getType()->isRealFloatingType()) {
3795 Diag(StartValue.get()->getBeginLoc(),
3796 diag::err_builtin_invalid_arg_type)
3797 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3798 << StartValue.get()->getType();
3799 return ExprError();
3800 }
3801 TheCall->setArg(1, StartValue.get());
3802 }
3803
3804 TheCall->setType(ElTy);
3805 break;
3806 }
3807
3808 case Builtin::BI__builtin_matrix_transpose:
3809 return BuiltinMatrixTranspose(TheCall, TheCallResult);
3810
3811 case Builtin::BI__builtin_matrix_column_major_load:
3812 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3813
3814 case Builtin::BI__builtin_matrix_column_major_store:
3815 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3816
3817 case Builtin::BI__builtin_verbose_trap:
3818 if (!checkBuiltinVerboseTrap(TheCall, *this))
3819 return ExprError();
3820 break;
3821
3822 case Builtin::BI__builtin_get_device_side_mangled_name: {
3823 auto Check = [](CallExpr *TheCall) {
3824 if (TheCall->getNumArgs() != 1)
3825 return false;
3826 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3827 if (!DRE)
3828 return false;
3829 auto *D = DRE->getDecl();
3830 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3831 return false;
3832 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3833 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3834 };
3835 if (!Check(TheCall)) {
3836 Diag(TheCall->getBeginLoc(),
3837 diag::err_hip_invalid_args_builtin_mangled_name);
3838 return ExprError();
3839 }
3840 break;
3841 }
3842 case Builtin::BI__builtin_bswapg:
3843 if (BuiltinBswapg(*this, TheCall))
3844 return ExprError();
3845 break;
3846 case Builtin::BI__builtin_bitreverseg:
3847 if (BuiltinBitreverseg(*this, TheCall))
3848 return ExprError();
3849 break;
3850 case Builtin::BI__builtin_popcountg:
3851 if (BuiltinPopcountg(*this, TheCall))
3852 return ExprError();
3853 break;
3854 case Builtin::BI__builtin_clzg:
3855 case Builtin::BI__builtin_ctzg:
3856 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3857 return ExprError();
3858 break;
3859
3860 case Builtin::BI__builtin_stdc_rotate_left:
3861 case Builtin::BI__builtin_stdc_rotate_right:
3862 if (BuiltinRotateGeneric(*this, TheCall))
3863 return ExprError();
3864 break;
3865
3866 case Builtin::BI__builtin_stdc_bit_floor:
3867 case Builtin::BI__builtin_stdc_bit_ceil:
3868 case Builtin::BIstdc_bit_floor:
3869 case Builtin::BIstdc_bit_ceil:
3870 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
3871 return ExprError();
3872 break;
3873 case Builtin::BI__builtin_stdc_has_single_bit:
3874 case Builtin::BIstdc_has_single_bit:
3875 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
3876 return ExprError();
3877 break;
3878 case Builtin::BI__builtin_stdc_leading_zeros:
3879 case Builtin::BI__builtin_stdc_leading_ones:
3880 case Builtin::BI__builtin_stdc_trailing_zeros:
3881 case Builtin::BI__builtin_stdc_trailing_ones:
3882 case Builtin::BI__builtin_stdc_first_leading_zero:
3883 case Builtin::BI__builtin_stdc_first_leading_one:
3884 case Builtin::BI__builtin_stdc_first_trailing_zero:
3885 case Builtin::BI__builtin_stdc_first_trailing_one:
3886 case Builtin::BI__builtin_stdc_count_zeros:
3887 case Builtin::BI__builtin_stdc_count_ones:
3888 case Builtin::BI__builtin_stdc_bit_width:
3889 case Builtin::BIstdc_leading_zeros:
3890 case Builtin::BIstdc_leading_ones:
3891 case Builtin::BIstdc_trailing_zeros:
3892 case Builtin::BIstdc_trailing_ones:
3893 case Builtin::BIstdc_first_leading_zero:
3894 case Builtin::BIstdc_first_leading_one:
3895 case Builtin::BIstdc_first_trailing_zero:
3896 case Builtin::BIstdc_first_trailing_one:
3897 case Builtin::BIstdc_count_zeros:
3898 case Builtin::BIstdc_count_ones:
3899 case Builtin::BIstdc_bit_width:
3900 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
3901 return ExprError();
3902 break;
3903
3904 case Builtin::BI__builtin_allow_runtime_check: {
3905 Expr *Arg = TheCall->getArg(0);
3906 // Check if the argument is a string literal.
3908 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3909 << Arg->getSourceRange();
3910 return ExprError();
3911 }
3912 break;
3913 }
3914
3915 case Builtin::BI__builtin_allow_sanitize_check: {
3916 if (checkArgCount(TheCall, 1))
3917 return ExprError();
3918
3919 Expr *Arg = TheCall->getArg(0);
3920 // Check if the argument is a string literal.
3921 const StringLiteral *SanitizerName =
3922 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
3923 if (!SanitizerName) {
3924 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3925 << Arg->getSourceRange();
3926 return ExprError();
3927 }
3928 // Validate the sanitizer name.
3929 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3930 .Cases({"address", "thread", "memory", "hwaddress",
3931 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3932 true)
3933 .Default(false)) {
3934 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
3935 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3936 << Arg->getSourceRange();
3937 return ExprError();
3938 }
3939 break;
3940 }
3941 case Builtin::BI__builtin_counted_by_ref:
3942 if (BuiltinCountedByRef(TheCall))
3943 return ExprError();
3944 break;
3945 }
3946
3947 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3948 return ExprError();
3949
3950 // Since the target specific builtins for each arch overlap, only check those
3951 // of the arch we are compiling for.
3952 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3953 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3954 assert(Context.getAuxTargetInfo() &&
3955 "Aux Target Builtin, but not an aux target?");
3956
3957 if (CheckTSBuiltinFunctionCall(
3958 *Context.getAuxTargetInfo(),
3959 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3960 return ExprError();
3961 } else {
3962 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3963 TheCall))
3964 return ExprError();
3965 }
3966 }
3967
3968 return TheCallResult;
3969}
3970
3971bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3972 llvm::APSInt Result;
3973 // We can't check the value of a dependent argument.
3974 Expr *Arg = TheCall->getArg(ArgNum);
3975 if (Arg->isTypeDependent() || Arg->isValueDependent())
3976 return false;
3977
3978 // Check constant-ness first.
3979 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3980 return true;
3981
3982 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3983 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3984 return false;
3985
3986 return Diag(TheCall->getBeginLoc(),
3987 diag::err_argument_not_contiguous_bit_field)
3988 << ArgNum << Arg->getSourceRange();
3989}
3990
3991bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3992 unsigned FirstArg, FormatStringInfo *FSI) {
3993 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3994 bool IsVariadic = false;
3995 if (const FunctionType *FnTy = D->getFunctionType())
3996 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
3997 else if (const auto *BD = dyn_cast<BlockDecl>(D))
3998 IsVariadic = BD->isVariadic();
3999 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4000 IsVariadic = OMD->isVariadic();
4001
4002 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4003 IsVariadic, FSI);
4004}
4005
4006bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4007 bool HasImplicitThisParam, bool IsVariadic,
4008 FormatStringInfo *FSI) {
4009 if (FirstArg == 0)
4011 else if (IsVariadic)
4013 else
4015 FSI->FormatIdx = FormatIdx - 1;
4016 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4017
4018 // The way the format attribute works in GCC, the implicit this argument
4019 // of member functions is counted. However, it doesn't appear in our own
4020 // lists, so decrement format_idx in that case.
4021 if (HasImplicitThisParam) {
4022 if(FSI->FormatIdx == 0)
4023 return false;
4024 --FSI->FormatIdx;
4025 if (FSI->FirstDataArg != 0)
4026 --FSI->FirstDataArg;
4027 }
4028 return true;
4029}
4030
4031/// Checks if a the given expression evaluates to null.
4032///
4033/// Returns true if the value evaluates to null.
4034static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4035 // Treat (smart) pointers constructed from nullptr as null, whether we can
4036 // const-evaluate them or not.
4037 // This must happen first: the smart pointer expr might have _Nonnull type!
4041 return true;
4042
4043 // If the expression has non-null type, it doesn't evaluate to null.
4044 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4045 if (*nullability == NullabilityKind::NonNull)
4046 return false;
4047 }
4048
4049 // As a special case, transparent unions initialized with zero are
4050 // considered null for the purposes of the nonnull attribute.
4051 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4052 UT &&
4053 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4054 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4055 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4056 Expr = ILE->getInit(0);
4057 }
4058
4059 bool Result;
4060 return (!Expr->isValueDependent() &&
4062 !Result);
4063}
4064
4066 const Expr *ArgExpr,
4067 SourceLocation CallSiteLoc) {
4068 if (CheckNonNullExpr(S, ArgExpr))
4069 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4070 S.PDiag(diag::warn_null_arg)
4071 << ArgExpr->getSourceRange());
4072}
4073
4074/// Determine whether the given type has a non-null nullability annotation.
4076 if (auto nullability = type->getNullability())
4077 return *nullability == NullabilityKind::NonNull;
4078
4079 return false;
4080}
4081
4083 const NamedDecl *FDecl,
4084 const FunctionProtoType *Proto,
4086 SourceLocation CallSiteLoc) {
4087 assert((FDecl || Proto) && "Need a function declaration or prototype");
4088
4089 // Already checked by constant evaluator.
4091 return;
4092 // Check the attributes attached to the method/function itself.
4093 llvm::SmallBitVector NonNullArgs;
4094 if (FDecl) {
4095 // Handle the nonnull attribute on the function/method declaration itself.
4096 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4097 if (!NonNull->args_size()) {
4098 // Easy case: all pointer arguments are nonnull.
4099 for (const auto *Arg : Args)
4100 if (S.isValidPointerAttrType(Arg->getType()))
4101 CheckNonNullArgument(S, Arg, CallSiteLoc);
4102 return;
4103 }
4104
4105 for (const ParamIdx &Idx : NonNull->args()) {
4106 unsigned IdxAST = Idx.getASTIndex();
4107 if (IdxAST >= Args.size())
4108 continue;
4109 if (NonNullArgs.empty())
4110 NonNullArgs.resize(Args.size());
4111 NonNullArgs.set(IdxAST);
4112 }
4113 }
4114 }
4115
4116 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4117 // Handle the nonnull attribute on the parameters of the
4118 // function/method.
4120 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4121 parms = FD->parameters();
4122 else
4123 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4124
4125 unsigned ParamIndex = 0;
4126 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4127 I != E; ++I, ++ParamIndex) {
4128 const ParmVarDecl *PVD = *I;
4129 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4130 if (NonNullArgs.empty())
4131 NonNullArgs.resize(Args.size());
4132
4133 NonNullArgs.set(ParamIndex);
4134 }
4135 }
4136 } else {
4137 // If we have a non-function, non-method declaration but no
4138 // function prototype, try to dig out the function prototype.
4139 if (!Proto) {
4140 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4141 QualType type = VD->getType().getNonReferenceType();
4142 if (auto pointerType = type->getAs<PointerType>())
4143 type = pointerType->getPointeeType();
4144 else if (auto blockType = type->getAs<BlockPointerType>())
4145 type = blockType->getPointeeType();
4146 // FIXME: data member pointers?
4147
4148 // Dig out the function prototype, if there is one.
4149 Proto = type->getAs<FunctionProtoType>();
4150 }
4151 }
4152
4153 // Fill in non-null argument information from the nullability
4154 // information on the parameter types (if we have them).
4155 if (Proto) {
4156 unsigned Index = 0;
4157 for (auto paramType : Proto->getParamTypes()) {
4158 if (isNonNullType(paramType)) {
4159 if (NonNullArgs.empty())
4160 NonNullArgs.resize(Args.size());
4161
4162 NonNullArgs.set(Index);
4163 }
4164
4165 ++Index;
4166 }
4167 }
4168 }
4169
4170 // Check for non-null arguments.
4171 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4172 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4173 if (NonNullArgs[ArgIndex])
4174 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4175 }
4176}
4177
4178void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4179 StringRef ParamName, QualType ArgTy,
4180 QualType ParamTy) {
4181
4182 // If a function accepts a pointer or reference type
4183 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4184 return;
4185
4186 // If the parameter is a pointer type, get the pointee type for the
4187 // argument too. If the parameter is a reference type, don't try to get
4188 // the pointee type for the argument.
4189 if (ParamTy->isPointerType())
4190 ArgTy = ArgTy->getPointeeType();
4191
4192 // Remove reference or pointer
4193 ParamTy = ParamTy->getPointeeType();
4194
4195 // Find expected alignment, and the actual alignment of the passed object.
4196 // getTypeAlignInChars requires complete types
4197 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4198 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4199 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4200 return;
4201
4202 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4203 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4204
4205 // If the argument is less aligned than the parameter, there is a
4206 // potential alignment issue.
4207 if (ArgAlign < ParamAlign)
4208 Diag(Loc, diag::warn_param_mismatched_alignment)
4209 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4210 << ParamName << (FDecl != nullptr) << FDecl;
4211}
4212
4213void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4214 const Expr *ThisArg,
4216 if (!FD || Args.empty())
4217 return;
4218 auto GetArgAt = [&](int Idx) -> const Expr * {
4219 if (Idx == LifetimeCaptureByAttr::Global ||
4220 Idx == LifetimeCaptureByAttr::Unknown)
4221 return nullptr;
4222 if (IsMemberFunction && Idx == 0)
4223 return ThisArg;
4224 return Args[Idx - IsMemberFunction];
4225 };
4226 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4227 unsigned ArgIdx) {
4228 if (!Attr)
4229 return;
4230
4231 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4232 for (int CapturingParamIdx : Attr->params()) {
4233 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4234 // initialization codepath.
4235 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4237 continue;
4238 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4239 CapturingEntity CE{Capturing};
4240 // Ensure that 'Captured' outlives the 'Capturing' entity.
4241 checkCaptureByLifetime(*this, CE, Captured);
4242 }
4243 };
4244 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4245 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
4246 I + IsMemberFunction);
4247 // Check when the implicit object param is captured.
4248 if (IsMemberFunction) {
4249 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4250 if (!TSI)
4251 return;
4253 for (TypeLoc TL = TSI->getTypeLoc();
4254 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4255 TL = ATL.getModifiedLoc())
4256 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4257 }
4258}
4259
4261 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4262 bool IsMemberFunction, SourceLocation Loc,
4263 SourceRange Range, VariadicCallType CallType) {
4264
4265 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4266 llvm::any_of(Args, [](const Expr *E) {
4267 return E && E->isInstantiationDependent();
4268 }))
4269 return;
4270
4271 // Printf and scanf checking.
4272 llvm::SmallBitVector CheckedVarArgs;
4273 if (FDecl) {
4274 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4275 // Only create vector if there are format attributes.
4276 CheckedVarArgs.resize(Args.size());
4277 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4278 CheckedVarArgs);
4279 }
4280
4281 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4282 CheckedVarArgs.resize(Args.size());
4283 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4284 CheckedVarArgs);
4285 }
4286 }
4287
4288 // Refuse POD arguments that weren't caught by the format string
4289 // checks above.
4290 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4291 if (CallType != VariadicCallType::DoesNotApply &&
4292 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4293 unsigned NumParams = Proto ? Proto->getNumParams()
4294 : isa_and_nonnull<FunctionDecl>(FDecl)
4295 ? cast<FunctionDecl>(FDecl)->getNumParams()
4296 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4297 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4298 : 0;
4299
4300 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4301 // Args[ArgIdx] can be null in malformed code.
4302 if (const Expr *Arg = Args[ArgIdx]) {
4303 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4304 checkVariadicArgument(Arg, CallType);
4305 }
4306 }
4307 }
4308 if (FD)
4309 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4310 if (FDecl || Proto) {
4311 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4312
4313 // Type safety checking.
4314 if (FDecl) {
4315 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4316 CheckArgumentWithTypeTag(I, Args, Loc);
4317 }
4318 }
4319
4320 // Check that passed arguments match the alignment of original arguments.
4321 // Try to get the missing prototype from the declaration.
4322 if (!Proto && FDecl) {
4323 const auto *FT = FDecl->getFunctionType();
4324 if (isa_and_nonnull<FunctionProtoType>(FT))
4325 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4326 }
4327 if (Proto) {
4328 // For variadic functions, we may have more args than parameters.
4329 // For some K&R functions, we may have less args than parameters.
4330 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4331 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4332 bool IsScalableArg = false;
4333 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4334 // Args[ArgIdx] can be null in malformed code.
4335 if (const Expr *Arg = Args[ArgIdx]) {
4336 if (Arg->containsErrors())
4337 continue;
4338
4339 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4340 FDecl->hasLinkage() &&
4341 FDecl->getFormalLinkage() != Linkage::Internal &&
4343 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4344
4345 QualType ParamTy = Proto->getParamType(ArgIdx);
4346 if (ParamTy->isSizelessVectorType())
4347 IsScalableArg = true;
4348 QualType ArgTy = Arg->getType();
4349 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4350 ArgTy, ParamTy);
4351 }
4352 }
4353
4354 // If the callee has an AArch64 SME attribute to indicate that it is an
4355 // __arm_streaming function, then the caller requires SME to be available.
4358 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4359 llvm::StringMap<bool> CallerFeatureMap;
4360 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4361 if (!CallerFeatureMap.contains("sme"))
4362 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4363 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4364 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4365 }
4366 }
4367
4368 // If the call requires a streaming-mode change and has scalable vector
4369 // arguments or return values, then warn the user that the streaming and
4370 // non-streaming vector lengths may be different.
4371 // When both streaming and non-streaming vector lengths are defined and
4372 // mismatched, produce an error.
4373 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4374 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4375 (IsScalableArg || IsScalableRet)) {
4376 bool IsCalleeStreaming =
4378 bool IsCalleeStreamingCompatible =
4379 ExtInfo.AArch64SMEAttributes &
4381 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4382 if (!IsCalleeStreamingCompatible &&
4383 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4384 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4385 const LangOptions &LO = getLangOpts();
4386 unsigned VL = LO.VScaleMin * 128;
4387 unsigned SVL = LO.VScaleStreamingMin * 128;
4388 bool IsVLMismatch = VL && SVL && VL != SVL;
4389
4390 auto EmitDiag = [&](bool IsArg) {
4391 if (IsVLMismatch) {
4392 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4393 // Emit warning for streaming-compatible callers
4394 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4395 << IsArg << IsCalleeStreaming << SVL << VL;
4396 else
4397 // Emit error otherwise
4398 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4399 << IsArg << SVL << VL;
4400 } else
4401 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4402 << IsArg;
4403 };
4404
4405 if (IsScalableArg)
4406 EmitDiag(true);
4407 if (IsScalableRet)
4408 EmitDiag(false);
4409 }
4410 }
4411
4412 FunctionType::ArmStateValue CalleeArmZAState =
4414 FunctionType::ArmStateValue CalleeArmZT0State =
4416 if (CalleeArmZAState != FunctionType::ARM_None ||
4417 CalleeArmZT0State != FunctionType::ARM_None) {
4418 bool CallerHasZAState = false;
4419 bool CallerHasZT0State = false;
4420 if (CallerFD) {
4421 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4422 if (Attr && Attr->isNewZA())
4423 CallerHasZAState = true;
4424 if (Attr && Attr->isNewZT0())
4425 CallerHasZT0State = true;
4426 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4427 CallerHasZAState |=
4429 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4431 CallerHasZT0State |=
4433 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4435 }
4436 }
4437
4438 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4439 Diag(Loc, diag::err_sme_za_call_no_za_state);
4440
4441 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4442 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4443
4444 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4445 CalleeArmZT0State != FunctionType::ARM_None) {
4446 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4447 Diag(Loc, diag::note_sme_use_preserves_za);
4448 }
4449 }
4450 }
4451
4452 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4453 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4454 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4455 if (!Arg->isValueDependent()) {
4456 Expr::EvalResult Align;
4457 if (Arg->EvaluateAsInt(Align, Context)) {
4458 const llvm::APSInt &I = Align.Val.getInt();
4459 if (!I.isPowerOf2())
4460 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4461 << Arg->getSourceRange();
4462
4463 if (I > Sema::MaximumAlignment)
4464 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4465 << Arg->getSourceRange() << Sema::MaximumAlignment;
4466 }
4467 }
4468 }
4469
4470 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4472 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4473 << diag::OffloadLang::SYCL;
4474
4475 if (FD)
4476 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4477}
4478
4479void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4480 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4481 DiagnoseUseOfDecl(Decl, Loc);
4482 }
4483}
4484
4485void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4487 const FunctionProtoType *Proto,
4488 SourceLocation Loc) {
4489 VariadicCallType CallType = Proto->isVariadic()
4492
4493 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4494 CheckArgAlignment(
4495 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4496 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4497
4498 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4499 Loc, SourceRange(), CallType);
4500}
4501
4503 const FunctionProtoType *Proto) {
4504 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4505 isa<CXXMethodDecl>(FDecl);
4506 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4507 IsMemberOperatorCall;
4508 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4509 TheCall->getCallee());
4510 Expr** Args = TheCall->getArgs();
4511 unsigned NumArgs = TheCall->getNumArgs();
4512
4513 Expr *ImplicitThis = nullptr;
4514 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4515 // If this is a call to a member operator, hide the first
4516 // argument from checkCall.
4517 // FIXME: Our choice of AST representation here is less than ideal.
4518 ImplicitThis = Args[0];
4519 ++Args;
4520 --NumArgs;
4521 } else if (IsMemberFunction && !FDecl->isStatic() &&
4523 ImplicitThis =
4524 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4525
4526 if (ImplicitThis) {
4527 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4528 // used.
4529 QualType ThisType = ImplicitThis->getType();
4530 if (!ThisType->isPointerType()) {
4531 assert(!ThisType->isReferenceType());
4532 ThisType = Context.getPointerType(ThisType);
4533 }
4534
4535 QualType ThisTypeFromDecl = Context.getPointerType(
4536 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4537
4538 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4539 ThisTypeFromDecl);
4540 }
4541
4542 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4543 IsMemberFunction, TheCall->getRParenLoc(),
4544 TheCall->getCallee()->getSourceRange(), CallType);
4545
4546 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4547 // None of the checks below are needed for functions that don't have
4548 // simple names (e.g., C++ conversion functions).
4549 if (!FnInfo)
4550 return false;
4551
4552 // Enforce TCB except for builtin calls, which are always allowed.
4553 if (FDecl->getBuiltinID() == 0)
4554 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4555
4556 CheckAbsoluteValueFunction(TheCall, FDecl);
4557 CheckMaxUnsignedZero(TheCall, FDecl);
4558 CheckInfNaNFunction(TheCall, FDecl);
4559
4560 if (getLangOpts().ObjC)
4561 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4562
4563 unsigned CMId = FDecl->getMemoryFunctionKind();
4564
4565 // Handle memory setting and copying functions.
4566 switch (CMId) {
4567 case 0:
4568 return false;
4569 case Builtin::BIstrlcpy: // fallthrough
4570 case Builtin::BIstrlcat:
4571 CheckStrlcpycatArguments(TheCall, FnInfo);
4572 break;
4573 case Builtin::BIstrncat:
4574 CheckStrncatArguments(TheCall, FnInfo);
4575 break;
4576 case Builtin::BIfree:
4577 CheckFreeArguments(TheCall);
4578 break;
4579 default:
4580 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4581 }
4582
4583 return false;
4584}
4585
4586bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4587 const FunctionProtoType *Proto) {
4588 QualType Ty;
4589 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4590 Ty = V->getType().getNonReferenceType();
4591 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4592 Ty = F->getType().getNonReferenceType();
4593 else
4594 return false;
4595
4596 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4597 !Ty->isFunctionProtoType())
4598 return false;
4599
4600 VariadicCallType CallType;
4601 if (!Proto || !Proto->isVariadic()) {
4603 } else if (Ty->isBlockPointerType()) {
4604 CallType = VariadicCallType::Block;
4605 } else { // Ty->isFunctionPointerType()
4606 CallType = VariadicCallType::Function;
4607 }
4608
4609 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4610 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4611 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4612 TheCall->getCallee()->getSourceRange(), CallType);
4613
4614 return false;
4615}
4616
4617bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4618 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4619 TheCall->getCallee());
4620 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4621 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4622 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4623 TheCall->getCallee()->getSourceRange(), CallType);
4624
4625 return false;
4626}
4627
4628static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4629 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4630 return false;
4631
4632 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4633 switch (Op) {
4634 case AtomicExpr::AO__c11_atomic_init:
4635 case AtomicExpr::AO__opencl_atomic_init:
4636 llvm_unreachable("There is no ordering argument for an init");
4637
4638 case AtomicExpr::AO__c11_atomic_load:
4639 case AtomicExpr::AO__opencl_atomic_load:
4640 case AtomicExpr::AO__hip_atomic_load:
4641 case AtomicExpr::AO__atomic_load_n:
4642 case AtomicExpr::AO__atomic_load:
4643 case AtomicExpr::AO__scoped_atomic_load_n:
4644 case AtomicExpr::AO__scoped_atomic_load:
4645 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4646 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4647
4648 case AtomicExpr::AO__c11_atomic_store:
4649 case AtomicExpr::AO__opencl_atomic_store:
4650 case AtomicExpr::AO__hip_atomic_store:
4651 case AtomicExpr::AO__atomic_store:
4652 case AtomicExpr::AO__atomic_store_n:
4653 case AtomicExpr::AO__scoped_atomic_store:
4654 case AtomicExpr::AO__scoped_atomic_store_n:
4655 case AtomicExpr::AO__atomic_clear:
4656 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4657 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4658 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4659
4660 default:
4661 return true;
4662 }
4663}
4664
4665ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4667 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4668 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4669 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4670 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4671 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4672 Op);
4673}
4674
4675/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4676/// equivalents. Provide a fixit when the scope is a compile-time constant and
4677/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4678/// compare_exchange builtins differ in how they accept the desired value, so
4679/// only a warning (without a fixit) is emitted for those.
4681 MultiExprArg Args,
4683 StringRef OldName;
4684 StringRef NewName;
4685 bool CanFixIt;
4686
4687 switch (Op) {
4688#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4689 case AtomicExpr::AO__hip_atomic_##hip: \
4690 OldName = "__hip_atomic_" #hip; \
4691 NewName = "__scoped_atomic_" #scoped; \
4692 CanFixIt = true; \
4693 break;
4694 HIP_ATOMIC_FIXABLE(load, load_n)
4695 HIP_ATOMIC_FIXABLE(store, store_n)
4696 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4697 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4698 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4699 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4700 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4701 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4702 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4703 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4704#undef HIP_ATOMIC_FIXABLE
4705 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4706 OldName = "__hip_atomic_compare_exchange_weak";
4707 NewName = "__scoped_atomic_compare_exchange";
4708 CanFixIt = false;
4709 break;
4710 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4711 OldName = "__hip_atomic_compare_exchange_strong";
4712 NewName = "__scoped_atomic_compare_exchange";
4713 CanFixIt = false;
4714 break;
4715 default:
4716 llvm_unreachable("unhandled HIP atomic op");
4717 }
4718
4719 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4720 << OldName << NewName;
4721 if (!CanFixIt)
4722 return;
4723
4724 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4725
4726 Expr *Scope = Args[Args.size() - 1];
4727 std::optional<llvm::APSInt> ScopeVal =
4728 Scope->getIntegerConstantExpr(S.Context);
4729 if (!ScopeVal)
4730 return;
4731
4732 StringRef ScopeName;
4733 switch (ScopeVal->getZExtValue()) {
4735 ScopeName = "__MEMORY_SCOPE_SINGLE";
4736 break;
4738 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4739 break;
4741 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4742 break;
4744 ScopeName = "__MEMORY_SCOPE_DEVICE";
4745 break;
4747 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4748 break;
4750 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4751 break;
4752 default:
4753 return;
4754 }
4755
4757 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
4758}
4759
4761 SourceLocation RParenLoc, MultiExprArg Args,
4763 AtomicArgumentOrder ArgOrder) {
4764 // All the non-OpenCL operations take one of the following forms.
4765 // The OpenCL operations take the __c11 forms with one extra argument for
4766 // synchronization scope.
4767 enum {
4768 // C __c11_atomic_init(A *, C)
4769 Init,
4770
4771 // C __c11_atomic_load(A *, int)
4772 Load,
4773
4774 // void __atomic_load(A *, CP, int)
4775 LoadCopy,
4776
4777 // void __atomic_store(A *, CP, int)
4778 Copy,
4779
4780 // C __c11_atomic_add(A *, M, int)
4781 Arithmetic,
4782
4783 // C __atomic_exchange_n(A *, CP, int)
4784 Xchg,
4785
4786 // void __atomic_exchange(A *, C *, CP, int)
4787 GNUXchg,
4788
4789 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4790 C11CmpXchg,
4791
4792 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4793 GNUCmpXchg,
4794
4795 // bool __atomic_test_and_set(A *, int)
4796 TestAndSetByte,
4797
4798 // void __atomic_clear(A *, int)
4799 ClearByte,
4800 } Form = Init;
4801
4802 const unsigned NumForm = ClearByte + 1;
4803 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4804 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4805 // where:
4806 // C is an appropriate type,
4807 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4808 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4809 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4810 // the int parameters are for orderings.
4811
4812 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4813 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4814 "need to update code for modified forms");
4815 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4816 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4817 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4818 "need to update code for modified C11 atomics");
4819 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4820 Op <= AtomicExpr::AO__opencl_atomic_store;
4821 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4822 Op <= AtomicExpr::AO__hip_atomic_store;
4823 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4824 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4825 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4826 Op <= AtomicExpr::AO__c11_atomic_store) ||
4827 IsOpenCL;
4828 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4829 Op == AtomicExpr::AO__atomic_store_n ||
4830 Op == AtomicExpr::AO__atomic_exchange_n ||
4831 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4832 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4833 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4834 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4835 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4836 // Bit mask for extra allowed value types other than integers for atomic
4837 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4838 // allow floating point.
4839 enum ArithOpExtraValueType {
4840 AOEVT_None = 0,
4841 AOEVT_Pointer = 1,
4842 AOEVT_FP = 2,
4843 };
4844 unsigned ArithAllows = AOEVT_None;
4845
4846 switch (Op) {
4847 case AtomicExpr::AO__c11_atomic_init:
4848 case AtomicExpr::AO__opencl_atomic_init:
4849 Form = Init;
4850 break;
4851
4852 case AtomicExpr::AO__c11_atomic_load:
4853 case AtomicExpr::AO__opencl_atomic_load:
4854 case AtomicExpr::AO__hip_atomic_load:
4855 case AtomicExpr::AO__atomic_load_n:
4856 case AtomicExpr::AO__scoped_atomic_load_n:
4857 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4858 Form = Load;
4859 break;
4860
4861 case AtomicExpr::AO__atomic_load:
4862 case AtomicExpr::AO__scoped_atomic_load:
4863 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4864 Form = LoadCopy;
4865 break;
4866
4867 case AtomicExpr::AO__c11_atomic_store:
4868 case AtomicExpr::AO__opencl_atomic_store:
4869 case AtomicExpr::AO__hip_atomic_store:
4870 case AtomicExpr::AO__atomic_store:
4871 case AtomicExpr::AO__atomic_store_n:
4872 case AtomicExpr::AO__scoped_atomic_store:
4873 case AtomicExpr::AO__scoped_atomic_store_n:
4874 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4875 Form = Copy;
4876 break;
4877 case AtomicExpr::AO__atomic_fetch_add:
4878 case AtomicExpr::AO__atomic_fetch_sub:
4879 case AtomicExpr::AO__atomic_add_fetch:
4880 case AtomicExpr::AO__atomic_sub_fetch:
4881 case AtomicExpr::AO__scoped_atomic_fetch_add:
4882 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4883 case AtomicExpr::AO__scoped_atomic_add_fetch:
4884 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4885 case AtomicExpr::AO__c11_atomic_fetch_add:
4886 case AtomicExpr::AO__c11_atomic_fetch_sub:
4887 case AtomicExpr::AO__opencl_atomic_fetch_add:
4888 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4889 case AtomicExpr::AO__hip_atomic_fetch_add:
4890 case AtomicExpr::AO__hip_atomic_fetch_sub:
4891 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4892 Form = Arithmetic;
4893 break;
4894 case AtomicExpr::AO__atomic_fetch_max:
4895 case AtomicExpr::AO__atomic_fetch_min:
4896 case AtomicExpr::AO__atomic_max_fetch:
4897 case AtomicExpr::AO__atomic_min_fetch:
4898 case AtomicExpr::AO__scoped_atomic_fetch_max:
4899 case AtomicExpr::AO__scoped_atomic_fetch_min:
4900 case AtomicExpr::AO__scoped_atomic_max_fetch:
4901 case AtomicExpr::AO__scoped_atomic_min_fetch:
4902 case AtomicExpr::AO__c11_atomic_fetch_max:
4903 case AtomicExpr::AO__c11_atomic_fetch_min:
4904 case AtomicExpr::AO__opencl_atomic_fetch_max:
4905 case AtomicExpr::AO__opencl_atomic_fetch_min:
4906 case AtomicExpr::AO__hip_atomic_fetch_max:
4907 case AtomicExpr::AO__hip_atomic_fetch_min:
4908 ArithAllows = AOEVT_FP;
4909 Form = Arithmetic;
4910 break;
4911 case AtomicExpr::AO__c11_atomic_fetch_and:
4912 case AtomicExpr::AO__c11_atomic_fetch_or:
4913 case AtomicExpr::AO__c11_atomic_fetch_xor:
4914 case AtomicExpr::AO__hip_atomic_fetch_and:
4915 case AtomicExpr::AO__hip_atomic_fetch_or:
4916 case AtomicExpr::AO__hip_atomic_fetch_xor:
4917 case AtomicExpr::AO__c11_atomic_fetch_nand:
4918 case AtomicExpr::AO__opencl_atomic_fetch_and:
4919 case AtomicExpr::AO__opencl_atomic_fetch_or:
4920 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4921 case AtomicExpr::AO__atomic_fetch_and:
4922 case AtomicExpr::AO__atomic_fetch_or:
4923 case AtomicExpr::AO__atomic_fetch_xor:
4924 case AtomicExpr::AO__atomic_fetch_nand:
4925 case AtomicExpr::AO__atomic_and_fetch:
4926 case AtomicExpr::AO__atomic_or_fetch:
4927 case AtomicExpr::AO__atomic_xor_fetch:
4928 case AtomicExpr::AO__atomic_nand_fetch:
4929 case AtomicExpr::AO__atomic_fetch_uinc:
4930 case AtomicExpr::AO__atomic_fetch_udec:
4931 case AtomicExpr::AO__scoped_atomic_fetch_and:
4932 case AtomicExpr::AO__scoped_atomic_fetch_or:
4933 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4934 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4935 case AtomicExpr::AO__scoped_atomic_and_fetch:
4936 case AtomicExpr::AO__scoped_atomic_or_fetch:
4937 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4938 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4939 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4940 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4941 Form = Arithmetic;
4942 break;
4943
4944 case AtomicExpr::AO__c11_atomic_exchange:
4945 case AtomicExpr::AO__hip_atomic_exchange:
4946 case AtomicExpr::AO__opencl_atomic_exchange:
4947 case AtomicExpr::AO__atomic_exchange_n:
4948 case AtomicExpr::AO__scoped_atomic_exchange_n:
4949 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4950 Form = Xchg;
4951 break;
4952
4953 case AtomicExpr::AO__atomic_exchange:
4954 case AtomicExpr::AO__scoped_atomic_exchange:
4955 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4956 Form = GNUXchg;
4957 break;
4958
4959 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4960 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4961 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4962 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4963 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4964 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4965 Form = C11CmpXchg;
4966 break;
4967
4968 case AtomicExpr::AO__atomic_compare_exchange:
4969 case AtomicExpr::AO__atomic_compare_exchange_n:
4970 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4971 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4972 ArithAllows = AOEVT_Pointer;
4973 Form = GNUCmpXchg;
4974 break;
4975
4976 case AtomicExpr::AO__atomic_test_and_set:
4977 Form = TestAndSetByte;
4978 break;
4979
4980 case AtomicExpr::AO__atomic_clear:
4981 Form = ClearByte;
4982 break;
4983 }
4984
4985 unsigned AdjustedNumArgs = NumArgs[Form];
4986 if ((IsOpenCL || IsHIP || IsScoped) &&
4987 Op != AtomicExpr::AO__opencl_atomic_init)
4988 ++AdjustedNumArgs;
4989 // Check we have the right number of arguments.
4990 if (Args.size() < AdjustedNumArgs) {
4991 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4992 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4993 << /*is non object*/ 0 << ExprRange;
4994 return ExprError();
4995 } else if (Args.size() > AdjustedNumArgs) {
4996 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4997 diag::err_typecheck_call_too_many_args)
4998 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4999 << /*is non object*/ 0 << ExprRange;
5000 return ExprError();
5001 }
5002
5003 // Inspect the first argument of the atomic operation.
5004 Expr *Ptr = Args[0];
5006 if (ConvertedPtr.isInvalid())
5007 return ExprError();
5008
5009 Ptr = ConvertedPtr.get();
5010 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5011 if (!pointerType) {
5012 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5013 << Ptr->getType() << 0 << Ptr->getSourceRange();
5014 return ExprError();
5015 }
5016
5017 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5018 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5019 QualType ValType = AtomTy; // 'C'
5020 if (IsC11) {
5021 if (!AtomTy->isAtomicType()) {
5022 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5023 << Ptr->getType() << Ptr->getSourceRange();
5024 return ExprError();
5025 }
5026 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5028 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5029 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5030 << Ptr->getSourceRange();
5031 return ExprError();
5032 }
5033 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5034 } else if (Form != Load && Form != LoadCopy) {
5035 if (ValType.isConstQualified()) {
5036 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5037 << Ptr->getType() << Ptr->getSourceRange();
5038 return ExprError();
5039 }
5040 }
5041
5042 if (Form != TestAndSetByte && Form != ClearByte) {
5043 // Pointer to object of size zero is not allowed.
5044 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5045 diag::err_incomplete_type))
5046 return ExprError();
5047
5048 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5049 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5050 << Ptr->getType() << 1 << Ptr->getSourceRange();
5051 return ExprError();
5052 }
5053 } else {
5054 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5055 // non-const pointer type, including void* and pointers to incomplete
5056 // structs, but only access the first byte.
5057 AtomTy = Context.CharTy;
5058 AtomTy = AtomTy.withCVRQualifiers(
5059 pointerType->getPointeeType().getCVRQualifiers());
5060 QualType PointerQT = Context.getPointerType(AtomTy);
5061 pointerType = PointerQT->getAs<PointerType>();
5062 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5063 ValType = AtomTy;
5064 }
5065
5066 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5067 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5068 Diag(ExprRange.getBegin(),
5069 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5070 << 0 << Ptr->getType() << Ptr->getSourceRange();
5071 return ExprError();
5072 }
5073
5074 // For an arithmetic operation, the implied arithmetic must be well-formed.
5075 // For _n operations, the value type must also be a valid atomic type.
5076 if (Form == Arithmetic || IsN) {
5077 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5078 // trivial type errors.
5079 auto IsAllowedValueType = [&](QualType ValType,
5080 unsigned AllowedType) -> bool {
5081 bool IsX87LongDouble =
5082 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5083 &Context.getTargetInfo().getLongDoubleFormat() ==
5084 &llvm::APFloat::x87DoubleExtended();
5085 if (ValType->isIntegerType())
5086 return true;
5087 if (ValType->isPointerType())
5088 return AllowedType & AOEVT_Pointer;
5089 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5090 return false;
5091 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5092 if (IsX87LongDouble)
5093 return false;
5094 return true;
5095 };
5096 if (!IsAllowedValueType(ValType, ArithAllows)) {
5097 auto DID = ArithAllows & AOEVT_FP
5098 ? (ArithAllows & AOEVT_Pointer
5099 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5100 : diag::err_atomic_op_needs_atomic_int_or_fp)
5101 : (ArithAllows & AOEVT_Pointer
5102 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5103 : diag::err_atomic_op_needs_atomic_int);
5104 Diag(ExprRange.getBegin(), DID)
5105 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5106 return ExprError();
5107 }
5108 if (IsC11 && ValType->isPointerType() &&
5110 diag::err_incomplete_type)) {
5111 return ExprError();
5112 }
5113 }
5114
5115 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5116 !AtomTy->isScalarType()) {
5117 // For GNU atomics, require a trivially-copyable type. This is not part of
5118 // the GNU atomics specification but we enforce it for consistency with
5119 // other atomics which generally all require a trivially-copyable type. This
5120 // is because atomics just copy bits.
5121 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5122 << Ptr->getType() << Ptr->getSourceRange();
5123 return ExprError();
5124 }
5125
5126 switch (ValType.getObjCLifetime()) {
5129 // okay
5130 break;
5131
5135 // FIXME: Can this happen? By this point, ValType should be known
5136 // to be trivially copyable.
5137 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5138 << ValType << Ptr->getSourceRange();
5139 return ExprError();
5140 }
5141
5142 // All atomic operations have an overload which takes a pointer to a volatile
5143 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5144 // into the result or the other operands. Similarly atomic_load takes a
5145 // pointer to a const 'A'.
5146 ValType.removeLocalVolatile();
5147 ValType.removeLocalConst();
5148 QualType ResultType = ValType;
5149 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5150 Form == ClearByte)
5151 ResultType = Context.VoidTy;
5152 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5153 ResultType = Context.BoolTy;
5154
5155 // The type of a parameter passed 'by value'. In the GNU atomics, such
5156 // arguments are actually passed as pointers.
5157 QualType ByValType = ValType; // 'CP'
5158 bool IsPassedByAddress = false;
5159 if (!IsC11 && !IsHIP && !IsN) {
5160 ByValType = Ptr->getType();
5161 IsPassedByAddress = true;
5162 }
5163
5164 SmallVector<Expr *, 5> APIOrderedArgs;
5165 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5166 APIOrderedArgs.push_back(Args[0]);
5167 switch (Form) {
5168 case Init:
5169 case Load:
5170 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5171 break;
5172 case LoadCopy:
5173 case Copy:
5174 case Arithmetic:
5175 case Xchg:
5176 APIOrderedArgs.push_back(Args[2]); // Val1
5177 APIOrderedArgs.push_back(Args[1]); // Order
5178 break;
5179 case GNUXchg:
5180 APIOrderedArgs.push_back(Args[2]); // Val1
5181 APIOrderedArgs.push_back(Args[3]); // Val2
5182 APIOrderedArgs.push_back(Args[1]); // Order
5183 break;
5184 case C11CmpXchg:
5185 APIOrderedArgs.push_back(Args[2]); // Val1
5186 APIOrderedArgs.push_back(Args[4]); // Val2
5187 APIOrderedArgs.push_back(Args[1]); // Order
5188 APIOrderedArgs.push_back(Args[3]); // OrderFail
5189 break;
5190 case GNUCmpXchg:
5191 APIOrderedArgs.push_back(Args[2]); // Val1
5192 APIOrderedArgs.push_back(Args[4]); // Val2
5193 APIOrderedArgs.push_back(Args[5]); // Weak
5194 APIOrderedArgs.push_back(Args[1]); // Order
5195 APIOrderedArgs.push_back(Args[3]); // OrderFail
5196 break;
5197 case TestAndSetByte:
5198 case ClearByte:
5199 APIOrderedArgs.push_back(Args[1]); // Order
5200 break;
5201 }
5202 } else
5203 APIOrderedArgs.append(Args.begin(), Args.end());
5204
5205 // The first argument's non-CV pointer type is used to deduce the type of
5206 // subsequent arguments, except for:
5207 // - weak flag (always converted to bool)
5208 // - memory order (always converted to int)
5209 // - scope (always converted to int)
5210 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5211 QualType Ty;
5212 if (i < NumVals[Form] + 1) {
5213 switch (i) {
5214 case 0:
5215 // The first argument is always a pointer. It has a fixed type.
5216 // It is always dereferenced, a nullptr is undefined.
5217 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5218 // Nothing else to do: we already know all we want about this pointer.
5219 continue;
5220 case 1:
5221 // The second argument is the non-atomic operand. For arithmetic, this
5222 // is always passed by value, and for a compare_exchange it is always
5223 // passed by address. For the rest, GNU uses by-address and C11 uses
5224 // by-value.
5225 assert(Form != Load);
5226 if (Form == Arithmetic && ValType->isPointerType())
5227 Ty = Context.getPointerDiffType();
5228 else if (Form == Init || Form == Arithmetic)
5229 Ty = ValType;
5230 else if (Form == Copy || Form == Xchg) {
5231 if (IsPassedByAddress) {
5232 // The value pointer is always dereferenced, a nullptr is undefined.
5233 CheckNonNullArgument(*this, APIOrderedArgs[i],
5234 ExprRange.getBegin());
5235 }
5236 Ty = ByValType;
5237 } else {
5238 Expr *ValArg = APIOrderedArgs[i];
5239 // The value pointer is always dereferenced, a nullptr is undefined.
5240 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5242 // Keep address space of non-atomic pointer type.
5243 if (const PointerType *PtrTy =
5244 ValArg->getType()->getAs<PointerType>()) {
5245 AS = PtrTy->getPointeeType().getAddressSpace();
5246 }
5247 Ty = Context.getPointerType(
5248 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5249 }
5250 break;
5251 case 2:
5252 // The third argument to compare_exchange / GNU exchange is the desired
5253 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5254 if (IsPassedByAddress)
5255 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5256 Ty = ByValType;
5257 break;
5258 case 3:
5259 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5260 Ty = Context.BoolTy;
5261 break;
5262 }
5263 } else {
5264 // The order(s) and scope are always converted to int.
5265 Ty = Context.IntTy;
5266 }
5267
5268 InitializedEntity Entity =
5270 ExprResult Arg = APIOrderedArgs[i];
5271 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5272 if (Arg.isInvalid())
5273 return true;
5274 APIOrderedArgs[i] = Arg.get();
5275 }
5276
5277 // Permute the arguments into a 'consistent' order.
5278 SmallVector<Expr*, 5> SubExprs;
5279 SubExprs.push_back(Ptr);
5280 switch (Form) {
5281 case Init:
5282 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5283 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5284 break;
5285 case Load:
5286 case TestAndSetByte:
5287 case ClearByte:
5288 SubExprs.push_back(APIOrderedArgs[1]); // Order
5289 break;
5290 case LoadCopy:
5291 case Copy:
5292 case Arithmetic:
5293 case Xchg:
5294 SubExprs.push_back(APIOrderedArgs[2]); // Order
5295 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5296 break;
5297 case GNUXchg:
5298 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5299 SubExprs.push_back(APIOrderedArgs[3]); // Order
5300 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5301 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5302 break;
5303 case C11CmpXchg:
5304 SubExprs.push_back(APIOrderedArgs[3]); // Order
5305 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5306 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5307 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5308 break;
5309 case GNUCmpXchg:
5310 SubExprs.push_back(APIOrderedArgs[4]); // Order
5311 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5312 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5313 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5314 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5315 break;
5316 }
5317
5318 // If the memory orders are constants, check they are valid.
5319 if (SubExprs.size() >= 2 && Form != Init) {
5320 std::optional<llvm::APSInt> Success =
5321 SubExprs[1]->getIntegerConstantExpr(Context);
5322 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5323 Diag(SubExprs[1]->getBeginLoc(),
5324 diag::warn_atomic_op_has_invalid_memory_order)
5325 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5326 << SubExprs[1]->getSourceRange();
5327 }
5328 if (SubExprs.size() >= 5) {
5329 if (std::optional<llvm::APSInt> Failure =
5330 SubExprs[3]->getIntegerConstantExpr(Context)) {
5331 if (!llvm::is_contained(
5332 {llvm::AtomicOrderingCABI::relaxed,
5333 llvm::AtomicOrderingCABI::consume,
5334 llvm::AtomicOrderingCABI::acquire,
5335 llvm::AtomicOrderingCABI::seq_cst},
5336 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5337 Diag(SubExprs[3]->getBeginLoc(),
5338 diag::warn_atomic_op_has_invalid_memory_order)
5339 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5340 }
5341 }
5342 }
5343 }
5344
5345 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5346 auto *Scope = Args[Args.size() - 1];
5347 if (std::optional<llvm::APSInt> Result =
5348 Scope->getIntegerConstantExpr(Context)) {
5349 if (!ScopeModel->isValid(Result->getZExtValue()))
5350 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5351 << Scope->getSourceRange();
5352 }
5353 SubExprs.push_back(Scope);
5354 }
5355
5356 if (IsHIP)
5357 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5358
5359 AtomicExpr *AE = new (Context)
5360 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5361
5362 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5363 Op == AtomicExpr::AO__c11_atomic_store ||
5364 Op == AtomicExpr::AO__opencl_atomic_load ||
5365 Op == AtomicExpr::AO__hip_atomic_load ||
5366 Op == AtomicExpr::AO__opencl_atomic_store ||
5367 Op == AtomicExpr::AO__hip_atomic_store) &&
5368 Context.AtomicUsesUnsupportedLibcall(AE))
5369 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5370 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5371 Op == AtomicExpr::AO__opencl_atomic_load ||
5372 Op == AtomicExpr::AO__hip_atomic_load)
5373 ? 0
5374 : 1);
5375
5376 if (ValType->isBitIntType()) {
5377 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5378 return ExprError();
5379 }
5380
5381 return AE;
5382}
5383
5384/// checkBuiltinArgument - Given a call to a builtin function, perform
5385/// normal type-checking on the given argument, updating the call in
5386/// place. This is useful when a builtin function requires custom
5387/// type-checking for some of its arguments but not necessarily all of
5388/// them.
5389///
5390/// Returns true on error.
5391static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5392 FunctionDecl *Fn = E->getDirectCallee();
5393 assert(Fn && "builtin call without direct callee!");
5394
5395 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5396 InitializedEntity Entity =
5398
5399 ExprResult Arg = E->getArg(ArgIndex);
5400 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5401 if (Arg.isInvalid())
5402 return true;
5403
5404 E->setArg(ArgIndex, Arg.get());
5405 return false;
5406}
5407
5408ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5409 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5410 Expr *Callee = TheCall->getCallee();
5411 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5412 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5413
5414 // Ensure that we have at least one argument to do type inference from.
5415 if (TheCall->getNumArgs() < 1) {
5416 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5417 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5418 << Callee->getSourceRange();
5419 return ExprError();
5420 }
5421
5422 // Inspect the first argument of the atomic builtin. This should always be
5423 // a pointer type, whose element is an integral scalar or pointer type.
5424 // Because it is a pointer type, we don't have to worry about any implicit
5425 // casts here.
5426 // FIXME: We don't allow floating point scalars as input.
5427 Expr *FirstArg = TheCall->getArg(0);
5428 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5429 if (FirstArgResult.isInvalid())
5430 return ExprError();
5431 FirstArg = FirstArgResult.get();
5432 TheCall->setArg(0, FirstArg);
5433
5434 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5435 if (!pointerType) {
5436 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5437 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5438 return ExprError();
5439 }
5440
5441 QualType ValType = pointerType->getPointeeType();
5442 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5443 !ValType->isBlockPointerType()) {
5444 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5445 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5446 return ExprError();
5447 }
5448 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5449 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5450 Diag(FirstArg->getBeginLoc(),
5451 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5452 << 1 << ValType << FirstArg->getSourceRange();
5453 return ExprError();
5454 }
5455
5456 if (ValType.isConstQualified()) {
5457 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5458 << FirstArg->getType() << FirstArg->getSourceRange();
5459 return ExprError();
5460 }
5461
5462 switch (ValType.getObjCLifetime()) {
5465 // okay
5466 break;
5467
5471 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5472 << ValType << FirstArg->getSourceRange();
5473 return ExprError();
5474 }
5475
5476 // Strip any qualifiers off ValType.
5477 ValType = ValType.getUnqualifiedType();
5478
5479 // The majority of builtins return a value, but a few have special return
5480 // types, so allow them to override appropriately below.
5481 QualType ResultType = ValType;
5482
5483 // We need to figure out which concrete builtin this maps onto. For example,
5484 // __sync_fetch_and_add with a 2 byte object turns into
5485 // __sync_fetch_and_add_2.
5486#define BUILTIN_ROW(x) \
5487 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5488 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5489
5490 static const unsigned BuiltinIndices[][5] = {
5491 BUILTIN_ROW(__sync_fetch_and_add),
5492 BUILTIN_ROW(__sync_fetch_and_sub),
5493 BUILTIN_ROW(__sync_fetch_and_or),
5494 BUILTIN_ROW(__sync_fetch_and_and),
5495 BUILTIN_ROW(__sync_fetch_and_xor),
5496 BUILTIN_ROW(__sync_fetch_and_nand),
5497
5498 BUILTIN_ROW(__sync_add_and_fetch),
5499 BUILTIN_ROW(__sync_sub_and_fetch),
5500 BUILTIN_ROW(__sync_and_and_fetch),
5501 BUILTIN_ROW(__sync_or_and_fetch),
5502 BUILTIN_ROW(__sync_xor_and_fetch),
5503 BUILTIN_ROW(__sync_nand_and_fetch),
5504
5505 BUILTIN_ROW(__sync_val_compare_and_swap),
5506 BUILTIN_ROW(__sync_bool_compare_and_swap),
5507 BUILTIN_ROW(__sync_lock_test_and_set),
5508 BUILTIN_ROW(__sync_lock_release),
5509 BUILTIN_ROW(__sync_swap)
5510 };
5511#undef BUILTIN_ROW
5512
5513 // Determine the index of the size.
5514 unsigned SizeIndex;
5515 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5516 case 1: SizeIndex = 0; break;
5517 case 2: SizeIndex = 1; break;
5518 case 4: SizeIndex = 2; break;
5519 case 8: SizeIndex = 3; break;
5520 case 16: SizeIndex = 4; break;
5521 default:
5522 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5523 << FirstArg->getType() << FirstArg->getSourceRange();
5524 return ExprError();
5525 }
5526
5527 // Each of these builtins has one pointer argument, followed by some number of
5528 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5529 // that we ignore. Find out which row of BuiltinIndices to read from as well
5530 // as the number of fixed args.
5531 unsigned BuiltinID = FDecl->getBuiltinID();
5532 unsigned BuiltinIndex, NumFixed = 1;
5533 bool WarnAboutSemanticsChange = false;
5534 switch (BuiltinID) {
5535 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5536 case Builtin::BI__sync_fetch_and_add:
5537 case Builtin::BI__sync_fetch_and_add_1:
5538 case Builtin::BI__sync_fetch_and_add_2:
5539 case Builtin::BI__sync_fetch_and_add_4:
5540 case Builtin::BI__sync_fetch_and_add_8:
5541 case Builtin::BI__sync_fetch_and_add_16:
5542 BuiltinIndex = 0;
5543 break;
5544
5545 case Builtin::BI__sync_fetch_and_sub:
5546 case Builtin::BI__sync_fetch_and_sub_1:
5547 case Builtin::BI__sync_fetch_and_sub_2:
5548 case Builtin::BI__sync_fetch_and_sub_4:
5549 case Builtin::BI__sync_fetch_and_sub_8:
5550 case Builtin::BI__sync_fetch_and_sub_16:
5551 BuiltinIndex = 1;
5552 break;
5553
5554 case Builtin::BI__sync_fetch_and_or:
5555 case Builtin::BI__sync_fetch_and_or_1:
5556 case Builtin::BI__sync_fetch_and_or_2:
5557 case Builtin::BI__sync_fetch_and_or_4:
5558 case Builtin::BI__sync_fetch_and_or_8:
5559 case Builtin::BI__sync_fetch_and_or_16:
5560 BuiltinIndex = 2;
5561 break;
5562
5563 case Builtin::BI__sync_fetch_and_and:
5564 case Builtin::BI__sync_fetch_and_and_1:
5565 case Builtin::BI__sync_fetch_and_and_2:
5566 case Builtin::BI__sync_fetch_and_and_4:
5567 case Builtin::BI__sync_fetch_and_and_8:
5568 case Builtin::BI__sync_fetch_and_and_16:
5569 BuiltinIndex = 3;
5570 break;
5571
5572 case Builtin::BI__sync_fetch_and_xor:
5573 case Builtin::BI__sync_fetch_and_xor_1:
5574 case Builtin::BI__sync_fetch_and_xor_2:
5575 case Builtin::BI__sync_fetch_and_xor_4:
5576 case Builtin::BI__sync_fetch_and_xor_8:
5577 case Builtin::BI__sync_fetch_and_xor_16:
5578 BuiltinIndex = 4;
5579 break;
5580
5581 case Builtin::BI__sync_fetch_and_nand:
5582 case Builtin::BI__sync_fetch_and_nand_1:
5583 case Builtin::BI__sync_fetch_and_nand_2:
5584 case Builtin::BI__sync_fetch_and_nand_4:
5585 case Builtin::BI__sync_fetch_and_nand_8:
5586 case Builtin::BI__sync_fetch_and_nand_16:
5587 BuiltinIndex = 5;
5588 WarnAboutSemanticsChange = true;
5589 break;
5590
5591 case Builtin::BI__sync_add_and_fetch:
5592 case Builtin::BI__sync_add_and_fetch_1:
5593 case Builtin::BI__sync_add_and_fetch_2:
5594 case Builtin::BI__sync_add_and_fetch_4:
5595 case Builtin::BI__sync_add_and_fetch_8:
5596 case Builtin::BI__sync_add_and_fetch_16:
5597 BuiltinIndex = 6;
5598 break;
5599
5600 case Builtin::BI__sync_sub_and_fetch:
5601 case Builtin::BI__sync_sub_and_fetch_1:
5602 case Builtin::BI__sync_sub_and_fetch_2:
5603 case Builtin::BI__sync_sub_and_fetch_4:
5604 case Builtin::BI__sync_sub_and_fetch_8:
5605 case Builtin::BI__sync_sub_and_fetch_16:
5606 BuiltinIndex = 7;
5607 break;
5608
5609 case Builtin::BI__sync_and_and_fetch:
5610 case Builtin::BI__sync_and_and_fetch_1:
5611 case Builtin::BI__sync_and_and_fetch_2:
5612 case Builtin::BI__sync_and_and_fetch_4:
5613 case Builtin::BI__sync_and_and_fetch_8:
5614 case Builtin::BI__sync_and_and_fetch_16:
5615 BuiltinIndex = 8;
5616 break;
5617
5618 case Builtin::BI__sync_or_and_fetch:
5619 case Builtin::BI__sync_or_and_fetch_1:
5620 case Builtin::BI__sync_or_and_fetch_2:
5621 case Builtin::BI__sync_or_and_fetch_4:
5622 case Builtin::BI__sync_or_and_fetch_8:
5623 case Builtin::BI__sync_or_and_fetch_16:
5624 BuiltinIndex = 9;
5625 break;
5626
5627 case Builtin::BI__sync_xor_and_fetch:
5628 case Builtin::BI__sync_xor_and_fetch_1:
5629 case Builtin::BI__sync_xor_and_fetch_2:
5630 case Builtin::BI__sync_xor_and_fetch_4:
5631 case Builtin::BI__sync_xor_and_fetch_8:
5632 case Builtin::BI__sync_xor_and_fetch_16:
5633 BuiltinIndex = 10;
5634 break;
5635
5636 case Builtin::BI__sync_nand_and_fetch:
5637 case Builtin::BI__sync_nand_and_fetch_1:
5638 case Builtin::BI__sync_nand_and_fetch_2:
5639 case Builtin::BI__sync_nand_and_fetch_4:
5640 case Builtin::BI__sync_nand_and_fetch_8:
5641 case Builtin::BI__sync_nand_and_fetch_16:
5642 BuiltinIndex = 11;
5643 WarnAboutSemanticsChange = true;
5644 break;
5645
5646 case Builtin::BI__sync_val_compare_and_swap:
5647 case Builtin::BI__sync_val_compare_and_swap_1:
5648 case Builtin::BI__sync_val_compare_and_swap_2:
5649 case Builtin::BI__sync_val_compare_and_swap_4:
5650 case Builtin::BI__sync_val_compare_and_swap_8:
5651 case Builtin::BI__sync_val_compare_and_swap_16:
5652 BuiltinIndex = 12;
5653 NumFixed = 2;
5654 break;
5655
5656 case Builtin::BI__sync_bool_compare_and_swap:
5657 case Builtin::BI__sync_bool_compare_and_swap_1:
5658 case Builtin::BI__sync_bool_compare_and_swap_2:
5659 case Builtin::BI__sync_bool_compare_and_swap_4:
5660 case Builtin::BI__sync_bool_compare_and_swap_8:
5661 case Builtin::BI__sync_bool_compare_and_swap_16:
5662 BuiltinIndex = 13;
5663 NumFixed = 2;
5664 ResultType = Context.BoolTy;
5665 break;
5666
5667 case Builtin::BI__sync_lock_test_and_set:
5668 case Builtin::BI__sync_lock_test_and_set_1:
5669 case Builtin::BI__sync_lock_test_and_set_2:
5670 case Builtin::BI__sync_lock_test_and_set_4:
5671 case Builtin::BI__sync_lock_test_and_set_8:
5672 case Builtin::BI__sync_lock_test_and_set_16:
5673 BuiltinIndex = 14;
5674 break;
5675
5676 case Builtin::BI__sync_lock_release:
5677 case Builtin::BI__sync_lock_release_1:
5678 case Builtin::BI__sync_lock_release_2:
5679 case Builtin::BI__sync_lock_release_4:
5680 case Builtin::BI__sync_lock_release_8:
5681 case Builtin::BI__sync_lock_release_16:
5682 BuiltinIndex = 15;
5683 NumFixed = 0;
5684 ResultType = Context.VoidTy;
5685 break;
5686
5687 case Builtin::BI__sync_swap:
5688 case Builtin::BI__sync_swap_1:
5689 case Builtin::BI__sync_swap_2:
5690 case Builtin::BI__sync_swap_4:
5691 case Builtin::BI__sync_swap_8:
5692 case Builtin::BI__sync_swap_16:
5693 BuiltinIndex = 16;
5694 break;
5695 }
5696
5697 // Now that we know how many fixed arguments we expect, first check that we
5698 // have at least that many.
5699 if (TheCall->getNumArgs() < 1+NumFixed) {
5700 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5701 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5702 << Callee->getSourceRange();
5703 return ExprError();
5704 }
5705
5706 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5707 << Callee->getSourceRange();
5708
5709 if (WarnAboutSemanticsChange) {
5710 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5711 << Callee->getSourceRange();
5712 }
5713
5714 // Get the decl for the concrete builtin from this, we can tell what the
5715 // concrete integer type we should convert to is.
5716 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5717 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5718 FunctionDecl *NewBuiltinDecl;
5719 if (NewBuiltinID == BuiltinID)
5720 NewBuiltinDecl = FDecl;
5721 else {
5722 // Perform builtin lookup to avoid redeclaring it.
5723 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5724 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5725 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5726 assert(Res.getFoundDecl());
5727 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5728 if (!NewBuiltinDecl)
5729 return ExprError();
5730 }
5731
5732 // The first argument --- the pointer --- has a fixed type; we
5733 // deduce the types of the rest of the arguments accordingly. Walk
5734 // the remaining arguments, converting them to the deduced value type.
5735 for (unsigned i = 0; i != NumFixed; ++i) {
5736 ExprResult Arg = TheCall->getArg(i+1);
5737
5738 // GCC does an implicit conversion to the pointer or integer ValType. This
5739 // can fail in some cases (1i -> int**), check for this error case now.
5740 // Initialize the argument.
5741 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5742 ValType, /*consume*/ false);
5743 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5744 if (Arg.isInvalid())
5745 return ExprError();
5746
5747 // Okay, we have something that *can* be converted to the right type. Check
5748 // to see if there is a potentially weird extension going on here. This can
5749 // happen when you do an atomic operation on something like an char* and
5750 // pass in 42. The 42 gets converted to char. This is even more strange
5751 // for things like 45.123 -> char, etc.
5752 // FIXME: Do this check.
5753 TheCall->setArg(i+1, Arg.get());
5754 }
5755
5756 // Create a new DeclRefExpr to refer to the new decl.
5757 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5758 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5759 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5760 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5761
5762 // Set the callee in the CallExpr.
5763 // FIXME: This loses syntactic information.
5764 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5765 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5766 CK_BuiltinFnToFnPtr);
5767 TheCall->setCallee(PromotedCall.get());
5768
5769 // Change the result type of the call to match the original value type. This
5770 // is arbitrary, but the codegen for these builtins ins design to handle it
5771 // gracefully.
5772 TheCall->setType(ResultType);
5773
5774 // Prohibit problematic uses of bit-precise integer types with atomic
5775 // builtins. The arguments would have already been converted to the first
5776 // argument's type, so only need to check the first argument.
5777 const auto *BitIntValType = ValType->getAs<BitIntType>();
5778 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5779 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5780 return ExprError();
5781 }
5782
5783 return TheCallResult;
5784}
5785
5786ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5787 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5788 DeclRefExpr *DRE =
5790 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5791 unsigned BuiltinID = FDecl->getBuiltinID();
5792 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5793 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5794 "Unexpected nontemporal load/store builtin!");
5795 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5796 unsigned numArgs = isStore ? 2 : 1;
5797
5798 // Ensure that we have the proper number of arguments.
5799 if (checkArgCount(TheCall, numArgs))
5800 return ExprError();
5801
5802 // Inspect the last argument of the nontemporal builtin. This should always
5803 // be a pointer type, from which we imply the type of the memory access.
5804 // Because it is a pointer type, we don't have to worry about any implicit
5805 // casts here.
5806 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5807 ExprResult PointerArgResult =
5809
5810 if (PointerArgResult.isInvalid())
5811 return ExprError();
5812 PointerArg = PointerArgResult.get();
5813 TheCall->setArg(numArgs - 1, PointerArg);
5814
5815 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5816 if (!pointerType) {
5817 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5818 << PointerArg->getType() << PointerArg->getSourceRange();
5819 return ExprError();
5820 }
5821
5822 QualType ValType = pointerType->getPointeeType();
5823
5824 // Strip any qualifiers off ValType.
5825 ValType = ValType.getUnqualifiedType();
5826 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5827 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5828 !ValType->isVectorType()) {
5829 Diag(DRE->getBeginLoc(),
5830 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5831 << PointerArg->getType() << PointerArg->getSourceRange();
5832 return ExprError();
5833 }
5834
5835 if (!isStore) {
5836 TheCall->setType(ValType);
5837 return TheCallResult;
5838 }
5839
5840 ExprResult ValArg = TheCall->getArg(0);
5841 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5842 Context, ValType, /*consume*/ false);
5843 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5844 if (ValArg.isInvalid())
5845 return ExprError();
5846
5847 TheCall->setArg(0, ValArg.get());
5848 TheCall->setType(Context.VoidTy);
5849 return TheCallResult;
5850}
5851
5852/// CheckObjCString - Checks that the format string argument to the os_log()
5853/// and os_trace() functions is correct, and converts it to const char *.
5854ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5855 Arg = Arg->IgnoreParenCasts();
5856 auto *Literal = dyn_cast<StringLiteral>(Arg);
5857 if (!Literal) {
5858 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5859 Literal = ObjcLiteral->getString();
5860 }
5861 }
5862
5863 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5864 return ExprError(
5865 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5866 << Arg->getSourceRange());
5867 }
5868
5869 ExprResult Result(Literal);
5870 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5871 InitializedEntity Entity =
5873 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5874 return Result;
5875}
5876
5877/// Check that the user is calling the appropriate va_start builtin for the
5878/// target and calling convention.
5879static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5880 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5881 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5882 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5883 TT.getArch() == llvm::Triple::aarch64_32);
5884 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5885 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5886 if (IsX64 || IsAArch64) {
5887 CallingConv CC = CC_C;
5888 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5889 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5890 if (IsMSVAStart) {
5891 // Don't allow this in System V ABI functions.
5892 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5893 return S.Diag(Fn->getBeginLoc(),
5894 diag::err_ms_va_start_used_in_sysv_function);
5895 } else {
5896 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5897 // On x64 Windows, don't allow this in System V ABI functions.
5898 // (Yes, that means there's no corresponding way to support variadic
5899 // System V ABI functions on Windows.)
5900 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5901 (!IsWindowsOrUEFI && CC == CC_Win64))
5902 return S.Diag(Fn->getBeginLoc(),
5903 diag::err_va_start_used_in_wrong_abi_function)
5904 << !IsWindowsOrUEFI;
5905 }
5906 return false;
5907 }
5908
5909 if (IsMSVAStart)
5910 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5911 return false;
5912}
5913
5915 ParmVarDecl **LastParam = nullptr) {
5916 // Determine whether the current function, block, or obj-c method is variadic
5917 // and get its parameter list.
5918 bool IsVariadic = false;
5920 DeclContext *Caller = S.CurContext;
5921 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5922 IsVariadic = Block->isVariadic();
5923 Params = Block->parameters();
5924 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5925 IsVariadic = FD->isVariadic();
5926 Params = FD->parameters();
5927 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5928 IsVariadic = MD->isVariadic();
5929 // FIXME: This isn't correct for methods (results in bogus warning).
5930 Params = MD->parameters();
5931 } else if (isa<CapturedDecl>(Caller)) {
5932 // We don't support va_start in a CapturedDecl.
5933 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5934 return true;
5935 } else {
5936 // This must be some other declcontext that parses exprs.
5937 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5938 return true;
5939 }
5940
5941 if (!IsVariadic) {
5942 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5943 return true;
5944 }
5945
5946 if (LastParam)
5947 *LastParam = Params.empty() ? nullptr : Params.back();
5948
5949 return false;
5950}
5951
5952bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5953 Expr *Fn = TheCall->getCallee();
5954 if (checkVAStartABI(*this, BuiltinID, Fn))
5955 return true;
5956
5957 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5958 // This builtin requires one argument (the va_list), allows two arguments,
5959 // but diagnoses more than two arguments. e.g.,
5960 // __builtin_c23_va_start(); // error
5961 // __builtin_c23_va_start(list); // ok
5962 // __builtin_c23_va_start(list, param); // ok
5963 // __builtin_c23_va_start(list, anything, anything); // error
5964 // This differs from the GCC behavior in that they accept the last case
5965 // with a warning, but it doesn't seem like a useful behavior to allow.
5966 if (checkArgCountRange(TheCall, 1, 2))
5967 return true;
5968 } else {
5969 // In C23 mode, va_start only needs one argument. However, the builtin still
5970 // requires two arguments (which matches the behavior of the GCC builtin),
5971 // <stdarg.h> passes `0` as the second argument in C23 mode.
5972 if (checkArgCount(TheCall, 2))
5973 return true;
5974 }
5975
5976 // Type-check the first argument normally.
5977 if (checkBuiltinArgument(*this, TheCall, 0))
5978 return true;
5979
5980 // Check that the current function is variadic, and get its last parameter.
5981 ParmVarDecl *LastParam;
5982 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5983 return true;
5984
5985 // Verify that the second argument to the builtin is the last non-variadic
5986 // argument of the current function or method. In C23 mode, if the call is
5987 // not to __builtin_c23_va_start, and the second argument is an integer
5988 // constant expression with value 0, then we don't bother with this check.
5989 // For __builtin_c23_va_start, we only perform the check for the second
5990 // argument being the last argument to the current function if there is a
5991 // second argument present.
5992 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5993 TheCall->getNumArgs() < 2) {
5994 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5995 return false;
5996 }
5997
5998 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5999 if (std::optional<llvm::APSInt> Val =
6001 Val && LangOpts.C23 && *Val == 0 &&
6002 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6003 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6004 return false;
6005 }
6006
6007 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6008 // next block.
6009 QualType Type;
6010 SourceLocation ParamLoc;
6011 bool IsCRegister = false;
6012 bool SecondArgIsLastNonVariadicArgument = false;
6013 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6014 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6015 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6016
6017 Type = PV->getType();
6018 ParamLoc = PV->getLocation();
6019 IsCRegister =
6020 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6021 }
6022 }
6023
6024 if (!SecondArgIsLastNonVariadicArgument)
6025 Diag(TheCall->getArg(1)->getBeginLoc(),
6026 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6027 else if (IsCRegister || Type->isReferenceType() ||
6028 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6029 // Promotable integers are UB, but enumerations need a bit of
6030 // extra checking to see what their promotable type actually is.
6031 if (!Context.isPromotableIntegerType(Type))
6032 return false;
6033 const auto *ED = Type->getAsEnumDecl();
6034 if (!ED)
6035 return true;
6036 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6037 }()) {
6038 unsigned Reason = 0;
6039 if (Type->isReferenceType()) Reason = 1;
6040 else if (IsCRegister) Reason = 2;
6041 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6042 Diag(ParamLoc, diag::note_parameter_type) << Type;
6043 }
6044
6045 return false;
6046}
6047
6048bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6049 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6050 const LangOptions &LO = getLangOpts();
6051
6052 if (LO.CPlusPlus)
6053 return Arg->getType()
6055 .getTypePtr()
6056 ->getPointeeType()
6058
6059 // In C, allow aliasing through `char *`, this is required for AArch64 at
6060 // least.
6061 return true;
6062 };
6063
6064 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6065 // const char *named_addr);
6066
6067 Expr *Func = Call->getCallee();
6068
6069 if (Call->getNumArgs() < 3)
6070 return Diag(Call->getEndLoc(),
6071 diag::err_typecheck_call_too_few_args_at_least)
6072 << 0 /*function call*/ << 3 << Call->getNumArgs()
6073 << /*is non object*/ 0;
6074
6075 // Type-check the first argument normally.
6076 if (checkBuiltinArgument(*this, Call, 0))
6077 return true;
6078
6079 // Check that the current function is variadic.
6081 return true;
6082
6083 // __va_start on Windows does not validate the parameter qualifiers
6084
6085 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6086 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6087
6088 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6089 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6090
6091 const QualType &ConstCharPtrTy =
6092 Context.getPointerType(Context.CharTy.withConst());
6093 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6094 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6095 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6096 << 0 /* qualifier difference */
6097 << 3 /* parameter mismatch */
6098 << 2 << Arg1->getType() << ConstCharPtrTy;
6099
6100 const QualType SizeTy = Context.getSizeType();
6101 if (!Context.hasSameType(
6103 SizeTy))
6104 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6105 << Arg2->getType() << SizeTy << 1 /* different class */
6106 << 0 /* qualifier difference */
6107 << 3 /* parameter mismatch */
6108 << 3 << Arg2->getType() << SizeTy;
6109
6110 return false;
6111}
6112
6113bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6114 if (checkArgCount(TheCall, 2))
6115 return true;
6116
6117 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6118 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6119 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6120 << 1 << 0 << TheCall->getSourceRange();
6121
6122 ExprResult OrigArg0 = TheCall->getArg(0);
6123 ExprResult OrigArg1 = TheCall->getArg(1);
6124
6125 // Do standard promotions between the two arguments, returning their common
6126 // type.
6127 QualType Res = UsualArithmeticConversions(
6128 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6129 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6130 return true;
6131
6132 // Make sure any conversions are pushed back into the call; this is
6133 // type safe since unordered compare builtins are declared as "_Bool
6134 // foo(...)".
6135 TheCall->setArg(0, OrigArg0.get());
6136 TheCall->setArg(1, OrigArg1.get());
6137
6138 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6139 return false;
6140
6141 // If the common type isn't a real floating type, then the arguments were
6142 // invalid for this operation.
6143 if (Res.isNull() || !Res->isRealFloatingType())
6144 return Diag(OrigArg0.get()->getBeginLoc(),
6145 diag::err_typecheck_call_invalid_ordered_compare)
6146 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6147 << SourceRange(OrigArg0.get()->getBeginLoc(),
6148 OrigArg1.get()->getEndLoc());
6149
6150 return false;
6151}
6152
6153bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6154 unsigned BuiltinID) {
6155 if (checkArgCount(TheCall, NumArgs))
6156 return true;
6157
6158 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6159 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6160 BuiltinID == Builtin::BI__builtin_isinf ||
6161 BuiltinID == Builtin::BI__builtin_isinf_sign))
6162 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6163 << 0 << 0 << TheCall->getSourceRange();
6164
6165 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6166 BuiltinID == Builtin::BI__builtin_isunordered))
6167 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6168 << 1 << 0 << TheCall->getSourceRange();
6169
6170 bool IsFPClass = NumArgs == 2;
6171
6172 // Find out position of floating-point argument.
6173 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6174
6175 // We can count on all parameters preceding the floating-point just being int.
6176 // Try all of those.
6177 for (unsigned i = 0; i < FPArgNo; ++i) {
6178 Expr *Arg = TheCall->getArg(i);
6179
6180 if (Arg->isTypeDependent())
6181 return false;
6182
6185
6186 if (Res.isInvalid())
6187 return true;
6188 TheCall->setArg(i, Res.get());
6189 }
6190
6191 Expr *OrigArg = TheCall->getArg(FPArgNo);
6192
6193 if (OrigArg->isTypeDependent())
6194 return false;
6195
6196 // Usual Unary Conversions will convert half to float, which we want for
6197 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6198 // type how it is, but do normal L->Rvalue conversions.
6199 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6200 ExprResult Res = UsualUnaryConversions(OrigArg);
6201
6202 if (!Res.isUsable())
6203 return true;
6204 OrigArg = Res.get();
6205 } else {
6207
6208 if (!Res.isUsable())
6209 return true;
6210 OrigArg = Res.get();
6211 }
6212 TheCall->setArg(FPArgNo, OrigArg);
6213
6214 QualType VectorResultTy;
6215 QualType ElementTy = OrigArg->getType();
6216 // TODO: When all classification function are implemented with is_fpclass,
6217 // vector argument can be supported in all of them.
6218 if (ElementTy->isVectorType() && IsFPClass) {
6219 VectorResultTy = GetSignedVectorType(ElementTy);
6220 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6221 }
6222
6223 // This operation requires a non-_Complex floating-point number.
6224 if (!ElementTy->isRealFloatingType())
6225 return Diag(OrigArg->getBeginLoc(),
6226 diag::err_typecheck_call_invalid_unary_fp)
6227 << OrigArg->getType() << OrigArg->getSourceRange();
6228
6229 // __builtin_isfpclass has integer parameter that specify test mask. It is
6230 // passed in (...), so it should be analyzed completely here.
6231 if (IsFPClass)
6232 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6233 return true;
6234
6235 // TODO: enable this code to all classification functions.
6236 if (IsFPClass) {
6237 QualType ResultTy;
6238 if (!VectorResultTy.isNull())
6239 ResultTy = VectorResultTy;
6240 else
6241 ResultTy = Context.IntTy;
6242 TheCall->setType(ResultTy);
6243 }
6244
6245 return false;
6246}
6247
6248bool Sema::BuiltinComplex(CallExpr *TheCall) {
6249 if (checkArgCount(TheCall, 2))
6250 return true;
6251
6252 bool Dependent = false;
6253 for (unsigned I = 0; I != 2; ++I) {
6254 Expr *Arg = TheCall->getArg(I);
6255 QualType T = Arg->getType();
6256 if (T->isDependentType()) {
6257 Dependent = true;
6258 continue;
6259 }
6260
6261 // Despite supporting _Complex int, GCC requires a real floating point type
6262 // for the operands of __builtin_complex.
6263 if (!T->isRealFloatingType()) {
6264 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6265 << Arg->getType() << Arg->getSourceRange();
6266 }
6267
6268 ExprResult Converted = DefaultLvalueConversion(Arg);
6269 if (Converted.isInvalid())
6270 return true;
6271 TheCall->setArg(I, Converted.get());
6272 }
6273
6274 if (Dependent) {
6275 TheCall->setType(Context.DependentTy);
6276 return false;
6277 }
6278
6279 Expr *Real = TheCall->getArg(0);
6280 Expr *Imag = TheCall->getArg(1);
6281 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6282 return Diag(Real->getBeginLoc(),
6283 diag::err_typecheck_call_different_arg_types)
6284 << Real->getType() << Imag->getType()
6285 << Real->getSourceRange() << Imag->getSourceRange();
6286 }
6287
6288 TheCall->setType(Context.getComplexType(Real->getType()));
6289 return false;
6290}
6291
6292/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6293// This is declared to take (...), so we have to check everything.
6295 unsigned NumArgs = TheCall->getNumArgs();
6296 if (NumArgs < 2)
6297 return ExprError(Diag(TheCall->getEndLoc(),
6298 diag::err_typecheck_call_too_few_args_at_least)
6299 << 0 /*function call*/ << 2 << NumArgs
6300 << /*is non object*/ 0 << TheCall->getSourceRange());
6301
6302 // Determine which of the following types of shufflevector we're checking:
6303 // 1) unary, vector mask: (lhs, mask)
6304 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6305 QualType ResType = TheCall->getArg(0)->getType();
6306 unsigned NumElements = 0;
6307
6308 if (!TheCall->getArg(0)->isTypeDependent() &&
6309 !TheCall->getArg(1)->isTypeDependent()) {
6310 QualType LHSType = TheCall->getArg(0)->getType();
6311 QualType RHSType = TheCall->getArg(1)->getType();
6312
6313 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6314 return ExprError(
6315 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6316 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6317 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6318 TheCall->getArg(1)->getEndLoc()));
6319
6320 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6321 unsigned NumResElements = NumArgs - 2;
6322
6323 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6324 // with mask. If so, verify that RHS is an integer vector type with the
6325 // same number of elts as lhs.
6326 if (NumArgs == 2) {
6327 if (!RHSType->hasIntegerRepresentation() ||
6328 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6329 return ExprError(Diag(TheCall->getBeginLoc(),
6330 diag::err_vec_builtin_incompatible_vector)
6331 << TheCall->getDirectCallee()
6332 << /*isMoreThanTwoArgs*/ false
6333 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6334 TheCall->getArg(1)->getEndLoc()));
6335 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6336 return ExprError(Diag(TheCall->getBeginLoc(),
6337 diag::err_vec_builtin_incompatible_vector)
6338 << TheCall->getDirectCallee()
6339 << /*isMoreThanTwoArgs*/ false
6340 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6341 TheCall->getArg(1)->getEndLoc()));
6342 } else if (NumElements != NumResElements) {
6343 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6344 ResType = ResType->isExtVectorType()
6345 ? Context.getExtVectorType(EltType, NumResElements)
6346 : Context.getVectorType(EltType, NumResElements,
6348 }
6349 }
6350
6351 for (unsigned I = 2; I != NumArgs; ++I) {
6352 Expr *Arg = TheCall->getArg(I);
6353 if (Arg->isTypeDependent() || Arg->isValueDependent())
6354 continue;
6355
6356 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6357 if (!Result)
6358 return ExprError(Diag(TheCall->getBeginLoc(),
6359 diag::err_shufflevector_nonconstant_argument)
6360 << Arg->getSourceRange());
6361
6362 // Allow -1 which will be translated to undef in the IR.
6363 if (Result->isSigned() && Result->isAllOnes())
6364 ;
6365 else if (Result->getActiveBits() > 64 ||
6366 Result->getZExtValue() >= NumElements * 2)
6367 return ExprError(Diag(TheCall->getBeginLoc(),
6368 diag::err_shufflevector_argument_too_large)
6369 << Arg->getSourceRange());
6370
6371 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6372 }
6373
6374 auto *Result = new (Context) ShuffleVectorExpr(
6375 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6376 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6377
6378 // All moved to Result.
6379 TheCall->shrinkNumArgs(0);
6380 return Result;
6381}
6382
6384 SourceLocation BuiltinLoc,
6385 SourceLocation RParenLoc) {
6388 QualType DstTy = TInfo->getType();
6389 QualType SrcTy = E->getType();
6390
6391 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6392 return ExprError(Diag(BuiltinLoc,
6393 diag::err_convertvector_non_vector)
6394 << E->getSourceRange());
6395 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6396 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6397 << "second"
6398 << "__builtin_convertvector");
6399
6400 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6401 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6402 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6403 if (SrcElts != DstElts)
6404 return ExprError(Diag(BuiltinLoc,
6405 diag::err_convertvector_incompatible_vector)
6406 << E->getSourceRange());
6407 }
6408
6409 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6410 RParenLoc, CurFPFeatureOverrides());
6411}
6412
6413bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6414 unsigned NumArgs = TheCall->getNumArgs();
6415
6416 if (NumArgs > 3)
6417 return Diag(TheCall->getEndLoc(),
6418 diag::err_typecheck_call_too_many_args_at_most)
6419 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6420 << TheCall->getSourceRange();
6421
6422 // Argument 0 is checked for us and the remaining arguments must be
6423 // constant integers.
6424 for (unsigned i = 1; i != NumArgs; ++i)
6425 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6426 return true;
6427
6428 return false;
6429}
6430
6431bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6432 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6433 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6434 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6435 if (checkArgCount(TheCall, 1))
6436 return true;
6437 Expr *Arg = TheCall->getArg(0);
6438 if (Arg->isInstantiationDependent())
6439 return false;
6440
6441 QualType ArgTy = Arg->getType();
6442 if (!ArgTy->hasFloatingRepresentation())
6443 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6444 << ArgTy;
6445 if (Arg->isLValue()) {
6446 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6447 TheCall->setArg(0, FirstArg.get());
6448 }
6449 TheCall->setType(TheCall->getArg(0)->getType());
6450 return false;
6451}
6452
6453bool Sema::BuiltinAssume(CallExpr *TheCall) {
6454 Expr *Arg = TheCall->getArg(0);
6455 if (Arg->isInstantiationDependent()) return false;
6456
6457 if (Arg->HasSideEffects(Context))
6458 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6459 << Arg->getSourceRange()
6460 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6461
6462 return false;
6463}
6464
6465bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6466 // The alignment must be a constant integer.
6467 Expr *Arg = TheCall->getArg(1);
6468
6469 // We can't check the value of a dependent argument.
6470 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6471 if (const auto *UE =
6472 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6473 if (UE->getKind() == UETT_AlignOf ||
6474 UE->getKind() == UETT_PreferredAlignOf)
6475 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6476 << Arg->getSourceRange();
6477
6478 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6479
6480 if (!Result.isPowerOf2())
6481 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6482 << Arg->getSourceRange();
6483
6484 if (Result < Context.getCharWidth())
6485 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6486 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6487
6488 if (Result > std::numeric_limits<int32_t>::max())
6489 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6490 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6491 }
6492
6493 return false;
6494}
6495
6496bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6497 if (checkArgCountRange(TheCall, 2, 3))
6498 return true;
6499
6500 unsigned NumArgs = TheCall->getNumArgs();
6501 Expr *FirstArg = TheCall->getArg(0);
6502
6503 {
6504 ExprResult FirstArgResult =
6506 if (!FirstArgResult.get()->getType()->isPointerType()) {
6507 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6508 << TheCall->getSourceRange();
6509 return true;
6510 }
6511 TheCall->setArg(0, FirstArgResult.get());
6512 }
6513
6514 // The alignment must be a constant integer.
6515 Expr *SecondArg = TheCall->getArg(1);
6516
6517 // We can't check the value of a dependent argument.
6518 if (!SecondArg->isValueDependent()) {
6519 llvm::APSInt Result;
6520 if (BuiltinConstantArg(TheCall, 1, Result))
6521 return true;
6522
6523 if (!Result.isPowerOf2())
6524 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6525 << SecondArg->getSourceRange();
6526
6528 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6529 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6530
6531 TheCall->setArg(1,
6533 }
6534
6535 if (NumArgs > 2) {
6536 Expr *ThirdArg = TheCall->getArg(2);
6537 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6538 return true;
6539 TheCall->setArg(2, ThirdArg);
6540 }
6541
6542 return false;
6543}
6544
6545bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6546 unsigned BuiltinID =
6547 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6548 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6549
6550 unsigned NumArgs = TheCall->getNumArgs();
6551 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6552 if (NumArgs < NumRequiredArgs) {
6553 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6554 << 0 /* function call */ << NumRequiredArgs << NumArgs
6555 << /*is non object*/ 0 << TheCall->getSourceRange();
6556 }
6557 if (NumArgs >= NumRequiredArgs + 0x100) {
6558 return Diag(TheCall->getEndLoc(),
6559 diag::err_typecheck_call_too_many_args_at_most)
6560 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6561 << /*is non object*/ 0 << TheCall->getSourceRange();
6562 }
6563 unsigned i = 0;
6564
6565 // For formatting call, check buffer arg.
6566 if (!IsSizeCall) {
6567 ExprResult Arg(TheCall->getArg(i));
6568 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6569 Context, Context.VoidPtrTy, false);
6570 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6571 if (Arg.isInvalid())
6572 return true;
6573 TheCall->setArg(i, Arg.get());
6574 i++;
6575 }
6576
6577 // Check string literal arg.
6578 unsigned FormatIdx = i;
6579 {
6580 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6581 if (Arg.isInvalid())
6582 return true;
6583 TheCall->setArg(i, Arg.get());
6584 i++;
6585 }
6586
6587 // Make sure variadic args are scalar.
6588 unsigned FirstDataArg = i;
6589 while (i < NumArgs) {
6591 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6592 if (Arg.isInvalid())
6593 return true;
6594 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6595 if (ArgSize.getQuantity() >= 0x100) {
6596 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6597 << i << (int)ArgSize.getQuantity() << 0xff
6598 << TheCall->getSourceRange();
6599 }
6600 TheCall->setArg(i, Arg.get());
6601 i++;
6602 }
6603
6604 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6605 // call to avoid duplicate diagnostics.
6606 if (!IsSizeCall) {
6607 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6608 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6609 bool Success = CheckFormatArguments(
6610 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6612 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6613 if (!Success)
6614 return true;
6615 }
6616
6617 if (IsSizeCall) {
6618 TheCall->setType(Context.getSizeType());
6619 } else {
6620 TheCall->setType(Context.VoidPtrTy);
6621 }
6622 return false;
6623}
6624
6625bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6626 llvm::APSInt &Result) {
6627 Expr *Arg = TheCall->getArg(ArgNum);
6628
6629 if (Arg->isTypeDependent() || Arg->isValueDependent())
6630 return false;
6631
6632 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6633 if (!R) {
6634 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6635 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6636 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6637 << FDecl->getDeclName() << Arg->getSourceRange();
6638 }
6639 Result = *R;
6640
6641 return false;
6642}
6643
6644bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6645 int High, bool RangeIsError) {
6647 return false;
6648 llvm::APSInt Result;
6649
6650 // We can't check the value of a dependent argument.
6651 Expr *Arg = TheCall->getArg(ArgNum);
6652 if (Arg->isTypeDependent() || Arg->isValueDependent())
6653 return false;
6654
6655 // Check constant-ness first.
6656 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6657 return true;
6658
6659 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6660 if (RangeIsError)
6661 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6662 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6663 else
6664 // Defer the warning until we know if the code will be emitted so that
6665 // dead code can ignore this.
6666 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6667 PDiag(diag::warn_argument_invalid_range)
6668 << toString(Result, 10) << Low << High
6669 << Arg->getSourceRange());
6670 }
6671
6672 return false;
6673}
6674
6675bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6676 unsigned Num) {
6677 llvm::APSInt Result;
6678
6679 // We can't check the value of a dependent argument.
6680 Expr *Arg = TheCall->getArg(ArgNum);
6681 if (Arg->isTypeDependent() || Arg->isValueDependent())
6682 return false;
6683
6684 // Check constant-ness first.
6685 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6686 return true;
6687
6688 if (Result.getSExtValue() % Num != 0)
6689 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6690 << Num << Arg->getSourceRange();
6691
6692 return false;
6693}
6694
6695bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6696 llvm::APSInt Result;
6697
6698 // We can't check the value of a dependent argument.
6699 Expr *Arg = TheCall->getArg(ArgNum);
6700 if (Arg->isTypeDependent() || Arg->isValueDependent())
6701 return false;
6702
6703 // Check constant-ness first.
6704 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6705 return true;
6706
6707 if (Result.isPowerOf2())
6708 return false;
6709
6710 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6711 << Arg->getSourceRange();
6712}
6713
6714static bool IsShiftedByte(llvm::APSInt Value) {
6715 if (Value.isNegative())
6716 return false;
6717
6718 // Check if it's a shifted byte, by shifting it down
6719 while (true) {
6720 // If the value fits in the bottom byte, the check passes.
6721 if (Value < 0x100)
6722 return true;
6723
6724 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6725 // fails.
6726 if ((Value & 0xFF) != 0)
6727 return false;
6728
6729 // If the bottom 8 bits are all 0, but something above that is nonzero,
6730 // then shifting the value right by 8 bits won't affect whether it's a
6731 // shifted byte or not. So do that, and go round again.
6732 Value >>= 8;
6733 }
6734}
6735
6736bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6737 unsigned ArgBits) {
6738 llvm::APSInt Result;
6739
6740 // We can't check the value of a dependent argument.
6741 Expr *Arg = TheCall->getArg(ArgNum);
6742 if (Arg->isTypeDependent() || Arg->isValueDependent())
6743 return false;
6744
6745 // Check constant-ness first.
6746 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6747 return true;
6748
6749 // Truncate to the given size.
6750 Result = Result.getLoBits(ArgBits);
6751 Result.setIsUnsigned(true);
6752
6753 if (IsShiftedByte(Result))
6754 return false;
6755
6756 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6757 << Arg->getSourceRange();
6758}
6759
6761 unsigned ArgNum,
6762 unsigned ArgBits) {
6763 llvm::APSInt Result;
6764
6765 // We can't check the value of a dependent argument.
6766 Expr *Arg = TheCall->getArg(ArgNum);
6767 if (Arg->isTypeDependent() || Arg->isValueDependent())
6768 return false;
6769
6770 // Check constant-ness first.
6771 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6772 return true;
6773
6774 // Truncate to the given size.
6775 Result = Result.getLoBits(ArgBits);
6776 Result.setIsUnsigned(true);
6777
6778 // Check to see if it's in either of the required forms.
6779 if (IsShiftedByte(Result) ||
6780 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6781 return false;
6782
6783 return Diag(TheCall->getBeginLoc(),
6784 diag::err_argument_not_shifted_byte_or_xxff)
6785 << Arg->getSourceRange();
6786}
6787
6788bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6789 if (!Context.getTargetInfo().hasSjLjLowering())
6790 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6791 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6792
6793 Expr *Arg = TheCall->getArg(1);
6794 llvm::APSInt Result;
6795
6796 // TODO: This is less than ideal. Overload this to take a value.
6797 if (BuiltinConstantArg(TheCall, 1, Result))
6798 return true;
6799
6800 if (Result != 1)
6801 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6802 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6803
6804 return false;
6805}
6806
6807bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6808 if (!Context.getTargetInfo().hasSjLjLowering())
6809 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6810 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6811 return false;
6812}
6813
6814bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6815 if (checkArgCount(TheCall, 1))
6816 return true;
6817
6818 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6819 if (ArgRes.isInvalid())
6820 return true;
6821
6822 // For simplicity, we support only limited expressions for the argument.
6823 // Specifically a flexible array member or a pointer with counted_by:
6824 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6825 // complex casting, which really shouldn't be a huge problem.
6826 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6827 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6828 return Diag(Arg->getBeginLoc(),
6829 diag::err_builtin_counted_by_ref_invalid_arg)
6830 << Arg->getSourceRange();
6831
6832 if (Arg->HasSideEffects(Context))
6833 return Diag(Arg->getBeginLoc(),
6834 diag::err_builtin_counted_by_ref_has_side_effects)
6835 << Arg->getSourceRange();
6836
6837 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6838 const auto *CATy =
6839 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6840
6841 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6842 // Member has counted_by attribute - return pointer to count field
6843 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
6844 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6845 TheCall->setType(Context.getPointerType(CountFD->getType()));
6846 return false;
6847 }
6848 }
6849
6850 // FAMs and pointers without counted_by return void*
6851 QualType MemberTy = ME->getMemberDecl()->getType();
6852 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6853 return Diag(Arg->getBeginLoc(),
6854 diag::err_builtin_counted_by_ref_invalid_arg)
6855 << Arg->getSourceRange();
6856 } else {
6857 return Diag(Arg->getBeginLoc(),
6858 diag::err_builtin_counted_by_ref_invalid_arg)
6859 << Arg->getSourceRange();
6860 }
6861
6862 TheCall->setType(Context.getPointerType(Context.VoidTy));
6863 return false;
6864}
6865
6866/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6867/// It allows leaking and modification of bounds safety information.
6868bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6870 const CallExpr *CE =
6871 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6872 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6873 return false;
6874
6875 switch (K) {
6878 Diag(E->getExprLoc(),
6879 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6880 << 0 << E->getSourceRange();
6881 break;
6883 Diag(E->getExprLoc(),
6884 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6885 << 1 << E->getSourceRange();
6886 break;
6888 Diag(E->getExprLoc(),
6889 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6890 << 2 << E->getSourceRange();
6891 break;
6893 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6894 << 0 << E->getSourceRange();
6895 break;
6897 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6898 << 1 << E->getSourceRange();
6899 break;
6900 }
6901
6902 return true;
6903}
6904
6905namespace {
6906
6907class UncoveredArgHandler {
6908 enum { Unknown = -1, AllCovered = -2 };
6909
6910 signed FirstUncoveredArg = Unknown;
6911 SmallVector<const Expr *, 4> DiagnosticExprs;
6912
6913public:
6914 UncoveredArgHandler() = default;
6915
6916 bool hasUncoveredArg() const {
6917 return (FirstUncoveredArg >= 0);
6918 }
6919
6920 unsigned getUncoveredArg() const {
6921 assert(hasUncoveredArg() && "no uncovered argument");
6922 return FirstUncoveredArg;
6923 }
6924
6925 void setAllCovered() {
6926 // A string has been found with all arguments covered, so clear out
6927 // the diagnostics.
6928 DiagnosticExprs.clear();
6929 FirstUncoveredArg = AllCovered;
6930 }
6931
6932 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6933 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6934
6935 // Don't update if a previous string covers all arguments.
6936 if (FirstUncoveredArg == AllCovered)
6937 return;
6938
6939 // UncoveredArgHandler tracks the highest uncovered argument index
6940 // and with it all the strings that match this index.
6941 if (NewFirstUncoveredArg == FirstUncoveredArg)
6942 DiagnosticExprs.push_back(StrExpr);
6943 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6944 DiagnosticExprs.clear();
6945 DiagnosticExprs.push_back(StrExpr);
6946 FirstUncoveredArg = NewFirstUncoveredArg;
6947 }
6948 }
6949
6950 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6951};
6952
6953enum StringLiteralCheckType {
6954 SLCT_NotALiteral,
6955 SLCT_UncheckedLiteral,
6956 SLCT_CheckedLiteral
6957};
6958
6959} // namespace
6960
6961static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6962 BinaryOperatorKind BinOpKind,
6963 bool AddendIsRight) {
6964 unsigned BitWidth = Offset.getBitWidth();
6965 unsigned AddendBitWidth = Addend.getBitWidth();
6966 // There might be negative interim results.
6967 if (Addend.isUnsigned()) {
6968 Addend = Addend.zext(++AddendBitWidth);
6969 Addend.setIsSigned(true);
6970 }
6971 // Adjust the bit width of the APSInts.
6972 if (AddendBitWidth > BitWidth) {
6973 Offset = Offset.sext(AddendBitWidth);
6974 BitWidth = AddendBitWidth;
6975 } else if (BitWidth > AddendBitWidth) {
6976 Addend = Addend.sext(BitWidth);
6977 }
6978
6979 bool Ov = false;
6980 llvm::APSInt ResOffset = Offset;
6981 if (BinOpKind == BO_Add)
6982 ResOffset = Offset.sadd_ov(Addend, Ov);
6983 else {
6984 assert(AddendIsRight && BinOpKind == BO_Sub &&
6985 "operator must be add or sub with addend on the right");
6986 ResOffset = Offset.ssub_ov(Addend, Ov);
6987 }
6988
6989 // We add an offset to a pointer here so we should support an offset as big as
6990 // possible.
6991 if (Ov) {
6992 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6993 "index (intermediate) result too big");
6994 Offset = Offset.sext(2 * BitWidth);
6995 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6996 return;
6997 }
6998
6999 Offset = std::move(ResOffset);
7000}
7001
7002namespace {
7003
7004// This is a wrapper class around StringLiteral to support offsetted string
7005// literals as format strings. It takes the offset into account when returning
7006// the string and its length or the source locations to display notes correctly.
7007class FormatStringLiteral {
7008 const StringLiteral *FExpr;
7009 int64_t Offset;
7010
7011public:
7012 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7013 : FExpr(fexpr), Offset(Offset) {}
7014
7015 const StringLiteral *getFormatString() const { return FExpr; }
7016
7017 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7018
7019 unsigned getByteLength() const {
7020 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7021 }
7022
7023 unsigned getLength() const { return FExpr->getLength() - Offset; }
7024 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7025
7026 StringLiteralKind getKind() const { return FExpr->getKind(); }
7027
7028 QualType getType() const { return FExpr->getType(); }
7029
7030 bool isAscii() const { return FExpr->isOrdinary(); }
7031 bool isWide() const { return FExpr->isWide(); }
7032 bool isUTF8() const { return FExpr->isUTF8(); }
7033 bool isUTF16() const { return FExpr->isUTF16(); }
7034 bool isUTF32() const { return FExpr->isUTF32(); }
7035 bool isPascal() const { return FExpr->isPascal(); }
7036
7037 SourceLocation getLocationOfByte(
7038 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7039 const TargetInfo &Target, unsigned *StartToken = nullptr,
7040 unsigned *StartTokenByteOffset = nullptr) const {
7041 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7042 StartToken, StartTokenByteOffset);
7043 }
7044
7045 SourceLocation getBeginLoc() const LLVM_READONLY {
7046 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7047 }
7048
7049 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7050};
7051
7052} // namespace
7053
7054static void CheckFormatString(
7055 Sema &S, const FormatStringLiteral *FExpr,
7056 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7058 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7059 bool inFunctionCall, VariadicCallType CallType,
7060 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7061 bool IgnoreStringsWithoutSpecifiers);
7062
7063static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7064 const Expr *E);
7065
7066// Determine if an expression is a string literal or constant string.
7067// If this function returns false on the arguments to a function expecting a
7068// format string, we will usually need to emit a warning.
7069// True string literals are then checked by CheckFormatString.
7070static StringLiteralCheckType
7071checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7072 const Expr *E, ArrayRef<const Expr *> Args,
7073 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7074 unsigned firstDataArg, FormatStringType Type,
7075 VariadicCallType CallType, bool InFunctionCall,
7076 llvm::SmallBitVector &CheckedVarArgs,
7077 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7078 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7079 bool IgnoreStringsWithoutSpecifiers = false) {
7081 return SLCT_NotALiteral;
7082tryAgain:
7083 assert(Offset.isSigned() && "invalid offset");
7084
7085 if (E->isTypeDependent() || E->isValueDependent())
7086 return SLCT_NotALiteral;
7087
7088 E = E->IgnoreParenCasts();
7089
7091 // Technically -Wformat-nonliteral does not warn about this case.
7092 // The behavior of printf and friends in this case is implementation
7093 // dependent. Ideally if the format string cannot be null then
7094 // it should have a 'nonnull' attribute in the function prototype.
7095 return SLCT_UncheckedLiteral;
7096
7097 switch (E->getStmtClass()) {
7098 case Stmt::InitListExprClass:
7099 // Handle expressions like {"foobar"}.
7100 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7101 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7102 format_idx, firstDataArg, Type, CallType,
7103 /*InFunctionCall*/ false, CheckedVarArgs,
7104 UncoveredArg, Offset, CallerFormatParamIdx,
7105 IgnoreStringsWithoutSpecifiers);
7106 }
7107 return SLCT_NotALiteral;
7108 case Stmt::BinaryConditionalOperatorClass:
7109 case Stmt::ConditionalOperatorClass: {
7110 // The expression is a literal if both sub-expressions were, and it was
7111 // completely checked only if both sub-expressions were checked.
7114
7115 // Determine whether it is necessary to check both sub-expressions, for
7116 // example, because the condition expression is a constant that can be
7117 // evaluated at compile time.
7118 bool CheckLeft = true, CheckRight = true;
7119
7120 bool Cond;
7121 if (C->getCond()->EvaluateAsBooleanCondition(
7123 if (Cond)
7124 CheckRight = false;
7125 else
7126 CheckLeft = false;
7127 }
7128
7129 // We need to maintain the offsets for the right and the left hand side
7130 // separately to check if every possible indexed expression is a valid
7131 // string literal. They might have different offsets for different string
7132 // literals in the end.
7133 StringLiteralCheckType Left;
7134 if (!CheckLeft)
7135 Left = SLCT_UncheckedLiteral;
7136 else {
7137 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7138 Args, APK, format_idx, firstDataArg, Type,
7139 CallType, InFunctionCall, CheckedVarArgs,
7140 UncoveredArg, Offset, CallerFormatParamIdx,
7141 IgnoreStringsWithoutSpecifiers);
7142 if (Left == SLCT_NotALiteral || !CheckRight) {
7143 return Left;
7144 }
7145 }
7146
7147 StringLiteralCheckType Right = checkFormatStringExpr(
7148 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7149 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7150 UncoveredArg, Offset, CallerFormatParamIdx,
7151 IgnoreStringsWithoutSpecifiers);
7152
7153 return (CheckLeft && Left < Right) ? Left : Right;
7154 }
7155
7156 case Stmt::ImplicitCastExprClass:
7157 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7158 goto tryAgain;
7159
7160 case Stmt::OpaqueValueExprClass:
7161 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7162 E = src;
7163 goto tryAgain;
7164 }
7165 return SLCT_NotALiteral;
7166
7167 case Stmt::PredefinedExprClass:
7168 // While __func__, etc., are technically not string literals, they
7169 // cannot contain format specifiers and thus are not a security
7170 // liability.
7171 return SLCT_UncheckedLiteral;
7172
7173 case Stmt::DeclRefExprClass: {
7174 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7175
7176 // As an exception, do not flag errors for variables binding to
7177 // const string literals.
7178 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7179 bool isConstant = false;
7180 QualType T = DR->getType();
7181
7182 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7183 isConstant = AT->getElementType().isConstant(S.Context);
7184 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7185 isConstant = T.isConstant(S.Context) &&
7186 PT->getPointeeType().isConstant(S.Context);
7187 } else if (T->isObjCObjectPointerType()) {
7188 // In ObjC, there is usually no "const ObjectPointer" type,
7189 // so don't check if the pointee type is constant.
7190 isConstant = T.isConstant(S.Context);
7191 }
7192
7193 if (isConstant) {
7194 if (const Expr *Init = VD->getAnyInitializer()) {
7195 // Look through initializers like const char c[] = { "foo" }
7196 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7197 if (InitList->isStringLiteralInit())
7198 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7199 }
7200 return checkFormatStringExpr(
7201 S, ReferenceFormatString, Init, Args, APK, format_idx,
7202 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7203 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7204 }
7205 }
7206
7207 // When the format argument is an argument of this function, and this
7208 // function also has the format attribute, there are several interactions
7209 // for which there shouldn't be a warning. For instance, when calling
7210 // v*printf from a function that has the printf format attribute, we
7211 // should not emit a warning about using `fmt`, even though it's not
7212 // constant, because the arguments have already been checked for the
7213 // caller of `logmessage`:
7214 //
7215 // __attribute__((format(printf, 1, 2)))
7216 // void logmessage(char const *fmt, ...) {
7217 // va_list ap;
7218 // va_start(ap, fmt);
7219 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7220 // ...
7221 // }
7222 //
7223 // Another interaction that we need to support is using a format string
7224 // specified by the format_matches attribute:
7225 //
7226 // __attribute__((format_matches(printf, 1, "%s %d")))
7227 // void logmessage(char const *fmt, const char *a, int b) {
7228 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7229 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7230 // ...
7231 // }
7232 //
7233 // Yet another interaction that we need to support is calling a variadic
7234 // format function from a format function that has fixed arguments. For
7235 // instance:
7236 //
7237 // __attribute__((format(printf, 1, 2)))
7238 // void logstring(char const *fmt, char const *str) {
7239 // printf(fmt, str); /* do not emit a warning about "fmt" */
7240 // }
7241 //
7242 // Same (and perhaps more relatably) for the variadic template case:
7243 //
7244 // template<typename... Args>
7245 // __attribute__((format(printf, 1, 2)))
7246 // void log(const char *fmt, Args&&... args) {
7247 // printf(fmt, forward<Args>(args)...);
7248 // /* do not emit a warning about "fmt" */
7249 // }
7250 //
7251 // Due to implementation difficulty, we only check the format, not the
7252 // format arguments, in all cases.
7253 //
7254 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7255 if (CallerFormatParamIdx)
7256 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7257 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7258 for (const auto *PVFormatMatches :
7259 D->specific_attrs<FormatMatchesAttr>()) {
7260 Sema::FormatStringInfo CalleeFSI;
7261 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7262 0, &CalleeFSI))
7263 continue;
7264 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7265 // If using the wrong type of format string, emit a diagnostic
7266 // here and stop checking to avoid irrelevant diagnostics.
7267 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7268 S.Diag(Args[format_idx]->getBeginLoc(),
7269 diag::warn_format_string_type_incompatible)
7270 << PVFormatMatches->getType()->getName()
7272 if (!InFunctionCall) {
7273 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7274 diag::note_format_string_defined);
7275 }
7276 return SLCT_UncheckedLiteral;
7277 }
7278 return checkFormatStringExpr(
7279 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7280 Args, APK, format_idx, firstDataArg, Type, CallType,
7281 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7282 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7283 }
7284 }
7285
7286 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7287 Sema::FormatStringInfo CallerFSI;
7288 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7289 PVFormat->getFirstArg(), &CallerFSI))
7290 continue;
7291 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7292 // We also check if the formats are compatible.
7293 // We can't pass a 'scanf' string to a 'printf' function.
7294 if (Type != S.GetFormatStringType(PVFormat)) {
7295 S.Diag(Args[format_idx]->getBeginLoc(),
7296 diag::warn_format_string_type_incompatible)
7297 << PVFormat->getType()->getName()
7299 if (!InFunctionCall) {
7300 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7301 }
7302 return SLCT_UncheckedLiteral;
7303 }
7304 // Lastly, check that argument passing kinds transition in a
7305 // way that makes sense:
7306 // from a caller with FAPK_VAList, allow FAPK_VAList
7307 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7308 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7309 // from a caller with FAPK_Variadic, allow FAPK_VAList
7310 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7315 return SLCT_UncheckedLiteral;
7316 }
7317 }
7318 }
7319 }
7320 }
7321 }
7322
7323 return SLCT_NotALiteral;
7324 }
7325
7326 case Stmt::CallExprClass:
7327 case Stmt::CXXMemberCallExprClass: {
7328 const CallExpr *CE = cast<CallExpr>(E);
7329 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7330 bool IsFirst = true;
7331 StringLiteralCheckType CommonResult;
7332 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7333 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7334 StringLiteralCheckType Result = checkFormatStringExpr(
7335 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7336 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7337 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7338 if (IsFirst) {
7339 CommonResult = Result;
7340 IsFirst = false;
7341 }
7342 }
7343 if (!IsFirst)
7344 return CommonResult;
7345
7346 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7347 unsigned BuiltinID = FD->getBuiltinID();
7348 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7349 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7350 const Expr *Arg = CE->getArg(0);
7351 return checkFormatStringExpr(
7352 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7353 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7354 UncoveredArg, Offset, CallerFormatParamIdx,
7355 IgnoreStringsWithoutSpecifiers);
7356 }
7357 }
7358 }
7359 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7360 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7361 format_idx, firstDataArg, Type, CallType,
7362 /*InFunctionCall*/ false, CheckedVarArgs,
7363 UncoveredArg, Offset, CallerFormatParamIdx,
7364 IgnoreStringsWithoutSpecifiers);
7365 return SLCT_NotALiteral;
7366 }
7367 case Stmt::ObjCMessageExprClass: {
7368 const auto *ME = cast<ObjCMessageExpr>(E);
7369 if (const auto *MD = ME->getMethodDecl()) {
7370 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7371 // As a special case heuristic, if we're using the method -[NSBundle
7372 // localizedStringForKey:value:table:], ignore any key strings that lack
7373 // format specifiers. The idea is that if the key doesn't have any
7374 // format specifiers then its probably just a key to map to the
7375 // localized strings. If it does have format specifiers though, then its
7376 // likely that the text of the key is the format string in the
7377 // programmer's language, and should be checked.
7378 const ObjCInterfaceDecl *IFace;
7379 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7380 IFace->getIdentifier()->isStr("NSBundle") &&
7381 MD->getSelector().isKeywordSelector(
7382 {"localizedStringForKey", "value", "table"})) {
7383 IgnoreStringsWithoutSpecifiers = true;
7384 }
7385
7386 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7387 return checkFormatStringExpr(
7388 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7389 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7390 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7391 }
7392 }
7393
7394 return SLCT_NotALiteral;
7395 }
7396 case Stmt::ObjCStringLiteralClass:
7397 case Stmt::StringLiteralClass: {
7398 const StringLiteral *StrE = nullptr;
7399
7400 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7401 StrE = ObjCFExpr->getString();
7402 else
7403 StrE = cast<StringLiteral>(E);
7404
7405 if (StrE) {
7406 if (Offset.isNegative() || Offset > StrE->getLength()) {
7407 // TODO: It would be better to have an explicit warning for out of
7408 // bounds literals.
7409 return SLCT_NotALiteral;
7410 }
7411 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7412 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7413 format_idx, firstDataArg, Type, InFunctionCall,
7414 CallType, CheckedVarArgs, UncoveredArg,
7415 IgnoreStringsWithoutSpecifiers);
7416 return SLCT_CheckedLiteral;
7417 }
7418
7419 return SLCT_NotALiteral;
7420 }
7421 case Stmt::BinaryOperatorClass: {
7422 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7423
7424 // A string literal + an int offset is still a string literal.
7425 if (BinOp->isAdditiveOp()) {
7426 Expr::EvalResult LResult, RResult;
7427
7428 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7429 LResult, S.Context, Expr::SE_NoSideEffects,
7431 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7432 RResult, S.Context, Expr::SE_NoSideEffects,
7434
7435 if (LIsInt != RIsInt) {
7436 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7437
7438 if (LIsInt) {
7439 if (BinOpKind == BO_Add) {
7440 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7441 E = BinOp->getRHS();
7442 goto tryAgain;
7443 }
7444 } else {
7445 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7446 E = BinOp->getLHS();
7447 goto tryAgain;
7448 }
7449 }
7450 }
7451
7452 return SLCT_NotALiteral;
7453 }
7454 case Stmt::UnaryOperatorClass: {
7455 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7456 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7457 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7458 Expr::EvalResult IndexResult;
7459 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7462 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7463 /*RHS is int*/ true);
7464 E = ASE->getBase();
7465 goto tryAgain;
7466 }
7467 }
7468
7469 return SLCT_NotALiteral;
7470 }
7471
7472 default:
7473 return SLCT_NotALiteral;
7474 }
7475}
7476
7477// If this expression can be evaluated at compile-time,
7478// check if the result is a StringLiteral and return it
7479// otherwise return nullptr
7481 const Expr *E) {
7483 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7484 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7485 if (isa_and_nonnull<StringLiteral>(LVE))
7486 return LVE;
7487 }
7488 return nullptr;
7489}
7490
7492 switch (FST) {
7494 return "scanf";
7496 return "printf";
7498 return "NSString";
7500 return "strftime";
7502 return "strfmon";
7504 return "kprintf";
7506 return "freebsd_kprintf";
7508 return "os_log";
7509 default:
7510 return "<unknown>";
7511 }
7512}
7513
7515 return llvm::StringSwitch<FormatStringType>(Flavor)
7516 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7517 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7519 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7520 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7521 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7522 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7524 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7525 .Case("os_trace", FormatStringType::OSLog)
7526 .Case("os_log", FormatStringType::OSLog)
7527 .Default(FormatStringType::Unknown);
7528}
7529
7531 return GetFormatStringType(Format->getType()->getName());
7532}
7533
7534FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7535 return GetFormatStringType(Format->getType()->getName());
7536}
7537
7538bool Sema::CheckFormatArguments(const FormatAttr *Format,
7539 ArrayRef<const Expr *> Args, bool IsCXXMember,
7540 VariadicCallType CallType, SourceLocation Loc,
7541 SourceRange Range,
7542 llvm::SmallBitVector &CheckedVarArgs) {
7543 FormatStringInfo FSI;
7544 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7545 IsCXXMember,
7546 CallType != VariadicCallType::DoesNotApply, &FSI))
7547 return CheckFormatArguments(
7548 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7549 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7550 return false;
7551}
7552
7553bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7554 ArrayRef<const Expr *> Args, bool IsCXXMember,
7555 VariadicCallType CallType, SourceLocation Loc,
7556 SourceRange Range,
7557 llvm::SmallBitVector &CheckedVarArgs) {
7558 FormatStringInfo FSI;
7559 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7560 &FSI)) {
7561 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7562 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7563 Format->getFormatString(), FSI.FormatIdx,
7564 FSI.FirstDataArg, GetFormatStringType(Format),
7565 CallType, Loc, Range, CheckedVarArgs);
7566 }
7567 return false;
7568}
7569
7572 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7573 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7574 SourceLocation Loc) {
7575 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7576 return false;
7577
7578 DeclContext *DC = S->CurContext;
7579 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7580 return false;
7581 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7582
7583 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7584
7585 // Find the offset to convert between attribute and parameter indexes.
7586 unsigned CallerArgumentIndexOffset =
7587 hasImplicitObjectParameter(Caller) ? 2 : 1;
7588
7589 unsigned FirstArgumentIndex = -1;
7590 switch (APK) {
7593 // As an extension, clang allows the format attribute on non-variadic
7594 // functions.
7595 // Caller must have fixed arguments to pass them to a fixed or variadic
7596 // function. Try to match caller and callee arguments. If successful, then
7597 // emit a diag with the caller idx, otherwise we can't determine the callee
7598 // arguments.
7599 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7600 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7601 // There aren't enough arguments in the caller to pass to callee.
7602 return false;
7603 }
7604 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7605 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7606 const auto *Arg =
7607 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7608 if (!Arg)
7609 return false;
7610 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7611 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7612 return false;
7613 }
7614 FirstArgumentIndex =
7615 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7616 break;
7617 }
7619 // Caller arguments are either variadic or a va_list.
7620 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7621 ? (NumCallerParams + CallerArgumentIndexOffset)
7622 : 0;
7623 break;
7625 // The callee has a format_matches attribute. We will emit that instead.
7626 if (!ReferenceFormatString)
7627 return false;
7628 break;
7629 }
7630
7631 // Emit the diagnostic and fixit.
7632 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7633 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7634 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7635 do {
7636 std::string Attr, Fixit;
7637 llvm::raw_string_ostream AttrOS(Attr);
7639 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7640 << FirstArgumentIndex << ")";
7641 } else {
7642 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7643 << ", \"";
7644 AttrOS.write_escaped(ReferenceFormatString->getString());
7645 AttrOS << "\")";
7646 }
7647 AttrOS.flush();
7648 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7649 if (ND)
7650 DB << ND;
7651 else
7652 DB << "block";
7653
7654 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7655 if (isa<BlockDecl>(Caller))
7656 break;
7657
7658 SourceLocation SL;
7659 llvm::raw_string_ostream IS(Fixit);
7660 // The attribute goes at the start of the declaration in C/C++ functions
7661 // and methods, but after the declaration for Objective-C methods.
7662 if (isa<ObjCMethodDecl>(Caller)) {
7663 IS << ' ';
7664 SL = Caller->getEndLoc();
7665 }
7666 const LangOptions &LO = S->getLangOpts();
7667 if (LO.C23 || LO.CPlusPlus11)
7668 IS << "[[gnu::" << Attr << "]]";
7669 else if (LO.ObjC || LO.GNUMode)
7670 IS << "__attribute__((" << Attr << "))";
7671 else
7672 break;
7673 if (!isa<ObjCMethodDecl>(Caller)) {
7674 IS << ' ';
7675 SL = Caller->getBeginLoc();
7676 }
7677 IS.flush();
7678
7679 DB << FixItHint::CreateInsertion(SL, Fixit);
7680 } while (false);
7681
7682 // Add implicit format or format_matches attribute.
7684 Caller->addAttr(FormatAttr::CreateImplicit(
7685 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7686 FormatStringIndex, FirstArgumentIndex));
7687 } else {
7688 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7689 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7690 FormatStringIndex, ReferenceFormatString));
7691 }
7692
7693 {
7694 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7695 if (ND)
7696 DB << ND;
7697 else
7698 DB << "block";
7699 }
7700 return true;
7701}
7702
7703bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7705 StringLiteral *ReferenceFormatString,
7706 unsigned format_idx, unsigned firstDataArg,
7708 VariadicCallType CallType, SourceLocation Loc,
7709 SourceRange Range,
7710 llvm::SmallBitVector &CheckedVarArgs) {
7711 // CHECK: printf/scanf-like function is called with no format string.
7712 if (format_idx >= Args.size()) {
7713 Diag(Loc, diag::warn_missing_format_string) << Range;
7714 return false;
7715 }
7716
7717 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7718
7719 // CHECK: format string is not a string literal.
7720 //
7721 // Dynamically generated format strings are difficult to
7722 // automatically vet at compile time. Requiring that format strings
7723 // are string literals: (1) permits the checking of format strings by
7724 // the compiler and thereby (2) can practically remove the source of
7725 // many format string exploits.
7726
7727 // Format string can be either ObjC string (e.g. @"%d") or
7728 // C string (e.g. "%d")
7729 // ObjC string uses the same format specifiers as C string, so we can use
7730 // the same format string checking logic for both ObjC and C strings.
7731 UncoveredArgHandler UncoveredArg;
7732 std::optional<unsigned> CallerParamIdx;
7733 StringLiteralCheckType CT = checkFormatStringExpr(
7734 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7735 firstDataArg, Type, CallType,
7736 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7737 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
7738
7739 // Generate a diagnostic where an uncovered argument is detected.
7740 if (UncoveredArg.hasUncoveredArg()) {
7741 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7742 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7743 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7744 }
7745
7746 if (CT != SLCT_NotALiteral)
7747 // Literal format string found, check done!
7748 return CT == SLCT_CheckedLiteral;
7749
7750 // Do not emit diag when the string param is a macro expansion and the
7751 // format is either NSString or CFString. This is a hack to prevent
7752 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7753 // which are usually used in place of NS and CF string literals.
7754 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7756 SourceMgr.isInSystemMacro(FormatLoc))
7757 return false;
7758
7759 if (CallerParamIdx && CheckMissingFormatAttribute(
7760 this, Args, APK, ReferenceFormatString, format_idx,
7761 firstDataArg, Type, *CallerParamIdx, Loc))
7762 return false;
7763
7764 // Strftime is particular as it always uses a single 'time' argument,
7765 // so it is safe to pass a non-literal string.
7767 return false;
7768
7769 // If there are no arguments specified, warn with -Wformat-security, otherwise
7770 // warn only with -Wformat-nonliteral.
7771 if (Args.size() == firstDataArg) {
7772 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7773 << OrigFormatExpr->getSourceRange();
7774 switch (Type) {
7775 default:
7776 break;
7780 Diag(FormatLoc, diag::note_format_security_fixit)
7781 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7782 break;
7784 Diag(FormatLoc, diag::note_format_security_fixit)
7785 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7786 break;
7787 }
7788 } else {
7789 Diag(FormatLoc, diag::warn_format_nonliteral)
7790 << OrigFormatExpr->getSourceRange();
7791 }
7792 return false;
7793}
7794
7795namespace {
7796
7797class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7798protected:
7799 Sema &S;
7800 const FormatStringLiteral *FExpr;
7801 const Expr *OrigFormatExpr;
7802 const FormatStringType FSType;
7803 const unsigned FirstDataArg;
7804 const unsigned NumDataArgs;
7805 const char *Beg; // Start of format string.
7806 const Sema::FormatArgumentPassingKind ArgPassingKind;
7807 ArrayRef<const Expr *> Args;
7808 unsigned FormatIdx;
7809 llvm::SmallBitVector CoveredArgs;
7810 bool usesPositionalArgs = false;
7811 bool atFirstArg = true;
7812 bool inFunctionCall;
7813 VariadicCallType CallType;
7814 llvm::SmallBitVector &CheckedVarArgs;
7815 UncoveredArgHandler &UncoveredArg;
7816
7817public:
7818 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7819 const Expr *origFormatExpr, const FormatStringType type,
7820 unsigned firstDataArg, unsigned numDataArgs,
7821 const char *beg, Sema::FormatArgumentPassingKind APK,
7822 ArrayRef<const Expr *> Args, unsigned formatIdx,
7823 bool inFunctionCall, VariadicCallType callType,
7824 llvm::SmallBitVector &CheckedVarArgs,
7825 UncoveredArgHandler &UncoveredArg)
7826 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7827 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7828 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7829 inFunctionCall(inFunctionCall), CallType(callType),
7830 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7831 CoveredArgs.resize(numDataArgs);
7832 CoveredArgs.reset();
7833 }
7834
7835 bool HasFormatArguments() const {
7836 return ArgPassingKind == Sema::FAPK_Fixed ||
7837 ArgPassingKind == Sema::FAPK_Variadic;
7838 }
7839
7840 void DoneProcessing();
7841
7842 void HandleIncompleteSpecifier(const char *startSpecifier,
7843 unsigned specifierLen) override;
7844
7845 void HandleInvalidLengthModifier(
7846 const analyze_format_string::FormatSpecifier &FS,
7847 const analyze_format_string::ConversionSpecifier &CS,
7848 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
7849
7850 void HandleNonStandardLengthModifier(
7851 const analyze_format_string::FormatSpecifier &FS,
7852 const char *startSpecifier, unsigned specifierLen);
7853
7854 void HandleNonStandardConversionSpecifier(
7855 const analyze_format_string::ConversionSpecifier &CS,
7856 const char *startSpecifier, unsigned specifierLen);
7857
7858 void HandlePosition(const char *startPos, unsigned posLen) override;
7859
7860 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
7862
7863 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7864
7865 void HandleNullChar(const char *nullCharacter) override;
7866
7867 template <typename Range>
7868 static void
7869 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7870 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7871 bool IsStringLocation, Range StringRange,
7872 ArrayRef<FixItHint> Fixit = {});
7873
7874protected:
7875 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7876 const char *startSpec,
7877 unsigned specifierLen,
7878 const char *csStart, unsigned csLen);
7879
7880 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7881 const char *startSpec,
7882 unsigned specifierLen);
7883
7884 SourceRange getFormatStringRange();
7885 CharSourceRange getSpecifierRange(const char *startSpecifier,
7886 unsigned specifierLen);
7887 SourceLocation getLocationOfByte(const char *x);
7888
7889 const Expr *getDataArg(unsigned i) const;
7890
7891 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7892 const analyze_format_string::ConversionSpecifier &CS,
7893 const char *startSpecifier, unsigned specifierLen,
7894 unsigned argIndex);
7895
7896 template <typename Range>
7897 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7898 bool IsStringLocation, Range StringRange,
7899 ArrayRef<FixItHint> Fixit = {});
7900};
7901
7902} // namespace
7903
7904SourceRange CheckFormatHandler::getFormatStringRange() {
7905 return OrigFormatExpr->getSourceRange();
7906}
7907
7909CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
7910 unsigned specifierLen) {
7911 SourceLocation Start = getLocationOfByte(startSpecifier);
7912 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7913
7914 // Advance the end SourceLocation by one due to half-open ranges.
7915 End = End.getLocWithOffset(1);
7916
7917 return CharSourceRange::getCharRange(Start, End);
7918}
7919
7920SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7921 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7923}
7924
7925void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7926 unsigned specifierLen) {
7927 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7928 getLocationOfByte(startSpecifier),
7929 /*IsStringLocation*/ true,
7930 getSpecifierRange(startSpecifier, specifierLen));
7931}
7932
7933void CheckFormatHandler::HandleInvalidLengthModifier(
7936 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7937 using namespace analyze_format_string;
7938
7939 const LengthModifier &LM = FS.getLengthModifier();
7940 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7941
7942 // See if we know how to fix this length modifier.
7943 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7944 if (FixedLM) {
7945 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7946 getLocationOfByte(LM.getStart()),
7947 /*IsStringLocation*/ true,
7948 getSpecifierRange(startSpecifier, specifierLen));
7949
7950 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7951 << FixedLM->toString()
7952 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7953
7954 } else {
7955 FixItHint Hint;
7956 if (DiagID == diag::warn_format_nonsensical_length)
7957 Hint = FixItHint::CreateRemoval(LMRange);
7958
7959 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7960 getLocationOfByte(LM.getStart()),
7961 /*IsStringLocation*/ true,
7962 getSpecifierRange(startSpecifier, specifierLen), Hint);
7963 }
7964}
7965
7966void CheckFormatHandler::HandleNonStandardLengthModifier(
7968 const char *startSpecifier, unsigned specifierLen) {
7969 using namespace analyze_format_string;
7970
7971 const LengthModifier &LM = FS.getLengthModifier();
7972 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7973
7974 // See if we know how to fix this length modifier.
7975 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7976 if (FixedLM) {
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 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7984 << FixedLM->toString()
7985 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7986
7987 } else {
7988 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7989 << LM.toString() << 0,
7990 getLocationOfByte(LM.getStart()),
7991 /*IsStringLocation*/ true,
7992 getSpecifierRange(startSpecifier, specifierLen));
7993 }
7994}
7995
7996void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7998 const char *startSpecifier, unsigned specifierLen) {
7999 using namespace analyze_format_string;
8000
8001 // See if we know how to fix this conversion specifier.
8002 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8003 if (FixedCS) {
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 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8011 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8012 << FixedCS->toString()
8013 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8014 } else {
8015 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8016 << CS.toString() << /*conversion specifier*/ 1,
8017 getLocationOfByte(CS.getStart()),
8018 /*IsStringLocation*/ true,
8019 getSpecifierRange(startSpecifier, specifierLen));
8020 }
8021}
8022
8023void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8024 if (!S.getDiagnostics().isIgnored(
8025 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8026 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8027 getLocationOfByte(startPos),
8028 /*IsStringLocation*/ true,
8029 getSpecifierRange(startPos, posLen));
8030}
8031
8032void CheckFormatHandler::HandleInvalidPosition(
8033 const char *startSpecifier, unsigned specifierLen,
8035 if (!S.getDiagnostics().isIgnored(
8036 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8037 EmitFormatDiagnostic(
8038 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8039 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8040 getSpecifierRange(startSpecifier, specifierLen));
8041}
8042
8043void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8044 unsigned posLen) {
8045 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8046 SourceLocation()))
8047 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8048 getLocationOfByte(startPos),
8049 /*IsStringLocation*/ true,
8050 getSpecifierRange(startPos, posLen));
8051}
8052
8053void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8054 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8055 // The presence of a null character is likely an error.
8056 EmitFormatDiagnostic(
8057 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8058 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8059 getFormatStringRange());
8060 }
8061}
8062
8063// Note that this may return NULL if there was an error parsing or building
8064// one of the argument expressions.
8065const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8066 return Args[FirstDataArg + i];
8067}
8068
8069void CheckFormatHandler::DoneProcessing() {
8070 // Does the number of data arguments exceed the number of
8071 // format conversions in the format string?
8072 if (HasFormatArguments()) {
8073 // Find any arguments that weren't covered.
8074 CoveredArgs.flip();
8075 signed notCoveredArg = CoveredArgs.find_first();
8076 if (notCoveredArg >= 0) {
8077 assert((unsigned)notCoveredArg < NumDataArgs);
8078 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8079 } else {
8080 UncoveredArg.setAllCovered();
8081 }
8082 }
8083}
8084
8085void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8086 const Expr *ArgExpr) {
8087 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8088
8089 if (!ArgExpr)
8090 return;
8091
8092 SourceLocation Loc = ArgExpr->getBeginLoc();
8093
8094 if (S.getSourceManager().isInSystemMacro(Loc))
8095 return;
8096
8097 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8098 for (auto E : DiagnosticExprs)
8099 PDiag << E->getSourceRange();
8100
8101 CheckFormatHandler::EmitFormatDiagnostic(
8102 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8103 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8104}
8105
8106bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8107 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8108 unsigned specifierLen, const char *csStart, unsigned csLen) {
8109 bool keepGoing = true;
8110 if (argIndex < NumDataArgs) {
8111 // Consider the argument coverered, even though the specifier doesn't
8112 // make sense.
8113 CoveredArgs.set(argIndex);
8114 } else {
8115 // If argIndex exceeds the number of data arguments we
8116 // don't issue a warning because that is just a cascade of warnings (and
8117 // they may have intended '%%' anyway). We don't want to continue processing
8118 // the format string after this point, however, as we will like just get
8119 // gibberish when trying to match arguments.
8120 keepGoing = false;
8121 }
8122
8123 StringRef Specifier(csStart, csLen);
8124
8125 // If the specifier in non-printable, it could be the first byte of a UTF-8
8126 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8127 // hex value.
8128 std::string CodePointStr;
8129 if (!llvm::sys::locale::isPrint(*csStart)) {
8130 llvm::UTF32 CodePoint;
8131 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8132 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8133 llvm::ConversionResult Result =
8134 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8135
8136 if (Result != llvm::conversionOK) {
8137 unsigned char FirstChar = *csStart;
8138 CodePoint = (llvm::UTF32)FirstChar;
8139 }
8140
8141 llvm::raw_string_ostream OS(CodePointStr);
8142 if (CodePoint < 256)
8143 OS << "\\x" << llvm::format("%02x", CodePoint);
8144 else if (CodePoint <= 0xFFFF)
8145 OS << "\\u" << llvm::format("%04x", CodePoint);
8146 else
8147 OS << "\\U" << llvm::format("%08x", CodePoint);
8148 Specifier = CodePointStr;
8149 }
8150
8151 EmitFormatDiagnostic(
8152 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8153 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8154
8155 return keepGoing;
8156}
8157
8158void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8159 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8160 EmitFormatDiagnostic(
8161 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8162 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8163}
8164
8165bool CheckFormatHandler::CheckNumArgs(
8168 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8169
8170 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8171 PartialDiagnostic PDiag =
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(PDiag, getLocationOfByte(CS.getStart()),
8177 /*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, Loc,
8195 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, const char *startSpecifier,
8277 unsigned specifierLen) override;
8278
8279 void handleInvalidMaskType(StringRef MaskType) override;
8280
8281 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8282 const char *startSpecifier, unsigned specifierLen,
8283 const TargetInfo &Target) override;
8284 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8285 const char *StartSpecifier, unsigned SpecifierLen,
8286 const Expr *E);
8287
8288 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8289 unsigned k, const char *startSpecifier,
8290 unsigned specifierLen);
8291 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8292 const analyze_printf::OptionalAmount &Amt,
8293 unsigned type, const char *startSpecifier,
8294 unsigned specifierLen);
8295 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8296 const analyze_printf::OptionalFlag &flag,
8297 const char *startSpecifier, unsigned specifierLen);
8298 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8299 const analyze_printf::OptionalFlag &ignoredFlag,
8300 const analyze_printf::OptionalFlag &flag,
8301 const char *startSpecifier, unsigned specifierLen);
8302 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8303
8304 void HandleEmptyObjCModifierFlag(const char *startFlag,
8305 unsigned flagLen) override;
8306
8307 void HandleInvalidObjCModifierFlag(const char *startFlag,
8308 unsigned flagLen) override;
8309
8310 void
8311 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8312 const char *flagsEnd,
8313 const char *conversionPosition) override;
8314};
8315
8316/// Keeps around the information needed to verify that two specifiers are
8317/// compatible.
8318class EquatableFormatArgument {
8319public:
8320 enum SpecifierSensitivity : unsigned {
8321 SS_None,
8322 SS_Private,
8323 SS_Public,
8324 SS_Sensitive
8325 };
8326
8327 enum FormatArgumentRole : unsigned {
8328 FAR_Data,
8329 FAR_FieldWidth,
8330 FAR_Precision,
8331 FAR_Auxiliary, // FreeBSD kernel %b and %D
8332 };
8333
8334private:
8335 analyze_format_string::ArgType ArgType;
8337 StringRef SpecifierLetter;
8338 CharSourceRange Range;
8339 SourceLocation ElementLoc;
8340 FormatArgumentRole Role : 2;
8341 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8342 unsigned Position : 14;
8343 unsigned ModifierFor : 14; // not set for FAR_Data
8344
8345 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8346 bool InFunctionCall) const;
8347
8348public:
8349 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8351 StringRef SpecifierLetter,
8352 analyze_format_string::ArgType ArgType,
8353 FormatArgumentRole Role,
8354 SpecifierSensitivity Sensitivity, unsigned Position,
8355 unsigned ModifierFor)
8356 : ArgType(ArgType), LengthMod(LengthMod),
8357 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8358 Role(Role), Sensitivity(Sensitivity), Position(Position),
8359 ModifierFor(ModifierFor) {}
8360
8361 unsigned getPosition() const { return Position; }
8362 SourceLocation getSourceLocation() const { return ElementLoc; }
8363 CharSourceRange getSourceRange() const { return Range; }
8364 analyze_format_string::LengthModifier getLengthModifier() const {
8365 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8366 }
8367 void setModifierFor(unsigned V) { ModifierFor = V; }
8368
8369 std::string buildFormatSpecifier() const {
8370 std::string result;
8371 llvm::raw_string_ostream(result)
8372 << getLengthModifier().toString() << SpecifierLetter;
8373 return result;
8374 }
8375
8376 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8377 const Expr *FmtExpr, bool InFunctionCall) const;
8378};
8379
8380/// Turns format strings into lists of EquatableSpecifier objects.
8381class DecomposePrintfHandler : public CheckPrintfHandler {
8382 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8383 bool HadError;
8384
8385 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8386 const Expr *origFormatExpr,
8387 const FormatStringType type, unsigned firstDataArg,
8388 unsigned numDataArgs, bool isObjC, const char *beg,
8390 ArrayRef<const Expr *> Args, unsigned formatIdx,
8391 bool inFunctionCall, VariadicCallType CallType,
8392 llvm::SmallBitVector &CheckedVarArgs,
8393 UncoveredArgHandler &UncoveredArg,
8394 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8395 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8396 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8397 inFunctionCall, CallType, CheckedVarArgs,
8398 UncoveredArg),
8399 Specs(Specs), HadError(false) {}
8400
8401public:
8402 static bool
8403 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8404 FormatStringType type, bool IsObjC, bool InFunctionCall,
8405 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8406
8407 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8408 const char *startSpecifier,
8409 unsigned specifierLen,
8410 const TargetInfo &Target) override;
8411};
8412
8413} // namespace
8414
8415bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8416 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8417 unsigned specifierLen) {
8420
8421 return HandleInvalidConversionSpecifier(
8422 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8423 specifierLen, CS.getStart(), CS.getLength());
8424}
8425
8426void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8427 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8428}
8429
8430// Error out if struct or complex type argments are passed to os_log.
8432 QualType T) {
8433 if (FSType != FormatStringType::OSLog)
8434 return false;
8435 return T->isRecordType() || T->isComplexType();
8436}
8437
8438bool CheckPrintfHandler::HandleAmount(
8439 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8440 const char *startSpecifier, unsigned specifierLen) {
8441 if (Amt.hasDataArgument()) {
8442 if (HasFormatArguments()) {
8443 unsigned argIndex = Amt.getArgIndex();
8444 if (argIndex >= NumDataArgs) {
8445 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8446 << k,
8447 getLocationOfByte(Amt.getStart()),
8448 /*IsStringLocation*/ true,
8449 getSpecifierRange(startSpecifier, specifierLen));
8450 // Don't do any more checking. We will just emit
8451 // spurious errors.
8452 return false;
8453 }
8454
8455 // Type check the data argument. It should be an 'int'.
8456 // Although not in conformance with C99, we also allow the argument to be
8457 // an 'unsigned int' as that is a reasonably safe case. GCC also
8458 // doesn't emit a warning for that case.
8459 CoveredArgs.set(argIndex);
8460 const Expr *Arg = getDataArg(argIndex);
8461 if (!Arg)
8462 return false;
8463
8464 QualType T = Arg->getType();
8465
8466 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8467 assert(AT.isValid());
8468
8469 if (!AT.matchesType(S.Context, T)) {
8470 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8471 ? diag::err_printf_asterisk_wrong_type
8472 : diag::warn_printf_asterisk_wrong_type;
8473 EmitFormatDiagnostic(S.PDiag(DiagID)
8475 << T << Arg->getSourceRange(),
8476 getLocationOfByte(Amt.getStart()),
8477 /*IsStringLocation*/ true,
8478 getSpecifierRange(startSpecifier, specifierLen));
8479 // Don't do any more checking. We will just emit
8480 // spurious errors.
8481 return false;
8482 }
8483 }
8484 }
8485 return true;
8486}
8487
8488void CheckPrintfHandler::HandleInvalidAmount(
8490 const analyze_printf::OptionalAmount &Amt, unsigned type,
8491 const char *startSpecifier, unsigned specifierLen) {
8494
8495 FixItHint fixit =
8498 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8499 : FixItHint();
8500
8501 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8502 << type << CS.toString(),
8503 getLocationOfByte(Amt.getStart()),
8504 /*IsStringLocation*/ true,
8505 getSpecifierRange(startSpecifier, specifierLen), fixit);
8506}
8507
8508void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8509 const analyze_printf::OptionalFlag &flag,
8510 const char *startSpecifier,
8511 unsigned specifierLen) {
8512 // Warn about pointless flag with a fixit removal.
8515 EmitFormatDiagnostic(
8516 S.PDiag(diag::warn_printf_nonsensical_flag)
8517 << flag.toString() << CS.toString(),
8518 getLocationOfByte(flag.getPosition()),
8519 /*IsStringLocation*/ true,
8520 getSpecifierRange(startSpecifier, specifierLen),
8521 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8522}
8523
8524void CheckPrintfHandler::HandleIgnoredFlag(
8526 const analyze_printf::OptionalFlag &ignoredFlag,
8527 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8528 unsigned specifierLen) {
8529 // Warn about ignored flag with a fixit removal.
8530 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8531 << ignoredFlag.toString() << flag.toString(),
8532 getLocationOfByte(ignoredFlag.getPosition()),
8533 /*IsStringLocation*/ true,
8534 getSpecifierRange(startSpecifier, specifierLen),
8536 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8537}
8538
8539void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8540 unsigned flagLen) {
8541 // Warn about an empty flag.
8542 EmitFormatDiagnostic(
8543 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8544 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8545}
8546
8547void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8548 unsigned flagLen) {
8549 // Warn about an invalid flag.
8550 auto Range = getSpecifierRange(startFlag, flagLen);
8551 StringRef flag(startFlag, flagLen);
8552 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8553 getLocationOfByte(startFlag),
8554 /*IsStringLocation*/ true, Range,
8556}
8557
8558void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8559 const char *flagsStart, const char *flagsEnd,
8560 const char *conversionPosition) {
8561 // Warn about using '[...]' without a '@' conversion.
8562 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8563 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8564 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8565 getLocationOfByte(conversionPosition),
8566 /*IsStringLocation*/ true, Range,
8568}
8569
8570void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8571 const Expr *FmtExpr,
8572 bool InFunctionCall) const {
8573 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8574 ElementLoc, true, Range);
8575}
8576
8577bool EquatableFormatArgument::VerifyCompatible(
8578 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8579 bool InFunctionCall) const {
8581 if (Role != Other.Role) {
8582 // diagnose and stop
8583 EmitDiagnostic(
8584 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8585 FmtExpr, InFunctionCall);
8586 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8587 return false;
8588 }
8589
8590 if (Role != FAR_Data) {
8591 if (ModifierFor != Other.ModifierFor) {
8592 // diagnose and stop
8593 EmitDiagnostic(S,
8594 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8595 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8596 FmtExpr, InFunctionCall);
8597 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8598 return false;
8599 }
8600 return true;
8601 }
8602
8603 bool HadError = false;
8604 if (Sensitivity != Other.Sensitivity) {
8605 // diagnose and continue
8606 EmitDiagnostic(S,
8607 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8608 << Sensitivity << Other.Sensitivity,
8609 FmtExpr, InFunctionCall);
8610 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8611 << 0 << Other.Range;
8612 }
8613
8614 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8615 case MK::Match:
8616 break;
8617
8618 case MK::MatchPromotion:
8619 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8620 // MatchPromotion is treated as a failure by format_matches.
8621 case MK::NoMatch:
8622 case MK::NoMatchTypeConfusion:
8623 case MK::NoMatchPromotionTypeConfusion:
8624 EmitDiagnostic(S,
8625 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8626 << buildFormatSpecifier()
8627 << Other.buildFormatSpecifier(),
8628 FmtExpr, InFunctionCall);
8629 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8630 << 0 << Other.Range;
8631 break;
8632
8633 case MK::NoMatchPedantic:
8634 EmitDiagnostic(S,
8635 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8636 << buildFormatSpecifier()
8637 << Other.buildFormatSpecifier(),
8638 FmtExpr, InFunctionCall);
8639 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8640 << 0 << Other.Range;
8641 break;
8642
8643 case MK::NoMatchSignedness:
8644 EmitDiagnostic(S,
8645 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8646 << buildFormatSpecifier()
8647 << Other.buildFormatSpecifier(),
8648 FmtExpr, InFunctionCall);
8649 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8650 << 0 << Other.Range;
8651 break;
8652 }
8653 return !HadError;
8654}
8655
8656bool DecomposePrintfHandler::GetSpecifiers(
8657 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8658 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8660 StringRef Data = FSL->getString();
8661 const char *Str = Data.data();
8662 llvm::SmallBitVector BV;
8663 UncoveredArgHandler UA;
8664 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8665 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8666 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8667 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8668 UA, Args);
8669
8671 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8673 H.DoneProcessing();
8674 if (H.HadError)
8675 return false;
8676
8677 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8678 const EquatableFormatArgument &B) {
8679 return A.getPosition() < B.getPosition();
8680 });
8681 return true;
8682}
8683
8684bool DecomposePrintfHandler::HandlePrintfSpecifier(
8685 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8686 unsigned specifierLen, const TargetInfo &Target) {
8687 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8688 specifierLen, Target)) {
8689 HadError = true;
8690 return false;
8691 }
8692
8693 // Do not add any specifiers to the list for %%. This is possibly incorrect
8694 // if using a precision/width with a data argument, but that combination is
8695 // meaningless and we wouldn't know which format to attach the
8696 // precision/width to.
8697 const auto &CS = FS.getConversionSpecifier();
8699 return true;
8700
8701 // have to patch these to have the right ModifierFor if they are used
8702 const unsigned Unset = ~0;
8703 unsigned FieldWidthIndex = Unset;
8704 unsigned PrecisionIndex = Unset;
8705
8706 // field width?
8707 const auto &FieldWidth = FS.getFieldWidth();
8708 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8709 FieldWidthIndex = Specs.size();
8710 Specs.emplace_back(
8711 getSpecifierRange(startSpecifier, specifierLen),
8712 getLocationOfByte(FieldWidth.getStart()),
8713 analyze_format_string::LengthModifier::None, FieldWidth.getCharacters(),
8714 FieldWidth.getArgType(S.Context),
8715 EquatableFormatArgument::FAR_FieldWidth,
8716 EquatableFormatArgument::SS_None,
8717 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8718 : FieldWidthIndex,
8719 0);
8720 }
8721 // precision?
8722 const auto &Precision = FS.getPrecision();
8723 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8724 PrecisionIndex = Specs.size();
8725 Specs.emplace_back(
8726 getSpecifierRange(startSpecifier, specifierLen),
8727 getLocationOfByte(Precision.getStart()),
8728 analyze_format_string::LengthModifier::None, Precision.getCharacters(),
8729 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8730 EquatableFormatArgument::SS_None,
8731 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8732 : PrecisionIndex,
8733 0);
8734 }
8735
8736 // this specifier
8737 unsigned SpecIndex =
8738 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8739 if (FieldWidthIndex != Unset)
8740 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8741 if (PrecisionIndex != Unset)
8742 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8743
8744 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8745 if (FS.isPrivate())
8746 Sensitivity = EquatableFormatArgument::SS_Private;
8747 else if (FS.isPublic())
8748 Sensitivity = EquatableFormatArgument::SS_Public;
8749 else if (FS.isSensitive())
8750 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8751 else
8752 Sensitivity = EquatableFormatArgument::SS_None;
8753
8754 Specs.emplace_back(
8755 getSpecifierRange(startSpecifier, specifierLen),
8756 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8757 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8758 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8759
8760 // auxiliary argument?
8763 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8764 getLocationOfByte(CS.getStart()),
8766 CS.getCharacters(),
8768 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8769 SpecIndex + 1, SpecIndex);
8770 }
8771 return true;
8772}
8773
8774// Determines if the specified is a C++ class or struct containing
8775// a member with the specified name and kind (e.g. a CXXMethodDecl named
8776// "c_str()").
8777template<typename MemberKind>
8779CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8780 auto *RD = Ty->getAsCXXRecordDecl();
8782
8783 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8784 return Results;
8785
8786 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8788 R.suppressDiagnostics();
8789
8790 // We just need to include all members of the right kind turned up by the
8791 // filter, at this point.
8792 if (S.LookupQualifiedName(R, RD))
8793 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8794 NamedDecl *decl = (*I)->getUnderlyingDecl();
8795 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8796 Results.insert(FK);
8797 }
8798 return Results;
8799}
8800
8801/// Check if we could call '.c_str()' on an object.
8802///
8803/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8804/// allow the call, or if it would be ambiguous).
8806 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8807
8808 MethodSet Results =
8809 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8810 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8811 MI != ME; ++MI)
8812 if ((*MI)->getMinRequiredArguments() == 0)
8813 return true;
8814 return false;
8815}
8816
8817// Check if a (w)string was passed when a (w)char* was needed, and offer a
8818// better diagnostic if so. AT is assumed to be valid.
8819// Returns true when a c_str() conversion method is found.
8820bool CheckPrintfHandler::checkForCStrMembers(
8821 const analyze_printf::ArgType &AT, const Expr *E) {
8822 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8823
8824 MethodSet Results =
8826
8827 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8828 MI != ME; ++MI) {
8829 const CXXMethodDecl *Method = *MI;
8830 if (Method->getMinRequiredArguments() == 0 &&
8831 AT.matchesType(S.Context, Method->getReturnType())) {
8832 // FIXME: Suggest parens if the expression needs them.
8834 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8835 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8836 return true;
8837 }
8838 }
8839
8840 return false;
8841}
8842
8843bool CheckPrintfHandler::HandlePrintfSpecifier(
8844 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8845 unsigned specifierLen, const TargetInfo &Target) {
8846 using namespace analyze_format_string;
8847 using namespace analyze_printf;
8848
8849 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8850
8851 if (FS.consumesDataArgument()) {
8852 if (atFirstArg) {
8853 atFirstArg = false;
8854 usesPositionalArgs = FS.usesPositionalArg();
8855 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
8856 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8857 startSpecifier, specifierLen);
8858 return false;
8859 }
8860 }
8861
8862 // First check if the field width, precision, and conversion specifier
8863 // have matching data arguments.
8864 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
8865 specifierLen)) {
8866 return false;
8867 }
8868
8869 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
8870 specifierLen)) {
8871 return false;
8872 }
8873
8874 if (!CS.consumesDataArgument()) {
8875 // FIXME: Technically specifying a precision or field width here
8876 // makes no sense. Worth issuing a warning at some point.
8877 return true;
8878 }
8879
8880 // Consume the argument.
8881 unsigned argIndex = FS.getArgIndex();
8882 if (argIndex < NumDataArgs) {
8883 // The check to see if the argIndex is valid will come later.
8884 // We set the bit here because we may exit early from this
8885 // function if we encounter some other error.
8886 CoveredArgs.set(argIndex);
8887 }
8888
8889 // FreeBSD kernel extensions.
8890 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8891 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8892 // We need at least two arguments.
8893 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8894 return false;
8895
8896 if (HasFormatArguments()) {
8897 // Claim the second argument.
8898 CoveredArgs.set(argIndex + 1);
8899
8900 // Type check the first argument (int for %b, pointer for %D)
8901 const Expr *Ex = getDataArg(argIndex);
8902 const analyze_printf::ArgType &AT =
8903 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8904 ? ArgType(S.Context.IntTy)
8905 : ArgType::CPointerTy;
8906 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8907 EmitFormatDiagnostic(
8908 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8909 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8910 << false << Ex->getSourceRange(),
8911 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8912 getSpecifierRange(startSpecifier, specifierLen));
8913
8914 // Type check the second argument (char * for both %b and %D)
8915 Ex = getDataArg(argIndex + 1);
8917 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8918 EmitFormatDiagnostic(
8919 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8920 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8921 << false << Ex->getSourceRange(),
8922 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8923 getSpecifierRange(startSpecifier, specifierLen));
8924 }
8925 return true;
8926 }
8927
8928 // Check for using an Objective-C specific conversion specifier
8929 // in a non-ObjC literal.
8930 if (!allowsObjCArg() && CS.isObjCArg()) {
8931 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8932 specifierLen);
8933 }
8934
8935 // %P can only be used with os_log.
8936 if (FSType != FormatStringType::OSLog &&
8937 CS.getKind() == ConversionSpecifier::PArg) {
8938 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8939 specifierLen);
8940 }
8941
8942 // %n is not allowed with os_log.
8943 if (FSType == FormatStringType::OSLog &&
8944 CS.getKind() == ConversionSpecifier::nArg) {
8945 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8946 getLocationOfByte(CS.getStart()),
8947 /*IsStringLocation*/ false,
8948 getSpecifierRange(startSpecifier, specifierLen));
8949
8950 return true;
8951 }
8952
8953 // Only scalars are allowed for os_trace.
8954 if (FSType == FormatStringType::OSTrace &&
8955 (CS.getKind() == ConversionSpecifier::PArg ||
8956 CS.getKind() == ConversionSpecifier::sArg ||
8957 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8958 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8959 specifierLen);
8960 }
8961
8962 // Check for use of public/private annotation outside of os_log().
8963 if (FSType != FormatStringType::OSLog) {
8964 if (FS.isPublic().isSet()) {
8965 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8966 << "public",
8967 getLocationOfByte(FS.isPublic().getPosition()),
8968 /*IsStringLocation*/ false,
8969 getSpecifierRange(startSpecifier, specifierLen));
8970 }
8971 if (FS.isPrivate().isSet()) {
8972 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8973 << "private",
8974 getLocationOfByte(FS.isPrivate().getPosition()),
8975 /*IsStringLocation*/ false,
8976 getSpecifierRange(startSpecifier, specifierLen));
8977 }
8978 }
8979
8980 const llvm::Triple &Triple = Target.getTriple();
8981 if (CS.getKind() == ConversionSpecifier::nArg &&
8982 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8983 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8984 getLocationOfByte(CS.getStart()),
8985 /*IsStringLocation*/ false,
8986 getSpecifierRange(startSpecifier, specifierLen));
8987 }
8988
8989 // Check for invalid use of field width
8990 if (!FS.hasValidFieldWidth()) {
8991 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8992 startSpecifier, specifierLen);
8993 }
8994
8995 // Check for invalid use of precision
8996 if (!FS.hasValidPrecision()) {
8997 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8998 startSpecifier, specifierLen);
8999 }
9000
9001 // Precision is mandatory for %P specifier.
9002 if (CS.getKind() == ConversionSpecifier::PArg &&
9004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9005 getLocationOfByte(startSpecifier),
9006 /*IsStringLocation*/ false,
9007 getSpecifierRange(startSpecifier, specifierLen));
9008 }
9009
9010 // Check each flag does not conflict with any other component.
9012 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9013 if (!FS.hasValidLeadingZeros())
9014 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9015 if (!FS.hasValidPlusPrefix())
9016 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9017 if (!FS.hasValidSpacePrefix())
9018 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9019 if (!FS.hasValidAlternativeForm())
9020 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9021 if (!FS.hasValidLeftJustified())
9022 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9023
9024 // Check that flags are not ignored by another flag
9025 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9026 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9027 startSpecifier, specifierLen);
9028 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9029 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9030 startSpecifier, specifierLen);
9031
9032 // Check the length modifier is valid with the given conversion specifier.
9034 S.getLangOpts()))
9035 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9036 diag::warn_format_nonsensical_length);
9037 else if (!FS.hasStandardLengthModifier())
9038 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9040 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9041 diag::warn_format_non_standard_conversion_spec);
9042
9044 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9045
9046 // The remaining checks depend on the data arguments.
9047 if (!HasFormatArguments())
9048 return true;
9049
9050 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9051 return false;
9052
9053 const Expr *Arg = getDataArg(argIndex);
9054 if (!Arg)
9055 return true;
9056
9057 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9058}
9059
9060static bool requiresParensToAddCast(const Expr *E) {
9061 // FIXME: We should have a general way to reason about operator
9062 // precedence and whether parens are actually needed here.
9063 // Take care of a few common cases where they aren't.
9064 const Expr *Inside = E->IgnoreImpCasts();
9065 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9066 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9067
9068 switch (Inside->getStmtClass()) {
9069 case Stmt::ArraySubscriptExprClass:
9070 case Stmt::CallExprClass:
9071 case Stmt::CharacterLiteralClass:
9072 case Stmt::CXXBoolLiteralExprClass:
9073 case Stmt::DeclRefExprClass:
9074 case Stmt::FloatingLiteralClass:
9075 case Stmt::IntegerLiteralClass:
9076 case Stmt::MemberExprClass:
9077 case Stmt::ObjCArrayLiteralClass:
9078 case Stmt::ObjCBoolLiteralExprClass:
9079 case Stmt::ObjCBoxedExprClass:
9080 case Stmt::ObjCDictionaryLiteralClass:
9081 case Stmt::ObjCEncodeExprClass:
9082 case Stmt::ObjCIvarRefExprClass:
9083 case Stmt::ObjCMessageExprClass:
9084 case Stmt::ObjCPropertyRefExprClass:
9085 case Stmt::ObjCStringLiteralClass:
9086 case Stmt::ObjCSubscriptRefExprClass:
9087 case Stmt::ParenExprClass:
9088 case Stmt::StringLiteralClass:
9089 case Stmt::UnaryOperatorClass:
9090 return false;
9091 default:
9092 return true;
9093 }
9094}
9095
9096static std::pair<QualType, StringRef>
9097shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9098 const Expr *E) {
9099 // Use a 'while' to peel off layers of typedefs.
9100 QualType TyTy = IntendedTy;
9101 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9102 StringRef Name = UserTy->getDecl()->getName();
9103 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9104 .Case("CFIndex", Context.getNSIntegerType())
9105 .Case("NSInteger", Context.getNSIntegerType())
9106 .Case("NSUInteger", Context.getNSUIntegerType())
9107 .Case("SInt32", Context.IntTy)
9108 .Case("UInt32", Context.UnsignedIntTy)
9109 .Default(QualType());
9110
9111 if (!CastTy.isNull())
9112 return std::make_pair(CastTy, Name);
9113
9114 TyTy = UserTy->desugar();
9115 }
9116
9117 // Strip parens if necessary.
9118 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9119 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9120 PE->getSubExpr());
9121
9122 // If this is a conditional expression, then its result type is constructed
9123 // via usual arithmetic conversions and thus there might be no necessary
9124 // typedef sugar there. Recurse to operands to check for NSInteger &
9125 // Co. usage condition.
9126 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9127 QualType TrueTy, FalseTy;
9128 StringRef TrueName, FalseName;
9129
9130 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9131 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9132 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9133 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9134
9135 if (TrueTy == FalseTy)
9136 return std::make_pair(TrueTy, TrueName);
9137 else if (TrueTy.isNull())
9138 return std::make_pair(FalseTy, FalseName);
9139 else if (FalseTy.isNull())
9140 return std::make_pair(TrueTy, TrueName);
9141 }
9142
9143 return std::make_pair(QualType(), StringRef());
9144}
9145
9146/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9147/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9148/// type do not count.
9150 const ImplicitCastExpr *ICE) {
9151 QualType From = ICE->getSubExpr()->getType();
9152 QualType To = ICE->getType();
9153 // It's an integer promotion if the destination type is the promoted
9154 // source type.
9155 if (ICE->getCastKind() == CK_IntegralCast &&
9157 S.Context.getPromotedIntegerType(From) == To)
9158 return true;
9159 // Look through vector types, since we do default argument promotion for
9160 // those in OpenCL.
9161 if (const auto *VecTy = From->getAs<ExtVectorType>())
9162 From = VecTy->getElementType();
9163 if (const auto *VecTy = To->getAs<ExtVectorType>())
9164 To = VecTy->getElementType();
9165 // It's a floating promotion if the source type is a lower rank.
9166 return ICE->getCastKind() == CK_FloatingCast &&
9167 S.Context.getFloatingTypeOrder(From, To) < 0;
9168}
9169
9172 DiagnosticsEngine &Diags, SourceLocation Loc) {
9174 if (Diags.isIgnored(
9175 diag::warn_format_conversion_argument_type_mismatch_signedness,
9176 Loc) ||
9177 Diags.isIgnored(
9178 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9179 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9181 }
9182 }
9183 return Match;
9184}
9185
9186bool CheckPrintfHandler::checkFormatExpr(
9187 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9188 unsigned SpecifierLen, const Expr *E) {
9189 using namespace analyze_format_string;
9190 using namespace analyze_printf;
9191
9192 // Now type check the data expression that matches the
9193 // format specifier.
9194 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9195 if (!AT.isValid())
9196 return true;
9197
9198 QualType ExprTy = E->getType();
9199 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9200 ExprTy = TET->getUnderlyingExpr()->getType();
9201 }
9202
9203 if (const OverflowBehaviorType *OBT =
9204 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9205 ExprTy = OBT->getUnderlyingType();
9206
9207 // When using the format attribute in C++, you can receive a function or an
9208 // array that will necessarily decay to a pointer when passed to the final
9209 // format consumer. Apply decay before type comparison.
9210 if (ExprTy->canDecayToPointerType())
9211 ExprTy = S.Context.getDecayedType(ExprTy);
9212
9213 // Diagnose attempts to print a boolean value as a character. Unlike other
9214 // -Wformat diagnostics, this is fine from a type perspective, but it still
9215 // doesn't make sense.
9218 const CharSourceRange &CSR =
9219 getSpecifierRange(StartSpecifier, SpecifierLen);
9220 SmallString<4> FSString;
9221 llvm::raw_svector_ostream os(FSString);
9222 FS.toString(os);
9223 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9224 << FSString,
9225 E->getExprLoc(), false, CSR);
9226 return true;
9227 }
9228
9229 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9230 // dumping raw class data (like is-a pointer), not actual data.
9232 ExprTy->isObjCObjectPointerType()) {
9233 const CharSourceRange &CSR =
9234 getSpecifierRange(StartSpecifier, SpecifierLen);
9235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9236 E->getExprLoc(), false, CSR);
9237 return true;
9238 }
9239
9240 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9242 ArgType::MatchKind OrigMatch = Match;
9243
9245 if (Match == ArgType::Match)
9246 return true;
9247
9248 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9249 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9250
9251 // Look through argument promotions for our error message's reported type.
9252 // This includes the integral and floating promotions, but excludes array
9253 // and function pointer decay (seeing that an argument intended to be a
9254 // string has type 'char [6]' is probably more confusing than 'char *') and
9255 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9256 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9257 if (isArithmeticArgumentPromotion(S, ICE)) {
9258 E = ICE->getSubExpr();
9259 ExprTy = E->getType();
9260
9261 // Check if we didn't match because of an implicit cast from a 'char'
9262 // or 'short' to an 'int'. This is done because printf is a varargs
9263 // function.
9264 if (ICE->getType() == S.Context.IntTy ||
9265 ICE->getType() == S.Context.UnsignedIntTy) {
9266 // All further checking is done on the subexpression
9267 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9268 if (OrigMatch == ArgType::NoMatchSignedness &&
9269 ImplicitMatch != ArgType::NoMatchSignedness)
9270 // If the original match was a signedness match this match on the
9271 // implicit cast type also need to be signedness match otherwise we
9272 // might introduce new unexpected warnings from -Wformat-signedness.
9273 return true;
9274 ImplicitMatch = handleFormatSignedness(
9275 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9276 if (ImplicitMatch == ArgType::Match)
9277 return true;
9278 }
9279 }
9280 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9281 // Special case for 'a', which has type 'int' in C.
9282 // Note, however, that we do /not/ want to treat multibyte constants like
9283 // 'MooV' as characters! This form is deprecated but still exists. In
9284 // addition, don't treat expressions as of type 'char' if one byte length
9285 // modifier is provided.
9286 if (ExprTy == S.Context.IntTy &&
9288 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9289 ExprTy = S.Context.CharTy;
9290 // To improve check results, we consider a character literal in C
9291 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9292 // more likely a type confusion situation, so we will suggest to
9293 // use '%hhd' instead by discarding the MatchPromotion.
9294 if (Match == ArgType::MatchPromotion)
9296 }
9297 }
9298 if (Match == ArgType::MatchPromotion) {
9299 // WG14 N2562 only clarified promotions in *printf
9300 // For NSLog in ObjC, just preserve -Wformat behavior
9301 if (!S.getLangOpts().ObjC &&
9302 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9303 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9304 return true;
9306 }
9307 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9308 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9309 Match = ImplicitMatch;
9310 assert(Match != ArgType::MatchPromotion);
9311
9312 // Look through unscoped enums to their underlying type.
9313 bool IsEnum = false;
9314 bool IsScopedEnum = false;
9315 QualType IntendedTy = ExprTy;
9316 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9317 IntendedTy = ED->getIntegerType();
9318 if (!ED->isScoped()) {
9319 ExprTy = IntendedTy;
9320 // This controls whether we're talking about the underlying type or not,
9321 // which we only want to do when it's an unscoped enum.
9322 IsEnum = true;
9323 } else {
9324 IsScopedEnum = true;
9325 }
9326 }
9327
9328 // %C in an Objective-C context prints a unichar, not a wchar_t.
9329 // If the argument is an integer of some kind, believe the %C and suggest
9330 // a cast instead of changing the conversion specifier.
9331 if (isObjCContext() &&
9334 !ExprTy->isCharType()) {
9335 // 'unichar' is defined as a typedef of unsigned short, but we should
9336 // prefer using the typedef if it is visible.
9337 IntendedTy = S.Context.UnsignedShortTy;
9338
9339 // While we are here, check if the value is an IntegerLiteral that happens
9340 // to be within the valid range.
9341 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9342 const llvm::APInt &V = IL->getValue();
9343 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9344 return true;
9345 }
9346
9347 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9349 if (S.LookupName(Result, S.getCurScope())) {
9350 NamedDecl *ND = Result.getFoundDecl();
9351 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9352 if (TD->getUnderlyingType() == IntendedTy)
9353 IntendedTy =
9355 /*Qualifier=*/std::nullopt, TD);
9356 }
9357 }
9358 }
9359
9360 // Special-case some of Darwin's platform-independence types by suggesting
9361 // casts to primitive types that are known to be large enough.
9362 bool ShouldNotPrintDirectly = false;
9363 StringRef CastTyName;
9364 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9365 QualType CastTy;
9366 std::tie(CastTy, CastTyName) =
9367 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9368 if (!CastTy.isNull()) {
9369 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9370 // (long in ASTContext). Only complain to pedants or when they're the
9371 // underlying type of a scoped enum (which always needs a cast).
9372 if (!IsScopedEnum &&
9373 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9374 (AT.isSizeT() || AT.isPtrdiffT()) &&
9375 AT.matchesType(S.Context, CastTy))
9377 IntendedTy = CastTy;
9378 ShouldNotPrintDirectly = true;
9379 }
9380 }
9381
9382 // We may be able to offer a FixItHint if it is a supported type.
9383 PrintfSpecifier fixedFS = FS;
9384 bool Success =
9385 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9386
9387 if (Success) {
9388 // Get the fix string from the fixed format specifier
9389 SmallString<16> buf;
9390 llvm::raw_svector_ostream os(buf);
9391 fixedFS.toString(os);
9392
9393 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9394
9395 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9396 unsigned Diag;
9397 switch (Match) {
9398 case ArgType::Match:
9401 llvm_unreachable("expected non-matching");
9403 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9404 break;
9406 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9407 break;
9409 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9410 break;
9411 case ArgType::NoMatch:
9412 Diag = diag::warn_format_conversion_argument_type_mismatch;
9413 break;
9414 }
9415
9416 // In this case, the specifier is wrong and should be changed to match
9417 // the argument.
9418 EmitFormatDiagnostic(S.PDiag(Diag)
9420 << IntendedTy << IsEnum << E->getSourceRange(),
9421 E->getBeginLoc(),
9422 /*IsStringLocation*/ false, SpecRange,
9423 FixItHint::CreateReplacement(SpecRange, os.str()));
9424 } else {
9425 // The canonical type for formatting this value is different from the
9426 // actual type of the expression. (This occurs, for example, with Darwin's
9427 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9428 // should be printed as 'long' for 64-bit compatibility.)
9429 // Rather than emitting a normal format/argument mismatch, we want to
9430 // add a cast to the recommended type (and correct the format string
9431 // if necessary). We should also do so for scoped enumerations.
9432 SmallString<16> CastBuf;
9433 llvm::raw_svector_ostream CastFix(CastBuf);
9434 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9435 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9436 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9437
9439 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9440 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9441 E->getExprLoc());
9442 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9443 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9444
9445 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9446 // If there's already a cast present, just replace it.
9447 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9448 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9449
9450 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9451 // If the expression has high enough precedence,
9452 // just write the C-style cast.
9453 Hints.push_back(
9454 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9455 } else {
9456 // Otherwise, add parens around the expression as well as the cast.
9457 CastFix << "(";
9458 Hints.push_back(
9459 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9460
9461 // We don't use getLocForEndOfToken because it returns invalid source
9462 // locations for macro expansions (by design).
9466 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9467 }
9468
9469 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9470 // The expression has a type that should not be printed directly.
9471 // We extract the name from the typedef because we don't want to show
9472 // the underlying type in the diagnostic.
9473 StringRef Name;
9474 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9475 Name = TypedefTy->getDecl()->getName();
9476 else
9477 Name = CastTyName;
9478 unsigned Diag = Match == ArgType::NoMatchPedantic
9479 ? diag::warn_format_argument_needs_cast_pedantic
9480 : diag::warn_format_argument_needs_cast;
9481 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9482 << E->getSourceRange(),
9483 E->getBeginLoc(), /*IsStringLocation=*/false,
9484 SpecRange, Hints);
9485 } else {
9486 // In this case, the expression could be printed using a different
9487 // specifier, but we've decided that the specifier is probably correct
9488 // and we should cast instead. Just use the normal warning message.
9489
9490 unsigned Diag =
9491 IsScopedEnum
9492 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9493 : diag::warn_format_conversion_argument_type_mismatch;
9494
9495 EmitFormatDiagnostic(
9496 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9497 << IsEnum << E->getSourceRange(),
9498 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9499 }
9500 }
9501 } else {
9502 const CharSourceRange &CSR =
9503 getSpecifierRange(StartSpecifier, SpecifierLen);
9504 // Since the warning for passing non-POD types to variadic functions
9505 // was deferred until now, we emit a warning for non-POD
9506 // arguments here.
9507 bool EmitTypeMismatch = false;
9508 switch (S.isValidVarArgType(ExprTy)) {
9509 case VarArgKind::Valid:
9511 unsigned Diag;
9512 switch (Match) {
9513 case ArgType::Match:
9516 llvm_unreachable("expected non-matching");
9518 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9519 break;
9521 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9522 break;
9524 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9525 break;
9526 case ArgType::NoMatch:
9527 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
9528 ? diag::err_format_conversion_argument_type_mismatch
9529 : diag::warn_format_conversion_argument_type_mismatch;
9530 break;
9531 }
9532
9533 EmitFormatDiagnostic(
9534 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9535 << IsEnum << CSR << E->getSourceRange(),
9536 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9537 break;
9538 }
9541 if (CallType == VariadicCallType::DoesNotApply) {
9542 EmitTypeMismatch = true;
9543 } else {
9544 EmitFormatDiagnostic(
9545 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9546 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9547 << AT.getRepresentativeTypeName(S.Context) << CSR
9548 << E->getSourceRange(),
9549 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9550 checkForCStrMembers(AT, E);
9551 }
9552 break;
9553
9555 if (CallType == VariadicCallType::DoesNotApply)
9556 EmitTypeMismatch = true;
9557 else if (ExprTy->isObjCObjectType())
9558 EmitFormatDiagnostic(
9559 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9560 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9561 << AT.getRepresentativeTypeName(S.Context) << CSR
9562 << E->getSourceRange(),
9563 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9564 else
9565 // FIXME: If this is an initializer list, suggest removing the braces
9566 // or inserting a cast to the target type.
9567 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9568 << isa<InitListExpr>(E) << ExprTy << CallType
9570 break;
9571 }
9572
9573 if (EmitTypeMismatch) {
9574 // The function is not variadic, so we do not generate warnings about
9575 // being allowed to pass that object as a variadic argument. Instead,
9576 // since there are inherently no printf specifiers for types which cannot
9577 // be passed as variadic arguments, emit a plain old specifier mismatch
9578 // argument.
9579 EmitFormatDiagnostic(
9580 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9581 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9582 << E->getSourceRange(),
9583 E->getBeginLoc(), false, CSR);
9584 }
9585
9586 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9587 "format string specifier index out of range");
9588 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9589 }
9590
9591 return true;
9592}
9593
9594//===--- CHECK: Scanf format string checking ------------------------------===//
9595
9596namespace {
9597
9598class CheckScanfHandler : public CheckFormatHandler {
9599public:
9600 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9601 const Expr *origFormatExpr, FormatStringType type,
9602 unsigned firstDataArg, unsigned numDataArgs,
9603 const char *beg, Sema::FormatArgumentPassingKind APK,
9604 ArrayRef<const Expr *> Args, unsigned formatIdx,
9605 bool inFunctionCall, VariadicCallType CallType,
9606 llvm::SmallBitVector &CheckedVarArgs,
9607 UncoveredArgHandler &UncoveredArg)
9608 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9609 numDataArgs, beg, APK, Args, formatIdx,
9610 inFunctionCall, CallType, CheckedVarArgs,
9611 UncoveredArg) {}
9612
9613 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9614 const char *startSpecifier,
9615 unsigned specifierLen) override;
9616
9617 bool
9618 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9619 const char *startSpecifier,
9620 unsigned specifierLen) override;
9621
9622 void HandleIncompleteScanList(const char *start, const char *end) override;
9623};
9624
9625} // namespace
9626
9627void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9628 const char *end) {
9629 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9630 getLocationOfByte(end), /*IsStringLocation*/ true,
9631 getSpecifierRange(start, end - start));
9632}
9633
9634bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9635 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9636 unsigned specifierLen) {
9639
9640 return HandleInvalidConversionSpecifier(
9641 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9642 specifierLen, CS.getStart(), CS.getLength());
9643}
9644
9645bool CheckScanfHandler::HandleScanfSpecifier(
9646 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9647 unsigned specifierLen) {
9648 using namespace analyze_scanf;
9649 using namespace analyze_format_string;
9650
9651 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9652
9653 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9654 // be used to decide if we are using positional arguments consistently.
9655 if (FS.consumesDataArgument()) {
9656 if (atFirstArg) {
9657 atFirstArg = false;
9658 usesPositionalArgs = FS.usesPositionalArg();
9659 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9660 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9661 startSpecifier, specifierLen);
9662 return false;
9663 }
9664 }
9665
9666 // Check if the field with is non-zero.
9667 const OptionalAmount &Amt = FS.getFieldWidth();
9669 if (Amt.getConstantAmount() == 0) {
9670 const CharSourceRange &R =
9671 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9672 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9673 getLocationOfByte(Amt.getStart()),
9674 /*IsStringLocation*/ true, R,
9676 }
9677 }
9678
9679 if (!FS.consumesDataArgument()) {
9680 // FIXME: Technically specifying a precision or field width here
9681 // makes no sense. Worth issuing a warning at some point.
9682 return true;
9683 }
9684
9685 // Consume the argument.
9686 unsigned argIndex = FS.getArgIndex();
9687 if (argIndex < NumDataArgs) {
9688 // The check to see if the argIndex is valid will come later.
9689 // We set the bit here because we may exit early from this
9690 // function if we encounter some other error.
9691 CoveredArgs.set(argIndex);
9692 }
9693
9694 // Check the length modifier is valid with the given conversion specifier.
9696 S.getLangOpts()))
9697 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9698 diag::warn_format_nonsensical_length);
9699 else if (!FS.hasStandardLengthModifier())
9700 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9702 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9703 diag::warn_format_non_standard_conversion_spec);
9704
9706 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9707
9708 // The remaining checks depend on the data arguments.
9709 if (!HasFormatArguments())
9710 return true;
9711
9712 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9713 return false;
9714
9715 // Check that the argument type matches the format specifier.
9716 const Expr *Ex = getDataArg(argIndex);
9717 if (!Ex)
9718 return true;
9719
9721
9722 if (!AT.isValid()) {
9723 return true;
9724 }
9725
9727 AT.matchesType(S.Context, Ex->getType());
9730 return true;
9733
9734 ScanfSpecifier fixedFS = FS;
9735 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9736 S.getLangOpts(), S.Context);
9737
9738 unsigned Diag =
9739 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9740 : Signedness
9741 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9742 : diag::warn_format_conversion_argument_type_mismatch;
9743
9744 if (Success) {
9745 // Get the fix string from the fixed format specifier.
9746 SmallString<128> buf;
9747 llvm::raw_svector_ostream os(buf);
9748 fixedFS.toString(os);
9749
9750 EmitFormatDiagnostic(
9752 << Ex->getType() << false << Ex->getSourceRange(),
9753 Ex->getBeginLoc(),
9754 /*IsStringLocation*/ false,
9755 getSpecifierRange(startSpecifier, specifierLen),
9757 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9758 } else {
9759 EmitFormatDiagnostic(S.PDiag(Diag)
9761 << Ex->getType() << false << Ex->getSourceRange(),
9762 Ex->getBeginLoc(),
9763 /*IsStringLocation*/ false,
9764 getSpecifierRange(startSpecifier, specifierLen));
9765 }
9766
9767 return true;
9768}
9769
9770static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9772 const StringLiteral *Fmt,
9774 const Expr *FmtExpr, bool InFunctionCall) {
9775 bool HadError = false;
9776 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9777 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9778 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9779 // In positional-style format strings, the same specifier can appear
9780 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9781 // are sorted by getPosition(), and we process each range of equal
9782 // getPosition() values as one group.
9783 // RefArgs are taken from a string literal that was given to
9784 // attribute(format_matches), and if we got this far, we have already
9785 // verified that if it has positional specifiers that appear in multiple
9786 // locations, then they are all mutually compatible. What's left for us to
9787 // do is verify that all specifiers with the same position in FmtArgs are
9788 // compatible with the RefArgs specifiers. We check each specifier from
9789 // FmtArgs against the first member of the RefArgs group.
9790 for (; FmtIter < FmtEnd; ++FmtIter) {
9791 // Clang does not diagnose missing format specifiers in positional-style
9792 // strings (TODO: which it probably should do, as it is UB to skip over a
9793 // format argument). Skip specifiers if needed.
9794 if (FmtIter->getPosition() < RefIter->getPosition())
9795 continue;
9796
9797 // Delimits a new getPosition() value.
9798 if (FmtIter->getPosition() > RefIter->getPosition())
9799 break;
9800
9801 HadError |=
9802 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9803 }
9804
9805 // Jump RefIter to the start of the next group.
9806 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9807 return Arg.getPosition() != RefIter->getPosition();
9808 });
9809 }
9810
9811 if (FmtIter < FmtEnd) {
9812 CheckFormatHandler::EmitFormatDiagnostic(
9813 S, InFunctionCall, FmtExpr,
9814 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9815 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9816 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9817 } else if (RefIter < RefEnd) {
9818 CheckFormatHandler::EmitFormatDiagnostic(
9819 S, InFunctionCall, FmtExpr,
9820 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9821 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9822 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9823 << 1 << RefIter->getSourceRange();
9824 }
9825 return !HadError;
9826}
9827
9829 Sema &S, const FormatStringLiteral *FExpr,
9830 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9832 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9833 bool inFunctionCall, VariadicCallType CallType,
9834 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9835 bool IgnoreStringsWithoutSpecifiers) {
9836 // CHECK: is the format string a wide literal?
9837 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9838 CheckFormatHandler::EmitFormatDiagnostic(
9839 S, inFunctionCall, Args[format_idx],
9840 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9841 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9842 return;
9843 }
9844
9845 // Str - The format string. NOTE: this is NOT null-terminated!
9846 StringRef StrRef = FExpr->getString();
9847 const char *Str = StrRef.data();
9848 // Account for cases where the string literal is truncated in a declaration.
9849 const ConstantArrayType *T =
9850 S.Context.getAsConstantArrayType(FExpr->getType());
9851 assert(T && "String literal not of constant array type!");
9852 size_t TypeSize = T->getZExtSize();
9853 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9854 const unsigned numDataArgs = Args.size() - firstDataArg;
9855
9856 if (IgnoreStringsWithoutSpecifiers &&
9858 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9859 return;
9860
9861 // Emit a warning if the string literal is truncated and does not contain an
9862 // embedded null character.
9863 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9864 CheckFormatHandler::EmitFormatDiagnostic(
9865 S, inFunctionCall, Args[format_idx],
9866 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9867 FExpr->getBeginLoc(),
9868 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9869 return;
9870 }
9871
9872 // CHECK: empty format string?
9873 if (StrLen == 0 && numDataArgs > 0) {
9874 CheckFormatHandler::EmitFormatDiagnostic(
9875 S, inFunctionCall, Args[format_idx],
9876 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9877 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9878 return;
9879 }
9880
9885 bool IsObjC =
9887 if (ReferenceFormatString == nullptr) {
9888 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9889 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9890 inFunctionCall, CallType, CheckedVarArgs,
9891 UncoveredArg);
9892
9894 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9897 H.DoneProcessing();
9898 } else {
9900 Type, ReferenceFormatString, FExpr->getFormatString(),
9901 inFunctionCall ? nullptr : Args[format_idx]);
9902 }
9903 } else if (Type == FormatStringType::Scanf) {
9904 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9905 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9906 CallType, CheckedVarArgs, UncoveredArg);
9907
9909 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9910 H.DoneProcessing();
9911 } // TODO: handle other formats
9912}
9913
9915 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9916 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9921 return true;
9922
9923 bool IsObjC =
9926 FormatStringLiteral RefLit = AuthoritativeFormatString;
9927 FormatStringLiteral TestLit = TestedFormatString;
9928 const Expr *Arg;
9929 bool DiagAtStringLiteral;
9930 if (FunctionCallArg) {
9931 Arg = FunctionCallArg;
9932 DiagAtStringLiteral = false;
9933 } else {
9934 Arg = TestedFormatString;
9935 DiagAtStringLiteral = true;
9936 }
9937 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9938 AuthoritativeFormatString, Type,
9939 IsObjC, true, RefArgs) &&
9940 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9941 DiagAtStringLiteral, FmtArgs)) {
9942 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9943 TestedFormatString, FmtArgs, Arg,
9944 DiagAtStringLiteral);
9945 }
9946 return false;
9947}
9948
9950 const StringLiteral *Str) {
9955 return true;
9956
9957 FormatStringLiteral RefLit = Str;
9959 bool IsObjC =
9961 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9962 true, Args))
9963 return false;
9964
9965 // Group arguments by getPosition() value, and check that each member of the
9966 // group is compatible with the first member. This verifies that when
9967 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9968 // are mutually compatible. As an optimization, don't test the first member
9969 // against itself.
9970 bool HadError = false;
9971 auto Iter = Args.begin();
9972 auto End = Args.end();
9973 while (Iter != End) {
9974 const auto &FirstInGroup = *Iter;
9975 for (++Iter;
9976 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9977 ++Iter) {
9978 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9979 }
9980 }
9981 return !HadError;
9982}
9983
9985 // Str - The format string. NOTE: this is NOT null-terminated!
9986 StringRef StrRef = FExpr->getString();
9987 const char *Str = StrRef.data();
9988 // Account for cases where the string literal is truncated in a declaration.
9989 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9990 assert(T && "String literal not of constant array type!");
9991 size_t TypeSize = T->getZExtSize();
9992 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9994 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
9995}
9996
9997//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9998
9999// Returns the related absolute value function that is larger, of 0 if one
10000// does not exist.
10001static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10002 switch (AbsFunction) {
10003 default:
10004 return 0;
10005
10006 case Builtin::BI__builtin_abs:
10007 return Builtin::BI__builtin_labs;
10008 case Builtin::BI__builtin_labs:
10009 return Builtin::BI__builtin_llabs;
10010 case Builtin::BI__builtin_llabs:
10011 return 0;
10012
10013 case Builtin::BI__builtin_fabsf:
10014 return Builtin::BI__builtin_fabs;
10015 case Builtin::BI__builtin_fabs:
10016 return Builtin::BI__builtin_fabsl;
10017 case Builtin::BI__builtin_fabsl:
10018 return 0;
10019
10020 case Builtin::BI__builtin_cabsf:
10021 return Builtin::BI__builtin_cabs;
10022 case Builtin::BI__builtin_cabs:
10023 return Builtin::BI__builtin_cabsl;
10024 case Builtin::BI__builtin_cabsl:
10025 return 0;
10026
10027 case Builtin::BIabs:
10028 return Builtin::BIlabs;
10029 case Builtin::BIlabs:
10030 return Builtin::BIllabs;
10031 case Builtin::BIllabs:
10032 return 0;
10033
10034 case Builtin::BIfabsf:
10035 return Builtin::BIfabs;
10036 case Builtin::BIfabs:
10037 return Builtin::BIfabsl;
10038 case Builtin::BIfabsl:
10039 return 0;
10040
10041 case Builtin::BIcabsf:
10042 return Builtin::BIcabs;
10043 case Builtin::BIcabs:
10044 return Builtin::BIcabsl;
10045 case Builtin::BIcabsl:
10046 return 0;
10047 }
10048}
10049
10050// Returns the argument type of the absolute value function.
10052 unsigned AbsType) {
10053 if (AbsType == 0)
10054 return QualType();
10055
10057 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10059 return QualType();
10060
10062 if (!FT)
10063 return QualType();
10064
10065 if (FT->getNumParams() != 1)
10066 return QualType();
10067
10068 return FT->getParamType(0);
10069}
10070
10071// Returns the best absolute value function, or zero, based on type and
10072// current absolute value function.
10073static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10074 unsigned AbsFunctionKind) {
10075 unsigned BestKind = 0;
10076 uint64_t ArgSize = Context.getTypeSize(ArgType);
10077 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10078 Kind = getLargerAbsoluteValueFunction(Kind)) {
10079 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10080 if (Context.getTypeSize(ParamType) >= ArgSize) {
10081 if (BestKind == 0)
10082 BestKind = Kind;
10083 else if (Context.hasSameType(ParamType, ArgType)) {
10084 BestKind = Kind;
10085 break;
10086 }
10087 }
10088 }
10089 return BestKind;
10090}
10091
10097
10099 if (T->isIntegralOrEnumerationType())
10100 return AVK_Integer;
10101 if (T->isRealFloatingType())
10102 return AVK_Floating;
10103 if (T->isAnyComplexType())
10104 return AVK_Complex;
10105
10106 llvm_unreachable("Type not integer, floating, or complex");
10107}
10108
10109// Changes the absolute value function to a different type. Preserves whether
10110// the function is a builtin.
10111static unsigned changeAbsFunction(unsigned AbsKind,
10112 AbsoluteValueKind ValueKind) {
10113 switch (ValueKind) {
10114 case AVK_Integer:
10115 switch (AbsKind) {
10116 default:
10117 return 0;
10118 case Builtin::BI__builtin_fabsf:
10119 case Builtin::BI__builtin_fabs:
10120 case Builtin::BI__builtin_fabsl:
10121 case Builtin::BI__builtin_cabsf:
10122 case Builtin::BI__builtin_cabs:
10123 case Builtin::BI__builtin_cabsl:
10124 return Builtin::BI__builtin_abs;
10125 case Builtin::BIfabsf:
10126 case Builtin::BIfabs:
10127 case Builtin::BIfabsl:
10128 case Builtin::BIcabsf:
10129 case Builtin::BIcabs:
10130 case Builtin::BIcabsl:
10131 return Builtin::BIabs;
10132 }
10133 case AVK_Floating:
10134 switch (AbsKind) {
10135 default:
10136 return 0;
10137 case Builtin::BI__builtin_abs:
10138 case Builtin::BI__builtin_labs:
10139 case Builtin::BI__builtin_llabs:
10140 case Builtin::BI__builtin_cabsf:
10141 case Builtin::BI__builtin_cabs:
10142 case Builtin::BI__builtin_cabsl:
10143 return Builtin::BI__builtin_fabsf;
10144 case Builtin::BIabs:
10145 case Builtin::BIlabs:
10146 case Builtin::BIllabs:
10147 case Builtin::BIcabsf:
10148 case Builtin::BIcabs:
10149 case Builtin::BIcabsl:
10150 return Builtin::BIfabsf;
10151 }
10152 case AVK_Complex:
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_fabsf:
10160 case Builtin::BI__builtin_fabs:
10161 case Builtin::BI__builtin_fabsl:
10162 return Builtin::BI__builtin_cabsf;
10163 case Builtin::BIabs:
10164 case Builtin::BIlabs:
10165 case Builtin::BIllabs:
10166 case Builtin::BIfabsf:
10167 case Builtin::BIfabs:
10168 case Builtin::BIfabsl:
10169 return Builtin::BIcabsf;
10170 }
10171 }
10172 llvm_unreachable("Unable to convert function");
10173}
10174
10175static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10176 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10177 if (!FnInfo)
10178 return 0;
10179
10180 switch (FDecl->getBuiltinID()) {
10181 default:
10182 return 0;
10183 case Builtin::BI__builtin_abs:
10184 case Builtin::BI__builtin_fabs:
10185 case Builtin::BI__builtin_fabsf:
10186 case Builtin::BI__builtin_fabsl:
10187 case Builtin::BI__builtin_labs:
10188 case Builtin::BI__builtin_llabs:
10189 case Builtin::BI__builtin_cabs:
10190 case Builtin::BI__builtin_cabsf:
10191 case Builtin::BI__builtin_cabsl:
10192 case Builtin::BIabs:
10193 case Builtin::BIlabs:
10194 case Builtin::BIllabs:
10195 case Builtin::BIfabs:
10196 case Builtin::BIfabsf:
10197 case Builtin::BIfabsl:
10198 case Builtin::BIcabs:
10199 case Builtin::BIcabsf:
10200 case Builtin::BIcabsl:
10201 return FDecl->getBuiltinID();
10202 }
10203 llvm_unreachable("Unknown Builtin type");
10204}
10205
10206// If the replacement is valid, emit a note with replacement function.
10207// Additionally, suggest including the proper header if not already included.
10209 unsigned AbsKind, QualType ArgType) {
10210 bool EmitHeaderHint = true;
10211 const char *HeaderName = nullptr;
10212 std::string FunctionName;
10213 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10214 FunctionName = "std::abs";
10215 if (ArgType->isIntegralOrEnumerationType()) {
10216 HeaderName = "cstdlib";
10217 } else if (ArgType->isRealFloatingType()) {
10218 HeaderName = "cmath";
10219 } else {
10220 llvm_unreachable("Invalid Type");
10221 }
10222
10223 // Lookup all std::abs
10224 if (NamespaceDecl *Std = S.getStdNamespace()) {
10225 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10226 R.suppressDiagnostics();
10227 S.LookupQualifiedName(R, Std);
10228
10229 for (const auto *I : R) {
10230 const FunctionDecl *FDecl = nullptr;
10231 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10232 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10233 } else {
10234 FDecl = dyn_cast<FunctionDecl>(I);
10235 }
10236 if (!FDecl)
10237 continue;
10238
10239 // Found std::abs(), check that they are the right ones.
10240 if (FDecl->getNumParams() != 1)
10241 continue;
10242
10243 // Check that the parameter type can handle the argument.
10244 QualType ParamType = FDecl->getParamDecl(0)->getType();
10245 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10246 S.Context.getTypeSize(ArgType) <=
10247 S.Context.getTypeSize(ParamType)) {
10248 // Found a function, don't need the header hint.
10249 EmitHeaderHint = false;
10250 break;
10251 }
10252 }
10253 }
10254 } else {
10255 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10256 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10257
10258 if (HeaderName) {
10259 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10260 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10261 R.suppressDiagnostics();
10262 S.LookupName(R, S.getCurScope());
10263
10264 if (R.isSingleResult()) {
10265 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10266 if (FD && FD->getBuiltinID() == AbsKind) {
10267 EmitHeaderHint = false;
10268 } else {
10269 return;
10270 }
10271 } else if (!R.empty()) {
10272 return;
10273 }
10274 }
10275 }
10276
10277 S.Diag(Loc, diag::note_replace_abs_function)
10278 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10279
10280 if (!HeaderName)
10281 return;
10282
10283 if (!EmitHeaderHint)
10284 return;
10285
10286 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10287 << FunctionName;
10288}
10289
10290template <std::size_t StrLen>
10291static bool IsStdFunction(const FunctionDecl *FDecl,
10292 const char (&Str)[StrLen]) {
10293 if (!FDecl)
10294 return false;
10295 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10296 return false;
10297 if (!FDecl->isInStdNamespace())
10298 return false;
10299
10300 return true;
10301}
10302
10303enum class MathCheck { NaN, Inf };
10304static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10305 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10306 return llvm::is_contained(names, calleeName);
10307 };
10308
10309 switch (Check) {
10310 case MathCheck::NaN:
10311 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10312 "__builtin_nanf16", "__builtin_nanf128"});
10313 case MathCheck::Inf:
10314 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10315 "__builtin_inff16", "__builtin_inff128"});
10316 }
10317 llvm_unreachable("unknown MathCheck");
10318}
10319
10320static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10321 if (FDecl->getName() != "infinity")
10322 return false;
10323
10324 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10325 const CXXRecordDecl *RDecl = MDecl->getParent();
10326 if (RDecl->getName() != "numeric_limits")
10327 return false;
10328
10329 if (const NamespaceDecl *NSDecl =
10330 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10331 return NSDecl->isStdNamespace();
10332 }
10333
10334 return false;
10335}
10336
10337void Sema::CheckInfNaNFunction(const CallExpr *Call,
10338 const FunctionDecl *FDecl) {
10339 if (!FDecl->getIdentifier())
10340 return;
10341
10342 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10343 if (FPO.getNoHonorNaNs() &&
10344 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10346 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10347 << 1 << 0 << Call->getSourceRange();
10348 return;
10349 }
10350
10351 if (FPO.getNoHonorInfs() &&
10352 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10353 IsInfinityFunction(FDecl) ||
10355 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10356 << 0 << 0 << Call->getSourceRange();
10357 }
10358}
10359
10360void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10361 const FunctionDecl *FDecl) {
10362 if (Call->getNumArgs() != 1)
10363 return;
10364
10365 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10366 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10367 if (AbsKind == 0 && !IsStdAbs)
10368 return;
10369
10370 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10371 QualType ParamType = Call->getArg(0)->getType();
10372
10373 // Unsigned types cannot be negative. Suggest removing the absolute value
10374 // function call.
10375 if (ArgType->isUnsignedIntegerType()) {
10376 std::string FunctionName =
10377 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10378 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10379 Diag(Call->getExprLoc(), diag::note_remove_abs)
10380 << FunctionName
10381 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10382 return;
10383 }
10384
10385 // Taking the absolute value of a pointer is very suspicious, they probably
10386 // wanted to index into an array, dereference a pointer, call a function, etc.
10387 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10388 unsigned DiagType = 0;
10389 if (ArgType->isFunctionType())
10390 DiagType = 1;
10391 else if (ArgType->isArrayType())
10392 DiagType = 2;
10393
10394 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10395 return;
10396 }
10397
10398 // std::abs has overloads which prevent most of the absolute value problems
10399 // from occurring.
10400 if (IsStdAbs)
10401 return;
10402
10403 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10404 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10405
10406 // The argument and parameter are the same kind. Check if they are the right
10407 // size.
10408 if (ArgValueKind == ParamValueKind) {
10409 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10410 return;
10411
10412 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10413 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10414 << FDecl << ArgType << ParamType;
10415
10416 if (NewAbsKind == 0)
10417 return;
10418
10419 emitReplacement(*this, Call->getExprLoc(),
10420 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10421 return;
10422 }
10423
10424 // ArgValueKind != ParamValueKind
10425 // The wrong type of absolute value function was used. Attempt to find the
10426 // proper one.
10427 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10428 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10429 if (NewAbsKind == 0)
10430 return;
10431
10432 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10433 << FDecl << ParamValueKind << ArgValueKind;
10434
10435 emitReplacement(*this, Call->getExprLoc(),
10436 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10437}
10438
10439//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10440void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10441 const FunctionDecl *FDecl) {
10442 if (!Call || !FDecl) return;
10443
10444 // Ignore template specializations and macros.
10445 if (inTemplateInstantiation()) return;
10446 if (Call->getExprLoc().isMacroID()) return;
10447
10448 // Only care about the one template argument, two function parameter std::max
10449 if (Call->getNumArgs() != 2) return;
10450 if (!IsStdFunction(FDecl, "max")) return;
10451 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10452 if (!ArgList) return;
10453 if (ArgList->size() != 1) return;
10454
10455 // Check that template type argument is unsigned integer.
10456 const auto& TA = ArgList->get(0);
10457 if (TA.getKind() != TemplateArgument::Type) return;
10458 QualType ArgType = TA.getAsType();
10459 if (!ArgType->isUnsignedIntegerType()) return;
10460
10461 // See if either argument is a literal zero.
10462 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10463 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10464 if (!MTE) return false;
10465 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10466 if (!Num) return false;
10467 if (Num->getValue() != 0) return false;
10468 return true;
10469 };
10470
10471 const Expr *FirstArg = Call->getArg(0);
10472 const Expr *SecondArg = Call->getArg(1);
10473 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10474 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10475
10476 // Only warn when exactly one argument is zero.
10477 if (IsFirstArgZero == IsSecondArgZero) return;
10478
10479 SourceRange FirstRange = FirstArg->getSourceRange();
10480 SourceRange SecondRange = SecondArg->getSourceRange();
10481
10482 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10483
10484 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10485 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10486
10487 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10488 SourceRange RemovalRange;
10489 if (IsFirstArgZero) {
10490 RemovalRange = SourceRange(FirstRange.getBegin(),
10491 SecondRange.getBegin().getLocWithOffset(-1));
10492 } else {
10493 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10494 SecondRange.getEnd());
10495 }
10496
10497 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10498 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10499 << FixItHint::CreateRemoval(RemovalRange);
10500}
10501
10502//===--- CHECK: Standard memory functions ---------------------------------===//
10503
10504/// Takes the expression passed to the size_t parameter of functions
10505/// such as memcmp, strncat, etc and warns if it's a comparison.
10506///
10507/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10509 const IdentifierInfo *FnName,
10510 SourceLocation FnLoc,
10511 SourceLocation RParenLoc) {
10512 const auto *Size = dyn_cast<BinaryOperator>(E);
10513 if (!Size)
10514 return false;
10515
10516 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10517 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10518 return false;
10519
10520 SourceRange SizeRange = Size->getSourceRange();
10521 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10522 << SizeRange << FnName;
10523 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10524 << FnName
10526 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10527 << FixItHint::CreateRemoval(RParenLoc);
10528 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10529 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10531 ")");
10532
10533 return true;
10534}
10535
10536/// Determine whether the given type is or contains a dynamic class type
10537/// (e.g., whether it has a vtable).
10539 bool &IsContained) {
10540 // Look through array types while ignoring qualifiers.
10541 const Type *Ty = T->getBaseElementTypeUnsafe();
10542 IsContained = false;
10543
10544 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10545 RD = RD ? RD->getDefinition() : nullptr;
10546 if (!RD || RD->isInvalidDecl())
10547 return nullptr;
10548
10549 if (RD->isDynamicClass())
10550 return RD;
10551
10552 // Check all the fields. If any bases were dynamic, the class is dynamic.
10553 // It's impossible for a class to transitively contain itself by value, so
10554 // infinite recursion is impossible.
10555 for (auto *FD : RD->fields()) {
10556 bool SubContained;
10557 if (const CXXRecordDecl *ContainedRD =
10558 getContainedDynamicClass(FD->getType(), SubContained)) {
10559 IsContained = true;
10560 return ContainedRD;
10561 }
10562 }
10563
10564 return nullptr;
10565}
10566
10568 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10569 if (Unary->getKind() == UETT_SizeOf)
10570 return Unary;
10571 return nullptr;
10572}
10573
10574/// If E is a sizeof expression, returns its argument expression,
10575/// otherwise returns NULL.
10576static const Expr *getSizeOfExprArg(const Expr *E) {
10578 if (!SizeOf->isArgumentType())
10579 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10580 return nullptr;
10581}
10582
10583/// If E is a sizeof expression, returns its argument type.
10586 return SizeOf->getTypeOfArgument();
10587 return QualType();
10588}
10589
10590namespace {
10591
10592struct SearchNonTrivialToInitializeField
10593 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10594 using Super =
10595 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10596
10597 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10598
10599 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10600 SourceLocation SL) {
10601 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10602 asDerived().visitArray(PDIK, AT, SL);
10603 return;
10604 }
10605
10606 Super::visitWithKind(PDIK, FT, SL);
10607 }
10608
10609 void visitARCStrong(QualType FT, SourceLocation SL) {
10610 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10611 }
10612 void visitARCWeak(QualType FT, SourceLocation SL) {
10613 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10614 }
10615 void visitStruct(QualType FT, SourceLocation SL) {
10616 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10617 visit(FD->getType(), FD->getLocation());
10618 }
10619 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10620 const ArrayType *AT, SourceLocation SL) {
10621 visit(getContext().getBaseElementType(AT), SL);
10622 }
10623 void visitTrivial(QualType FT, SourceLocation SL) {}
10624
10625 static void diag(QualType RT, const Expr *E, Sema &S) {
10626 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10627 }
10628
10629 ASTContext &getContext() { return S.getASTContext(); }
10630
10631 const Expr *E;
10632 Sema &S;
10633};
10634
10635struct SearchNonTrivialToCopyField
10636 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10637 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10638
10639 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10640
10641 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10642 SourceLocation SL) {
10643 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10644 asDerived().visitArray(PCK, AT, SL);
10645 return;
10646 }
10647
10648 Super::visitWithKind(PCK, FT, SL);
10649 }
10650
10651 void visitARCStrong(QualType FT, SourceLocation SL) {
10652 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10653 }
10654 void visitARCWeak(QualType FT, SourceLocation SL) {
10655 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10656 }
10657 void visitPtrAuth(QualType FT, SourceLocation SL) {
10658 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10659 }
10660 void visitStruct(QualType FT, SourceLocation SL) {
10661 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10662 visit(FD->getType(), FD->getLocation());
10663 }
10664 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10665 SourceLocation SL) {
10666 visit(getContext().getBaseElementType(AT), SL);
10667 }
10668 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10669 SourceLocation SL) {}
10670 void visitTrivial(QualType FT, SourceLocation SL) {}
10671 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10672
10673 static void diag(QualType RT, const Expr *E, Sema &S) {
10674 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10675 }
10676
10677 ASTContext &getContext() { return S.getASTContext(); }
10678
10679 const Expr *E;
10680 Sema &S;
10681};
10682
10683}
10684
10685/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10686static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10687 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10688
10689 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10690 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10691 return false;
10692
10693 return doesExprLikelyComputeSize(BO->getLHS()) ||
10694 doesExprLikelyComputeSize(BO->getRHS());
10695 }
10696
10697 return getAsSizeOfExpr(SizeofExpr) != nullptr;
10698}
10699
10700/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10701///
10702/// \code
10703/// #define MACRO 0
10704/// foo(MACRO);
10705/// foo(0);
10706/// \endcode
10707///
10708/// This should return true for the first call to foo, but not for the second
10709/// (regardless of whether foo is a macro or function).
10711 SourceLocation CallLoc,
10712 SourceLocation ArgLoc) {
10713 if (!CallLoc.isMacroID())
10714 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10715
10716 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10717 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10718}
10719
10720/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10721/// last two arguments transposed.
10722static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10723 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10724 return;
10725
10726 const Expr *SizeArg =
10727 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10728
10729 auto isLiteralZero = [](const Expr *E) {
10730 return (isa<IntegerLiteral>(E) &&
10731 cast<IntegerLiteral>(E)->getValue() == 0) ||
10733 cast<CharacterLiteral>(E)->getValue() == 0);
10734 };
10735
10736 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10737 SourceLocation CallLoc = Call->getRParenLoc();
10739 if (isLiteralZero(SizeArg) &&
10740 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10741
10742 SourceLocation DiagLoc = SizeArg->getExprLoc();
10743
10744 // Some platforms #define bzero to __builtin_memset. See if this is the
10745 // case, and if so, emit a better diagnostic.
10746 if (BId == Builtin::BIbzero ||
10748 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10749 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10750 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10751 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10752 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10753 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10754 }
10755 return;
10756 }
10757
10758 // If the second argument to a memset is a sizeof expression and the third
10759 // isn't, this is also likely an error. This should catch
10760 // 'memset(buf, sizeof(buf), 0xff)'.
10761 if (BId == Builtin::BImemset &&
10762 doesExprLikelyComputeSize(Call->getArg(1)) &&
10763 !doesExprLikelyComputeSize(Call->getArg(2))) {
10764 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10765 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10766 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10767 return;
10768 }
10769}
10770
10771void Sema::CheckMemaccessArguments(const CallExpr *Call,
10772 unsigned BId,
10773 IdentifierInfo *FnName) {
10774 assert(BId != 0);
10775
10776 // It is possible to have a non-standard definition of memset. Validate
10777 // we have enough arguments, and if not, abort further checking.
10778 unsigned ExpectedNumArgs =
10779 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10780 if (Call->getNumArgs() < ExpectedNumArgs)
10781 return;
10782
10783 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10784 BId == Builtin::BIstrndup ? 1 : 2);
10785 unsigned LenArg =
10786 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10787 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10788
10789 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10790 Call->getBeginLoc(), Call->getRParenLoc()))
10791 return;
10792
10793 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10794 CheckMemaccessSize(*this, BId, Call);
10795
10796 // We have special checking when the length is a sizeof expression.
10797 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10798
10799 // Although widely used, 'bzero' is not a standard function. Be more strict
10800 // with the argument types before allowing diagnostics and only allow the
10801 // form bzero(ptr, sizeof(...)).
10802 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10803 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10804 return;
10805
10806 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10807 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10808 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10809
10810 QualType DestTy = Dest->getType();
10811 QualType PointeeTy;
10812 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10813 PointeeTy = DestPtrTy->getPointeeType();
10814
10815 // Never warn about void type pointers. This can be used to suppress
10816 // false positives.
10817 if (PointeeTy->isVoidType())
10818 continue;
10819
10820 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10821 // actually comparing the expressions for equality. Because computing the
10822 // expression IDs can be expensive, we only do this if the diagnostic is
10823 // enabled.
10824 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
10825 break;
10826
10827 // Also check for cases where the sizeof argument is the exact same
10828 // type as the memory argument, and where it points to a user-defined
10829 // record type.
10830 if (SizeOfArgTy != QualType()) {
10831 if (PointeeTy->isRecordType() &&
10832 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10833 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10834 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10835 << FnName << SizeOfArgTy << ArgIdx
10836 << PointeeTy << Dest->getSourceRange()
10837 << LenExpr->getSourceRange());
10838 break;
10839 }
10840 }
10841 } else if (DestTy->isArrayType()) {
10842 PointeeTy = DestTy;
10843 }
10844
10845 if (PointeeTy == QualType())
10846 continue;
10847
10848 // Always complain about dynamic classes.
10849 bool IsContained;
10850 if (const CXXRecordDecl *ContainedRD =
10851 getContainedDynamicClass(PointeeTy, IsContained)) {
10852
10853 unsigned OperationType = 0;
10854 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10855 // "overwritten" if we're warning about the destination for any call
10856 // but memcmp; otherwise a verb appropriate to the call.
10857 if (ArgIdx != 0 || IsCmp) {
10858 if (BId == Builtin::BImemcpy)
10859 OperationType = 1;
10860 else if(BId == Builtin::BImemmove)
10861 OperationType = 2;
10862 else if (IsCmp)
10863 OperationType = 3;
10864 }
10865
10866 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10867 PDiag(diag::warn_dyn_class_memaccess)
10868 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10869 << IsContained << ContainedRD << OperationType
10870 << Call->getCallee()->getSourceRange());
10871 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10872 BId != Builtin::BImemset)
10874 Dest->getExprLoc(), Dest,
10875 PDiag(diag::warn_arc_object_memaccess)
10876 << ArgIdx << FnName << PointeeTy
10877 << Call->getCallee()->getSourceRange());
10878 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10879
10880 // FIXME: Do not consider incomplete types even though they may be
10881 // completed later. GCC does not diagnose such code, but we may want to
10882 // consider diagnosing it in the future, perhaps under a different, but
10883 // related, diagnostic group.
10884 bool NonTriviallyCopyableCXXRecord =
10885 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10886 !PointeeTy.isTriviallyCopyableType(Context);
10887
10888 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10890 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10891 PDiag(diag::warn_cstruct_memaccess)
10892 << ArgIdx << FnName << PointeeTy << 0);
10893 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10894 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10895 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10896 // FIXME: Limiting this warning to dest argument until we decide
10897 // whether it's valid for source argument too.
10898 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10899 PDiag(diag::warn_cxxstruct_memaccess)
10900 << FnName << PointeeTy);
10901 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10903 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10904 PDiag(diag::warn_cstruct_memaccess)
10905 << ArgIdx << FnName << PointeeTy << 1);
10906 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10907 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10908 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10909 // FIXME: Limiting this warning to dest argument until we decide
10910 // whether it's valid for source argument too.
10911 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10912 PDiag(diag::warn_cxxstruct_memaccess)
10913 << FnName << PointeeTy);
10914 } else {
10915 continue;
10916 }
10917 } else
10918 continue;
10919
10921 Dest->getExprLoc(), Dest,
10922 PDiag(diag::note_bad_memaccess_silence)
10923 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10924 break;
10925 }
10926}
10927
10928bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10929 IdentifierInfo *FnName) {
10930 llvm::FoldingSetNodeID SizeOfArgID;
10931 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10932 if (!SizeOfArg)
10933 return false;
10934 // Computing this warning is expensive, so we only do so if the warning is
10935 // enabled.
10936 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10937 SizeOfArg->getExprLoc()))
10938 return false;
10939 QualType DestTy = Dest->getType();
10940 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10941 if (!DestPtrTy)
10942 return false;
10943
10944 QualType PointeeTy = DestPtrTy->getPointeeType();
10945
10946 if (SizeOfArgID == llvm::FoldingSetNodeID())
10947 SizeOfArg->Profile(SizeOfArgID, Context, true);
10948
10949 llvm::FoldingSetNodeID DestID;
10950 Dest->Profile(DestID, Context, true);
10951 if (DestID == SizeOfArgID) {
10952 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10953 // over sizeof(src) as well.
10954 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10955 StringRef ReadableName = FnName->getName();
10956
10957 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
10958 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
10959 ActionIdx = 1; // If its an address-of operator, just remove it.
10960 if (!PointeeTy->isIncompleteType() &&
10961 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10962 ActionIdx = 2; // If the pointee's size is sizeof(char),
10963 // suggest an explicit length.
10964
10965 // If the function is defined as a builtin macro, do not show macro
10966 // expansion.
10967 SourceLocation SL = SizeOfArg->getExprLoc();
10968 SourceRange DSR = Dest->getSourceRange();
10969 SourceRange SSR = SizeOfArg->getSourceRange();
10970 SourceManager &SM = getSourceManager();
10971
10972 if (SM.isMacroArgExpansion(SL)) {
10973 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10974 SL = SM.getSpellingLoc(SL);
10975 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10976 SM.getSpellingLoc(DSR.getEnd()));
10977 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10978 SM.getSpellingLoc(SSR.getEnd()));
10979 }
10980
10981 DiagRuntimeBehavior(SL, SizeOfArg,
10982 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10983 << ReadableName << PointeeTy << DestTy << DSR
10984 << SSR);
10985 DiagRuntimeBehavior(SL, SizeOfArg,
10986 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10987 << ActionIdx << SSR);
10988 return true;
10989 }
10990 return false;
10991}
10992
10993// A little helper routine: ignore addition and subtraction of integer literals.
10994// This intentionally does not ignore all integer constant expressions because
10995// we don't want to remove sizeof().
10996static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10997 Ex = Ex->IgnoreParenCasts();
10998
10999 while (true) {
11000 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11001 if (!BO || !BO->isAdditiveOp())
11002 break;
11003
11004 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11005 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11006
11007 if (isa<IntegerLiteral>(RHS))
11008 Ex = LHS;
11009 else if (isa<IntegerLiteral>(LHS))
11010 Ex = RHS;
11011 else
11012 break;
11013 }
11014
11015 return Ex;
11016}
11017
11019 ASTContext &Context) {
11020 // Only handle constant-sized or VLAs, but not flexible members.
11021 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11022 // Only issue the FIXIT for arrays of size > 1.
11023 if (CAT->getZExtSize() <= 1)
11024 return false;
11025 } else if (!Ty->isVariableArrayType()) {
11026 return false;
11027 }
11028 return true;
11029}
11030
11031void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11032 IdentifierInfo *FnName) {
11033
11034 // Don't crash if the user has the wrong number of arguments
11035 unsigned NumArgs = Call->getNumArgs();
11036 if ((NumArgs != 3) && (NumArgs != 4))
11037 return;
11038
11039 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11040 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11041 const Expr *CompareWithSrc = nullptr;
11042
11043 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11044 Call->getBeginLoc(), Call->getRParenLoc()))
11045 return;
11046
11047 // Look for 'strlcpy(dst, x, sizeof(x))'
11048 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11049 CompareWithSrc = Ex;
11050 else {
11051 // Look for 'strlcpy(dst, x, strlen(x))'
11052 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11053 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11054 SizeCall->getNumArgs() == 1)
11055 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11056 }
11057 }
11058
11059 if (!CompareWithSrc)
11060 return;
11061
11062 // Determine if the argument to sizeof/strlen is equal to the source
11063 // argument. In principle there's all kinds of things you could do
11064 // here, for instance creating an == expression and evaluating it with
11065 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11066 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11067 if (!SrcArgDRE)
11068 return;
11069
11070 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11071 if (!CompareWithSrcDRE ||
11072 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11073 return;
11074
11075 const Expr *OriginalSizeArg = Call->getArg(2);
11076 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11077 << OriginalSizeArg->getSourceRange() << FnName;
11078
11079 // Output a FIXIT hint if the destination is an array (rather than a
11080 // pointer to an array). This could be enhanced to handle some
11081 // pointers if we know the actual size, like if DstArg is 'array+2'
11082 // we could say 'sizeof(array)-2'.
11083 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11085 return;
11086
11087 SmallString<128> sizeString;
11088 llvm::raw_svector_ostream OS(sizeString);
11089 OS << "sizeof(";
11090 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11091 OS << ")";
11092
11093 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11094 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11095 OS.str());
11096}
11097
11098/// Check if two expressions refer to the same declaration.
11099static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11100 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11101 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11102 return D1->getDecl() == D2->getDecl();
11103 return false;
11104}
11105
11106static const Expr *getStrlenExprArg(const Expr *E) {
11107 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11108 const FunctionDecl *FD = CE->getDirectCallee();
11109 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11110 return nullptr;
11111 return CE->getArg(0)->IgnoreParenCasts();
11112 }
11113 return nullptr;
11114}
11115
11116void Sema::CheckStrncatArguments(const CallExpr *CE,
11117 const IdentifierInfo *FnName) {
11118 // Don't crash if the user has the wrong number of arguments.
11119 if (CE->getNumArgs() < 3)
11120 return;
11121 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11122 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11123 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11124
11125 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11126 CE->getRParenLoc()))
11127 return;
11128
11129 // Identify common expressions, which are wrongly used as the size argument
11130 // to strncat and may lead to buffer overflows.
11131 unsigned PatternType = 0;
11132 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11133 // - sizeof(dst)
11134 if (referToTheSameDecl(SizeOfArg, DstArg))
11135 PatternType = 1;
11136 // - sizeof(src)
11137 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11138 PatternType = 2;
11139 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11140 if (BE->getOpcode() == BO_Sub) {
11141 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11142 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11143 // - sizeof(dst) - strlen(dst)
11144 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11146 PatternType = 1;
11147 // - sizeof(src) - (anything)
11148 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11149 PatternType = 2;
11150 }
11151 }
11152
11153 if (PatternType == 0)
11154 return;
11155
11156 // Generate the diagnostic.
11157 SourceLocation SL = LenArg->getBeginLoc();
11158 SourceRange SR = LenArg->getSourceRange();
11159 SourceManager &SM = getSourceManager();
11160
11161 // If the function is defined as a builtin macro, do not show macro expansion.
11162 if (SM.isMacroArgExpansion(SL)) {
11163 SL = SM.getSpellingLoc(SL);
11164 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11165 SM.getSpellingLoc(SR.getEnd()));
11166 }
11167
11168 // Check if the destination is an array (rather than a pointer to an array).
11169 QualType DstTy = DstArg->getType();
11170 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11171 Context);
11172 if (!isKnownSizeArray) {
11173 if (PatternType == 1)
11174 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11175 else
11176 Diag(SL, diag::warn_strncat_src_size) << SR;
11177 return;
11178 }
11179
11180 if (PatternType == 1)
11181 Diag(SL, diag::warn_strncat_large_size) << SR;
11182 else
11183 Diag(SL, diag::warn_strncat_src_size) << SR;
11184
11185 SmallString<128> sizeString;
11186 llvm::raw_svector_ostream OS(sizeString);
11187 OS << "sizeof(";
11188 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11189 OS << ") - ";
11190 OS << "strlen(";
11191 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11192 OS << ") - 1";
11193
11194 Diag(SL, diag::note_strncat_wrong_size)
11195 << FixItHint::CreateReplacement(SR, OS.str());
11196}
11197
11198namespace {
11199void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11200 const UnaryOperator *UnaryExpr, const Decl *D) {
11202 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11203 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11204 return;
11205 }
11206}
11207
11208void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11209 const UnaryOperator *UnaryExpr) {
11210 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11211 const Decl *D = Lvalue->getDecl();
11212 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11213 if (!DD->getType()->isReferenceType())
11214 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11215 }
11216 }
11217
11218 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11219 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11220 Lvalue->getMemberDecl());
11221}
11222
11223void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11224 const UnaryOperator *UnaryExpr) {
11225 const auto *Lambda = dyn_cast<LambdaExpr>(
11227 if (!Lambda)
11228 return;
11229
11230 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11231 << CalleeName << 2 /*object: lambda expression*/;
11232}
11233
11234void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11235 const DeclRefExpr *Lvalue) {
11236 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11237 if (Var == nullptr)
11238 return;
11239
11240 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11241 << CalleeName << 0 /*object: */ << Var;
11242}
11243
11244void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11245 const CastExpr *Cast) {
11246 SmallString<128> SizeString;
11247 llvm::raw_svector_ostream OS(SizeString);
11248
11249 clang::CastKind Kind = Cast->getCastKind();
11250 if (Kind == clang::CK_BitCast &&
11251 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11252 return;
11253 if (Kind == clang::CK_IntegralToPointer &&
11255 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11256 return;
11257
11258 switch (Cast->getCastKind()) {
11259 case clang::CK_BitCast:
11260 case clang::CK_IntegralToPointer:
11261 case clang::CK_FunctionToPointerDecay:
11262 OS << '\'';
11263 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11264 OS << '\'';
11265 break;
11266 default:
11267 return;
11268 }
11269
11270 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11271 << CalleeName << 0 /*object: */ << OS.str();
11272}
11273} // namespace
11274
11275void Sema::CheckFreeArguments(const CallExpr *E) {
11276 const std::string CalleeName =
11277 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11278
11279 { // Prefer something that doesn't involve a cast to make things simpler.
11280 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11281 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11282 switch (UnaryExpr->getOpcode()) {
11283 case UnaryOperator::Opcode::UO_AddrOf:
11284 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11285 case UnaryOperator::Opcode::UO_Plus:
11286 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11287 default:
11288 break;
11289 }
11290
11291 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11292 if (Lvalue->getType()->isArrayType())
11293 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11294
11295 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11296 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11297 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11298 return;
11299 }
11300
11301 if (isa<BlockExpr>(Arg)) {
11302 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11303 << CalleeName << 1 /*object: block*/;
11304 return;
11305 }
11306 }
11307 // Maybe the cast was important, check after the other cases.
11308 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11309 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11310}
11311
11312void
11313Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11314 SourceLocation ReturnLoc,
11315 bool isObjCMethod,
11316 const AttrVec *Attrs,
11317 const FunctionDecl *FD) {
11318 // Check if the return value is null but should not be.
11319 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11320 (!isObjCMethod && isNonNullType(lhsType))) &&
11321 CheckNonNullExpr(*this, RetValExp))
11322 Diag(ReturnLoc, diag::warn_null_ret)
11323 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11324
11325 // C++11 [basic.stc.dynamic.allocation]p4:
11326 // If an allocation function declared with a non-throwing
11327 // exception-specification fails to allocate storage, it shall return
11328 // a null pointer. Any other allocation function that fails to allocate
11329 // storage shall indicate failure only by throwing an exception [...]
11330 if (FD) {
11332 if (Op == OO_New || Op == OO_Array_New) {
11333 const FunctionProtoType *Proto
11334 = FD->getType()->castAs<FunctionProtoType>();
11335 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11336 CheckNonNullExpr(*this, RetValExp))
11337 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11338 << FD << getLangOpts().CPlusPlus11;
11339 }
11340 }
11341
11342 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11343 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11344 }
11345
11346 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11347 // here prevent the user from using a PPC MMA type as trailing return type.
11348 if (Context.getTargetInfo().getTriple().isPPC64())
11349 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11350}
11351
11353 const Expr *RHS, BinaryOperatorKind Opcode) {
11354 if (!BinaryOperator::isEqualityOp(Opcode))
11355 return;
11356
11357 // Match and capture subexpressions such as "(float) X == 0.1".
11358 const FloatingLiteral *FPLiteral;
11359 const CastExpr *FPCast;
11360 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11361 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11362 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11363 return FPLiteral && FPCast;
11364 };
11365
11366 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11367 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11368 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11369 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11370 TargetTy->isFloatingPoint()) {
11371 bool Lossy;
11372 llvm::APFloat TargetC = FPLiteral->getValue();
11373 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11374 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11375 if (Lossy) {
11376 // If the literal cannot be represented in the source type, then a
11377 // check for == is always false and check for != is always true.
11378 Diag(Loc, diag::warn_float_compare_literal)
11379 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11380 << LHS->getSourceRange() << RHS->getSourceRange();
11381 return;
11382 }
11383 }
11384 }
11385
11386 // Match a more general floating-point equality comparison (-Wfloat-equal).
11387 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11388 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11389
11390 // Special case: check for x == x (which is OK).
11391 // Do not emit warnings for such cases.
11392 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11393 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11394 if (DRL->getDecl() == DRR->getDecl())
11395 return;
11396
11397 // Special case: check for comparisons against literals that can be exactly
11398 // represented by APFloat. In such cases, do not emit a warning. This
11399 // is a heuristic: often comparison against such literals are used to
11400 // detect if a value in a variable has not changed. This clearly can
11401 // lead to false negatives.
11402 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11403 if (FLL->isExact())
11404 return;
11405 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11406 if (FLR->isExact())
11407 return;
11408
11409 // Check for comparisons with builtin types.
11410 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11411 CL && CL->getBuiltinCallee())
11412 return;
11413
11414 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11415 CR && CR->getBuiltinCallee())
11416 return;
11417
11418 // Emit the diagnostic.
11419 Diag(Loc, diag::warn_floatingpoint_eq)
11420 << LHS->getSourceRange() << RHS->getSourceRange();
11421}
11422
11423//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11424//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11425
11426namespace {
11427
11428/// Structure recording the 'active' range of an integer-valued
11429/// expression.
11430struct IntRange {
11431 /// The number of bits active in the int. Note that this includes exactly one
11432 /// sign bit if !NonNegative.
11433 unsigned Width;
11434
11435 /// True if the int is known not to have negative values. If so, all leading
11436 /// bits before Width are known zero, otherwise they are known to be the
11437 /// same as the MSB within Width.
11438 bool NonNegative;
11439
11440 IntRange(unsigned Width, bool NonNegative)
11441 : Width(Width), NonNegative(NonNegative) {}
11442
11443 /// Number of bits excluding the sign bit.
11444 unsigned valueBits() const {
11445 return NonNegative ? Width : Width - 1;
11446 }
11447
11448 /// Returns the range of the bool type.
11449 static IntRange forBoolType() {
11450 return IntRange(1, true);
11451 }
11452
11453 /// Returns the range of an opaque value of the given integral type.
11454 static IntRange forValueOfType(ASTContext &C, QualType T) {
11455 return forValueOfCanonicalType(C,
11457 }
11458
11459 /// Returns the range of an opaque value of a canonical integral type.
11460 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11461 assert(T->isCanonicalUnqualified());
11462
11463 if (const auto *VT = dyn_cast<VectorType>(T))
11464 T = VT->getElementType().getTypePtr();
11465 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11466 T = MT->getElementType().getTypePtr();
11467 if (const auto *CT = dyn_cast<ComplexType>(T))
11468 T = CT->getElementType().getTypePtr();
11469 if (const auto *AT = dyn_cast<AtomicType>(T))
11470 T = AT->getValueType().getTypePtr();
11471 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11472 T = OBT->getUnderlyingType().getTypePtr();
11473
11474 if (!C.getLangOpts().CPlusPlus) {
11475 // For enum types in C code, use the underlying datatype.
11476 if (const auto *ED = T->getAsEnumDecl())
11477 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11478 } else if (auto *Enum = T->getAsEnumDecl()) {
11479 // For enum types in C++, use the known bit width of the enumerators.
11480 // In C++11, enums can have a fixed underlying type. Use this type to
11481 // compute the range.
11482 if (Enum->isFixed()) {
11483 return IntRange(C.getIntWidth(QualType(T, 0)),
11484 !Enum->getIntegerType()->isSignedIntegerType());
11485 }
11486
11487 unsigned NumPositive = Enum->getNumPositiveBits();
11488 unsigned NumNegative = Enum->getNumNegativeBits();
11489
11490 if (NumNegative == 0)
11491 return IntRange(NumPositive, true/*NonNegative*/);
11492 else
11493 return IntRange(std::max(NumPositive + 1, NumNegative),
11494 false/*NonNegative*/);
11495 }
11496
11497 if (const auto *EIT = dyn_cast<BitIntType>(T))
11498 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11499
11500 const BuiltinType *BT = cast<BuiltinType>(T);
11501 assert(BT->isInteger());
11502
11503 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11504 }
11505
11506 /// Returns the "target" range of a canonical integral type, i.e.
11507 /// the range of values expressible in the type.
11508 ///
11509 /// This matches forValueOfCanonicalType except that enums have the
11510 /// full range of their type, not the range of their enumerators.
11511 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11512 assert(T->isCanonicalUnqualified());
11513
11514 if (const VectorType *VT = dyn_cast<VectorType>(T))
11515 T = VT->getElementType().getTypePtr();
11516 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11517 T = MT->getElementType().getTypePtr();
11518 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11519 T = CT->getElementType().getTypePtr();
11520 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11521 T = AT->getValueType().getTypePtr();
11522 if (const auto *ED = T->getAsEnumDecl())
11523 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11524 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11525 T = OBT->getUnderlyingType().getTypePtr();
11526
11527 if (const auto *EIT = dyn_cast<BitIntType>(T))
11528 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11529
11530 const BuiltinType *BT = cast<BuiltinType>(T);
11531 assert(BT->isInteger());
11532
11533 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11534 }
11535
11536 /// Returns the supremum of two ranges: i.e. their conservative merge.
11537 static IntRange join(IntRange L, IntRange R) {
11538 bool Unsigned = L.NonNegative && R.NonNegative;
11539 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11540 L.NonNegative && R.NonNegative);
11541 }
11542
11543 /// Return the range of a bitwise-AND of the two ranges.
11544 static IntRange bit_and(IntRange L, IntRange R) {
11545 unsigned Bits = std::max(L.Width, R.Width);
11546 bool NonNegative = false;
11547 if (L.NonNegative) {
11548 Bits = std::min(Bits, L.Width);
11549 NonNegative = true;
11550 }
11551 if (R.NonNegative) {
11552 Bits = std::min(Bits, R.Width);
11553 NonNegative = true;
11554 }
11555 return IntRange(Bits, NonNegative);
11556 }
11557
11558 /// Return the range of a sum of the two ranges.
11559 static IntRange sum(IntRange L, IntRange R) {
11560 bool Unsigned = L.NonNegative && R.NonNegative;
11561 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11562 Unsigned);
11563 }
11564
11565 /// Return the range of a difference of the two ranges.
11566 static IntRange difference(IntRange L, IntRange R) {
11567 // We need a 1-bit-wider range if:
11568 // 1) LHS can be negative: least value can be reduced.
11569 // 2) RHS can be negative: greatest value can be increased.
11570 bool CanWiden = !L.NonNegative || !R.NonNegative;
11571 bool Unsigned = L.NonNegative && R.Width == 0;
11572 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11573 !Unsigned,
11574 Unsigned);
11575 }
11576
11577 /// Return the range of a product of the two ranges.
11578 static IntRange product(IntRange L, IntRange R) {
11579 // If both LHS and RHS can be negative, we can form
11580 // -2^L * -2^R = 2^(L + R)
11581 // which requires L + R + 1 value bits to represent.
11582 bool CanWiden = !L.NonNegative && !R.NonNegative;
11583 bool Unsigned = L.NonNegative && R.NonNegative;
11584 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11585 Unsigned);
11586 }
11587
11588 /// Return the range of a remainder operation between the two ranges.
11589 static IntRange rem(IntRange L, IntRange R) {
11590 // The result of a remainder can't be larger than the result of
11591 // either side. The sign of the result is the sign of the LHS.
11592 bool Unsigned = L.NonNegative;
11593 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11594 Unsigned);
11595 }
11596};
11597
11598} // namespace
11599
11600static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11601 if (value.isSigned() && value.isNegative())
11602 return IntRange(value.getSignificantBits(), false);
11603
11604 if (value.getBitWidth() > MaxWidth)
11605 value = value.trunc(MaxWidth);
11606
11607 // isNonNegative() just checks the sign bit without considering
11608 // signedness.
11609 return IntRange(value.getActiveBits(), true);
11610}
11611
11612static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11613 if (result.isInt())
11614 return GetValueRange(result.getInt(), MaxWidth);
11615
11616 if (result.isVector()) {
11617 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11618 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11619 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11620 R = IntRange::join(R, El);
11621 }
11622 return R;
11623 }
11624
11625 if (result.isComplexInt()) {
11626 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11627 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11628 return IntRange::join(R, I);
11629 }
11630
11631 // This can happen with lossless casts to intptr_t of "based" lvalues.
11632 // Assume it might use arbitrary bits.
11633 // FIXME: The only reason we need to pass the type in here is to get
11634 // the sign right on this one case. It would be nice if APValue
11635 // preserved this.
11636 assert(result.isLValue() || result.isAddrLabelDiff());
11637 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11638}
11639
11640static QualType GetExprType(const Expr *E) {
11641 QualType Ty = E->getType();
11642 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11643 Ty = AtomicRHS->getValueType();
11644 return Ty;
11645}
11646
11647/// Attempts to estimate an approximate range for the given integer expression.
11648/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11649/// reliable estimation cannot be determined.
11650///
11651/// \param MaxWidth The width to which the value will be truncated.
11652/// \param InConstantContext If \c true, interpret the expression within a
11653/// constant context.
11654/// \param Approximate If \c true, provide a likely range of values by assuming
11655/// that arithmetic on narrower types remains within those types.
11656/// If \c false, return a range that includes all possible values
11657/// resulting from the expression.
11658/// \returns A range of values that the expression might take, or
11659/// std::nullopt if a reliable estimation cannot be determined.
11660static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11661 unsigned MaxWidth,
11662 bool InConstantContext,
11663 bool Approximate) {
11664 E = E->IgnoreParens();
11665
11666 // Try a full evaluation first.
11667 Expr::EvalResult result;
11668 if (E->EvaluateAsRValue(result, C, InConstantContext))
11669 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11670
11671 // I think we only want to look through implicit casts here; if the
11672 // user has an explicit widening cast, we should treat the value as
11673 // being of the new, wider type.
11674 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11675 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11676 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11677 Approximate);
11678
11679 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11680
11681 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11682 CE->getCastKind() == CK_BooleanToSignedIntegral;
11683
11684 // Assume that non-integer casts can span the full range of the type.
11685 if (!isIntegerCast)
11686 return OutputTypeRange;
11687
11688 std::optional<IntRange> SubRange = TryGetExprRange(
11689 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11690 InConstantContext, Approximate);
11691 if (!SubRange)
11692 return std::nullopt;
11693
11694 // Bail out if the subexpr's range is as wide as the cast type.
11695 if (SubRange->Width >= OutputTypeRange.Width)
11696 return OutputTypeRange;
11697
11698 // Otherwise, we take the smaller width, and we're non-negative if
11699 // either the output type or the subexpr is.
11700 return IntRange(SubRange->Width,
11701 SubRange->NonNegative || OutputTypeRange.NonNegative);
11702 }
11703
11704 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11705 // If we can fold the condition, just take that operand.
11706 bool CondResult;
11707 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11708 return TryGetExprRange(
11709 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11710 InConstantContext, Approximate);
11711
11712 // Otherwise, conservatively merge.
11713 // TryGetExprRange requires an integer expression, but a throw expression
11714 // results in a void type.
11715 Expr *TrueExpr = CO->getTrueExpr();
11716 if (TrueExpr->getType()->isVoidType())
11717 return std::nullopt;
11718
11719 std::optional<IntRange> L =
11720 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11721 if (!L)
11722 return std::nullopt;
11723
11724 Expr *FalseExpr = CO->getFalseExpr();
11725 if (FalseExpr->getType()->isVoidType())
11726 return std::nullopt;
11727
11728 std::optional<IntRange> R =
11729 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11730 if (!R)
11731 return std::nullopt;
11732
11733 return IntRange::join(*L, *R);
11734 }
11735
11736 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11737 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11738
11739 switch (BO->getOpcode()) {
11740 case BO_Cmp:
11741 llvm_unreachable("builtin <=> should have class type");
11742
11743 // Boolean-valued operations are single-bit and positive.
11744 case BO_LAnd:
11745 case BO_LOr:
11746 case BO_LT:
11747 case BO_GT:
11748 case BO_LE:
11749 case BO_GE:
11750 case BO_EQ:
11751 case BO_NE:
11752 return IntRange::forBoolType();
11753
11754 // The type of the assignments is the type of the LHS, so the RHS
11755 // is not necessarily the same type.
11756 case BO_MulAssign:
11757 case BO_DivAssign:
11758 case BO_RemAssign:
11759 case BO_AddAssign:
11760 case BO_SubAssign:
11761 case BO_XorAssign:
11762 case BO_OrAssign:
11763 // TODO: bitfields?
11764 return IntRange::forValueOfType(C, GetExprType(E));
11765
11766 // Simple assignments just pass through the RHS, which will have
11767 // been coerced to the LHS type.
11768 case BO_Assign:
11769 // TODO: bitfields?
11770 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11771 Approximate);
11772
11773 // Operations with opaque sources are black-listed.
11774 case BO_PtrMemD:
11775 case BO_PtrMemI:
11776 return IntRange::forValueOfType(C, GetExprType(E));
11777
11778 // Bitwise-and uses the *infinum* of the two source ranges.
11779 case BO_And:
11780 case BO_AndAssign:
11781 Combine = IntRange::bit_and;
11782 break;
11783
11784 // Left shift gets black-listed based on a judgement call.
11785 case BO_Shl:
11786 // ...except that we want to treat '1 << (blah)' as logically
11787 // positive. It's an important idiom.
11788 if (IntegerLiteral *I
11789 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11790 if (I->getValue() == 1) {
11791 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11792 return IntRange(R.Width, /*NonNegative*/ true);
11793 }
11794 }
11795 [[fallthrough]];
11796
11797 case BO_ShlAssign:
11798 return IntRange::forValueOfType(C, GetExprType(E));
11799
11800 // Right shift by a constant can narrow its left argument.
11801 case BO_Shr:
11802 case BO_ShrAssign: {
11803 std::optional<IntRange> L = TryGetExprRange(
11804 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11805 if (!L)
11806 return std::nullopt;
11807
11808 // If the shift amount is a positive constant, drop the width by
11809 // that much.
11810 if (std::optional<llvm::APSInt> shift =
11811 BO->getRHS()->getIntegerConstantExpr(C)) {
11812 if (shift->isNonNegative()) {
11813 if (shift->uge(L->Width))
11814 L->Width = (L->NonNegative ? 0 : 1);
11815 else
11816 L->Width -= shift->getZExtValue();
11817 }
11818 }
11819
11820 return L;
11821 }
11822
11823 // Comma acts as its right operand.
11824 case BO_Comma:
11825 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11826 Approximate);
11827
11828 case BO_Add:
11829 if (!Approximate)
11830 Combine = IntRange::sum;
11831 break;
11832
11833 case BO_Sub:
11834 if (BO->getLHS()->getType()->isPointerType())
11835 return IntRange::forValueOfType(C, GetExprType(E));
11836 if (!Approximate)
11837 Combine = IntRange::difference;
11838 break;
11839
11840 case BO_Mul:
11841 if (!Approximate)
11842 Combine = IntRange::product;
11843 break;
11844
11845 // The width of a division result is mostly determined by the size
11846 // of the LHS.
11847 case BO_Div: {
11848 // Don't 'pre-truncate' the operands.
11849 unsigned opWidth = C.getIntWidth(GetExprType(E));
11850 std::optional<IntRange> L = TryGetExprRange(
11851 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11852 if (!L)
11853 return std::nullopt;
11854
11855 // If the divisor is constant, use that.
11856 if (std::optional<llvm::APSInt> divisor =
11857 BO->getRHS()->getIntegerConstantExpr(C)) {
11858 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11859 if (log2 >= L->Width)
11860 L->Width = (L->NonNegative ? 0 : 1);
11861 else
11862 L->Width = std::min(L->Width - log2, MaxWidth);
11863 return L;
11864 }
11865
11866 // Otherwise, just use the LHS's width.
11867 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11868 // could be -1.
11869 std::optional<IntRange> R = TryGetExprRange(
11870 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11871 if (!R)
11872 return std::nullopt;
11873
11874 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11875 }
11876
11877 case BO_Rem:
11878 Combine = IntRange::rem;
11879 break;
11880
11881 // The default behavior is okay for these.
11882 case BO_Xor:
11883 case BO_Or:
11884 break;
11885 }
11886
11887 // Combine the two ranges, but limit the result to the type in which we
11888 // performed the computation.
11889 QualType T = GetExprType(E);
11890 unsigned opWidth = C.getIntWidth(T);
11891 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11892 InConstantContext, Approximate);
11893 if (!L)
11894 return std::nullopt;
11895
11896 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11897 InConstantContext, Approximate);
11898 if (!R)
11899 return std::nullopt;
11900
11901 IntRange C = Combine(*L, *R);
11902 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11903 C.Width = std::min(C.Width, MaxWidth);
11904 return C;
11905 }
11906
11907 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11908 switch (UO->getOpcode()) {
11909 // Boolean-valued operations are white-listed.
11910 case UO_LNot:
11911 return IntRange::forBoolType();
11912
11913 // Operations with opaque sources are black-listed.
11914 case UO_Deref:
11915 case UO_AddrOf: // should be impossible
11916 return IntRange::forValueOfType(C, GetExprType(E));
11917
11918 case UO_Minus: {
11919 if (E->getType()->isUnsignedIntegerType()) {
11920 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11921 Approximate);
11922 }
11923
11924 std::optional<IntRange> SubRange = TryGetExprRange(
11925 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11926
11927 if (!SubRange)
11928 return std::nullopt;
11929
11930 // If the range was previously non-negative, we need an extra bit for the
11931 // sign bit. Otherwise, we need an extra bit because the negation of the
11932 // most-negative value is one bit wider than that value.
11933 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11934 }
11935
11936 case UO_Not: {
11937 if (E->getType()->isUnsignedIntegerType()) {
11938 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11939 Approximate);
11940 }
11941
11942 std::optional<IntRange> SubRange = TryGetExprRange(
11943 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11944
11945 if (!SubRange)
11946 return std::nullopt;
11947
11948 // The width increments by 1 if the sub-expression cannot be negative
11949 // since it now can be.
11950 return IntRange(
11951 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11952 false);
11953 }
11954
11955 default:
11956 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11957 Approximate);
11958 }
11959 }
11960
11961 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11962 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11963 Approximate);
11964
11965 if (const auto *BitField = E->getSourceBitField())
11966 return IntRange(BitField->getBitWidthValue(),
11967 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11968
11969 if (GetExprType(E)->isVoidType())
11970 return std::nullopt;
11971
11972 return IntRange::forValueOfType(C, GetExprType(E));
11973}
11974
11975static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11976 bool InConstantContext,
11977 bool Approximate) {
11978 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11979 Approximate);
11980}
11981
11982/// Checks whether the given value, which currently has the given
11983/// source semantics, has the same value when coerced through the
11984/// target semantics.
11985static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11986 const llvm::fltSemantics &Src,
11987 const llvm::fltSemantics &Tgt) {
11988 llvm::APFloat truncated = value;
11989
11990 bool ignored;
11991 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11992 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11993
11994 return truncated.bitwiseIsEqual(value);
11995}
11996
11997/// Checks whether the given value, which currently has the given
11998/// source semantics, has the same value when coerced through the
11999/// target semantics.
12000///
12001/// The value might be a vector of floats (or a complex number).
12002static bool IsSameFloatAfterCast(const APValue &value,
12003 const llvm::fltSemantics &Src,
12004 const llvm::fltSemantics &Tgt) {
12005 if (value.isFloat())
12006 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12007
12008 if (value.isVector()) {
12009 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12010 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12011 return false;
12012 return true;
12013 }
12014
12015 if (value.isMatrix()) {
12016 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12017 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12018 return false;
12019 return true;
12020 }
12021
12022 assert(value.isComplexFloat());
12023 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12024 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12025}
12026
12027static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12028 bool IsListInit = false);
12029
12030static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12031 // Suppress cases where we are comparing against an enum constant.
12032 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12033 if (isa<EnumConstantDecl>(DR->getDecl()))
12034 return true;
12035
12036 // Suppress cases where the value is expanded from a macro, unless that macro
12037 // is how a language represents a boolean literal. This is the case in both C
12038 // and Objective-C.
12039 SourceLocation BeginLoc = E->getBeginLoc();
12040 if (BeginLoc.isMacroID()) {
12041 StringRef MacroName = Lexer::getImmediateMacroName(
12042 BeginLoc, S.getSourceManager(), S.getLangOpts());
12043 return MacroName != "YES" && MacroName != "NO" &&
12044 MacroName != "true" && MacroName != "false";
12045 }
12046
12047 return false;
12048}
12049
12050static bool isKnownToHaveUnsignedValue(const Expr *E) {
12051 return E->getType()->isIntegerType() &&
12052 (!E->getType()->isSignedIntegerType() ||
12054}
12055
12056namespace {
12057/// The promoted range of values of a type. In general this has the
12058/// following structure:
12059///
12060/// |-----------| . . . |-----------|
12061/// ^ ^ ^ ^
12062/// Min HoleMin HoleMax Max
12063///
12064/// ... where there is only a hole if a signed type is promoted to unsigned
12065/// (in which case Min and Max are the smallest and largest representable
12066/// values).
12067struct PromotedRange {
12068 // Min, or HoleMax if there is a hole.
12069 llvm::APSInt PromotedMin;
12070 // Max, or HoleMin if there is a hole.
12071 llvm::APSInt PromotedMax;
12072
12073 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12074 if (R.Width == 0)
12075 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12076 else if (R.Width >= BitWidth && !Unsigned) {
12077 // Promotion made the type *narrower*. This happens when promoting
12078 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12079 // Treat all values of 'signed int' as being in range for now.
12080 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12081 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12082 } else {
12083 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12084 .extOrTrunc(BitWidth);
12085 PromotedMin.setIsUnsigned(Unsigned);
12086
12087 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12088 .extOrTrunc(BitWidth);
12089 PromotedMax.setIsUnsigned(Unsigned);
12090 }
12091 }
12092
12093 // Determine whether this range is contiguous (has no hole).
12094 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12095
12096 // Where a constant value is within the range.
12097 enum ComparisonResult {
12098 LT = 0x1,
12099 LE = 0x2,
12100 GT = 0x4,
12101 GE = 0x8,
12102 EQ = 0x10,
12103 NE = 0x20,
12104 InRangeFlag = 0x40,
12105
12106 Less = LE | LT | NE,
12107 Min = LE | InRangeFlag,
12108 InRange = InRangeFlag,
12109 Max = GE | InRangeFlag,
12110 Greater = GE | GT | NE,
12111
12112 OnlyValue = LE | GE | EQ | InRangeFlag,
12113 InHole = NE
12114 };
12115
12116 ComparisonResult compare(const llvm::APSInt &Value) const {
12117 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12118 Value.isUnsigned() == PromotedMin.isUnsigned());
12119 if (!isContiguous()) {
12120 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12121 if (Value.isMinValue()) return Min;
12122 if (Value.isMaxValue()) return Max;
12123 if (Value >= PromotedMin) return InRange;
12124 if (Value <= PromotedMax) return InRange;
12125 return InHole;
12126 }
12127
12128 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12129 case -1: return Less;
12130 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12131 case 1:
12132 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12133 case -1: return InRange;
12134 case 0: return Max;
12135 case 1: return Greater;
12136 }
12137 }
12138
12139 llvm_unreachable("impossible compare result");
12140 }
12141
12142 static std::optional<StringRef>
12143 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12144 if (Op == BO_Cmp) {
12145 ComparisonResult LTFlag = LT, GTFlag = GT;
12146 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12147
12148 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12149 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12150 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12151 return std::nullopt;
12152 }
12153
12154 ComparisonResult TrueFlag, FalseFlag;
12155 if (Op == BO_EQ) {
12156 TrueFlag = EQ;
12157 FalseFlag = NE;
12158 } else if (Op == BO_NE) {
12159 TrueFlag = NE;
12160 FalseFlag = EQ;
12161 } else {
12162 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12163 TrueFlag = LT;
12164 FalseFlag = GE;
12165 } else {
12166 TrueFlag = GT;
12167 FalseFlag = LE;
12168 }
12169 if (Op == BO_GE || Op == BO_LE)
12170 std::swap(TrueFlag, FalseFlag);
12171 }
12172 if (R & TrueFlag)
12173 return StringRef("true");
12174 if (R & FalseFlag)
12175 return StringRef("false");
12176 return std::nullopt;
12177 }
12178};
12179}
12180
12181static bool HasEnumType(const Expr *E) {
12182 // Strip off implicit integral promotions.
12183 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12184 if (ICE->getCastKind() != CK_IntegralCast &&
12185 ICE->getCastKind() != CK_NoOp)
12186 break;
12187 E = ICE->getSubExpr();
12188 }
12189
12190 return E->getType()->isEnumeralType();
12191}
12192
12194 // The values of this enumeration are used in the diagnostics
12195 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12196 enum ConstantValueKind {
12197 Miscellaneous = 0,
12198 LiteralTrue,
12199 LiteralFalse
12200 };
12201 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12202 return BL->getValue() ? ConstantValueKind::LiteralTrue
12203 : ConstantValueKind::LiteralFalse;
12204 return ConstantValueKind::Miscellaneous;
12205}
12206
12209 const llvm::APSInt &Value,
12210 bool RhsConstant) {
12212 return false;
12213
12214 Expr *OriginalOther = Other;
12215
12216 Constant = Constant->IgnoreParenImpCasts();
12217 Other = Other->IgnoreParenImpCasts();
12218
12219 // Suppress warnings on tautological comparisons between values of the same
12220 // enumeration type. There are only two ways we could warn on this:
12221 // - If the constant is outside the range of representable values of
12222 // the enumeration. In such a case, we should warn about the cast
12223 // to enumeration type, not about the comparison.
12224 // - If the constant is the maximum / minimum in-range value. For an
12225 // enumeratin type, such comparisons can be meaningful and useful.
12226 if (Constant->getType()->isEnumeralType() &&
12227 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12228 return false;
12229
12230 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12231 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12232 if (!OtherValueRange)
12233 return false;
12234
12235 QualType OtherT = Other->getType();
12236 if (const auto *AT = OtherT->getAs<AtomicType>())
12237 OtherT = AT->getValueType();
12238 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12239
12240 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12241 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12242 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12243 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12244 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12245
12246 // Whether we're treating Other as being a bool because of the form of
12247 // expression despite it having another type (typically 'int' in C).
12248 bool OtherIsBooleanDespiteType =
12249 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12250 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12251 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12252
12253 // Check if all values in the range of possible values of this expression
12254 // lead to the same comparison outcome.
12255 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12256 Value.isUnsigned());
12257 auto Cmp = OtherPromotedValueRange.compare(Value);
12258 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12259 if (!Result)
12260 return false;
12261
12262 // Also consider the range determined by the type alone. This allows us to
12263 // classify the warning under the proper diagnostic group.
12264 bool TautologicalTypeCompare = false;
12265 {
12266 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12267 Value.isUnsigned());
12268 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12269 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12270 RhsConstant)) {
12271 TautologicalTypeCompare = true;
12272 Cmp = TypeCmp;
12274 }
12275 }
12276
12277 // Don't warn if the non-constant operand actually always evaluates to the
12278 // same value.
12279 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12280 return false;
12281
12282 // Suppress the diagnostic for an in-range comparison if the constant comes
12283 // from a macro or enumerator. We don't want to diagnose
12284 //
12285 // some_long_value <= INT_MAX
12286 //
12287 // when sizeof(int) == sizeof(long).
12288 bool InRange = Cmp & PromotedRange::InRangeFlag;
12289 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12290 return false;
12291
12292 // A comparison of an unsigned bit-field against 0 is really a type problem,
12293 // even though at the type level the bit-field might promote to 'signed int'.
12294 if (Other->refersToBitField() && InRange && Value == 0 &&
12295 Other->getType()->isUnsignedIntegerOrEnumerationType())
12296 TautologicalTypeCompare = true;
12297
12298 // If this is a comparison to an enum constant, include that
12299 // constant in the diagnostic.
12300 const EnumConstantDecl *ED = nullptr;
12301 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12302 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12303
12304 // Should be enough for uint128 (39 decimal digits)
12305 SmallString<64> PrettySourceValue;
12306 llvm::raw_svector_ostream OS(PrettySourceValue);
12307 if (ED) {
12308 OS << '\'' << *ED << "' (" << Value << ")";
12309 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12310 Constant->IgnoreParenImpCasts())) {
12311 OS << (BL->getValue() ? "YES" : "NO");
12312 } else {
12313 OS << Value;
12314 }
12315
12316 if (!TautologicalTypeCompare) {
12317 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12318 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12319 << E->getOpcodeStr() << OS.str() << *Result
12320 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12321 return true;
12322 }
12323
12324 if (IsObjCSignedCharBool) {
12326 S.PDiag(diag::warn_tautological_compare_objc_bool)
12327 << OS.str() << *Result);
12328 return true;
12329 }
12330
12331 // FIXME: We use a somewhat different formatting for the in-range cases and
12332 // cases involving boolean values for historical reasons. We should pick a
12333 // consistent way of presenting these diagnostics.
12334 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12335
12337 E->getOperatorLoc(), E,
12338 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12339 : diag::warn_tautological_bool_compare)
12340 << OS.str() << classifyConstantValue(Constant) << OtherT
12341 << OtherIsBooleanDespiteType << *Result
12342 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12343 } else {
12344 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12345 unsigned Diag =
12346 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12347 ? (HasEnumType(OriginalOther)
12348 ? diag::warn_unsigned_enum_always_true_comparison
12349 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12350 : diag::warn_unsigned_always_true_comparison)
12351 : diag::warn_tautological_constant_compare;
12352
12353 S.Diag(E->getOperatorLoc(), Diag)
12354 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12355 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12356 }
12357
12358 return true;
12359}
12360
12361/// Analyze the operands of the given comparison. Implements the
12362/// fallback case from AnalyzeComparison.
12367
12368/// Implements -Wsign-compare.
12369///
12370/// \param E the binary operator to check for warnings
12372 // The type the comparison is being performed in.
12373 QualType T = E->getLHS()->getType();
12374
12375 // Only analyze comparison operators where both sides have been converted to
12376 // the same type.
12377 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12378 return AnalyzeImpConvsInComparison(S, E);
12379
12380 // Don't analyze value-dependent comparisons directly.
12381 if (E->isValueDependent())
12382 return AnalyzeImpConvsInComparison(S, E);
12383
12384 Expr *LHS = E->getLHS();
12385 Expr *RHS = E->getRHS();
12386
12387 if (T->isIntegralType(S.Context)) {
12388 std::optional<llvm::APSInt> RHSValue =
12390 std::optional<llvm::APSInt> LHSValue =
12392
12393 // We don't care about expressions whose result is a constant.
12394 if (RHSValue && LHSValue)
12395 return AnalyzeImpConvsInComparison(S, E);
12396
12397 // We only care about expressions where just one side is literal
12398 if ((bool)RHSValue ^ (bool)LHSValue) {
12399 // Is the constant on the RHS or LHS?
12400 const bool RhsConstant = (bool)RHSValue;
12401 Expr *Const = RhsConstant ? RHS : LHS;
12402 Expr *Other = RhsConstant ? LHS : RHS;
12403 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12404
12405 // Check whether an integer constant comparison results in a value
12406 // of 'true' or 'false'.
12407 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12408 return AnalyzeImpConvsInComparison(S, E);
12409 }
12410 }
12411
12412 if (!T->hasUnsignedIntegerRepresentation()) {
12413 // We don't do anything special if this isn't an unsigned integral
12414 // comparison: we're only interested in integral comparisons, and
12415 // signed comparisons only happen in cases we don't care to warn about.
12416 return AnalyzeImpConvsInComparison(S, E);
12417 }
12418
12419 LHS = LHS->IgnoreParenImpCasts();
12420 RHS = RHS->IgnoreParenImpCasts();
12421
12422 if (!S.getLangOpts().CPlusPlus) {
12423 // Avoid warning about comparison of integers with different signs when
12424 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12425 // the type of `E`.
12426 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12427 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12428 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12429 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12430 }
12431
12432 // Check to see if one of the (unmodified) operands is of different
12433 // signedness.
12434 Expr *signedOperand, *unsignedOperand;
12436 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12437 "unsigned comparison between two signed integer expressions?");
12438 signedOperand = LHS;
12439 unsignedOperand = RHS;
12440 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12441 signedOperand = RHS;
12442 unsignedOperand = LHS;
12443 } else {
12444 return AnalyzeImpConvsInComparison(S, E);
12445 }
12446
12447 // Otherwise, calculate the effective range of the signed operand.
12448 std::optional<IntRange> signedRange =
12450 /*Approximate=*/true);
12451 if (!signedRange)
12452 return;
12453
12454 // Go ahead and analyze implicit conversions in the operands. Note
12455 // that we skip the implicit conversions on both sides.
12458
12459 // If the signed range is non-negative, -Wsign-compare won't fire.
12460 if (signedRange->NonNegative)
12461 return;
12462
12463 // For (in)equality comparisons, if the unsigned operand is a
12464 // constant which cannot collide with a overflowed signed operand,
12465 // then reinterpreting the signed operand as unsigned will not
12466 // change the result of the comparison.
12467 if (E->isEqualityOp()) {
12468 unsigned comparisonWidth = S.Context.getIntWidth(T);
12469 std::optional<IntRange> unsignedRange = TryGetExprRange(
12470 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12471 /*Approximate=*/true);
12472 if (!unsignedRange)
12473 return;
12474
12475 // We should never be unable to prove that the unsigned operand is
12476 // non-negative.
12477 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12478
12479 if (unsignedRange->Width < comparisonWidth)
12480 return;
12481 }
12482
12484 S.PDiag(diag::warn_mixed_sign_comparison)
12485 << LHS->getType() << RHS->getType()
12486 << LHS->getSourceRange() << RHS->getSourceRange());
12487}
12488
12489/// Analyzes an attempt to assign the given value to a bitfield.
12490///
12491/// Returns true if there was something fishy about the attempt.
12493 SourceLocation InitLoc) {
12494 assert(Bitfield->isBitField());
12495 if (Bitfield->isInvalidDecl())
12496 return false;
12497
12498 // White-list bool bitfields.
12499 QualType BitfieldType = Bitfield->getType();
12500 if (BitfieldType->isBooleanType())
12501 return false;
12502
12503 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12504 // If the underlying enum type was not explicitly specified as an unsigned
12505 // type and the enum contain only positive values, MSVC++ will cause an
12506 // inconsistency by storing this as a signed type.
12507 if (S.getLangOpts().CPlusPlus11 &&
12508 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12509 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12510 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12511 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12512 << BitfieldEnumDecl;
12513 }
12514 }
12515
12516 // Ignore value- or type-dependent expressions.
12517 if (Bitfield->getBitWidth()->isValueDependent() ||
12518 Bitfield->getBitWidth()->isTypeDependent() ||
12519 Init->isValueDependent() ||
12520 Init->isTypeDependent())
12521 return false;
12522
12523 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12524 unsigned FieldWidth = Bitfield->getBitWidthValue();
12525
12527 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12529 // The RHS is not constant. If the RHS has an enum type, make sure the
12530 // bitfield is wide enough to hold all the values of the enum without
12531 // truncation.
12532 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12533 const PreferredTypeAttr *PTAttr = nullptr;
12534 if (!ED) {
12535 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12536 if (PTAttr)
12537 ED = PTAttr->getType()->getAsEnumDecl();
12538 }
12539 if (ED) {
12540 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12541
12542 // Enum types are implicitly signed on Windows, so check if there are any
12543 // negative enumerators to see if the enum was intended to be signed or
12544 // not.
12545 bool SignedEnum = ED->getNumNegativeBits() > 0;
12546
12547 // Check for surprising sign changes when assigning enum values to a
12548 // bitfield of different signedness. If the bitfield is signed and we
12549 // have exactly the right number of bits to store this unsigned enum,
12550 // suggest changing the enum to an unsigned type. This typically happens
12551 // on Windows where unfixed enums always use an underlying type of 'int'.
12552 unsigned DiagID = 0;
12553 if (SignedEnum && !SignedBitfield) {
12554 DiagID =
12555 PTAttr == nullptr
12556 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12557 : diag::
12558 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12559 } else if (SignedBitfield && !SignedEnum &&
12560 ED->getNumPositiveBits() == FieldWidth) {
12561 DiagID =
12562 PTAttr == nullptr
12563 ? diag::warn_signed_bitfield_enum_conversion
12564 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12565 }
12566 if (DiagID) {
12567 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12568 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12569 SourceRange TypeRange =
12570 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12571 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12572 << SignedEnum << TypeRange;
12573 if (PTAttr)
12574 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12575 << ED;
12576 }
12577
12578 // Compute the required bitwidth. If the enum has negative values, we need
12579 // one more bit than the normal number of positive bits to represent the
12580 // sign bit.
12581 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12582 ED->getNumNegativeBits())
12583 : ED->getNumPositiveBits();
12584
12585 // Check the bitwidth.
12586 if (BitsNeeded > FieldWidth) {
12587 Expr *WidthExpr = Bitfield->getBitWidth();
12588 auto DiagID =
12589 PTAttr == nullptr
12590 ? diag::warn_bitfield_too_small_for_enum
12591 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12592 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12593 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12594 << BitsNeeded << ED << WidthExpr->getSourceRange();
12595 if (PTAttr)
12596 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12597 << ED;
12598 }
12599 }
12600
12601 return false;
12602 }
12603
12604 llvm::APSInt Value = Result.Val.getInt();
12605
12606 unsigned OriginalWidth = Value.getBitWidth();
12607
12608 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12609 // false positives where the user is demonstrating they intend to use the
12610 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12611 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12612 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12613 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12614 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12615 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12616 S.findMacroSpelling(MaybeMacroLoc, "true"))
12617 return false;
12618 }
12619
12620 if (!Value.isSigned() || Value.isNegative())
12621 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12622 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12623 OriginalWidth = Value.getSignificantBits();
12624
12625 if (OriginalWidth <= FieldWidth)
12626 return false;
12627
12628 // Compute the value which the bitfield will contain.
12629 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12630 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12631
12632 // Check whether the stored value is equal to the original value.
12633 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12634 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12635 return false;
12636
12637 std::string PrettyValue = toString(Value, 10);
12638 std::string PrettyTrunc = toString(TruncatedValue, 10);
12639
12640 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12641 ? diag::warn_impcast_single_bit_bitield_precision_constant
12642 : diag::warn_impcast_bitfield_precision_constant)
12643 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12644 << Init->getSourceRange();
12645
12646 return true;
12647}
12648
12649/// Analyze the given simple or compound assignment for warning-worthy
12650/// operations.
12652 // Just recurse on the LHS.
12654
12655 // We want to recurse on the RHS as normal unless we're assigning to
12656 // a bitfield.
12657 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12658 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12659 E->getOperatorLoc())) {
12660 // Recurse, ignoring any implicit conversions on the RHS.
12662 E->getOperatorLoc());
12663 }
12664 }
12665
12666 // Set context flag for overflow behavior type assignment analysis, use RAII
12667 // pattern to handle nested assignments.
12668 llvm::SaveAndRestore OBTAssignmentContext(
12670
12672
12673 // Diagnose implicitly sequentially-consistent atomic assignment.
12674 if (E->getLHS()->getType()->isAtomicType())
12675 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12676}
12677
12678/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12679static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12680 QualType T, SourceLocation CContext, unsigned diag,
12681 bool PruneControlFlow = false) {
12682 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12683 // address space annotations isn't really useful. The warnings aren't because
12684 // you're converting a `private int` to `unsigned int`, it is because you're
12685 // conerting `int` to `unsigned int`.
12686 if (SourceType.hasAddressSpace())
12687 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
12688 if (T.hasAddressSpace())
12690 if (PruneControlFlow) {
12692 S.PDiag(diag)
12693 << SourceType << T << E->getSourceRange()
12694 << SourceRange(CContext));
12695 return;
12696 }
12697 S.Diag(E->getExprLoc(), diag)
12698 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12699}
12700
12701/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12702static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12703 SourceLocation CContext, unsigned diag,
12704 bool PruneControlFlow = false) {
12705 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
12706}
12707
12708/// Diagnose an implicit cast from a floating point value to an integer value.
12709static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12710 SourceLocation CContext) {
12711 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12712 bool PruneWarnings = S.inTemplateInstantiation();
12713
12714 const Expr *InnerE = E->IgnoreParenImpCasts();
12715 // We also want to warn on, e.g., "int i = -1.234"
12716 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
12717 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12718 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12719
12720 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12721
12722 llvm::APFloat Value(0.0);
12723 bool IsConstant =
12725 if (!IsConstant) {
12726 if (S.ObjC().isSignedCharBool(T)) {
12728 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12729 << E->getType());
12730 }
12731
12732 return DiagnoseImpCast(S, E, T, CContext,
12733 diag::warn_impcast_float_integer, PruneWarnings);
12734 }
12735
12736 bool isExact = false;
12737
12738 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12739 T->hasUnsignedIntegerRepresentation());
12740 llvm::APFloat::opStatus Result = Value.convertToInteger(
12741 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12742
12743 // FIXME: Force the precision of the source value down so we don't print
12744 // digits which are usually useless (we don't really care here if we
12745 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12746 // would automatically print the shortest representation, but it's a bit
12747 // tricky to implement.
12748 SmallString<16> PrettySourceValue;
12749 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12750 precision = (precision * 59 + 195) / 196;
12751 Value.toString(PrettySourceValue, precision);
12752
12753 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12755 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12756 << PrettySourceValue);
12757 }
12758
12759 if (Result == llvm::APFloat::opOK && isExact) {
12760 if (IsLiteral) return;
12761 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12762 PruneWarnings);
12763 }
12764
12765 // Conversion of a floating-point value to a non-bool integer where the
12766 // integral part cannot be represented by the integer type is undefined.
12767 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12768 return DiagnoseImpCast(
12769 S, E, T, CContext,
12770 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12771 : diag::warn_impcast_float_to_integer_out_of_range,
12772 PruneWarnings);
12773
12774 unsigned DiagID = 0;
12775 if (IsLiteral) {
12776 // Warn on floating point literal to integer.
12777 DiagID = diag::warn_impcast_literal_float_to_integer;
12778 } else if (IntegerValue == 0) {
12779 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12780 return DiagnoseImpCast(S, E, T, CContext,
12781 diag::warn_impcast_float_integer, PruneWarnings);
12782 }
12783 // Warn on non-zero to zero conversion.
12784 DiagID = diag::warn_impcast_float_to_integer_zero;
12785 } else {
12786 if (IntegerValue.isUnsigned()) {
12787 if (!IntegerValue.isMaxValue()) {
12788 return DiagnoseImpCast(S, E, T, CContext,
12789 diag::warn_impcast_float_integer, PruneWarnings);
12790 }
12791 } else { // IntegerValue.isSigned()
12792 if (!IntegerValue.isMaxSignedValue() &&
12793 !IntegerValue.isMinSignedValue()) {
12794 return DiagnoseImpCast(S, E, T, CContext,
12795 diag::warn_impcast_float_integer, PruneWarnings);
12796 }
12797 }
12798 // Warn on evaluatable floating point expression to integer conversion.
12799 DiagID = diag::warn_impcast_float_to_integer;
12800 }
12801
12802 SmallString<16> PrettyTargetValue;
12803 if (IsBool)
12804 PrettyTargetValue = Value.isZero() ? "false" : "true";
12805 else
12806 IntegerValue.toString(PrettyTargetValue);
12807
12808 if (PruneWarnings) {
12810 S.PDiag(DiagID)
12811 << E->getType() << T.getUnqualifiedType()
12812 << PrettySourceValue << PrettyTargetValue
12813 << E->getSourceRange() << SourceRange(CContext));
12814 } else {
12815 S.Diag(E->getExprLoc(), DiagID)
12816 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12817 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12818 }
12819}
12820
12821/// Analyze the given compound assignment for the possible losing of
12822/// floating-point precision.
12824 assert(isa<CompoundAssignOperator>(E) &&
12825 "Must be compound assignment operation");
12826 // Recurse on the LHS and RHS in here
12829
12830 if (E->getLHS()->getType()->isAtomicType())
12831 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12832
12833 // Now check the outermost expression
12834 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12835 const auto *RBT = cast<CompoundAssignOperator>(E)
12836 ->getComputationResultType()
12837 ->getAs<BuiltinType>();
12838
12839 // The below checks assume source is floating point.
12840 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12841
12842 // If source is floating point but target is an integer.
12843 if (ResultBT->isInteger())
12844 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12845 E->getExprLoc(), diag::warn_impcast_float_integer);
12846
12847 if (!ResultBT->isFloatingPoint())
12848 return;
12849
12850 // If both source and target are floating points, warn about losing precision.
12852 QualType(ResultBT, 0), QualType(RBT, 0));
12853 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12854 // warn about dropping FP rank.
12855 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12856 diag::warn_impcast_float_result_precision);
12857}
12858
12859static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12860 IntRange Range) {
12861 if (!Range.Width) return "0";
12862
12863 llvm::APSInt ValueInRange = Value;
12864 ValueInRange.setIsSigned(!Range.NonNegative);
12865 ValueInRange = ValueInRange.trunc(Range.Width);
12866 return toString(ValueInRange, 10);
12867}
12868
12869static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12870 bool ToBool) {
12871 if (!isa<ImplicitCastExpr>(Ex))
12872 return false;
12873
12874 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12876 const Type *Source =
12878 if (Target->isDependentType())
12879 return false;
12880
12881 const auto *FloatCandidateBT =
12882 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12883 const Type *BoolCandidateType = ToBool ? Target : Source;
12884
12885 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12886 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12887}
12888
12889static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12890 SourceLocation CC) {
12891 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12892 const Expr *CurrA = TheCall->getArg(I);
12893 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12894 continue;
12895
12896 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12897 S, TheCall->getArg(I - 1), false));
12898 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12899 S, TheCall->getArg(I + 1), false));
12900 if (IsSwapped) {
12901 // Warn on this floating-point to bool conversion.
12903 CurrA->getType(), CC,
12904 diag::warn_impcast_floating_point_to_bool);
12905 }
12906 }
12907}
12908
12910 SourceLocation CC) {
12911 // Don't warn on functions which have return type nullptr_t.
12912 if (isa<CallExpr>(E))
12913 return;
12914
12915 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12916 const Expr *NewE = E->IgnoreParenImpCasts();
12917 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12918 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12919 if (!IsGNUNullExpr && !HasNullPtrType)
12920 return;
12921
12922 // Return if target type is a safe conversion.
12923 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12924 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12925 return;
12926
12927 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12928 E->getExprLoc()))
12929 return;
12930
12932
12933 // Venture through the macro stacks to get to the source of macro arguments.
12934 // The new location is a better location than the complete location that was
12935 // passed in.
12936 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12938
12939 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12940 if (IsGNUNullExpr && Loc.isMacroID()) {
12941 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12942 Loc, S.SourceMgr, S.getLangOpts());
12943 if (MacroName == "NULL")
12945 }
12946
12947 // Only warn if the null and context location are in the same macro expansion.
12948 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12949 return;
12950
12951 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12952 << HasNullPtrType << T << SourceRange(CC)
12954 S.getFixItZeroLiteralForType(T, Loc));
12955}
12956
12957// Helper function to filter out cases for constant width constant conversion.
12958// Don't warn on char array initialization or for non-decimal values.
12960 SourceLocation CC) {
12961 // If initializing from a constant, and the constant starts with '0',
12962 // then it is a binary, octal, or hexadecimal. Allow these constants
12963 // to fill all the bits, even if there is a sign change.
12964 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12965 const char FirstLiteralCharacter =
12966 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12967 if (FirstLiteralCharacter == '0')
12968 return false;
12969 }
12970
12971 // If the CC location points to a '{', and the type is char, then assume
12972 // assume it is an array initialization.
12973 if (CC.isValid() && T->isCharType()) {
12974 const char FirstContextCharacter =
12976 if (FirstContextCharacter == '{')
12977 return false;
12978 }
12979
12980 return true;
12981}
12982
12984 const auto *IL = dyn_cast<IntegerLiteral>(E);
12985 if (!IL) {
12986 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12987 if (UO->getOpcode() == UO_Minus)
12988 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12989 }
12990 }
12991
12992 return IL;
12993}
12994
12996 E = E->IgnoreParenImpCasts();
12997 SourceLocation ExprLoc = E->getExprLoc();
12998
12999 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13000 BinaryOperator::Opcode Opc = BO->getOpcode();
13002 // Do not diagnose unsigned shifts.
13003 if (Opc == BO_Shl) {
13004 const auto *LHS = getIntegerLiteral(BO->getLHS());
13005 const auto *RHS = getIntegerLiteral(BO->getRHS());
13006 if (LHS && LHS->getValue() == 0)
13007 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13008 else if (!E->isValueDependent() && LHS && RHS &&
13009 RHS->getValue().isNonNegative() &&
13011 S.Diag(ExprLoc, diag::warn_left_shift_always)
13012 << (Result.Val.getInt() != 0);
13013 else if (E->getType()->isSignedIntegerType())
13014 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13017 ") != 0");
13018 }
13019 }
13020
13021 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13022 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13023 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13024 if (!LHS || !RHS)
13025 return;
13026 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13027 (RHS->getValue() == 0 || RHS->getValue() == 1))
13028 // Do not diagnose common idioms.
13029 return;
13030 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13031 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13032 }
13033}
13034
13036 const Type *Target, Expr *E,
13037 QualType T,
13038 SourceLocation CC) {
13039 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13040 Source != Target);
13041
13042 // Lone surrogates have a distinct representation in UTF-32.
13043 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13044 // so don't warn on such conversion.
13045 if (Source->isChar16Type() && Target->isChar32Type())
13046 return;
13047
13051 llvm::APSInt Value(32);
13052 Value = Result.Val.getInt();
13053 bool IsASCII = Value <= 0x7F;
13054 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13055 bool ConversionPreservesSemantics =
13056 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13057
13058 if (!ConversionPreservesSemantics) {
13059 auto IsSingleCodeUnitCP = [](const QualType &T,
13060 const llvm::APSInt &Value) {
13061 if (T->isChar8Type())
13062 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13063 if (T->isChar16Type())
13064 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13065 assert(T->isChar32Type());
13066 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13067 };
13068
13069 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13070 << E->getType() << T
13071 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13072 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13073 }
13074 } else {
13075 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13077 DiagnoseImpCast(S, E, T, CC,
13078 LosesPrecision ? diag::warn_impcast_unicode_precision
13079 : diag::warn_impcast_unicode_char_type);
13080 }
13081}
13082
13084 From = Context.getCanonicalType(From);
13085 To = Context.getCanonicalType(To);
13086 QualType MaybePointee = From->getPointeeType();
13087 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13088 From = MaybePointee;
13089 MaybePointee = To->getPointeeType();
13090 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13091 To = MaybePointee;
13092
13093 if (const auto *FromFn = From->getAs<FunctionType>()) {
13094 if (const auto *ToFn = To->getAs<FunctionType>()) {
13095 if (FromFn->getCFIUncheckedCalleeAttr() &&
13096 !ToFn->getCFIUncheckedCalleeAttr())
13097 return true;
13098 }
13099 }
13100 return false;
13101}
13102
13104 bool *ICContext, bool IsListInit) {
13105 if (E->isTypeDependent() || E->isValueDependent()) return;
13106
13107 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13108 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13109 if (Source == Target) return;
13110 if (Target->isDependentType()) return;
13111
13112 // If the conversion context location is invalid don't complain. We also
13113 // don't want to emit a warning if the issue occurs from the expansion of
13114 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13115 // delay this check as long as possible. Once we detect we are in that
13116 // scenario, we just return.
13117 if (CC.isInvalid())
13118 return;
13119
13120 if (Source->isAtomicType())
13121 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13122
13123 // Diagnose implicit casts to bool.
13124 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13125 if (isa<StringLiteral>(E))
13126 // Warn on string literal to bool. Checks for string literals in logical
13127 // and expressions, for instance, assert(0 && "error here"), are
13128 // prevented by a check in AnalyzeImplicitConversions().
13129 return DiagnoseImpCast(*this, E, T, CC,
13130 diag::warn_impcast_string_literal_to_bool);
13133 // This covers the literal expressions that evaluate to Objective-C
13134 // objects.
13135 return DiagnoseImpCast(*this, E, T, CC,
13136 diag::warn_impcast_objective_c_literal_to_bool);
13137 }
13138 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13139 // Warn on pointer to bool conversion that is always true.
13141 SourceRange(CC));
13142 }
13143 }
13144
13146
13147 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13148 // is a typedef for signed char (macOS), then that constant value has to be 1
13149 // or 0.
13150 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13153 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13155 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13156 << toString(Result.Val.getInt(), 10));
13157 }
13158 return;
13159 }
13160 }
13161
13162 // Check implicit casts from Objective-C collection literals to specialized
13163 // collection types, e.g., NSArray<NSString *> *.
13164 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13165 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13166 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13167 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13168
13169 // Strip complex types.
13170 if (isa<ComplexType>(Source)) {
13171 if (!isa<ComplexType>(Target)) {
13172 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13173 return;
13174
13175 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13176 return DiagnoseImpCast(*this, E, T, CC,
13177 diag::err_impcast_incompatible_type);
13178 }
13179
13180 return DiagnoseImpCast(*this, E, T, CC,
13182 ? diag::err_impcast_complex_scalar
13183 : diag::warn_impcast_complex_scalar);
13184 }
13185
13186 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13187 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13188 }
13189
13190 // Strip vector types.
13191 if (isa<VectorType>(Source)) {
13192 if (Target->isSveVLSBuiltinType() &&
13193 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13194 QualType(Source, 0)) ||
13195 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13196 QualType(Source, 0))))
13197 return;
13198
13199 if (Target->isRVVVLSBuiltinType() &&
13200 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13201 QualType(Source, 0)) ||
13202 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13203 QualType(Source, 0))))
13204 return;
13205
13206 if (!isa<VectorType>(Target)) {
13207 if (SourceMgr.isInSystemMacro(CC))
13208 return;
13209 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13210 }
13211 if (getLangOpts().HLSL &&
13212 Target->castAs<VectorType>()->getNumElements() <
13213 Source->castAs<VectorType>()->getNumElements()) {
13214 // Diagnose vector truncation but don't return. We may also want to
13215 // diagnose an element conversion.
13216 DiagnoseImpCast(*this, E, T, CC,
13217 diag::warn_hlsl_impcast_vector_truncation);
13218 }
13219
13220 // If the vector cast is cast between two vectors of the same size, it is
13221 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13222 if (!getLangOpts().HLSL &&
13223 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13224 return;
13225
13226 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13227 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13228 }
13229 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13230 Target = VecTy->getElementType().getTypePtr();
13231
13232 // Strip matrix types.
13233 if (isa<ConstantMatrixType>(Source)) {
13234 if (Target->isScalarType())
13235 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13236
13239 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13240 // Diagnose Matrix truncation but don't return. We may also want to
13241 // diagnose an element conversion.
13242 DiagnoseImpCast(*this, E, T, CC,
13243 diag::warn_hlsl_impcast_matrix_truncation);
13244 }
13245
13246 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13247 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13248 }
13249 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13250 Target = MatTy->getElementType().getTypePtr();
13251
13252 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13253 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13254
13255 // Strip SVE vector types
13256 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13257 // Need the original target type for vector type checks
13258 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13259 // Handle conversion from scalable to fixed when msve-vector-bits is
13260 // specified
13261 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13262 QualType(Source, 0)) ||
13263 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13264 QualType(Source, 0)))
13265 return;
13266
13267 // If the vector cast is cast between two vectors of the same size, it is
13268 // a bitcast, not a conversion.
13269 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13270 return;
13271
13272 Source = SourceBT->getSveEltType(Context).getTypePtr();
13273 }
13274
13275 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13276 Target = TargetBT->getSveEltType(Context).getTypePtr();
13277
13278 // If the source is floating point...
13279 if (SourceBT && SourceBT->isFloatingPoint()) {
13280 // ...and the target is floating point...
13281 if (TargetBT && TargetBT->isFloatingPoint()) {
13282 // ...then warn if we're dropping FP rank.
13283
13285 QualType(SourceBT, 0), QualType(TargetBT, 0));
13286 if (Order > 0) {
13287 // Don't warn about float constants that are precisely
13288 // representable in the target type.
13289 Expr::EvalResult result;
13290 if (E->EvaluateAsRValue(result, Context)) {
13291 // Value might be a float, a float vector, or a float complex.
13293 result.Val,
13294 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13295 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13296 return;
13297 }
13298
13299 if (SourceMgr.isInSystemMacro(CC))
13300 return;
13301
13302 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13303 }
13304 // ... or possibly if we're increasing rank, too
13305 else if (Order < 0) {
13306 if (SourceMgr.isInSystemMacro(CC))
13307 return;
13308
13309 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13310 }
13311 return;
13312 }
13313
13314 // If the target is integral, always warn.
13315 if (TargetBT && TargetBT->isInteger()) {
13316 if (SourceMgr.isInSystemMacro(CC))
13317 return;
13318
13319 DiagnoseFloatingImpCast(*this, E, T, CC);
13320 }
13321
13322 // Detect the case where a call result is converted from floating-point to
13323 // to bool, and the final argument to the call is converted from bool, to
13324 // discover this typo:
13325 //
13326 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13327 //
13328 // FIXME: This is an incredibly special case; is there some more general
13329 // way to detect this class of misplaced-parentheses bug?
13330 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13331 // Check last argument of function call to see if it is an
13332 // implicit cast from a type matching the type the result
13333 // is being cast to.
13334 CallExpr *CEx = cast<CallExpr>(E);
13335 if (unsigned NumArgs = CEx->getNumArgs()) {
13336 Expr *LastA = CEx->getArg(NumArgs - 1);
13337 Expr *InnerE = LastA->IgnoreParenImpCasts();
13338 if (isa<ImplicitCastExpr>(LastA) &&
13339 InnerE->getType()->isBooleanType()) {
13340 // Warn on this floating-point to bool conversion
13341 DiagnoseImpCast(*this, E, T, CC,
13342 diag::warn_impcast_floating_point_to_bool);
13343 }
13344 }
13345 }
13346 return;
13347 }
13348
13349 // Valid casts involving fixed point types should be accounted for here.
13350 if (Source->isFixedPointType()) {
13351 if (Target->isUnsaturatedFixedPointType()) {
13355 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13356 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13357 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13358 if (Value > MaxVal || Value < MinVal) {
13360 PDiag(diag::warn_impcast_fixed_point_range)
13361 << Value.toString() << T
13362 << E->getSourceRange()
13363 << clang::SourceRange(CC));
13364 return;
13365 }
13366 }
13367 } else if (Target->isIntegerType()) {
13371 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13372
13373 bool Overflowed;
13374 llvm::APSInt IntResult = FXResult.convertToInt(
13375 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13376 &Overflowed);
13377
13378 if (Overflowed) {
13380 PDiag(diag::warn_impcast_fixed_point_range)
13381 << FXResult.toString() << T
13382 << E->getSourceRange()
13383 << clang::SourceRange(CC));
13384 return;
13385 }
13386 }
13387 }
13388 } else if (Target->isUnsaturatedFixedPointType()) {
13389 if (Source->isIntegerType()) {
13393 llvm::APSInt Value = Result.Val.getInt();
13394
13395 bool Overflowed;
13396 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13397 Value, Context.getFixedPointSemantics(T), &Overflowed);
13398
13399 if (Overflowed) {
13401 PDiag(diag::warn_impcast_fixed_point_range)
13402 << toString(Value, /*Radix=*/10) << T
13403 << E->getSourceRange()
13404 << clang::SourceRange(CC));
13405 return;
13406 }
13407 }
13408 }
13409 }
13410
13411 // If we are casting an integer type to a floating point type without
13412 // initialization-list syntax, we might lose accuracy if the floating
13413 // point type has a narrower significand than the integer type.
13414 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13415 TargetBT->isFloatingType() && !IsListInit) {
13416 // Determine the number of precision bits in the source integer type.
13417 std::optional<IntRange> SourceRange =
13419 /*Approximate=*/true);
13420 if (!SourceRange)
13421 return;
13422 unsigned int SourcePrecision = SourceRange->Width;
13423
13424 // Determine the number of precision bits in the
13425 // target floating point type.
13426 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13427 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13428
13429 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13430 SourcePrecision > TargetPrecision) {
13431
13432 if (std::optional<llvm::APSInt> SourceInt =
13434 // If the source integer is a constant, convert it to the target
13435 // floating point type. Issue a warning if the value changes
13436 // during the whole conversion.
13437 llvm::APFloat TargetFloatValue(
13438 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13439 llvm::APFloat::opStatus ConversionStatus =
13440 TargetFloatValue.convertFromAPInt(
13441 *SourceInt, SourceBT->isSignedInteger(),
13442 llvm::APFloat::rmNearestTiesToEven);
13443
13444 if (ConversionStatus != llvm::APFloat::opOK) {
13445 SmallString<32> PrettySourceValue;
13446 SourceInt->toString(PrettySourceValue, 10);
13447 SmallString<32> PrettyTargetValue;
13448 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13449
13451 E->getExprLoc(), E,
13452 PDiag(diag::warn_impcast_integer_float_precision_constant)
13453 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13454 << E->getSourceRange() << clang::SourceRange(CC));
13455 }
13456 } else {
13457 // Otherwise, the implicit conversion may lose precision.
13458 DiagnoseImpCast(*this, E, T, CC,
13459 diag::warn_impcast_integer_float_precision);
13460 }
13461 }
13462 }
13463
13464 DiagnoseNullConversion(*this, E, T, CC);
13465
13467
13468 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13469 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13470 return;
13471 }
13472
13473 if (Target->isBooleanType())
13474 DiagnoseIntInBoolContext(*this, E);
13475
13477 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13478 << QualType(Source, 0) << QualType(Target, 0);
13479 }
13480
13481 if (!Source->isIntegerType() || !Target->isIntegerType())
13482 return;
13483
13484 // TODO: remove this early return once the false positives for constant->bool
13485 // in templates, macros, etc, are reduced or removed.
13486 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13487 return;
13488
13489 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13490 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13492 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13493 << E->getType());
13494 }
13495 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13496 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13497 if (!LikelySourceRange)
13498 return;
13499
13500 IntRange SourceTypeRange =
13501 IntRange::forTargetOfCanonicalType(Context, Source);
13502 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13503
13504 if (LikelySourceRange->Width > TargetRange.Width) {
13505 // Check if target is a wrapping OBT - if so, don't warn about constant
13506 // conversion as this type may be used intentionally with implicit
13507 // truncation, especially during assignments.
13508 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13509 if (TargetOBT->isWrapKind()) {
13510 return;
13511 }
13512 }
13513
13514 // Check if source expression has an explicit __ob_wrap cast because if so,
13515 // wrapping was explicitly requested and we shouldn't warn
13516 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13517 if (SourceOBT->isWrapKind()) {
13518 return;
13519 }
13520 }
13521
13522 // If the source is a constant, use a default-on diagnostic.
13523 // TODO: this should happen for bitfield stores, too.
13527 llvm::APSInt Value(32);
13528 Value = Result.Val.getInt();
13529
13530 if (SourceMgr.isInSystemMacro(CC))
13531 return;
13532
13533 std::string PrettySourceValue = toString(Value, 10);
13534 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13535
13537 PDiag(diag::warn_impcast_integer_precision_constant)
13538 << PrettySourceValue << PrettyTargetValue
13539 << E->getType() << T << E->getSourceRange()
13540 << SourceRange(CC));
13541 return;
13542 }
13543
13544 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13545 if (SourceMgr.isInSystemMacro(CC))
13546 return;
13547
13548 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13549 if (UO->getOpcode() == UO_Minus)
13550 return DiagnoseImpCast(
13551 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13552 }
13553
13554 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13555 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13556 /* pruneControlFlow */ true);
13557 return DiagnoseImpCast(*this, E, T, CC,
13558 diag::warn_impcast_integer_precision);
13559 }
13560
13561 if (TargetRange.Width > SourceTypeRange.Width) {
13562 if (auto *UO = dyn_cast<UnaryOperator>(E))
13563 if (UO->getOpcode() == UO_Minus)
13564 if (Source->isUnsignedIntegerType()) {
13565 if (Target->isUnsignedIntegerType())
13566 return DiagnoseImpCast(*this, E, T, CC,
13567 diag::warn_impcast_high_order_zero_bits);
13568 if (Target->isSignedIntegerType())
13569 return DiagnoseImpCast(*this, E, T, CC,
13570 diag::warn_impcast_nonnegative_result);
13571 }
13572 }
13573
13574 if (TargetRange.Width == LikelySourceRange->Width &&
13575 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13576 Source->isSignedIntegerType()) {
13577 // Warn when doing a signed to signed conversion, warn if the positive
13578 // source value is exactly the width of the target type, which will
13579 // cause a negative value to be stored.
13580
13583 !SourceMgr.isInSystemMacro(CC)) {
13584 llvm::APSInt Value = Result.Val.getInt();
13585 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13586 std::string PrettySourceValue = toString(Value, 10);
13587 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13588
13589 Diag(E->getExprLoc(),
13590 PDiag(diag::warn_impcast_integer_precision_constant)
13591 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13592 << E->getSourceRange() << SourceRange(CC));
13593 return;
13594 }
13595 }
13596
13597 // Fall through for non-constants to give a sign conversion warning.
13598 }
13599
13600 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13601 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13602 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13603 LikelySourceRange->Width == TargetRange.Width))) {
13604 if (SourceMgr.isInSystemMacro(CC))
13605 return;
13606
13607 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13608 TargetBT->isInteger() &&
13609 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13610 return;
13611 }
13612
13613 unsigned DiagID = diag::warn_impcast_integer_sign;
13614
13615 // Traditionally, gcc has warned about this under -Wsign-compare.
13616 // We also want to warn about it in -Wconversion.
13617 // So if -Wconversion is off, use a completely identical diagnostic
13618 // in the sign-compare group.
13619 // The conditional-checking code will
13620 if (ICContext) {
13621 DiagID = diag::warn_impcast_integer_sign_conditional;
13622 *ICContext = true;
13623 }
13624
13625 DiagnoseImpCast(*this, E, T, CC, DiagID);
13626 }
13627
13628 // If we're implicitly converting from an integer into an enumeration, that
13629 // is valid in C but invalid in C++.
13630 QualType SourceType = E->getEnumCoercedType(Context);
13631 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13632 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13633 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13634
13635 // Diagnose conversions between different enumeration types.
13636 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13637 // type, to give us better diagnostics.
13638 Source = Context.getCanonicalType(SourceType).getTypePtr();
13639
13640 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13641 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13642 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13643 TargetEnum->getDecl()->hasNameForLinkage() &&
13644 SourceEnum != TargetEnum) {
13645 if (SourceMgr.isInSystemMacro(CC))
13646 return;
13647
13648 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13649 diag::warn_impcast_different_enum_types);
13650 }
13651}
13652
13654 SourceLocation CC, QualType T);
13655
13657 SourceLocation CC, bool &ICContext) {
13658 E = E->IgnoreParenImpCasts();
13659 // Diagnose incomplete type for second or third operand in C.
13660 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13661 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13662
13663 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13664 return CheckConditionalOperator(S, CO, CC, T);
13665
13667 if (E->getType() != T)
13668 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13669}
13670
13672 SourceLocation CC, QualType T) {
13674
13675 Expr *TrueExpr = E->getTrueExpr();
13676 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13677 TrueExpr = BCO->getCommon();
13678
13679 bool Suspicious = false;
13680 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13681 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13682
13683 if (T->isBooleanType())
13685
13686 // If -Wconversion would have warned about either of the candidates
13687 // for a signedness conversion to the context type...
13688 if (!Suspicious) return;
13689
13690 // ...but it's currently ignored...
13691 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13692 return;
13693
13694 // ...then check whether it would have warned about either of the
13695 // candidates for a signedness conversion to the condition type.
13696 if (E->getType() == T) return;
13697
13698 Suspicious = false;
13699 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
13700 &Suspicious);
13701 if (!Suspicious)
13703 E->getType(), CC, &Suspicious);
13704}
13705
13706/// Check conversion of given expression to boolean.
13707/// Input argument E is a logical expression.
13709 // Run the bool-like conversion checks only for C since there bools are
13710 // still not used as the return type from "boolean" operators or as the input
13711 // type for conditional operators.
13712 if (S.getLangOpts().CPlusPlus)
13713 return;
13715 return;
13717}
13718
13719namespace {
13720struct AnalyzeImplicitConversionsWorkItem {
13721 Expr *E;
13722 SourceLocation CC;
13723 bool IsListInit;
13724};
13725}
13726
13728 Sema &S, Expr *E, QualType T, SourceLocation CC,
13729 bool ExtraCheckForImplicitConversion,
13731 E = E->IgnoreParenImpCasts();
13732 WorkList.push_back({E, CC, false});
13733
13734 if (ExtraCheckForImplicitConversion && E->getType() != T)
13735 S.CheckImplicitConversion(E, T, CC);
13736}
13737
13738/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13739/// that should be visited are added to WorkList.
13741 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13743 Expr *OrigE = Item.E;
13744 SourceLocation CC = Item.CC;
13745
13746 QualType T = OrigE->getType();
13747 Expr *E = OrigE->IgnoreParenImpCasts();
13748
13749 // Propagate whether we are in a C++ list initialization expression.
13750 // If so, we do not issue warnings for implicit int-float conversion
13751 // precision loss, because C++11 narrowing already handles it.
13752 //
13753 // HLSL's initialization lists are special, so they shouldn't observe the C++
13754 // behavior here.
13755 bool IsListInit =
13756 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
13757 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13758
13759 if (E->isTypeDependent() || E->isValueDependent())
13760 return;
13761
13762 Expr *SourceExpr = E;
13763 // Examine, but don't traverse into the source expression of an
13764 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13765 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13766 // evaluate it in the context of checking the specific conversion to T though.
13767 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13768 if (auto *Src = OVE->getSourceExpr())
13769 SourceExpr = Src;
13770
13771 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13772 if (UO->getOpcode() == UO_Not &&
13773 UO->getSubExpr()->isKnownToHaveBooleanValue())
13774 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13775 << OrigE->getSourceRange() << T->isBooleanType()
13776 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13777
13778 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13779 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13780 BO->getLHS()->isKnownToHaveBooleanValue() &&
13781 BO->getRHS()->isKnownToHaveBooleanValue() &&
13782 BO->getLHS()->HasSideEffects(S.Context) &&
13783 BO->getRHS()->HasSideEffects(S.Context)) {
13785 const LangOptions &LO = S.getLangOpts();
13786 SourceLocation BLoc = BO->getOperatorLoc();
13787 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13788 StringRef SR = clang::Lexer::getSourceText(
13789 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13790 // To reduce false positives, only issue the diagnostic if the operator
13791 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13792 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13793 // in C, along with other macro spellings the user might invent.
13794 if (SR.str() == "&" || SR.str() == "|") {
13795
13796 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13797 << (BO->getOpcode() == BO_And ? "&" : "|")
13798 << OrigE->getSourceRange()
13800 BO->getOperatorLoc(),
13801 (BO->getOpcode() == BO_And ? "&&" : "||"));
13802 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13803 }
13804 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13805 /// Analyze the given comma operator. The basic idea behind the analysis
13806 /// is to analyze the left and right operands slightly differently. The
13807 /// left operand needs to check whether the operand itself has an implicit
13808 /// conversion, but not whether the left operand induces an implicit
13809 /// conversion for the entire comma expression itself. This is similar to
13810 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13811 /// were directly used for the implicit conversion check.
13812 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13813 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13814 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13815 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13816 return;
13817 }
13818 }
13819
13820 // For conditional operators, we analyze the arguments as if they
13821 // were being fed directly into the output.
13822 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13823 CheckConditionalOperator(S, CO, CC, T);
13824 return;
13825 }
13826
13827 // Check implicit argument conversions for function calls.
13828 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13830
13831 // Go ahead and check any implicit conversions we might have skipped.
13832 // The non-canonical typecheck is just an optimization;
13833 // CheckImplicitConversion will filter out dead implicit conversions.
13834 if (SourceExpr->getType() != T)
13835 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13836
13837 // Now continue drilling into this expression.
13838
13839 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13840 // The bound subexpressions in a PseudoObjectExpr are not reachable
13841 // as transitive children.
13842 // FIXME: Use a more uniform representation for this.
13843 for (auto *SE : POE->semantics())
13844 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13845 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13846 }
13847
13848 // Skip past explicit casts.
13849 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13850 E = CE->getSubExpr();
13851 // In the special case of a C++ function-style cast with braces,
13852 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13853 // initializer. This InitListExpr basically belongs to the cast itself, so
13854 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13856 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13857 if (InitListE->getNumInits() == 1) {
13858 E = InitListE->getInit(0);
13859 }
13860 }
13861 }
13862 E = E->IgnoreParenImpCasts();
13863 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13864 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13865 WorkList.push_back({E, CC, IsListInit});
13866 return;
13867 }
13868
13869 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13870 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13871 // The base expression is only used to initialize the parameter for
13872 // arguments to `inout` parameters, so we only traverse down the base
13873 // expression for `inout` cases.
13874 if (OutArgE->isInOut())
13875 WorkList.push_back(
13876 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13877 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13878 return;
13879 }
13880
13881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13882 // Do a somewhat different check with comparison operators.
13883 if (BO->isComparisonOp())
13884 return AnalyzeComparison(S, BO);
13885
13886 // And with simple assignments.
13887 if (BO->getOpcode() == BO_Assign)
13888 return AnalyzeAssignment(S, BO);
13889 // And with compound assignments.
13890 if (BO->isAssignmentOp())
13891 return AnalyzeCompoundAssignment(S, BO);
13892 }
13893
13894 // These break the otherwise-useful invariant below. Fortunately,
13895 // we don't really need to recurse into them, because any internal
13896 // expressions should have been analyzed already when they were
13897 // built into statements.
13898 if (isa<StmtExpr>(E)) return;
13899
13900 // Don't descend into unevaluated contexts.
13901 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13902
13903 // Now just recurse over the expression's children.
13904 CC = E->getExprLoc();
13905 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13906 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13907 for (Stmt *SubStmt : E->children()) {
13908 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13909 if (!ChildExpr)
13910 continue;
13911
13912 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13913 if (ChildExpr == CSE->getOperand())
13914 // Do not recurse over a CoroutineSuspendExpr's operand.
13915 // The operand is also a subexpression of getCommonExpr(), and
13916 // recursing into it directly would produce duplicate diagnostics.
13917 continue;
13918
13919 if (IsLogicalAndOperator &&
13921 // Ignore checking string literals that are in logical and operators.
13922 // This is a common pattern for asserts.
13923 continue;
13924 WorkList.push_back({ChildExpr, CC, IsListInit});
13925 }
13926
13927 if (BO && BO->isLogicalOp()) {
13928 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13929 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13930 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13931
13932 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13933 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13934 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13935 }
13936
13937 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13938 if (U->getOpcode() == UO_LNot) {
13939 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13940 } else if (U->getOpcode() != UO_AddrOf) {
13941 if (U->getSubExpr()->getType()->isAtomicType())
13942 S.Diag(U->getSubExpr()->getBeginLoc(),
13943 diag::warn_atomic_implicit_seq_cst);
13944 }
13945 }
13946}
13947
13948/// AnalyzeImplicitConversions - Find and report any interesting
13949/// implicit conversions in the given expression. There are a couple
13950/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13952 bool IsListInit/*= false*/) {
13954 WorkList.push_back({OrigE, CC, IsListInit});
13955 while (!WorkList.empty())
13956 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13957}
13958
13959// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13960// Returns true when emitting a warning about taking the address of a reference.
13961static bool CheckForReference(Sema &SemaRef, const Expr *E,
13962 const PartialDiagnostic &PD) {
13963 E = E->IgnoreParenImpCasts();
13964
13965 const FunctionDecl *FD = nullptr;
13966
13967 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13968 if (!DRE->getDecl()->getType()->isReferenceType())
13969 return false;
13970 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13971 if (!M->getMemberDecl()->getType()->isReferenceType())
13972 return false;
13973 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13974 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13975 return false;
13976 FD = Call->getDirectCallee();
13977 } else {
13978 return false;
13979 }
13980
13981 SemaRef.Diag(E->getExprLoc(), PD);
13982
13983 // If possible, point to location of function.
13984 if (FD) {
13985 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13986 }
13987
13988 return true;
13989}
13990
13991// Returns true if the SourceLocation is expanded from any macro body.
13992// Returns false if the SourceLocation is invalid, is from not in a macro
13993// expansion, or is from expanded from a top-level macro argument.
13995 if (Loc.isInvalid())
13996 return false;
13997
13998 while (Loc.isMacroID()) {
13999 if (SM.isMacroBodyExpansion(Loc))
14000 return true;
14001 Loc = SM.getImmediateMacroCallerLoc(Loc);
14002 }
14003
14004 return false;
14005}
14006
14009 bool IsEqual, SourceRange Range) {
14010 if (!E)
14011 return;
14012
14013 // Don't warn inside macros.
14014 if (E->getExprLoc().isMacroID()) {
14016 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14017 IsInAnyMacroBody(SM, Range.getBegin()))
14018 return;
14019 }
14020 E = E->IgnoreImpCasts();
14021
14022 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14023
14024 if (isa<CXXThisExpr>(E)) {
14025 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14026 : diag::warn_this_bool_conversion;
14027 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14028 return;
14029 }
14030
14031 bool IsAddressOf = false;
14032
14033 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14034 if (UO->getOpcode() != UO_AddrOf)
14035 return;
14036 IsAddressOf = true;
14037 E = UO->getSubExpr();
14038 }
14039
14040 if (IsAddressOf) {
14041 unsigned DiagID = IsCompare
14042 ? diag::warn_address_of_reference_null_compare
14043 : diag::warn_address_of_reference_bool_conversion;
14044 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14045 << IsEqual;
14046 if (CheckForReference(*this, E, PD)) {
14047 return;
14048 }
14049 }
14050
14051 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14052 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14053 std::string Str;
14054 llvm::raw_string_ostream S(Str);
14055 E->printPretty(S, nullptr, getPrintingPolicy());
14056 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14057 : diag::warn_cast_nonnull_to_bool;
14058 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14059 << E->getSourceRange() << Range << IsEqual;
14060 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14061 };
14062
14063 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14064 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14065 if (auto *Callee = Call->getDirectCallee()) {
14066 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14067 ComplainAboutNonnullParamOrCall(A);
14068 return;
14069 }
14070 }
14071 }
14072
14073 // Complain if we are converting a lambda expression to a boolean value
14074 // outside of instantiation.
14075 if (!inTemplateInstantiation()) {
14076 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14077 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14078 MRecordDecl && MRecordDecl->isLambda()) {
14079 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14080 << /*LambdaPointerConversionOperatorType=*/3
14081 << MRecordDecl->getSourceRange() << Range << IsEqual;
14082 return;
14083 }
14084 }
14085 }
14086
14087 // Expect to find a single Decl. Skip anything more complicated.
14088 ValueDecl *D = nullptr;
14089 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14090 D = R->getDecl();
14091 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14092 D = M->getMemberDecl();
14093 }
14094
14095 // Weak Decls can be null.
14096 if (!D || D->isWeak())
14097 return;
14098
14099 // Check for parameter decl with nonnull attribute
14100 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14101 if (getCurFunction() &&
14102 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14103 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14104 ComplainAboutNonnullParamOrCall(A);
14105 return;
14106 }
14107
14108 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14109 // Skip function template not specialized yet.
14111 return;
14112 auto ParamIter = llvm::find(FD->parameters(), PV);
14113 assert(ParamIter != FD->param_end());
14114 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14115
14116 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14117 if (!NonNull->args_size()) {
14118 ComplainAboutNonnullParamOrCall(NonNull);
14119 return;
14120 }
14121
14122 for (const ParamIdx &ArgNo : NonNull->args()) {
14123 if (ArgNo.getASTIndex() == ParamNo) {
14124 ComplainAboutNonnullParamOrCall(NonNull);
14125 return;
14126 }
14127 }
14128 }
14129 }
14130 }
14131 }
14132
14133 QualType T = D->getType();
14134 const bool IsArray = T->isArrayType();
14135 const bool IsFunction = T->isFunctionType();
14136
14137 // Address of function is used to silence the function warning.
14138 if (IsAddressOf && IsFunction) {
14139 return;
14140 }
14141
14142 // Found nothing.
14143 if (!IsAddressOf && !IsFunction && !IsArray)
14144 return;
14145
14146 // Pretty print the expression for the diagnostic.
14147 std::string Str;
14148 llvm::raw_string_ostream S(Str);
14149 E->printPretty(S, nullptr, getPrintingPolicy());
14150
14151 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14152 : diag::warn_impcast_pointer_to_bool;
14153 enum {
14154 AddressOf,
14155 FunctionPointer,
14156 ArrayPointer
14157 } DiagType;
14158 if (IsAddressOf)
14159 DiagType = AddressOf;
14160 else if (IsFunction)
14161 DiagType = FunctionPointer;
14162 else if (IsArray)
14163 DiagType = ArrayPointer;
14164 else
14165 llvm_unreachable("Could not determine diagnostic.");
14166 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14167 << Range << IsEqual;
14168
14169 if (!IsFunction)
14170 return;
14171
14172 // Suggest '&' to silence the function warning.
14173 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14175
14176 // Check to see if '()' fixit should be emitted.
14177 QualType ReturnType;
14178 UnresolvedSet<4> NonTemplateOverloads;
14179 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14180 if (ReturnType.isNull())
14181 return;
14182
14183 if (IsCompare) {
14184 // There are two cases here. If there is null constant, the only suggest
14185 // for a pointer return type. If the null is 0, then suggest if the return
14186 // type is a pointer or an integer type.
14187 if (!ReturnType->isPointerType()) {
14188 if (NullKind == Expr::NPCK_ZeroExpression ||
14189 NullKind == Expr::NPCK_ZeroLiteral) {
14190 if (!ReturnType->isIntegerType())
14191 return;
14192 } else {
14193 return;
14194 }
14195 }
14196 } else { // !IsCompare
14197 // For function to bool, only suggest if the function pointer has bool
14198 // return type.
14199 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14200 return;
14201 }
14202 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14204}
14205
14207 SourceLocation CC) {
14208 QualType Source = E->getType();
14209 QualType Target = T;
14210
14211 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14212 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14213 // Overflow behavior type is being stripped - issue warning
14214 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14215 Target->isUnsignedIntegerType()) {
14216 // For unsigned wrap to unsigned conversions, use pedantic version
14217 unsigned DiagId =
14219 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14220 : diag::warn_impcast_overflow_behavior_pedantic;
14221 DiagnoseImpCast(*this, E, T, CC, DiagId);
14222 } else {
14223 unsigned DiagId = InOverflowBehaviorAssignmentContext
14224 ? diag::warn_impcast_overflow_behavior_assignment
14225 : diag::warn_impcast_overflow_behavior;
14226 DiagnoseImpCast(*this, E, T, CC, DiagId);
14227 }
14228 }
14229 }
14230
14231 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14232 if (TargetOBT->isWrapKind()) {
14233 return true;
14234 }
14235 }
14236
14237 return false;
14238}
14239
14240void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14241 // Don't diagnose in unevaluated contexts.
14243 return;
14244
14245 // Don't diagnose for value- or type-dependent expressions.
14246 if (E->isTypeDependent() || E->isValueDependent())
14247 return;
14248
14249 // Check for array bounds violations in cases where the check isn't triggered
14250 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14251 // ArraySubscriptExpr is on the RHS of a variable initialization.
14252 CheckArrayAccess(E);
14253
14254 // This is not the right CC for (e.g.) a variable initialization.
14255 AnalyzeImplicitConversions(*this, E, CC);
14256}
14257
14258void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14259 ::CheckBoolLikeConversion(*this, E, CC);
14260}
14261
14262void Sema::CheckForIntOverflow (const Expr *E) {
14263 // Use a work list to deal with nested struct initializers.
14264 SmallVector<const Expr *, 2> Exprs(1, E);
14265
14266 do {
14267 const Expr *OriginalE = Exprs.pop_back_val();
14268 const Expr *E = OriginalE->IgnoreParenCasts();
14269
14272 continue;
14273 }
14274
14275 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14276 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14277 else if (isa<ObjCBoxedExpr>(OriginalE))
14279 else if (const auto *Call = dyn_cast<CallExpr>(E))
14280 Exprs.append(Call->arg_begin(), Call->arg_end());
14281 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14282 Exprs.append(Message->arg_begin(), Message->arg_end());
14283 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14284 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14285 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14286 Exprs.push_back(Temporary->getSubExpr());
14287 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14288 Exprs.push_back(Array->getIdx());
14289 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14290 Exprs.push_back(Compound->getInitializer());
14291 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14292 New && New->isArray()) {
14293 if (auto ArraySize = New->getArraySize())
14294 Exprs.push_back(*ArraySize);
14295 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14296 Exprs.push_back(MTE->getSubExpr());
14297 } while (!Exprs.empty());
14298}
14299
14300namespace {
14301
14302/// Visitor for expressions which looks for unsequenced operations on the
14303/// same object.
14304class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14305 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14306
14307 /// A tree of sequenced regions within an expression. Two regions are
14308 /// unsequenced if one is an ancestor or a descendent of the other. When we
14309 /// finish processing an expression with sequencing, such as a comma
14310 /// expression, we fold its tree nodes into its parent, since they are
14311 /// unsequenced with respect to nodes we will visit later.
14312 class SequenceTree {
14313 struct Value {
14314 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14315 unsigned Parent : 31;
14316 LLVM_PREFERRED_TYPE(bool)
14317 unsigned Merged : 1;
14318 };
14319 SmallVector<Value, 8> Values;
14320
14321 public:
14322 /// A region within an expression which may be sequenced with respect
14323 /// to some other region.
14324 class Seq {
14325 friend class SequenceTree;
14326
14327 unsigned Index;
14328
14329 explicit Seq(unsigned N) : Index(N) {}
14330
14331 public:
14332 Seq() : Index(0) {}
14333 };
14334
14335 SequenceTree() { Values.push_back(Value(0)); }
14336 Seq root() const { return Seq(0); }
14337
14338 /// Create a new sequence of operations, which is an unsequenced
14339 /// subset of \p Parent. This sequence of operations is sequenced with
14340 /// respect to other children of \p Parent.
14341 Seq allocate(Seq Parent) {
14342 Values.push_back(Value(Parent.Index));
14343 return Seq(Values.size() - 1);
14344 }
14345
14346 /// Merge a sequence of operations into its parent.
14347 void merge(Seq S) {
14348 Values[S.Index].Merged = true;
14349 }
14350
14351 /// Determine whether two operations are unsequenced. This operation
14352 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14353 /// should have been merged into its parent as appropriate.
14354 bool isUnsequenced(Seq Cur, Seq Old) {
14355 unsigned C = representative(Cur.Index);
14356 unsigned Target = representative(Old.Index);
14357 while (C >= Target) {
14358 if (C == Target)
14359 return true;
14360 C = Values[C].Parent;
14361 }
14362 return false;
14363 }
14364
14365 private:
14366 /// Pick a representative for a sequence.
14367 unsigned representative(unsigned K) {
14368 if (Values[K].Merged)
14369 // Perform path compression as we go.
14370 return Values[K].Parent = representative(Values[K].Parent);
14371 return K;
14372 }
14373 };
14374
14375 /// An object for which we can track unsequenced uses.
14376 using Object = const NamedDecl *;
14377
14378 /// Different flavors of object usage which we track. We only track the
14379 /// least-sequenced usage of each kind.
14380 enum UsageKind {
14381 /// A read of an object. Multiple unsequenced reads are OK.
14382 UK_Use,
14383
14384 /// A modification of an object which is sequenced before the value
14385 /// computation of the expression, such as ++n in C++.
14386 UK_ModAsValue,
14387
14388 /// A modification of an object which is not sequenced before the value
14389 /// computation of the expression, such as n++.
14390 UK_ModAsSideEffect,
14391
14392 UK_Count = UK_ModAsSideEffect + 1
14393 };
14394
14395 /// Bundle together a sequencing region and the expression corresponding
14396 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14397 struct Usage {
14398 const Expr *UsageExpr = nullptr;
14399 SequenceTree::Seq Seq;
14400
14401 Usage() = default;
14402 };
14403
14404 struct UsageInfo {
14405 Usage Uses[UK_Count];
14406
14407 /// Have we issued a diagnostic for this object already?
14408 bool Diagnosed = false;
14409
14410 UsageInfo();
14411 };
14412 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14413
14414 Sema &SemaRef;
14415
14416 /// Sequenced regions within the expression.
14417 SequenceTree Tree;
14418
14419 /// Declaration modifications and references which we have seen.
14420 UsageInfoMap UsageMap;
14421
14422 /// The region we are currently within.
14423 SequenceTree::Seq Region;
14424
14425 /// Filled in with declarations which were modified as a side-effect
14426 /// (that is, post-increment operations).
14427 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14428
14429 /// Expressions to check later. We defer checking these to reduce
14430 /// stack usage.
14431 SmallVectorImpl<const Expr *> &WorkList;
14432
14433 /// RAII object wrapping the visitation of a sequenced subexpression of an
14434 /// expression. At the end of this process, the side-effects of the evaluation
14435 /// become sequenced with respect to the value computation of the result, so
14436 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14437 /// UK_ModAsValue.
14438 struct SequencedSubexpression {
14439 SequencedSubexpression(SequenceChecker &Self)
14440 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14441 Self.ModAsSideEffect = &ModAsSideEffect;
14442 }
14443
14444 ~SequencedSubexpression() {
14445 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14446 // Add a new usage with usage kind UK_ModAsValue, and then restore
14447 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14448 // the previous one was empty).
14449 UsageInfo &UI = Self.UsageMap[M.first];
14450 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14451 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14452 SideEffectUsage = M.second;
14453 }
14454 Self.ModAsSideEffect = OldModAsSideEffect;
14455 }
14456
14457 SequenceChecker &Self;
14458 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14459 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14460 };
14461
14462 /// RAII object wrapping the visitation of a subexpression which we might
14463 /// choose to evaluate as a constant. If any subexpression is evaluated and
14464 /// found to be non-constant, this allows us to suppress the evaluation of
14465 /// the outer expression.
14466 class EvaluationTracker {
14467 public:
14468 EvaluationTracker(SequenceChecker &Self)
14469 : Self(Self), Prev(Self.EvalTracker) {
14470 Self.EvalTracker = this;
14471 }
14472
14473 ~EvaluationTracker() {
14474 Self.EvalTracker = Prev;
14475 if (Prev)
14476 Prev->EvalOK &= EvalOK;
14477 }
14478
14479 bool evaluate(const Expr *E, bool &Result) {
14480 if (!EvalOK || E->isValueDependent())
14481 return false;
14482 EvalOK = E->EvaluateAsBooleanCondition(
14483 Result, Self.SemaRef.Context,
14484 Self.SemaRef.isConstantEvaluatedContext());
14485 return EvalOK;
14486 }
14487
14488 private:
14489 SequenceChecker &Self;
14490 EvaluationTracker *Prev;
14491 bool EvalOK = true;
14492 } *EvalTracker = nullptr;
14493
14494 /// Find the object which is produced by the specified expression,
14495 /// if any.
14496 Object getObject(const Expr *E, bool Mod) const {
14497 E = E->IgnoreParenCasts();
14498 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14499 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14500 return getObject(UO->getSubExpr(), Mod);
14501 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14502 if (BO->getOpcode() == BO_Comma)
14503 return getObject(BO->getRHS(), Mod);
14504 if (Mod && BO->isAssignmentOp())
14505 return getObject(BO->getLHS(), Mod);
14506 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14507 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14508 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14509 return ME->getMemberDecl();
14510 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14511 // FIXME: If this is a reference, map through to its value.
14512 return DRE->getDecl();
14513 return nullptr;
14514 }
14515
14516 /// Note that an object \p O was modified or used by an expression
14517 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14518 /// the object \p O as obtained via the \p UsageMap.
14519 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14520 // Get the old usage for the given object and usage kind.
14521 Usage &U = UI.Uses[UK];
14522 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14523 // If we have a modification as side effect and are in a sequenced
14524 // subexpression, save the old Usage so that we can restore it later
14525 // in SequencedSubexpression::~SequencedSubexpression.
14526 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14527 ModAsSideEffect->push_back(std::make_pair(O, U));
14528 // Then record the new usage with the current sequencing region.
14529 U.UsageExpr = UsageExpr;
14530 U.Seq = Region;
14531 }
14532 }
14533
14534 /// Check whether a modification or use of an object \p O in an expression
14535 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14536 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14537 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14538 /// usage and false we are checking for a mod-use unsequenced usage.
14539 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14540 UsageKind OtherKind, bool IsModMod) {
14541 if (UI.Diagnosed)
14542 return;
14543
14544 const Usage &U = UI.Uses[OtherKind];
14545 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14546 return;
14547
14548 const Expr *Mod = U.UsageExpr;
14549 const Expr *ModOrUse = UsageExpr;
14550 if (OtherKind == UK_Use)
14551 std::swap(Mod, ModOrUse);
14552
14553 SemaRef.DiagRuntimeBehavior(
14554 Mod->getExprLoc(), {Mod, ModOrUse},
14555 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14556 : diag::warn_unsequenced_mod_use)
14557 << O << SourceRange(ModOrUse->getExprLoc()));
14558 UI.Diagnosed = true;
14559 }
14560
14561 // A note on note{Pre, Post}{Use, Mod}:
14562 //
14563 // (It helps to follow the algorithm with an expression such as
14564 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14565 // operations before C++17 and both are well-defined in C++17).
14566 //
14567 // When visiting a node which uses/modify an object we first call notePreUse
14568 // or notePreMod before visiting its sub-expression(s). At this point the
14569 // children of the current node have not yet been visited and so the eventual
14570 // uses/modifications resulting from the children of the current node have not
14571 // been recorded yet.
14572 //
14573 // We then visit the children of the current node. After that notePostUse or
14574 // notePostMod is called. These will 1) detect an unsequenced modification
14575 // as side effect (as in "k++ + k") and 2) add a new usage with the
14576 // appropriate usage kind.
14577 //
14578 // We also have to be careful that some operation sequences modification as
14579 // side effect as well (for example: || or ,). To account for this we wrap
14580 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14581 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14582 // which record usages which are modifications as side effect, and then
14583 // downgrade them (or more accurately restore the previous usage which was a
14584 // modification as side effect) when exiting the scope of the sequenced
14585 // subexpression.
14586
14587 void notePreUse(Object O, const Expr *UseExpr) {
14588 UsageInfo &UI = UsageMap[O];
14589 // Uses conflict with other modifications.
14590 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14591 }
14592
14593 void notePostUse(Object O, const Expr *UseExpr) {
14594 UsageInfo &UI = UsageMap[O];
14595 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14596 /*IsModMod=*/false);
14597 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14598 }
14599
14600 void notePreMod(Object O, const Expr *ModExpr) {
14601 UsageInfo &UI = UsageMap[O];
14602 // Modifications conflict with other modifications and with uses.
14603 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14604 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14605 }
14606
14607 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14608 UsageInfo &UI = UsageMap[O];
14609 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14610 /*IsModMod=*/true);
14611 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14612 }
14613
14614public:
14615 SequenceChecker(Sema &S, const Expr *E,
14616 SmallVectorImpl<const Expr *> &WorkList)
14617 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14618 Visit(E);
14619 // Silence a -Wunused-private-field since WorkList is now unused.
14620 // TODO: Evaluate if it can be used, and if not remove it.
14621 (void)this->WorkList;
14622 }
14623
14624 void VisitStmt(const Stmt *S) {
14625 // Skip all statements which aren't expressions for now.
14626 }
14627
14628 void VisitExpr(const Expr *E) {
14629 // By default, just recurse to evaluated subexpressions.
14630 Base::VisitStmt(E);
14631 }
14632
14633 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14634 for (auto *Sub : CSE->children()) {
14635 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14636 if (!ChildExpr)
14637 continue;
14638
14639 if (ChildExpr == CSE->getOperand())
14640 // Do not recurse over a CoroutineSuspendExpr's operand.
14641 // The operand is also a subexpression of getCommonExpr(), and
14642 // recursing into it directly could confuse object management
14643 // for the sake of sequence tracking.
14644 continue;
14645
14646 Visit(Sub);
14647 }
14648 }
14649
14650 void VisitCastExpr(const CastExpr *E) {
14651 Object O = Object();
14652 if (E->getCastKind() == CK_LValueToRValue)
14653 O = getObject(E->getSubExpr(), false);
14654
14655 if (O)
14656 notePreUse(O, E);
14657 VisitExpr(E);
14658 if (O)
14659 notePostUse(O, E);
14660 }
14661
14662 void VisitSequencedExpressions(const Expr *SequencedBefore,
14663 const Expr *SequencedAfter) {
14664 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14665 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14666 SequenceTree::Seq OldRegion = Region;
14667
14668 {
14669 SequencedSubexpression SeqBefore(*this);
14670 Region = BeforeRegion;
14671 Visit(SequencedBefore);
14672 }
14673
14674 Region = AfterRegion;
14675 Visit(SequencedAfter);
14676
14677 Region = OldRegion;
14678
14679 Tree.merge(BeforeRegion);
14680 Tree.merge(AfterRegion);
14681 }
14682
14683 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14684 // C++17 [expr.sub]p1:
14685 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14686 // expression E1 is sequenced before the expression E2.
14687 if (SemaRef.getLangOpts().CPlusPlus17)
14688 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14689 else {
14690 Visit(ASE->getLHS());
14691 Visit(ASE->getRHS());
14692 }
14693 }
14694
14695 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14696 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14697 void VisitBinPtrMem(const BinaryOperator *BO) {
14698 // C++17 [expr.mptr.oper]p4:
14699 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14700 // the expression E1 is sequenced before the expression E2.
14701 if (SemaRef.getLangOpts().CPlusPlus17)
14702 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14703 else {
14704 Visit(BO->getLHS());
14705 Visit(BO->getRHS());
14706 }
14707 }
14708
14709 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14710 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14711 void VisitBinShlShr(const BinaryOperator *BO) {
14712 // C++17 [expr.shift]p4:
14713 // The expression E1 is sequenced before the expression E2.
14714 if (SemaRef.getLangOpts().CPlusPlus17)
14715 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14716 else {
14717 Visit(BO->getLHS());
14718 Visit(BO->getRHS());
14719 }
14720 }
14721
14722 void VisitBinComma(const BinaryOperator *BO) {
14723 // C++11 [expr.comma]p1:
14724 // Every value computation and side effect associated with the left
14725 // expression is sequenced before every value computation and side
14726 // effect associated with the right expression.
14727 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14728 }
14729
14730 void VisitBinAssign(const BinaryOperator *BO) {
14731 SequenceTree::Seq RHSRegion;
14732 SequenceTree::Seq LHSRegion;
14733 if (SemaRef.getLangOpts().CPlusPlus17) {
14734 RHSRegion = Tree.allocate(Region);
14735 LHSRegion = Tree.allocate(Region);
14736 } else {
14737 RHSRegion = Region;
14738 LHSRegion = Region;
14739 }
14740 SequenceTree::Seq OldRegion = Region;
14741
14742 // C++11 [expr.ass]p1:
14743 // [...] the assignment is sequenced after the value computation
14744 // of the right and left operands, [...]
14745 //
14746 // so check it before inspecting the operands and update the
14747 // map afterwards.
14748 Object O = getObject(BO->getLHS(), /*Mod=*/true);
14749 if (O)
14750 notePreMod(O, BO);
14751
14752 if (SemaRef.getLangOpts().CPlusPlus17) {
14753 // C++17 [expr.ass]p1:
14754 // [...] The right operand is sequenced before the left operand. [...]
14755 {
14756 SequencedSubexpression SeqBefore(*this);
14757 Region = RHSRegion;
14758 Visit(BO->getRHS());
14759 }
14760
14761 Region = LHSRegion;
14762 Visit(BO->getLHS());
14763
14764 if (O && isa<CompoundAssignOperator>(BO))
14765 notePostUse(O, BO);
14766
14767 } else {
14768 // C++11 does not specify any sequencing between the LHS and RHS.
14769 Region = LHSRegion;
14770 Visit(BO->getLHS());
14771
14772 if (O && isa<CompoundAssignOperator>(BO))
14773 notePostUse(O, BO);
14774
14775 Region = RHSRegion;
14776 Visit(BO->getRHS());
14777 }
14778
14779 // C++11 [expr.ass]p1:
14780 // the assignment is sequenced [...] before the value computation of the
14781 // assignment expression.
14782 // C11 6.5.16/3 has no such rule.
14783 Region = OldRegion;
14784 if (O)
14785 notePostMod(O, BO,
14786 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14787 : UK_ModAsSideEffect);
14788 if (SemaRef.getLangOpts().CPlusPlus17) {
14789 Tree.merge(RHSRegion);
14790 Tree.merge(LHSRegion);
14791 }
14792 }
14793
14794 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14795 VisitBinAssign(CAO);
14796 }
14797
14798 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14799 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14800 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14801 Object O = getObject(UO->getSubExpr(), true);
14802 if (!O)
14803 return VisitExpr(UO);
14804
14805 notePreMod(O, UO);
14806 Visit(UO->getSubExpr());
14807 // C++11 [expr.pre.incr]p1:
14808 // the expression ++x is equivalent to x+=1
14809 notePostMod(O, UO,
14810 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14811 : UK_ModAsSideEffect);
14812 }
14813
14814 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14815 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14816 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14817 Object O = getObject(UO->getSubExpr(), true);
14818 if (!O)
14819 return VisitExpr(UO);
14820
14821 notePreMod(O, UO);
14822 Visit(UO->getSubExpr());
14823 notePostMod(O, UO, UK_ModAsSideEffect);
14824 }
14825
14826 void VisitBinLOr(const BinaryOperator *BO) {
14827 // C++11 [expr.log.or]p2:
14828 // If the second expression is evaluated, every value computation and
14829 // side effect associated with the first expression is sequenced before
14830 // every value computation and side effect associated with the
14831 // second expression.
14832 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14833 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14834 SequenceTree::Seq OldRegion = Region;
14835
14836 EvaluationTracker Eval(*this);
14837 {
14838 SequencedSubexpression Sequenced(*this);
14839 Region = LHSRegion;
14840 Visit(BO->getLHS());
14841 }
14842
14843 // C++11 [expr.log.or]p1:
14844 // [...] the second operand is not evaluated if the first operand
14845 // evaluates to true.
14846 bool EvalResult = false;
14847 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14848 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14849 if (ShouldVisitRHS) {
14850 Region = RHSRegion;
14851 Visit(BO->getRHS());
14852 }
14853
14854 Region = OldRegion;
14855 Tree.merge(LHSRegion);
14856 Tree.merge(RHSRegion);
14857 }
14858
14859 void VisitBinLAnd(const BinaryOperator *BO) {
14860 // C++11 [expr.log.and]p2:
14861 // If the second expression is evaluated, every value computation and
14862 // side effect associated with the first expression is sequenced before
14863 // every value computation and side effect associated with the
14864 // second expression.
14865 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14866 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14867 SequenceTree::Seq OldRegion = Region;
14868
14869 EvaluationTracker Eval(*this);
14870 {
14871 SequencedSubexpression Sequenced(*this);
14872 Region = LHSRegion;
14873 Visit(BO->getLHS());
14874 }
14875
14876 // C++11 [expr.log.and]p1:
14877 // [...] the second operand is not evaluated if the first operand is false.
14878 bool EvalResult = false;
14879 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14880 bool ShouldVisitRHS = !EvalOK || EvalResult;
14881 if (ShouldVisitRHS) {
14882 Region = RHSRegion;
14883 Visit(BO->getRHS());
14884 }
14885
14886 Region = OldRegion;
14887 Tree.merge(LHSRegion);
14888 Tree.merge(RHSRegion);
14889 }
14890
14891 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14892 // C++11 [expr.cond]p1:
14893 // [...] Every value computation and side effect associated with the first
14894 // expression is sequenced before every value computation and side effect
14895 // associated with the second or third expression.
14896 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14897
14898 // No sequencing is specified between the true and false expression.
14899 // However since exactly one of both is going to be evaluated we can
14900 // consider them to be sequenced. This is needed to avoid warning on
14901 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14902 // both the true and false expressions because we can't evaluate x.
14903 // This will still allow us to detect an expression like (pre C++17)
14904 // "(x ? y += 1 : y += 2) = y".
14905 //
14906 // We don't wrap the visitation of the true and false expression with
14907 // SequencedSubexpression because we don't want to downgrade modifications
14908 // as side effect in the true and false expressions after the visition
14909 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14910 // not warn between the two "y++", but we should warn between the "y++"
14911 // and the "y".
14912 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14913 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14914 SequenceTree::Seq OldRegion = Region;
14915
14916 EvaluationTracker Eval(*this);
14917 {
14918 SequencedSubexpression Sequenced(*this);
14919 Region = ConditionRegion;
14920 Visit(CO->getCond());
14921 }
14922
14923 // C++11 [expr.cond]p1:
14924 // [...] The first expression is contextually converted to bool (Clause 4).
14925 // It is evaluated and if it is true, the result of the conditional
14926 // expression is the value of the second expression, otherwise that of the
14927 // third expression. Only one of the second and third expressions is
14928 // evaluated. [...]
14929 bool EvalResult = false;
14930 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14931 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14932 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14933 if (ShouldVisitTrueExpr) {
14934 Region = TrueRegion;
14935 Visit(CO->getTrueExpr());
14936 }
14937 if (ShouldVisitFalseExpr) {
14938 Region = FalseRegion;
14939 Visit(CO->getFalseExpr());
14940 }
14941
14942 Region = OldRegion;
14943 Tree.merge(ConditionRegion);
14944 Tree.merge(TrueRegion);
14945 Tree.merge(FalseRegion);
14946 }
14947
14948 void VisitCallExpr(const CallExpr *CE) {
14949 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14950
14951 if (CE->isUnevaluatedBuiltinCall(Context))
14952 return;
14953
14954 // C++11 [intro.execution]p15:
14955 // When calling a function [...], every value computation and side effect
14956 // associated with any argument expression, or with the postfix expression
14957 // designating the called function, is sequenced before execution of every
14958 // expression or statement in the body of the function [and thus before
14959 // the value computation of its result].
14960 SequencedSubexpression Sequenced(*this);
14961 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14962 // C++17 [expr.call]p5
14963 // The postfix-expression is sequenced before each expression in the
14964 // expression-list and any default argument. [...]
14965 SequenceTree::Seq CalleeRegion;
14966 SequenceTree::Seq OtherRegion;
14967 if (SemaRef.getLangOpts().CPlusPlus17) {
14968 CalleeRegion = Tree.allocate(Region);
14969 OtherRegion = Tree.allocate(Region);
14970 } else {
14971 CalleeRegion = Region;
14972 OtherRegion = Region;
14973 }
14974 SequenceTree::Seq OldRegion = Region;
14975
14976 // Visit the callee expression first.
14977 Region = CalleeRegion;
14978 if (SemaRef.getLangOpts().CPlusPlus17) {
14979 SequencedSubexpression Sequenced(*this);
14980 Visit(CE->getCallee());
14981 } else {
14982 Visit(CE->getCallee());
14983 }
14984
14985 // Then visit the argument expressions.
14986 Region = OtherRegion;
14987 for (const Expr *Argument : CE->arguments())
14988 Visit(Argument);
14989
14990 Region = OldRegion;
14991 if (SemaRef.getLangOpts().CPlusPlus17) {
14992 Tree.merge(CalleeRegion);
14993 Tree.merge(OtherRegion);
14994 }
14995 });
14996 }
14997
14998 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14999 // C++17 [over.match.oper]p2:
15000 // [...] the operator notation is first transformed to the equivalent
15001 // function-call notation as summarized in Table 12 (where @ denotes one
15002 // of the operators covered in the specified subclause). However, the
15003 // operands are sequenced in the order prescribed for the built-in
15004 // operator (Clause 8).
15005 //
15006 // From the above only overloaded binary operators and overloaded call
15007 // operators have sequencing rules in C++17 that we need to handle
15008 // separately.
15009 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15010 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15011 return VisitCallExpr(CXXOCE);
15012
15013 enum {
15014 NoSequencing,
15015 LHSBeforeRHS,
15016 RHSBeforeLHS,
15017 LHSBeforeRest
15018 } SequencingKind;
15019 switch (CXXOCE->getOperator()) {
15020 case OO_Equal:
15021 case OO_PlusEqual:
15022 case OO_MinusEqual:
15023 case OO_StarEqual:
15024 case OO_SlashEqual:
15025 case OO_PercentEqual:
15026 case OO_CaretEqual:
15027 case OO_AmpEqual:
15028 case OO_PipeEqual:
15029 case OO_LessLessEqual:
15030 case OO_GreaterGreaterEqual:
15031 SequencingKind = RHSBeforeLHS;
15032 break;
15033
15034 case OO_LessLess:
15035 case OO_GreaterGreater:
15036 case OO_AmpAmp:
15037 case OO_PipePipe:
15038 case OO_Comma:
15039 case OO_ArrowStar:
15040 case OO_Subscript:
15041 SequencingKind = LHSBeforeRHS;
15042 break;
15043
15044 case OO_Call:
15045 SequencingKind = LHSBeforeRest;
15046 break;
15047
15048 default:
15049 SequencingKind = NoSequencing;
15050 break;
15051 }
15052
15053 if (SequencingKind == NoSequencing)
15054 return VisitCallExpr(CXXOCE);
15055
15056 // This is a call, so all subexpressions are sequenced before the result.
15057 SequencedSubexpression Sequenced(*this);
15058
15059 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15060 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15061 "Should only get there with C++17 and above!");
15062 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15063 "Should only get there with an overloaded binary operator"
15064 " or an overloaded call operator!");
15065
15066 if (SequencingKind == LHSBeforeRest) {
15067 assert(CXXOCE->getOperator() == OO_Call &&
15068 "We should only have an overloaded call operator here!");
15069
15070 // This is very similar to VisitCallExpr, except that we only have the
15071 // C++17 case. The postfix-expression is the first argument of the
15072 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15073 // are in the following arguments.
15074 //
15075 // Note that we intentionally do not visit the callee expression since
15076 // it is just a decayed reference to a function.
15077 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15078 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15079 SequenceTree::Seq OldRegion = Region;
15080
15081 assert(CXXOCE->getNumArgs() >= 1 &&
15082 "An overloaded call operator must have at least one argument"
15083 " for the postfix-expression!");
15084 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15085 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15086 CXXOCE->getNumArgs() - 1);
15087
15088 // Visit the postfix-expression first.
15089 {
15090 Region = PostfixExprRegion;
15091 SequencedSubexpression Sequenced(*this);
15092 Visit(PostfixExpr);
15093 }
15094
15095 // Then visit the argument expressions.
15096 Region = ArgsRegion;
15097 for (const Expr *Arg : Args)
15098 Visit(Arg);
15099
15100 Region = OldRegion;
15101 Tree.merge(PostfixExprRegion);
15102 Tree.merge(ArgsRegion);
15103 } else {
15104 assert(CXXOCE->getNumArgs() == 2 &&
15105 "Should only have two arguments here!");
15106 assert((SequencingKind == LHSBeforeRHS ||
15107 SequencingKind == RHSBeforeLHS) &&
15108 "Unexpected sequencing kind!");
15109
15110 // We do not visit the callee expression since it is just a decayed
15111 // reference to a function.
15112 const Expr *E1 = CXXOCE->getArg(0);
15113 const Expr *E2 = CXXOCE->getArg(1);
15114 if (SequencingKind == RHSBeforeLHS)
15115 std::swap(E1, E2);
15116
15117 return VisitSequencedExpressions(E1, E2);
15118 }
15119 });
15120 }
15121
15122 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15123 // This is a call, so all subexpressions are sequenced before the result.
15124 SequencedSubexpression Sequenced(*this);
15125
15126 if (!CCE->isListInitialization())
15127 return VisitExpr(CCE);
15128
15129 // In C++11, list initializations are sequenced.
15130 SequenceExpressionsInOrder(
15131 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15132 }
15133
15134 void VisitInitListExpr(const InitListExpr *ILE) {
15135 if (!SemaRef.getLangOpts().CPlusPlus11)
15136 return VisitExpr(ILE);
15137
15138 // In C++11, list initializations are sequenced.
15139 SequenceExpressionsInOrder(ILE->inits());
15140 }
15141
15142 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15143 // C++20 parenthesized list initializations are sequenced. See C++20
15144 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15145 SequenceExpressionsInOrder(PLIE->getInitExprs());
15146 }
15147
15148private:
15149 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15151 SequenceTree::Seq Parent = Region;
15152 for (const Expr *E : ExpressionList) {
15153 if (!E)
15154 continue;
15155 Region = Tree.allocate(Parent);
15156 Elts.push_back(Region);
15157 Visit(E);
15158 }
15159
15160 // Forget that the initializers are sequenced.
15161 Region = Parent;
15162 for (unsigned I = 0; I < Elts.size(); ++I)
15163 Tree.merge(Elts[I]);
15164 }
15165};
15166
15167SequenceChecker::UsageInfo::UsageInfo() = default;
15168
15169} // namespace
15170
15171void Sema::CheckUnsequencedOperations(const Expr *E) {
15172 SmallVector<const Expr *, 8> WorkList;
15173 WorkList.push_back(E);
15174 while (!WorkList.empty()) {
15175 const Expr *Item = WorkList.pop_back_val();
15176 SequenceChecker(*this, Item, WorkList);
15177 }
15178}
15179
15180void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15181 bool IsConstexpr) {
15182 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15183 IsConstexpr || isa<ConstantExpr>(E));
15184 CheckImplicitConversions(E, CheckLoc);
15185 if (!E->isInstantiationDependent())
15186 CheckUnsequencedOperations(E);
15187 if (!IsConstexpr && !E->isValueDependent())
15188 CheckForIntOverflow(E);
15189}
15190
15191void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15192 FieldDecl *BitField,
15193 Expr *Init) {
15194 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15195}
15196
15198 SourceLocation Loc) {
15199 if (!PType->isVariablyModifiedType())
15200 return;
15201 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15202 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15203 return;
15204 }
15205 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15206 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15207 return;
15208 }
15209 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15210 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15211 return;
15212 }
15213
15214 const ArrayType *AT = S.Context.getAsArrayType(PType);
15215 if (!AT)
15216 return;
15217
15220 return;
15221 }
15222
15223 S.Diag(Loc, diag::err_array_star_in_function_definition);
15224}
15225
15227 bool CheckParameterNames) {
15228 bool HasInvalidParm = false;
15229 for (ParmVarDecl *Param : Parameters) {
15230 assert(Param && "null in a parameter list");
15231 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15232 // function declarator that is part of a function definition of
15233 // that function shall not have incomplete type.
15234 //
15235 // C++23 [dcl.fct.def.general]/p2
15236 // The type of a parameter [...] for a function definition
15237 // shall not be a (possibly cv-qualified) class type that is incomplete
15238 // or abstract within the function body unless the function is deleted.
15239 if (!Param->isInvalidDecl() &&
15240 (RequireCompleteType(Param->getLocation(), Param->getType(),
15241 diag::err_typecheck_decl_incomplete_type) ||
15242 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15243 diag::err_abstract_type_in_decl,
15245 Param->setInvalidDecl();
15246 HasInvalidParm = true;
15247 }
15248
15249 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15250 // declaration of each parameter shall include an identifier.
15251 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15252 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15253 // Diagnose this as an extension in C17 and earlier.
15254 if (!getLangOpts().C23)
15255 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15256 }
15257
15258 // C99 6.7.5.3p12:
15259 // If the function declarator is not part of a definition of that
15260 // function, parameters may have incomplete type and may use the [*]
15261 // notation in their sequences of declarator specifiers to specify
15262 // variable length array types.
15263 QualType PType = Param->getOriginalType();
15264 // FIXME: This diagnostic should point the '[*]' if source-location
15265 // information is added for it.
15266 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15267
15268 // If the parameter is a c++ class type and it has to be destructed in the
15269 // callee function, declare the destructor so that it can be called by the
15270 // callee function. Do not perform any direct access check on the dtor here.
15271 if (!Param->isInvalidDecl()) {
15272 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15273 if (!ClassDecl->isInvalidDecl() &&
15274 !ClassDecl->hasIrrelevantDestructor() &&
15275 !ClassDecl->isDependentContext() &&
15276 ClassDecl->isParamDestroyedInCallee()) {
15278 MarkFunctionReferenced(Param->getLocation(), Destructor);
15279 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15280 }
15281 }
15282 }
15283
15284 // Parameters with the pass_object_size attribute only need to be marked
15285 // constant at function definitions. Because we lack information about
15286 // whether we're on a declaration or definition when we're instantiating the
15287 // attribute, we need to check for constness here.
15288 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15289 if (!Param->getType().isConstQualified())
15290 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15291 << Attr->getSpelling() << 1;
15292
15293 // Check for parameter names shadowing fields from the class.
15294 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15295 // The owning context for the parameter should be the function, but we
15296 // want to see if this function's declaration context is a record.
15297 DeclContext *DC = Param->getDeclContext();
15298 if (DC && DC->isFunctionOrMethod()) {
15299 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15300 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15301 RD, /*DeclIsField*/ false);
15302 }
15303 }
15304
15305 if (!Param->isInvalidDecl() &&
15306 Param->getOriginalType()->isWebAssemblyTableType()) {
15307 Param->setInvalidDecl();
15308 HasInvalidParm = true;
15309 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15310 }
15311 }
15312
15313 return HasInvalidParm;
15314}
15315
15316std::optional<std::pair<
15318 *E,
15320 &Ctx);
15321
15322/// Compute the alignment and offset of the base class object given the
15323/// derived-to-base cast expression and the alignment and offset of the derived
15324/// class object.
15325static std::pair<CharUnits, CharUnits>
15327 CharUnits BaseAlignment, CharUnits Offset,
15328 ASTContext &Ctx) {
15329 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15330 ++PathI) {
15331 const CXXBaseSpecifier *Base = *PathI;
15332 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15333 if (Base->isVirtual()) {
15334 // The complete object may have a lower alignment than the non-virtual
15335 // alignment of the base, in which case the base may be misaligned. Choose
15336 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15337 // conservative lower bound of the complete object alignment.
15338 CharUnits NonVirtualAlignment =
15340 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15341 Offset = CharUnits::Zero();
15342 } else {
15343 const ASTRecordLayout &RL =
15344 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15345 Offset += RL.getBaseClassOffset(BaseDecl);
15346 }
15347 DerivedType = Base->getType();
15348 }
15349
15350 return std::make_pair(BaseAlignment, Offset);
15351}
15352
15353/// Compute the alignment and offset of a binary additive operator.
15354static std::optional<std::pair<CharUnits, CharUnits>>
15356 bool IsSub, ASTContext &Ctx) {
15357 QualType PointeeType = PtrE->getType()->getPointeeType();
15358
15359 if (!PointeeType->isConstantSizeType())
15360 return std::nullopt;
15361
15362 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15363
15364 if (!P)
15365 return std::nullopt;
15366
15367 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15368 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15369 CharUnits Offset = EltSize * IdxRes->getExtValue();
15370 if (IsSub)
15371 Offset = -Offset;
15372 return std::make_pair(P->first, P->second + Offset);
15373 }
15374
15375 // If the integer expression isn't a constant expression, compute the lower
15376 // bound of the alignment using the alignment and offset of the pointer
15377 // expression and the element size.
15378 return std::make_pair(
15379 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15380 CharUnits::Zero());
15381}
15382
15383/// This helper function takes an lvalue expression and returns the alignment of
15384/// a VarDecl and a constant offset from the VarDecl.
15385std::optional<std::pair<
15386 CharUnits,
15388 ASTContext &Ctx) {
15389 E = E->IgnoreParens();
15390 switch (E->getStmtClass()) {
15391 default:
15392 break;
15393 case Stmt::CStyleCastExprClass:
15394 case Stmt::CXXStaticCastExprClass:
15395 case Stmt::ImplicitCastExprClass: {
15396 auto *CE = cast<CastExpr>(E);
15397 const Expr *From = CE->getSubExpr();
15398 switch (CE->getCastKind()) {
15399 default:
15400 break;
15401 case CK_NoOp:
15402 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15403 case CK_UncheckedDerivedToBase:
15404 case CK_DerivedToBase: {
15405 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15406 if (!P)
15407 break;
15408 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15409 P->second, Ctx);
15410 }
15411 }
15412 break;
15413 }
15414 case Stmt::ArraySubscriptExprClass: {
15415 auto *ASE = cast<ArraySubscriptExpr>(E);
15417 false, Ctx);
15418 }
15419 case Stmt::DeclRefExprClass: {
15420 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15421 // FIXME: If VD is captured by copy or is an escaping __block variable,
15422 // use the alignment of VD's type.
15423 if (!VD->getType()->isReferenceType()) {
15424 // Dependent alignment cannot be resolved -> bail out.
15425 if (VD->hasDependentAlignment())
15426 break;
15427 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15428 }
15429 if (VD->hasInit())
15430 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15431 }
15432 break;
15433 }
15434 case Stmt::MemberExprClass: {
15435 auto *ME = cast<MemberExpr>(E);
15436 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15437 if (!FD || FD->getType()->isReferenceType() ||
15438 FD->getParent()->isInvalidDecl())
15439 break;
15440 std::optional<std::pair<CharUnits, CharUnits>> P;
15441 if (ME->isArrow())
15442 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15443 else
15444 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15445 if (!P)
15446 break;
15447 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15448 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15449 return std::make_pair(P->first,
15450 P->second + CharUnits::fromQuantity(Offset));
15451 }
15452 case Stmt::UnaryOperatorClass: {
15453 auto *UO = cast<UnaryOperator>(E);
15454 switch (UO->getOpcode()) {
15455 default:
15456 break;
15457 case UO_Deref:
15459 }
15460 break;
15461 }
15462 case Stmt::BinaryOperatorClass: {
15463 auto *BO = cast<BinaryOperator>(E);
15464 auto Opcode = BO->getOpcode();
15465 switch (Opcode) {
15466 default:
15467 break;
15468 case BO_Comma:
15470 }
15471 break;
15472 }
15473 }
15474 return std::nullopt;
15475}
15476
15477/// This helper function takes a pointer expression and returns the alignment of
15478/// a VarDecl and a constant offset from the VarDecl.
15479std::optional<std::pair<
15481 *E,
15483 &Ctx) {
15484 E = E->IgnoreParens();
15485 switch (E->getStmtClass()) {
15486 default:
15487 break;
15488 case Stmt::CStyleCastExprClass:
15489 case Stmt::CXXStaticCastExprClass:
15490 case Stmt::ImplicitCastExprClass: {
15491 auto *CE = cast<CastExpr>(E);
15492 const Expr *From = CE->getSubExpr();
15493 switch (CE->getCastKind()) {
15494 default:
15495 break;
15496 case CK_NoOp:
15497 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15498 case CK_ArrayToPointerDecay:
15499 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15500 case CK_UncheckedDerivedToBase:
15501 case CK_DerivedToBase: {
15502 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15503 if (!P)
15504 break;
15506 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15507 }
15508 }
15509 break;
15510 }
15511 case Stmt::CXXThisExprClass: {
15512 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15514 return std::make_pair(Alignment, CharUnits::Zero());
15515 }
15516 case Stmt::UnaryOperatorClass: {
15517 auto *UO = cast<UnaryOperator>(E);
15518 if (UO->getOpcode() == UO_AddrOf)
15520 break;
15521 }
15522 case Stmt::BinaryOperatorClass: {
15523 auto *BO = cast<BinaryOperator>(E);
15524 auto Opcode = BO->getOpcode();
15525 switch (Opcode) {
15526 default:
15527 break;
15528 case BO_Add:
15529 case BO_Sub: {
15530 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15531 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15532 std::swap(LHS, RHS);
15533 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15534 Ctx);
15535 }
15536 case BO_Comma:
15537 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15538 }
15539 break;
15540 }
15541 }
15542 return std::nullopt;
15543}
15544
15546 // See if we can compute the alignment of a VarDecl and an offset from it.
15547 std::optional<std::pair<CharUnits, CharUnits>> P =
15549
15550 if (P)
15551 return P->first.alignmentAtOffset(P->second);
15552
15553 // If that failed, return the type's alignment.
15555}
15556
15558 // This is actually a lot of work to potentially be doing on every
15559 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15560 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15561 return;
15562
15563 // Ignore dependent types.
15564 if (T->isDependentType() || Op->getType()->isDependentType())
15565 return;
15566
15567 // Require that the destination be a pointer type.
15568 const PointerType *DestPtr = T->getAs<PointerType>();
15569 if (!DestPtr) return;
15570
15571 // If the destination has alignment 1, we're done.
15572 QualType DestPointee = DestPtr->getPointeeType();
15573 if (DestPointee->isIncompleteType()) return;
15574 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15575 if (DestAlign.isOne()) return;
15576
15577 // Require that the source be a pointer type.
15578 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15579 if (!SrcPtr) return;
15580 QualType SrcPointee = SrcPtr->getPointeeType();
15581
15582 // Explicitly allow casts from cv void*. We already implicitly
15583 // allowed casts to cv void*, since they have alignment 1.
15584 // Also allow casts involving incomplete types, which implicitly
15585 // includes 'void'.
15586 if (SrcPointee->isIncompleteType()) return;
15587
15588 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15589
15590 if (SrcAlign >= DestAlign) return;
15591
15592 Diag(TRange.getBegin(), diag::warn_cast_align)
15593 << Op->getType() << T
15594 << static_cast<unsigned>(SrcAlign.getQuantity())
15595 << static_cast<unsigned>(DestAlign.getQuantity())
15596 << TRange << Op->getSourceRange();
15597}
15598
15599void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15600 const ArraySubscriptExpr *ASE,
15601 bool AllowOnePastEnd, bool IndexNegated) {
15602 // Already diagnosed by the constant evaluator.
15604 return;
15605
15606 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15607 if (IndexExpr->isValueDependent())
15608 return;
15609
15610 const Type *EffectiveType =
15612 BaseExpr = BaseExpr->IgnoreParenCasts();
15613 const ConstantArrayType *ArrayTy =
15614 Context.getAsConstantArrayType(BaseExpr->getType());
15615
15617 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15618
15619 const Type *BaseType =
15620 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15621 bool IsUnboundedArray =
15622 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15623 Context, StrictFlexArraysLevel,
15624 /*IgnoreTemplateOrMacroSubstitution=*/true);
15625 if (EffectiveType->isDependentType() ||
15626 (!IsUnboundedArray && BaseType->isDependentType()))
15627 return;
15628
15630 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15631 return;
15632
15633 llvm::APSInt index = Result.Val.getInt();
15634 if (IndexNegated) {
15635 index.setIsUnsigned(false);
15636 index = -index;
15637 }
15638
15639 if (IsUnboundedArray) {
15640 if (EffectiveType->isFunctionType())
15641 return;
15642 if (index.isUnsigned() || !index.isNegative()) {
15643 const auto &ASTC = getASTContext();
15644 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15645 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15646 if (index.getBitWidth() < AddrBits)
15647 index = index.zext(AddrBits);
15648 std::optional<CharUnits> ElemCharUnits =
15649 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15650 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15651 // pointer) bounds-checking isn't meaningful.
15652 if (!ElemCharUnits || ElemCharUnits->isZero())
15653 return;
15654 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15655 // If index has more active bits than address space, we already know
15656 // we have a bounds violation to warn about. Otherwise, compute
15657 // address of (index + 1)th element, and warn about bounds violation
15658 // only if that address exceeds address space.
15659 if (index.getActiveBits() <= AddrBits) {
15660 bool Overflow;
15661 llvm::APInt Product(index);
15662 Product += 1;
15663 Product = Product.umul_ov(ElemBytes, Overflow);
15664 if (!Overflow && Product.getActiveBits() <= AddrBits)
15665 return;
15666 }
15667
15668 // Need to compute max possible elements in address space, since that
15669 // is included in diag message.
15670 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15671 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15672 MaxElems += 1;
15673 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15674 MaxElems = MaxElems.udiv(ElemBytes);
15675
15676 unsigned DiagID =
15677 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15678 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15679
15680 // Diag message shows element size in bits and in "bytes" (platform-
15681 // dependent CharUnits)
15682 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15683 PDiag(DiagID) << index << AddrBits
15684 << (unsigned)ASTC.toBits(*ElemCharUnits)
15685 << ElemBytes << MaxElems
15686 << MaxElems.getZExtValue()
15687 << IndexExpr->getSourceRange());
15688
15689 const NamedDecl *ND = nullptr;
15690 // Try harder to find a NamedDecl to point at in the note.
15691 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15692 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15693 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15694 ND = DRE->getDecl();
15695 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15696 ND = ME->getMemberDecl();
15697
15698 if (ND)
15699 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15700 PDiag(diag::note_array_declared_here) << ND);
15701 }
15702 return;
15703 }
15704
15705 if (index.isUnsigned() || !index.isNegative()) {
15706 // It is possible that the type of the base expression after
15707 // IgnoreParenCasts is incomplete, even though the type of the base
15708 // expression before IgnoreParenCasts is complete (see PR39746 for an
15709 // example). In this case we have no information about whether the array
15710 // access exceeds the array bounds. However we can still diagnose an array
15711 // access which precedes the array bounds.
15712 if (BaseType->isIncompleteType())
15713 return;
15714
15715 llvm::APInt size = ArrayTy->getSize();
15716
15717 if (BaseType != EffectiveType) {
15718 // Make sure we're comparing apples to apples when comparing index to
15719 // size.
15720 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15721 uint64_t array_typesize = Context.getTypeSize(BaseType);
15722
15723 // Handle ptrarith_typesize being zero, such as when casting to void*.
15724 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15725 if (!ptrarith_typesize)
15726 ptrarith_typesize = Context.getCharWidth();
15727
15728 if (ptrarith_typesize != array_typesize) {
15729 // There's a cast to a different size type involved.
15730 uint64_t ratio = array_typesize / ptrarith_typesize;
15731
15732 // TODO: Be smarter about handling cases where array_typesize is not a
15733 // multiple of ptrarith_typesize.
15734 if (ptrarith_typesize * ratio == array_typesize)
15735 size *= llvm::APInt(size.getBitWidth(), ratio);
15736 }
15737 }
15738
15739 if (size.getBitWidth() > index.getBitWidth())
15740 index = index.zext(size.getBitWidth());
15741 else if (size.getBitWidth() < index.getBitWidth())
15742 size = size.zext(index.getBitWidth());
15743
15744 // For array subscripting the index must be less than size, but for pointer
15745 // arithmetic also allow the index (offset) to be equal to size since
15746 // computing the next address after the end of the array is legal and
15747 // commonly done e.g. in C++ iterators and range-based for loops.
15748 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15749 return;
15750
15751 // Suppress the warning if the subscript expression (as identified by the
15752 // ']' location) and the index expression are both from macro expansions
15753 // within a system header.
15754 if (ASE) {
15755 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15756 ASE->getRBracketLoc());
15757 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15758 SourceLocation IndexLoc =
15759 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15760 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15761 return;
15762 }
15763 }
15764
15765 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15766 : diag::warn_ptr_arith_exceeds_bounds;
15767 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15768 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15769
15770 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15771 PDiag(DiagID)
15772 << index << ArrayTy->desugar() << CastMsg
15773 << CastMsgTy << IndexExpr->getSourceRange());
15774 } else {
15775 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15776 if (!ASE) {
15777 DiagID = diag::warn_ptr_arith_precedes_bounds;
15778 if (index.isNegative()) index = -index;
15779 }
15780
15781 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15782 PDiag(DiagID) << index << IndexExpr->getSourceRange());
15783 }
15784
15785 const NamedDecl *ND = nullptr;
15786 // Try harder to find a NamedDecl to point at in the note.
15787 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15788 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15789 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15790 ND = DRE->getDecl();
15791 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15792 ND = ME->getMemberDecl();
15793
15794 if (ND)
15795 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15796 PDiag(diag::note_array_declared_here) << ND);
15797}
15798
15799void Sema::CheckArrayAccess(const Expr *expr) {
15800 int AllowOnePastEnd = 0;
15801 while (expr) {
15802 expr = expr->IgnoreParenImpCasts();
15803 switch (expr->getStmtClass()) {
15804 case Stmt::ArraySubscriptExprClass: {
15805 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15806 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15807 AllowOnePastEnd > 0);
15808 expr = ASE->getBase();
15809 break;
15810 }
15811 case Stmt::MemberExprClass: {
15812 expr = cast<MemberExpr>(expr)->getBase();
15813 break;
15814 }
15815 case Stmt::CXXMemberCallExprClass: {
15816 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
15817 break;
15818 }
15819 case Stmt::ArraySectionExprClass: {
15820 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15821 // FIXME: We should probably be checking all of the elements to the
15822 // 'length' here as well.
15823 if (ASE->getLowerBound())
15824 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15825 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15826 return;
15827 }
15828 case Stmt::UnaryOperatorClass: {
15829 // Only unwrap the * and & unary operators
15830 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15831 expr = UO->getSubExpr();
15832 switch (UO->getOpcode()) {
15833 case UO_AddrOf:
15834 AllowOnePastEnd++;
15835 break;
15836 case UO_Deref:
15837 AllowOnePastEnd--;
15838 break;
15839 default:
15840 return;
15841 }
15842 break;
15843 }
15844 case Stmt::ConditionalOperatorClass: {
15845 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15846 if (const Expr *lhs = cond->getLHS())
15847 CheckArrayAccess(lhs);
15848 if (const Expr *rhs = cond->getRHS())
15849 CheckArrayAccess(rhs);
15850 return;
15851 }
15852 case Stmt::CXXOperatorCallExprClass: {
15853 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15854 for (const auto *Arg : OCE->arguments())
15855 CheckArrayAccess(Arg);
15856 return;
15857 }
15858 default:
15859 return;
15860 }
15861 }
15862}
15863
15865 Expr *RHS, bool isProperty) {
15866 // Check if RHS is an Objective-C object literal, which also can get
15867 // immediately zapped in a weak reference. Note that we explicitly
15868 // allow ObjCStringLiterals, since those are designed to never really die.
15869 RHS = RHS->IgnoreParenImpCasts();
15870
15871 // This enum needs to match with the 'select' in
15872 // warn_objc_arc_literal_assign (off-by-1).
15874 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15875 return false;
15876
15877 S.Diag(Loc, diag::warn_arc_literal_assign)
15878 << (unsigned) Kind
15879 << (isProperty ? 0 : 1)
15880 << RHS->getSourceRange();
15881
15882 return true;
15883}
15884
15887 Expr *RHS, bool isProperty) {
15888 // Strip off any implicit cast added to get to the one ARC-specific.
15889 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15890 if (cast->getCastKind() == CK_ARCConsumeObject) {
15891 S.Diag(Loc, diag::warn_arc_retained_assign)
15893 << (isProperty ? 0 : 1)
15894 << RHS->getSourceRange();
15895 return true;
15896 }
15897 RHS = cast->getSubExpr();
15898 }
15899
15900 if (LT == Qualifiers::OCL_Weak &&
15901 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15902 return true;
15903
15904 return false;
15905}
15906
15908 QualType LHS, Expr *RHS) {
15910
15912 return false;
15913
15914 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15915 return true;
15916
15917 return false;
15918}
15919
15921 Expr *LHS, Expr *RHS) {
15922 QualType LHSType;
15923 // PropertyRef on LHS type need be directly obtained from
15924 // its declaration as it has a PseudoType.
15926 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15927 if (PRE && !PRE->isImplicitProperty()) {
15928 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15929 if (PD)
15930 LHSType = PD->getType();
15931 }
15932
15933 if (LHSType.isNull())
15934 LHSType = LHS->getType();
15935
15937
15938 if (LT == Qualifiers::OCL_Weak) {
15939 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15941 }
15942
15943 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15944 return;
15945
15946 // FIXME. Check for other life times.
15947 if (LT != Qualifiers::OCL_None)
15948 return;
15949
15950 if (PRE) {
15951 if (PRE->isImplicitProperty())
15952 return;
15953 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15954 if (!PD)
15955 return;
15956
15957 unsigned Attributes = PD->getPropertyAttributes();
15958 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15959 // when 'assign' attribute was not explicitly specified
15960 // by user, ignore it and rely on property type itself
15961 // for lifetime info.
15962 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15963 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15964 LHSType->isObjCRetainableType())
15965 return;
15966
15967 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15968 if (cast->getCastKind() == CK_ARCConsumeObject) {
15969 Diag(Loc, diag::warn_arc_retained_property_assign)
15970 << RHS->getSourceRange();
15971 return;
15972 }
15973 RHS = cast->getSubExpr();
15974 }
15975 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15976 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15977 return;
15978 }
15979 }
15980}
15981
15982//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15983
15984static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15985 SourceLocation StmtLoc,
15986 const NullStmt *Body) {
15987 // Do not warn if the body is a macro that expands to nothing, e.g:
15988 //
15989 // #define CALL(x)
15990 // if (condition)
15991 // CALL(0);
15992 if (Body->hasLeadingEmptyMacro())
15993 return false;
15994
15995 // Get line numbers of statement and body.
15996 bool StmtLineInvalid;
15997 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15998 &StmtLineInvalid);
15999 if (StmtLineInvalid)
16000 return false;
16001
16002 bool BodyLineInvalid;
16003 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16004 &BodyLineInvalid);
16005 if (BodyLineInvalid)
16006 return false;
16007
16008 // Warn if null statement and body are on the same line.
16009 if (StmtLine != BodyLine)
16010 return false;
16011
16012 return true;
16013}
16014
16016 const Stmt *Body,
16017 unsigned DiagID) {
16018 // Since this is a syntactic check, don't emit diagnostic for template
16019 // instantiations, this just adds noise.
16021 return;
16022
16023 // The body should be a null statement.
16024 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16025 if (!NBody)
16026 return;
16027
16028 // Do the usual checks.
16029 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16030 return;
16031
16032 Diag(NBody->getSemiLoc(), DiagID);
16033 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16034}
16035
16037 const Stmt *PossibleBody) {
16038 assert(!CurrentInstantiationScope); // Ensured by caller
16039
16040 SourceLocation StmtLoc;
16041 const Stmt *Body;
16042 unsigned DiagID;
16043 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16044 StmtLoc = FS->getRParenLoc();
16045 Body = FS->getBody();
16046 DiagID = diag::warn_empty_for_body;
16047 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16048 StmtLoc = WS->getRParenLoc();
16049 Body = WS->getBody();
16050 DiagID = diag::warn_empty_while_body;
16051 } else
16052 return; // Neither `for' nor `while'.
16053
16054 // The body should be a null statement.
16055 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16056 if (!NBody)
16057 return;
16058
16059 // Skip expensive checks if diagnostic is disabled.
16060 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16061 return;
16062
16063 // Do the usual checks.
16064 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16065 return;
16066
16067 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16068 // noise level low, emit diagnostics only if for/while is followed by a
16069 // CompoundStmt, e.g.:
16070 // for (int i = 0; i < n; i++);
16071 // {
16072 // a(i);
16073 // }
16074 // or if for/while is followed by a statement with more indentation
16075 // than for/while itself:
16076 // for (int i = 0; i < n; i++);
16077 // a(i);
16078 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16079 if (!ProbableTypo) {
16080 bool BodyColInvalid;
16081 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16082 PossibleBody->getBeginLoc(), &BodyColInvalid);
16083 if (BodyColInvalid)
16084 return;
16085
16086 bool StmtColInvalid;
16087 unsigned StmtCol =
16088 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16089 if (StmtColInvalid)
16090 return;
16091
16092 if (BodyCol > StmtCol)
16093 ProbableTypo = true;
16094 }
16095
16096 if (ProbableTypo) {
16097 Diag(NBody->getSemiLoc(), DiagID);
16098 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16099 }
16100}
16101
16102//===--- CHECK: Warn on self move with std::move. -------------------------===//
16103
16104void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16105 SourceLocation OpLoc) {
16106 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16107 return;
16108
16110 return;
16111
16112 // Strip parens and casts away.
16113 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16114 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16115
16116 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16117 // which we can treat as an inlined std::move
16118 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16119 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16120 RHSExpr = CE->getArg(0);
16121 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16122 CXXSCE && CXXSCE->isXValue())
16123 RHSExpr = CXXSCE->getSubExpr();
16124 else
16125 return;
16126
16127 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16128 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16129
16130 // Two DeclRefExpr's, check that the decls are the same.
16131 if (LHSDeclRef && RHSDeclRef) {
16132 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16133 return;
16134 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16135 RHSDeclRef->getDecl()->getCanonicalDecl())
16136 return;
16137
16138 auto D = Diag(OpLoc, diag::warn_self_move)
16139 << LHSExpr->getType() << LHSExpr->getSourceRange()
16140 << RHSExpr->getSourceRange();
16141 if (const FieldDecl *F =
16143 D << 1 << F
16144 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16145 else
16146 D << 0;
16147 return;
16148 }
16149
16150 // Member variables require a different approach to check for self moves.
16151 // MemberExpr's are the same if every nested MemberExpr refers to the same
16152 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16153 // the base Expr's are CXXThisExpr's.
16154 const Expr *LHSBase = LHSExpr;
16155 const Expr *RHSBase = RHSExpr;
16156 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16157 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16158 if (!LHSME || !RHSME)
16159 return;
16160
16161 while (LHSME && RHSME) {
16162 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16163 RHSME->getMemberDecl()->getCanonicalDecl())
16164 return;
16165
16166 LHSBase = LHSME->getBase();
16167 RHSBase = RHSME->getBase();
16168 LHSME = dyn_cast<MemberExpr>(LHSBase);
16169 RHSME = dyn_cast<MemberExpr>(RHSBase);
16170 }
16171
16172 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16173 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16174 if (LHSDeclRef && RHSDeclRef) {
16175 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16176 return;
16177 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16178 RHSDeclRef->getDecl()->getCanonicalDecl())
16179 return;
16180
16181 Diag(OpLoc, diag::warn_self_move)
16182 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16183 << RHSExpr->getSourceRange();
16184 return;
16185 }
16186
16187 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16188 Diag(OpLoc, diag::warn_self_move)
16189 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16190 << RHSExpr->getSourceRange();
16191}
16192
16193//===--- Layout compatibility ----------------------------------------------//
16194
16195static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16196
16197/// Check if two enumeration types are layout-compatible.
16198static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16199 const EnumDecl *ED2) {
16200 // C++11 [dcl.enum] p8:
16201 // Two enumeration types are layout-compatible if they have the same
16202 // underlying type.
16203 return ED1->isComplete() && ED2->isComplete() &&
16204 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16205}
16206
16207/// Check if two fields are layout-compatible.
16208/// Can be used on union members, which are exempt from alignment requirement
16209/// of common initial sequence.
16210static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16211 const FieldDecl *Field2,
16212 bool AreUnionMembers = false) {
16213#ifndef NDEBUG
16214 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16215 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16216 assert(((Field1Parent->isStructureOrClassType() &&
16217 Field2Parent->isStructureOrClassType()) ||
16218 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16219 "Can't evaluate layout compatibility between a struct field and a "
16220 "union field.");
16221 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16222 (AreUnionMembers && Field1Parent->isUnionType())) &&
16223 "AreUnionMembers should be 'true' for union fields (only).");
16224#endif
16225
16226 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16227 return false;
16228
16229 if (Field1->isBitField() != Field2->isBitField())
16230 return false;
16231
16232 if (Field1->isBitField()) {
16233 // Make sure that the bit-fields are the same length.
16234 unsigned Bits1 = Field1->getBitWidthValue();
16235 unsigned Bits2 = Field2->getBitWidthValue();
16236
16237 if (Bits1 != Bits2)
16238 return false;
16239 }
16240
16241 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16242 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16243 return false;
16244
16245 if (!AreUnionMembers &&
16246 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16247 return false;
16248
16249 return true;
16250}
16251
16252/// Check if two standard-layout structs are layout-compatible.
16253/// (C++11 [class.mem] p17)
16254static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16255 const RecordDecl *RD2) {
16256 // Get to the class where the fields are declared
16257 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16258 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16259
16260 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16261 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16262
16263 // Check the fields.
16264 return llvm::equal(RD1->fields(), RD2->fields(),
16265 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16266 return isLayoutCompatible(C, F1, F2);
16267 });
16268}
16269
16270/// Check if two standard-layout unions are layout-compatible.
16271/// (C++11 [class.mem] p18)
16272static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16273 const RecordDecl *RD2) {
16274 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16275 RD2->fields());
16276
16277 for (auto *Field1 : RD1->fields()) {
16278 auto I = UnmatchedFields.begin();
16279 auto E = UnmatchedFields.end();
16280
16281 for ( ; I != E; ++I) {
16282 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
16283 bool Result = UnmatchedFields.erase(*I);
16284 (void) Result;
16285 assert(Result);
16286 break;
16287 }
16288 }
16289 if (I == E)
16290 return false;
16291 }
16292
16293 return UnmatchedFields.empty();
16294}
16295
16296static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16297 const RecordDecl *RD2) {
16298 if (RD1->isUnion() != RD2->isUnion())
16299 return false;
16300
16301 if (RD1->isUnion())
16302 return isLayoutCompatibleUnion(C, RD1, RD2);
16303 else
16304 return isLayoutCompatibleStruct(C, RD1, RD2);
16305}
16306
16307/// Check if two types are layout-compatible in C++11 sense.
16308static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16309 if (T1.isNull() || T2.isNull())
16310 return false;
16311
16312 // C++20 [basic.types] p11:
16313 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16314 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16315 // or layout-compatible standard-layout class types (11.4).
16318
16319 if (C.hasSameType(T1, T2))
16320 return true;
16321
16322 const Type::TypeClass TC1 = T1->getTypeClass();
16323 const Type::TypeClass TC2 = T2->getTypeClass();
16324
16325 if (TC1 != TC2)
16326 return false;
16327
16328 if (TC1 == Type::Enum)
16329 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16330 if (TC1 == Type::Record) {
16331 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16332 return false;
16333
16335 T2->castAsRecordDecl());
16336 }
16337
16338 return false;
16339}
16340
16342 return isLayoutCompatible(getASTContext(), T1, T2);
16343}
16344
16345//===-------------- Pointer interconvertibility ----------------------------//
16346
16348 const TypeSourceInfo *Derived) {
16349 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16350 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16351
16352 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16353 getASTContext().hasSameType(BaseT, DerivedT))
16354 return true;
16355
16356 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16357 return false;
16358
16359 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16360 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16361 return true;
16362
16363 return false;
16364}
16365
16366//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16367
16368/// Given a type tag expression find the type tag itself.
16369///
16370/// \param TypeExpr Type tag expression, as it appears in user's code.
16371///
16372/// \param VD Declaration of an identifier that appears in a type tag.
16373///
16374/// \param MagicValue Type tag magic value.
16375///
16376/// \param isConstantEvaluated whether the evalaution should be performed in
16377
16378/// constant context.
16379static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16380 const ValueDecl **VD, uint64_t *MagicValue,
16381 bool isConstantEvaluated) {
16382 while(true) {
16383 if (!TypeExpr)
16384 return false;
16385
16386 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16387
16388 switch (TypeExpr->getStmtClass()) {
16389 case Stmt::UnaryOperatorClass: {
16390 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16391 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16392 TypeExpr = UO->getSubExpr();
16393 continue;
16394 }
16395 return false;
16396 }
16397
16398 case Stmt::DeclRefExprClass: {
16399 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16400 *VD = DRE->getDecl();
16401 return true;
16402 }
16403
16404 case Stmt::IntegerLiteralClass: {
16405 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16406 llvm::APInt MagicValueAPInt = IL->getValue();
16407 if (MagicValueAPInt.getActiveBits() <= 64) {
16408 *MagicValue = MagicValueAPInt.getZExtValue();
16409 return true;
16410 } else
16411 return false;
16412 }
16413
16414 case Stmt::BinaryConditionalOperatorClass:
16415 case Stmt::ConditionalOperatorClass: {
16416 const AbstractConditionalOperator *ACO =
16418 bool Result;
16419 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16420 isConstantEvaluated)) {
16421 if (Result)
16422 TypeExpr = ACO->getTrueExpr();
16423 else
16424 TypeExpr = ACO->getFalseExpr();
16425 continue;
16426 }
16427 return false;
16428 }
16429
16430 case Stmt::BinaryOperatorClass: {
16431 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16432 if (BO->getOpcode() == BO_Comma) {
16433 TypeExpr = BO->getRHS();
16434 continue;
16435 }
16436 return false;
16437 }
16438
16439 default:
16440 return false;
16441 }
16442 }
16443}
16444
16445/// Retrieve the C type corresponding to type tag TypeExpr.
16446///
16447/// \param TypeExpr Expression that specifies a type tag.
16448///
16449/// \param MagicValues Registered magic values.
16450///
16451/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16452/// kind.
16453///
16454/// \param TypeInfo Information about the corresponding C type.
16455///
16456/// \param isConstantEvaluated whether the evalaution should be performed in
16457/// constant context.
16458///
16459/// \returns true if the corresponding C type was found.
16461 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16462 const ASTContext &Ctx,
16463 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16464 *MagicValues,
16465 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16466 bool isConstantEvaluated) {
16467 FoundWrongKind = false;
16468
16469 // Variable declaration that has type_tag_for_datatype attribute.
16470 const ValueDecl *VD = nullptr;
16471
16472 uint64_t MagicValue;
16473
16474 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16475 return false;
16476
16477 if (VD) {
16478 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16479 if (I->getArgumentKind() != ArgumentKind) {
16480 FoundWrongKind = true;
16481 return false;
16482 }
16483 TypeInfo.Type = I->getMatchingCType();
16484 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16485 TypeInfo.MustBeNull = I->getMustBeNull();
16486 return true;
16487 }
16488 return false;
16489 }
16490
16491 if (!MagicValues)
16492 return false;
16493
16494 llvm::DenseMap<Sema::TypeTagMagicValue,
16496 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16497 if (I == MagicValues->end())
16498 return false;
16499
16500 TypeInfo = I->second;
16501 return true;
16502}
16503
16505 uint64_t MagicValue, QualType Type,
16506 bool LayoutCompatible,
16507 bool MustBeNull) {
16508 if (!TypeTagForDatatypeMagicValues)
16509 TypeTagForDatatypeMagicValues.reset(
16510 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16511
16512 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16513 (*TypeTagForDatatypeMagicValues)[Magic] =
16514 TypeTagData(Type, LayoutCompatible, MustBeNull);
16515}
16516
16517static bool IsSameCharType(QualType T1, QualType T2) {
16518 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16519 if (!BT1)
16520 return false;
16521
16522 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16523 if (!BT2)
16524 return false;
16525
16526 BuiltinType::Kind T1Kind = BT1->getKind();
16527 BuiltinType::Kind T2Kind = BT2->getKind();
16528
16529 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16530 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16531 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16532 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16533}
16534
16535void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16536 const ArrayRef<const Expr *> ExprArgs,
16537 SourceLocation CallSiteLoc) {
16538 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16539 bool IsPointerAttr = Attr->getIsPointer();
16540
16541 // Retrieve the argument representing the 'type_tag'.
16542 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16543 if (TypeTagIdxAST >= ExprArgs.size()) {
16544 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16545 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16546 return;
16547 }
16548 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16549 bool FoundWrongKind;
16550 TypeTagData TypeInfo;
16551 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16552 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16553 TypeInfo, isConstantEvaluatedContext())) {
16554 if (FoundWrongKind)
16555 Diag(TypeTagExpr->getExprLoc(),
16556 diag::warn_type_tag_for_datatype_wrong_kind)
16557 << TypeTagExpr->getSourceRange();
16558 return;
16559 }
16560
16561 // Retrieve the argument representing the 'arg_idx'.
16562 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16563 if (ArgumentIdxAST >= ExprArgs.size()) {
16564 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16565 << 1 << Attr->getArgumentIdx().getSourceIndex();
16566 return;
16567 }
16568 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16569 if (IsPointerAttr) {
16570 // Skip implicit cast of pointer to `void *' (as a function argument).
16571 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16572 if (ICE->getType()->isVoidPointerType() &&
16573 ICE->getCastKind() == CK_BitCast)
16574 ArgumentExpr = ICE->getSubExpr();
16575 }
16576 QualType ArgumentType = ArgumentExpr->getType();
16577
16578 // Passing a `void*' pointer shouldn't trigger a warning.
16579 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16580 return;
16581
16582 if (TypeInfo.MustBeNull) {
16583 // Type tag with matching void type requires a null pointer.
16584 if (!ArgumentExpr->isNullPointerConstant(Context,
16586 Diag(ArgumentExpr->getExprLoc(),
16587 diag::warn_type_safety_null_pointer_required)
16588 << ArgumentKind->getName()
16589 << ArgumentExpr->getSourceRange()
16590 << TypeTagExpr->getSourceRange();
16591 }
16592 return;
16593 }
16594
16595 QualType RequiredType = TypeInfo.Type;
16596 if (IsPointerAttr)
16597 RequiredType = Context.getPointerType(RequiredType);
16598
16599 bool mismatch = false;
16600 if (!TypeInfo.LayoutCompatible) {
16601 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16602
16603 // C++11 [basic.fundamental] p1:
16604 // Plain char, signed char, and unsigned char are three distinct types.
16605 //
16606 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16607 // char' depending on the current char signedness mode.
16608 if (mismatch)
16609 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16610 RequiredType->getPointeeType())) ||
16611 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16612 mismatch = false;
16613 } else
16614 if (IsPointerAttr)
16615 mismatch = !isLayoutCompatible(Context,
16616 ArgumentType->getPointeeType(),
16617 RequiredType->getPointeeType());
16618 else
16619 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16620
16621 if (mismatch)
16622 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16623 << ArgumentType << ArgumentKind
16624 << TypeInfo.LayoutCompatible << RequiredType
16625 << ArgumentExpr->getSourceRange()
16626 << TypeTagExpr->getSourceRange();
16627}
16628
16629void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16630 CharUnits Alignment) {
16631 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16632 Alignment);
16633}
16634
16636 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16637 const NamedDecl *ND = m.RD;
16638 if (ND->getName().empty()) {
16639 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16640 ND = TD;
16641 }
16642 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16643 << m.MD << ND << m.E->getSourceRange();
16644 }
16646}
16647
16649 E = E->IgnoreParens();
16650 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16651 return;
16652 if (isa<UnaryOperator>(E) &&
16653 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16654 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16655 if (isa<MemberExpr>(Op)) {
16656 auto &MisalignedMembersForExpr =
16658 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16659 if (MA != MisalignedMembersForExpr.end() &&
16660 (T->isDependentType() || T->isIntegerType() ||
16661 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16662 Context.getTypeAlignInChars(
16663 T->getPointeeType()) <= MA->Alignment))))
16664 MisalignedMembersForExpr.erase(MA);
16665 }
16666 }
16667}
16668
16670 Expr *E,
16671 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16672 Action) {
16673 const auto *ME = dyn_cast<MemberExpr>(E);
16674 if (!ME)
16675 return;
16676
16677 // No need to check expressions with an __unaligned-qualified type.
16678 if (E->getType().getQualifiers().hasUnaligned())
16679 return;
16680
16681 // For a chain of MemberExpr like "a.b.c.d" this list
16682 // will keep FieldDecl's like [d, c, b].
16683 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16684 const MemberExpr *TopME = nullptr;
16685 bool AnyIsPacked = false;
16686 do {
16687 QualType BaseType = ME->getBase()->getType();
16688 if (BaseType->isDependentType())
16689 return;
16690 if (ME->isArrow())
16691 BaseType = BaseType->getPointeeType();
16692 auto *RD = BaseType->castAsRecordDecl();
16693 if (RD->isInvalidDecl())
16694 return;
16695
16696 ValueDecl *MD = ME->getMemberDecl();
16697 auto *FD = dyn_cast<FieldDecl>(MD);
16698 // We do not care about non-data members.
16699 if (!FD || FD->isInvalidDecl())
16700 return;
16701
16702 AnyIsPacked =
16703 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16704 ReverseMemberChain.push_back(FD);
16705
16706 TopME = ME;
16707 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16708 } while (ME);
16709 assert(TopME && "We did not compute a topmost MemberExpr!");
16710
16711 // Not the scope of this diagnostic.
16712 if (!AnyIsPacked)
16713 return;
16714
16715 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16716 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16717 // TODO: The innermost base of the member expression may be too complicated.
16718 // For now, just disregard these cases. This is left for future
16719 // improvement.
16720 if (!DRE && !isa<CXXThisExpr>(TopBase))
16721 return;
16722
16723 // Alignment expected by the whole expression.
16724 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16725
16726 // No need to do anything else with this case.
16727 if (ExpectedAlignment.isOne())
16728 return;
16729
16730 // Synthesize offset of the whole access.
16731 CharUnits Offset;
16732 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16733 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16734
16735 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16736 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16737 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
16738
16739 // The base expression of the innermost MemberExpr may give
16740 // stronger guarantees than the class containing the member.
16741 if (DRE && !TopME->isArrow()) {
16742 const ValueDecl *VD = DRE->getDecl();
16743 if (!VD->getType()->isReferenceType())
16744 CompleteObjectAlignment =
16745 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16746 }
16747
16748 // Check if the synthesized offset fulfills the alignment.
16749 if (!Offset.isMultipleOf(ExpectedAlignment) ||
16750 // It may fulfill the offset it but the effective alignment may still be
16751 // lower than the expected expression alignment.
16752 CompleteObjectAlignment < ExpectedAlignment) {
16753 // If this happens, we want to determine a sensible culprit of this.
16754 // Intuitively, watching the chain of member expressions from right to
16755 // left, we start with the required alignment (as required by the field
16756 // type) but some packed attribute in that chain has reduced the alignment.
16757 // It may happen that another packed structure increases it again. But if
16758 // we are here such increase has not been enough. So pointing the first
16759 // FieldDecl that either is packed or else its RecordDecl is,
16760 // seems reasonable.
16761 FieldDecl *FD = nullptr;
16762 CharUnits Alignment;
16763 for (FieldDecl *FDI : ReverseMemberChain) {
16764 if (FDI->hasAttr<PackedAttr>() ||
16765 FDI->getParent()->hasAttr<PackedAttr>()) {
16766 FD = FDI;
16767 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
16768 Context.getTypeAlignInChars(
16769 Context.getCanonicalTagType(FD->getParent())));
16770 break;
16771 }
16772 }
16773 assert(FD && "We did not find a packed FieldDecl!");
16774 Action(E, FD->getParent(), FD, Alignment);
16775 }
16776}
16777
16778void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16779 using namespace std::placeholders;
16780
16782 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16783 _2, _3, _4));
16784}
16785
16787 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16788 if (checkArgCount(TheCall, 1))
16789 return true;
16790
16791 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16792 if (A.isInvalid())
16793 return true;
16794
16795 TheCall->setArg(0, A.get());
16796 QualType TyA = A.get()->getType();
16797
16798 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16799 ArgTyRestr, 1))
16800 return true;
16801
16802 TheCall->setType(TyA);
16803 return false;
16804}
16805
16806bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16807 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16808 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16809 TheCall->setType(*Res);
16810 return false;
16811 }
16812 return true;
16813}
16814
16816 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16817 if (!Res)
16818 return true;
16819
16820 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16821 TheCall->setType(VecTy0->getElementType());
16822 else
16823 TheCall->setType(*Res);
16824
16825 return false;
16826}
16827
16829 SourceLocation Loc) {
16831 R = RHS->getEnumCoercedType(S.Context);
16832 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16834 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16835 << LHS->getSourceRange() << RHS->getSourceRange()
16836 << /*Arithmetic Between*/ 0 << L << R;
16837 }
16838 return false;
16839}
16840
16841/// Check if all arguments have the same type. If the types don't match, emit an
16842/// error message and return true. Otherwise return false.
16843///
16844/// For scalars we directly compare their unqualified types. But even if we
16845/// compare unqualified vector types, a difference in qualifiers in the element
16846/// types can make the vector types be considered not equal. For example,
16847/// vector of 4 'const float' values vs vector of 4 'float' values.
16848/// So we compare unqualified types of their elements and number of elements.
16850 ArrayRef<Expr *> Args) {
16851 assert(!Args.empty() && "Should have at least one argument.");
16852
16853 Expr *Arg0 = Args.front();
16854 QualType Ty0 = Arg0->getType();
16855
16856 auto EmitError = [&](Expr *ArgI) {
16857 SemaRef.Diag(Arg0->getBeginLoc(),
16858 diag::err_typecheck_call_different_arg_types)
16859 << Arg0->getType() << ArgI->getType();
16860 };
16861
16862 // Compare scalar types.
16863 if (!Ty0->isVectorType()) {
16864 for (Expr *ArgI : Args.drop_front())
16865 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16866 EmitError(ArgI);
16867 return true;
16868 }
16869
16870 return false;
16871 }
16872
16873 // Compare vector types.
16874 const auto *Vec0 = Ty0->castAs<VectorType>();
16875 for (Expr *ArgI : Args.drop_front()) {
16876 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16877 if (!VecI ||
16878 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16879 VecI->getElementType()) ||
16880 Vec0->getNumElements() != VecI->getNumElements()) {
16881 EmitError(ArgI);
16882 return true;
16883 }
16884 }
16885
16886 return false;
16887}
16888
16889std::optional<QualType>
16891 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16892 if (checkArgCount(TheCall, 2))
16893 return std::nullopt;
16894
16896 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16897 return std::nullopt;
16898
16899 Expr *Args[2];
16900 for (int I = 0; I < 2; ++I) {
16901 ExprResult Converted =
16902 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16903 if (Converted.isInvalid())
16904 return std::nullopt;
16905 Args[I] = Converted.get();
16906 }
16907
16908 SourceLocation LocA = Args[0]->getBeginLoc();
16909 QualType TyA = Args[0]->getType();
16910
16911 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16912 return std::nullopt;
16913
16914 if (checkBuiltinVectorMathArgTypes(*this, Args))
16915 return std::nullopt;
16916
16917 TheCall->setArg(0, Args[0]);
16918 TheCall->setArg(1, Args[1]);
16919 return TyA;
16920}
16921
16923 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16924 if (checkArgCount(TheCall, 3))
16925 return true;
16926
16927 SourceLocation Loc = TheCall->getExprLoc();
16928 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16929 TheCall->getArg(1), Loc) ||
16930 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16931 TheCall->getArg(2), Loc))
16932 return true;
16933
16934 Expr *Args[3];
16935 for (int I = 0; I < 3; ++I) {
16936 ExprResult Converted =
16937 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16938 if (Converted.isInvalid())
16939 return true;
16940 Args[I] = Converted.get();
16941 }
16942
16943 int ArgOrdinal = 1;
16944 for (Expr *Arg : Args) {
16945 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16946 ArgTyRestr, ArgOrdinal++))
16947 return true;
16948 }
16949
16950 if (checkBuiltinVectorMathArgTypes(*this, Args))
16951 return true;
16952
16953 for (int I = 0; I < 3; ++I)
16954 TheCall->setArg(I, Args[I]);
16955
16956 TheCall->setType(Args[0]->getType());
16957 return false;
16958}
16959
16960bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16961 if (checkArgCount(TheCall, 1))
16962 return true;
16963
16964 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16965 if (A.isInvalid())
16966 return true;
16967
16968 TheCall->setArg(0, A.get());
16969 return false;
16970}
16971
16972bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16973 if (checkArgCount(TheCall, 1))
16974 return true;
16975
16976 ExprResult Arg = TheCall->getArg(0);
16977 QualType TyArg = Arg.get()->getType();
16978
16979 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16980 return Diag(TheCall->getArg(0)->getBeginLoc(),
16981 diag::err_builtin_invalid_arg_type)
16982 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16983
16984 TheCall->setType(TyArg);
16985 return false;
16986}
16987
16988ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16989 ExprResult CallResult) {
16990 if (checkArgCount(TheCall, 1))
16991 return ExprError();
16992
16993 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16994 if (MatrixArg.isInvalid())
16995 return MatrixArg;
16996 Expr *Matrix = MatrixArg.get();
16997
16998 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16999 if (!MType) {
17000 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17001 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17002 << Matrix->getType();
17003 return ExprError();
17004 }
17005
17006 // Create returned matrix type by swapping rows and columns of the argument
17007 // matrix type.
17008 QualType ResultType = Context.getConstantMatrixType(
17009 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17010
17011 // Change the return type to the type of the returned matrix.
17012 TheCall->setType(ResultType);
17013
17014 // Update call argument to use the possibly converted matrix argument.
17015 TheCall->setArg(0, Matrix);
17016 return CallResult;
17017}
17018
17019// Get and verify the matrix dimensions.
17020static std::optional<unsigned>
17022 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17023 if (!Value) {
17024 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17025 << Name;
17026 return {};
17027 }
17028 uint64_t Dim = Value->getZExtValue();
17029 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17030 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17031 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17032 return {};
17033 }
17034 return Dim;
17035}
17036
17037ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17038 ExprResult CallResult) {
17039 if (!getLangOpts().MatrixTypes) {
17040 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17041 return ExprError();
17042 }
17043
17044 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17046 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17047 << /*column*/ 1 << /*load*/ 0;
17048 return ExprError();
17049 }
17050
17051 if (checkArgCount(TheCall, 4))
17052 return ExprError();
17053
17054 unsigned PtrArgIdx = 0;
17055 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17056 Expr *RowsExpr = TheCall->getArg(1);
17057 Expr *ColumnsExpr = TheCall->getArg(2);
17058 Expr *StrideExpr = TheCall->getArg(3);
17059
17060 bool ArgError = false;
17061
17062 // Check pointer argument.
17063 {
17065 if (PtrConv.isInvalid())
17066 return PtrConv;
17067 PtrExpr = PtrConv.get();
17068 TheCall->setArg(0, PtrExpr);
17069 if (PtrExpr->isTypeDependent()) {
17070 TheCall->setType(Context.DependentTy);
17071 return TheCall;
17072 }
17073 }
17074
17075 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17076 QualType ElementTy;
17077 if (!PtrTy) {
17078 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17079 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17080 << PtrExpr->getType();
17081 ArgError = true;
17082 } else {
17083 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17084
17086 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17087 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17088 << /* no fp */ 0 << PtrExpr->getType();
17089 ArgError = true;
17090 }
17091 }
17092
17093 // Apply default Lvalue conversions and convert the expression to size_t.
17094 auto ApplyArgumentConversions = [this](Expr *E) {
17096 if (Conv.isInvalid())
17097 return Conv;
17098
17099 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17100 };
17101
17102 // Apply conversion to row and column expressions.
17103 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17104 if (!RowsConv.isInvalid()) {
17105 RowsExpr = RowsConv.get();
17106 TheCall->setArg(1, RowsExpr);
17107 } else
17108 RowsExpr = nullptr;
17109
17110 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17111 if (!ColumnsConv.isInvalid()) {
17112 ColumnsExpr = ColumnsConv.get();
17113 TheCall->setArg(2, ColumnsExpr);
17114 } else
17115 ColumnsExpr = nullptr;
17116
17117 // If any part of the result matrix type is still pending, just use
17118 // Context.DependentTy, until all parts are resolved.
17119 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17120 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17121 TheCall->setType(Context.DependentTy);
17122 return CallResult;
17123 }
17124
17125 // Check row and column dimensions.
17126 std::optional<unsigned> MaybeRows;
17127 if (RowsExpr)
17128 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17129
17130 std::optional<unsigned> MaybeColumns;
17131 if (ColumnsExpr)
17132 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17133
17134 // Check stride argument.
17135 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17136 if (StrideConv.isInvalid())
17137 return ExprError();
17138 StrideExpr = StrideConv.get();
17139 TheCall->setArg(3, StrideExpr);
17140
17141 if (MaybeRows) {
17142 if (std::optional<llvm::APSInt> Value =
17143 StrideExpr->getIntegerConstantExpr(Context)) {
17144 uint64_t Stride = Value->getZExtValue();
17145 if (Stride < *MaybeRows) {
17146 Diag(StrideExpr->getBeginLoc(),
17147 diag::err_builtin_matrix_stride_too_small);
17148 ArgError = true;
17149 }
17150 }
17151 }
17152
17153 if (ArgError || !MaybeRows || !MaybeColumns)
17154 return ExprError();
17155
17156 TheCall->setType(
17157 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17158 return CallResult;
17159}
17160
17161ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17162 ExprResult CallResult) {
17163 if (!getLangOpts().MatrixTypes) {
17164 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17165 return ExprError();
17166 }
17167
17168 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17170 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17171 << /*column*/ 1 << /*store*/ 1;
17172 return ExprError();
17173 }
17174
17175 if (checkArgCount(TheCall, 3))
17176 return ExprError();
17177
17178 unsigned PtrArgIdx = 1;
17179 Expr *MatrixExpr = TheCall->getArg(0);
17180 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17181 Expr *StrideExpr = TheCall->getArg(2);
17182
17183 bool ArgError = false;
17184
17185 {
17186 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17187 if (MatrixConv.isInvalid())
17188 return MatrixConv;
17189 MatrixExpr = MatrixConv.get();
17190 TheCall->setArg(0, MatrixExpr);
17191 }
17192 if (MatrixExpr->isTypeDependent()) {
17193 TheCall->setType(Context.DependentTy);
17194 return TheCall;
17195 }
17196
17197 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17198 if (!MatrixTy) {
17199 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17200 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17201 ArgError = true;
17202 }
17203
17204 {
17206 if (PtrConv.isInvalid())
17207 return PtrConv;
17208 PtrExpr = PtrConv.get();
17209 TheCall->setArg(1, PtrExpr);
17210 if (PtrExpr->isTypeDependent()) {
17211 TheCall->setType(Context.DependentTy);
17212 return TheCall;
17213 }
17214 }
17215
17216 // Check pointer argument.
17217 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17218 if (!PtrTy) {
17219 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17220 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17221 << PtrExpr->getType();
17222 ArgError = true;
17223 } else {
17224 QualType ElementTy = PtrTy->getPointeeType();
17225 if (ElementTy.isConstQualified()) {
17226 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17227 ArgError = true;
17228 }
17229 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17230 if (MatrixTy &&
17231 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17232 Diag(PtrExpr->getBeginLoc(),
17233 diag::err_builtin_matrix_pointer_arg_mismatch)
17234 << ElementTy << MatrixTy->getElementType();
17235 ArgError = true;
17236 }
17237 }
17238
17239 // Apply default Lvalue conversions and convert the stride expression to
17240 // size_t.
17241 {
17242 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17243 if (StrideConv.isInvalid())
17244 return StrideConv;
17245
17246 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17247 if (StrideConv.isInvalid())
17248 return StrideConv;
17249 StrideExpr = StrideConv.get();
17250 TheCall->setArg(2, StrideExpr);
17251 }
17252
17253 // Check stride argument.
17254 if (MatrixTy) {
17255 if (std::optional<llvm::APSInt> Value =
17256 StrideExpr->getIntegerConstantExpr(Context)) {
17257 uint64_t Stride = Value->getZExtValue();
17258 if (Stride < MatrixTy->getNumRows()) {
17259 Diag(StrideExpr->getBeginLoc(),
17260 diag::err_builtin_matrix_stride_too_small);
17261 ArgError = true;
17262 }
17263 }
17264 }
17265
17266 if (ArgError)
17267 return ExprError();
17268
17269 return CallResult;
17270}
17271
17273 const NamedDecl *Callee) {
17274 // This warning does not make sense in code that has no runtime behavior.
17276 return;
17277
17278 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17279
17280 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17281 return;
17282
17283 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17284 // all TCBs the callee is a part of.
17285 llvm::StringSet<> CalleeTCBs;
17286 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17287 CalleeTCBs.insert(A->getTCBName());
17288 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17289 CalleeTCBs.insert(A->getTCBName());
17290
17291 // Go through the TCBs the caller is a part of and emit warnings if Caller
17292 // is in a TCB that the Callee is not.
17293 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17294 StringRef CallerTCB = A->getTCBName();
17295 if (CalleeTCBs.count(CallerTCB) == 0) {
17296 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17297 << Callee << CallerTCB;
17298 }
17299 }
17300}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
#define SM(sm)
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
llvm::json::Object Object
llvm::json::Array Array
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static QualType getVectorElementType(ASTContext &Context, QualType VecTy)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
__device__ __2f16 float __ockl_bool s
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * toString() const
const char * getStart() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:508
bool isVector() const
Definition APValue.h:491
APSInt & getComplexIntImag()
Definition APValue.h:546
bool isComplexInt() const
Definition APValue.h:488
bool isFloat() const
Definition APValue.h:486
bool isComplexFloat() const
Definition APValue.h:489
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
bool isInt() const
Definition APValue.h:485
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:606
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
bool isMatrix() const
Definition APValue.h:492
unsigned getMatrixNumElements() const
Definition APValue.h:603
bool isAddrLabelDiff() const
Definition APValue.h:497
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
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:805
Builtin::Context & BuiltinInfo
Definition ASTContext.h:807
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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:858
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:924
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:7298
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7302
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:3777
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3791
QualType getElementType() const
Definition TypeBase.h:3789
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6929
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7078
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7060
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:3597
This class is used for builtin types like 'int'.
Definition TypeBase.h:3219
bool isInteger() const
Definition TypeBase.h:3280
bool isFloatingPoint() const
Definition TypeBase.h:3292
bool isSignedInteger() const
Definition TypeBase.h:3284
bool isUnsignedInteger() const
Definition TypeBase.h:3288
Kind getKind() const
Definition TypeBase.h:3267
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:2952
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:158
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:115
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:75
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:3815
QualType desugar() const
Definition TypeBase.h:3916
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3871
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:4442
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4464
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:5320
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp: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:2003
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3441
Represents an enum.
Definition Decl.h:4029
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4261
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4202
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:4322
Represents a member of a struct/union/class.
Definition Decl.h:3178
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3281
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4747
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3414
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3294
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:2018
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4548
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3757
param_iterator param_end()
Definition Decl.h:2805
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3860
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
param_iterator param_begin()
Definition Decl.h:2804
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3128
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4324
bool isStatic() const
Definition Decl.h:2947
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4139
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4125
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3821
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5362
unsigned getNumParams() const
Definition TypeBase.h:5640
QualType getParamType(unsigned i) const
Definition TypeBase.h:5642
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5766
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5651
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5761
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5647
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4558
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4867
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4863
QualType getReturnType() const
Definition TypeBase.h:4898
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
Describes an C or C++ initializer list.
Definition Expr.h:5302
ArrayRef< Expr * > inits() const
Definition Expr.h: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:4392
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4413
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:3708
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:1808
Pointer-authentication qualifiers.
Definition TypeBase.h:152
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:232
bool isAddressDiscriminated() const
Definition TypeBase.h:265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3383
QualType getPointeeType() const
Definition TypeBase.h:3393
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6805
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:8520
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2961
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1464
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1225
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:8436
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8562
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8476
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1449
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8488
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8530
void removeLocalVolatile()
Definition TypeBase.h:8552
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1190
void removeLocalConst()
Definition TypeBase.h:8544
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8509
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8557
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8482
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1343
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1453
@ 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:4343
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4429
field_range fields() const
Definition Decl.h:4546
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4421
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)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp:30
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:289
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:535
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h: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:7010
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
SemaHexagon & Hexagon()
Definition Sema.h:1488
SemaSYCL & SYCL()
Definition Sema.h:1558
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:838
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1578
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ASTContext & Context
Definition Sema.h:1308
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
SemaObjC & ObjC()
Definition Sema.h:1518
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1373
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:759
ASTContext & getASTContext() const
Definition Sema.h:939
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2637
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
AtomicArgumentOrder
Definition Sema.h:2744
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:932
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
SemaBPF & BPF()
Definition Sema.h:1463
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
SemaDirectX & DirectX()
Definition Sema.h:1478
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition Sema.h:1306
static const uint64_t MaximumAlignment
Definition Sema.h:1235
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:957
SemaHLSL & HLSL()
Definition Sema.h:1483
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1503
SemaRISCV & RISCV()
Definition Sema.h:1548
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2810
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7046
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:15540
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:14063
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:6310
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:6498
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:3856
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3836
bool isUnion() const
Definition Decl.h:3946
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:6273
A container of type source information.
Definition TypeBase.h:8407
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:8418
The base class of the type hierarchy.
Definition TypeBase.h:1871
bool isBlockPointerType() const
Definition TypeBase.h:8693
bool isVoidType() const
Definition TypeBase.h:9039
bool isBooleanType() const
Definition TypeBase.h:9176
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9226
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2355
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9206
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2119
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2517
bool isArrayType() const
Definition TypeBase.h:8772
bool isCharType() const
Definition Type.cpp:2193
bool isFunctionPointerType() const
Definition TypeBase.h:8740
bool isPointerType() const
Definition TypeBase.h:8673
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9083
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9333
bool isReferenceType() const
Definition TypeBase.h:8697
bool isEnumeralType() const
Definition TypeBase.h:8804
bool isScalarType() const
Definition TypeBase.h:9145
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1958
bool isVariableArrayType() const
Definition TypeBase.h:8784
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorType() const
Definition TypeBase.h:8816
bool isExtVectorBoolType() const
Definition TypeBase.h:8820
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2740
bool isBitIntType() const
Definition TypeBase.h:8948
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9008
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8796
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2837
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2310
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3174
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9219
bool isMemberPointerType() const
Definition TypeBase.h:8754
bool isAtomicType() const
Definition TypeBase.h:8865
bool isFunctionProtoType() const
Definition TypeBase.h:2654
bool isMatrixType() const
Definition TypeBase.h:8836
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3196
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:2855
bool isUnscopedEnumerationType() const
Definition Type.cpp:2186
bool isObjCObjectType() const
Definition TypeBase.h:8856
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9319
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9182
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2563
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8669
bool isObjCObjectPointerType() const
Definition TypeBase.h:8852
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2397
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isVectorType() const
Definition TypeBase.h:8812
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isFloatingType() const
Definition Type.cpp:2389
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2332
bool isAnyPointerType() const
Definition TypeBase.h:8681
TypeClass getTypeClass() const
Definition TypeBase.h:2438
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2464
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9266
bool isNullPtrType() const
Definition TypeBase.h:9076
bool isRecordType() const
Definition TypeBase.h:8800
bool isObjCRetainableType() const
Definition Type.cpp:5416
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2663
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5147
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2728
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3580
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:1034
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1122
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5576
Represents a variable declaration or definition.
Definition Decl.h:924
Represents a GCC generic vector type.
Definition TypeBase.h:4230
unsigned getNumElements() const
Definition TypeBase.h:4245
QualType getElementType() const
Definition TypeBase.h:4244
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:1464
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1449
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1442
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1456
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2687
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1410
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1471
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:4191
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5982
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5975
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
Extra information about a function prototype.
Definition TypeBase.h:5447
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:6904
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2659
#define log2(__x)
Definition tgmath.h:970