clang 24.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
18#include "clang/AST/Attr.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
32#include "clang/AST/NSAPI.h"
36#include "clang/AST/Stmt.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
48#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any unrecoverable errors, even if we managed
545 // to build the call.
546 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150namespace {
1151/// Helper class for buffer overflow/overread checking in fortified functions.
1152class FortifiedBufferChecker {
1153public:
1154 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1155 : S(S), TheCall(TheCall), FD(FD),
1156 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1157 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1158 SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1159 }
1160
1161 std::optional<unsigned> TranslateIndex(unsigned Index) {
1162 // If we refer to a diagnose_as_builtin attribute, we need to change the
1163 // argument index to refer to the arguments of the called function. Unless
1164 // the index is out of bounds, which presumably means it's a variadic
1165 // function.
1166 unsigned NewIndex = Index;
1167 if (DABAttr) {
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 NewIndex = Index < DABIndices ? DABAttr->argIndices_begin()[Index]
1170 : Index - DABIndices + FD->getNumParams();
1171 }
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 /// Evaluate the argument at Index as an integer constant while preserving
1178 /// its signedness, or return std::nullopt if it cannot be evaluated.
1179 std::optional<llvm::APSInt> EvaluateIntegerArgument(unsigned Index) {
1180 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1181 if (!IndexOptional)
1182 return std::nullopt;
1183 Expr::EvalResult Result;
1184 Expr *Arg = TheCall->getArg(*IndexOptional);
1185 if (!Arg->EvaluateAsInt(Result, S.getASTContext()))
1186 return std::nullopt;
1187
1188 return Result.Val.getInt();
1189 }
1190
1191 std::optional<llvm::APSInt>
1192 ComputeExplicitObjectSizeArgument(unsigned Index) {
1193 std::optional<llvm::APSInt> Integer = EvaluateIntegerArgument(Index);
1194 if (!Integer)
1195 return std::nullopt;
1196 *Integer = Integer->extOrTrunc(SizeTypeWidth);
1197 Integer->setIsUnsigned(true);
1198 return Integer;
1199 }
1200
1201 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1202 // If the parameter has a pass_object_size attribute, then we should use its
1203 // (potentially) more strict checking mode. Otherwise, conservatively assume
1204 // type 0.
1205 int BOSType = 0;
1206 // This check can fail for variadic functions.
1207 if (Index < FD->getNumParams()) {
1208 if (const auto *POS =
1209 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1210 BOSType = POS->getType();
1211 }
1212
1213 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1214 if (!IndexOptional)
1215 return std::nullopt;
1216
1217 const Expr *ObjArg = TheCall->getArg(*IndexOptional);
1218 if (std::optional<uint64_t> ObjSize =
1219 ObjArg->tryEvaluateObjectSize(S.getASTContext(), BOSType)) {
1220 // Get the object size in the target's size_t width.
1221 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1222 }
1223 return std::nullopt;
1224 }
1225
1226 std::optional<llvm::APSInt>
1227 ComputeExplicitObjectSizeArgumentProduct(unsigned LIndex, unsigned RIndex) {
1228 auto L = ComputeExplicitObjectSizeArgument(LIndex);
1229 auto R = ComputeExplicitObjectSizeArgument(RIndex);
1230 if (!L || !R)
1231 return std::nullopt;
1232
1233 unsigned W =
1234 2 * std::max({L->getBitWidth(), R->getBitWidth(), SizeTypeWidth});
1235
1236 llvm::APSInt LE = L->extOrTrunc(W);
1237 llvm::APSInt RE = R->extOrTrunc(W);
1238
1239 return LE * RE;
1240 }
1241
1242 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1243 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1244 if (!IndexOptional)
1245 return std::nullopt;
1246 unsigned NewIndex = *IndexOptional;
1247
1248 const Expr *ObjArg = TheCall->getArg(NewIndex);
1249
1250 if (std::optional<uint64_t> Result =
1251 ObjArg->tryEvaluateStrLen(S.getASTContext())) {
1252 // Add 1 for null byte.
1253 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1254 }
1255 return std::nullopt;
1256 }
1257
1258 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1259
1260 unsigned getBuiltinID() const {
1261 const FunctionDecl *UseDecl = FD;
1262 if (DABAttr) {
1263 UseDecl = DABAttr->getFunction();
1264 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1265 }
1266 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1267 }
1268
1269 /// Return function name after stripping __builtin_ and _chk affixes.
1270 std::string getFunctionName() const {
1271 unsigned ID = getBuiltinID();
1272 if (!ID) {
1273 // Use callee name directly if not a builtin.
1274 const FunctionDecl *Callee = TheCall->getDirectCallee();
1275 assert(Callee && "expected callee");
1276 return Callee->getName().str();
1277 }
1278 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1279 StringRef Ref = Name;
1280 // Strip __builtin___*_chk or __builtin_ prefix.
1281 if (!(Ref.consume_front("__builtin___") && Ref.consume_back("_chk")))
1282 Ref.consume_front("__builtin_");
1283 assert(!Ref.empty() && "expected non-empty function name");
1284 return Ref.str();
1285 }
1286
1287 /// Check for source buffer overread in memory functions.
1288 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1290 return;
1291
1292 const Expr *SrcArg = TheCall->getArg(SrcArgIdx);
1293 const Expr *SizeArg = TheCall->getArg(SizeArgIdx);
1294 if (SrcArg->isInstantiationDependent() ||
1295 SizeArg->isInstantiationDependent())
1296 return;
1297
1298 std::optional<llvm::APSInt> CopyLen =
1299 ComputeExplicitObjectSizeArgument(SizeArgIdx);
1300 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(SrcArgIdx);
1301
1302 if (!CopyLen || !SrcBufSize)
1303 return;
1304
1305 // Warn only if copy length exceeds source buffer size.
1306 if (llvm::APSInt::compareValues(*CopyLen, *SrcBufSize) <= 0)
1307 return;
1308
1309 S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1310 S.PDiag(diag::warn_stringop_overread)
1311 << getFunctionName() << CopyLen->getZExtValue()
1312 << SrcBufSize->getZExtValue());
1313 }
1314
1315private:
1316 Sema &S;
1317 CallExpr *TheCall;
1318 FunctionDecl *FD;
1319 const DiagnoseAsBuiltinAttr *DABAttr;
1320 unsigned SizeTypeWidth;
1321};
1322} // anonymous namespace
1323
1324void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1325 CallExpr *TheCall) {
1327 return;
1328
1329 FortifiedBufferChecker Checker(*this, FD, TheCall);
1330
1331 unsigned BuiltinID = Checker.getBuiltinID();
1332 if (!BuiltinID)
1333 return;
1334
1335 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1336
1337 std::optional<llvm::APSInt> AccessSize;
1338 std::optional<llvm::APSInt> BufferSize;
1339 unsigned DiagID = 0;
1340
1341 switch (BuiltinID) {
1342 default:
1343 return;
1344 case Builtin::BI__builtin_strcat:
1345 case Builtin::BIstrcat:
1346 case Builtin::BI__builtin_stpcpy:
1347 case Builtin::BIstpcpy:
1348 case Builtin::BI__builtin_strcpy:
1349 case Builtin::BIstrcpy: {
1350 DiagID = diag::warn_fortify_strlen_overflow;
1351 AccessSize = Checker.ComputeStrLenArgument(1);
1352 BufferSize = Checker.ComputeSizeArgument(0);
1353 break;
1354 }
1355
1356 case Builtin::BI__builtin___strcat_chk:
1357 case Builtin::BI__builtin___stpcpy_chk:
1358 case Builtin::BI__builtin___strcpy_chk: {
1359 DiagID = diag::warn_fortify_strlen_overflow;
1360 AccessSize = Checker.ComputeStrLenArgument(1);
1361 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1362 break;
1363 }
1364
1365 case Builtin::BIscanf:
1366 case Builtin::BIfscanf:
1367 case Builtin::BIsscanf: {
1368 unsigned FormatIndex = 1;
1369 unsigned DataIndex = 2;
1370 if (BuiltinID == Builtin::BIscanf) {
1371 FormatIndex = 0;
1372 DataIndex = 1;
1373 }
1374
1375 const auto *FormatExpr =
1376 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1377
1378 StringRef FormatStrRef;
1379 size_t StrLen;
1380 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1381 return;
1382
1383 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1384 unsigned SourceSize) {
1385 DiagID = diag::warn_fortify_scanf_overflow;
1386 unsigned Index = ArgIndex + DataIndex;
1387 std::string FunctionName = Checker.getFunctionName();
1388 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1389 PDiag(DiagID) << FunctionName << (Index + 1)
1390 << DestSize << SourceSize);
1391 };
1392
1393 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1394 return Checker.ComputeSizeArgument(Index + DataIndex);
1395 };
1396 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1397 const char *FormatBytes = FormatStrRef.data();
1399 FormatBytes + StrLen, getLangOpts(),
1400 Context.getTargetInfo());
1401
1402 // Unlike the other cases, in this one we have already issued the diagnostic
1403 // here, so no need to continue (because unlike the other cases, here the
1404 // diagnostic refers to the argument number).
1405 return;
1406 }
1407
1408 case Builtin::BIsprintf:
1409 case Builtin::BI__builtin_sprintf:
1410 case Builtin::BI__builtin___sprintf_chk:
1411 case Builtin::BIvsprintf:
1412 case Builtin::BI__builtin_vsprintf:
1413 case Builtin::BI__builtin___vsprintf_chk: {
1414 bool IsChk = BuiltinID == Builtin::BI__builtin___sprintf_chk ||
1415 BuiltinID == Builtin::BI__builtin___vsprintf_chk;
1416 std::optional<unsigned> FormatIndex = Checker.TranslateIndex(IsChk ? 3 : 1);
1417 if (!FormatIndex)
1418 return;
1419 const auto *FormatExpr =
1420 TheCall->getArg(*FormatIndex)->IgnoreParenImpCasts();
1421
1422 StringRef FormatStrRef;
1423 size_t StrLen;
1424 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1425 EstimateSizeFormatHandler H(FormatStrRef);
1426 const char *FormatBytes = FormatStrRef.data();
1428 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1429 Context.getTargetInfo(), false)) {
1430 DiagID = H.isKernelCompatible()
1431 ? diag::warn_format_overflow
1432 : diag::warn_format_overflow_non_kprintf;
1433 AccessSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1434 .extOrTrunc(SizeTypeWidth);
1435 if (IsChk) {
1436 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1437 } else {
1438 BufferSize = Checker.ComputeSizeArgument(0);
1439 }
1440 break;
1441 }
1442 }
1443 return;
1444 }
1445 case Builtin::BI__builtin___memcpy_chk:
1446 case Builtin::BI__builtin___memmove_chk:
1447 case Builtin::BI__builtin___memset_chk:
1448 case Builtin::BI__builtin___strlcat_chk:
1449 case Builtin::BI__builtin___strlcpy_chk:
1450 case Builtin::BI__builtin___strncat_chk:
1451 case Builtin::BI__builtin___strncpy_chk:
1452 case Builtin::BI__builtin___stpncpy_chk:
1453 case Builtin::BI__builtin___memccpy_chk:
1454 case Builtin::BI__builtin___mempcpy_chk: {
1455 DiagID = diag::warn_builtin_chk_overflow;
1456 AccessSize =
1457 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1458 BufferSize =
1459 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1460
1461 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1462 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1463 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1464 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1465 }
1466 break;
1467 }
1468
1469 case Builtin::BI__builtin___snprintf_chk:
1470 case Builtin::BI__builtin___vsnprintf_chk: {
1471 DiagID = diag::warn_builtin_chk_overflow;
1472 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1473 BufferSize = Checker.ComputeExplicitObjectSizeArgument(3);
1474 break;
1475 }
1476
1477 case Builtin::BIstrncat:
1478 case Builtin::BI__builtin_strncat:
1479 case Builtin::BIstrncpy:
1480 case Builtin::BI__builtin_strncpy:
1481 case Builtin::BIstpncpy:
1482 case Builtin::BI__builtin_stpncpy:
1483 case Builtin::BIstrlcat:
1484 case Builtin::BI__builtin_strlcat:
1485 case Builtin::BIstrlcpy:
1486 case Builtin::BI__builtin_strlcpy: {
1487 // Whether these functions overflow depends on the runtime strlen of the
1488 // string, not just the buffer size, so emitting the "always overflow"
1489 // diagnostic isn't quite right. We should still diagnose passing a buffer
1490 // size larger than the destination buffer though; this is a runtime abort
1491 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1492 DiagID = diag::warn_fortify_source_size_mismatch;
1493 AccessSize =
1494 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1495 BufferSize = Checker.ComputeSizeArgument(0);
1496 break;
1497 }
1498
1499 case Builtin::BIrecv:
1500 case Builtin::BIrecvfrom: {
1501 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1502 if (TheCall->getNumArgs() != ExpectedArgs ||
1503 !TheCall->getArg(1)->getType()->isPointerType() ||
1504 !TheCall->getArg(2)->getType()->isIntegerType())
1505 return;
1506 DiagID = diag::warn_fortify_source_size_mismatch;
1507 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1508 BufferSize = Checker.ComputeSizeArgument(1);
1509 break;
1510 }
1511
1512 case Builtin::BIpoll:
1513 case Builtin::BIppoll:
1514 case Builtin::BIppoll64: {
1515 unsigned ExpectedArgs = BuiltinID == Builtin::BIpoll ? 3 : 4;
1516 if (TheCall->getNumArgs() != ExpectedArgs ||
1517 !TheCall->getArg(1)->getType()->isIntegerType())
1518 return;
1519 QualType PointeeTy = TheCall->getArg(0)->getType()->getPointeeType();
1520 if (PointeeTy.isNull())
1521 return;
1522 const RecordDecl *RD = PointeeTy->getAsRecordDecl();
1523 if (!RD || !RD->getIdentifier() || RD->getName() != "pollfd")
1524 return;
1525 if (BuiltinID == Builtin::BIpoll) {
1526 if (!TheCall->getArg(2)->getType()->isIntegerType())
1527 return;
1528 } else {
1529 QualType TmoPointeeTy = TheCall->getArg(2)->getType()->getPointeeType();
1530 if (TmoPointeeTy.isNull())
1531 return;
1532 const RecordDecl *TmoRD = TmoPointeeTy->getAsRecordDecl();
1533 if (!TmoRD || !TmoRD->getIdentifier() || TmoRD->getName() != "timespec" ||
1534 !TheCall->getArg(3)->getType()->isPointerType())
1535 return;
1536 }
1537 std::optional<CharUnits> ElemSize =
1538 Context.getTypeSizeInCharsIfKnown(PointeeTy);
1539 if (!ElemSize)
1540 return;
1541 std::optional<llvm::APSInt> Count =
1542 Checker.ComputeExplicitObjectSizeArgument(1);
1543 if (!Count)
1544 return;
1545 DiagID = diag::warn_fortify_source_size_mismatch;
1546 unsigned WideWidth = SizeTypeWidth * 2;
1547 AccessSize = Count->extOrTrunc(WideWidth) *
1548 llvm::APSInt(llvm::APInt(WideWidth, ElemSize->getQuantity()),
1549 /*isUnsigned=*/true);
1550 BufferSize = Checker.ComputeSizeArgument(0);
1551 break;
1552 }
1553
1554 case Builtin::BIbzero:
1555 case Builtin::BI__builtin_bzero:
1556 case Builtin::BImemcpy:
1557 case Builtin::BI__builtin_memcpy:
1558 case Builtin::BImemmove:
1559 case Builtin::BI__builtin_memmove:
1560 case Builtin::BImemset:
1561 case Builtin::BI__builtin_memset:
1562 case Builtin::BImempcpy:
1563 case Builtin::BI__builtin_mempcpy: {
1564 DiagID = diag::warn_fortify_source_overflow;
1565 AccessSize =
1566 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1567 BufferSize = Checker.ComputeSizeArgument(0);
1568
1569 // Buffer overread doesn't make sense for memset/bzero.
1570 if (BuiltinID != Builtin::BImemset &&
1571 BuiltinID != Builtin::BI__builtin_memset &&
1572 BuiltinID != Builtin::BIbzero &&
1573 BuiltinID != Builtin::BI__builtin_bzero) {
1574 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1575 }
1576 break;
1577 }
1578 case Builtin::BIbcopy:
1579 case Builtin::BI__builtin_bcopy: {
1580 DiagID = diag::warn_fortify_source_overflow;
1581 AccessSize =
1582 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1583 BufferSize = Checker.ComputeSizeArgument(1);
1584 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1585 break;
1586 }
1587 case Builtin::BIfread: {
1588 DiagID = diag::warn_fortify_source_overflow;
1589 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1590 BufferSize = Checker.ComputeSizeArgument(0);
1591 break;
1592 }
1593 case Builtin::BIfwrite: {
1594 DiagID = diag::warn_fortify_source_overread;
1595 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1596 BufferSize = Checker.ComputeSizeArgument(0);
1597 break;
1598 }
1599 case Builtin::BIfgets: {
1600 AccessSize = Checker.EvaluateIntegerArgument(1);
1601
1602 if (AccessSize && AccessSize->isNegative()) {
1603 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1604 PDiag(diag::warn_fortify_source_negative_size)
1605 << Checker.getFunctionName());
1606 return;
1607 }
1608
1609 DiagID = diag::warn_fortify_source_size_mismatch;
1610 BufferSize = Checker.ComputeSizeArgument(0);
1611 break;
1612 }
1613 // memchr(buf, val, size)
1614 case Builtin::BImemchr:
1615 case Builtin::BI__builtin_memchr: {
1616 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1617 return;
1618 }
1619
1620 // memcmp/bcmp(buf0, buf1, size)
1621 // Two checks since each buffer is read
1622 case Builtin::BImemcmp:
1623 case Builtin::BI__builtin_memcmp:
1624 case Builtin::BIbcmp:
1625 case Builtin::BI__builtin_bcmp: {
1626 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1627 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1628 return;
1629 }
1630 case Builtin::BIsnprintf:
1631 case Builtin::BI__builtin_snprintf:
1632 case Builtin::BIvsnprintf:
1633 case Builtin::BI__builtin_vsnprintf: {
1634 DiagID = diag::warn_fortify_source_size_mismatch;
1635 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1636 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1637 StringRef FormatStrRef;
1638 size_t StrLen;
1639 if (AccessSize &&
1640 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1641 EstimateSizeFormatHandler H(FormatStrRef);
1642 const char *FormatBytes = FormatStrRef.data();
1644 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1645 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1646 llvm::APSInt FormatSize =
1647 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1648 .extOrTrunc(SizeTypeWidth);
1649 if (FormatSize > *AccessSize && *AccessSize != 0) {
1650 unsigned TruncationDiagID =
1651 H.isKernelCompatible() ? diag::warn_format_truncation
1652 : diag::warn_format_truncation_non_kprintf;
1653 SmallString<16> SpecifiedSizeStr;
1654 SmallString<16> FormatSizeStr;
1655 AccessSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1656 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1657 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1658 PDiag(TruncationDiagID)
1659 << Checker.getFunctionName()
1660 << SpecifiedSizeStr << FormatSizeStr);
1661 }
1662 }
1663 }
1664 BufferSize = Checker.ComputeSizeArgument(0);
1665 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1666 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1667 IdentifierInfo *FnInfo = FD->getIdentifier();
1668 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1669 }
1670 }
1671
1672 if (!AccessSize || !BufferSize ||
1673 llvm::APSInt::compareValues(*AccessSize, *BufferSize) <= 0)
1674 return;
1675
1676 std::string FunctionName = Checker.getFunctionName();
1677
1678 SmallString<16> BufferSizeStr;
1679 SmallString<16> AccessSizeStr;
1680 BufferSize->toString(BufferSizeStr, /*Radix=*/10);
1681 AccessSize->toString(AccessSizeStr, /*Radix=*/10);
1682 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1683 PDiag(DiagID)
1684 << FunctionName << BufferSizeStr << AccessSizeStr);
1685}
1686
1687void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1688 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1689 return;
1690
1691 // Recognize the libc function by builtin identity rather than by name and
1692 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1693 // builtin id is attached to any file-scope, C-linkage declaration of umask
1694 // regardless of the libc's mode_t spelling -- including a hand-written
1695 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1696 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1697 if (FD->getBuiltinID() != Builtin::BIumask)
1698 return;
1699
1700 // umask(mode_t): warn when the constant-evaluated argument has bits set
1701 // outside the file-permission mask (0777). Those bits are ignored.
1702 if (TheCall->getNumArgs() != 1)
1703 return;
1704 Expr *Arg = TheCall->getArg(0);
1705 if (!Arg->getType()->isIntegerType())
1706 return;
1707 Expr::EvalResult R;
1708 if (!Arg->EvaluateAsInt(R, getASTContext()))
1709 return;
1710 // Operate on the raw two's-complement bit pattern so that negative literals
1711 // (which convert to large unsigned mode_t values) are caught.
1712 llvm::APInt RawValue = R.Val.getInt();
1713 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1714 llvm::APInt Extra = RawValue & ~Mask;
1715 if (Extra == 0)
1716 return;
1717 SmallString<16> ExtraStr;
1718 Extra.toString(ExtraStr, /*Radix=*/8, /*Signed=*/false);
1719 Diag(TheCall->getBeginLoc(), diag::warn_fortify_umask_unused_bits)
1720 << ExtraStr;
1721}
1722
1723static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1724 Scope::ScopeFlags NeededScopeFlags,
1725 unsigned DiagID) {
1726 // Scopes aren't available during instantiation. Fortunately, builtin
1727 // functions cannot be template args so they cannot be formed through template
1728 // instantiation. Therefore checking once during the parse is sufficient.
1729 if (SemaRef.inTemplateInstantiation())
1730 return false;
1731
1732 Scope *S = SemaRef.getCurScope();
1733 while (S && !S->isSEHExceptScope())
1734 S = S->getParent();
1735 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1736 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1737 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1738 << DRE->getDecl()->getIdentifier();
1739 return true;
1740 }
1741
1742 return false;
1743}
1744
1745// In OpenCL, __builtin_alloca_* should return a pointer to address space
1746// that corresponds to the stack address space i.e private address space.
1747static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1748 QualType RT = TheCall->getType();
1749 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1750 "__builtin_alloca has invalid address space");
1751
1752 RT = RT->getPointeeType();
1754 TheCall->setType(S.Context.getPointerType(RT));
1755}
1756
1757static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1758 if (S.checkArgCountAtLeast(TheCall, 1))
1759 return true;
1760
1761 for (Expr *Arg : TheCall->arguments()) {
1762 // If argument is dependent on a template parameter, we can't resolve now.
1763 if (Arg->isTypeDependent() || Arg->isValueDependent())
1764 continue;
1765 // Reject void types.
1766 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1767 if (ArgTy->isVoidType())
1768 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1769 }
1770
1771 TheCall->setType(S.Context.getSizeType());
1772 return false;
1773}
1774
1775namespace {
1776enum PointerAuthOpKind {
1777 PAO_Strip,
1778 PAO_Sign,
1779 PAO_Auth,
1780 PAO_SignGeneric,
1781 PAO_Discriminator,
1782 PAO_BlendPointer,
1783 PAO_BlendInteger,
1784 PAO_BlendPC
1785};
1786}
1787
1789 if (getLangOpts().PointerAuthIntrinsics)
1790 return false;
1791
1792 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1793 return true;
1794}
1795
1796static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1798}
1799
1800static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1801 // Convert it to type 'int'.
1802 if (S.convertArgumentToType(Arg, S.Context.IntTy))
1803 return true;
1804
1805 // Value-dependent expressions are okay; wait for template instantiation.
1806 if (Arg->isValueDependent())
1807 return false;
1808
1809 unsigned KeyValue;
1810 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1811}
1812
1814 // Attempt to constant-evaluate the expression.
1815 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1816 if (!KeyValue) {
1817 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1818 << 0 << Arg->getSourceRange();
1819 return true;
1820 }
1821
1822 // Ask the target to validate the key parameter.
1823 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1825 {
1826 llvm::raw_svector_ostream Str(Value);
1827 Str << *KeyValue;
1828 }
1829
1830 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1831 << Value << Arg->getSourceRange();
1832 return true;
1833 }
1834
1835 Result = KeyValue->getZExtValue();
1836 return false;
1837}
1838
1841 unsigned &IntVal) {
1842 if (!Arg) {
1843 IntVal = 0;
1844 return true;
1845 }
1846
1847 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1848 if (!Result) {
1849 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1850 return false;
1851 }
1852
1853 unsigned Max;
1854 bool IsAddrDiscArg = false;
1855
1856 switch (Kind) {
1858 Max = 1;
1859 IsAddrDiscArg = true;
1860 break;
1863 break;
1864 };
1865
1867 if (IsAddrDiscArg)
1868 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1869 << Result->getExtValue();
1870 else
1871 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1872 << Result->getExtValue() << Max;
1873
1874 return false;
1875 };
1876
1877 IntVal = Result->getZExtValue();
1878 return true;
1879}
1880
1881static std::pair<const ValueDecl *, CharUnits>
1883 // Must evaluate as a pointer.
1885 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1886 return {nullptr, CharUnits()};
1887
1888 const auto *BaseDecl =
1889 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1890 if (!BaseDecl)
1891 return {nullptr, CharUnits()};
1892
1893 return {BaseDecl, Result.Val.getLValueOffset()};
1894}
1895
1896static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1897 bool RequireConstant = false) {
1898 if (Arg->hasPlaceholderType()) {
1900 if (R.isInvalid())
1901 return true;
1902 Arg = R.get();
1903 }
1904
1905 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1906 return OpKind != PAO_BlendInteger;
1907 };
1908 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1909 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1910 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1911 };
1912
1913 // Require the value to have the right range of type.
1914 QualType ExpectedTy;
1915 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1916 ExpectedTy = Arg->getType().getUnqualifiedType();
1917 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1918 ExpectedTy = S.Context.VoidPtrTy;
1919 } else if (AllowsInteger(OpKind) &&
1921 ExpectedTy = S.Context.getUIntPtrType();
1922
1923 } else {
1924 // Diagnose the failures.
1925 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1926 << unsigned(OpKind == PAO_Discriminator ? 1
1927 : OpKind == PAO_BlendPointer ? 2
1928 : OpKind == PAO_BlendInteger ? 3
1929 : OpKind == PAO_BlendPC ? 4
1930 : 0)
1931 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1932 << Arg->getType() << Arg->getSourceRange();
1933 return true;
1934 }
1935
1936 // Convert to that type. This should just be an lvalue-to-rvalue
1937 // conversion.
1938 if (S.convertArgumentToType(Arg, ExpectedTy))
1939 return true;
1940
1941 if (!RequireConstant) {
1942 // Warn about null pointers for non-generic sign and auth operations.
1943 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1945 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1946 ? diag::warn_ptrauth_sign_null_pointer
1947 : diag::warn_ptrauth_auth_null_pointer)
1948 << Arg->getSourceRange();
1949 }
1950
1951 return false;
1952 }
1953
1954 // Perform special checking on the arguments to ptrauth_sign_constant.
1955
1956 // The main argument.
1957 if (OpKind == PAO_Sign) {
1958 // Require the value we're signing to have a special form.
1959 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1960 bool Invalid;
1961
1962 // Must be rooted in a declaration reference.
1963 if (!BaseDecl)
1964 Invalid = true;
1965
1966 // If it's a function declaration, we can't have an offset.
1967 else if (isa<FunctionDecl>(BaseDecl))
1968 Invalid = !Offset.isZero();
1969
1970 // Otherwise we're fine.
1971 else
1972 Invalid = false;
1973
1974 if (Invalid)
1975 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1976 return Invalid;
1977 }
1978
1979 // The discriminator argument.
1980 assert(OpKind == PAO_Discriminator);
1981
1982 // Must be a pointer or integer or blend thereof.
1983 Expr *Pointer = nullptr;
1984 Expr *Integer = nullptr;
1985 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1986 if (Call->getBuiltinCallee() ==
1987 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1988 Pointer = Call->getArg(0);
1989 Integer = Call->getArg(1);
1990 }
1991 }
1992 if (!Pointer && !Integer) {
1993 if (Arg->getType()->isPointerType())
1994 Pointer = Arg;
1995 else
1996 Integer = Arg;
1997 }
1998
1999 // Check the pointer.
2000 bool Invalid = false;
2001 if (Pointer) {
2002 assert(Pointer->getType()->isPointerType());
2003
2004 // TODO: if we're initializing a global, check that the address is
2005 // somehow related to what we're initializing. This probably will
2006 // never really be feasible and we'll have to catch it at link-time.
2007 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
2008 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
2009 Invalid = true;
2010 }
2011
2012 // Check the integer.
2013 if (Integer) {
2014 assert(Integer->getType()->isIntegerType());
2015 if (!Integer->isEvaluatable(S.Context))
2016 Invalid = true;
2017 }
2018
2019 if (Invalid)
2020 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
2021 return Invalid;
2022}
2023
2025 if (S.checkArgCount(Call, 2))
2026 return ExprError();
2028 return ExprError();
2029 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
2030 checkPointerAuthKey(S, Call->getArgs()[1]))
2031 return ExprError();
2032
2033 Call->setType(Call->getArgs()[0]->getType());
2034 return Call;
2035}
2036
2038 if (S.checkArgCount(Call, 2))
2039 return ExprError();
2041 return ExprError();
2042 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
2043 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
2044 return ExprError();
2045
2046 Call->setType(S.Context.getUIntPtrType());
2047 return Call;
2048}
2049
2051 if (S.checkArgCount(Call, 2))
2052 return ExprError();
2054 return ExprError();
2055 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
2056 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
2057 return ExprError();
2058
2059 Call->setType(S.Context.getUIntPtrType());
2060 return Call;
2061}
2062
2064 PointerAuthOpKind OpKind,
2065 bool RequireConstant) {
2066 if (S.checkArgCount(Call, 3))
2067 return ExprError();
2069 return ExprError();
2070 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
2071 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2072 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
2073 RequireConstant))
2074 return ExprError();
2075
2076 Call->setType(Call->getArgs()[0]->getType());
2077 return Call;
2078}
2079
2081 if (S.checkArgCount(Call, 5))
2082 return ExprError();
2084 return ExprError();
2085 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2086 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2087 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2088 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2089 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
2090 return ExprError();
2091
2092 Call->setType(Call->getArgs()[0]->getType());
2093 return Call;
2094}
2095
2097 if (S.checkArgCount(Call, 6))
2098 return ExprError();
2100 return ExprError();
2101 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2102 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2103 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2104 checkPointerAuthValue(S, Call->getArgs()[3], PAO_BlendPC) ||
2105 checkPointerAuthKey(S, Call->getArgs()[4]) ||
2106 checkPointerAuthValue(S, Call->getArgs()[5], PAO_Discriminator))
2107 return ExprError();
2108
2109 // Validate that the oldKey is IA or IB, not DA or DB.
2110 // This enforces the constraint that auth_with_pc_and_resign only supports
2111 // IA/IB keys for authentication, as only those keys support the PC-based
2112 // signing instructions (paciasppc/pacibsppc).
2113 unsigned OldKey = 0;
2114 if (!S.checkConstantPointerAuthKey(Call->getArgs()[1], OldKey)) {
2116 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2117 OldKey != static_cast<unsigned>(AK::ASIB)) {
2118 S.Diag(Call->getArgs()[1]->getExprLoc(),
2119 diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2120 << OldKey << Call->getArgs()[1]->getSourceRange();
2121 return ExprError();
2122 }
2123 }
2124
2125 Call->setType(Call->getArgs()[0]->getType());
2126 return Call;
2127}
2128
2130 if (S.checkArgCount(Call, 6))
2131 return ExprError();
2133 return ExprError();
2134 const Expr *AddendExpr = Call->getArg(5);
2135 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
2136 if (!AddendIsConstInt) {
2137 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
2138 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
2139 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2140 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
2141 << FDecl->getDeclName() << Arg->getSourceRange();
2142 }
2143 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2144 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2145 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2146 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2147 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
2148 !AddendIsConstInt)
2149 return ExprError();
2150
2151 Call->setType(Call->getArgs()[0]->getType());
2152 return Call;
2153}
2154
2157 return ExprError();
2158
2159 // We've already performed normal call type-checking.
2160 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
2161
2162 // Operand must be an ordinary or UTF-8 string literal.
2163 const auto *Literal = dyn_cast<StringLiteral>(Arg);
2164 if (!Literal || Literal->getCharByteWidth() != 1) {
2165 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
2166 << (Literal ? 1 : 0) << Arg->getSourceRange();
2167 return ExprError();
2168 }
2169
2170 return Call;
2171}
2172
2174 if (S.checkArgCount(Call, 1))
2175 return ExprError();
2176 Expr *FirstArg = Call->getArg(0);
2177 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
2178 if (FirstValue.isInvalid())
2179 return ExprError();
2180 Call->setArg(0, FirstValue.get());
2181 QualType FirstArgType = FirstArg->getType();
2182 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2183 FirstArgType = S.Context.getDecayedType(FirstArgType);
2184
2185 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2186 if (!FirstArgRecord) {
2187 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2188 << /*isPolymorphic=*/0 << FirstArgType;
2189 return ExprError();
2190 }
2191 if (S.RequireCompleteType(
2192 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
2193 diag::err_get_vtable_pointer_requires_complete_type)) {
2194 return ExprError();
2195 }
2196
2197 if (!FirstArgRecord->isPolymorphic()) {
2198 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2199 << /*isPolymorphic=*/1 << FirstArgRecord;
2200 return ExprError();
2201 }
2203 Call->setType(ReturnType);
2204 return Call;
2205}
2206
2208 if (S.checkArgCount(TheCall, 1))
2209 return ExprError();
2210
2211 // Compute __builtin_launder's parameter type from the argument.
2212 // The parameter type is:
2213 // * The type of the argument if it's not an array or function type,
2214 // Otherwise,
2215 // * The decayed argument type.
2216 QualType ParamTy = [&]() {
2217 QualType ArgTy = TheCall->getArg(0)->getType();
2218 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2219 return S.Context.getPointerType(Ty->getElementType());
2220 if (ArgTy->isFunctionType()) {
2221 return S.Context.getPointerType(ArgTy);
2222 }
2223 return ArgTy;
2224 }();
2225
2226 TheCall->setType(ParamTy);
2227
2228 auto DiagSelect = [&]() -> std::optional<unsigned> {
2229 if (!ParamTy->isPointerType())
2230 return 0;
2231 if (ParamTy->isFunctionPointerType())
2232 return 1;
2233 if (ParamTy->isVoidPointerType())
2234 return 2;
2235 return std::optional<unsigned>{};
2236 }();
2237 if (DiagSelect) {
2238 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2239 << *DiagSelect << TheCall->getSourceRange();
2240 return ExprError();
2241 }
2242
2243 // We either have an incomplete class type, or we have a class template
2244 // whose instantiation has not been forced. Example:
2245 //
2246 // template <class T> struct Foo { T value; };
2247 // Foo<int> *p = nullptr;
2248 // auto *d = __builtin_launder(p);
2249 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2250 diag::err_incomplete_type))
2251 return ExprError();
2252
2253 assert(ParamTy->getPointeeType()->isObjectType() &&
2254 "Unhandled non-object pointer case");
2255
2256 InitializedEntity Entity =
2258 ExprResult Arg =
2259 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2260 if (Arg.isInvalid())
2261 return ExprError();
2262 TheCall->setArg(0, Arg.get());
2263
2264 return TheCall;
2265}
2266
2268 if (S.checkArgCount(TheCall, 1))
2269 return ExprError();
2270
2272 if (Arg.isInvalid())
2273 return ExprError();
2274 QualType ParamTy = Arg.get()->getType();
2275 TheCall->setArg(0, Arg.get());
2276 TheCall->setType(S.Context.BoolTy);
2277
2278 // Only accept pointers to objects as arguments, which should have object
2279 // pointer or void pointer types.
2280 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2281 // LWG4138: Function pointer types not allowed
2282 if (PT->getPointeeType()->isFunctionType()) {
2283 S.Diag(TheCall->getArg(0)->getExprLoc(),
2284 diag::err_builtin_is_within_lifetime_invalid_arg)
2285 << 1;
2286 return ExprError();
2287 }
2288 // Disallow VLAs too since those shouldn't be able to
2289 // be a template parameter for `std::is_within_lifetime`
2290 if (PT->getPointeeType()->isVariableArrayType()) {
2291 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2292 << 1 << "__builtin_is_within_lifetime";
2293 return ExprError();
2294 }
2295 } else {
2296 S.Diag(TheCall->getArg(0)->getExprLoc(),
2297 diag::err_builtin_is_within_lifetime_invalid_arg)
2298 << 0;
2299 return ExprError();
2300 }
2301 return TheCall;
2302}
2303
2305 if (S.checkArgCount(TheCall, 3))
2306 return ExprError();
2307
2308 QualType Dest = TheCall->getArg(0)->getType();
2309 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2310 S.Diag(TheCall->getArg(0)->getExprLoc(),
2311 diag::err_builtin_trivially_relocate_invalid_arg_type)
2312 << /*a pointer*/ 0;
2313 return ExprError();
2314 }
2315
2316 QualType T = Dest->getPointeeType();
2317 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2318 diag::err_incomplete_type))
2319 return ExprError();
2320
2321 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2322 T->isIncompleteArrayType()) {
2323 S.Diag(TheCall->getArg(0)->getExprLoc(),
2324 diag::err_builtin_trivially_relocate_invalid_arg_type)
2325 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2326 return ExprError();
2327 }
2328
2329 TheCall->setType(Dest);
2330
2331 QualType Src = TheCall->getArg(1)->getType();
2332 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2333 S.Diag(TheCall->getArg(1)->getExprLoc(),
2334 diag::err_builtin_trivially_relocate_invalid_arg_type)
2335 << /*the same*/ 3;
2336 return ExprError();
2337 }
2338
2339 Expr *SizeExpr = TheCall->getArg(2);
2340 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2341 if (Size.isInvalid())
2342 return ExprError();
2343
2344 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2345 if (Size.isInvalid())
2346 return ExprError();
2347 SizeExpr = Size.get();
2348 TheCall->setArg(2, SizeExpr);
2349
2350 return TheCall;
2351}
2352
2353// Emit an error and return true if the current object format type is in the
2354// list of unsupported types.
2356 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2357 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2358 llvm::Triple::ObjectFormatType CurObjFormat =
2359 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2360 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2361 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2362 << TheCall->getSourceRange();
2363 return true;
2364 }
2365 return false;
2366}
2367
2368// Emit an error and return true if the current architecture is not in the list
2369// of supported architectures.
2370static bool
2372 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2373 llvm::Triple::ArchType CurArch =
2374 S.getASTContext().getTargetInfo().getTriple().getArch();
2375 if (llvm::is_contained(SupportedArchs, CurArch))
2376 return false;
2377 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2378 << TheCall->getSourceRange();
2379 return true;
2380}
2381
2382static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2383 SourceLocation CallSiteLoc);
2384
2385bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2386 CallExpr *TheCall) {
2387 switch (TI.getTriple().getArch()) {
2388 default:
2389 // Some builtins don't require additional checking, so just consider these
2390 // acceptable.
2391 return false;
2392 case llvm::Triple::arm:
2393 case llvm::Triple::armeb:
2394 case llvm::Triple::thumb:
2395 case llvm::Triple::thumbeb:
2396 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2397 case llvm::Triple::aarch64:
2398 case llvm::Triple::aarch64_32:
2399 case llvm::Triple::aarch64_be:
2400 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2401 case llvm::Triple::bpfeb:
2402 case llvm::Triple::bpfel:
2403 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2404 case llvm::Triple::dxil:
2405 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2406 case llvm::Triple::hexagon:
2407 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2408 case llvm::Triple::mips:
2409 case llvm::Triple::mipsel:
2410 case llvm::Triple::mips64:
2411 case llvm::Triple::mips64el:
2412 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2413 case llvm::Triple::spirv:
2414 case llvm::Triple::spirv32:
2415 case llvm::Triple::spirv64:
2416 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2417 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2418 return false;
2419 case llvm::Triple::systemz:
2420 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2421 case llvm::Triple::x86:
2422 case llvm::Triple::x86_64:
2423 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2424 case llvm::Triple::ppc:
2425 case llvm::Triple::ppcle:
2426 case llvm::Triple::ppc64:
2427 case llvm::Triple::ppc64le:
2428 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2429 case llvm::Triple::amdgpu:
2430 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2431 case llvm::Triple::riscv32:
2432 case llvm::Triple::riscv64:
2433 case llvm::Triple::riscv32be:
2434 case llvm::Triple::riscv64be:
2435 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2436 case llvm::Triple::loongarch32:
2437 case llvm::Triple::loongarch64:
2438 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2439 TheCall);
2440 case llvm::Triple::wasm32:
2441 case llvm::Triple::wasm64:
2442 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2443 case llvm::Triple::nvptx:
2444 case llvm::Triple::nvptx64:
2445 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2446 }
2447}
2448
2450 return T->isDependentType() ||
2451 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2452}
2453
2454// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2455// not a valid type, emit an error message and return true. Otherwise return
2456// false.
2457static bool
2460 int ArgOrdinal) {
2461 clang::QualType EltTy =
2462 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2463 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2464 : ArgTy;
2465
2466 switch (ArgTyRestr) {
2468 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2469 !isValidMathElementType(ArgTy)) {
2470 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2471 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2472 << ArgTy;
2473 }
2474 break;
2476 if (!EltTy->isRealFloatingType()) {
2477 // FIXME: make diagnostic's wording correct for matrices
2478 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2479 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2480 << /* floating-point */ 1 << ArgTy;
2481 }
2482 break;
2484 if (!EltTy->isIntegerType()) {
2485 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2486 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2487 << /* no fp */ 0 << ArgTy;
2488 }
2489 break;
2491 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2492 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2493 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2494 << /* or fp */ 1 << ArgTy;
2495 }
2496 break;
2497 }
2498
2499 return false;
2500}
2501
2502/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2503/// This checks that the target supports the builtin and that the string
2504/// argument is constant and valid.
2505static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2506 const TargetInfo *AuxTI, unsigned BuiltinID) {
2507 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2508 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2509 "Expecting __builtin_cpu_...");
2510
2511 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2512 const TargetInfo *TheTI = &TI;
2513 auto SupportsBI = [=](const TargetInfo *TInfo) {
2514 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2515 (!IsCPUSupports && TInfo->supportsCpuIs()));
2516 };
2517 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2518 TheTI = AuxTI;
2519
2520 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2521 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2522 return S.Diag(TheCall->getBeginLoc(),
2523 TI.getTriple().isOSAIX()
2524 ? diag::err_builtin_aix_os_unsupported
2525 : diag::err_builtin_target_unsupported)
2526 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2527
2528 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2529 // Check if the argument is a string literal.
2530 if (!isa<StringLiteral>(Arg))
2531 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2532 << Arg->getSourceRange();
2533
2534 // Check the contents of the string.
2535 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2536 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2537 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2538 << Arg->getSourceRange();
2539 return false;
2540 }
2541 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2542 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2543 << Arg->getSourceRange();
2544 return false;
2545}
2546
2547/// Checks that __builtin_bswapg was called with a single argument, which is an
2548/// unsigned integer, and overrides the return value type to the integer type.
2549static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2550 if (S.checkArgCount(TheCall, 1))
2551 return true;
2552 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2553 if (ArgRes.isInvalid())
2554 return true;
2555
2556 Expr *Arg = ArgRes.get();
2557 TheCall->setArg(0, Arg);
2558 if (Arg->isTypeDependent())
2559 return false;
2560
2561 QualType ArgTy = Arg->getType();
2562
2563 if (!ArgTy->isIntegerType()) {
2564 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2565 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2566 << ArgTy;
2567 return true;
2568 }
2569 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2570 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2571 BT->getNumBits() != 1) {
2572 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2573 << ArgTy << BT->getNumBits();
2574 return true;
2575 }
2576 }
2577 TheCall->setType(ArgTy);
2578 return false;
2579}
2580
2581/// Checks that __builtin_bitreverseg was called with a single argument, which
2582/// is an integer
2583static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2584 if (S.checkArgCount(TheCall, 1))
2585 return true;
2586 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2587 if (ArgRes.isInvalid())
2588 return true;
2589
2590 Expr *Arg = ArgRes.get();
2591 TheCall->setArg(0, Arg);
2592 if (Arg->isTypeDependent())
2593 return false;
2594
2595 QualType ArgTy = Arg->getType();
2596
2597 if (!ArgTy->isIntegerType()) {
2598 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2599 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2600 << ArgTy;
2601 return true;
2602 }
2603 TheCall->setType(ArgTy);
2604 return false;
2605}
2606
2607/// Checks that __builtin_popcountg was called with a single argument, which is
2608/// an unsigned integer.
2609static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2610 if (S.checkArgCount(TheCall, 1))
2611 return true;
2612
2613 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2614 if (ArgRes.isInvalid())
2615 return true;
2616
2617 Expr *Arg = ArgRes.get();
2618 TheCall->setArg(0, Arg);
2619
2620 QualType ArgTy = Arg->getType();
2621
2622 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2623 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2624 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2625 << ArgTy;
2626 return true;
2627 }
2628 return false;
2629}
2630
2631/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2632/// argument and return either int, bool, or the argument type.
2633static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2634 QualType ReturnType) {
2635 if (S.checkArgCount(TheCall, 1))
2636 return true;
2637
2638 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2639 if (ArgRes.isInvalid())
2640 return true;
2641
2642 Expr *Arg = ArgRes.get();
2643 TheCall->setArg(0, Arg);
2644
2645 QualType ArgTy = Arg->getType();
2646 // C23 stdbit.h functions do not permit bool or enumeration types.
2647 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2648 return S.Diag(Arg->getBeginLoc(),
2649 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2650 << 1 /*1st argument*/ << ArgTy;
2651 if (!ArgTy->isUnsignedIntegerType())
2652 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2653 << 1 /*1st argument*/ << ArgTy;
2654
2655 // For builtins returning unsigned int, verify the argument's bit width fits.
2656 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2657 // produce a count that overflows the return type.
2658 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2659 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2660 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2661 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2662 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2663 << ArgTy;
2664 }
2665
2666 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2667 return false;
2668}
2669
2670/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2671/// an unsigned integer, and an optional second argument, which is promoted to
2672/// an 'int'.
2673static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2674 if (S.checkArgCountRange(TheCall, 1, 2))
2675 return true;
2676
2677 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2678 if (Arg0Res.isInvalid())
2679 return true;
2680
2681 Expr *Arg0 = Arg0Res.get();
2682 TheCall->setArg(0, Arg0);
2683
2684 QualType Arg0Ty = Arg0->getType();
2685
2686 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2687 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2688 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2689 << Arg0Ty;
2690 return true;
2691 }
2692
2693 if (TheCall->getNumArgs() > 1) {
2694 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2695 if (Arg1Res.isInvalid())
2696 return true;
2697
2698 Expr *Arg1 = Arg1Res.get();
2699 TheCall->setArg(1, Arg1);
2700
2701 QualType Arg1Ty = Arg1->getType();
2702
2703 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2704 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2705 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2706 return true;
2707 }
2708 }
2709
2710 return false;
2711}
2712
2714 unsigned ArgIndex;
2715 bool OnlyUnsigned;
2716
2718 QualType T) {
2719 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2720 << ArgIndex << /*scalar*/ 1
2721 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2722 << /*no fp*/ 0 << T;
2723 }
2724
2725public:
2726 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2727 : ContextualImplicitConverter(/*Suppress=*/false,
2728 /*SuppressConversion=*/true),
2729 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2730
2731 bool match(QualType T) override {
2732 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2733 }
2734
2736 QualType T) override {
2737 return emitError(S, Loc, T);
2738 }
2739
2741 QualType T) override {
2742 return emitError(S, Loc, T);
2743 }
2744
2746 QualType T,
2747 QualType ConvTy) override {
2748 return emitError(S, Loc, T);
2749 }
2750
2752 QualType ConvTy) override {
2753 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2754 }
2755
2757 QualType T) override {
2758 return emitError(S, Loc, T);
2759 }
2760
2762 QualType ConvTy) override {
2763 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2764 }
2765
2767 QualType T,
2768 QualType ConvTy) override {
2769 llvm_unreachable("conversion functions are permitted");
2770 }
2771};
2772
2773/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2774/// arguments, that the first argument is an unsigned integer type, and that
2775/// the second argument is an integer type.
2776static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2777 if (S.checkArgCount(TheCall, 2))
2778 return true;
2779
2780 // First argument (value to rotate) must be unsigned integer type.
2781 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2783 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2784 if (Arg0Res.isInvalid())
2785 return true;
2786
2787 Expr *Arg0 = Arg0Res.get();
2788 TheCall->setArg(0, Arg0);
2789
2790 QualType Arg0Ty = Arg0->getType();
2791 if (!Arg0Ty->isUnsignedIntegerType())
2792 return true;
2793
2794 // Second argument (rotation count) must be integer type.
2795 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2797 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2798 if (Arg1Res.isInvalid())
2799 return true;
2800
2801 Expr *Arg1 = Arg1Res.get();
2802 TheCall->setArg(1, Arg1);
2803
2804 QualType Arg1Ty = Arg1->getType();
2805 if (!Arg1Ty->isIntegerType())
2806 return true;
2807
2808 TheCall->setType(Arg0Ty);
2809 return false;
2810}
2811
2812static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2813 unsigned Pos, bool AllowConst,
2814 bool AllowAS) {
2815 QualType MaskTy = MaskArg->getType();
2816 if (!MaskTy->isExtVectorBoolType())
2817 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2818 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2819 << MaskTy;
2820
2821 QualType PtrTy = PtrArg->getType();
2822 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2823 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2824 << Pos << "scalar pointer";
2825
2826 QualType PointeeTy = PtrTy->getPointeeType();
2827 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2828 (!AllowConst && PointeeTy.isConstQualified()) ||
2829 (!AllowAS && PointeeTy.hasAddressSpace())) {
2832 return S.Diag(PtrArg->getExprLoc(),
2833 diag::err_typecheck_convert_incompatible)
2834 << PtrTy << Target << /*different qualifiers=*/5
2835 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2836 << PtrTy << Target;
2837 }
2838 return false;
2839}
2840
2841static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2842 bool TypeDependent = false;
2843 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2844 ExprResult Converted =
2846 if (Converted.isInvalid())
2847 return true;
2848 TheCall->setArg(Arg, Converted.get());
2849 TypeDependent |= Converted.get()->isTypeDependent();
2850 }
2851
2852 if (TypeDependent)
2853 TheCall->setType(S.Context.DependentTy);
2854 return false;
2855}
2856
2858 if (S.checkArgCountRange(TheCall, 2, 3))
2859 return ExprError();
2860
2861 if (ConvertMaskedBuiltinArgs(S, TheCall))
2862 return ExprError();
2863
2864 Expr *MaskArg = TheCall->getArg(0);
2865 Expr *PtrArg = TheCall->getArg(1);
2866 if (TheCall->isTypeDependent())
2867 return TheCall;
2868
2869 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2870 TheCall->getBuiltinCallee() ==
2871 Builtin::BI__builtin_masked_load))
2872 return ExprError();
2873
2874 QualType MaskTy = MaskArg->getType();
2875 QualType PtrTy = PtrArg->getType();
2876 QualType PointeeTy = PtrTy->getPointeeType();
2877 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2878
2880 MaskVecTy->getNumElements());
2881 if (TheCall->getNumArgs() == 3) {
2882 Expr *PassThruArg = TheCall->getArg(2);
2883 QualType PassThruTy = PassThruArg->getType();
2884 if (!S.Context.hasSameType(PassThruTy, RetTy))
2885 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2886 << /* third argument */ 3 << RetTy;
2887 }
2888
2889 TheCall->setType(RetTy);
2890 return TheCall;
2891}
2892
2894 if (S.checkArgCount(TheCall, 3))
2895 return ExprError();
2896
2897 if (ConvertMaskedBuiltinArgs(S, TheCall))
2898 return ExprError();
2899
2900 Expr *MaskArg = TheCall->getArg(0);
2901 Expr *ValArg = TheCall->getArg(1);
2902 Expr *PtrArg = TheCall->getArg(2);
2903 if (TheCall->isTypeDependent())
2904 return TheCall;
2905
2906 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2907 TheCall->getBuiltinCallee() ==
2908 Builtin::BI__builtin_masked_store))
2909 return ExprError();
2910
2911 QualType MaskTy = MaskArg->getType();
2912 QualType PtrTy = PtrArg->getType();
2913 QualType ValTy = ValArg->getType();
2914 if (!ValTy->isVectorType())
2915 return ExprError(
2916 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2917 << 2 << "vector");
2918
2919 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2920 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2921
2922 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2923 return ExprError(
2924 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2926 TheCall->getBuiltinCallee())
2927 << MaskTy << ValTy);
2928 }
2929
2930 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2931 PtrTy->getPointeeType().getUnqualifiedType()))
2932 return ExprError(S.Diag(TheCall->getBeginLoc(),
2933 diag::err_vec_builtin_incompatible_vector)
2934 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2935 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2936 TheCall->getArg(1)->getEndLoc()));
2937
2938 TheCall->setType(S.Context.VoidTy);
2939 return TheCall;
2940}
2941
2943 if (S.checkArgCountRange(TheCall, 3, 4))
2944 return ExprError();
2945
2946 if (ConvertMaskedBuiltinArgs(S, TheCall))
2947 return ExprError();
2948
2949 Expr *MaskArg = TheCall->getArg(0);
2950 Expr *IdxArg = TheCall->getArg(1);
2951 Expr *PtrArg = TheCall->getArg(2);
2952 if (TheCall->isTypeDependent())
2953 return TheCall;
2954
2955 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2956 /*AllowAS=*/true))
2957 return ExprError();
2958
2959 QualType IdxTy = IdxArg->getType();
2960 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2961 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2962 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2963 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2964 << IdxTy;
2965
2966 QualType MaskTy = MaskArg->getType();
2967 QualType PtrTy = PtrArg->getType();
2968 QualType PointeeTy = PtrTy->getPointeeType();
2969 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2970 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2971 return ExprError(
2972 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2974 TheCall->getBuiltinCallee())
2975 << MaskTy << IdxTy);
2976
2978 MaskVecTy->getNumElements());
2979 if (TheCall->getNumArgs() == 4) {
2980 Expr *PassThruArg = TheCall->getArg(3);
2981 QualType PassThruTy = PassThruArg->getType();
2982 if (!S.Context.hasSameType(PassThruTy, RetTy))
2983 return S.Diag(PassThruArg->getExprLoc(),
2984 diag::err_vec_masked_load_store_ptr)
2985 << /* fourth argument */ 4 << RetTy;
2986 }
2987
2988 TheCall->setType(RetTy);
2989 return TheCall;
2990}
2991
2993 if (S.checkArgCount(TheCall, 4))
2994 return ExprError();
2995
2996 if (ConvertMaskedBuiltinArgs(S, TheCall))
2997 return ExprError();
2998
2999 Expr *MaskArg = TheCall->getArg(0);
3000 Expr *IdxArg = TheCall->getArg(1);
3001 Expr *ValArg = TheCall->getArg(2);
3002 Expr *PtrArg = TheCall->getArg(3);
3003 if (TheCall->isTypeDependent())
3004 return TheCall;
3005
3006 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
3007 /*AllowAS=*/true))
3008 return ExprError();
3009
3010 QualType IdxTy = IdxArg->getType();
3011 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
3012 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
3013 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3014 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
3015 << IdxTy;
3016
3017 QualType ValTy = ValArg->getType();
3018 QualType MaskTy = MaskArg->getType();
3019 QualType PtrTy = PtrArg->getType();
3020
3021 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
3022 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
3023 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
3024 return ExprError(
3025 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
3027 TheCall->getBuiltinCallee())
3028 << MaskTy << IdxTy);
3029 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
3030 return ExprError(
3031 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
3033 TheCall->getBuiltinCallee())
3034 << MaskTy << ValTy);
3035
3036 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
3037 PtrTy->getPointeeType().getUnqualifiedType()))
3038 return ExprError(S.Diag(TheCall->getBeginLoc(),
3039 diag::err_vec_builtin_incompatible_vector)
3040 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
3041 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
3042 TheCall->getArg(1)->getEndLoc()));
3043
3044 TheCall->setType(S.Context.VoidTy);
3045 return TheCall;
3046}
3047
3049 SourceLocation Loc = TheCall->getBeginLoc();
3050 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
3051 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
3052
3053 if (Args.size() == 0) {
3054 S.Diag(TheCall->getBeginLoc(),
3055 diag::err_typecheck_call_too_few_args_at_least)
3056 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
3057 << /*is_non_object=*/0 << TheCall->getSourceRange();
3058 return ExprError();
3059 }
3060
3061 QualType FuncT = Args[0]->getType();
3062
3063 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
3064 if (Args.size() < 2) {
3065 S.Diag(TheCall->getBeginLoc(),
3066 diag::err_typecheck_call_too_few_args_at_least)
3067 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
3068 << /*is_non_object=*/0 << TheCall->getSourceRange();
3069 return ExprError();
3070 }
3071
3072 const Type *MemPtrClass = MPT->getQualifier().getAsType();
3073 QualType ObjectT = Args[1]->getType();
3074
3075 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
3076 return ExprError();
3077
3078 ExprResult ObjectArg = [&]() -> ExprResult {
3079 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
3080 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3081 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3082 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
3083 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3084 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3085 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
3086 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
3087 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
3088 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
3089 return Args[1];
3090 }
3091
3092 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
3093 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
3094 // reference_wrapper;
3095 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
3096 if (RD->isInStdNamespace() &&
3097 RD->getDeclName().getAsString() == "reference_wrapper") {
3098 CXXScopeSpec SS;
3099 IdentifierInfo *GetName = &S.Context.Idents.get("get");
3100 UnqualifiedId GetID;
3101 GetID.setIdentifier(GetName, Loc);
3102
3104 S.getCurScope(), Args[1], Loc, tok::period, SS,
3105 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
3106
3107 if (MemExpr.isInvalid())
3108 return ExprError();
3109
3110 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
3111 }
3112 }
3113
3114 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3115 // class T and t1 does not satisfy the previous two items;
3116
3117 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
3118 }();
3119
3120 if (ObjectArg.isInvalid())
3121 return ExprError();
3122
3123 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
3124 tok::periodstar, ObjectArg.get(), Args[0]);
3125 if (BinOp.isInvalid())
3126 return ExprError();
3127
3128 if (MPT->isMemberDataPointer())
3129 return BinOp;
3130
3131 // Give the synthesized expression a valid source range for diagnostics.
3132 auto *MemCall = new (S.Context)
3133 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3134
3135 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
3136 Args.drop_front(2), TheCall->getRParenLoc());
3137 }
3138 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
3139 Args.drop_front(), TheCall->getRParenLoc());
3140}
3141
3142// Performs a similar job to Sema::UsualUnaryConversions, but without any
3143// implicit promotion of integral/enumeration types.
3145 // First, convert to an r-value.
3147 if (Res.isInvalid())
3148 return ExprError();
3149
3150 // Promote floating-point types.
3151 return S.UsualUnaryFPConversions(Res.get());
3152}
3153
3155 if (const auto *TyA = VecTy->getAs<VectorType>())
3156 return TyA->getElementType();
3157 if (VecTy->isSizelessVectorType())
3158 return VecTy->getSizelessVectorEltType(Context);
3159 return QualType();
3160}
3161
3163Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3164 CallExpr *TheCall) {
3165 ExprResult TheCallResult(TheCall);
3166
3167 // Find out if any arguments are required to be integer constant expressions.
3168 unsigned ICEArguments = 0;
3170 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
3172 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3173
3174 // If any arguments are required to be ICE's, check and diagnose.
3175 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3176 // Skip arguments not required to be ICE's.
3177 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3178
3179 llvm::APSInt Result;
3180 // If we don't have enough arguments, continue so we can issue better
3181 // diagnostic in checkArgCount(...)
3182 if (ArgNo < TheCall->getNumArgs() &&
3183 BuiltinConstantArg(TheCall, ArgNo, Result))
3184 return true;
3185 ICEArguments &= ~(1 << ArgNo);
3186 }
3187
3188 FPOptions FPO;
3189 switch (BuiltinID) {
3190 case Builtin::BI__builtin___get_unsafe_stack_start:
3191 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3192 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3193 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3194 << "__safestack_get_unsafe_stack_bottom";
3195 break;
3196 case Builtin::BI__builtin___get_unsafe_stack_top:
3197 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3198 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3199 << "__safestack_get_unsafe_stack_top";
3200 break;
3201 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3202 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3203 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3204 << "__safestack_get_unsafe_stack_ptr";
3205 break;
3206 case Builtin::BI__builtin_cpu_supports:
3207 case Builtin::BI__builtin_cpu_is:
3208 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
3209 Context.getAuxTargetInfo(), BuiltinID))
3210 return ExprError();
3211 break;
3212 case Builtin::BI__builtin_cpu_init:
3213 if (!Context.getTargetInfo().supportsCpuInit()) {
3214 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3215 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3216 return ExprError();
3217 }
3218 break;
3219 case Builtin::BI__builtin___CFStringMakeConstantString:
3220 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3221 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3223 *this, BuiltinID, TheCall,
3224 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3225 return ExprError();
3226 assert(TheCall->getNumArgs() == 1 &&
3227 "Wrong # arguments to builtin CFStringMakeConstantString");
3228 if (ObjC().CheckObjCString(TheCall->getArg(0)))
3229 return ExprError();
3230 break;
3231 case Builtin::BI__builtin_ms_va_start:
3232 case Builtin::BI__builtin_zos_va_start:
3233 case Builtin::BI__builtin_stdarg_start:
3234 case Builtin::BI__builtin_va_start:
3235 case Builtin::BI__builtin_c23_va_start:
3236 if (BuiltinVAStart(BuiltinID, TheCall))
3237 return ExprError();
3238 break;
3239 case Builtin::BI__va_start: {
3240 switch (Context.getTargetInfo().getTriple().getArch()) {
3241 case llvm::Triple::aarch64:
3242 case llvm::Triple::arm:
3243 case llvm::Triple::thumb:
3244 if (BuiltinVAStartARMMicrosoft(TheCall))
3245 return ExprError();
3246 break;
3247 default:
3248 if (BuiltinVAStart(BuiltinID, TheCall))
3249 return ExprError();
3250 break;
3251 }
3252 break;
3253 }
3254
3255 // The acquire, release, and no fence variants are ARM and AArch64 only.
3256 case Builtin::BI_interlockedbittestandset_acq:
3257 case Builtin::BI_interlockedbittestandset_rel:
3258 case Builtin::BI_interlockedbittestandset_nf:
3259 case Builtin::BI_interlockedbittestandreset_acq:
3260 case Builtin::BI_interlockedbittestandreset_rel:
3261 case Builtin::BI_interlockedbittestandreset_nf:
3263 *this, TheCall,
3264 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3265 return ExprError();
3266 break;
3267
3268 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3269 case Builtin::BI_bittest64:
3270 case Builtin::BI_bittestandcomplement64:
3271 case Builtin::BI_bittestandreset64:
3272 case Builtin::BI_bittestandset64:
3273 case Builtin::BI_interlockedbittestandreset64:
3274 case Builtin::BI_interlockedbittestandset64:
3276 *this, TheCall,
3277 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3278 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3279 return ExprError();
3280 break;
3281
3282 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3283 case Builtin::BI_interlockedbittestandreset64_acq:
3284 case Builtin::BI_interlockedbittestandreset64_rel:
3285 case Builtin::BI_interlockedbittestandreset64_nf:
3286 case Builtin::BI_interlockedbittestandset64_acq:
3287 case Builtin::BI_interlockedbittestandset64_rel:
3288 case Builtin::BI_interlockedbittestandset64_nf:
3289 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3290 return ExprError();
3291 break;
3292
3293 case Builtin::BI__builtin_set_flt_rounds:
3295 *this, TheCall,
3296 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3297 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3298 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3299 llvm::Triple::ppc64le}))
3300 return ExprError();
3301 break;
3302
3303 case Builtin::BI__builtin_isgreater:
3304 case Builtin::BI__builtin_isgreaterequal:
3305 case Builtin::BI__builtin_isless:
3306 case Builtin::BI__builtin_islessequal:
3307 case Builtin::BI__builtin_islessgreater:
3308 case Builtin::BI__builtin_isunordered:
3309 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3310 return ExprError();
3311 break;
3312 case Builtin::BI__builtin_fpclassify:
3313 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3314 return ExprError();
3315 break;
3316 case Builtin::BI__builtin_isfpclass:
3317 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3318 return ExprError();
3319 break;
3320 case Builtin::BI__builtin_isfinite:
3321 case Builtin::BI__builtin_isinf:
3322 case Builtin::BI__builtin_isinf_sign:
3323 case Builtin::BI__builtin_isnan:
3324 case Builtin::BI__builtin_issignaling:
3325 case Builtin::BI__builtin_isnormal:
3326 case Builtin::BI__builtin_issubnormal:
3327 case Builtin::BI__builtin_iszero:
3328 case Builtin::BI__builtin_signbit:
3329 case Builtin::BI__builtin_signbitf:
3330 case Builtin::BI__builtin_signbitl:
3331 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3332 return ExprError();
3333 break;
3334 case Builtin::BI__builtin_shufflevector:
3335 return BuiltinShuffleVector(TheCall);
3336 // TheCall will be freed by the smart pointer here, but that's fine, since
3337 // BuiltinShuffleVector guts it, but then doesn't release it.
3338 case Builtin::BI__builtin_masked_load:
3339 case Builtin::BI__builtin_masked_expand_load:
3340 return BuiltinMaskedLoad(*this, TheCall);
3341 case Builtin::BI__builtin_masked_store:
3342 case Builtin::BI__builtin_masked_compress_store:
3343 return BuiltinMaskedStore(*this, TheCall);
3344 case Builtin::BI__builtin_masked_gather:
3345 return BuiltinMaskedGather(*this, TheCall);
3346 case Builtin::BI__builtin_masked_scatter:
3347 return BuiltinMaskedScatter(*this, TheCall);
3348 case Builtin::BI__builtin_invoke:
3349 return BuiltinInvoke(*this, TheCall);
3350 case Builtin::BI__builtin_prefetch:
3351 if (BuiltinPrefetch(TheCall))
3352 return ExprError();
3353 break;
3354 case Builtin::BI__builtin_alloca_with_align:
3355 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3356 if (BuiltinAllocaWithAlign(TheCall))
3357 return ExprError();
3358 [[fallthrough]];
3359 case Builtin::BI__builtin_alloca:
3360 case Builtin::BI__builtin_alloca_uninitialized:
3361 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3362 << TheCall->getDirectCallee();
3363 if (getLangOpts().OpenCL) {
3364 builtinAllocaAddrSpace(*this, TheCall);
3365 }
3366 break;
3367 case Builtin::BI__builtin_infer_alloc_token:
3368 if (checkBuiltinInferAllocToken(*this, TheCall))
3369 return ExprError();
3370 break;
3371 case Builtin::BI__arithmetic_fence:
3372 if (BuiltinArithmeticFence(TheCall))
3373 return ExprError();
3374 break;
3375 case Builtin::BI__assume:
3376 case Builtin::BI__builtin_assume:
3377 if (BuiltinAssume(TheCall))
3378 return ExprError();
3379 break;
3380 case Builtin::BI__builtin_assume_aligned:
3381 if (BuiltinAssumeAligned(TheCall))
3382 return ExprError();
3383 break;
3384 case Builtin::BI__builtin_dynamic_object_size:
3385 case Builtin::BI__builtin_object_size:
3386 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3387 return ExprError();
3388 break;
3389 case Builtin::BI__builtin_longjmp:
3390 if (BuiltinLongjmp(TheCall))
3391 return ExprError();
3392 break;
3393 case Builtin::BI__builtin_setjmp:
3394 if (BuiltinSetjmp(TheCall))
3395 return ExprError();
3396 break;
3397 case Builtin::BI__builtin_complex:
3398 if (BuiltinComplex(TheCall))
3399 return ExprError();
3400 break;
3401 case Builtin::BI__builtin_classify_type:
3402 case Builtin::BI__builtin_constant_p: {
3403 if (checkArgCount(TheCall, 1))
3404 return true;
3406 if (Arg.isInvalid()) return true;
3407 TheCall->setArg(0, Arg.get());
3408 TheCall->setType(Context.IntTy);
3409 break;
3410 }
3411 case Builtin::BI__builtin_launder:
3412 return BuiltinLaunder(*this, TheCall);
3413 case Builtin::BI__builtin_is_within_lifetime:
3414 return BuiltinIsWithinLifetime(*this, TheCall);
3415 case Builtin::BI__builtin_trivially_relocate:
3416 return BuiltinTriviallyRelocate(*this, TheCall);
3417 case Builtin::BI__builtin_clear_padding: {
3418 if (checkArgCount(TheCall, 1))
3419 return ExprError();
3420
3421 const Expr *PtrArg = TheCall->getArg(0);
3422 const QualType PtrArgType = PtrArg->getType();
3423 if (!PtrArgType->isPointerType()) {
3424 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3425 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3426 << "pointer";
3427 return ExprError();
3428 }
3429 QualType PointeeType = PtrArgType->getPointeeType();
3430 if (PointeeType.isConstQualified()) {
3431 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3432 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3433 return ExprError();
3434 }
3435 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3436 diag::err_typecheck_decl_incomplete_type))
3437 return ExprError();
3438
3439 // For non trivially copyable types, we try to match gcc's behaviour.
3440 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3441 // object, either a local variable or a function parameter passed by value
3442 auto IsAddrOfDeclExpr = [&]() {
3443 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3444 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3445 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3446 return false;
3447
3448 const Expr *Operand =
3449 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3450 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3451 if (!DeclRef)
3452 return false;
3453
3454 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3455 if (!VarDecl || VarDecl->getType()->isReferenceType())
3456 return false;
3457
3458 // matching GCC behaviour
3459 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3460 QualType VarQType = VarDecl->getType();
3461 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3462 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3463 };
3464
3465 if (!PointeeType.isTriviallyCopyableType(Context) &&
3466 !PointeeType->isAtomicType() // _Atomic is not copyable
3467 && !IsAddrOfDeclExpr()) {
3468 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3469 << PtrArg->getType() << PtrArg->getSourceRange();
3470 return ExprError();
3471 }
3472
3473 if (auto *Record = PointeeType->getAsRecordDecl();
3475 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3476 << PointeeType << PtrArg->getSourceRange();
3477 return ExprError();
3478 }
3479
3480 break;
3481 }
3482 case Builtin::BI__sync_fetch_and_add:
3483 case Builtin::BI__sync_fetch_and_add_1:
3484 case Builtin::BI__sync_fetch_and_add_2:
3485 case Builtin::BI__sync_fetch_and_add_4:
3486 case Builtin::BI__sync_fetch_and_add_8:
3487 case Builtin::BI__sync_fetch_and_add_16:
3488 case Builtin::BI__sync_fetch_and_sub:
3489 case Builtin::BI__sync_fetch_and_sub_1:
3490 case Builtin::BI__sync_fetch_and_sub_2:
3491 case Builtin::BI__sync_fetch_and_sub_4:
3492 case Builtin::BI__sync_fetch_and_sub_8:
3493 case Builtin::BI__sync_fetch_and_sub_16:
3494 case Builtin::BI__sync_fetch_and_or:
3495 case Builtin::BI__sync_fetch_and_or_1:
3496 case Builtin::BI__sync_fetch_and_or_2:
3497 case Builtin::BI__sync_fetch_and_or_4:
3498 case Builtin::BI__sync_fetch_and_or_8:
3499 case Builtin::BI__sync_fetch_and_or_16:
3500 case Builtin::BI__sync_fetch_and_and:
3501 case Builtin::BI__sync_fetch_and_and_1:
3502 case Builtin::BI__sync_fetch_and_and_2:
3503 case Builtin::BI__sync_fetch_and_and_4:
3504 case Builtin::BI__sync_fetch_and_and_8:
3505 case Builtin::BI__sync_fetch_and_and_16:
3506 case Builtin::BI__sync_fetch_and_xor:
3507 case Builtin::BI__sync_fetch_and_xor_1:
3508 case Builtin::BI__sync_fetch_and_xor_2:
3509 case Builtin::BI__sync_fetch_and_xor_4:
3510 case Builtin::BI__sync_fetch_and_xor_8:
3511 case Builtin::BI__sync_fetch_and_xor_16:
3512 case Builtin::BI__sync_fetch_and_nand:
3513 case Builtin::BI__sync_fetch_and_nand_1:
3514 case Builtin::BI__sync_fetch_and_nand_2:
3515 case Builtin::BI__sync_fetch_and_nand_4:
3516 case Builtin::BI__sync_fetch_and_nand_8:
3517 case Builtin::BI__sync_fetch_and_nand_16:
3518 case Builtin::BI__sync_add_and_fetch:
3519 case Builtin::BI__sync_add_and_fetch_1:
3520 case Builtin::BI__sync_add_and_fetch_2:
3521 case Builtin::BI__sync_add_and_fetch_4:
3522 case Builtin::BI__sync_add_and_fetch_8:
3523 case Builtin::BI__sync_add_and_fetch_16:
3524 case Builtin::BI__sync_sub_and_fetch:
3525 case Builtin::BI__sync_sub_and_fetch_1:
3526 case Builtin::BI__sync_sub_and_fetch_2:
3527 case Builtin::BI__sync_sub_and_fetch_4:
3528 case Builtin::BI__sync_sub_and_fetch_8:
3529 case Builtin::BI__sync_sub_and_fetch_16:
3530 case Builtin::BI__sync_and_and_fetch:
3531 case Builtin::BI__sync_and_and_fetch_1:
3532 case Builtin::BI__sync_and_and_fetch_2:
3533 case Builtin::BI__sync_and_and_fetch_4:
3534 case Builtin::BI__sync_and_and_fetch_8:
3535 case Builtin::BI__sync_and_and_fetch_16:
3536 case Builtin::BI__sync_or_and_fetch:
3537 case Builtin::BI__sync_or_and_fetch_1:
3538 case Builtin::BI__sync_or_and_fetch_2:
3539 case Builtin::BI__sync_or_and_fetch_4:
3540 case Builtin::BI__sync_or_and_fetch_8:
3541 case Builtin::BI__sync_or_and_fetch_16:
3542 case Builtin::BI__sync_xor_and_fetch:
3543 case Builtin::BI__sync_xor_and_fetch_1:
3544 case Builtin::BI__sync_xor_and_fetch_2:
3545 case Builtin::BI__sync_xor_and_fetch_4:
3546 case Builtin::BI__sync_xor_and_fetch_8:
3547 case Builtin::BI__sync_xor_and_fetch_16:
3548 case Builtin::BI__sync_nand_and_fetch:
3549 case Builtin::BI__sync_nand_and_fetch_1:
3550 case Builtin::BI__sync_nand_and_fetch_2:
3551 case Builtin::BI__sync_nand_and_fetch_4:
3552 case Builtin::BI__sync_nand_and_fetch_8:
3553 case Builtin::BI__sync_nand_and_fetch_16:
3554 case Builtin::BI__sync_val_compare_and_swap:
3555 case Builtin::BI__sync_val_compare_and_swap_1:
3556 case Builtin::BI__sync_val_compare_and_swap_2:
3557 case Builtin::BI__sync_val_compare_and_swap_4:
3558 case Builtin::BI__sync_val_compare_and_swap_8:
3559 case Builtin::BI__sync_val_compare_and_swap_16:
3560 case Builtin::BI__sync_bool_compare_and_swap:
3561 case Builtin::BI__sync_bool_compare_and_swap_1:
3562 case Builtin::BI__sync_bool_compare_and_swap_2:
3563 case Builtin::BI__sync_bool_compare_and_swap_4:
3564 case Builtin::BI__sync_bool_compare_and_swap_8:
3565 case Builtin::BI__sync_bool_compare_and_swap_16:
3566 case Builtin::BI__sync_lock_test_and_set:
3567 case Builtin::BI__sync_lock_test_and_set_1:
3568 case Builtin::BI__sync_lock_test_and_set_2:
3569 case Builtin::BI__sync_lock_test_and_set_4:
3570 case Builtin::BI__sync_lock_test_and_set_8:
3571 case Builtin::BI__sync_lock_test_and_set_16:
3572 case Builtin::BI__sync_lock_release:
3573 case Builtin::BI__sync_lock_release_1:
3574 case Builtin::BI__sync_lock_release_2:
3575 case Builtin::BI__sync_lock_release_4:
3576 case Builtin::BI__sync_lock_release_8:
3577 case Builtin::BI__sync_lock_release_16:
3578 case Builtin::BI__sync_swap:
3579 case Builtin::BI__sync_swap_1:
3580 case Builtin::BI__sync_swap_2:
3581 case Builtin::BI__sync_swap_4:
3582 case Builtin::BI__sync_swap_8:
3583 case Builtin::BI__sync_swap_16:
3584 return BuiltinAtomicOverloaded(TheCallResult);
3585 case Builtin::BI__sync_synchronize:
3586 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3587 << TheCall->getCallee()->getSourceRange();
3588 break;
3589 case Builtin::BI__builtin_nontemporal_load:
3590 case Builtin::BI__builtin_nontemporal_store:
3591 return BuiltinNontemporalOverloaded(TheCallResult);
3592 case Builtin::BI__builtin_memcpy_inline: {
3593 clang::Expr *SizeOp = TheCall->getArg(2);
3594 // We warn about copying to or from `nullptr` pointers when `size` is
3595 // greater than 0. When `size` is value dependent we cannot evaluate its
3596 // value so we bail out.
3597 if (SizeOp->isValueDependent())
3598 break;
3599 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3600 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3601 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3602 }
3603 break;
3604 }
3605 case Builtin::BI__builtin_memset_inline: {
3606 clang::Expr *SizeOp = TheCall->getArg(2);
3607 // We warn about filling to `nullptr` pointers when `size` is greater than
3608 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3609 // out.
3610 if (SizeOp->isValueDependent())
3611 break;
3612 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3613 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3614 break;
3615 }
3616#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3617 case Builtin::BI##ID: \
3618 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3619#include "clang/Basic/Builtins.inc"
3620 case Builtin::BI__annotation: {
3621 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3622 if (!TT.isOSWindows() && !TT.isUEFI()) {
3623 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3624 << TheCall->getSourceRange();
3625 return ExprError();
3626 }
3627 if (BuiltinMSVCAnnotation(*this, TheCall))
3628 return ExprError();
3629 break;
3630 }
3631 case Builtin::BI__builtin_annotation:
3632 if (BuiltinAnnotation(*this, TheCall))
3633 return ExprError();
3634 break;
3635 case Builtin::BI__builtin_addressof:
3636 if (BuiltinAddressof(*this, TheCall))
3637 return ExprError();
3638 break;
3639 case Builtin::BI__builtin_function_start:
3640 if (BuiltinFunctionStart(*this, TheCall))
3641 return ExprError();
3642 break;
3643 case Builtin::BI__builtin_is_aligned:
3644 case Builtin::BI__builtin_align_up:
3645 case Builtin::BI__builtin_align_down:
3646 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3647 return ExprError();
3648 break;
3649 case Builtin::BI__builtin_add_overflow:
3650 case Builtin::BI__builtin_sub_overflow:
3651 case Builtin::BI__builtin_mul_overflow:
3652 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3653 return ExprError();
3654 break;
3655 case Builtin::BI__builtin_operator_new:
3656 case Builtin::BI__builtin_operator_delete: {
3657 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3658 ExprResult Res =
3659 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3660 return Res;
3661 }
3662 case Builtin::BI__builtin_dump_struct:
3663 return BuiltinDumpStruct(*this, TheCall);
3664 case Builtin::BI__builtin_expect_with_probability: {
3665 // We first want to ensure we are called with 3 arguments
3666 if (checkArgCount(TheCall, 3))
3667 return ExprError();
3668 // then check probability is constant float in range [0.0, 1.0]
3669 const Expr *ProbArg = TheCall->getArg(2);
3670 SmallVector<PartialDiagnosticAt, 8> Notes;
3671 Expr::EvalResult Eval;
3672 Eval.Diag = &Notes;
3673 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3674 !Eval.Val.isFloat()) {
3675 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3676 << ProbArg->getSourceRange();
3677 for (const PartialDiagnosticAt &PDiag : Notes)
3678 Diag(PDiag.first, PDiag.second);
3679 return ExprError();
3680 }
3681 llvm::APFloat Probability = Eval.Val.getFloat();
3682 bool LoseInfo = false;
3683 Probability.convert(llvm::APFloat::IEEEdouble(),
3684 llvm::RoundingMode::Dynamic, &LoseInfo);
3685 if (!(Probability >= llvm::APFloat(0.0) &&
3686 Probability <= llvm::APFloat(1.0))) {
3687 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3688 << ProbArg->getSourceRange();
3689 return ExprError();
3690 }
3691 break;
3692 }
3693 case Builtin::BI__builtin_preserve_access_index:
3694 if (BuiltinPreserveAI(*this, TheCall))
3695 return ExprError();
3696 break;
3697 case Builtin::BI__builtin_call_with_static_chain:
3698 if (BuiltinCallWithStaticChain(*this, TheCall))
3699 return ExprError();
3700 break;
3701 case Builtin::BI__exception_code:
3702 case Builtin::BI_exception_code:
3703 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3704 diag::err_seh___except_block))
3705 return ExprError();
3706 break;
3707 case Builtin::BI__exception_info:
3708 case Builtin::BI_exception_info:
3709 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3710 diag::err_seh___except_filter))
3711 return ExprError();
3712 break;
3713 case Builtin::BI__GetExceptionInfo:
3714 if (checkArgCount(TheCall, 1))
3715 return ExprError();
3716
3718 TheCall->getBeginLoc(),
3719 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3720 TheCall))
3721 return ExprError();
3722
3723 TheCall->setType(Context.VoidPtrTy);
3724 break;
3725 case Builtin::BIaddressof:
3726 case Builtin::BI__addressof:
3727 case Builtin::BIforward:
3728 case Builtin::BIforward_like:
3729 case Builtin::BImove:
3730 case Builtin::BImove_if_noexcept:
3731 case Builtin::BIas_const: {
3732 // These are all expected to be of the form
3733 // T &/&&/* f(U &/&&)
3734 // where T and U only differ in qualification.
3735 if (checkArgCount(TheCall, 1))
3736 return ExprError();
3737 QualType Param = FDecl->getParamDecl(0)->getType();
3738 QualType Result = FDecl->getReturnType();
3739 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3740 BuiltinID == Builtin::BI__addressof;
3741 if (!(Param->isReferenceType() &&
3742 (ReturnsPointer ? Result->isAnyPointerType()
3743 : Result->isReferenceType()) &&
3744 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3745 Result->getPointeeType()))) {
3746 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3747 << FDecl;
3748 return ExprError();
3749 }
3750 break;
3751 }
3752 case Builtin::BI__builtin_ptrauth_strip:
3753 return PointerAuthStrip(*this, TheCall);
3754 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3755 return PointerAuthBlendDiscriminator(*this, TheCall);
3756 case Builtin::BI__builtin_ptrauth_sign_constant:
3757 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3758 /*RequireConstant=*/true);
3759 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3760 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3761 /*RequireConstant=*/false);
3762 case Builtin::BI__builtin_ptrauth_auth:
3763 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3764 /*RequireConstant=*/false);
3765 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3766 return PointerAuthSignGenericData(*this, TheCall);
3767 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3768 return PointerAuthAuthAndResign(*this, TheCall);
3769 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3770 return PointerAuthAuthWithPCAndResign(*this, TheCall);
3771 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3772 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3773 case Builtin::BI__builtin_ptrauth_string_discriminator:
3774 return PointerAuthStringDiscriminator(*this, TheCall);
3775
3776 case Builtin::BI__builtin_get_vtable_pointer:
3777 return GetVTablePointer(*this, TheCall);
3778
3779 // OpenCL v2.0, s6.13.16 - Pipe functions
3780 case Builtin::BIread_pipe:
3781 case Builtin::BIwrite_pipe:
3782 // Since those two functions are declared with var args, we need a semantic
3783 // check for the argument.
3784 if (OpenCL().checkBuiltinRWPipe(TheCall))
3785 return ExprError();
3786 break;
3787 case Builtin::BIreserve_read_pipe:
3788 case Builtin::BIreserve_write_pipe:
3789 case Builtin::BIwork_group_reserve_read_pipe:
3790 case Builtin::BIwork_group_reserve_write_pipe:
3791 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3792 return ExprError();
3793 break;
3794 case Builtin::BIsub_group_reserve_read_pipe:
3795 case Builtin::BIsub_group_reserve_write_pipe:
3796 if (OpenCL().checkSubgroupExt(TheCall) ||
3797 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3798 return ExprError();
3799 break;
3800 case Builtin::BIcommit_read_pipe:
3801 case Builtin::BIcommit_write_pipe:
3802 case Builtin::BIwork_group_commit_read_pipe:
3803 case Builtin::BIwork_group_commit_write_pipe:
3804 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3805 return ExprError();
3806 break;
3807 case Builtin::BIsub_group_commit_read_pipe:
3808 case Builtin::BIsub_group_commit_write_pipe:
3809 if (OpenCL().checkSubgroupExt(TheCall) ||
3810 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3811 return ExprError();
3812 break;
3813 case Builtin::BIget_pipe_num_packets:
3814 case Builtin::BIget_pipe_max_packets:
3815 if (OpenCL().checkBuiltinPipePackets(TheCall))
3816 return ExprError();
3817 break;
3818 case Builtin::BIto_global:
3819 case Builtin::BIto_local:
3820 case Builtin::BIto_private:
3821 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3822 return ExprError();
3823 break;
3824 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3825 case Builtin::BIenqueue_kernel:
3826 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3827 return ExprError();
3828 break;
3829 case Builtin::BIget_kernel_work_group_size:
3830 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3831 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3832 return ExprError();
3833 break;
3834 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3835 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3836 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3837 return ExprError();
3838 break;
3839 case Builtin::BI__builtin_os_log_format:
3840 Cleanup.setExprNeedsCleanups(true);
3841 [[fallthrough]];
3842 case Builtin::BI__builtin_os_log_format_buffer_size:
3843 if (BuiltinOSLogFormat(TheCall))
3844 return ExprError();
3845 break;
3846 case Builtin::BI__builtin_frame_address:
3847 case Builtin::BI__builtin_return_address: {
3848 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3849 return ExprError();
3850
3851 // -Wframe-address warning if non-zero passed to builtin
3852 // return/frame address.
3853 Expr::EvalResult Result;
3854 if (!TheCall->getArg(0)->isValueDependent() &&
3855 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3856 Result.Val.getInt() != 0)
3857 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3858 << ((BuiltinID == Builtin::BI__builtin_return_address)
3859 ? "__builtin_return_address"
3860 : "__builtin_frame_address")
3861 << TheCall->getSourceRange();
3862 break;
3863 }
3864
3865 case Builtin::BI__builtin_nondeterministic_value: {
3866 if (BuiltinNonDeterministicValue(TheCall))
3867 return ExprError();
3868 break;
3869 }
3870
3871 // __builtin_elementwise_abs restricts the element type to signed integers or
3872 // floating point types only.
3873 case Builtin::BI__builtin_elementwise_abs:
3876 return ExprError();
3877 break;
3878
3879 // These builtins restrict the element type to floating point
3880 // types only.
3881 case Builtin::BI__builtin_elementwise_acos:
3882 case Builtin::BI__builtin_elementwise_asin:
3883 case Builtin::BI__builtin_elementwise_atan:
3884 case Builtin::BI__builtin_elementwise_ceil:
3885 case Builtin::BI__builtin_elementwise_cos:
3886 case Builtin::BI__builtin_elementwise_cosh:
3887 case Builtin::BI__builtin_elementwise_exp:
3888 case Builtin::BI__builtin_elementwise_exp2:
3889 case Builtin::BI__builtin_elementwise_exp10:
3890 case Builtin::BI__builtin_elementwise_floor:
3891 case Builtin::BI__builtin_elementwise_log:
3892 case Builtin::BI__builtin_elementwise_log2:
3893 case Builtin::BI__builtin_elementwise_log10:
3894 case Builtin::BI__builtin_elementwise_roundeven:
3895 case Builtin::BI__builtin_elementwise_round:
3896 case Builtin::BI__builtin_elementwise_rint:
3897 case Builtin::BI__builtin_elementwise_nearbyint:
3898 case Builtin::BI__builtin_elementwise_sin:
3899 case Builtin::BI__builtin_elementwise_sinh:
3900 case Builtin::BI__builtin_elementwise_sqrt:
3901 case Builtin::BI__builtin_elementwise_tan:
3902 case Builtin::BI__builtin_elementwise_tanh:
3903 case Builtin::BI__builtin_elementwise_trunc:
3904 case Builtin::BI__builtin_elementwise_canonicalize:
3907 return ExprError();
3908 break;
3909 case Builtin::BI__builtin_elementwise_fma:
3910 if (BuiltinElementwiseTernaryMath(TheCall))
3911 return ExprError();
3912 break;
3913
3914 case Builtin::BI__builtin_elementwise_ldexp: {
3915 if (checkArgCount(TheCall, 2))
3916 return ExprError();
3917
3918 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3919 if (A.isInvalid())
3920 return ExprError();
3921 QualType TyA = A.get()->getType();
3922 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3924 return ExprError();
3925
3926 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3927 if (Exp.isInvalid())
3928 return ExprError();
3929 QualType TyExp = Exp.get()->getType();
3930 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3932 2))
3933 return ExprError();
3934
3935 // Check the two arguments are either scalars or vectors of equal length.
3936 const auto *Vec0 = TyA->getAs<VectorType>();
3937 const auto *Vec1 = TyExp->getAs<VectorType>();
3938 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3939 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3940 if (Arg0Length != Arg1Length) {
3941 Diag(Exp.get()->getBeginLoc(),
3942 diag::err_typecheck_vector_lengths_not_equal)
3943 << TyA << TyExp << A.get()->getSourceRange()
3944 << Exp.get()->getSourceRange();
3945 return ExprError();
3946 }
3947
3948 TheCall->setArg(0, A.get());
3949 TheCall->setArg(1, Exp.get());
3950 TheCall->setType(TyA);
3951 break;
3952 }
3953
3954 // These builtins restrict the element type to floating point
3955 // types only, and take in two arguments.
3956 case Builtin::BI__builtin_elementwise_minnum:
3957 case Builtin::BI__builtin_elementwise_maxnum:
3958 case Builtin::BI__builtin_elementwise_minimum:
3959 case Builtin::BI__builtin_elementwise_maximum:
3960 case Builtin::BI__builtin_elementwise_minimumnum:
3961 case Builtin::BI__builtin_elementwise_maximumnum:
3962 case Builtin::BI__builtin_elementwise_atan2:
3963 case Builtin::BI__builtin_elementwise_fmod:
3964 case Builtin::BI__builtin_elementwise_pow:
3965 if (BuiltinElementwiseMath(TheCall,
3967 return ExprError();
3968 break;
3969 // These builtins restrict the element type to integer
3970 // types only.
3971 case Builtin::BI__builtin_elementwise_add_sat:
3972 case Builtin::BI__builtin_elementwise_sub_sat:
3973 case Builtin::BI__builtin_elementwise_clmul:
3974 case Builtin::BI__builtin_elementwise_pext:
3975 case Builtin::BI__builtin_elementwise_pdep:
3976 if (BuiltinElementwiseMath(TheCall,
3978 return ExprError();
3979 break;
3980 case Builtin::BI__builtin_elementwise_fshl:
3981 case Builtin::BI__builtin_elementwise_fshr:
3984 return ExprError();
3985 break;
3986 case Builtin::BI__builtin_elementwise_min:
3987 case Builtin::BI__builtin_elementwise_max: {
3988 if (BuiltinElementwiseMath(TheCall))
3989 return ExprError();
3990 Expr *Arg0 = TheCall->getArg(0);
3991 Expr *Arg1 = TheCall->getArg(1);
3992 QualType Ty0 = Arg0->getType();
3993 QualType Ty1 = Arg1->getType();
3994 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3995 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3996 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3997 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3998 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3999 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
4000 << Context.BuiltinInfo.getQuotedName(BuiltinID);
4001 break;
4002 }
4003 case Builtin::BI__builtin_elementwise_popcount:
4004 case Builtin::BI__builtin_elementwise_bitreverse:
4007 return ExprError();
4008 break;
4009 case Builtin::BI__builtin_elementwise_copysign: {
4010 if (checkArgCount(TheCall, 2))
4011 return ExprError();
4012
4013 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
4014 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
4015 if (Magnitude.isInvalid() || Sign.isInvalid())
4016 return ExprError();
4017
4018 QualType MagnitudeTy = Magnitude.get()->getType();
4019 QualType SignTy = Sign.get()->getType();
4021 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
4024 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
4026 return ExprError();
4027 }
4028
4029 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
4030 return Diag(Sign.get()->getBeginLoc(),
4031 diag::err_typecheck_call_different_arg_types)
4032 << MagnitudeTy << SignTy;
4033 }
4034
4035 TheCall->setArg(0, Magnitude.get());
4036 TheCall->setArg(1, Sign.get());
4037 TheCall->setType(Magnitude.get()->getType());
4038 break;
4039 }
4040 case Builtin::BI__builtin_elementwise_clzg:
4041 case Builtin::BI__builtin_elementwise_ctzg:
4042 // These builtins can be unary or binary. Note for empty calls we call the
4043 // unary checker in order to not emit an error that says the function
4044 // expects 2 arguments, which would be misleading.
4045 if (TheCall->getNumArgs() <= 1) {
4048 return ExprError();
4049 } else if (BuiltinElementwiseMath(
4051 return ExprError();
4052 break;
4053 case Builtin::BI__builtin_reduce_max:
4054 case Builtin::BI__builtin_reduce_min: {
4055 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4056 return ExprError();
4057
4058 const Expr *Arg = TheCall->getArg(0);
4059 const auto *TyA = Arg->getType()->getAs<VectorType>();
4060
4061 QualType ElTy;
4062 if (TyA)
4063 ElTy = TyA->getElementType();
4064 else if (Arg->getType()->isSizelessVectorType())
4066
4067 if (ElTy.isNull()) {
4068 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4069 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
4070 << Arg->getType();
4071 return ExprError();
4072 }
4073
4074 TheCall->setType(ElTy);
4075 break;
4076 }
4077 case Builtin::BI__builtin_reduce_maximum:
4078 case Builtin::BI__builtin_reduce_minimum: {
4079 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4080 return ExprError();
4081
4082 const Expr *Arg = TheCall->getArg(0);
4083 const auto *TyA = Arg->getType()->getAs<VectorType>();
4084
4085 QualType ElTy;
4086 if (TyA)
4087 ElTy = TyA->getElementType();
4088 else if (Arg->getType()->isSizelessVectorType())
4090
4091 if (ElTy.isNull() || !ElTy->isFloatingType()) {
4092 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4093 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4094 << Arg->getType();
4095 return ExprError();
4096 }
4097
4098 TheCall->setType(ElTy);
4099 break;
4100 }
4101
4102 // These builtins support vectors of integers only.
4103 // TODO: ADD/MUL should support floating-point types.
4104 case Builtin::BI__builtin_reduce_add:
4105 case Builtin::BI__builtin_reduce_mul:
4106 case Builtin::BI__builtin_reduce_xor:
4107 case Builtin::BI__builtin_reduce_or:
4108 case Builtin::BI__builtin_reduce_and: {
4109 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4110 return ExprError();
4111
4112 const Expr *Arg = TheCall->getArg(0);
4113
4114 QualType ElTy = getVectorElementType(Context, Arg->getType());
4115 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4116 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4117 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4118 << Arg->getType();
4119 return ExprError();
4120 }
4121
4122 TheCall->setType(ElTy);
4123 break;
4124 }
4125
4126 case Builtin::BI__builtin_reduce_assoc_fadd:
4127 case Builtin::BI__builtin_reduce_in_order_fadd: {
4128 // For in-order reductions require the user to specify the start value.
4129 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4130 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
4131 return ExprError();
4132
4133 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
4134 if (Vec.isInvalid())
4135 return ExprError();
4136
4137 TheCall->setArg(0, Vec.get());
4138
4139 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
4140 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4141 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4142 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4143 << Vec.get()->getType();
4144 return ExprError();
4145 }
4146
4147 if (TheCall->getNumArgs() == 2) {
4148 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
4149 if (StartValue.isInvalid())
4150 return ExprError();
4151
4152 if (!StartValue.get()->getType()->isRealFloatingType()) {
4153 Diag(StartValue.get()->getBeginLoc(),
4154 diag::err_builtin_invalid_arg_type)
4155 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4156 << StartValue.get()->getType();
4157 return ExprError();
4158 }
4159 TheCall->setArg(1, StartValue.get());
4160 }
4161
4162 TheCall->setType(ElTy);
4163 break;
4164 }
4165
4166 case Builtin::BI__builtin_matrix_transpose:
4167 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4168
4169 case Builtin::BI__builtin_matrix_column_major_load:
4170 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4171
4172 case Builtin::BI__builtin_matrix_column_major_store:
4173 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4174
4175 case Builtin::BI__builtin_verbose_trap:
4176 if (!checkBuiltinVerboseTrap(TheCall, *this))
4177 return ExprError();
4178 break;
4179
4180 case Builtin::BI__builtin_get_device_side_mangled_name: {
4181 auto Check = [](CallExpr *TheCall) {
4182 if (TheCall->getNumArgs() != 1)
4183 return false;
4184 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
4185 if (!DRE)
4186 return false;
4187 auto *D = DRE->getDecl();
4188 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
4189 return false;
4190 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4191 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4192 };
4193 if (!Check(TheCall)) {
4194 Diag(TheCall->getBeginLoc(),
4195 diag::err_hip_invalid_args_builtin_mangled_name);
4196 return ExprError();
4197 }
4198 break;
4199 }
4200 case Builtin::BI__builtin_bswapg:
4201 if (BuiltinBswapg(*this, TheCall))
4202 return ExprError();
4203 break;
4204 case Builtin::BI__builtin_bitreverseg:
4205 if (BuiltinBitreverseg(*this, TheCall))
4206 return ExprError();
4207 break;
4208 case Builtin::BI__builtin_popcountg:
4209 if (BuiltinPopcountg(*this, TheCall))
4210 return ExprError();
4211 break;
4212 case Builtin::BI__builtin_clzg:
4213 case Builtin::BI__builtin_ctzg:
4214 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
4215 return ExprError();
4216 break;
4217
4218 case Builtin::BI__builtin_stdc_rotate_left:
4219 case Builtin::BI__builtin_stdc_rotate_right:
4220 if (BuiltinRotateGeneric(*this, TheCall))
4221 return ExprError();
4222 break;
4223
4224 case Builtin::BI__builtin_stdc_memreverse8:
4225 case Builtin::BIstdc_memreverse8:
4226 case Builtin::BIstdc_memreverse8u8:
4227 case Builtin::BIstdc_memreverse8u16:
4228 case Builtin::BIstdc_memreverse8u32:
4229 case Builtin::BIstdc_memreverse8u64:
4230 if (Context.getTargetInfo().getCharWidth() != 8) {
4231 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
4232 << TheCall->getDirectCallee()->getName();
4233 return ExprError();
4234 }
4235 break;
4236
4237 case Builtin::BI__builtin_stdc_bit_floor:
4238 case Builtin::BI__builtin_stdc_bit_ceil:
4239 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4240 return ExprError();
4241 break;
4242 case Builtin::BI__builtin_stdc_has_single_bit:
4243 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4244 return ExprError();
4245 break;
4246 case Builtin::BI__builtin_stdc_leading_zeros:
4247 case Builtin::BI__builtin_stdc_leading_ones:
4248 case Builtin::BI__builtin_stdc_trailing_zeros:
4249 case Builtin::BI__builtin_stdc_trailing_ones:
4250 case Builtin::BI__builtin_stdc_first_leading_zero:
4251 case Builtin::BI__builtin_stdc_first_leading_one:
4252 case Builtin::BI__builtin_stdc_first_trailing_zero:
4253 case Builtin::BI__builtin_stdc_first_trailing_one:
4254 case Builtin::BI__builtin_stdc_count_zeros:
4255 case Builtin::BI__builtin_stdc_count_ones:
4256 case Builtin::BI__builtin_stdc_bit_width:
4257 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4258 return ExprError();
4259 break;
4260
4261 case Builtin::BI__builtin_allow_runtime_check: {
4262 Expr *Arg = TheCall->getArg(0);
4263 // Check if the argument is a string literal.
4265 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4266 << Arg->getSourceRange();
4267 return ExprError();
4268 }
4269 break;
4270 }
4271
4272 case Builtin::BI__builtin_allow_sanitize_check: {
4273 if (checkArgCount(TheCall, 1))
4274 return ExprError();
4275
4276 Expr *Arg = TheCall->getArg(0);
4277 // Check if the argument is a string literal.
4278 const StringLiteral *SanitizerName =
4279 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4280 if (!SanitizerName) {
4281 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4282 << Arg->getSourceRange();
4283 return ExprError();
4284 }
4285 // Validate the sanitizer name.
4286 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4287 .Cases({"address", "thread", "memory", "hwaddress",
4288 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4289 true)
4290 .Default(false)) {
4291 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4292 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4293 << Arg->getSourceRange();
4294 return ExprError();
4295 }
4296 break;
4297 }
4298 case Builtin::BI__builtin_counted_by_ref:
4299 if (BuiltinCountedByRef(TheCall))
4300 return ExprError();
4301 break;
4302 }
4303
4304 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4305 return ExprError();
4306
4307 // Since the target specific builtins for each arch overlap, only check those
4308 // of the arch we are compiling for.
4309 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4310 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4311 assert(Context.getAuxTargetInfo() &&
4312 "Aux Target Builtin, but not an aux target?");
4313
4314 if (CheckTSBuiltinFunctionCall(
4315 *Context.getAuxTargetInfo(),
4316 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4317 return ExprError();
4318 } else {
4319 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4320 TheCall))
4321 return ExprError();
4322 }
4323 }
4324
4325 return TheCallResult;
4326}
4327
4328bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4329 llvm::APSInt Result;
4330 // We can't check the value of a dependent argument.
4331 Expr *Arg = TheCall->getArg(ArgNum);
4332 if (Arg->isTypeDependent() || Arg->isValueDependent())
4333 return false;
4334
4335 // Check constant-ness first.
4336 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4337 return true;
4338
4339 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4340 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4341 return false;
4342
4343 return Diag(TheCall->getBeginLoc(),
4344 diag::err_argument_not_contiguous_bit_field)
4345 << ArgNum << Arg->getSourceRange();
4346}
4347
4348bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4349 unsigned FirstArg, FormatStringInfo *FSI) {
4350 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4351 bool IsVariadic = false;
4352 if (const FunctionType *FnTy = D->getFunctionType())
4353 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4354 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4355 IsVariadic = BD->isVariadic();
4356 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4357 IsVariadic = OMD->isVariadic();
4358
4359 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4360 IsVariadic, FSI);
4361}
4362
4363bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4364 bool HasImplicitThisParam, bool IsVariadic,
4365 FormatStringInfo *FSI) {
4366 if (FirstArg == 0)
4368 else if (IsVariadic)
4370 else
4372 FSI->FormatIdx = FormatIdx - 1;
4373 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4374
4375 // The way the format attribute works in GCC, the implicit this argument
4376 // of member functions is counted. However, it doesn't appear in our own
4377 // lists, so decrement format_idx in that case.
4378 if (HasImplicitThisParam) {
4379 if(FSI->FormatIdx == 0)
4380 return false;
4381 --FSI->FormatIdx;
4382 if (FSI->FirstDataArg != 0)
4383 --FSI->FirstDataArg;
4384 }
4385 return true;
4386}
4387
4388/// Checks if a the given expression evaluates to null.
4389///
4390/// Returns true if the value evaluates to null.
4391static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4392 // Treat (smart) pointers constructed from nullptr as null, whether we can
4393 // const-evaluate them or not.
4394 // This must happen first: the smart pointer expr might have _Nonnull type!
4398 return true;
4399
4400 // If the expression has non-null type, it doesn't evaluate to null.
4401 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4402 if (*nullability == NullabilityKind::NonNull)
4403 return false;
4404 }
4405
4406 // As a special case, transparent unions initialized with zero are
4407 // considered null for the purposes of the nonnull attribute.
4408 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4409 UT &&
4410 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4411 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4412 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4413 Expr = ILE->getInit(0);
4414 }
4415
4416 bool Result;
4417 return (!Expr->isValueDependent() &&
4419 !Result);
4420}
4421
4423 const Expr *ArgExpr,
4424 SourceLocation CallSiteLoc) {
4425 if (CheckNonNullExpr(S, ArgExpr))
4426 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4427 S.PDiag(diag::warn_null_arg)
4428 << ArgExpr->getSourceRange());
4429}
4430
4431/// Determine whether the given type has a non-null nullability annotation.
4433 if (auto nullability = type->getNullability())
4434 return *nullability == NullabilityKind::NonNull;
4435
4436 return false;
4437}
4438
4440 const NamedDecl *FDecl,
4441 const FunctionProtoType *Proto,
4443 SourceLocation CallSiteLoc) {
4444 assert((FDecl || Proto) && "Need a function declaration or prototype");
4445
4446 // Already checked by constant evaluator.
4448 return;
4449 // Check the attributes attached to the method/function itself.
4450 llvm::SmallBitVector NonNullArgs;
4451 if (FDecl) {
4452 // Handle the nonnull attribute on the function/method declaration itself.
4453 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4454 if (!NonNull->args_size()) {
4455 // Easy case: all pointer arguments are nonnull.
4456 for (const auto *Arg : Args)
4457 if (S.isValidPointerAttrType(Arg->getType()))
4458 CheckNonNullArgument(S, Arg, CallSiteLoc);
4459 return;
4460 }
4461
4462 for (const ParamIdx &Idx : NonNull->args()) {
4463 unsigned IdxAST = Idx.getASTIndex();
4464 if (IdxAST >= Args.size())
4465 continue;
4466 if (NonNullArgs.empty())
4467 NonNullArgs.resize(Args.size());
4468 NonNullArgs.set(IdxAST);
4469 }
4470 }
4471 }
4472
4473 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4474 // Handle the nonnull attribute on the parameters of the
4475 // function/method.
4477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4478 parms = FD->parameters();
4479 else
4480 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4481
4482 unsigned ParamIndex = 0;
4483 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4484 I != E; ++I, ++ParamIndex) {
4485 const ParmVarDecl *PVD = *I;
4486 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4487 if (NonNullArgs.empty())
4488 NonNullArgs.resize(Args.size());
4489
4490 NonNullArgs.set(ParamIndex);
4491 }
4492 }
4493 } else {
4494 // If we have a non-function, non-method declaration but no
4495 // function prototype, try to dig out the function prototype.
4496 if (!Proto) {
4497 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4498 QualType type = VD->getType().getNonReferenceType();
4499 if (auto pointerType = type->getAs<PointerType>())
4500 type = pointerType->getPointeeType();
4501 else if (auto blockType = type->getAs<BlockPointerType>())
4502 type = blockType->getPointeeType();
4503 // FIXME: data member pointers?
4504
4505 // Dig out the function prototype, if there is one.
4506 Proto = type->getAs<FunctionProtoType>();
4507 }
4508 }
4509
4510 // Fill in non-null argument information from the nullability
4511 // information on the parameter types (if we have them).
4512 if (Proto) {
4513 unsigned Index = 0;
4514 for (auto paramType : Proto->getParamTypes()) {
4515 if (isNonNullType(paramType)) {
4516 if (NonNullArgs.empty())
4517 NonNullArgs.resize(Args.size());
4518
4519 NonNullArgs.set(Index);
4520 }
4521
4522 ++Index;
4523 }
4524 }
4525 }
4526
4527 // Check for non-null arguments.
4528 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4529 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4530 if (NonNullArgs[ArgIndex])
4531 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4532 }
4533}
4534
4535void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4536 StringRef ParamName, QualType ArgTy,
4537 QualType ParamTy) {
4538
4539 // If a function accepts a pointer or reference type
4540 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4541 return;
4542
4543 // If the parameter is a pointer type, get the pointee type for the
4544 // argument too. If the parameter is a reference type, don't try to get
4545 // the pointee type for the argument.
4546 if (ParamTy->isPointerType())
4547 ArgTy = ArgTy->getPointeeType();
4548
4549 // Remove reference or pointer
4550 ParamTy = ParamTy->getPointeeType();
4551
4552 // Find expected alignment, and the actual alignment of the passed object.
4553 // getTypeAlignInChars requires complete types
4554 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4555 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4556 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4557 return;
4558
4559 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4560 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4561
4562 // If the argument is less aligned than the parameter, there is a
4563 // potential alignment issue.
4564 if (ArgAlign < ParamAlign)
4565 Diag(Loc, diag::warn_param_mismatched_alignment)
4566 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4567 << ParamName << (FDecl != nullptr) << FDecl;
4568}
4569
4570void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4571 const Expr *ThisArg,
4573 if (!FD || Args.empty())
4574 return;
4575 auto GetArgAt = [&](int Idx) -> const Expr * {
4576 if (Idx == LifetimeCaptureByAttr::Global ||
4577 Idx == LifetimeCaptureByAttr::Unknown)
4578 return nullptr;
4579 if (IsMemberFunction && Idx == 0)
4580 return ThisArg;
4581 return Args[Idx - IsMemberFunction];
4582 };
4583 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4584 unsigned ArgIdx) {
4585 if (!Attr)
4586 return;
4587
4588 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4589 for (int CapturingParamIdx : Attr->params()) {
4590 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4591 continue;
4592 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4593 // initialization codepath.
4594 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4596 continue;
4597 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4598 CapturingEntity CE{Capturing};
4599 // Ensure that 'Captured' outlives the 'Capturing' entity.
4600 checkCaptureByLifetime(*this, CE, Captured);
4601 }
4602 };
4603 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4604 for (const auto *A :
4605 FD->getParamDecl(I)->specific_attrs<LifetimeCaptureByAttr>())
4606 HandleCaptureByAttr(A, I + IsMemberFunction);
4607 // Check when the implicit object param is captured.
4608 if (IsMemberFunction) {
4609 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4610 if (!TSI)
4611 return;
4613 for (TypeLoc TL = TSI->getTypeLoc();
4614 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4615 TL = ATL.getModifiedLoc())
4616 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4617 }
4618}
4619
4621 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4622 bool IsMemberFunction, SourceLocation Loc,
4623 SourceRange Range, VariadicCallType CallType) {
4624
4625 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4626 llvm::any_of(Args, [](const Expr *E) {
4627 return E && E->isInstantiationDependent();
4628 }))
4629 return;
4630
4631 // Printf and scanf checking.
4632 llvm::SmallBitVector CheckedVarArgs;
4633 if (FDecl) {
4634 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4635 // Only create vector if there are format attributes.
4636 CheckedVarArgs.resize(Args.size());
4637 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4638 CheckedVarArgs);
4639 }
4640
4641 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4642 CheckedVarArgs.resize(Args.size());
4643 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4644 CheckedVarArgs);
4645 }
4646 }
4647
4648 // Refuse POD arguments that weren't caught by the format string
4649 // checks above.
4650 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4651 if (CallType != VariadicCallType::DoesNotApply &&
4652 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4653 unsigned NumParams = Proto ? Proto->getNumParams()
4654 : isa_and_nonnull<FunctionDecl>(FDecl)
4655 ? cast<FunctionDecl>(FDecl)->getNumParams()
4656 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4657 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4658 : 0;
4659
4660 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4661 // Args[ArgIdx] can be null in malformed code.
4662 if (const Expr *Arg = Args[ArgIdx]) {
4663 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4664 checkVariadicArgument(Arg, CallType);
4665 }
4666 }
4667 }
4668 if (FD)
4669 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4670 if (FDecl || Proto) {
4671 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4672
4673 // Type safety checking.
4674 if (FDecl) {
4675 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4676 CheckArgumentWithTypeTag(I, Args, Loc);
4677 }
4678 }
4679
4680 // Check that passed arguments match the alignment of original arguments.
4681 // Try to get the missing prototype from the declaration.
4682 if (!Proto && FDecl) {
4683 const auto *FT = FDecl->getFunctionType();
4684 if (isa_and_nonnull<FunctionProtoType>(FT))
4685 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4686 }
4687 if (Proto) {
4688 // For variadic functions, we may have more args than parameters.
4689 // For some K&R functions, we may have less args than parameters.
4690 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4691 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4692 bool IsScalableArg = false;
4693 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4694 // Args[ArgIdx] can be null in malformed code.
4695 if (const Expr *Arg = Args[ArgIdx]) {
4696 if (Arg->containsErrors())
4697 continue;
4698
4699 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4700 FDecl->hasLinkage() &&
4701 FDecl->getFormalLinkage() != Linkage::Internal &&
4703 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4704
4705 QualType ParamTy = Proto->getParamType(ArgIdx);
4706 if (ParamTy->isSizelessVectorType())
4707 IsScalableArg = true;
4708 QualType ArgTy = Arg->getType();
4709 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4710 ArgTy, ParamTy);
4711 }
4712 }
4713
4714 // If the callee has an AArch64 SME attribute to indicate that it is an
4715 // __arm_streaming function, then the caller requires SME to be available.
4718 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4719 llvm::StringMap<bool> CallerFeatureMap;
4720 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4721 if (!CallerFeatureMap.contains("sme"))
4722 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4723 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4724 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4725 }
4726 }
4727
4728 // If the call requires a streaming-mode change and has scalable vector
4729 // arguments or return values, then warn the user that the streaming and
4730 // non-streaming vector lengths may be different.
4731 // When both streaming and non-streaming vector lengths are defined and
4732 // mismatched, produce an error.
4733 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4734 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4735 (IsScalableArg || IsScalableRet)) {
4736 bool IsCalleeStreaming =
4738 bool IsCalleeStreamingCompatible =
4739 ExtInfo.AArch64SMEAttributes &
4741 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4742 if (!IsCalleeStreamingCompatible &&
4743 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4744 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4745 const LangOptions &LO = getLangOpts();
4746 unsigned VL = LO.VScaleMin * 128;
4747 unsigned SVL = LO.VScaleStreamingMin * 128;
4748 bool IsVLMismatch = VL && SVL && VL != SVL;
4749
4750 auto EmitDiag = [&](bool IsArg) {
4751 if (IsVLMismatch) {
4752 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4753 // Emit warning for streaming-compatible callers
4754 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4755 << IsArg << IsCalleeStreaming << SVL << VL;
4756 else
4757 // Emit error otherwise
4758 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4759 << IsArg << SVL << VL;
4760 } else
4761 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4762 << IsArg;
4763 };
4764
4765 if (IsScalableArg)
4766 EmitDiag(true);
4767 if (IsScalableRet)
4768 EmitDiag(false);
4769 }
4770 }
4771
4772 FunctionType::ArmStateValue CalleeArmZAState =
4774 FunctionType::ArmStateValue CalleeArmZT0State =
4776 if (CalleeArmZAState != FunctionType::ARM_None ||
4777 CalleeArmZT0State != FunctionType::ARM_None) {
4778 bool CallerHasZAState = false;
4779 bool CallerHasZT0State = false;
4780 if (CallerFD) {
4781 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4782 if (Attr && Attr->isNewZA())
4783 CallerHasZAState = true;
4784 if (Attr && Attr->isNewZT0())
4785 CallerHasZT0State = true;
4786 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4787 CallerHasZAState |=
4789 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4791 CallerHasZT0State |=
4793 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4795 }
4796 }
4797
4798 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4799 Diag(Loc, diag::err_sme_za_call_no_za_state);
4800
4801 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4802 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4803
4804 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4805 CalleeArmZT0State != FunctionType::ARM_None) {
4806 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4807 Diag(Loc, diag::note_sme_use_preserves_za);
4808 }
4809 }
4810 }
4811
4812 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4813 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4814 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4815 if (!Arg->isValueDependent()) {
4816 Expr::EvalResult Align;
4817 if (Arg->EvaluateAsInt(Align, Context)) {
4818 const llvm::APSInt &I = Align.Val.getInt();
4819 if (!I.isPowerOf2())
4820 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4821 << Arg->getSourceRange();
4822
4823 if (I > Sema::MaximumAlignment)
4824 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4825 << Arg->getSourceRange() << Sema::MaximumAlignment;
4826 }
4827 }
4828 }
4829
4830 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4832 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4833 << diag::OffloadLang::SYCL;
4834
4835 if (FD)
4836 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4837}
4838
4839void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4840 if (TemplateDecl *Decl =
4841 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4842 DiagnoseUseOfDecl(Decl, Loc);
4843 }
4844}
4845
4846void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4848 const FunctionProtoType *Proto,
4849 SourceLocation Loc) {
4850 VariadicCallType CallType = Proto->isVariadic()
4853
4854 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4855 CheckArgAlignment(
4856 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4857 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4858
4859 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4860 Loc, SourceRange(), CallType);
4861}
4862
4864 const FunctionProtoType *Proto) {
4865 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4866 isa<CXXMethodDecl>(FDecl);
4867 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4868 IsMemberOperatorCall;
4869 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4870 TheCall->getCallee());
4871 Expr** Args = TheCall->getArgs();
4872 unsigned NumArgs = TheCall->getNumArgs();
4873
4874 Expr *ImplicitThis = nullptr;
4875 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4876 // If this is a call to a member operator, hide the first
4877 // argument from checkCall.
4878 // FIXME: Our choice of AST representation here is less than ideal.
4879 ImplicitThis = Args[0];
4880 ++Args;
4881 --NumArgs;
4882 } else if (IsMemberFunction && !FDecl->isStatic() &&
4884 ImplicitThis =
4885 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4886
4887 if (ImplicitThis) {
4888 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4889 // used.
4890 QualType ThisType = ImplicitThis->getType();
4891 if (!ThisType->isPointerType()) {
4892 assert(!ThisType->isReferenceType());
4893 ThisType = Context.getPointerType(ThisType);
4894 }
4895
4896 QualType ThisTypeFromDecl = Context.getPointerType(
4897 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4898
4899 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4900 ThisTypeFromDecl);
4901 }
4902
4903 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4904 IsMemberFunction, TheCall->getRParenLoc(),
4905 TheCall->getCallee()->getSourceRange(), CallType);
4906
4907 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4908 // None of the checks below are needed for functions that don't have
4909 // simple names (e.g., C++ conversion functions).
4910 if (!FnInfo)
4911 return false;
4912
4913 // Enforce TCB except for builtin calls, which are always allowed.
4914 if (FDecl->getBuiltinID() == 0)
4915 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4916
4917 CheckAbsoluteValueFunction(TheCall, FDecl);
4918 CheckMaxUnsignedZero(TheCall, FDecl);
4919 CheckInfNaNFunction(TheCall, FDecl);
4920
4921 if (getLangOpts().ObjC)
4922 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4923
4924 unsigned CMId = FDecl->getMemoryFunctionKind();
4925
4926 // Handle memory setting and copying functions.
4927 switch (CMId) {
4928 case 0:
4929 return false;
4930 case Builtin::BIstrlcpy: // fallthrough
4931 case Builtin::BIstrlcat:
4932 CheckStrlcpycatArguments(TheCall, FnInfo);
4933 break;
4934 case Builtin::BIstrncat:
4935 CheckStrncatArguments(TheCall, FnInfo);
4936 break;
4937 case Builtin::BIfree:
4938 CheckFreeArguments(TheCall);
4939 break;
4940 default:
4941 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4942 }
4943
4944 return false;
4945}
4946
4947bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4948 const FunctionProtoType *Proto) {
4949 QualType Ty;
4950 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4951 Ty = V->getType().getNonReferenceType();
4952 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4953 Ty = F->getType().getNonReferenceType();
4954 else
4955 return false;
4956
4957 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4958 !Ty->isFunctionProtoType())
4959 return false;
4960
4961 VariadicCallType CallType;
4962 if (!Proto || !Proto->isVariadic()) {
4964 } else if (Ty->isBlockPointerType()) {
4965 CallType = VariadicCallType::Block;
4966 } else { // Ty->isFunctionPointerType()
4967 CallType = VariadicCallType::Function;
4968 }
4969
4970 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4971 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4972 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4973 TheCall->getCallee()->getSourceRange(), CallType);
4974
4975 return false;
4976}
4977
4978bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4979 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4980 TheCall->getCallee());
4981 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4982 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4983 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4984 TheCall->getCallee()->getSourceRange(), CallType);
4985
4986 return false;
4987}
4988
4989static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4990 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4991 return false;
4992
4993 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4994 switch (Op) {
4995 case AtomicExpr::AO__c11_atomic_init:
4996 case AtomicExpr::AO__opencl_atomic_init:
4997 llvm_unreachable("There is no ordering argument for an init");
4998
4999 case AtomicExpr::AO__c11_atomic_load:
5000 case AtomicExpr::AO__opencl_atomic_load:
5001 case AtomicExpr::AO__hip_atomic_load:
5002 case AtomicExpr::AO__atomic_load_n:
5003 case AtomicExpr::AO__atomic_load:
5004 case AtomicExpr::AO__scoped_atomic_load_n:
5005 case AtomicExpr::AO__scoped_atomic_load:
5006 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5007 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5008
5009 case AtomicExpr::AO__c11_atomic_store:
5010 case AtomicExpr::AO__opencl_atomic_store:
5011 case AtomicExpr::AO__hip_atomic_store:
5012 case AtomicExpr::AO__atomic_store:
5013 case AtomicExpr::AO__atomic_store_n:
5014 case AtomicExpr::AO__scoped_atomic_store:
5015 case AtomicExpr::AO__scoped_atomic_store_n:
5016 case AtomicExpr::AO__atomic_clear:
5017 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5018 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5019 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5020
5021 default:
5022 return true;
5023 }
5024}
5025
5026ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
5028 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5029 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5030 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5031 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5032 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5033 Op);
5034}
5035
5036/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
5037/// equivalents. Provide a fixit when the scope is a compile-time constant and
5038/// there is a direct mapping from the HIP builtin to a Clang builtin. The
5039/// compare_exchange builtins differ in how they accept the desired value, so
5040/// only a warning (without a fixit) is emitted for those.
5042 MultiExprArg Args,
5044 StringRef OldName;
5045 StringRef NewName;
5046 bool CanFixIt;
5047
5048 switch (Op) {
5049#define HIP_ATOMIC_FIXABLE(hip, scoped) \
5050 case AtomicExpr::AO__hip_atomic_##hip: \
5051 OldName = "__hip_atomic_" #hip; \
5052 NewName = "__scoped_atomic_" #scoped; \
5053 CanFixIt = true; \
5054 break;
5055 HIP_ATOMIC_FIXABLE(load, load_n)
5056 HIP_ATOMIC_FIXABLE(store, store_n)
5057 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
5058 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
5059 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
5060 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
5061 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
5062 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
5063 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
5064 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
5065#undef HIP_ATOMIC_FIXABLE
5066 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5067 OldName = "__hip_atomic_compare_exchange_weak";
5068 NewName = "__scoped_atomic_compare_exchange";
5069 CanFixIt = false;
5070 break;
5071 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5072 OldName = "__hip_atomic_compare_exchange_strong";
5073 NewName = "__scoped_atomic_compare_exchange";
5074 CanFixIt = false;
5075 break;
5076 default:
5077 llvm_unreachable("unhandled HIP atomic op");
5078 }
5079
5080 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
5081 << OldName << NewName;
5082 if (!CanFixIt)
5083 return;
5084
5085 DB << FixItHint::CreateReplacement(ExprRange, NewName);
5086
5087 Expr *Scope = Args[Args.size() - 1];
5088 std::optional<llvm::APSInt> ScopeVal =
5089 Scope->getIntegerConstantExpr(S.Context);
5090 if (!ScopeVal)
5091 return;
5092
5093 StringRef ScopeName;
5094 switch (ScopeVal->getZExtValue()) {
5096 ScopeName = "__MEMORY_SCOPE_SINGLE";
5097 break;
5099 ScopeName = "__MEMORY_SCOPE_WVFRNT";
5100 break;
5102 ScopeName = "__MEMORY_SCOPE_WRKGRP";
5103 break;
5105 ScopeName = "__MEMORY_SCOPE_DEVICE";
5106 break;
5108 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5109 break;
5111 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5112 break;
5113 default:
5114 return;
5115 }
5116
5118 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
5119}
5120
5122 SourceLocation RParenLoc, MultiExprArg Args,
5124 AtomicArgumentOrder ArgOrder) {
5125 // All the non-OpenCL operations take one of the following forms.
5126 // The OpenCL operations take the __c11 forms with one extra argument for
5127 // synchronization scope.
5128 enum {
5129 // C __c11_atomic_init(A *, C)
5130 Init,
5131
5132 // C __c11_atomic_load(A *, int)
5133 Load,
5134
5135 // void __atomic_load(A *, CP, int)
5136 LoadCopy,
5137
5138 // void __atomic_store(A *, CP, int)
5139 Copy,
5140
5141 // C __c11_atomic_add(A *, M, int)
5142 Arithmetic,
5143
5144 // C __atomic_exchange_n(A *, CP, int)
5145 Xchg,
5146
5147 // void __atomic_exchange(A *, C *, CP, int)
5148 GNUXchg,
5149
5150 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5151 C11CmpXchg,
5152
5153 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5154 GNUCmpXchg,
5155
5156 // bool __atomic_test_and_set(A *, int)
5157 TestAndSetByte,
5158
5159 // void __atomic_clear(A *, int)
5160 ClearByte,
5161 } Form = Init;
5162
5163 const unsigned NumForm = ClearByte + 1;
5164 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5165 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5166 // where:
5167 // C is an appropriate type,
5168 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5169 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5170 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5171 // the int parameters are for orderings.
5172
5173 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5174 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5175 "need to update code for modified forms");
5176 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5177 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5178 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5179 "need to update code for modified C11 atomics");
5180 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5181 Op <= AtomicExpr::AO__opencl_atomic_store;
5182 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5183 Op <= AtomicExpr::AO__hip_atomic_store;
5184 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5185 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5186 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5187 Op <= AtomicExpr::AO__c11_atomic_store) ||
5188 IsOpenCL;
5189 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5190 Op == AtomicExpr::AO__atomic_store_n ||
5191 Op == AtomicExpr::AO__atomic_exchange_n ||
5192 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5193 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5194 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5195 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5196 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5197 // Bit mask for extra allowed value types other than integers for atomic
5198 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5199 // allow floating point.
5200 enum ArithOpExtraValueType {
5201 AOEVT_None = 0,
5202 AOEVT_Pointer = 1,
5203 AOEVT_FP = 2,
5204 AOEVT_Int = 4,
5205 };
5206 unsigned ArithAllows = AOEVT_None;
5207
5208 switch (Op) {
5209 case AtomicExpr::AO__c11_atomic_init:
5210 case AtomicExpr::AO__opencl_atomic_init:
5211 Form = Init;
5212 break;
5213
5214 case AtomicExpr::AO__c11_atomic_load:
5215 case AtomicExpr::AO__opencl_atomic_load:
5216 case AtomicExpr::AO__hip_atomic_load:
5217 case AtomicExpr::AO__atomic_load_n:
5218 case AtomicExpr::AO__scoped_atomic_load_n:
5219 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5220 Form = Load;
5221 break;
5222
5223 case AtomicExpr::AO__atomic_load:
5224 case AtomicExpr::AO__scoped_atomic_load:
5225 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5226 Form = LoadCopy;
5227 break;
5228
5229 case AtomicExpr::AO__c11_atomic_store:
5230 case AtomicExpr::AO__opencl_atomic_store:
5231 case AtomicExpr::AO__hip_atomic_store:
5232 case AtomicExpr::AO__atomic_store:
5233 case AtomicExpr::AO__atomic_store_n:
5234 case AtomicExpr::AO__scoped_atomic_store:
5235 case AtomicExpr::AO__scoped_atomic_store_n:
5236 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5237 Form = Copy;
5238 break;
5239 case AtomicExpr::AO__atomic_fetch_add:
5240 case AtomicExpr::AO__atomic_fetch_sub:
5241 case AtomicExpr::AO__atomic_add_fetch:
5242 case AtomicExpr::AO__atomic_sub_fetch:
5243 case AtomicExpr::AO__scoped_atomic_fetch_add:
5244 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5245 case AtomicExpr::AO__scoped_atomic_add_fetch:
5246 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5247 case AtomicExpr::AO__c11_atomic_fetch_add:
5248 case AtomicExpr::AO__c11_atomic_fetch_sub:
5249 case AtomicExpr::AO__opencl_atomic_fetch_add:
5250 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5251 case AtomicExpr::AO__hip_atomic_fetch_add:
5252 case AtomicExpr::AO__hip_atomic_fetch_sub:
5253 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5254 Form = Arithmetic;
5255 break;
5256 case AtomicExpr::AO__atomic_fetch_fminimum:
5257 case AtomicExpr::AO__atomic_fetch_fmaximum:
5258 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5259 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5260 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5261 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5262 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5263 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5264 ArithAllows = AOEVT_FP;
5265 Form = Arithmetic;
5266 break;
5267 case AtomicExpr::AO__atomic_fetch_max:
5268 case AtomicExpr::AO__atomic_fetch_min:
5269 case AtomicExpr::AO__atomic_max_fetch:
5270 case AtomicExpr::AO__atomic_min_fetch:
5271 case AtomicExpr::AO__scoped_atomic_fetch_max:
5272 case AtomicExpr::AO__scoped_atomic_fetch_min:
5273 case AtomicExpr::AO__scoped_atomic_max_fetch:
5274 case AtomicExpr::AO__scoped_atomic_min_fetch:
5275 case AtomicExpr::AO__c11_atomic_fetch_max:
5276 case AtomicExpr::AO__c11_atomic_fetch_min:
5277 case AtomicExpr::AO__opencl_atomic_fetch_max:
5278 case AtomicExpr::AO__opencl_atomic_fetch_min:
5279 case AtomicExpr::AO__hip_atomic_fetch_max:
5280 case AtomicExpr::AO__hip_atomic_fetch_min:
5281 ArithAllows = AOEVT_Int | AOEVT_FP;
5282 Form = Arithmetic;
5283 break;
5284 case AtomicExpr::AO__c11_atomic_fetch_and:
5285 case AtomicExpr::AO__c11_atomic_fetch_or:
5286 case AtomicExpr::AO__c11_atomic_fetch_xor:
5287 case AtomicExpr::AO__hip_atomic_fetch_and:
5288 case AtomicExpr::AO__hip_atomic_fetch_or:
5289 case AtomicExpr::AO__hip_atomic_fetch_xor:
5290 case AtomicExpr::AO__c11_atomic_fetch_nand:
5291 case AtomicExpr::AO__opencl_atomic_fetch_and:
5292 case AtomicExpr::AO__opencl_atomic_fetch_or:
5293 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5294 case AtomicExpr::AO__atomic_fetch_and:
5295 case AtomicExpr::AO__atomic_fetch_or:
5296 case AtomicExpr::AO__atomic_fetch_xor:
5297 case AtomicExpr::AO__atomic_fetch_nand:
5298 case AtomicExpr::AO__atomic_and_fetch:
5299 case AtomicExpr::AO__atomic_or_fetch:
5300 case AtomicExpr::AO__atomic_xor_fetch:
5301 case AtomicExpr::AO__atomic_nand_fetch:
5302 case AtomicExpr::AO__atomic_fetch_uinc:
5303 case AtomicExpr::AO__atomic_fetch_udec:
5304 case AtomicExpr::AO__scoped_atomic_fetch_and:
5305 case AtomicExpr::AO__scoped_atomic_fetch_or:
5306 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5307 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5308 case AtomicExpr::AO__scoped_atomic_and_fetch:
5309 case AtomicExpr::AO__scoped_atomic_or_fetch:
5310 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5311 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5312 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5313 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5314 Form = Arithmetic;
5315 break;
5316
5317 case AtomicExpr::AO__c11_atomic_exchange:
5318 case AtomicExpr::AO__hip_atomic_exchange:
5319 case AtomicExpr::AO__opencl_atomic_exchange:
5320 case AtomicExpr::AO__atomic_exchange_n:
5321 case AtomicExpr::AO__scoped_atomic_exchange_n:
5322 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5323 Form = Xchg;
5324 break;
5325
5326 case AtomicExpr::AO__atomic_exchange:
5327 case AtomicExpr::AO__scoped_atomic_exchange:
5328 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5329 Form = GNUXchg;
5330 break;
5331
5332 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5333 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5334 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5335 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5336 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5337 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5338 Form = C11CmpXchg;
5339 break;
5340
5341 case AtomicExpr::AO__atomic_compare_exchange:
5342 case AtomicExpr::AO__atomic_compare_exchange_n:
5343 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5344 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5345 ArithAllows = AOEVT_Pointer;
5346 Form = GNUCmpXchg;
5347 break;
5348
5349 case AtomicExpr::AO__atomic_test_and_set:
5350 Form = TestAndSetByte;
5351 break;
5352
5353 case AtomicExpr::AO__atomic_clear:
5354 Form = ClearByte;
5355 break;
5356 }
5357
5358 unsigned AdjustedNumArgs = NumArgs[Form];
5359 if ((IsOpenCL || IsHIP || IsScoped) &&
5360 Op != AtomicExpr::AO__opencl_atomic_init)
5361 ++AdjustedNumArgs;
5362 // Check we have the right number of arguments.
5363 if (Args.size() < AdjustedNumArgs) {
5364 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5365 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5366 << /*is non object*/ 0 << ExprRange;
5367 return ExprError();
5368 } else if (Args.size() > AdjustedNumArgs) {
5369 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5370 diag::err_typecheck_call_too_many_args)
5371 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5372 << /*is non object*/ 0 << ExprRange;
5373 return ExprError();
5374 }
5375
5376 // Inspect the first argument of the atomic operation.
5377 Expr *Ptr = Args[0];
5379 if (ConvertedPtr.isInvalid())
5380 return ExprError();
5381
5382 Ptr = ConvertedPtr.get();
5383 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5384 if (!pointerType) {
5385 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5386 << Ptr->getType() << 0 << Ptr->getSourceRange();
5387 return ExprError();
5388 }
5389
5390 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5391 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5392 QualType ValType = AtomTy; // 'C'
5393 if (IsC11) {
5394 if (!AtomTy->isAtomicType()) {
5395 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5396 << Ptr->getType() << Ptr->getSourceRange();
5397 return ExprError();
5398 }
5399 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5401 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5402 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5403 << Ptr->getSourceRange();
5404 return ExprError();
5405 }
5406 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5407 } else if (Form != Load && Form != LoadCopy) {
5408 if (ValType.isConstQualified()) {
5409 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5410 << Ptr->getType() << Ptr->getSourceRange();
5411 return ExprError();
5412 }
5413 }
5414
5415 if (Form != TestAndSetByte && Form != ClearByte) {
5416 // Pointer to object of size zero is not allowed.
5417 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5418 diag::err_incomplete_type))
5419 return ExprError();
5420
5421 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5422 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5423 << Ptr->getType() << 1 << Ptr->getSourceRange();
5424 return ExprError();
5425 }
5426 } else {
5427 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5428 // non-const pointer type, including void* and pointers to incomplete
5429 // structs, but only access the first byte.
5430 AtomTy = Context.CharTy;
5431 AtomTy = AtomTy.withCVRQualifiers(
5432 pointerType->getPointeeType().getCVRQualifiers());
5433 QualType PointerQT = Context.getPointerType(AtomTy);
5434 pointerType = PointerQT->getAs<PointerType>();
5435 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5436 ValType = AtomTy;
5437 }
5438
5439 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5440 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5441 Diag(ExprRange.getBegin(),
5442 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5443 << 0 << Ptr->getType() << Ptr->getSourceRange();
5444 return ExprError();
5445 }
5446
5447 // For an arithmetic operation, the implied arithmetic must be well-formed.
5448 // For _n operations, the value type must also be a valid atomic type.
5449 if (Form == Arithmetic || IsN) {
5450 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5451 // trivial type errors.
5452 auto IsAllowedValueType = [&](QualType ValType,
5453 unsigned AllowedType) -> bool {
5454 bool IsX87LongDouble =
5455 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5456 &Context.getTargetInfo().getLongDoubleFormat() ==
5457 &llvm::APFloat::x87DoubleExtended();
5458 if (ValType->isIntegerType())
5459 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5460 // integers. Explicit AOEVT_Int or other combinations allow integers.
5461 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5462 if (ValType->isPointerType())
5463 return AllowedType & AOEVT_Pointer;
5464 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5465 return false;
5466 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5467 if (IsX87LongDouble)
5468 return false;
5469 return true;
5470 };
5471 if (!IsAllowedValueType(ValType, ArithAllows)) {
5472 auto DID =
5473 ArithAllows == AOEVT_FP
5474 ? diag::err_atomic_op_needs_atomic_fp
5475 : (ArithAllows & AOEVT_FP
5476 ? (ArithAllows & AOEVT_Pointer
5477 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5478 : diag::err_atomic_op_needs_atomic_int_or_fp)
5479 : (ArithAllows & AOEVT_Pointer
5480 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5481 : diag::err_atomic_op_needs_atomic_int));
5482 Diag(ExprRange.getBegin(), DID)
5483 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5484 return ExprError();
5485 }
5486 if (IsC11 && ValType->isPointerType() &&
5487 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5488 diag::err_incomplete_type)) {
5489 return ExprError();
5490 }
5491 }
5492
5493 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5494 !AtomTy->isScalarType()) {
5495 // For GNU atomics, require a trivially-copyable type. This is not part of
5496 // the GNU atomics specification but we enforce it for consistency with
5497 // other atomics which generally all require a trivially-copyable type. This
5498 // is because atomics just copy bits.
5499 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5500 << Ptr->getType() << Ptr->getSourceRange();
5501 return ExprError();
5502 }
5503
5504 switch (ValType.getObjCLifetime()) {
5507 // okay
5508 break;
5509
5513 // FIXME: Can this happen? By this point, ValType should be known
5514 // to be trivially copyable.
5515 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5516 << ValType << Ptr->getSourceRange();
5517 return ExprError();
5518 }
5519
5520 // All atomic operations have an overload which takes a pointer to a volatile
5521 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5522 // into the result or the other operands. Similarly atomic_load takes a
5523 // pointer to a const 'A'.
5524 ValType.removeLocalVolatile();
5525 ValType.removeLocalConst();
5526 QualType ResultType = ValType;
5527 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5528 Form == ClearByte)
5529 ResultType = Context.VoidTy;
5530 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5531 ResultType = Context.BoolTy;
5532
5533 // The type of a parameter passed 'by value'. In the GNU atomics, such
5534 // arguments are actually passed as pointers.
5535 QualType ByValType = ValType; // 'CP'
5536 bool IsPassedByAddress = false;
5537 if (!IsC11 && !IsHIP && !IsN) {
5538 ByValType = Ptr->getType();
5539 IsPassedByAddress = true;
5540 }
5541
5542 SmallVector<Expr *, 5> APIOrderedArgs;
5543 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5544 APIOrderedArgs.push_back(Args[0]);
5545 switch (Form) {
5546 case Init:
5547 case Load:
5548 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5549 break;
5550 case LoadCopy:
5551 case Copy:
5552 case Arithmetic:
5553 case Xchg:
5554 APIOrderedArgs.push_back(Args[2]); // Val1
5555 APIOrderedArgs.push_back(Args[1]); // Order
5556 break;
5557 case GNUXchg:
5558 APIOrderedArgs.push_back(Args[2]); // Val1
5559 APIOrderedArgs.push_back(Args[3]); // Val2
5560 APIOrderedArgs.push_back(Args[1]); // Order
5561 break;
5562 case C11CmpXchg:
5563 APIOrderedArgs.push_back(Args[2]); // Val1
5564 APIOrderedArgs.push_back(Args[4]); // Val2
5565 APIOrderedArgs.push_back(Args[1]); // Order
5566 APIOrderedArgs.push_back(Args[3]); // OrderFail
5567 break;
5568 case GNUCmpXchg:
5569 APIOrderedArgs.push_back(Args[2]); // Val1
5570 APIOrderedArgs.push_back(Args[4]); // Val2
5571 APIOrderedArgs.push_back(Args[5]); // Weak
5572 APIOrderedArgs.push_back(Args[1]); // Order
5573 APIOrderedArgs.push_back(Args[3]); // OrderFail
5574 break;
5575 case TestAndSetByte:
5576 case ClearByte:
5577 APIOrderedArgs.push_back(Args[1]); // Order
5578 break;
5579 }
5580 } else
5581 APIOrderedArgs.append(Args.begin(), Args.end());
5582
5583 // The first argument's non-CV pointer type is used to deduce the type of
5584 // subsequent arguments, except for:
5585 // - weak flag (always converted to bool)
5586 // - memory order (always converted to int)
5587 // - scope (always converted to int)
5588 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5589 QualType Ty;
5590 if (i < NumVals[Form] + 1) {
5591 switch (i) {
5592 case 0:
5593 // The first argument is always a pointer. It has a fixed type.
5594 // It is always dereferenced, a nullptr is undefined.
5595 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5596 // Nothing else to do: we already know all we want about this pointer.
5597 continue;
5598 case 1:
5599 // The second argument is the non-atomic operand. For arithmetic, this
5600 // is always passed by value, and for a compare_exchange it is always
5601 // passed by address. For the rest, GNU uses by-address and C11 uses
5602 // by-value.
5603 assert(Form != Load);
5604 if (Form == Arithmetic && ValType->isPointerType())
5605 Ty = Context.getPointerDiffType();
5606 else if (Form == Init || Form == Arithmetic)
5607 Ty = ValType;
5608 else if (Form == Copy || Form == Xchg) {
5609 if (IsPassedByAddress) {
5610 // The value pointer is always dereferenced, a nullptr is undefined.
5611 CheckNonNullArgument(*this, APIOrderedArgs[i],
5612 ExprRange.getBegin());
5613 }
5614 Ty = ByValType;
5615 } else {
5616 Expr *ValArg = APIOrderedArgs[i];
5617 // The value pointer is always dereferenced, a nullptr is undefined.
5618 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5620 // Keep address space of non-atomic pointer type.
5621 if (const PointerType *PtrTy =
5622 ValArg->getType()->getAs<PointerType>()) {
5623 AS = PtrTy->getPointeeType().getAddressSpace();
5624 }
5625 Ty = Context.getPointerType(
5626 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5627 }
5628 break;
5629 case 2:
5630 // The third argument to compare_exchange / GNU exchange is the desired
5631 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5632 if (IsPassedByAddress)
5633 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5634 Ty = ByValType;
5635 break;
5636 case 3:
5637 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5638 Ty = Context.BoolTy;
5639 break;
5640 }
5641 } else {
5642 // The order(s) and scope are always converted to int.
5643 Ty = Context.IntTy;
5644 }
5645
5646 InitializedEntity Entity =
5648 ExprResult Arg = APIOrderedArgs[i];
5649 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5650 if (Arg.isInvalid())
5651 return true;
5652 APIOrderedArgs[i] = Arg.get();
5653 }
5654
5655 // Permute the arguments into a 'consistent' order.
5656 SmallVector<Expr*, 5> SubExprs;
5657 SubExprs.push_back(Ptr);
5658 switch (Form) {
5659 case Init:
5660 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5661 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5662 break;
5663 case Load:
5664 case TestAndSetByte:
5665 case ClearByte:
5666 SubExprs.push_back(APIOrderedArgs[1]); // Order
5667 break;
5668 case LoadCopy:
5669 case Copy:
5670 case Arithmetic:
5671 case Xchg:
5672 SubExprs.push_back(APIOrderedArgs[2]); // Order
5673 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5674 break;
5675 case GNUXchg:
5676 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5677 SubExprs.push_back(APIOrderedArgs[3]); // Order
5678 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5679 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5680 break;
5681 case C11CmpXchg:
5682 SubExprs.push_back(APIOrderedArgs[3]); // Order
5683 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5684 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5685 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5686 break;
5687 case GNUCmpXchg:
5688 SubExprs.push_back(APIOrderedArgs[4]); // Order
5689 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5690 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5691 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5692 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5693 break;
5694 }
5695
5696 // If the memory orders are constants, check they are valid.
5697 if (SubExprs.size() >= 2 && Form != Init) {
5698 std::optional<llvm::APSInt> Success =
5699 SubExprs[1]->getIntegerConstantExpr(Context);
5700 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5701 Diag(SubExprs[1]->getBeginLoc(),
5702 diag::warn_atomic_op_has_invalid_memory_order)
5703 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5704 << SubExprs[1]->getSourceRange();
5705 }
5706 if (SubExprs.size() >= 5) {
5707 if (std::optional<llvm::APSInt> Failure =
5708 SubExprs[3]->getIntegerConstantExpr(Context)) {
5709 if (!llvm::is_contained(
5710 {llvm::AtomicOrderingCABI::relaxed,
5711 llvm::AtomicOrderingCABI::consume,
5712 llvm::AtomicOrderingCABI::acquire,
5713 llvm::AtomicOrderingCABI::seq_cst},
5714 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5715 Diag(SubExprs[3]->getBeginLoc(),
5716 diag::warn_atomic_op_has_invalid_memory_order)
5717 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5718 }
5719 }
5720 }
5721 }
5722
5723 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5724 auto *Scope = Args[Args.size() - 1];
5725 if (std::optional<llvm::APSInt> Result =
5726 Scope->getIntegerConstantExpr(Context)) {
5727 if (!ScopeModel->isValid(Result->getZExtValue()))
5728 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5729 << Scope->getSourceRange();
5730 }
5731 SubExprs.push_back(Scope);
5732 }
5733
5734 if (IsHIP)
5735 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5736
5737 AtomicExpr *AE = new (Context)
5738 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5739
5740 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5741 Op == AtomicExpr::AO__c11_atomic_store ||
5742 Op == AtomicExpr::AO__opencl_atomic_load ||
5743 Op == AtomicExpr::AO__hip_atomic_load ||
5744 Op == AtomicExpr::AO__opencl_atomic_store ||
5745 Op == AtomicExpr::AO__hip_atomic_store) &&
5746 Context.AtomicUsesUnsupportedLibcall(AE))
5747 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5748 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5749 Op == AtomicExpr::AO__opencl_atomic_load ||
5750 Op == AtomicExpr::AO__hip_atomic_load)
5751 ? 0
5752 : 1);
5753
5754 if (ValType->isBitIntType()) {
5755 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5756 return ExprError();
5757 }
5758
5759 return AE;
5760}
5761
5762/// checkBuiltinArgument - Given a call to a builtin function, perform
5763/// normal type-checking on the given argument, updating the call in
5764/// place. This is useful when a builtin function requires custom
5765/// type-checking for some of its arguments but not necessarily all of
5766/// them.
5767///
5768/// Returns true on error.
5769static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5770 FunctionDecl *Fn = E->getDirectCallee();
5771 assert(Fn && "builtin call without direct callee!");
5772
5773 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5774 InitializedEntity Entity =
5776
5777 ExprResult Arg = E->getArg(ArgIndex);
5778 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5779 if (Arg.isInvalid())
5780 return true;
5781
5782 E->setArg(ArgIndex, Arg.get());
5783 return false;
5784}
5785
5786ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5787 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5788 Expr *Callee = TheCall->getCallee();
5789 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5790 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5791
5792 // Ensure that we have at least one argument to do type inference from.
5793 if (TheCall->getNumArgs() < 1) {
5794 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5795 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5796 << Callee->getSourceRange();
5797 return ExprError();
5798 }
5799
5800 // Inspect the first argument of the atomic builtin. This should always be
5801 // a pointer type, whose element is an integral scalar or pointer type.
5802 // Because it is a pointer type, we don't have to worry about any implicit
5803 // casts here.
5804 // FIXME: We don't allow floating point scalars as input.
5805 Expr *FirstArg = TheCall->getArg(0);
5806 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5807 if (FirstArgResult.isInvalid())
5808 return ExprError();
5809 FirstArg = FirstArgResult.get();
5810 TheCall->setArg(0, FirstArg);
5811
5812 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5813 if (!pointerType) {
5814 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5815 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5816 return ExprError();
5817 }
5818
5819 QualType ValType = pointerType->getPointeeType();
5820 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5821 !ValType->isBlockPointerType()) {
5822 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5823 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5824 return ExprError();
5825 }
5826 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5827 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5828 Diag(FirstArg->getBeginLoc(),
5829 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5830 << 1 << ValType << FirstArg->getSourceRange();
5831 return ExprError();
5832 }
5833
5834 if (ValType.isConstQualified()) {
5835 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5836 << FirstArg->getType() << FirstArg->getSourceRange();
5837 return ExprError();
5838 }
5839
5840 switch (ValType.getObjCLifetime()) {
5843 // okay
5844 break;
5845
5849 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5850 << ValType << FirstArg->getSourceRange();
5851
5852 return ExprError();
5853 }
5854
5855 // Strip any qualifiers off ValType.
5856 ValType = ValType.getUnqualifiedType();
5857
5858 // The majority of builtins return a value, but a few have special return
5859 // types, so allow them to override appropriately below.
5860 QualType ResultType = ValType;
5861
5862 // We need to figure out which concrete builtin this maps onto. For example,
5863 // __sync_fetch_and_add with a 2 byte object turns into
5864 // __sync_fetch_and_add_2.
5865#define BUILTIN_ROW(x) \
5866 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5867 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5868
5869 static const unsigned BuiltinIndices[][5] = {
5870 BUILTIN_ROW(__sync_fetch_and_add),
5871 BUILTIN_ROW(__sync_fetch_and_sub),
5872 BUILTIN_ROW(__sync_fetch_and_or),
5873 BUILTIN_ROW(__sync_fetch_and_and),
5874 BUILTIN_ROW(__sync_fetch_and_xor),
5875 BUILTIN_ROW(__sync_fetch_and_nand),
5876
5877 BUILTIN_ROW(__sync_add_and_fetch),
5878 BUILTIN_ROW(__sync_sub_and_fetch),
5879 BUILTIN_ROW(__sync_and_and_fetch),
5880 BUILTIN_ROW(__sync_or_and_fetch),
5881 BUILTIN_ROW(__sync_xor_and_fetch),
5882 BUILTIN_ROW(__sync_nand_and_fetch),
5883
5884 BUILTIN_ROW(__sync_val_compare_and_swap),
5885 BUILTIN_ROW(__sync_bool_compare_and_swap),
5886 BUILTIN_ROW(__sync_lock_test_and_set),
5887 BUILTIN_ROW(__sync_lock_release),
5888 BUILTIN_ROW(__sync_swap)
5889 };
5890#undef BUILTIN_ROW
5891
5892 // Determine the index of the size.
5893 unsigned SizeIndex;
5894 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5895 case 1: SizeIndex = 0; break;
5896 case 2: SizeIndex = 1; break;
5897 case 4: SizeIndex = 2; break;
5898 case 8: SizeIndex = 3; break;
5899 case 16: SizeIndex = 4; break;
5900 default:
5901 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5902 << FirstArg->getType() << FirstArg->getSourceRange();
5903 return ExprError();
5904 }
5905
5906 // Each of these builtins has one pointer argument, followed by some number of
5907 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5908 // that we ignore. Find out which row of BuiltinIndices to read from as well
5909 // as the number of fixed args.
5910 unsigned BuiltinID = FDecl->getBuiltinID();
5911 unsigned BuiltinIndex, NumFixed = 1;
5912 bool WarnAboutSemanticsChange = false;
5913 switch (BuiltinID) {
5914 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5915 case Builtin::BI__sync_fetch_and_add:
5916 case Builtin::BI__sync_fetch_and_add_1:
5917 case Builtin::BI__sync_fetch_and_add_2:
5918 case Builtin::BI__sync_fetch_and_add_4:
5919 case Builtin::BI__sync_fetch_and_add_8:
5920 case Builtin::BI__sync_fetch_and_add_16:
5921 BuiltinIndex = 0;
5922 break;
5923
5924 case Builtin::BI__sync_fetch_and_sub:
5925 case Builtin::BI__sync_fetch_and_sub_1:
5926 case Builtin::BI__sync_fetch_and_sub_2:
5927 case Builtin::BI__sync_fetch_and_sub_4:
5928 case Builtin::BI__sync_fetch_and_sub_8:
5929 case Builtin::BI__sync_fetch_and_sub_16:
5930 BuiltinIndex = 1;
5931 break;
5932
5933 case Builtin::BI__sync_fetch_and_or:
5934 case Builtin::BI__sync_fetch_and_or_1:
5935 case Builtin::BI__sync_fetch_and_or_2:
5936 case Builtin::BI__sync_fetch_and_or_4:
5937 case Builtin::BI__sync_fetch_and_or_8:
5938 case Builtin::BI__sync_fetch_and_or_16:
5939 BuiltinIndex = 2;
5940 break;
5941
5942 case Builtin::BI__sync_fetch_and_and:
5943 case Builtin::BI__sync_fetch_and_and_1:
5944 case Builtin::BI__sync_fetch_and_and_2:
5945 case Builtin::BI__sync_fetch_and_and_4:
5946 case Builtin::BI__sync_fetch_and_and_8:
5947 case Builtin::BI__sync_fetch_and_and_16:
5948 BuiltinIndex = 3;
5949 break;
5950
5951 case Builtin::BI__sync_fetch_and_xor:
5952 case Builtin::BI__sync_fetch_and_xor_1:
5953 case Builtin::BI__sync_fetch_and_xor_2:
5954 case Builtin::BI__sync_fetch_and_xor_4:
5955 case Builtin::BI__sync_fetch_and_xor_8:
5956 case Builtin::BI__sync_fetch_and_xor_16:
5957 BuiltinIndex = 4;
5958 break;
5959
5960 case Builtin::BI__sync_fetch_and_nand:
5961 case Builtin::BI__sync_fetch_and_nand_1:
5962 case Builtin::BI__sync_fetch_and_nand_2:
5963 case Builtin::BI__sync_fetch_and_nand_4:
5964 case Builtin::BI__sync_fetch_and_nand_8:
5965 case Builtin::BI__sync_fetch_and_nand_16:
5966 BuiltinIndex = 5;
5967 WarnAboutSemanticsChange = true;
5968 break;
5969
5970 case Builtin::BI__sync_add_and_fetch:
5971 case Builtin::BI__sync_add_and_fetch_1:
5972 case Builtin::BI__sync_add_and_fetch_2:
5973 case Builtin::BI__sync_add_and_fetch_4:
5974 case Builtin::BI__sync_add_and_fetch_8:
5975 case Builtin::BI__sync_add_and_fetch_16:
5976 BuiltinIndex = 6;
5977 break;
5978
5979 case Builtin::BI__sync_sub_and_fetch:
5980 case Builtin::BI__sync_sub_and_fetch_1:
5981 case Builtin::BI__sync_sub_and_fetch_2:
5982 case Builtin::BI__sync_sub_and_fetch_4:
5983 case Builtin::BI__sync_sub_and_fetch_8:
5984 case Builtin::BI__sync_sub_and_fetch_16:
5985 BuiltinIndex = 7;
5986 break;
5987
5988 case Builtin::BI__sync_and_and_fetch:
5989 case Builtin::BI__sync_and_and_fetch_1:
5990 case Builtin::BI__sync_and_and_fetch_2:
5991 case Builtin::BI__sync_and_and_fetch_4:
5992 case Builtin::BI__sync_and_and_fetch_8:
5993 case Builtin::BI__sync_and_and_fetch_16:
5994 BuiltinIndex = 8;
5995 break;
5996
5997 case Builtin::BI__sync_or_and_fetch:
5998 case Builtin::BI__sync_or_and_fetch_1:
5999 case Builtin::BI__sync_or_and_fetch_2:
6000 case Builtin::BI__sync_or_and_fetch_4:
6001 case Builtin::BI__sync_or_and_fetch_8:
6002 case Builtin::BI__sync_or_and_fetch_16:
6003 BuiltinIndex = 9;
6004 break;
6005
6006 case Builtin::BI__sync_xor_and_fetch:
6007 case Builtin::BI__sync_xor_and_fetch_1:
6008 case Builtin::BI__sync_xor_and_fetch_2:
6009 case Builtin::BI__sync_xor_and_fetch_4:
6010 case Builtin::BI__sync_xor_and_fetch_8:
6011 case Builtin::BI__sync_xor_and_fetch_16:
6012 BuiltinIndex = 10;
6013 break;
6014
6015 case Builtin::BI__sync_nand_and_fetch:
6016 case Builtin::BI__sync_nand_and_fetch_1:
6017 case Builtin::BI__sync_nand_and_fetch_2:
6018 case Builtin::BI__sync_nand_and_fetch_4:
6019 case Builtin::BI__sync_nand_and_fetch_8:
6020 case Builtin::BI__sync_nand_and_fetch_16:
6021 BuiltinIndex = 11;
6022 WarnAboutSemanticsChange = true;
6023 break;
6024
6025 case Builtin::BI__sync_val_compare_and_swap:
6026 case Builtin::BI__sync_val_compare_and_swap_1:
6027 case Builtin::BI__sync_val_compare_and_swap_2:
6028 case Builtin::BI__sync_val_compare_and_swap_4:
6029 case Builtin::BI__sync_val_compare_and_swap_8:
6030 case Builtin::BI__sync_val_compare_and_swap_16:
6031 BuiltinIndex = 12;
6032 NumFixed = 2;
6033 break;
6034
6035 case Builtin::BI__sync_bool_compare_and_swap:
6036 case Builtin::BI__sync_bool_compare_and_swap_1:
6037 case Builtin::BI__sync_bool_compare_and_swap_2:
6038 case Builtin::BI__sync_bool_compare_and_swap_4:
6039 case Builtin::BI__sync_bool_compare_and_swap_8:
6040 case Builtin::BI__sync_bool_compare_and_swap_16:
6041 BuiltinIndex = 13;
6042 NumFixed = 2;
6043 ResultType = Context.BoolTy;
6044 break;
6045
6046 case Builtin::BI__sync_lock_test_and_set:
6047 case Builtin::BI__sync_lock_test_and_set_1:
6048 case Builtin::BI__sync_lock_test_and_set_2:
6049 case Builtin::BI__sync_lock_test_and_set_4:
6050 case Builtin::BI__sync_lock_test_and_set_8:
6051 case Builtin::BI__sync_lock_test_and_set_16:
6052 BuiltinIndex = 14;
6053 break;
6054
6055 case Builtin::BI__sync_lock_release:
6056 case Builtin::BI__sync_lock_release_1:
6057 case Builtin::BI__sync_lock_release_2:
6058 case Builtin::BI__sync_lock_release_4:
6059 case Builtin::BI__sync_lock_release_8:
6060 case Builtin::BI__sync_lock_release_16:
6061 BuiltinIndex = 15;
6062 NumFixed = 0;
6063 ResultType = Context.VoidTy;
6064 break;
6065
6066 case Builtin::BI__sync_swap:
6067 case Builtin::BI__sync_swap_1:
6068 case Builtin::BI__sync_swap_2:
6069 case Builtin::BI__sync_swap_4:
6070 case Builtin::BI__sync_swap_8:
6071 case Builtin::BI__sync_swap_16:
6072 BuiltinIndex = 16;
6073 break;
6074 }
6075
6076 // Now that we know how many fixed arguments we expect, first check that we
6077 // have at least that many.
6078 if (TheCall->getNumArgs() < 1+NumFixed) {
6079 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6080 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
6081 << Callee->getSourceRange();
6082 return ExprError();
6083 }
6084
6085 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6086 << Callee->getSourceRange();
6087
6088 if (WarnAboutSemanticsChange) {
6089 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6090 << Callee->getSourceRange();
6091 }
6092
6093 // Get the decl for the concrete builtin from this, we can tell what the
6094 // concrete integer type we should convert to is.
6095 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6096 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6097 FunctionDecl *NewBuiltinDecl;
6098 if (NewBuiltinID == BuiltinID)
6099 NewBuiltinDecl = FDecl;
6100 else {
6101 // Perform builtin lookup to avoid redeclaring it.
6102 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6103 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6104 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6105 assert(Res.getFoundDecl());
6106 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6107 if (!NewBuiltinDecl)
6108 return ExprError();
6109 }
6110
6111 // The first argument --- the pointer --- has a fixed type; we
6112 // deduce the types of the rest of the arguments accordingly. Walk
6113 // the remaining arguments, converting them to the deduced value type.
6114 for (unsigned i = 0; i != NumFixed; ++i) {
6115 ExprResult Arg = TheCall->getArg(i+1);
6116
6117 // GCC does an implicit conversion to the pointer or integer ValType. This
6118 // can fail in some cases (1i -> int**), check for this error case now.
6119 // Initialize the argument.
6120 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6121 ValType, /*consume*/ false);
6122 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6123 if (Arg.isInvalid())
6124 return ExprError();
6125
6126 // Okay, we have something that *can* be converted to the right type. Check
6127 // to see if there is a potentially weird extension going on here. This can
6128 // happen when you do an atomic operation on something like an char* and
6129 // pass in 42. The 42 gets converted to char. This is even more strange
6130 // for things like 45.123 -> char, etc.
6131 // FIXME: Do this check.
6132 TheCall->setArg(i+1, Arg.get());
6133 }
6134
6135 // Create a new DeclRefExpr to refer to the new decl.
6136 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6137 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6138 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6139 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6140
6141 // Set the callee in the CallExpr.
6142 // FIXME: This loses syntactic information.
6143 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6144 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6145 CK_BuiltinFnToFnPtr);
6146 TheCall->setCallee(PromotedCall.get());
6147
6148 // Change the result type of the call to match the original value type. This
6149 // is arbitrary, but the codegen for these builtins ins design to handle it
6150 // gracefully.
6151 TheCall->setType(ResultType);
6152
6153 // Prohibit problematic uses of bit-precise integer types with atomic
6154 // builtins. The arguments would have already been converted to the first
6155 // argument's type, so only need to check the first argument.
6156 const auto *BitIntValType = ValType->getAs<BitIntType>();
6157 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6158 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6159 return ExprError();
6160 }
6161
6162 return TheCallResult;
6163}
6164
6165ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6166 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6167 DeclRefExpr *DRE =
6169 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6170 unsigned BuiltinID = FDecl->getBuiltinID();
6171 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6172 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6173 "Unexpected nontemporal load/store builtin!");
6174 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6175 unsigned numArgs = isStore ? 2 : 1;
6176
6177 // Ensure that we have the proper number of arguments.
6178 if (checkArgCount(TheCall, numArgs))
6179 return ExprError();
6180
6181 // Inspect the last argument of the nontemporal builtin. This should always
6182 // be a pointer type, from which we imply the type of the memory access.
6183 // Because it is a pointer type, we don't have to worry about any implicit
6184 // casts here.
6185 Expr *PointerArg = TheCall->getArg(numArgs - 1);
6186 ExprResult PointerArgResult =
6188
6189 if (PointerArgResult.isInvalid())
6190 return ExprError();
6191 PointerArg = PointerArgResult.get();
6192 TheCall->setArg(numArgs - 1, PointerArg);
6193
6194 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6195 if (!pointerType) {
6196 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6197 << PointerArg->getType() << PointerArg->getSourceRange();
6198 return ExprError();
6199 }
6200
6201 QualType ValType = pointerType->getPointeeType();
6202
6203 // Strip any qualifiers off ValType.
6204 ValType = ValType.getUnqualifiedType();
6205 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6206 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6207 !ValType->isVectorType()) {
6208 Diag(DRE->getBeginLoc(),
6209 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6210 << PointerArg->getType() << PointerArg->getSourceRange();
6211 return ExprError();
6212 }
6213
6214 if (!isStore) {
6215 TheCall->setType(ValType);
6216 return TheCallResult;
6217 }
6218
6219 ExprResult ValArg = TheCall->getArg(0);
6220 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6221 Context, ValType, /*consume*/ false);
6222 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6223 if (ValArg.isInvalid())
6224 return ExprError();
6225
6226 TheCall->setArg(0, ValArg.get());
6227 TheCall->setType(Context.VoidTy);
6228 return TheCallResult;
6229}
6230
6231/// CheckObjCString - Checks that the format string argument to the os_log()
6232/// and os_trace() functions is correct, and converts it to const char *.
6233ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6234 Arg = Arg->IgnoreParenCasts();
6235 auto *Literal = dyn_cast<StringLiteral>(Arg);
6236 if (!Literal) {
6237 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6238 Literal = ObjcLiteral->getString();
6239 }
6240 }
6241
6242 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6243 return ExprError(
6244 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6245 << Arg->getSourceRange());
6246 }
6247
6248 ExprResult Result(Literal);
6249 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6250 InitializedEntity Entity =
6252 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6253 return Result;
6254}
6255
6256/// Check that the user is calling the appropriate va_start builtin for the
6257/// target and calling convention.
6258static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6259 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6260 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6261 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6262 TT.getArch() == llvm::Triple::aarch64_32);
6263 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6264 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6265 if (IsX64 || IsAArch64) {
6266 CallingConv CC = CC_C;
6267 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6268 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6269 if (IsMSVAStart) {
6270 // Don't allow this in System V ABI functions.
6271 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6272 return S.Diag(Fn->getBeginLoc(),
6273 diag::err_ms_va_start_used_in_sysv_function);
6274 } else {
6275 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6276 // On x64 Windows, don't allow this in System V ABI functions.
6277 // (Yes, that means there's no corresponding way to support variadic
6278 // System V ABI functions on Windows.)
6279 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6280 (!IsWindowsOrUEFI && CC == CC_Win64))
6281 return S.Diag(Fn->getBeginLoc(),
6282 diag::err_va_start_used_in_wrong_abi_function)
6283 << !IsWindowsOrUEFI;
6284 }
6285 return false;
6286 }
6287
6288 if (IsMSVAStart)
6289 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6290 return false;
6291}
6292
6294 ParmVarDecl **LastParam = nullptr) {
6295 // Determine whether the current function, block, or obj-c method is variadic
6296 // and get its parameter list.
6297 bool IsVariadic = false;
6299 DeclContext *Caller =
6301 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6302 IsVariadic = Block->isVariadic();
6303 Params = Block->parameters();
6304 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6305 IsVariadic = FD->isVariadic();
6306 Params = FD->parameters();
6307 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6308 IsVariadic = MD->isVariadic();
6309 // FIXME: This isn't correct for methods (results in bogus warning).
6310 Params = MD->parameters();
6311 } else if (isa<CapturedDecl>(Caller)) {
6312 // We don't support va_start in a CapturedDecl.
6313 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6314 return true;
6315 } else {
6316 // This must be some other declcontext that parses exprs.
6317 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6318 return true;
6319 }
6320
6321 if (!IsVariadic) {
6322 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6323 return true;
6324 }
6325
6326 if (LastParam)
6327 *LastParam = Params.empty() ? nullptr : Params.back();
6328
6329 return false;
6330}
6331
6332bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6333 Expr *Fn = TheCall->getCallee();
6334 if (checkVAStartABI(*this, BuiltinID, Fn))
6335 return true;
6336
6337 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6338 // This builtin requires one argument (the va_list), allows two arguments,
6339 // but diagnoses more than two arguments. e.g.,
6340 // __builtin_c23_va_start(); // error
6341 // __builtin_c23_va_start(list); // ok
6342 // __builtin_c23_va_start(list, param); // ok
6343 // __builtin_c23_va_start(list, anything, anything); // error
6344 // This differs from the GCC behavior in that they accept the last case
6345 // with a warning, but it doesn't seem like a useful behavior to allow.
6346 if (checkArgCountRange(TheCall, 1, 2))
6347 return true;
6348 } else {
6349 // In C23 mode, va_start only needs one argument. However, the builtin still
6350 // requires two arguments (which matches the behavior of the GCC builtin),
6351 // <stdarg.h> passes `0` as the second argument in C23 mode.
6352 if (checkArgCount(TheCall, 2))
6353 return true;
6354 }
6355
6356 // Type-check the first argument normally.
6357 if (checkBuiltinArgument(*this, TheCall, 0))
6358 return true;
6359
6360 // Check that the current function is variadic, and get its last parameter.
6361 ParmVarDecl *LastParam;
6362 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6363 return true;
6364
6365 // Verify that the second argument to the builtin is the last non-variadic
6366 // argument of the current function or method. In C23 mode, if the call is
6367 // not to __builtin_c23_va_start, and the second argument is an integer
6368 // constant expression with value 0, then we don't bother with this check.
6369 // For __builtin_c23_va_start, we only perform the check for the second
6370 // argument being the last argument to the current function if there is a
6371 // second argument present.
6372 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6373 TheCall->getNumArgs() < 2) {
6374 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6375 return false;
6376 }
6377
6378 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6379 if (std::optional<llvm::APSInt> Val =
6381 Val && LangOpts.C23 && *Val == 0 &&
6382 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6383 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6384 return false;
6385 }
6386
6387 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6388 // next block.
6389 QualType Type;
6390 SourceLocation ParamLoc;
6391 bool IsCRegister = false;
6392 bool SecondArgIsLastNonVariadicArgument = false;
6393 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6394 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6395 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6396
6397 Type = PV->getType();
6398 ParamLoc = PV->getLocation();
6399 IsCRegister =
6400 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6401 }
6402 }
6403
6404 if (!SecondArgIsLastNonVariadicArgument)
6405 Diag(TheCall->getArg(1)->getBeginLoc(),
6406 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6407 else if (IsCRegister || Type->isReferenceType() ||
6408 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6409 // Promotable integers are UB, but enumerations need a bit of
6410 // extra checking to see what their promotable type actually is.
6411 if (!Context.isPromotableIntegerType(Type))
6412 return false;
6413 const auto *ED = Type->getAsEnumDecl();
6414 if (!ED)
6415 return true;
6416 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6417 }()) {
6418 unsigned Reason = 0;
6419 if (Type->isReferenceType()) Reason = 1;
6420 else if (IsCRegister) Reason = 2;
6421 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6422 Diag(ParamLoc, diag::note_parameter_type) << Type;
6423 }
6424
6425 return false;
6426}
6427
6428bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6429 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6430 const LangOptions &LO = getLangOpts();
6431
6432 if (LO.CPlusPlus)
6433 return Arg->getType()
6435 .getTypePtr()
6436 ->getPointeeType()
6438
6439 // In C, allow aliasing through `char *`, this is required for AArch64 at
6440 // least.
6441 return true;
6442 };
6443
6444 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6445 // const char *named_addr);
6446
6447 Expr *Func = Call->getCallee();
6448
6449 if (Call->getNumArgs() < 3)
6450 return Diag(Call->getEndLoc(),
6451 diag::err_typecheck_call_too_few_args_at_least)
6452 << 0 /*function call*/ << 3 << Call->getNumArgs()
6453 << /*is non object*/ 0;
6454
6455 // Type-check the first argument normally.
6456 if (checkBuiltinArgument(*this, Call, 0))
6457 return true;
6458
6459 // Check that the current function is variadic.
6461 return true;
6462
6463 // __va_start on Windows does not validate the parameter qualifiers
6464
6465 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6466 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6467
6468 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6469 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6470
6471 const QualType &ConstCharPtrTy =
6472 Context.getPointerType(Context.CharTy.withConst());
6473 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6474 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6475 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6476 << 0 /* qualifier difference */
6477 << 3 /* parameter mismatch */
6478 << 2 << Arg1->getType() << ConstCharPtrTy;
6479
6480 const QualType SizeTy = Context.getSizeType();
6481 if (!Context.hasSameType(
6483 SizeTy))
6484 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6485 << Arg2->getType() << SizeTy << 1 /* different class */
6486 << 0 /* qualifier difference */
6487 << 3 /* parameter mismatch */
6488 << 3 << Arg2->getType() << SizeTy;
6489
6490 return false;
6491}
6492
6493bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6494 if (checkArgCount(TheCall, 2))
6495 return true;
6496
6497 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6498 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6499 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6500 << 1 << 0 << TheCall->getSourceRange();
6501
6502 ExprResult OrigArg0 = TheCall->getArg(0);
6503 ExprResult OrigArg1 = TheCall->getArg(1);
6504
6505 // Do standard promotions between the two arguments, returning their common
6506 // type.
6507 QualType Res = UsualArithmeticConversions(
6508 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6509 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6510 return true;
6511
6512 // Make sure any conversions are pushed back into the call; this is
6513 // type safe since unordered compare builtins are declared as "_Bool
6514 // foo(...)".
6515 TheCall->setArg(0, OrigArg0.get());
6516 TheCall->setArg(1, OrigArg1.get());
6517
6518 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6519 return false;
6520
6521 // If the common type isn't a real floating type, then the arguments were
6522 // invalid for this operation.
6523 if (Res.isNull() || !Res->isRealFloatingType())
6524 return Diag(OrigArg0.get()->getBeginLoc(),
6525 diag::err_typecheck_call_invalid_ordered_compare)
6526 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6527 << SourceRange(OrigArg0.get()->getBeginLoc(),
6528 OrigArg1.get()->getEndLoc());
6529
6530 return false;
6531}
6532
6533bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6534 unsigned BuiltinID) {
6535 if (checkArgCount(TheCall, NumArgs))
6536 return true;
6537
6538 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6539 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6540 BuiltinID == Builtin::BI__builtin_isinf ||
6541 BuiltinID == Builtin::BI__builtin_isinf_sign))
6542 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6543 << 0 << 0 << TheCall->getSourceRange();
6544
6545 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6546 BuiltinID == Builtin::BI__builtin_isunordered))
6547 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6548 << 1 << 0 << TheCall->getSourceRange();
6549
6550 bool IsFPClass = NumArgs == 2;
6551
6552 // Find out position of floating-point argument.
6553 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6554
6555 // We can count on all parameters preceding the floating-point just being int.
6556 // Try all of those.
6557 for (unsigned i = 0; i < FPArgNo; ++i) {
6558 Expr *Arg = TheCall->getArg(i);
6559
6560 if (Arg->isTypeDependent())
6561 return false;
6562
6565
6566 if (Res.isInvalid())
6567 return true;
6568 TheCall->setArg(i, Res.get());
6569 }
6570
6571 Expr *OrigArg = TheCall->getArg(FPArgNo);
6572
6573 if (OrigArg->isTypeDependent())
6574 return false;
6575
6576 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6578 if (!Res.isUsable())
6579 return true;
6580 OrigArg = Res.get();
6581
6582 TheCall->setArg(FPArgNo, OrigArg);
6583
6584 QualType VectorResultTy;
6585 QualType ElementTy = OrigArg->getType();
6586 // TODO: When all classification function are implemented with is_fpclass,
6587 // vector argument can be supported in all of them.
6588 if (ElementTy->isVectorType() && IsFPClass) {
6589 VectorResultTy = GetSignedVectorType(ElementTy);
6590 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6591 }
6592
6593 // This operation requires a non-_Complex floating-point number.
6594 if (!ElementTy->isRealFloatingType())
6595 return Diag(OrigArg->getBeginLoc(),
6596 diag::err_typecheck_call_invalid_unary_fp)
6597 << OrigArg->getType() << OrigArg->getSourceRange();
6598
6599 // __builtin_isfpclass has integer parameter that specify test mask. It is
6600 // passed in (...), so it should be analyzed completely here.
6601 if (IsFPClass) {
6602 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6603 return true;
6604
6606 TheCall->getArg(NumArgs - 1), Context.IntTy, AssignmentAction::Passing);
6607 if (!MaskRes.isUsable())
6608 return true;
6609 TheCall->setArg(NumArgs - 1, MaskRes.get());
6610 }
6611
6612 // TODO: enable this code to all classification functions.
6613 if (IsFPClass) {
6614 QualType ResultTy;
6615 if (!VectorResultTy.isNull())
6616 ResultTy = VectorResultTy;
6617 else
6618 ResultTy = Context.IntTy;
6619 TheCall->setType(ResultTy);
6620 }
6621
6622 return false;
6623}
6624
6625bool Sema::BuiltinComplex(CallExpr *TheCall) {
6626 if (checkArgCount(TheCall, 2))
6627 return true;
6628
6629 bool Dependent = false;
6630 for (unsigned I = 0; I != 2; ++I) {
6631 Expr *Arg = TheCall->getArg(I);
6632 QualType T = Arg->getType();
6633 if (T->isDependentType()) {
6634 Dependent = true;
6635 continue;
6636 }
6637
6638 // Despite supporting _Complex int, GCC requires a real floating point type
6639 // for the operands of __builtin_complex.
6640 if (!T->isRealFloatingType()) {
6641 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6642 << Arg->getType() << Arg->getSourceRange();
6643 }
6644
6645 ExprResult Converted = DefaultLvalueConversion(Arg);
6646 if (Converted.isInvalid())
6647 return true;
6648 TheCall->setArg(I, Converted.get());
6649 }
6650
6651 if (Dependent) {
6652 TheCall->setType(Context.DependentTy);
6653 return false;
6654 }
6655
6656 Expr *Real = TheCall->getArg(0);
6657 Expr *Imag = TheCall->getArg(1);
6658 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6659 return Diag(Real->getBeginLoc(),
6660 diag::err_typecheck_call_different_arg_types)
6661 << Real->getType() << Imag->getType()
6662 << Real->getSourceRange() << Imag->getSourceRange();
6663 }
6664
6665 TheCall->setType(Context.getComplexType(Real->getType()));
6666 return false;
6667}
6668
6669/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6670// This is declared to take (...), so we have to check everything.
6672 unsigned NumArgs = TheCall->getNumArgs();
6673 if (NumArgs < 2)
6674 return ExprError(Diag(TheCall->getEndLoc(),
6675 diag::err_typecheck_call_too_few_args_at_least)
6676 << 0 /*function call*/ << 2 << NumArgs
6677 << /*is non object*/ 0 << TheCall->getSourceRange());
6678
6679 // Determine which of the following types of shufflevector we're checking:
6680 // 1) unary, vector mask: (lhs, mask)
6681 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6682 QualType ResType = TheCall->getArg(0)->getType();
6683 unsigned NumElements = 0;
6684
6685 if (!TheCall->getArg(0)->isTypeDependent() &&
6686 !TheCall->getArg(1)->isTypeDependent()) {
6687 QualType LHSType = TheCall->getArg(0)->getType();
6688 QualType RHSType = TheCall->getArg(1)->getType();
6689
6690 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6691 return ExprError(
6692 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6693 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6694 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6695 TheCall->getArg(1)->getEndLoc()));
6696
6697 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6698 unsigned NumResElements = NumArgs - 2;
6699
6700 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6701 // with mask. If so, verify that RHS is an integer vector type with the
6702 // same number of elts as lhs.
6703 if (NumArgs == 2) {
6704 auto *RHSVecType = RHSType->castAs<VectorType>();
6705 if (RHSVecType->getElementType()->isBooleanType() ||
6706 !RHSVecType->getElementType()->isIntegerType()) {
6707 return ExprError(
6708 Diag(TheCall->getBeginLoc(), diag::err_builtin_invalid_arg_type)
6709 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6710 << /*no fp*/ 0 << RHSType
6711 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6712 TheCall->getArg(1)->getEndLoc()));
6713 }
6714
6715 if (RHSVecType->getNumElements() != NumElements)
6716 return ExprError(Diag(TheCall->getBeginLoc(),
6717 diag::err_typecheck_vector_lengths_not_equal)
6718 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6719 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6720 TheCall->getArg(1)->getEndLoc()));
6721 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6722 return ExprError(Diag(TheCall->getBeginLoc(),
6723 diag::err_vec_builtin_incompatible_vector)
6724 << TheCall->getDirectCallee()
6725 << /*isMoreThanTwoArgs*/ false
6726 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6727 TheCall->getArg(1)->getEndLoc()));
6728 } else if (NumElements != NumResElements) {
6729 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6730 ResType = ResType->isExtVectorType()
6731 ? Context.getExtVectorType(EltType, NumResElements)
6732 : Context.getVectorType(EltType, NumResElements,
6734 }
6735 }
6736
6737 for (unsigned I = 2; I != NumArgs; ++I) {
6738 Expr *Arg = TheCall->getArg(I);
6739 if (Arg->isTypeDependent() || Arg->isValueDependent())
6740 continue;
6741
6742 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6743 if (!Result)
6744 return ExprError(Diag(TheCall->getBeginLoc(),
6745 diag::err_shufflevector_nonconstant_argument)
6746 << Arg->getSourceRange());
6747
6748 // Allow -1 which will be translated to undef in the IR.
6749 if (Result->isSigned() && Result->isAllOnes())
6750 ;
6751 else if (Result->getActiveBits() > 64 ||
6752 Result->getZExtValue() >= NumElements * 2)
6753 return ExprError(Diag(TheCall->getBeginLoc(),
6754 diag::err_shufflevector_argument_too_large)
6755 << Arg->getSourceRange());
6756
6757 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6758 }
6759
6760 auto *Result = new (Context) ShuffleVectorExpr(
6761 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6762 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6763
6764 // All moved to Result.
6765 TheCall->shrinkNumArgs(0);
6766 return Result;
6767}
6768
6770 SourceLocation BuiltinLoc,
6771 SourceLocation RParenLoc) {
6774 QualType DstTy = TInfo->getType();
6775 QualType SrcTy = E->getType();
6776
6777 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6778 return ExprError(Diag(BuiltinLoc,
6779 diag::err_convertvector_non_vector)
6780 << E->getSourceRange());
6781 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6782 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6783 << "second"
6784 << "__builtin_convertvector");
6785
6786 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6787 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6788 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6789 if (SrcElts != DstElts)
6790 return ExprError(Diag(BuiltinLoc,
6791 diag::err_convertvector_incompatible_vector)
6792 << E->getSourceRange());
6793 }
6794
6795 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6796 RParenLoc, CurFPFeatureOverrides());
6797}
6798
6799bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6800 unsigned NumArgs = TheCall->getNumArgs();
6801
6802 if (NumArgs > 3)
6803 return Diag(TheCall->getEndLoc(),
6804 diag::err_typecheck_call_too_many_args_at_most)
6805 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6806 << TheCall->getSourceRange();
6807
6808 // Argument 0 is checked for us and the remaining arguments must be
6809 // constant integers.
6810 for (unsigned i = 1; i != NumArgs; ++i) {
6811 if (convertArgumentToType(TheCall->getArgs()[i], Context.IntTy))
6812 return true;
6813 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6814 return true;
6815 }
6816
6817 return false;
6818}
6819
6820bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6821 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6822 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6823 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6824 if (checkArgCount(TheCall, 1))
6825 return true;
6826 Expr *Arg = TheCall->getArg(0);
6827 if (Arg->isInstantiationDependent())
6828 return false;
6829
6830 QualType ArgTy = Arg->getType();
6831 if (!ArgTy->hasFloatingRepresentation())
6832 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6833 << ArgTy;
6834 if (Arg->isLValue()) {
6835 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6836 TheCall->setArg(0, FirstArg.get());
6837 }
6838 TheCall->setType(TheCall->getArg(0)->getType());
6839 return false;
6840}
6841
6842bool Sema::BuiltinAssume(CallExpr *TheCall) {
6843 Expr *Arg = TheCall->getArg(0);
6844 if (Arg->isInstantiationDependent()) return false;
6845
6846 if (Arg->HasSideEffects(Context))
6847 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6848 << Arg->getSourceRange()
6849 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6850
6851 return false;
6852}
6853
6854bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6855 // The alignment must be a constant integer.
6856 Expr *Arg = TheCall->getArg(1);
6857
6858 // We can't check the value of a dependent argument.
6859 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6860 if (const auto *UE =
6861 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6862 if (UE->getKind() == UETT_AlignOf ||
6863 UE->getKind() == UETT_PreferredAlignOf)
6864 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6865 << Arg->getSourceRange();
6866
6867 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6868
6869 if (!Result.isPowerOf2())
6870 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6871 << Arg->getSourceRange();
6872
6873 if (Result < Context.getCharWidth())
6874 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6875 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6876
6877 if (Result > std::numeric_limits<int32_t>::max())
6878 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6879 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6880 }
6881
6882 return false;
6883}
6884
6885bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6886 if (checkArgCountRange(TheCall, 2, 3))
6887 return true;
6888
6889 unsigned NumArgs = TheCall->getNumArgs();
6890 Expr *FirstArg = TheCall->getArg(0);
6891
6892 {
6893 ExprResult FirstArgResult =
6895 if (!FirstArgResult.get()->getType()->isPointerType()) {
6896 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6897 << TheCall->getSourceRange();
6898 return true;
6899 }
6900 TheCall->setArg(0, FirstArgResult.get());
6901 }
6902
6903 // The alignment must be a constant integer.
6904 Expr *SecondArg = TheCall->getArg(1);
6905
6906 // We can't check the value of a dependent argument.
6907 if (!SecondArg->isValueDependent()) {
6908 llvm::APSInt Result;
6909 if (BuiltinConstantArg(TheCall, 1, Result))
6910 return true;
6911
6912 if (!Result.isPowerOf2())
6913 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6914 << SecondArg->getSourceRange();
6915
6917 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6918 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6919
6920 TheCall->setArg(1,
6922 }
6923
6924 if (NumArgs > 2) {
6925 Expr *ThirdArg = TheCall->getArg(2);
6926 if (convertArgumentToType(ThirdArg, Context.getSizeType()))
6927 return true;
6928 TheCall->setArg(2, ThirdArg);
6929 }
6930
6931 return false;
6932}
6933
6934bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6935 unsigned BuiltinID =
6936 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6937 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6938
6939 unsigned NumArgs = TheCall->getNumArgs();
6940 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6941 if (NumArgs < NumRequiredArgs) {
6942 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6943 << 0 /* function call */ << NumRequiredArgs << NumArgs
6944 << /*is non object*/ 0 << TheCall->getSourceRange();
6945 }
6946 if (NumArgs >= NumRequiredArgs + 0x100) {
6947 return Diag(TheCall->getEndLoc(),
6948 diag::err_typecheck_call_too_many_args_at_most)
6949 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6950 << /*is non object*/ 0 << TheCall->getSourceRange();
6951 }
6952 unsigned i = 0;
6953
6954 // For formatting call, check buffer arg.
6955 if (!IsSizeCall) {
6956 ExprResult Arg(TheCall->getArg(i));
6957 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6958 Context, Context.VoidPtrTy, false);
6959 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6960 if (Arg.isInvalid())
6961 return true;
6962 TheCall->setArg(i, Arg.get());
6963 i++;
6964 }
6965
6966 // Check string literal arg.
6967 unsigned FormatIdx = i;
6968 {
6969 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6970 if (Arg.isInvalid())
6971 return true;
6972 TheCall->setArg(i, Arg.get());
6973 i++;
6974 }
6975
6976 // Make sure variadic args are scalar.
6977 unsigned FirstDataArg = i;
6978 while (i < NumArgs) {
6980 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6981 if (Arg.isInvalid())
6982 return true;
6983 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6984 if (ArgSize.getQuantity() >= 0x100) {
6985 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6986 << i << (int)ArgSize.getQuantity() << 0xff
6987 << TheCall->getSourceRange();
6988 }
6989 TheCall->setArg(i, Arg.get());
6990 i++;
6991 }
6992
6993 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6994 // call to avoid duplicate diagnostics.
6995 if (!IsSizeCall) {
6996 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6997 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6998 bool Success = CheckFormatArguments(
6999 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
7001 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
7002 if (!Success)
7003 return true;
7004 }
7005
7006 if (IsSizeCall) {
7007 TheCall->setType(Context.getSizeType());
7008 } else {
7009 TheCall->setType(Context.VoidPtrTy);
7010 }
7011 return false;
7012}
7013
7014bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
7015 llvm::APSInt &Result) {
7016 Expr *Arg = TheCall->getArg(ArgNum);
7017
7018 if (Arg->isTypeDependent() || Arg->isValueDependent())
7019 return false;
7020
7021 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
7022 if (!R) {
7023 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7024 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
7025 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7026 << FDecl->getDeclName() << Arg->getSourceRange();
7027 }
7028 Result = *R;
7029
7030 return false;
7031}
7032
7033bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
7034 int High, bool RangeIsError) {
7036 return false;
7037 llvm::APSInt Result;
7038
7039 // We can't check the value of a dependent argument.
7040 Expr *Arg = TheCall->getArg(ArgNum);
7041 if (Arg->isTypeDependent() || Arg->isValueDependent())
7042 return false;
7043
7044 // Check constant-ness first.
7045 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7046 return true;
7047
7048 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7049 if (RangeIsError)
7050 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7051 << toString(Result, 10) << Low << High << Arg->getSourceRange();
7052 else
7053 // Defer the warning until we know if the code will be emitted so that
7054 // dead code can ignore this.
7055 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7056 PDiag(diag::warn_argument_invalid_range)
7057 << toString(Result, 10) << Low << High
7058 << Arg->getSourceRange());
7059 }
7060
7061 return false;
7062}
7063
7064bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
7065 unsigned Num) {
7066 llvm::APSInt Result;
7067
7068 // We can't check the value of a dependent argument.
7069 Expr *Arg = TheCall->getArg(ArgNum);
7070 if (Arg->isTypeDependent() || Arg->isValueDependent())
7071 return false;
7072
7073 // Check constant-ness first.
7074 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7075 return true;
7076
7077 if (Result.getSExtValue() % Num != 0)
7078 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7079 << Num << Arg->getSourceRange();
7080
7081 return false;
7082}
7083
7084bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
7085 llvm::APSInt Result;
7086
7087 // We can't check the value of a dependent argument.
7088 Expr *Arg = TheCall->getArg(ArgNum);
7089 if (Arg->isTypeDependent() || Arg->isValueDependent())
7090 return false;
7091
7092 // Check constant-ness first.
7093 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7094 return true;
7095
7096 if (Result.isPowerOf2())
7097 return false;
7098
7099 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7100 << Arg->getSourceRange();
7101}
7102
7103static bool IsShiftedByte(llvm::APSInt Value) {
7104 if (Value.isNegative())
7105 return false;
7106
7107 // Check if it's a shifted byte, by shifting it down
7108 while (true) {
7109 // If the value fits in the bottom byte, the check passes.
7110 if (Value < 0x100)
7111 return true;
7112
7113 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7114 // fails.
7115 if ((Value & 0xFF) != 0)
7116 return false;
7117
7118 // If the bottom 8 bits are all 0, but something above that is nonzero,
7119 // then shifting the value right by 8 bits won't affect whether it's a
7120 // shifted byte or not. So do that, and go round again.
7121 Value >>= 8;
7122 }
7123}
7124
7125bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7126 unsigned ArgBits) {
7127 llvm::APSInt Result;
7128
7129 // We can't check the value of a dependent argument.
7130 Expr *Arg = TheCall->getArg(ArgNum);
7131 if (Arg->isTypeDependent() || Arg->isValueDependent())
7132 return false;
7133
7134 // Check constant-ness first.
7135 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7136 return true;
7137
7138 // Truncate to the given size.
7139 Result = Result.getLoBits(ArgBits);
7140 Result.setIsUnsigned(true);
7141
7142 if (IsShiftedByte(Result))
7143 return false;
7144
7145 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7146 << Arg->getSourceRange();
7147}
7148
7150 unsigned ArgNum,
7151 unsigned ArgBits) {
7152 llvm::APSInt Result;
7153
7154 // We can't check the value of a dependent argument.
7155 Expr *Arg = TheCall->getArg(ArgNum);
7156 if (Arg->isTypeDependent() || Arg->isValueDependent())
7157 return false;
7158
7159 // Check constant-ness first.
7160 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7161 return true;
7162
7163 // Truncate to the given size.
7164 Result = Result.getLoBits(ArgBits);
7165 Result.setIsUnsigned(true);
7166
7167 // Check to see if it's in either of the required forms.
7168 if (IsShiftedByte(Result) ||
7169 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7170 return false;
7171
7172 return Diag(TheCall->getBeginLoc(),
7173 diag::err_argument_not_shifted_byte_or_xxff)
7174 << Arg->getSourceRange();
7175}
7176
7177bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7178 if (!Context.getTargetInfo().hasSjLjLowering())
7179 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7180 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7181
7182 Expr *Arg = TheCall->getArg(1);
7183 llvm::APSInt Result;
7184
7185 // TODO: This is less than ideal. Overload this to take a value.
7186 if (BuiltinConstantArg(TheCall, 1, Result))
7187 return true;
7188
7189 if (Result != 1)
7190 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7191 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7192
7193 return false;
7194}
7195
7196bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7197 if (!Context.getTargetInfo().hasSjLjLowering())
7198 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7199 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7200 return false;
7201}
7202
7203bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7204 if (checkArgCount(TheCall, 1))
7205 return true;
7206
7207 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
7208 if (ArgRes.isInvalid())
7209 return true;
7210
7211 // For simplicity, we support only limited expressions for the argument.
7212 // Specifically a flexible array member or a pointer with counted_by:
7213 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7214 // complex casting, which really shouldn't be a huge problem.
7215 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7216 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7217 return Diag(Arg->getBeginLoc(),
7218 diag::err_builtin_counted_by_ref_invalid_arg)
7219 << Arg->getSourceRange();
7220
7221 if (Arg->HasSideEffects(Context))
7222 return Diag(Arg->getBeginLoc(),
7223 diag::err_builtin_counted_by_ref_has_side_effects)
7224 << Arg->getSourceRange();
7225
7226 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7227 const auto *CATy =
7228 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7229
7230 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7231 // Member has counted_by attribute - return pointer to count field
7232 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
7233 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7234 if (CountFD->isBitField()) {
7235 Diag(ME->getBeginLoc(),
7236 diag::err_builtin_counted_by_ref_counter_field_is_bitfield)
7237 << Arg << CountFD << ME->getSourceRange();
7238 return Diag(CountFD->getBeginLoc(),
7239 diag::note_counted_by_counter_field)
7240 << CountFD << CountFD->getSourceRange();
7241 }
7242
7243 TheCall->setType(Context.getPointerType(CountFD->getType()));
7244 return false;
7245 }
7246 }
7247
7248 // FAMs and pointers without counted_by return void*
7249 QualType MemberTy = ME->getMemberDecl()->getType();
7250 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7251 return Diag(Arg->getBeginLoc(),
7252 diag::err_builtin_counted_by_ref_invalid_arg)
7253 << Arg->getSourceRange();
7254 } else {
7255 return Diag(Arg->getBeginLoc(),
7256 diag::err_builtin_counted_by_ref_invalid_arg)
7257 << Arg->getSourceRange();
7258 }
7259
7260 TheCall->setType(Context.getPointerType(Context.VoidTy));
7261 return false;
7262}
7263
7264/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7265/// It allows leaking and modification of bounds safety information.
7266bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7268 const CallExpr *CE =
7269 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7270 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7271 return false;
7272
7273 switch (K) {
7276 Diag(E->getExprLoc(),
7277 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7278 << 0 << E->getSourceRange();
7279 break;
7281 Diag(E->getExprLoc(),
7282 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7283 << 1 << E->getSourceRange();
7284 break;
7286 Diag(E->getExprLoc(),
7287 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7288 << 2 << E->getSourceRange();
7289 break;
7291 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7292 << 0 << E->getSourceRange();
7293 break;
7295 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7296 << 1 << E->getSourceRange();
7297 break;
7298 }
7299
7300 return true;
7301}
7302
7303namespace {
7304
7305class UncoveredArgHandler {
7306 enum { Unknown = -1, AllCovered = -2 };
7307
7308 signed FirstUncoveredArg = Unknown;
7309 SmallVector<const Expr *, 4> DiagnosticExprs;
7310
7311public:
7312 UncoveredArgHandler() = default;
7313
7314 bool hasUncoveredArg() const {
7315 return (FirstUncoveredArg >= 0);
7316 }
7317
7318 unsigned getUncoveredArg() const {
7319 assert(hasUncoveredArg() && "no uncovered argument");
7320 return FirstUncoveredArg;
7321 }
7322
7323 void setAllCovered() {
7324 // A string has been found with all arguments covered, so clear out
7325 // the diagnostics.
7326 DiagnosticExprs.clear();
7327 FirstUncoveredArg = AllCovered;
7328 }
7329
7330 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7331 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7332
7333 // Don't update if a previous string covers all arguments.
7334 if (FirstUncoveredArg == AllCovered)
7335 return;
7336
7337 // UncoveredArgHandler tracks the highest uncovered argument index
7338 // and with it all the strings that match this index.
7339 if (NewFirstUncoveredArg == FirstUncoveredArg)
7340 DiagnosticExprs.push_back(StrExpr);
7341 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7342 DiagnosticExprs.clear();
7343 DiagnosticExprs.push_back(StrExpr);
7344 FirstUncoveredArg = NewFirstUncoveredArg;
7345 }
7346 }
7347
7348 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7349};
7350
7351enum StringLiteralCheckType {
7352 SLCT_NotALiteral,
7353 SLCT_UncheckedLiteral,
7354 SLCT_CheckedLiteral
7355};
7356
7357} // namespace
7358
7359static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7360 BinaryOperatorKind BinOpKind,
7361 bool AddendIsRight) {
7362 unsigned BitWidth = Offset.getBitWidth();
7363 unsigned AddendBitWidth = Addend.getBitWidth();
7364 // There might be negative interim results.
7365 if (Addend.isUnsigned()) {
7366 Addend = Addend.zext(++AddendBitWidth);
7367 Addend.setIsSigned(true);
7368 }
7369 // Adjust the bit width of the APSInts.
7370 if (AddendBitWidth > BitWidth) {
7371 Offset = Offset.sext(AddendBitWidth);
7372 BitWidth = AddendBitWidth;
7373 } else if (BitWidth > AddendBitWidth) {
7374 Addend = Addend.sext(BitWidth);
7375 }
7376
7377 bool Ov = false;
7378 llvm::APSInt ResOffset = Offset;
7379 if (BinOpKind == BO_Add)
7380 ResOffset = Offset.sadd_ov(Addend, Ov);
7381 else {
7382 assert(AddendIsRight && BinOpKind == BO_Sub &&
7383 "operator must be add or sub with addend on the right");
7384 ResOffset = Offset.ssub_ov(Addend, Ov);
7385 }
7386
7387 // We add an offset to a pointer here so we should support an offset as big as
7388 // possible.
7389 if (Ov) {
7390 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7391 "index (intermediate) result too big");
7392 Offset = Offset.sext(2 * BitWidth);
7393 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7394 return;
7395 }
7396
7397 Offset = std::move(ResOffset);
7398}
7399
7400namespace {
7401
7402// This is a wrapper class around StringLiteral to support offsetted string
7403// literals as format strings. It takes the offset into account when returning
7404// the string and its length or the source locations to display notes correctly.
7405class FormatStringLiteral {
7406 const StringLiteral *FExpr;
7407 int64_t Offset;
7408
7409public:
7410 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7411 : FExpr(fexpr), Offset(Offset) {}
7412
7413 const StringLiteral *getFormatString() const { return FExpr; }
7414
7415 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7416
7417 unsigned getByteLength() const {
7418 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7419 }
7420
7421 unsigned getLength() const { return FExpr->getLength() - Offset; }
7422 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7423
7424 StringLiteralKind getKind() const { return FExpr->getKind(); }
7425
7426 QualType getType() const { return FExpr->getType(); }
7427
7428 bool isAscii() const { return FExpr->isOrdinary(); }
7429 bool isWide() const { return FExpr->isWide(); }
7430 bool isUTF8() const { return FExpr->isUTF8(); }
7431 bool isUTF16() const { return FExpr->isUTF16(); }
7432 bool isUTF32() const { return FExpr->isUTF32(); }
7433 bool isPascal() const { return FExpr->isPascal(); }
7434
7435 SourceLocation getLocationOfByte(
7436 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7437 const TargetInfo &Target, unsigned *StartToken = nullptr,
7438 unsigned *StartTokenByteOffset = nullptr) const {
7439 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7440 StartToken, StartTokenByteOffset);
7441 }
7442
7443 SourceLocation getBeginLoc() const LLVM_READONLY {
7444 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7445 }
7446
7447 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7448};
7449
7450} // namespace
7451
7452static void CheckFormatString(
7453 Sema &S, const FormatStringLiteral *FExpr,
7454 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7456 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7457 bool inFunctionCall, VariadicCallType CallType,
7458 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7459 bool IgnoreStringsWithoutSpecifiers);
7460
7461static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7462 const Expr *E);
7463
7464// Determine if an expression is a string literal or constant string.
7465// If this function returns false on the arguments to a function expecting a
7466// format string, we will usually need to emit a warning.
7467// True string literals are then checked by CheckFormatString.
7468static StringLiteralCheckType
7469checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7470 const Expr *E, ArrayRef<const Expr *> Args,
7471 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7472 unsigned firstDataArg, FormatStringType Type,
7473 VariadicCallType CallType, bool InFunctionCall,
7474 llvm::SmallBitVector &CheckedVarArgs,
7475 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7476 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7477 bool IgnoreStringsWithoutSpecifiers = false) {
7479 return SLCT_NotALiteral;
7480tryAgain:
7481 assert(Offset.isSigned() && "invalid offset");
7482
7483 if (E->isTypeDependent() || E->isValueDependent())
7484 return SLCT_NotALiteral;
7485
7486 E = E->IgnoreParenCasts();
7487
7489 // Technically -Wformat-nonliteral does not warn about this case.
7490 // The behavior of printf and friends in this case is implementation
7491 // dependent. Ideally if the format string cannot be null then
7492 // it should have a 'nonnull' attribute in the function prototype.
7493 return SLCT_UncheckedLiteral;
7494
7495 switch (E->getStmtClass()) {
7496 case Stmt::InitListExprClass:
7497 // Handle expressions like {"foobar"}.
7498 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7499 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7500 format_idx, firstDataArg, Type, CallType,
7501 /*InFunctionCall*/ false, CheckedVarArgs,
7502 UncoveredArg, Offset, CallerFormatParamIdx,
7503 IgnoreStringsWithoutSpecifiers);
7504 }
7505 return SLCT_NotALiteral;
7506 case Stmt::BinaryConditionalOperatorClass:
7507 case Stmt::ConditionalOperatorClass: {
7508 // The expression is a literal if both sub-expressions were, and it was
7509 // completely checked only if both sub-expressions were checked.
7512
7513 // Determine whether it is necessary to check both sub-expressions, for
7514 // example, because the condition expression is a constant that can be
7515 // evaluated at compile time.
7516 bool CheckLeft = true, CheckRight = true;
7517
7518 bool Cond;
7519 if (C->getCond()->EvaluateAsBooleanCondition(
7520 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
7521 if (Cond)
7522 CheckRight = false;
7523 else
7524 CheckLeft = false;
7525 }
7526
7527 // We need to maintain the offsets for the right and the left hand side
7528 // separately to check if every possible indexed expression is a valid
7529 // string literal. They might have different offsets for different string
7530 // literals in the end.
7531 StringLiteralCheckType Left;
7532 if (!CheckLeft)
7533 Left = SLCT_UncheckedLiteral;
7534 else {
7535 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7536 Args, APK, format_idx, firstDataArg, Type,
7537 CallType, InFunctionCall, CheckedVarArgs,
7538 UncoveredArg, Offset, CallerFormatParamIdx,
7539 IgnoreStringsWithoutSpecifiers);
7540 if (Left == SLCT_NotALiteral || !CheckRight) {
7541 return Left;
7542 }
7543 }
7544
7545 StringLiteralCheckType Right = checkFormatStringExpr(
7546 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7547 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7548 UncoveredArg, Offset, CallerFormatParamIdx,
7549 IgnoreStringsWithoutSpecifiers);
7550
7551 return (CheckLeft && Left < Right) ? Left : Right;
7552 }
7553
7554 case Stmt::ImplicitCastExprClass:
7555 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7556 goto tryAgain;
7557
7558 case Stmt::OpaqueValueExprClass:
7559 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7560 E = src;
7561 goto tryAgain;
7562 }
7563 return SLCT_NotALiteral;
7564
7565 case Stmt::PredefinedExprClass:
7566 // While __func__, etc., are technically not string literals, they
7567 // cannot contain format specifiers and thus are not a security
7568 // liability.
7569 return SLCT_UncheckedLiteral;
7570
7571 case Stmt::DeclRefExprClass: {
7572 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7573
7574 // As an exception, do not flag errors for variables binding to
7575 // const string literals.
7576 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7577 bool isConstant = false;
7578 QualType T = DR->getType();
7579
7580 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7581 isConstant = AT->getElementType().isConstant(S.Context);
7582 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7583 isConstant = T.isConstant(S.Context) &&
7584 PT->getPointeeType().isConstant(S.Context);
7585 } else if (T->isObjCObjectPointerType()) {
7586 // In ObjC, there is usually no "const ObjectPointer" type,
7587 // so don't check if the pointee type is constant.
7588 isConstant = T.isConstant(S.Context);
7589 }
7590
7591 if (isConstant) {
7592 if (const Expr *Init = VD->getAnyInitializer()) {
7593 // Look through initializers like const char c[] = { "foo" }
7594 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7595 if (InitList->isStringLiteralInit())
7596 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7597 }
7598 return checkFormatStringExpr(
7599 S, ReferenceFormatString, Init, Args, APK, format_idx,
7600 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7601 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7602 }
7603 }
7604
7605 // When the format argument is an argument of this function, and this
7606 // function also has the format attribute, there are several interactions
7607 // for which there shouldn't be a warning. For instance, when calling
7608 // v*printf from a function that has the printf format attribute, we
7609 // should not emit a warning about using `fmt`, even though it's not
7610 // constant, because the arguments have already been checked for the
7611 // caller of `logmessage`:
7612 //
7613 // __attribute__((format(printf, 1, 2)))
7614 // void logmessage(char const *fmt, ...) {
7615 // va_list ap;
7616 // va_start(ap, fmt);
7617 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7618 // ...
7619 // }
7620 //
7621 // Another interaction that we need to support is using a format string
7622 // specified by the format_matches attribute:
7623 //
7624 // __attribute__((format_matches(printf, 1, "%s %d")))
7625 // void logmessage(char const *fmt, const char *a, int b) {
7626 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7627 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7628 // ...
7629 // }
7630 //
7631 // Yet another interaction that we need to support is calling a variadic
7632 // format function from a format function that has fixed arguments. For
7633 // instance:
7634 //
7635 // __attribute__((format(printf, 1, 2)))
7636 // void logstring(char const *fmt, char const *str) {
7637 // printf(fmt, str); /* do not emit a warning about "fmt" */
7638 // }
7639 //
7640 // Same (and perhaps more relatably) for the variadic template case:
7641 //
7642 // template<typename... Args>
7643 // __attribute__((format(printf, 1, 2)))
7644 // void log(const char *fmt, Args&&... args) {
7645 // printf(fmt, forward<Args>(args)...);
7646 // /* do not emit a warning about "fmt" */
7647 // }
7648 //
7649 // Due to implementation difficulty, we only check the format, not the
7650 // format arguments, in all cases.
7651 //
7652 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7653 if (CallerFormatParamIdx)
7654 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7655 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7656 for (const auto *PVFormatMatches :
7657 D->specific_attrs<FormatMatchesAttr>()) {
7658 Sema::FormatStringInfo CalleeFSI;
7659 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7660 0, &CalleeFSI))
7661 continue;
7662 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7663 // If using the wrong type of format string, emit a diagnostic
7664 // here and stop checking to avoid irrelevant diagnostics.
7665 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7666 S.Diag(Args[format_idx]->getBeginLoc(),
7667 diag::warn_format_string_type_incompatible)
7668 << PVFormatMatches->getType()->getName()
7670 if (!InFunctionCall) {
7671 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7672 diag::note_format_string_defined);
7673 }
7674 return SLCT_UncheckedLiteral;
7675 }
7676 return checkFormatStringExpr(
7677 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7678 Args, APK, format_idx, firstDataArg, Type, CallType,
7679 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7680 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7681 }
7682 }
7683
7684 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7685 Sema::FormatStringInfo CallerFSI;
7686 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7687 PVFormat->getFirstArg(), &CallerFSI))
7688 continue;
7689 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7690 // We also check if the formats are compatible.
7691 // We can't pass a 'scanf' string to a 'printf' function.
7692 if (Type != S.GetFormatStringType(PVFormat)) {
7693 S.Diag(Args[format_idx]->getBeginLoc(),
7694 diag::warn_format_string_type_incompatible)
7695 << PVFormat->getType()->getName()
7697 if (!InFunctionCall) {
7698 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7699 }
7700 return SLCT_UncheckedLiteral;
7701 }
7702 // Lastly, check that argument passing kinds transition in a
7703 // way that makes sense:
7704 // from a caller with FAPK_VAList, allow FAPK_VAList
7705 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7706 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7707 // from a caller with FAPK_Variadic, allow FAPK_VAList
7708 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7713 return SLCT_UncheckedLiteral;
7714 }
7715 }
7716 }
7717 }
7718 }
7719 }
7720
7721 return SLCT_NotALiteral;
7722 }
7723
7724 case Stmt::CallExprClass:
7725 case Stmt::CXXMemberCallExprClass: {
7726 const CallExpr *CE = cast<CallExpr>(E);
7727 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7728 bool IsFirst = true;
7729 StringLiteralCheckType CommonResult;
7730 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7731 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7732 StringLiteralCheckType Result = checkFormatStringExpr(
7733 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7734 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7735 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7736 if (IsFirst) {
7737 CommonResult = Result;
7738 IsFirst = false;
7739 }
7740 }
7741 if (!IsFirst)
7742 return CommonResult;
7743
7744 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7745 unsigned BuiltinID = FD->getBuiltinID();
7746 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7747 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7748 const Expr *Arg = CE->getArg(0);
7749 return checkFormatStringExpr(
7750 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7751 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7752 UncoveredArg, Offset, CallerFormatParamIdx,
7753 IgnoreStringsWithoutSpecifiers);
7754 }
7755 }
7756 }
7757 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7758 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7759 format_idx, firstDataArg, Type, CallType,
7760 /*InFunctionCall*/ false, CheckedVarArgs,
7761 UncoveredArg, Offset, CallerFormatParamIdx,
7762 IgnoreStringsWithoutSpecifiers);
7763 return SLCT_NotALiteral;
7764 }
7765 case Stmt::ObjCMessageExprClass: {
7766 const auto *ME = cast<ObjCMessageExpr>(E);
7767 if (const auto *MD = ME->getMethodDecl()) {
7768 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7769 // As a special case heuristic, if we're using the method -[NSBundle
7770 // localizedStringForKey:value:table:], ignore any key strings that lack
7771 // format specifiers. The idea is that if the key doesn't have any
7772 // format specifiers then its probably just a key to map to the
7773 // localized strings. If it does have format specifiers though, then its
7774 // likely that the text of the key is the format string in the
7775 // programmer's language, and should be checked.
7776 const ObjCInterfaceDecl *IFace;
7777 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7778 IFace->getIdentifier()->isStr("NSBundle") &&
7779 MD->getSelector().isKeywordSelector(
7780 {"localizedStringForKey", "value", "table"})) {
7781 IgnoreStringsWithoutSpecifiers = true;
7782 }
7783
7784 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7785 return checkFormatStringExpr(
7786 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7787 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7788 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7789 }
7790 }
7791
7792 return SLCT_NotALiteral;
7793 }
7794 case Stmt::ObjCStringLiteralClass:
7795 case Stmt::StringLiteralClass: {
7796 const StringLiteral *StrE = nullptr;
7797
7798 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7799 StrE = ObjCFExpr->getString();
7800 else
7801 StrE = cast<StringLiteral>(E);
7802
7803 if (StrE) {
7804 if (Offset.isNegative() || Offset > StrE->getLength()) {
7805 // TODO: It would be better to have an explicit warning for out of
7806 // bounds literals.
7807 return SLCT_NotALiteral;
7808 }
7809 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7810 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7811 format_idx, firstDataArg, Type, InFunctionCall,
7812 CallType, CheckedVarArgs, UncoveredArg,
7813 IgnoreStringsWithoutSpecifiers);
7814 return SLCT_CheckedLiteral;
7815 }
7816
7817 return SLCT_NotALiteral;
7818 }
7819 case Stmt::BinaryOperatorClass: {
7820 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7821
7822 // A string literal + an int offset is still a string literal.
7823 if (BinOp->isAdditiveOp()) {
7824 Expr::EvalResult LResult, RResult;
7825
7826 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7827 LResult, S.Context, Expr::SE_NoSideEffects,
7829 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7830 RResult, S.Context, Expr::SE_NoSideEffects,
7832
7833 if (LIsInt != RIsInt) {
7834 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7835
7836 if (LIsInt) {
7837 if (BinOpKind == BO_Add) {
7838 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7839 E = BinOp->getRHS();
7840 goto tryAgain;
7841 }
7842 } else {
7843 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7844 E = BinOp->getLHS();
7845 goto tryAgain;
7846 }
7847 }
7848 }
7849
7850 return SLCT_NotALiteral;
7851 }
7852 case Stmt::UnaryOperatorClass: {
7853 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7854 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7855 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7856 Expr::EvalResult IndexResult;
7857 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7860 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7861 /*RHS is int*/ true);
7862 E = ASE->getBase();
7863 goto tryAgain;
7864 }
7865 }
7866
7867 return SLCT_NotALiteral;
7868 }
7869
7870 default:
7871 return SLCT_NotALiteral;
7872 }
7873}
7874
7875// If this expression can be evaluated at compile-time,
7876// check if the result is a StringLiteral and return it
7877// otherwise return nullptr
7879 const Expr *E) {
7881 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7882 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7883 if (isa_and_nonnull<StringLiteral>(LVE))
7884 return LVE;
7885 }
7886 return nullptr;
7887}
7888
7890 switch (FST) {
7892 return "scanf";
7894 return "printf";
7896 return "NSString";
7898 return "strftime";
7900 return "strfmon";
7902 return "kprintf";
7904 return "freebsd_kprintf";
7906 return "os_log";
7907 default:
7908 return "<unknown>";
7909 }
7910}
7911
7913 return llvm::StringSwitch<FormatStringType>(Flavor)
7914 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7915 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7917 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7918 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7919 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7920 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7922 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7923 .Case("os_trace", FormatStringType::OSLog)
7924 .Case("os_log", FormatStringType::OSLog)
7925 .Default(FormatStringType::Unknown);
7926}
7927
7929 return GetFormatStringType(Format->getType()->getName());
7930}
7931
7932FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7933 return GetFormatStringType(Format->getType()->getName());
7934}
7935
7936bool Sema::CheckFormatArguments(const FormatAttr *Format,
7937 ArrayRef<const Expr *> Args, bool IsCXXMember,
7938 VariadicCallType CallType, SourceLocation Loc,
7939 SourceRange Range,
7940 llvm::SmallBitVector &CheckedVarArgs) {
7941 FormatStringInfo FSI;
7942 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7943 IsCXXMember,
7944 CallType != VariadicCallType::DoesNotApply, &FSI))
7945 return CheckFormatArguments(
7946 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7947 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7948 return false;
7949}
7950
7951bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7952 ArrayRef<const Expr *> Args, bool IsCXXMember,
7953 VariadicCallType CallType, SourceLocation Loc,
7954 SourceRange Range,
7955 llvm::SmallBitVector &CheckedVarArgs) {
7956 FormatStringInfo FSI;
7957 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7958 &FSI)) {
7959 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7960 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7961 Format->getFormatString(), FSI.FormatIdx,
7962 FSI.FirstDataArg, GetFormatStringType(Format),
7963 CallType, Loc, Range, CheckedVarArgs);
7964 }
7965 return false;
7966}
7967
7970 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7971 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7972 SourceLocation Loc) {
7973 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7974 return false;
7975
7977 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7978 return false;
7979 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7980
7981 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7982
7983 // Find the offset to convert between attribute and parameter indexes.
7984 unsigned CallerArgumentIndexOffset =
7985 hasImplicitObjectParameter(Caller) ? 2 : 1;
7986
7987 unsigned FirstArgumentIndex = -1;
7988 switch (APK) {
7991 // As an extension, clang allows the format attribute on non-variadic
7992 // functions.
7993 // Caller must have fixed arguments to pass them to a fixed or variadic
7994 // function. Try to match caller and callee arguments. If successful, then
7995 // emit a diag with the caller idx, otherwise we can't determine the callee
7996 // arguments.
7997 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7998 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7999 // There aren't enough arguments in the caller to pass to callee.
8000 return false;
8001 }
8002 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
8003 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
8004 const auto *Arg =
8005 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
8006 if (!Arg)
8007 return false;
8008 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
8009 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
8010 return false;
8011 }
8012 FirstArgumentIndex =
8013 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
8014 break;
8015 }
8017 // Caller arguments are either variadic or a va_list.
8018 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
8019 ? (NumCallerParams + CallerArgumentIndexOffset)
8020 : 0;
8021 break;
8023 // The callee has a format_matches attribute. We will emit that instead.
8024 if (!ReferenceFormatString)
8025 return false;
8026 break;
8027 }
8028
8029 // Emit the diagnostic and fixit.
8030 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
8031 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
8032 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
8033 do {
8034 std::string Attr, Fixit;
8035 llvm::raw_string_ostream AttrOS(Attr);
8037 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
8038 << FirstArgumentIndex << ")";
8039 } else {
8040 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
8041 << ", \"";
8042 AttrOS.write_escaped(ReferenceFormatString->getString());
8043 AttrOS << "\")";
8044 }
8045 AttrOS.flush();
8046 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
8047 if (ND)
8048 DB << ND;
8049 else
8050 DB << "block";
8051
8052 // Blocks don't provide a correct end loc, so skip emitting a fixit.
8053 if (isa<BlockDecl>(Caller))
8054 break;
8055
8056 SourceLocation SL;
8057 llvm::raw_string_ostream IS(Fixit);
8058 // The attribute goes at the start of the declaration in C/C++ functions
8059 // and methods, but after the declaration for Objective-C methods.
8060 if (isa<ObjCMethodDecl>(Caller)) {
8061 IS << ' ';
8062 SL = Caller->getEndLoc();
8063 }
8064 const LangOptions &LO = S->getLangOpts();
8065 if (LO.C23 || LO.CPlusPlus11)
8066 IS << "[[gnu::" << Attr << "]]";
8067 else if (LO.ObjC || LO.GNUMode)
8068 IS << "__attribute__((" << Attr << "))";
8069 else
8070 break;
8071 if (!isa<ObjCMethodDecl>(Caller)) {
8072 IS << ' ';
8073 SL = Caller->getBeginLoc();
8074 }
8075 IS.flush();
8076
8077 DB << FixItHint::CreateInsertion(SL, Fixit);
8078 } while (false);
8079
8080 // Add implicit format or format_matches attribute.
8082 Caller->addAttr(FormatAttr::CreateImplicit(
8083 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
8084 FormatStringIndex, FirstArgumentIndex));
8085 } else {
8086 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
8087 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
8088 FormatStringIndex, ReferenceFormatString));
8089 }
8090
8091 {
8092 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
8093 if (ND)
8094 DB << ND;
8095 else
8096 DB << "block";
8097 }
8098 return true;
8099}
8100
8101bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8103 StringLiteral *ReferenceFormatString,
8104 unsigned format_idx, unsigned firstDataArg,
8106 VariadicCallType CallType, SourceLocation Loc,
8107 SourceRange Range,
8108 llvm::SmallBitVector &CheckedVarArgs) {
8109 // CHECK: printf/scanf-like function is called with no format string.
8110 if (format_idx >= Args.size()) {
8111 Diag(Loc, diag::warn_missing_format_string) << Range;
8112 return false;
8113 }
8114
8115 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8116
8117 // CHECK: format string is not a string literal.
8118 //
8119 // Dynamically generated format strings are difficult to
8120 // automatically vet at compile time. Requiring that format strings
8121 // are string literals: (1) permits the checking of format strings by
8122 // the compiler and thereby (2) can practically remove the source of
8123 // many format string exploits.
8124
8125 // Format string can be either ObjC string (e.g. @"%d") or
8126 // C string (e.g. "%d")
8127 // ObjC string uses the same format specifiers as C string, so we can use
8128 // the same format string checking logic for both ObjC and C strings.
8129 UncoveredArgHandler UncoveredArg;
8130 std::optional<unsigned> CallerParamIdx;
8131 StringLiteralCheckType CT = checkFormatStringExpr(
8132 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
8133 firstDataArg, Type, CallType,
8134 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
8135 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
8136
8137 // Generate a diagnostic where an uncovered argument is detected.
8138 if (UncoveredArg.hasUncoveredArg()) {
8139 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8140 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8141 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8142 }
8143
8144 if (CT != SLCT_NotALiteral)
8145 // Literal format string found, check done!
8146 return CT == SLCT_CheckedLiteral;
8147
8148 // Do not emit diag when the string param is a macro expansion and the
8149 // format is either NSString or CFString. This is a hack to prevent
8150 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8151 // which are usually used in place of NS and CF string literals.
8152 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8154 SourceMgr.isInSystemMacro(FormatLoc))
8155 return false;
8156
8157 if (CallerParamIdx && CheckMissingFormatAttribute(
8158 this, Args, APK, ReferenceFormatString, format_idx,
8159 firstDataArg, Type, *CallerParamIdx, Loc))
8160 return false;
8161
8162 // Strftime is particular as it always uses a single 'time' argument,
8163 // so it is safe to pass a non-literal string.
8165 return false;
8166
8167 // If there are no arguments specified, warn with -Wformat-security, otherwise
8168 // warn only with -Wformat-nonliteral.
8169 if (Args.size() == firstDataArg) {
8170 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8171 << OrigFormatExpr->getSourceRange();
8172 switch (Type) {
8173 default:
8174 break;
8178 Diag(FormatLoc, diag::note_format_security_fixit)
8179 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8180 break;
8182 Diag(FormatLoc, diag::note_format_security_fixit)
8183 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8184 break;
8185 }
8186 } else {
8187 Diag(FormatLoc, diag::warn_format_nonliteral)
8188 << OrigFormatExpr->getSourceRange();
8189 }
8190 return false;
8191}
8192
8193namespace {
8194
8195class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8196protected:
8197 Sema &S;
8198 const FormatStringLiteral *FExpr;
8199 const Expr *OrigFormatExpr;
8200 const FormatStringType FSType;
8201 const unsigned FirstDataArg;
8202 const unsigned NumDataArgs;
8203 const char *Beg; // Start of format string.
8204 const Sema::FormatArgumentPassingKind ArgPassingKind;
8205 ArrayRef<const Expr *> Args;
8206 unsigned FormatIdx;
8207 llvm::SmallBitVector CoveredArgs;
8208 bool usesPositionalArgs = false;
8209 bool atFirstArg = true;
8210 bool inFunctionCall;
8211 VariadicCallType CallType;
8212 llvm::SmallBitVector &CheckedVarArgs;
8213 UncoveredArgHandler &UncoveredArg;
8214
8215public:
8216 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8217 const Expr *origFormatExpr, const FormatStringType type,
8218 unsigned firstDataArg, unsigned numDataArgs,
8219 const char *beg, Sema::FormatArgumentPassingKind APK,
8220 ArrayRef<const Expr *> Args, unsigned formatIdx,
8221 bool inFunctionCall, VariadicCallType callType,
8222 llvm::SmallBitVector &CheckedVarArgs,
8223 UncoveredArgHandler &UncoveredArg)
8224 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8225 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8226 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8227 inFunctionCall(inFunctionCall), CallType(callType),
8228 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8229 CoveredArgs.resize(numDataArgs);
8230 CoveredArgs.reset();
8231 }
8232
8233 bool HasFormatArguments() const {
8234 return ArgPassingKind == Sema::FAPK_Fixed ||
8235 ArgPassingKind == Sema::FAPK_Variadic;
8236 }
8237
8238 void DoneProcessing();
8239
8240 void HandleIncompleteSpecifier(const char *startSpecifier,
8241 unsigned specifierLen) override;
8242
8243 void HandleInvalidLengthModifier(
8244 const analyze_format_string::FormatSpecifier &FS,
8245 const analyze_format_string::ConversionSpecifier &CS,
8246 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8247
8248 void HandleNonStandardLengthModifier(
8249 const analyze_format_string::FormatSpecifier &FS,
8250 const char *startSpecifier, unsigned specifierLen);
8251
8252 void HandleNonStandardConversionSpecifier(
8253 const analyze_format_string::ConversionSpecifier &CS,
8254 const char *startSpecifier, unsigned specifierLen);
8255
8256 void HandlePosition(const char *startPos, unsigned posLen) override;
8257
8258 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8260
8261 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8262
8263 void HandleNullChar(const char *nullCharacter) override;
8264
8265 template <typename Range>
8266 static void
8267 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8268 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8269 bool IsStringLocation, Range StringRange,
8270 ArrayRef<FixItHint> Fixit = {});
8271
8272protected:
8273 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8274 const char *startSpec,
8275 unsigned specifierLen,
8276 const char *csStart, unsigned csLen);
8277
8278 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8279 const char *startSpec,
8280 unsigned specifierLen);
8281
8282 SourceRange getFormatStringRange();
8283 CharSourceRange getSpecifierRange(const char *startSpecifier,
8284 unsigned specifierLen);
8285 SourceLocation getLocationOfByte(const char *x);
8286
8287 const Expr *getDataArg(unsigned i) const;
8288
8289 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8290 const analyze_format_string::ConversionSpecifier &CS,
8291 const char *startSpecifier, unsigned specifierLen,
8292 unsigned argIndex);
8293
8294 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8295 const Expr *E, const char *startSpecifier,
8296 unsigned specifierLen);
8297
8298 template <typename Range>
8299 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8300 bool IsStringLocation, Range StringRange,
8301 ArrayRef<FixItHint> Fixit = {});
8302};
8303
8304} // namespace
8305
8306SourceRange CheckFormatHandler::getFormatStringRange() {
8307 return OrigFormatExpr->getSourceRange();
8308}
8309
8311CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8312 unsigned specifierLen) {
8313 SourceLocation Start = getLocationOfByte(startSpecifier);
8314 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8315
8316 // Advance the end SourceLocation by one due to half-open ranges.
8317 End = End.getLocWithOffset(1);
8318
8319 return CharSourceRange::getCharRange(Start, End);
8320}
8321
8322SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8323 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8325}
8326
8327void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8328 unsigned specifierLen) {
8329 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8330 getLocationOfByte(startSpecifier),
8331 /*IsStringLocation*/ true,
8332 getSpecifierRange(startSpecifier, specifierLen));
8333}
8334
8335bool CheckFormatHandler::CheckUnsupportedType(
8336 const analyze_format_string::ArgType &AT, const Expr *E,
8337 const char *StartSpecifier, unsigned SpecifierLen) {
8338 if (!AT.isUnsupported())
8339 return false;
8340
8341 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8343 E->getExprLoc(), /*IsStringLocation=*/false,
8344 getSpecifierRange(StartSpecifier, SpecifierLen));
8345 return true;
8346}
8347
8348void CheckFormatHandler::HandleInvalidLengthModifier(
8351 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8352 using namespace analyze_format_string;
8353
8354 const LengthModifier &LM = FS.getLengthModifier();
8355 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8356
8357 // See if we know how to fix this length modifier.
8358 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8359 if (FixedLM) {
8360 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8361 getLocationOfByte(LM.getStart()),
8362 /*IsStringLocation*/ true,
8363 getSpecifierRange(startSpecifier, specifierLen));
8364
8365 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8366 << FixedLM->toString()
8367 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8368
8369 } else {
8370 FixItHint Hint;
8371 if (DiagID == diag::warn_format_nonsensical_length)
8372 Hint = FixItHint::CreateRemoval(LMRange);
8373
8374 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8375 getLocationOfByte(LM.getStart()),
8376 /*IsStringLocation*/ true,
8377 getSpecifierRange(startSpecifier, specifierLen), Hint);
8378 }
8379}
8380
8381void CheckFormatHandler::HandleNonStandardLengthModifier(
8383 const char *startSpecifier, unsigned specifierLen) {
8384 using namespace analyze_format_string;
8385
8386 const LengthModifier &LM = FS.getLengthModifier();
8387 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8388
8389 // See if we know how to fix this length modifier.
8390 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8391 if (FixedLM) {
8392 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8393 << LM.toString() << 0,
8394 getLocationOfByte(LM.getStart()),
8395 /*IsStringLocation*/ true,
8396 getSpecifierRange(startSpecifier, specifierLen));
8397
8398 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8399 << FixedLM->toString()
8400 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8401
8402 } else {
8403 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8404 << LM.toString() << 0,
8405 getLocationOfByte(LM.getStart()),
8406 /*IsStringLocation*/ true,
8407 getSpecifierRange(startSpecifier, specifierLen));
8408 }
8409}
8410
8411void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8413 const char *startSpecifier, unsigned specifierLen) {
8414 using namespace analyze_format_string;
8415
8416 // See if we know how to fix this conversion specifier.
8417 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8418 if (FixedCS) {
8419 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8420 << CS.toString() << /*conversion specifier*/ 1,
8421 getLocationOfByte(CS.getStart()),
8422 /*IsStringLocation*/ true,
8423 getSpecifierRange(startSpecifier, specifierLen));
8424
8425 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8426 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8427 << FixedCS->toString()
8428 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8429 } else {
8430 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8431 << CS.toString() << /*conversion specifier*/ 1,
8432 getLocationOfByte(CS.getStart()),
8433 /*IsStringLocation*/ true,
8434 getSpecifierRange(startSpecifier, specifierLen));
8435 }
8436}
8437
8438void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8439 if (!S.getDiagnostics().isIgnored(
8440 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8441 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8442 getLocationOfByte(startPos),
8443 /*IsStringLocation*/ true,
8444 getSpecifierRange(startPos, posLen));
8445}
8446
8447void CheckFormatHandler::HandleInvalidPosition(
8448 const char *startSpecifier, unsigned specifierLen,
8450 if (!S.getDiagnostics().isIgnored(
8451 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8452 EmitFormatDiagnostic(
8453 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8454 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8455 getSpecifierRange(startSpecifier, specifierLen));
8456}
8457
8458void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8459 unsigned posLen) {
8460 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8461 SourceLocation()))
8462 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8463 getLocationOfByte(startPos),
8464 /*IsStringLocation*/ true,
8465 getSpecifierRange(startPos, posLen));
8466}
8467
8468void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8469 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8470 // The presence of a null character is likely an error.
8471 EmitFormatDiagnostic(
8472 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8473 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8474 getFormatStringRange());
8475 }
8476}
8477
8478// Note that this may return NULL if there was an error parsing or building
8479// one of the argument expressions.
8480const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8481 return Args[FirstDataArg + i];
8482}
8483
8484void CheckFormatHandler::DoneProcessing() {
8485 // Does the number of data arguments exceed the number of
8486 // format conversions in the format string?
8487 if (HasFormatArguments()) {
8488 // Find any arguments that weren't covered.
8489 CoveredArgs.flip();
8490 signed notCoveredArg = CoveredArgs.find_first();
8491 if (notCoveredArg >= 0) {
8492 assert((unsigned)notCoveredArg < NumDataArgs);
8493 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8494 } else {
8495 UncoveredArg.setAllCovered();
8496 }
8497 }
8498}
8499
8500void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8501 const Expr *ArgExpr) {
8502 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8503
8504 if (!ArgExpr)
8505 return;
8506
8507 SourceLocation Loc = ArgExpr->getBeginLoc();
8508
8509 if (S.getSourceManager().isInSystemMacro(Loc))
8510 return;
8511
8512 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8513 for (auto E : DiagnosticExprs)
8514 PDiag << E->getSourceRange();
8515
8516 CheckFormatHandler::EmitFormatDiagnostic(
8517 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8518 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8519}
8520
8521bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8522 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8523 unsigned specifierLen, const char *csStart, unsigned csLen) {
8524 bool keepGoing = true;
8525 if (argIndex < NumDataArgs) {
8526 // Consider the argument coverered, even though the specifier doesn't
8527 // make sense.
8528 CoveredArgs.set(argIndex);
8529 } else {
8530 // If argIndex exceeds the number of data arguments we
8531 // don't issue a warning because that is just a cascade of warnings (and
8532 // they may have intended '%%' anyway). We don't want to continue processing
8533 // the format string after this point, however, as we will like just get
8534 // gibberish when trying to match arguments.
8535 keepGoing = false;
8536 }
8537
8538 StringRef Specifier(csStart, csLen);
8539
8540 // If the specifier in non-printable, it could be the first byte of a UTF-8
8541 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8542 // hex value.
8543 std::string CodePointStr;
8544 if (!llvm::sys::locale::isPrint(*csStart)) {
8545 llvm::UTF32 CodePoint;
8546 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8547 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8548 llvm::ConversionResult Result =
8549 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8550
8551 if (Result != llvm::conversionOK) {
8552 unsigned char FirstChar = *csStart;
8553 CodePoint = (llvm::UTF32)FirstChar;
8554 }
8555
8556 llvm::raw_string_ostream OS(CodePointStr);
8557 if (CodePoint < 256)
8558 OS << "\\x" << llvm::format("%02x", CodePoint);
8559 else if (CodePoint <= 0xFFFF)
8560 OS << "\\u" << llvm::format("%04x", CodePoint);
8561 else
8562 OS << "\\U" << llvm::format("%08x", CodePoint);
8563 Specifier = CodePointStr;
8564 }
8565
8566 EmitFormatDiagnostic(
8567 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8568 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8569
8570 return keepGoing;
8571}
8572
8573void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8574 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8575 EmitFormatDiagnostic(
8576 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8577 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8578}
8579
8580bool CheckFormatHandler::CheckNumArgs(
8583 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8584
8585 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8586 PartialDiagnostic PDiag =
8588 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8589 << (argIndex + 1) << NumDataArgs)
8590 : S.PDiag(diag::warn_printf_insufficient_data_args);
8591 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8592 /*IsStringLocation*/ true,
8593 getSpecifierRange(startSpecifier, specifierLen));
8594
8595 // Since more arguments than conversion tokens are given, by extension
8596 // all arguments are covered, so mark this as so.
8597 UncoveredArg.setAllCovered();
8598 return false;
8599 }
8600 return true;
8601}
8602
8603template <typename Range>
8604void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8605 SourceLocation Loc,
8606 bool IsStringLocation,
8607 Range StringRange,
8608 ArrayRef<FixItHint> FixIt) {
8609 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8610 IsStringLocation, StringRange, FixIt);
8611}
8612
8613/// If the format string is not within the function call, emit a note
8614/// so that the function call and string are in diagnostic messages.
8615///
8616/// \param InFunctionCall if true, the format string is within the function
8617/// call and only one diagnostic message will be produced. Otherwise, an
8618/// extra note will be emitted pointing to location of the format string.
8619///
8620/// \param ArgumentExpr the expression that is passed as the format string
8621/// argument in the function call. Used for getting locations when two
8622/// diagnostics are emitted.
8623///
8624/// \param PDiag the callee should already have provided any strings for the
8625/// diagnostic message. This function only adds locations and fixits
8626/// to diagnostics.
8627///
8628/// \param Loc primary location for diagnostic. If two diagnostics are
8629/// required, one will be at Loc and a new SourceLocation will be created for
8630/// the other one.
8631///
8632/// \param IsStringLocation if true, Loc points to the format string should be
8633/// used for the note. Otherwise, Loc points to the argument list and will
8634/// be used with PDiag.
8635///
8636/// \param StringRange some or all of the string to highlight. This is
8637/// templated so it can accept either a CharSourceRange or a SourceRange.
8638///
8639/// \param FixIt optional fix it hint for the format string.
8640template <typename Range>
8641void CheckFormatHandler::EmitFormatDiagnostic(
8642 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8643 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8644 Range StringRange, ArrayRef<FixItHint> FixIt) {
8645 if (InFunctionCall) {
8646 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8647 D << StringRange;
8648 D << FixIt;
8649 } else {
8650 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8651 << ArgumentExpr->getSourceRange();
8652
8654 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8655 diag::note_format_string_defined);
8656
8657 Note << StringRange;
8658 Note << FixIt;
8659 }
8660}
8661
8662//===--- CHECK: Printf format string checking -----------------------------===//
8663
8664namespace {
8665
8666class CheckPrintfHandler : public CheckFormatHandler {
8667public:
8668 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8669 const Expr *origFormatExpr, const FormatStringType type,
8670 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8671 const char *beg, Sema::FormatArgumentPassingKind APK,
8672 ArrayRef<const Expr *> Args, unsigned formatIdx,
8673 bool inFunctionCall, VariadicCallType CallType,
8674 llvm::SmallBitVector &CheckedVarArgs,
8675 UncoveredArgHandler &UncoveredArg)
8676 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8677 numDataArgs, beg, APK, Args, formatIdx,
8678 inFunctionCall, CallType, CheckedVarArgs,
8679 UncoveredArg) {}
8680
8681 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8682
8683 /// Returns true if '%@' specifiers are allowed in the format string.
8684 bool allowsObjCArg() const {
8685 return FSType == FormatStringType::NSString ||
8686 FSType == FormatStringType::OSLog ||
8687 FSType == FormatStringType::OSTrace;
8688 }
8689
8690 bool HandleInvalidPrintfConversionSpecifier(
8691 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8692 unsigned specifierLen) override;
8693
8694 void handleInvalidMaskType(StringRef MaskType) override;
8695
8696 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8697 const char *startSpecifier, unsigned specifierLen,
8698 const TargetInfo &Target) override;
8699 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8700 const char *StartSpecifier, unsigned SpecifierLen,
8701 const Expr *E);
8702
8703 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8704 unsigned k, const char *startSpecifier,
8705 unsigned specifierLen);
8706 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8707 const analyze_printf::OptionalAmount &Amt,
8708 unsigned type, const char *startSpecifier,
8709 unsigned specifierLen);
8710 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8711 const analyze_printf::OptionalFlag &flag,
8712 const char *startSpecifier, unsigned specifierLen);
8713 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8714 const analyze_printf::OptionalFlag &ignoredFlag,
8715 const analyze_printf::OptionalFlag &flag,
8716 const char *startSpecifier, unsigned specifierLen);
8717 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8718
8719 void HandleEmptyObjCModifierFlag(const char *startFlag,
8720 unsigned flagLen) override;
8721
8722 void HandleInvalidObjCModifierFlag(const char *startFlag,
8723 unsigned flagLen) override;
8724
8725 void
8726 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8727 const char *flagsEnd,
8728 const char *conversionPosition) override;
8729};
8730
8731/// Keeps around the information needed to verify that two specifiers are
8732/// compatible.
8733class EquatableFormatArgument {
8734public:
8735 enum SpecifierSensitivity : unsigned {
8736 SS_None,
8737 SS_Private,
8738 SS_Public,
8739 SS_Sensitive
8740 };
8741
8742 enum FormatArgumentRole : unsigned {
8743 FAR_Data,
8744 FAR_FieldWidth,
8745 FAR_Precision,
8746 FAR_Auxiliary, // FreeBSD kernel %b and %D
8747 };
8748
8749private:
8750 analyze_format_string::ArgType ArgType;
8751 analyze_format_string::LengthModifier LengthMod;
8752 StringRef SpecifierLetter;
8753 CharSourceRange Range;
8754 SourceLocation ElementLoc;
8755 FormatArgumentRole Role : 2;
8756 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8757 unsigned Position : 14;
8758 unsigned ModifierFor : 14; // not set for FAR_Data
8759
8760 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8761 bool InFunctionCall) const;
8762
8763public:
8764 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8765 analyze_format_string::LengthModifier LengthMod,
8766 StringRef SpecifierLetter,
8767 analyze_format_string::ArgType ArgType,
8768 FormatArgumentRole Role,
8769 SpecifierSensitivity Sensitivity, unsigned Position,
8770 unsigned ModifierFor)
8771 : ArgType(ArgType), LengthMod(LengthMod),
8772 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8773 Role(Role), Sensitivity(Sensitivity), Position(Position),
8774 ModifierFor(ModifierFor) {}
8775
8776 unsigned getPosition() const { return Position; }
8777 SourceLocation getSourceLocation() const { return ElementLoc; }
8778 CharSourceRange getSourceRange() const { return Range; }
8779 analyze_format_string::LengthModifier getLengthModifier() const {
8780 return LengthMod;
8781 }
8782 void setModifierFor(unsigned V) { ModifierFor = V; }
8783
8784 std::string buildFormatSpecifier() const {
8785 std::string result;
8786 llvm::raw_string_ostream(result)
8787 << getLengthModifier().toString() << SpecifierLetter;
8788 return result;
8789 }
8790
8791 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8792 const Expr *FmtExpr, bool InFunctionCall) const;
8793};
8794
8795/// Turns format strings into lists of EquatableSpecifier objects.
8796class DecomposePrintfHandler : public CheckPrintfHandler {
8797 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8798 bool HadError;
8799
8800 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8801 const Expr *origFormatExpr,
8802 const FormatStringType type, unsigned firstDataArg,
8803 unsigned numDataArgs, bool isObjC, const char *beg,
8805 ArrayRef<const Expr *> Args, unsigned formatIdx,
8806 bool inFunctionCall, VariadicCallType CallType,
8807 llvm::SmallBitVector &CheckedVarArgs,
8808 UncoveredArgHandler &UncoveredArg,
8809 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8810 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8811 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8812 inFunctionCall, CallType, CheckedVarArgs,
8813 UncoveredArg),
8814 Specs(Specs), HadError(false) {}
8815
8816public:
8817 static bool
8818 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8819 FormatStringType type, bool IsObjC, bool InFunctionCall,
8820 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8821
8822 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8823 const char *startSpecifier,
8824 unsigned specifierLen,
8825 const TargetInfo &Target) override;
8826};
8827
8828} // namespace
8829
8830bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8831 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8832 unsigned specifierLen) {
8835
8836 return HandleInvalidConversionSpecifier(
8837 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8838 specifierLen, CS.getStart(), CS.getLength());
8839}
8840
8841void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8842 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8843}
8844
8845// Error out if struct or complex type argments are passed to os_log.
8847 QualType T) {
8848 if (FSType != FormatStringType::OSLog)
8849 return false;
8850 return T->isRecordType() || T->isComplexType();
8851}
8852
8853bool CheckPrintfHandler::HandleAmount(
8854 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8855 const char *startSpecifier, unsigned specifierLen) {
8856 if (Amt.hasDataArgument()) {
8857 if (HasFormatArguments()) {
8858 unsigned argIndex = Amt.getArgIndex();
8859 if (argIndex >= NumDataArgs) {
8860 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8861 << k,
8862 getLocationOfByte(Amt.getStart()),
8863 /*IsStringLocation*/ true,
8864 getSpecifierRange(startSpecifier, specifierLen));
8865 // Don't do any more checking. We will just emit
8866 // spurious errors.
8867 return false;
8868 }
8869
8870 // Type check the data argument. It should be an 'int'.
8871 // Although not in conformance with C99, we also allow the argument to be
8872 // an 'unsigned int' as that is a reasonably safe case. GCC also
8873 // doesn't emit a warning for that case.
8874 CoveredArgs.set(argIndex);
8875 const Expr *Arg = getDataArg(argIndex);
8876 if (!Arg)
8877 return false;
8878
8879 QualType T = Arg->getType();
8880
8881 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8882 assert(AT.isValid());
8883
8884 if (!AT.matchesType(S.Context, T)) {
8885 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8886 ? diag::err_printf_asterisk_wrong_type
8887 : diag::warn_printf_asterisk_wrong_type;
8888 EmitFormatDiagnostic(S.PDiag(DiagID)
8890 << T << Arg->getSourceRange(),
8891 getLocationOfByte(Amt.getStart()),
8892 /*IsStringLocation*/ true,
8893 getSpecifierRange(startSpecifier, specifierLen));
8894 // Don't do any more checking. We will just emit
8895 // spurious errors.
8896 return false;
8897 }
8898 }
8899 }
8900 return true;
8901}
8902
8903void CheckPrintfHandler::HandleInvalidAmount(
8905 const analyze_printf::OptionalAmount &Amt, unsigned type,
8906 const char *startSpecifier, unsigned specifierLen) {
8909
8910 FixItHint fixit =
8913 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8914 : FixItHint();
8915
8916 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8917 << type << CS.toString(),
8918 getLocationOfByte(Amt.getStart()),
8919 /*IsStringLocation*/ true,
8920 getSpecifierRange(startSpecifier, specifierLen), fixit);
8921}
8922
8923void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8924 const analyze_printf::OptionalFlag &flag,
8925 const char *startSpecifier,
8926 unsigned specifierLen) {
8927 // Warn about pointless flag with a fixit removal.
8930 EmitFormatDiagnostic(
8931 S.PDiag(diag::warn_printf_nonsensical_flag)
8932 << flag.toString() << CS.toString(),
8933 getLocationOfByte(flag.getPosition()),
8934 /*IsStringLocation*/ true,
8935 getSpecifierRange(startSpecifier, specifierLen),
8936 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8937}
8938
8939void CheckPrintfHandler::HandleIgnoredFlag(
8941 const analyze_printf::OptionalFlag &ignoredFlag,
8942 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8943 unsigned specifierLen) {
8944 // Warn about ignored flag with a fixit removal.
8945 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8946 << ignoredFlag.toString() << flag.toString(),
8947 getLocationOfByte(ignoredFlag.getPosition()),
8948 /*IsStringLocation*/ true,
8949 getSpecifierRange(startSpecifier, specifierLen),
8951 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8952}
8953
8954void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8955 unsigned flagLen) {
8956 // Warn about an empty flag.
8957 EmitFormatDiagnostic(
8958 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8959 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8960}
8961
8962void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8963 unsigned flagLen) {
8964 // Warn about an invalid flag.
8965 auto Range = getSpecifierRange(startFlag, flagLen);
8966 StringRef flag(startFlag, flagLen);
8967 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8968 getLocationOfByte(startFlag),
8969 /*IsStringLocation*/ true, Range,
8971}
8972
8973void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8974 const char *flagsStart, const char *flagsEnd,
8975 const char *conversionPosition) {
8976 // Warn about using '[...]' without a '@' conversion.
8977 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8978 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8979 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8980 getLocationOfByte(conversionPosition),
8981 /*IsStringLocation*/ true, Range,
8983}
8984
8985void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8986 const Expr *FmtExpr,
8987 bool InFunctionCall) const {
8988 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8989 ElementLoc, true, Range);
8990}
8991
8992bool EquatableFormatArgument::VerifyCompatible(
8993 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8994 bool InFunctionCall) const {
8996 if (Role != Other.Role) {
8997 // diagnose and stop
8998 EmitDiagnostic(
8999 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
9000 FmtExpr, InFunctionCall);
9001 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
9002 return false;
9003 }
9004
9005 if (Role != FAR_Data) {
9006 if (ModifierFor != Other.ModifierFor) {
9007 // diagnose and stop
9008 EmitDiagnostic(S,
9009 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
9010 << (ModifierFor + 1) << (Other.ModifierFor + 1),
9011 FmtExpr, InFunctionCall);
9012 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
9013 return false;
9014 }
9015 return true;
9016 }
9017
9018 bool HadError = false;
9019 if (Sensitivity != Other.Sensitivity) {
9020 // diagnose and continue
9021 EmitDiagnostic(S,
9022 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
9023 << Sensitivity << Other.Sensitivity,
9024 FmtExpr, InFunctionCall);
9025 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9026 << 0 << Other.Range;
9027 }
9028
9029 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
9030 case MK::Match:
9031 break;
9032
9033 case MK::MatchPromotion:
9034 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
9035 // MatchPromotion is treated as a failure by format_matches.
9036 case MK::NoMatch:
9037 case MK::NoMatchTypeConfusion:
9038 case MK::NoMatchPromotionTypeConfusion:
9039 EmitDiagnostic(S,
9040 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
9041 << buildFormatSpecifier()
9042 << Other.buildFormatSpecifier(),
9043 FmtExpr, InFunctionCall);
9044 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9045 << 0 << Other.Range;
9046 break;
9047
9048 case MK::NoMatchPedantic:
9049 EmitDiagnostic(S,
9050 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
9051 << buildFormatSpecifier()
9052 << Other.buildFormatSpecifier(),
9053 FmtExpr, InFunctionCall);
9054 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9055 << 0 << Other.Range;
9056 break;
9057
9058 case MK::NoMatchSignedness:
9059 EmitDiagnostic(S,
9060 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
9061 << buildFormatSpecifier()
9062 << Other.buildFormatSpecifier(),
9063 FmtExpr, InFunctionCall);
9064 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9065 << 0 << Other.Range;
9066 break;
9067 }
9068 return !HadError;
9069}
9070
9071bool DecomposePrintfHandler::GetSpecifiers(
9072 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
9073 FormatStringType Type, bool IsObjC, bool InFunctionCall,
9075 StringRef Data = FSL->getString();
9076 const char *Str = Data.data();
9077 llvm::SmallBitVector BV;
9078 UncoveredArgHandler UA;
9079 const Expr *PrintfArgs[] = {FSL->getFormatString()};
9080 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
9081 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
9082 InFunctionCall, VariadicCallType::DoesNotApply, BV,
9083 UA, Args);
9084
9086 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
9088 H.DoneProcessing();
9089 if (H.HadError)
9090 return false;
9091
9092 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
9093 const EquatableFormatArgument &B) {
9094 return A.getPosition() < B.getPosition();
9095 });
9096 return true;
9097}
9098
9099bool DecomposePrintfHandler::HandlePrintfSpecifier(
9100 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9101 unsigned specifierLen, const TargetInfo &Target) {
9102 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
9103 specifierLen, Target)) {
9104 HadError = true;
9105 return false;
9106 }
9107
9108 // Do not add any specifiers to the list for %%. This is possibly incorrect
9109 // if using a precision/width with a data argument, but that combination is
9110 // meaningless and we wouldn't know which format to attach the
9111 // precision/width to.
9112 const auto &CS = FS.getConversionSpecifier();
9114 return true;
9115
9116 // have to patch these to have the right ModifierFor if they are used
9117 const unsigned Unset = ~0;
9118 unsigned FieldWidthIndex = Unset;
9119 unsigned PrecisionIndex = Unset;
9120
9121 // field width?
9122 const auto &FieldWidth = FS.getFieldWidth();
9123 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9124 FieldWidthIndex = Specs.size();
9125 Specs.emplace_back(
9126 getSpecifierRange(startSpecifier, specifierLen),
9127 getLocationOfByte(FieldWidth.getStart()),
9128 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
9129 FieldWidth.getArgType(S.Context),
9130 EquatableFormatArgument::FAR_FieldWidth,
9131 EquatableFormatArgument::SS_None,
9132 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9133 : FieldWidthIndex,
9134 0);
9135 }
9136 // precision?
9137 const auto &Precision = FS.getPrecision();
9138 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9139 PrecisionIndex = Specs.size();
9140 Specs.emplace_back(
9141 getSpecifierRange(startSpecifier, specifierLen),
9142 getLocationOfByte(Precision.getStart()),
9143 analyze_format_string::LengthModifier(), Precision.getCharacters(),
9144 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
9145 EquatableFormatArgument::SS_None,
9146 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9147 : PrecisionIndex,
9148 0);
9149 }
9150
9151 // this specifier
9152 unsigned SpecIndex =
9153 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9154 if (FieldWidthIndex != Unset)
9155 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9156 if (PrecisionIndex != Unset)
9157 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9158
9159 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9160 if (FS.isPrivate())
9161 Sensitivity = EquatableFormatArgument::SS_Private;
9162 else if (FS.isPublic())
9163 Sensitivity = EquatableFormatArgument::SS_Public;
9164 else if (FS.isSensitive())
9165 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9166 else
9167 Sensitivity = EquatableFormatArgument::SS_None;
9168
9169 Specs.emplace_back(
9170 getSpecifierRange(startSpecifier, specifierLen),
9171 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
9172 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
9173 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9174
9175 // auxiliary argument?
9178 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9179 getLocationOfByte(CS.getStart()),
9181 CS.getCharacters(),
9183 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9184 SpecIndex + 1, SpecIndex);
9185 }
9186 return true;
9187}
9188
9189// Determines if the specified is a C++ class or struct containing
9190// a member with the specified name and kind (e.g. a CXXMethodDecl named
9191// "c_str()").
9192template<typename MemberKind>
9194CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9195 auto *RD = Ty->getAsCXXRecordDecl();
9197
9198 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9199 return Results;
9200
9201 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9203 R.suppressDiagnostics();
9204
9205 // We just need to include all members of the right kind turned up by the
9206 // filter, at this point.
9207 if (S.LookupQualifiedName(R, RD))
9208 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9209 NamedDecl *decl = (*I)->getUnderlyingDecl();
9210 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9211 Results.insert(FK);
9212 }
9213 return Results;
9214}
9215
9216/// Check if we could call '.c_str()' on an object.
9217///
9218/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9219/// allow the call, or if it would be ambiguous).
9221 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9222
9223 MethodSet Results =
9224 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9225 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9226 MI != ME; ++MI)
9227 if ((*MI)->getMinRequiredArguments() == 0)
9228 return true;
9229 return false;
9230}
9231
9232// Check if a (w)string was passed when a (w)char* was needed, and offer a
9233// better diagnostic if so. AT is assumed to be valid.
9234// Returns true when a c_str() conversion method is found.
9235bool CheckPrintfHandler::checkForCStrMembers(
9236 const analyze_printf::ArgType &AT, const Expr *E) {
9237 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9238
9239 MethodSet Results =
9241
9242 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9243 MI != ME; ++MI) {
9244 const CXXMethodDecl *Method = *MI;
9245 if (Method->getMinRequiredArguments() == 0 &&
9246 AT.matchesType(S.Context, Method->getReturnType())) {
9247 // FIXME: Suggest parens if the expression needs them.
9249 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9250 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9251 return true;
9252 }
9253 }
9254
9255 return false;
9256}
9257
9258bool CheckPrintfHandler::HandlePrintfSpecifier(
9259 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9260 unsigned specifierLen, const TargetInfo &Target) {
9261 using namespace analyze_format_string;
9262 using namespace analyze_printf;
9263
9264 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9265
9266 if (FS.consumesDataArgument()) {
9267 if (atFirstArg) {
9268 atFirstArg = false;
9269 usesPositionalArgs = FS.usesPositionalArg();
9270 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9271 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9272 startSpecifier, specifierLen);
9273 return false;
9274 }
9275 }
9276
9277 // First check if the field width, precision, and conversion specifier
9278 // have matching data arguments.
9279 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9280 specifierLen)) {
9281 return false;
9282 }
9283
9284 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9285 specifierLen)) {
9286 return false;
9287 }
9288
9289 if (!CS.consumesDataArgument()) {
9290 // FIXME: Technically specifying a precision or field width here
9291 // makes no sense. Worth issuing a warning at some point.
9292 return true;
9293 }
9294
9295 // Consume the argument.
9296 unsigned argIndex = FS.getArgIndex();
9297 if (argIndex < NumDataArgs) {
9298 // The check to see if the argIndex is valid will come later.
9299 // We set the bit here because we may exit early from this
9300 // function if we encounter some other error.
9301 CoveredArgs.set(argIndex);
9302 }
9303
9304 // FreeBSD kernel extensions.
9305 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9306 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9307 // We need at least two arguments.
9308 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9309 return false;
9310
9311 if (HasFormatArguments()) {
9312 // Claim the second argument.
9313 CoveredArgs.set(argIndex + 1);
9314
9315 // Type check the first argument (int for %b, pointer for %D)
9316 const Expr *Ex = getDataArg(argIndex);
9317 const analyze_printf::ArgType &AT =
9318 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9319 ? ArgType(S.Context.IntTy)
9320 : ArgType::CPointerTy;
9321 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9322 EmitFormatDiagnostic(
9323 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9324 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9325 << false << Ex->getSourceRange(),
9326 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9327 getSpecifierRange(startSpecifier, specifierLen));
9328
9329 // Type check the second argument (char * for both %b and %D)
9330 Ex = getDataArg(argIndex + 1);
9332 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9333 EmitFormatDiagnostic(
9334 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9335 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9336 << false << Ex->getSourceRange(),
9337 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9338 getSpecifierRange(startSpecifier, specifierLen));
9339 }
9340 return true;
9341 }
9342
9343 // Check for using an Objective-C specific conversion specifier
9344 // in a non-ObjC literal.
9345 if (!allowsObjCArg() && CS.isObjCArg()) {
9346 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9347 specifierLen);
9348 }
9349
9350 // %P can only be used with os_log.
9351 if (FSType != FormatStringType::OSLog &&
9352 CS.getKind() == ConversionSpecifier::PArg) {
9353 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9354 specifierLen);
9355 }
9356
9357 // %n is not allowed with os_log.
9358 if (FSType == FormatStringType::OSLog &&
9359 CS.getKind() == ConversionSpecifier::nArg) {
9360 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9361 getLocationOfByte(CS.getStart()),
9362 /*IsStringLocation*/ false,
9363 getSpecifierRange(startSpecifier, specifierLen));
9364
9365 return true;
9366 }
9367
9368 // Only scalars are allowed for os_trace.
9369 if (FSType == FormatStringType::OSTrace &&
9370 (CS.getKind() == ConversionSpecifier::PArg ||
9371 CS.getKind() == ConversionSpecifier::sArg ||
9372 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9373 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9374 specifierLen);
9375 }
9376
9377 // Check for use of public/private annotation outside of os_log().
9378 if (FSType != FormatStringType::OSLog) {
9379 if (FS.isPublic().isSet()) {
9380 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9381 << "public",
9382 getLocationOfByte(FS.isPublic().getPosition()),
9383 /*IsStringLocation*/ false,
9384 getSpecifierRange(startSpecifier, specifierLen));
9385 }
9386 if (FS.isPrivate().isSet()) {
9387 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9388 << "private",
9389 getLocationOfByte(FS.isPrivate().getPosition()),
9390 /*IsStringLocation*/ false,
9391 getSpecifierRange(startSpecifier, specifierLen));
9392 }
9393 }
9394
9395 const llvm::Triple &Triple = Target.getTriple();
9396 if (CS.getKind() == ConversionSpecifier::nArg &&
9397 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9398 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9399 getLocationOfByte(CS.getStart()),
9400 /*IsStringLocation*/ false,
9401 getSpecifierRange(startSpecifier, specifierLen));
9402 }
9403
9404 // Check for invalid use of field width
9405 if (!FS.hasValidFieldWidth()) {
9406 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9407 startSpecifier, specifierLen);
9408 }
9409
9410 // Check for invalid use of precision
9411 if (!FS.hasValidPrecision()) {
9412 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9413 startSpecifier, specifierLen);
9414 }
9415
9416 // Precision is mandatory for %P specifier.
9417 if (CS.getKind() == ConversionSpecifier::PArg &&
9419 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9420 getLocationOfByte(startSpecifier),
9421 /*IsStringLocation*/ false,
9422 getSpecifierRange(startSpecifier, specifierLen));
9423 }
9424
9425 // Check each flag does not conflict with any other component.
9427 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9428 if (!FS.hasValidLeadingZeros())
9429 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9430 if (!FS.hasValidPlusPrefix())
9431 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9432 if (!FS.hasValidSpacePrefix())
9433 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9434 if (!FS.hasValidAlternativeForm())
9435 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9436 if (!FS.hasValidLeftJustified())
9437 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9438
9439 // Check that flags are not ignored by another flag
9440 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9441 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9442 startSpecifier, specifierLen);
9443 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9444 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9445 startSpecifier, specifierLen);
9446
9447 // Check the length modifier is valid with the given conversion specifier.
9449 S.getLangOpts()))
9450 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9451 diag::warn_format_nonsensical_length);
9452 else if (!FS.hasStandardLengthModifier())
9453 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9455 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9456 diag::warn_format_non_standard_conversion_spec);
9457
9459 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9460
9461 // The remaining checks depend on the data arguments.
9462 if (!HasFormatArguments())
9463 return true;
9464
9465 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9466 return false;
9467
9468 const Expr *Arg = getDataArg(argIndex);
9469 if (!Arg)
9470 return true;
9471
9472 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9473}
9474
9475static bool requiresParensToAddCast(const Expr *E) {
9476 // FIXME: We should have a general way to reason about operator
9477 // precedence and whether parens are actually needed here.
9478 // Take care of a few common cases where they aren't.
9479 const Expr *Inside = E->IgnoreImpCasts();
9480 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9481 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9482
9483 switch (Inside->getStmtClass()) {
9484 case Stmt::ArraySubscriptExprClass:
9485 case Stmt::CallExprClass:
9486 case Stmt::CharacterLiteralClass:
9487 case Stmt::CXXBoolLiteralExprClass:
9488 case Stmt::DeclRefExprClass:
9489 case Stmt::FloatingLiteralClass:
9490 case Stmt::IntegerLiteralClass:
9491 case Stmt::MemberExprClass:
9492 case Stmt::ObjCArrayLiteralClass:
9493 case Stmt::ObjCBoolLiteralExprClass:
9494 case Stmt::ObjCBoxedExprClass:
9495 case Stmt::ObjCDictionaryLiteralClass:
9496 case Stmt::ObjCEncodeExprClass:
9497 case Stmt::ObjCIvarRefExprClass:
9498 case Stmt::ObjCMessageExprClass:
9499 case Stmt::ObjCPropertyRefExprClass:
9500 case Stmt::ObjCStringLiteralClass:
9501 case Stmt::ObjCSubscriptRefExprClass:
9502 case Stmt::ParenExprClass:
9503 case Stmt::StringLiteralClass:
9504 case Stmt::UnaryOperatorClass:
9505 return false;
9506 default:
9507 return true;
9508 }
9509}
9510
9511static std::pair<QualType, StringRef>
9512shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9513 const Expr *E) {
9514 // Use a 'while' to peel off layers of typedefs.
9515 QualType TyTy = IntendedTy;
9516 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9517 StringRef Name = UserTy->getDecl()->getName();
9518 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9519 .Case("CFIndex", Context.getNSIntegerType())
9520 .Case("NSInteger", Context.getNSIntegerType())
9521 .Case("NSUInteger", Context.getNSUIntegerType())
9522 .Case("SInt32", Context.IntTy)
9523 .Case("UInt32", Context.UnsignedIntTy)
9524 .Default(QualType());
9525
9526 if (!CastTy.isNull())
9527 return std::make_pair(CastTy, Name);
9528
9529 TyTy = UserTy->desugar();
9530 }
9531
9532 // Strip parens if necessary.
9533 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9534 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9535 PE->getSubExpr());
9536
9537 // If this is a conditional expression, then its result type is constructed
9538 // via usual arithmetic conversions and thus there might be no necessary
9539 // typedef sugar there. Recurse to operands to check for NSInteger &
9540 // Co. usage condition.
9541 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9542 QualType TrueTy, FalseTy;
9543 StringRef TrueName, FalseName;
9544
9545 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9546 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9547 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9548 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9549
9550 if (TrueTy == FalseTy)
9551 return std::make_pair(TrueTy, TrueName);
9552 else if (TrueTy.isNull())
9553 return std::make_pair(FalseTy, FalseName);
9554 else if (FalseTy.isNull())
9555 return std::make_pair(TrueTy, TrueName);
9556 }
9557
9558 return std::make_pair(QualType(), StringRef());
9559}
9560
9561/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9562/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9563/// type do not count.
9565 const ImplicitCastExpr *ICE) {
9566 QualType From = ICE->getSubExpr()->getType();
9567 QualType To = ICE->getType();
9568 // It's an integer promotion if the destination type is the promoted
9569 // source type.
9570 if (ICE->getCastKind() == CK_IntegralCast &&
9572 S.Context.getPromotedIntegerType(From) == To)
9573 return true;
9574 // Look through vector types, since we do default argument promotion for
9575 // those in OpenCL.
9576 if (const auto *VecTy = From->getAs<ExtVectorType>())
9577 From = VecTy->getElementType();
9578 if (const auto *VecTy = To->getAs<ExtVectorType>())
9579 To = VecTy->getElementType();
9580 // It's a floating promotion if the source type is a lower rank.
9581 return ICE->getCastKind() == CK_FloatingCast &&
9582 S.Context.getFloatingTypeOrder(From, To) < 0;
9583}
9584
9587 DiagnosticsEngine &Diags, SourceLocation Loc) {
9589 if (Diags.isIgnored(
9590 diag::warn_format_conversion_argument_type_mismatch_signedness,
9591 Loc) ||
9592 Diags.isIgnored(
9593 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9594 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9596 }
9597 }
9598 return Match;
9599}
9600
9601bool CheckPrintfHandler::checkFormatExpr(
9602 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9603 unsigned SpecifierLen, const Expr *E) {
9604 using namespace analyze_format_string;
9605 using namespace analyze_printf;
9606
9607 // Now type check the data expression that matches the
9608 // format specifier.
9609 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9610 if (!AT.isValid())
9611 return true;
9612
9613 QualType ExprTy = E->getType();
9614 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9615 ExprTy = TET->getUnderlyingExpr()->getType();
9616 }
9617
9618 if (const OverflowBehaviorType *OBT =
9619 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9620 ExprTy = OBT->getUnderlyingType();
9621
9622 // When using the format attribute in C++, you can receive a function or an
9623 // array that will necessarily decay to a pointer when passed to the final
9624 // format consumer. Apply decay before type comparison.
9625 if (ExprTy->canDecayToPointerType())
9626 ExprTy = S.Context.getDecayedType(ExprTy);
9627
9628 // Diagnose attempts to print a boolean value as a character. Unlike other
9629 // -Wformat diagnostics, this is fine from a type perspective, but it still
9630 // doesn't make sense.
9633 const CharSourceRange &CSR =
9634 getSpecifierRange(StartSpecifier, SpecifierLen);
9635 SmallString<4> FSString;
9636 llvm::raw_svector_ostream os(FSString);
9637 FS.toString(os);
9638 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9639 << FSString,
9640 E->getExprLoc(), false, CSR);
9641 return true;
9642 }
9643
9644 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9645 // dumping raw class data (like is-a pointer), not actual data.
9647 ExprTy->isObjCObjectPointerType()) {
9648 const CharSourceRange &CSR =
9649 getSpecifierRange(StartSpecifier, SpecifierLen);
9650 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9651 E->getExprLoc(), false, CSR);
9652 return true;
9653 }
9654
9655 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9656 return true;
9657
9658 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9660 ArgType::MatchKind OrigMatch = Match;
9661
9663 if (Match == ArgType::Match)
9664 return true;
9665
9666 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9667 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9668
9669 // Look through argument promotions for our error message's reported type.
9670 // This includes the integral and floating promotions, but excludes array
9671 // and function pointer decay (seeing that an argument intended to be a
9672 // string has type 'char [6]' is probably more confusing than 'char *') and
9673 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9674 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9675 if (isArithmeticArgumentPromotion(S, ICE)) {
9676 E = ICE->getSubExpr();
9677 ExprTy = E->getType();
9678
9679 // Check if we didn't match because of an implicit cast from a 'char'
9680 // or 'short' to an 'int'. This is done because printf is a varargs
9681 // function.
9682 if (ICE->getType() == S.Context.IntTy ||
9683 ICE->getType() == S.Context.UnsignedIntTy) {
9684 // All further checking is done on the subexpression
9685 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9686 if (OrigMatch == ArgType::NoMatchSignedness &&
9687 ImplicitMatch != ArgType::NoMatchSignedness)
9688 // If the original match was a signedness match this match on the
9689 // implicit cast type also need to be signedness match otherwise we
9690 // might introduce new unexpected warnings from -Wformat-signedness.
9691 return true;
9692 ImplicitMatch = handleFormatSignedness(
9693 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9694 if (ImplicitMatch == ArgType::Match)
9695 return true;
9696 }
9697 }
9698 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9699 // Special case for 'a', which has type 'int' in C.
9700 // Note, however, that we do /not/ want to treat multibyte constants like
9701 // 'MooV' as characters! This form is deprecated but still exists. In
9702 // addition, don't treat expressions as of type 'char' if one byte length
9703 // modifier is provided.
9704 if (ExprTy == S.Context.IntTy &&
9706 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9707 ExprTy = S.Context.CharTy;
9708 // To improve check results, we consider a character literal in C
9709 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9710 // more likely a type confusion situation, so we will suggest to
9711 // use '%hhd' instead by discarding the MatchPromotion.
9712 if (Match == ArgType::MatchPromotion)
9714 }
9715 }
9716 if (Match == ArgType::MatchPromotion) {
9717 // WG14 N2562 only clarified promotions in *printf
9718 // For NSLog in ObjC, just preserve -Wformat behavior
9719 if (!S.getLangOpts().ObjC &&
9720 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9721 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9722 return true;
9724 }
9725 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9726 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9727 Match = ImplicitMatch;
9728 assert(Match != ArgType::MatchPromotion);
9729
9730 // Look through unscoped enums to their underlying type.
9731 bool IsEnum = false;
9732 bool IsScopedEnum = false;
9733 QualType IntendedTy = ExprTy;
9734 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9735 IntendedTy = ED->getIntegerType();
9736 if (!ED->isScoped()) {
9737 ExprTy = IntendedTy;
9738 // This controls whether we're talking about the underlying type or not,
9739 // which we only want to do when it's an unscoped enum.
9740 IsEnum = true;
9741 } else {
9742 IsScopedEnum = true;
9743 }
9744 }
9745
9746 // %C in an Objective-C context prints a unichar, not a wchar_t.
9747 // If the argument is an integer of some kind, believe the %C and suggest
9748 // a cast instead of changing the conversion specifier.
9749 if (isObjCContext() &&
9751 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9752 !ExprTy->isCharType()) {
9753 // 'unichar' is defined as a typedef of unsigned short, but we should
9754 // prefer using the typedef if it is visible.
9755 IntendedTy = S.Context.UnsignedShortTy;
9756
9757 // While we are here, check if the value is an IntegerLiteral that happens
9758 // to be within the valid range.
9759 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9760 const llvm::APInt &V = IL->getValue();
9761 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9762 return true;
9763 }
9764
9765 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9767 if (S.LookupName(Result, S.getCurScope())) {
9768 NamedDecl *ND = Result.getFoundDecl();
9769 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9770 if (TD->getUnderlyingType() == IntendedTy)
9771 IntendedTy =
9773 /*Qualifier=*/std::nullopt, TD);
9774 }
9775 }
9776 }
9777
9778 // Special-case some of Darwin's platform-independence types by suggesting
9779 // casts to primitive types that are known to be large enough.
9780 bool ShouldNotPrintDirectly = false;
9781 StringRef CastTyName;
9782 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9783 QualType CastTy;
9784 std::tie(CastTy, CastTyName) =
9785 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9786 if (!CastTy.isNull()) {
9787 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9788 // (long in ASTContext). Only complain to pedants or when they're the
9789 // underlying type of a scoped enum (which always needs a cast).
9790 if (!IsScopedEnum &&
9791 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9792 (AT.isSizeT() || AT.isPtrdiffT()) &&
9793 AT.matchesType(S.Context, CastTy))
9795 IntendedTy = CastTy;
9796 ShouldNotPrintDirectly = true;
9797 }
9798 }
9799
9800 // We may be able to offer a FixItHint if it is a supported type.
9801 PrintfSpecifier fixedFS = FS;
9802 bool Success =
9803 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9804
9805 if (Success) {
9806 // Get the fix string from the fixed format specifier
9807 SmallString<16> buf;
9808 llvm::raw_svector_ostream os(buf);
9809 fixedFS.toString(os);
9810
9811 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9812
9813 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9814 unsigned Diag;
9815 switch (Match) {
9816 case ArgType::Match:
9819 llvm_unreachable("expected non-matching");
9821 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9822 break;
9824 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9825 break;
9827 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9828 break;
9829 case ArgType::NoMatch:
9830 Diag = diag::warn_format_conversion_argument_type_mismatch;
9831 break;
9832 }
9833
9834 // In this case, the specifier is wrong and should be changed to match
9835 // the argument.
9836 EmitFormatDiagnostic(S.PDiag(Diag)
9838 << IntendedTy << IsEnum << E->getSourceRange(),
9839 E->getBeginLoc(),
9840 /*IsStringLocation*/ false, SpecRange,
9841 FixItHint::CreateReplacement(SpecRange, os.str()));
9842 } else {
9843 // The canonical type for formatting this value is different from the
9844 // actual type of the expression. (This occurs, for example, with Darwin's
9845 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9846 // should be printed as 'long' for 64-bit compatibility.)
9847 // Rather than emitting a normal format/argument mismatch, we want to
9848 // add a cast to the recommended type (and correct the format string
9849 // if necessary). We should also do so for scoped enumerations.
9850 SmallString<16> CastBuf;
9851 llvm::raw_svector_ostream CastFix(CastBuf);
9852 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9853 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9854 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9855
9857 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9858 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9859 E->getExprLoc());
9860 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9861 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9862
9863 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9864 // If there's already a cast present, just replace it.
9865 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9866 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9867
9868 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9869 // If the expression has high enough precedence,
9870 // just write the C-style cast.
9871 Hints.push_back(
9872 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9873 } else {
9874 // Otherwise, add parens around the expression as well as the cast.
9875 CastFix << "(";
9876 Hints.push_back(
9877 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9878
9879 // We don't use getLocForEndOfToken because it returns invalid source
9880 // locations for macro expansions (by design).
9884 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9885 }
9886
9887 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9888 // The expression has a type that should not be printed directly.
9889 // We extract the name from the typedef because we don't want to show
9890 // the underlying type in the diagnostic.
9891 StringRef Name;
9892 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9893 Name = TypedefTy->getDecl()->getName();
9894 else
9895 Name = CastTyName;
9896 unsigned Diag = Match == ArgType::NoMatchPedantic
9897 ? diag::warn_format_argument_needs_cast_pedantic
9898 : diag::warn_format_argument_needs_cast;
9899 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9900 << E->getSourceRange(),
9901 E->getBeginLoc(), /*IsStringLocation=*/false,
9902 SpecRange, Hints);
9903 } else {
9904 // In this case, the expression could be printed using a different
9905 // specifier, but we've decided that the specifier is probably correct
9906 // and we should cast instead. Just use the normal warning message.
9907
9908 unsigned Diag =
9909 IsScopedEnum
9910 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9911 : diag::warn_format_conversion_argument_type_mismatch;
9912
9913 EmitFormatDiagnostic(
9914 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9915 << IsEnum << E->getSourceRange(),
9916 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9917 }
9918 }
9919 } else {
9920 const CharSourceRange &CSR =
9921 getSpecifierRange(StartSpecifier, SpecifierLen);
9922 // Since the warning for passing non-POD types to variadic functions
9923 // was deferred until now, we emit a warning for non-POD
9924 // arguments here.
9925 bool EmitTypeMismatch = false;
9926 // Record and complex type arguments cannot be code generated for os_log
9927 // and would crash CodeGen, so they are rejected with a hard error emitted
9928 // after the switch below.
9929 bool EmitOSLogError = false;
9930 switch (S.isValidVarArgType(ExprTy)) {
9931 case VarArgKind::Valid:
9933 unsigned Diag;
9934 switch (Match) {
9935 case ArgType::Match:
9938 llvm_unreachable("expected non-matching");
9940 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9941 break;
9943 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9944 break;
9946 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9947 break;
9948 case ArgType::NoMatch:
9949 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
9950 Diag = diag::warn_format_conversion_argument_type_mismatch;
9951 break;
9952 }
9953
9954 if (!EmitOSLogError)
9955 EmitFormatDiagnostic(
9956 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9957 << IsEnum << CSR << E->getSourceRange(),
9958 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9959 break;
9960 }
9963 if (CallType == VariadicCallType::DoesNotApply) {
9964 EmitTypeMismatch = true;
9965 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
9966 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9967 // does not stop compilation.
9968 EmitOSLogError = true;
9969 } else {
9970 EmitFormatDiagnostic(
9971 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9972 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9973 << AT.getRepresentativeTypeName(S.Context) << CSR
9974 << E->getSourceRange(),
9975 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9976 checkForCStrMembers(AT, E);
9977 }
9978 break;
9979
9981 if (CallType == VariadicCallType::DoesNotApply)
9982 EmitTypeMismatch = true;
9983 else if (ExprTy->isObjCObjectType())
9984 EmitFormatDiagnostic(
9985 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9986 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9987 << AT.getRepresentativeTypeName(S.Context) << CSR
9988 << E->getSourceRange(),
9989 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9990 else
9991 // FIXME: If this is an initializer list, suggest removing the braces
9992 // or inserting a cast to the target type.
9993 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9994 << isa<InitListExpr>(E) << ExprTy << CallType
9996 break;
9997 }
9998
9999 if (EmitOSLogError)
10000 EmitFormatDiagnostic(
10001 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
10002 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
10003 << CSR << E->getSourceRange(),
10004 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10005
10006 if (EmitTypeMismatch) {
10007 // The function is not variadic, so we do not generate warnings about
10008 // being allowed to pass that object as a variadic argument. Instead,
10009 // since there are inherently no printf specifiers for types which cannot
10010 // be passed as variadic arguments, emit a plain old specifier mismatch
10011 // argument.
10012 EmitFormatDiagnostic(
10013 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
10014 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
10015 << E->getSourceRange(),
10016 E->getBeginLoc(), false, CSR);
10017 }
10018
10019 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10020 "format string specifier index out of range");
10021 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10022 }
10023
10024 return true;
10025}
10026
10027//===--- CHECK: Scanf format string checking ------------------------------===//
10028
10029namespace {
10030
10031class CheckScanfHandler : public CheckFormatHandler {
10032public:
10033 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10034 const Expr *origFormatExpr, FormatStringType type,
10035 unsigned firstDataArg, unsigned numDataArgs,
10036 const char *beg, Sema::FormatArgumentPassingKind APK,
10037 ArrayRef<const Expr *> Args, unsigned formatIdx,
10038 bool inFunctionCall, VariadicCallType CallType,
10039 llvm::SmallBitVector &CheckedVarArgs,
10040 UncoveredArgHandler &UncoveredArg)
10041 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10042 numDataArgs, beg, APK, Args, formatIdx,
10043 inFunctionCall, CallType, CheckedVarArgs,
10044 UncoveredArg) {}
10045
10046 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10047 const char *startSpecifier,
10048 unsigned specifierLen) override;
10049
10050 bool
10051 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10052 const char *startSpecifier,
10053 unsigned specifierLen) override;
10054
10055 void HandleIncompleteScanList(const char *start, const char *end) override;
10056};
10057
10058} // namespace
10059
10060void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10061 const char *end) {
10062 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
10063 getLocationOfByte(end), /*IsStringLocation*/ true,
10064 getSpecifierRange(start, end - start));
10065}
10066
10067bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10068 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10069 unsigned specifierLen) {
10072
10073 return HandleInvalidConversionSpecifier(
10074 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
10075 specifierLen, CS.getStart(), CS.getLength());
10076}
10077
10078bool CheckScanfHandler::HandleScanfSpecifier(
10079 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10080 unsigned specifierLen) {
10081 using namespace analyze_scanf;
10082 using namespace analyze_format_string;
10083
10084 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10085
10086 // Handle case where '%' and '*' don't consume an argument. These shouldn't
10087 // be used to decide if we are using positional arguments consistently.
10088 if (FS.consumesDataArgument()) {
10089 if (atFirstArg) {
10090 atFirstArg = false;
10091 usesPositionalArgs = FS.usesPositionalArg();
10092 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
10093 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
10094 startSpecifier, specifierLen);
10095 return false;
10096 }
10097 }
10098
10099 // Check if the field with is non-zero.
10100 const OptionalAmount &Amt = FS.getFieldWidth();
10102 if (Amt.getConstantAmount() == 0) {
10103 const CharSourceRange &R =
10104 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
10105 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
10106 getLocationOfByte(Amt.getStart()),
10107 /*IsStringLocation*/ true, R,
10109 }
10110 }
10111
10112 if (!FS.consumesDataArgument()) {
10113 // FIXME: Technically specifying a precision or field width here
10114 // makes no sense. Worth issuing a warning at some point.
10115 return true;
10116 }
10117
10118 // Consume the argument.
10119 unsigned argIndex = FS.getArgIndex();
10120 if (argIndex < NumDataArgs) {
10121 // The check to see if the argIndex is valid will come later.
10122 // We set the bit here because we may exit early from this
10123 // function if we encounter some other error.
10124 CoveredArgs.set(argIndex);
10125 }
10126
10127 // Check the length modifier is valid with the given conversion specifier.
10129 S.getLangOpts()))
10130 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10131 diag::warn_format_nonsensical_length);
10132 else if (!FS.hasStandardLengthModifier())
10133 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10135 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10136 diag::warn_format_non_standard_conversion_spec);
10137
10139 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10140
10141 // The remaining checks depend on the data arguments.
10142 if (!HasFormatArguments())
10143 return true;
10144
10145 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10146 return false;
10147
10148 // Check that the argument type matches the format specifier.
10149 const Expr *Ex = getDataArg(argIndex);
10150 if (!Ex)
10151 return true;
10152
10154
10155 if (!AT.isValid()) {
10156 return true;
10157 }
10158
10159 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10160 return true;
10161
10163 AT.matchesType(S.Context, Ex->getType());
10166 return true;
10169
10170 ScanfSpecifier fixedFS = FS;
10171 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10172 S.getLangOpts(), S.Context);
10173
10174 unsigned Diag =
10175 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10176 : Signedness
10177 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10178 : diag::warn_format_conversion_argument_type_mismatch;
10179
10180 if (Success) {
10181 // Get the fix string from the fixed format specifier.
10182 SmallString<128> buf;
10183 llvm::raw_svector_ostream os(buf);
10184 fixedFS.toString(os);
10185
10186 EmitFormatDiagnostic(
10188 << Ex->getType() << false << Ex->getSourceRange(),
10189 Ex->getBeginLoc(),
10190 /*IsStringLocation*/ false,
10191 getSpecifierRange(startSpecifier, specifierLen),
10193 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10194 } else {
10195 EmitFormatDiagnostic(S.PDiag(Diag)
10197 << Ex->getType() << false << Ex->getSourceRange(),
10198 Ex->getBeginLoc(),
10199 /*IsStringLocation*/ false,
10200 getSpecifierRange(startSpecifier, specifierLen));
10201 }
10202
10203 return true;
10204}
10205
10206static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10208 const StringLiteral *Fmt,
10210 const Expr *FmtExpr, bool InFunctionCall) {
10211 bool HadError = false;
10212 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10213 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10214 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10215 // In positional-style format strings, the same specifier can appear
10216 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10217 // are sorted by getPosition(), and we process each range of equal
10218 // getPosition() values as one group.
10219 // RefArgs are taken from a string literal that was given to
10220 // attribute(format_matches), and if we got this far, we have already
10221 // verified that if it has positional specifiers that appear in multiple
10222 // locations, then they are all mutually compatible. What's left for us to
10223 // do is verify that all specifiers with the same position in FmtArgs are
10224 // compatible with the RefArgs specifiers. We check each specifier from
10225 // FmtArgs against the first member of the RefArgs group.
10226 for (; FmtIter < FmtEnd; ++FmtIter) {
10227 // Clang does not diagnose missing format specifiers in positional-style
10228 // strings (TODO: which it probably should do, as it is UB to skip over a
10229 // format argument). Skip specifiers if needed.
10230 if (FmtIter->getPosition() < RefIter->getPosition())
10231 continue;
10232
10233 // Delimits a new getPosition() value.
10234 if (FmtIter->getPosition() > RefIter->getPosition())
10235 break;
10236
10237 HadError |=
10238 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10239 }
10240
10241 // Jump RefIter to the start of the next group.
10242 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
10243 return Arg.getPosition() != RefIter->getPosition();
10244 });
10245 }
10246
10247 if (FmtIter < FmtEnd) {
10248 CheckFormatHandler::EmitFormatDiagnostic(
10249 S, InFunctionCall, FmtExpr,
10250 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10251 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
10252 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
10253 } else if (RefIter < RefEnd) {
10254 CheckFormatHandler::EmitFormatDiagnostic(
10255 S, InFunctionCall, FmtExpr,
10256 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10257 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
10258 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
10259 << 1 << RefIter->getSourceRange();
10260 }
10261 return !HadError;
10262}
10263
10265 Sema &S, const FormatStringLiteral *FExpr,
10266 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10268 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10269 bool inFunctionCall, VariadicCallType CallType,
10270 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10271 bool IgnoreStringsWithoutSpecifiers) {
10272 // CHECK: is the format string a wide literal?
10273 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10274 CheckFormatHandler::EmitFormatDiagnostic(
10275 S, inFunctionCall, Args[format_idx],
10276 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10277 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10278 return;
10279 }
10280
10281 // Str - The format string. NOTE: this is NOT null-terminated!
10282 StringRef StrRef = FExpr->getString();
10283 const char *Str = StrRef.data();
10284 // Account for cases where the string literal is truncated in a declaration.
10285 const ConstantArrayType *T =
10286 S.Context.getAsConstantArrayType(FExpr->getType());
10287 assert(T && "String literal not of constant array type!");
10288 size_t TypeSize = T->getZExtSize();
10289 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10290 const unsigned numDataArgs = Args.size() - firstDataArg;
10291
10292 if (IgnoreStringsWithoutSpecifiers &&
10294 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10295 return;
10296
10297 // Emit a warning if the string literal is truncated and does not contain an
10298 // embedded null character.
10299 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10300 CheckFormatHandler::EmitFormatDiagnostic(
10301 S, inFunctionCall, Args[format_idx],
10302 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10303 FExpr->getBeginLoc(),
10304 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10305 return;
10306 }
10307
10308 // CHECK: empty format string?
10309 if (StrLen == 0 && numDataArgs > 0) {
10310 CheckFormatHandler::EmitFormatDiagnostic(
10311 S, inFunctionCall, Args[format_idx],
10312 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10313 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10314 return;
10315 }
10316
10321 bool IsObjC =
10323 if (ReferenceFormatString == nullptr) {
10324 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10325 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10326 inFunctionCall, CallType, CheckedVarArgs,
10327 UncoveredArg);
10328
10330 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10333 H.DoneProcessing();
10334 } else {
10336 Type, ReferenceFormatString, FExpr->getFormatString(),
10337 inFunctionCall ? nullptr : Args[format_idx]);
10338 }
10339 } else if (Type == FormatStringType::Scanf) {
10340 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10341 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10342 CallType, CheckedVarArgs, UncoveredArg);
10343
10345 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10346 H.DoneProcessing();
10347 } // TODO: handle other formats
10348}
10349
10351 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10352 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10357 return true;
10358
10359 bool IsObjC =
10362 FormatStringLiteral RefLit = AuthoritativeFormatString;
10363 FormatStringLiteral TestLit = TestedFormatString;
10364 const Expr *Arg;
10365 bool DiagAtStringLiteral;
10366 if (FunctionCallArg) {
10367 Arg = FunctionCallArg;
10368 DiagAtStringLiteral = false;
10369 } else {
10370 Arg = TestedFormatString;
10371 DiagAtStringLiteral = true;
10372 }
10373 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10374 AuthoritativeFormatString, Type,
10375 IsObjC, true, RefArgs) &&
10376 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10377 DiagAtStringLiteral, FmtArgs)) {
10378 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10379 TestedFormatString, FmtArgs, Arg,
10380 DiagAtStringLiteral);
10381 }
10382 return false;
10383}
10384
10386 const StringLiteral *Str) {
10391 return true;
10392
10393 FormatStringLiteral RefLit = Str;
10395 bool IsObjC =
10397 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10398 true, Args))
10399 return false;
10400
10401 // Group arguments by getPosition() value, and check that each member of the
10402 // group is compatible with the first member. This verifies that when
10403 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10404 // are mutually compatible. As an optimization, don't test the first member
10405 // against itself.
10406 bool HadError = false;
10407 auto Iter = Args.begin();
10408 auto End = Args.end();
10409 while (Iter != End) {
10410 const auto &FirstInGroup = *Iter;
10411 for (++Iter;
10412 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10413 ++Iter) {
10414 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10415 }
10416 }
10417 return !HadError;
10418}
10419
10421 // Str - The format string. NOTE: this is NOT null-terminated!
10422 StringRef StrRef = FExpr->getString();
10423 const char *Str = StrRef.data();
10424 // Account for cases where the string literal is truncated in a declaration.
10425 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10426 assert(T && "String literal not of constant array type!");
10427 size_t TypeSize = T->getZExtSize();
10428 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10430 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10431}
10432
10433//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10434
10435// Returns the related absolute value function that is larger, of 0 if one
10436// does not exist.
10437static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10438 switch (AbsFunction) {
10439 default:
10440 return 0;
10441
10442 case Builtin::BI__builtin_abs:
10443 return Builtin::BI__builtin_labs;
10444 case Builtin::BI__builtin_labs:
10445 return Builtin::BI__builtin_llabs;
10446 case Builtin::BI__builtin_llabs:
10447 return 0;
10448
10449 case Builtin::BI__builtin_fabsf:
10450 return Builtin::BI__builtin_fabs;
10451 case Builtin::BI__builtin_fabs:
10452 return Builtin::BI__builtin_fabsl;
10453 case Builtin::BI__builtin_fabsl:
10454 return 0;
10455
10456 case Builtin::BI__builtin_cabsf:
10457 return Builtin::BI__builtin_cabs;
10458 case Builtin::BI__builtin_cabs:
10459 return Builtin::BI__builtin_cabsl;
10460 case Builtin::BI__builtin_cabsl:
10461 return 0;
10462
10463 case Builtin::BIabs:
10464 return Builtin::BIlabs;
10465 case Builtin::BIlabs:
10466 return Builtin::BIllabs;
10467 case Builtin::BIllabs:
10468 return 0;
10469
10470 case Builtin::BIfabsf:
10471 return Builtin::BIfabs;
10472 case Builtin::BIfabs:
10473 return Builtin::BIfabsl;
10474 case Builtin::BIfabsl:
10475 return 0;
10476
10477 case Builtin::BIcabsf:
10478 return Builtin::BIcabs;
10479 case Builtin::BIcabs:
10480 return Builtin::BIcabsl;
10481 case Builtin::BIcabsl:
10482 return 0;
10483 }
10484}
10485
10486// Returns the argument type of the absolute value function.
10488 unsigned AbsType) {
10489 if (AbsType == 0)
10490 return QualType();
10491
10493 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10495 return QualType();
10496
10498 if (!FT)
10499 return QualType();
10500
10501 if (FT->getNumParams() != 1)
10502 return QualType();
10503
10504 return FT->getParamType(0);
10505}
10506
10507// Returns the best absolute value function, or zero, based on type and
10508// current absolute value function.
10509static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10510 unsigned AbsFunctionKind) {
10511 unsigned BestKind = 0;
10512 uint64_t ArgSize = Context.getTypeSize(ArgType);
10513 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10514 Kind = getLargerAbsoluteValueFunction(Kind)) {
10515 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10516 if (Context.getTypeSize(ParamType) >= ArgSize) {
10517 if (BestKind == 0)
10518 BestKind = Kind;
10519 else if (Context.hasSameType(ParamType, ArgType)) {
10520 BestKind = Kind;
10521 break;
10522 }
10523 }
10524 }
10525 return BestKind;
10526}
10527
10533
10535 if (T->isIntegralOrEnumerationType())
10536 return AVK_Integer;
10537 if (T->isRealFloatingType())
10538 return AVK_Floating;
10539 if (T->isAnyComplexType())
10540 return AVK_Complex;
10541
10542 llvm_unreachable("Type not integer, floating, or complex");
10543}
10544
10545// Changes the absolute value function to a different type. Preserves whether
10546// the function is a builtin.
10547static unsigned changeAbsFunction(unsigned AbsKind,
10548 AbsoluteValueKind ValueKind) {
10549 switch (ValueKind) {
10550 case AVK_Integer:
10551 switch (AbsKind) {
10552 default:
10553 return 0;
10554 case Builtin::BI__builtin_fabsf:
10555 case Builtin::BI__builtin_fabs:
10556 case Builtin::BI__builtin_fabsl:
10557 case Builtin::BI__builtin_cabsf:
10558 case Builtin::BI__builtin_cabs:
10559 case Builtin::BI__builtin_cabsl:
10560 return Builtin::BI__builtin_abs;
10561 case Builtin::BIfabsf:
10562 case Builtin::BIfabs:
10563 case Builtin::BIfabsl:
10564 case Builtin::BIcabsf:
10565 case Builtin::BIcabs:
10566 case Builtin::BIcabsl:
10567 return Builtin::BIabs;
10568 }
10569 case AVK_Floating:
10570 switch (AbsKind) {
10571 default:
10572 return 0;
10573 case Builtin::BI__builtin_abs:
10574 case Builtin::BI__builtin_labs:
10575 case Builtin::BI__builtin_llabs:
10576 case Builtin::BI__builtin_cabsf:
10577 case Builtin::BI__builtin_cabs:
10578 case Builtin::BI__builtin_cabsl:
10579 return Builtin::BI__builtin_fabsf;
10580 case Builtin::BIabs:
10581 case Builtin::BIlabs:
10582 case Builtin::BIllabs:
10583 case Builtin::BIcabsf:
10584 case Builtin::BIcabs:
10585 case Builtin::BIcabsl:
10586 return Builtin::BIfabsf;
10587 }
10588 case AVK_Complex:
10589 switch (AbsKind) {
10590 default:
10591 return 0;
10592 case Builtin::BI__builtin_abs:
10593 case Builtin::BI__builtin_labs:
10594 case Builtin::BI__builtin_llabs:
10595 case Builtin::BI__builtin_fabsf:
10596 case Builtin::BI__builtin_fabs:
10597 case Builtin::BI__builtin_fabsl:
10598 return Builtin::BI__builtin_cabsf;
10599 case Builtin::BIabs:
10600 case Builtin::BIlabs:
10601 case Builtin::BIllabs:
10602 case Builtin::BIfabsf:
10603 case Builtin::BIfabs:
10604 case Builtin::BIfabsl:
10605 return Builtin::BIcabsf;
10606 }
10607 }
10608 llvm_unreachable("Unable to convert function");
10609}
10610
10611static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10612 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10613 if (!FnInfo)
10614 return 0;
10615
10616 switch (FDecl->getBuiltinID()) {
10617 default:
10618 return 0;
10619 case Builtin::BI__builtin_abs:
10620 case Builtin::BI__builtin_fabs:
10621 case Builtin::BI__builtin_fabsf:
10622 case Builtin::BI__builtin_fabsl:
10623 case Builtin::BI__builtin_labs:
10624 case Builtin::BI__builtin_llabs:
10625 case Builtin::BI__builtin_cabs:
10626 case Builtin::BI__builtin_cabsf:
10627 case Builtin::BI__builtin_cabsl:
10628 case Builtin::BIabs:
10629 case Builtin::BIlabs:
10630 case Builtin::BIllabs:
10631 case Builtin::BIfabs:
10632 case Builtin::BIfabsf:
10633 case Builtin::BIfabsl:
10634 case Builtin::BIcabs:
10635 case Builtin::BIcabsf:
10636 case Builtin::BIcabsl:
10637 return FDecl->getBuiltinID();
10638 }
10639 llvm_unreachable("Unknown Builtin type");
10640}
10641
10642// If the replacement is valid, emit a note with replacement function.
10643// Additionally, suggest including the proper header if not already included.
10645 unsigned AbsKind, QualType ArgType) {
10646 bool EmitHeaderHint = true;
10647 const char *HeaderName = nullptr;
10648 std::string FunctionName;
10649 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10650 FunctionName = "std::abs";
10651 if (ArgType->isIntegralOrEnumerationType()) {
10652 HeaderName = "cstdlib";
10653 } else if (ArgType->isRealFloatingType()) {
10654 HeaderName = "cmath";
10655 } else {
10656 llvm_unreachable("Invalid Type");
10657 }
10658
10659 // Lookup all std::abs
10660 if (NamespaceDecl *Std = S.getStdNamespace()) {
10661 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10662 R.suppressDiagnostics();
10663 S.LookupQualifiedName(R, Std);
10664
10665 for (const auto *I : R) {
10666 const FunctionDecl *FDecl = nullptr;
10667 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10668 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10669 } else {
10670 FDecl = dyn_cast<FunctionDecl>(I);
10671 }
10672 if (!FDecl)
10673 continue;
10674
10675 // Found std::abs(), check that they are the right ones.
10676 if (FDecl->getNumParams() != 1)
10677 continue;
10678
10679 // Check that the parameter type can handle the argument.
10680 QualType ParamType = FDecl->getParamDecl(0)->getType();
10681 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10682 S.Context.getTypeSize(ArgType) <=
10683 S.Context.getTypeSize(ParamType)) {
10684 // Found a function, don't need the header hint.
10685 EmitHeaderHint = false;
10686 break;
10687 }
10688 }
10689 }
10690 } else {
10691 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10692 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10693
10694 if (HeaderName) {
10695 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10696 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10697 R.suppressDiagnostics();
10698 S.LookupName(R, S.getCurScope());
10699
10700 if (R.isSingleResult()) {
10701 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10702 if (FD && FD->getBuiltinID() == AbsKind) {
10703 EmitHeaderHint = false;
10704 } else {
10705 return;
10706 }
10707 } else if (!R.empty()) {
10708 return;
10709 }
10710 }
10711 }
10712
10713 S.Diag(Loc, diag::note_replace_abs_function)
10714 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10715
10716 if (!HeaderName)
10717 return;
10718
10719 if (!EmitHeaderHint)
10720 return;
10721
10722 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10723 << FunctionName;
10724}
10725
10726template <std::size_t StrLen>
10727static bool IsStdFunction(const FunctionDecl *FDecl,
10728 const char (&Str)[StrLen]) {
10729 if (!FDecl)
10730 return false;
10731 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10732 return false;
10733 if (!FDecl->isInStdNamespace())
10734 return false;
10735
10736 return true;
10737}
10738
10739enum class MathCheck { NaN, Inf };
10740static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10741 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10742 return llvm::is_contained(names, calleeName);
10743 };
10744
10745 switch (Check) {
10746 case MathCheck::NaN:
10747 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10748 "__builtin_nanf16", "__builtin_nanf128"});
10749 case MathCheck::Inf:
10750 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10751 "__builtin_inff16", "__builtin_inff128"});
10752 }
10753 llvm_unreachable("unknown MathCheck");
10754}
10755
10756static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10757 if (FDecl->getName() != "infinity")
10758 return false;
10759
10760 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10761 const CXXRecordDecl *RDecl = MDecl->getParent();
10762 if (RDecl->getName() != "numeric_limits")
10763 return false;
10764
10765 if (const NamespaceDecl *NSDecl =
10766 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10767 return NSDecl->isStdNamespace();
10768 }
10769
10770 return false;
10771}
10772
10773void Sema::CheckInfNaNFunction(const CallExpr *Call,
10774 const FunctionDecl *FDecl) {
10775 if (!FDecl->getIdentifier())
10776 return;
10777
10778 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10779 if (FPO.getNoHonorNaNs() &&
10780 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10782 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10783 << 1 << 0 << Call->getSourceRange();
10784 return;
10785 }
10786
10787 if (FPO.getNoHonorInfs() &&
10788 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10789 IsInfinityFunction(FDecl) ||
10791 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10792 << 0 << 0 << Call->getSourceRange();
10793 }
10794}
10795
10796void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10797 const FunctionDecl *FDecl) {
10798 if (Call->getNumArgs() != 1)
10799 return;
10800
10801 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10802 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10803 if (AbsKind == 0 && !IsStdAbs)
10804 return;
10805
10806 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10807 QualType ParamType = Call->getArg(0)->getType();
10808
10809 // Unsigned types cannot be negative. Suggest removing the absolute value
10810 // function call.
10811 if (ArgType->isUnsignedIntegerType()) {
10812 std::string FunctionName =
10813 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10814 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10815 Diag(Call->getExprLoc(), diag::note_remove_abs)
10816 << FunctionName
10817 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10818 return;
10819 }
10820
10821 // Taking the absolute value of a pointer is very suspicious, they probably
10822 // wanted to index into an array, dereference a pointer, call a function, etc.
10823 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10824 unsigned DiagType = 0;
10825 if (ArgType->isFunctionType())
10826 DiagType = 1;
10827 else if (ArgType->isArrayType())
10828 DiagType = 2;
10829
10830 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10831 return;
10832 }
10833
10834 // std::abs has overloads which prevent most of the absolute value problems
10835 // from occurring.
10836 if (IsStdAbs)
10837 return;
10838
10839 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10840 // types.
10841 if (!ArgType->isIntegralOrEnumerationType() &&
10842 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10843 return;
10844
10845 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10846 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10847
10848 // The argument and parameter are the same kind. Check if they are the right
10849 // size.
10850 if (ArgValueKind == ParamValueKind) {
10851 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10852 return;
10853
10854 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10855 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10856 << FDecl << ArgType << ParamType;
10857
10858 if (NewAbsKind == 0)
10859 return;
10860
10861 emitReplacement(*this, Call->getExprLoc(),
10862 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10863 return;
10864 }
10865
10866 // ArgValueKind != ParamValueKind
10867 // The wrong type of absolute value function was used. Attempt to find the
10868 // proper one.
10869 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10870 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10871 if (NewAbsKind == 0)
10872 return;
10873
10874 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10875 << FDecl << ParamValueKind << ArgValueKind;
10876
10877 emitReplacement(*this, Call->getExprLoc(),
10878 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10879}
10880
10881//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10882void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10883 const FunctionDecl *FDecl) {
10884 if (!Call || !FDecl) return;
10885
10886 // Ignore template specializations and macros.
10887 if (inTemplateInstantiation()) return;
10888 if (Call->getExprLoc().isMacroID()) return;
10889
10890 // Only care about the one template argument, two function parameter std::max
10891 if (Call->getNumArgs() != 2) return;
10892 if (!IsStdFunction(FDecl, "max")) return;
10893 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10894 if (!ArgList) return;
10895 if (ArgList->size() != 1) return;
10896
10897 // Check that template type argument is unsigned integer.
10898 const auto& TA = ArgList->get(0);
10899 if (TA.getKind() != TemplateArgument::Type) return;
10900 QualType ArgType = TA.getAsType();
10901 if (!ArgType->isUnsignedIntegerType()) return;
10902
10903 // See if either argument is a literal zero.
10904 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10905 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10906 if (!MTE) return false;
10907 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10908 if (!Num) return false;
10909 if (Num->getValue() != 0) return false;
10910 return true;
10911 };
10912
10913 const Expr *FirstArg = Call->getArg(0);
10914 const Expr *SecondArg = Call->getArg(1);
10915 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10916 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10917
10918 // Only warn when exactly one argument is zero.
10919 if (IsFirstArgZero == IsSecondArgZero) return;
10920
10921 SourceRange FirstRange = FirstArg->getSourceRange();
10922 SourceRange SecondRange = SecondArg->getSourceRange();
10923
10924 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10925
10926 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10927 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10928
10929 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10930 SourceRange RemovalRange;
10931 if (IsFirstArgZero) {
10932 RemovalRange = SourceRange(FirstRange.getBegin(),
10933 SecondRange.getBegin().getLocWithOffset(-1));
10934 } else {
10935 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10936 SecondRange.getEnd());
10937 }
10938
10939 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10940 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10941 << FixItHint::CreateRemoval(RemovalRange);
10942}
10943
10944//===--- CHECK: Standard memory functions ---------------------------------===//
10945
10946/// Takes the expression passed to the size_t parameter of functions
10947/// such as memcmp, strncat, etc and warns if it's a comparison.
10948///
10949/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10951 const IdentifierInfo *FnName,
10952 SourceLocation FnLoc,
10953 SourceLocation RParenLoc) {
10954 const auto *Size = dyn_cast<BinaryOperator>(E);
10955 if (!Size)
10956 return false;
10957
10958 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10959 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10960 return false;
10961
10962 SourceRange SizeRange = Size->getSourceRange();
10963 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10964 << SizeRange << FnName;
10965 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10966 << FnName
10968 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10969 << FixItHint::CreateRemoval(RParenLoc);
10970 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10971 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10973 ")");
10974
10975 return true;
10976}
10977
10978/// Determine whether the given type is or contains a dynamic class type
10979/// (e.g., whether it has a vtable).
10981 bool &IsContained) {
10982 // Look through array types while ignoring qualifiers.
10983 const Type *Ty = T->getBaseElementTypeUnsafe();
10984 IsContained = false;
10985
10986 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10987 RD = RD ? RD->getDefinition() : nullptr;
10988 if (!RD || RD->isInvalidDecl())
10989 return nullptr;
10990
10991 if (RD->isDynamicClass())
10992 return RD;
10993
10994 // Check all the fields. If any bases were dynamic, the class is dynamic.
10995 // It's impossible for a class to transitively contain itself by value, so
10996 // infinite recursion is impossible.
10997 for (auto *FD : RD->fields()) {
10998 bool SubContained;
10999 if (const CXXRecordDecl *ContainedRD =
11000 getContainedDynamicClass(FD->getType(), SubContained)) {
11001 IsContained = true;
11002 return ContainedRD;
11003 }
11004 }
11005
11006 return nullptr;
11007}
11008
11010 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
11011 if (Unary->getKind() == UETT_SizeOf)
11012 return Unary;
11013 return nullptr;
11014}
11015
11016/// If E is a sizeof expression, returns its argument expression,
11017/// otherwise returns NULL.
11018static const Expr *getSizeOfExprArg(const Expr *E) {
11020 if (!SizeOf->isArgumentType())
11021 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11022 return nullptr;
11023}
11024
11025/// If E is a sizeof expression, returns its argument type.
11028 return SizeOf->getTypeOfArgument();
11029 return QualType();
11030}
11031
11032namespace {
11033
11034struct SearchNonTrivialToInitializeField
11035 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11036 using Super =
11037 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11038
11039 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11040
11041 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11042 SourceLocation SL) {
11043 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11044 asDerived().visitArray(PDIK, AT, SL);
11045 return;
11046 }
11047
11048 Super::visitWithKind(PDIK, FT, SL);
11049 }
11050
11051 void visitARCStrong(QualType FT, SourceLocation SL) {
11052 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11053 }
11054 void visitARCWeak(QualType FT, SourceLocation SL) {
11055 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11056 }
11057 void visitStruct(QualType FT, SourceLocation SL) {
11058 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11059 visit(FD->getType(), FD->getLocation());
11060 }
11061 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11062 const ArrayType *AT, SourceLocation SL) {
11063 visit(getContext().getBaseElementType(AT), SL);
11064 }
11065 void visitTrivial(QualType FT, SourceLocation SL) {}
11066
11067 static void diag(QualType RT, const Expr *E, Sema &S) {
11068 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
11069 }
11070
11071 ASTContext &getContext() { return S.getASTContext(); }
11072
11073 const Expr *E;
11074 Sema &S;
11075};
11076
11077struct SearchNonTrivialToCopyField
11078 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11079 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11080
11081 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11082
11083 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11084 SourceLocation SL) {
11085 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11086 asDerived().visitArray(PCK, AT, SL);
11087 return;
11088 }
11089
11090 Super::visitWithKind(PCK, FT, SL);
11091 }
11092
11093 void visitARCStrong(QualType FT, SourceLocation SL) {
11094 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11095 }
11096 void visitARCWeak(QualType FT, SourceLocation SL) {
11097 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11098 }
11099 void visitPtrAuth(QualType FT, SourceLocation SL) {
11100 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11101 }
11102 void visitStruct(QualType FT, SourceLocation SL) {
11103 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11104 visit(FD->getType(), FD->getLocation());
11105 }
11106 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11107 SourceLocation SL) {
11108 visit(getContext().getBaseElementType(AT), SL);
11109 }
11110 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11111 SourceLocation SL) {}
11112 void visitTrivial(QualType FT, SourceLocation SL) {}
11113 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11114
11115 static void diag(QualType RT, const Expr *E, Sema &S) {
11116 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
11117 }
11118
11119 ASTContext &getContext() { return S.getASTContext(); }
11120
11121 const Expr *E;
11122 Sema &S;
11123};
11124
11125}
11126
11127/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11128static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11129 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11130
11131 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
11132 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11133 return false;
11134
11135 return doesExprLikelyComputeSize(BO->getLHS()) ||
11136 doesExprLikelyComputeSize(BO->getRHS());
11137 }
11138
11139 return getAsSizeOfExpr(SizeofExpr) != nullptr;
11140}
11141
11142/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11143///
11144/// \code
11145/// #define MACRO 0
11146/// foo(MACRO);
11147/// foo(0);
11148/// \endcode
11149///
11150/// This should return true for the first call to foo, but not for the second
11151/// (regardless of whether foo is a macro or function).
11153 SourceLocation CallLoc,
11154 SourceLocation ArgLoc) {
11155 if (!CallLoc.isMacroID())
11156 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11157
11158 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11160}
11161
11162/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11163/// last two arguments transposed.
11164static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11165 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11166 return;
11167
11168 const Expr *SizeArg =
11169 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11170
11171 auto isLiteralZero = [](const Expr *E) {
11172 return (isa<IntegerLiteral>(E) &&
11173 cast<IntegerLiteral>(E)->getValue() == 0) ||
11175 cast<CharacterLiteral>(E)->getValue() == 0);
11176 };
11177
11178 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11179 SourceLocation CallLoc = Call->getRParenLoc();
11181 if (isLiteralZero(SizeArg) &&
11182 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11183
11184 SourceLocation DiagLoc = SizeArg->getExprLoc();
11185
11186 // Some platforms #define bzero to __builtin_memset. See if this is the
11187 // case, and if so, emit a better diagnostic.
11188 if (BId == Builtin::BIbzero ||
11190 CallLoc, SM, S.getLangOpts()) == "bzero")) {
11191 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11192 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11193 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11194 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11195 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11196 }
11197 return;
11198 }
11199
11200 // If the second argument to a memset is a sizeof expression and the third
11201 // isn't, this is also likely an error. This should catch
11202 // 'memset(buf, sizeof(buf), 0xff)'.
11203 if (BId == Builtin::BImemset &&
11204 doesExprLikelyComputeSize(Call->getArg(1)) &&
11205 !doesExprLikelyComputeSize(Call->getArg(2))) {
11206 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11207 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11208 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11209 return;
11210 }
11211}
11212
11213void Sema::CheckMemaccessArguments(const CallExpr *Call,
11214 unsigned BId,
11215 IdentifierInfo *FnName) {
11216 assert(BId != 0);
11217
11218 // It is possible to have a non-standard definition of memset. Validate
11219 // we have enough arguments, and if not, abort further checking.
11220 unsigned ExpectedNumArgs =
11221 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11222 if (Call->getNumArgs() < ExpectedNumArgs)
11223 return;
11224
11225 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11226 BId == Builtin::BIstrndup ? 1 : 2);
11227 unsigned LenArg =
11228 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11229 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11230
11231 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11232 Call->getBeginLoc(), Call->getRParenLoc()))
11233 return;
11234
11235 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11236 CheckMemaccessSize(*this, BId, Call);
11237
11238 // We have special checking when the length is a sizeof expression.
11239 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11240
11241 // Although widely used, 'bzero' is not a standard function. Be more strict
11242 // with the argument types before allowing diagnostics and only allow the
11243 // form bzero(ptr, sizeof(...)).
11244 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11245 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11246 return;
11247
11248 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11249 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11250 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11251
11252 QualType DestTy = Dest->getType();
11253 QualType PointeeTy;
11254 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11255 PointeeTy = DestPtrTy->getPointeeType();
11256
11257 // Never warn about void type pointers. This can be used to suppress
11258 // false positives.
11259 if (PointeeTy->isVoidType())
11260 continue;
11261
11262 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11263 // actually comparing the expressions for equality. Because computing the
11264 // expression IDs can be expensive, we only do this if the diagnostic is
11265 // enabled.
11266 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11267 break;
11268
11269 // Also check for cases where the sizeof argument is the exact same
11270 // type as the memory argument, and where it points to a user-defined
11271 // record type.
11272 if (SizeOfArgTy != QualType()) {
11273 if (PointeeTy->isRecordType() &&
11274 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11275 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11276 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11277 << FnName << SizeOfArgTy << ArgIdx
11278 << PointeeTy << Dest->getSourceRange()
11279 << LenExpr->getSourceRange());
11280 break;
11281 }
11282 }
11283 } else if (DestTy->isArrayType()) {
11284 PointeeTy = DestTy;
11285 }
11286
11287 if (PointeeTy == QualType())
11288 continue;
11289
11290 // Always complain about dynamic classes.
11291 bool IsContained;
11292 if (const CXXRecordDecl *ContainedRD =
11293 getContainedDynamicClass(PointeeTy, IsContained)) {
11294
11295 unsigned OperationType = 0;
11296 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11297 // "overwritten" if we're warning about the destination for any call
11298 // but memcmp; otherwise a verb appropriate to the call.
11299 if (ArgIdx != 0 || IsCmp) {
11300 if (BId == Builtin::BImemcpy)
11301 OperationType = 1;
11302 else if(BId == Builtin::BImemmove)
11303 OperationType = 2;
11304 else if (IsCmp)
11305 OperationType = 3;
11306 }
11307
11308 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11309 PDiag(diag::warn_dyn_class_memaccess)
11310 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11311 << IsContained << ContainedRD << OperationType
11312 << Call->getCallee()->getSourceRange());
11313 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11314 BId != Builtin::BImemset)
11316 Dest->getExprLoc(), Dest,
11317 PDiag(diag::warn_arc_object_memaccess)
11318 << ArgIdx << FnName << PointeeTy
11319 << Call->getCallee()->getSourceRange());
11320 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11321
11322 // FIXME: Do not consider incomplete types even though they may be
11323 // completed later. GCC does not diagnose such code, but we may want to
11324 // consider diagnosing it in the future, perhaps under a different, but
11325 // related, diagnostic group.
11326 bool NonTriviallyCopyableCXXRecord =
11327 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11328 !PointeeTy.isTriviallyCopyableType(Context);
11329
11330 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11332 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11333 PDiag(diag::warn_cstruct_memaccess)
11334 << ArgIdx << FnName << PointeeTy << 0);
11335 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11336 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11337 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11338 // FIXME: Limiting this warning to dest argument until we decide
11339 // whether it's valid for source argument too.
11340 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11341 PDiag(diag::warn_cxxstruct_memaccess)
11342 << FnName << PointeeTy);
11343 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11345 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11346 PDiag(diag::warn_cstruct_memaccess)
11347 << ArgIdx << FnName << PointeeTy << 1);
11348 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11349 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11350 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11351 // FIXME: Limiting this warning to dest argument until we decide
11352 // whether it's valid for source argument too.
11353 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11354 PDiag(diag::warn_cxxstruct_memaccess)
11355 << FnName << PointeeTy);
11356 } else {
11357 continue;
11358 }
11359 } else
11360 continue;
11361
11363 Dest->getExprLoc(), Dest,
11364 PDiag(diag::note_bad_memaccess_silence)
11365 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11366 break;
11367 }
11368}
11369
11370bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11371 IdentifierInfo *FnName) {
11372 llvm::FoldingSetNodeID SizeOfArgID;
11373 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11374 if (!SizeOfArg)
11375 return false;
11376 // Computing this warning is expensive, so we only do so if the warning is
11377 // enabled.
11378 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11379 SizeOfArg->getExprLoc()))
11380 return false;
11381 QualType DestTy = Dest->getType();
11382 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11383 if (!DestPtrTy)
11384 return false;
11385
11386 QualType PointeeTy = DestPtrTy->getPointeeType();
11387
11388 if (SizeOfArgID == llvm::FoldingSetNodeID())
11389 SizeOfArg->Profile(SizeOfArgID, Context, true);
11390
11391 llvm::FoldingSetNodeID DestID;
11392 Dest->Profile(DestID, Context, true);
11393 if (DestID == SizeOfArgID) {
11394 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11395 // over sizeof(src) as well.
11396 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11397 StringRef ReadableName = FnName->getName();
11398
11399 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11400 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11401 ActionIdx = 1; // If its an address-of operator, just remove it.
11402 if (!PointeeTy->isIncompleteType() &&
11403 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11404 ActionIdx = 2; // If the pointee's size is sizeof(char),
11405 // suggest an explicit length.
11406
11407 // If the function is defined as a builtin macro, do not show macro
11408 // expansion.
11409 SourceLocation SL = SizeOfArg->getExprLoc();
11410 SourceRange DSR = Dest->getSourceRange();
11411 SourceRange SSR = SizeOfArg->getSourceRange();
11412 SourceManager &SM = getSourceManager();
11413
11414 if (SM.isMacroArgExpansion(SL)) {
11415 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11416 SL = SM.getSpellingLoc(SL);
11417 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11418 SM.getSpellingLoc(DSR.getEnd()));
11419 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11420 SM.getSpellingLoc(SSR.getEnd()));
11421 }
11422
11423 DiagRuntimeBehavior(SL, SizeOfArg,
11424 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11425 << ReadableName << PointeeTy << DestTy << DSR
11426 << SSR);
11427 DiagRuntimeBehavior(SL, SizeOfArg,
11428 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11429 << ActionIdx << SSR);
11430 return true;
11431 }
11432 return false;
11433}
11434
11435// A little helper routine: ignore addition and subtraction of integer literals.
11436// This intentionally does not ignore all integer constant expressions because
11437// we don't want to remove sizeof().
11438static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11439 Ex = Ex->IgnoreParenCasts();
11440
11441 while (true) {
11442 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11443 if (!BO || !BO->isAdditiveOp())
11444 break;
11445
11446 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11447 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11448
11449 if (isa<IntegerLiteral>(RHS))
11450 Ex = LHS;
11451 else if (isa<IntegerLiteral>(LHS))
11452 Ex = RHS;
11453 else
11454 break;
11455 }
11456
11457 return Ex;
11458}
11459
11461 ASTContext &Context) {
11462 // Only handle constant-sized or VLAs, but not flexible members.
11463 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11464 // Only issue the FIXIT for arrays of size > 1.
11465 if (CAT->getZExtSize() <= 1)
11466 return false;
11467 } else if (!Ty->isVariableArrayType()) {
11468 return false;
11469 }
11470 return true;
11471}
11472
11473void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11474 IdentifierInfo *FnName) {
11475
11476 // Don't crash if the user has the wrong number of arguments
11477 unsigned NumArgs = Call->getNumArgs();
11478 if ((NumArgs != 3) && (NumArgs != 4))
11479 return;
11480
11481 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11482 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11483 const Expr *CompareWithSrc = nullptr;
11484
11485 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11486 Call->getBeginLoc(), Call->getRParenLoc()))
11487 return;
11488
11489 // Look for 'strlcpy(dst, x, sizeof(x))'
11490 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11491 CompareWithSrc = Ex;
11492 else {
11493 // Look for 'strlcpy(dst, x, strlen(x))'
11494 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11495 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11496 SizeCall->getNumArgs() == 1)
11497 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11498 }
11499 }
11500
11501 if (!CompareWithSrc)
11502 return;
11503
11504 // Determine if the argument to sizeof/strlen is equal to the source
11505 // argument. In principle there's all kinds of things you could do
11506 // here, for instance creating an == expression and evaluating it with
11507 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11508 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11509 if (!SrcArgDRE)
11510 return;
11511
11512 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11513 if (!CompareWithSrcDRE ||
11514 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11515 return;
11516
11517 const Expr *OriginalSizeArg = Call->getArg(2);
11518 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11519 << OriginalSizeArg->getSourceRange() << FnName;
11520
11521 // Output a FIXIT hint if the destination is an array (rather than a
11522 // pointer to an array). This could be enhanced to handle some
11523 // pointers if we know the actual size, like if DstArg is 'array+2'
11524 // we could say 'sizeof(array)-2'.
11525 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11527 return;
11528
11529 SmallString<128> sizeString;
11530 llvm::raw_svector_ostream OS(sizeString);
11531 OS << "sizeof(";
11532 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11533 OS << ")";
11534
11535 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11536 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11537 OS.str());
11538}
11539
11540/// Check if two expressions refer to the same declaration.
11541static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11542 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11543 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11544 return D1->getDecl() == D2->getDecl();
11545 return false;
11546}
11547
11548static const Expr *getStrlenExprArg(const Expr *E) {
11549 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11550 const FunctionDecl *FD = CE->getDirectCallee();
11551 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11552 return nullptr;
11553 return CE->getArg(0)->IgnoreParenCasts();
11554 }
11555 return nullptr;
11556}
11557
11558void Sema::CheckStrncatArguments(const CallExpr *CE,
11559 const IdentifierInfo *FnName) {
11560 // Don't crash if the user has the wrong number of arguments.
11561 if (CE->getNumArgs() < 3)
11562 return;
11563 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11564 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11565 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11566
11567 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11568 CE->getRParenLoc()))
11569 return;
11570
11571 // Identify common expressions, which are wrongly used as the size argument
11572 // to strncat and may lead to buffer overflows.
11573 unsigned PatternType = 0;
11574 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11575 // - sizeof(dst)
11576 if (referToTheSameDecl(SizeOfArg, DstArg))
11577 PatternType = 1;
11578 // - sizeof(src)
11579 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11580 PatternType = 2;
11581 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11582 if (BE->getOpcode() == BO_Sub) {
11583 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11584 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11585 // - sizeof(dst) - strlen(dst)
11586 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11588 PatternType = 1;
11589 // - sizeof(src) - (anything)
11590 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11591 PatternType = 2;
11592 }
11593 }
11594
11595 if (PatternType == 0)
11596 return;
11597
11598 // Generate the diagnostic.
11599 SourceLocation SL = LenArg->getBeginLoc();
11600 SourceRange SR = LenArg->getSourceRange();
11601 SourceManager &SM = getSourceManager();
11602
11603 // If the function is defined as a builtin macro, do not show macro expansion.
11604 if (SM.isMacroArgExpansion(SL)) {
11605 SL = SM.getSpellingLoc(SL);
11606 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11607 SM.getSpellingLoc(SR.getEnd()));
11608 }
11609
11610 // Check if the destination is an array (rather than a pointer to an array).
11611 QualType DstTy = DstArg->getType();
11612 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11613 Context);
11614 if (!isKnownSizeArray) {
11615 if (PatternType == 1)
11616 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11617 else
11618 Diag(SL, diag::warn_strncat_src_size) << SR;
11619 return;
11620 }
11621
11622 if (PatternType == 1)
11623 Diag(SL, diag::warn_strncat_large_size) << SR;
11624 else
11625 Diag(SL, diag::warn_strncat_src_size) << SR;
11626
11627 SmallString<128> sizeString;
11628 llvm::raw_svector_ostream OS(sizeString);
11629 OS << "sizeof(";
11630 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11631 OS << ") - ";
11632 OS << "strlen(";
11633 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11634 OS << ") - 1";
11635
11636 Diag(SL, diag::note_strncat_wrong_size)
11637 << FixItHint::CreateReplacement(SR, OS.str());
11638}
11639
11640namespace {
11641void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11642 const UnaryOperator *UnaryExpr, const Decl *D) {
11644 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11645 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11646 return;
11647 }
11648}
11649
11650void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11651 const UnaryOperator *UnaryExpr) {
11652 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11653 const Decl *D = Lvalue->getDecl();
11654 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11655 if (!DD->getType()->isReferenceType())
11656 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11657 }
11658 }
11659
11660 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11661 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11662 Lvalue->getMemberDecl());
11663}
11664
11665void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11666 const UnaryOperator *UnaryExpr) {
11667 const auto *Lambda = dyn_cast<LambdaExpr>(
11669 if (!Lambda)
11670 return;
11671
11672 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11673 << CalleeName << 2 /*object: lambda expression*/;
11674}
11675
11676void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11677 const DeclRefExpr *Lvalue) {
11678 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11679 if (Var == nullptr)
11680 return;
11681
11682 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11683 << CalleeName << 0 /*object: */ << Var;
11684}
11685
11686void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11687 const CastExpr *Cast) {
11688 SmallString<128> SizeString;
11689 llvm::raw_svector_ostream OS(SizeString);
11690
11691 clang::CastKind Kind = Cast->getCastKind();
11692 if (Kind == clang::CK_BitCast &&
11693 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11694 return;
11695 if (Kind == clang::CK_IntegralToPointer &&
11697 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11698 return;
11699
11700 switch (Cast->getCastKind()) {
11701 case clang::CK_BitCast:
11702 case clang::CK_IntegralToPointer:
11703 case clang::CK_FunctionToPointerDecay:
11704 OS << '\'';
11705 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11706 OS << '\'';
11707 break;
11708 default:
11709 return;
11710 }
11711
11712 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11713 << CalleeName << 0 /*object: */ << OS.str();
11714}
11715} // namespace
11716
11717void Sema::CheckFreeArguments(const CallExpr *E) {
11718 const std::string CalleeName =
11719 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11720
11721 { // Prefer something that doesn't involve a cast to make things simpler.
11722 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11723 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11724 switch (UnaryExpr->getOpcode()) {
11725 case UnaryOperator::Opcode::UO_AddrOf:
11726 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11727 case UnaryOperator::Opcode::UO_Plus:
11728 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11729 default:
11730 break;
11731 }
11732
11733 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11734 if (Lvalue->getType()->isArrayType())
11735 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11736
11737 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11738 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11739 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11740 return;
11741 }
11742
11743 if (isa<BlockExpr>(Arg)) {
11744 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11745 << CalleeName << 1 /*object: block*/;
11746 return;
11747 }
11748 }
11749 // Maybe the cast was important, check after the other cases.
11750 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11751 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11752}
11753
11754void
11755Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11756 SourceLocation ReturnLoc,
11757 bool isObjCMethod,
11758 const AttrVec *Attrs,
11759 const FunctionDecl *FD) {
11760 // Check if the return value is null but should not be.
11761 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11762 (!isObjCMethod && isNonNullType(lhsType))) &&
11763 CheckNonNullExpr(*this, RetValExp))
11764 Diag(ReturnLoc, diag::warn_null_ret)
11765 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11766
11767 // C++11 [basic.stc.dynamic.allocation]p4:
11768 // If an allocation function declared with a non-throwing
11769 // exception-specification fails to allocate storage, it shall return
11770 // a null pointer. Any other allocation function that fails to allocate
11771 // storage shall indicate failure only by throwing an exception [...]
11772 if (FD) {
11774 if (Op == OO_New || Op == OO_Array_New) {
11775 const FunctionProtoType *Proto
11776 = FD->getType()->castAs<FunctionProtoType>();
11777 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11778 CheckNonNullExpr(*this, RetValExp))
11779 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11780 << FD << getLangOpts().CPlusPlus11;
11781 }
11782 }
11783
11784 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11785 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11786 }
11787
11788 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11789 // here prevent the user from using a PPC MMA type as trailing return type.
11790 if (Context.getTargetInfo().getTriple().isPPC64())
11791 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11792}
11793
11795 const Expr *RHS, BinaryOperatorKind Opcode) {
11796 if (!BinaryOperator::isEqualityOp(Opcode))
11797 return;
11798
11799 // Match and capture subexpressions such as "(float) X == 0.1".
11800 const FloatingLiteral *FPLiteral;
11801 const CastExpr *FPCast;
11802 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11803 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11804 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11805 return FPLiteral && FPCast;
11806 };
11807
11808 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11809 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11810 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11811 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11812 TargetTy->isFloatingPoint()) {
11813 bool Lossy;
11814 llvm::APFloat TargetC = FPLiteral->getValue();
11815 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11816 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11817 if (Lossy) {
11818 // If the literal cannot be represented in the source type, then a
11819 // check for == is always false and check for != is always true.
11820 Diag(Loc, diag::warn_float_compare_literal)
11821 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11822 << LHS->getSourceRange() << RHS->getSourceRange();
11823 return;
11824 }
11825 }
11826 }
11827
11828 // Match a more general floating-point equality comparison (-Wfloat-equal).
11829 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11830 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11831
11832 // Special case: check for x == x (which is OK).
11833 // Do not emit warnings for such cases.
11834 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11835 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11836 if (DRL->getDecl() == DRR->getDecl())
11837 return;
11838
11839 // Special case: check for comparisons against literals that can be exactly
11840 // represented by APFloat. In such cases, do not emit a warning. This
11841 // is a heuristic: often comparison against such literals are used to
11842 // detect if a value in a variable has not changed. This clearly can
11843 // lead to false negatives.
11844 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11845 if (FLL->isExact())
11846 return;
11847 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11848 if (FLR->isExact())
11849 return;
11850
11851 // Check for comparisons with builtin types.
11852 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11853 CL && CL->getBuiltinCallee())
11854 return;
11855
11856 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11857 CR && CR->getBuiltinCallee())
11858 return;
11859
11860 // Emit the diagnostic.
11861 Diag(Loc, diag::warn_floatingpoint_eq)
11862 << LHS->getSourceRange() << RHS->getSourceRange();
11863}
11864
11865//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11866//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11867
11868namespace {
11869
11870/// Structure recording the 'active' range of an integer-valued
11871/// expression.
11872struct IntRange {
11873 /// The number of bits active in the int. Note that this includes exactly one
11874 /// sign bit if !NonNegative.
11875 unsigned Width;
11876
11877 /// True if the int is known not to have negative values. If so, all leading
11878 /// bits before Width are known zero, otherwise they are known to be the
11879 /// same as the MSB within Width.
11880 bool NonNegative;
11881
11882 IntRange(unsigned Width, bool NonNegative)
11883 : Width(Width), NonNegative(NonNegative) {}
11884
11885 /// Number of bits excluding the sign bit.
11886 unsigned valueBits() const {
11887 return NonNegative ? Width : Width - 1;
11888 }
11889
11890 /// Returns the range of the bool type.
11891 static IntRange forBoolType() {
11892 return IntRange(1, true);
11893 }
11894
11895 /// Returns the range of an opaque value of the given integral type.
11896 static IntRange forValueOfType(ASTContext &C, QualType T) {
11897 return forValueOfCanonicalType(C,
11899 }
11900
11901 /// Returns the range of an opaque value of a canonical integral type.
11902 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11903 assert(T->isCanonicalUnqualified());
11904
11905 if (const auto *VT = dyn_cast<VectorType>(T))
11906 T = VT->getElementType().getTypePtr();
11907 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11908 T = MT->getElementType().getTypePtr();
11909 if (const auto *CT = dyn_cast<ComplexType>(T))
11910 T = CT->getElementType().getTypePtr();
11911 if (const auto *AT = dyn_cast<AtomicType>(T))
11912 T = AT->getValueType().getTypePtr();
11913 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11914 T = OBT->getUnderlyingType().getTypePtr();
11915
11916 if (!C.getLangOpts().CPlusPlus) {
11917 // For enum types in C code, use the underlying datatype.
11918 if (const auto *ED = T->getAsEnumDecl())
11919 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11920 } else if (auto *Enum = T->getAsEnumDecl()) {
11921 // For enum types in C++, use the known bit width of the enumerators.
11922 // In C++11, enums can have a fixed underlying type. Use this type to
11923 // compute the range.
11924 if (Enum->isFixed()) {
11925 return IntRange(C.getIntWidth(QualType(T, 0)),
11926 !Enum->getIntegerType()->isSignedIntegerType());
11927 }
11928
11929 unsigned NumPositive = Enum->getNumPositiveBits();
11930 unsigned NumNegative = Enum->getNumNegativeBits();
11931
11932 if (NumNegative == 0)
11933 return IntRange(NumPositive, true/*NonNegative*/);
11934 else
11935 return IntRange(std::max(NumPositive + 1, NumNegative),
11936 false/*NonNegative*/);
11937 }
11938
11939 if (const auto *EIT = dyn_cast<BitIntType>(T))
11940 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11941
11942 const BuiltinType *BT = cast<BuiltinType>(T);
11943 assert(BT->isInteger());
11944
11945 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11946 }
11947
11948 /// Returns the "target" range of a canonical integral type, i.e.
11949 /// the range of values expressible in the type.
11950 ///
11951 /// This matches forValueOfCanonicalType except that enums have the
11952 /// full range of their type, not the range of their enumerators.
11953 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11954 assert(T->isCanonicalUnqualified());
11955
11956 if (const VectorType *VT = dyn_cast<VectorType>(T))
11957 T = VT->getElementType().getTypePtr();
11958 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11959 T = MT->getElementType().getTypePtr();
11960 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11961 T = CT->getElementType().getTypePtr();
11962 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11963 T = AT->getValueType().getTypePtr();
11964 if (const auto *ED = T->getAsEnumDecl())
11965 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11966 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11967 T = OBT->getUnderlyingType().getTypePtr();
11968
11969 if (const auto *EIT = dyn_cast<BitIntType>(T))
11970 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11971
11972 const BuiltinType *BT = cast<BuiltinType>(T);
11973 assert(BT->isInteger());
11974
11975 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11976 }
11977
11978 /// Returns the supremum of two ranges: i.e. their conservative merge.
11979 static IntRange join(IntRange L, IntRange R) {
11980 bool Unsigned = L.NonNegative && R.NonNegative;
11981 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11982 L.NonNegative && R.NonNegative);
11983 }
11984
11985 /// Return the range of a bitwise-AND of the two ranges.
11986 static IntRange bit_and(IntRange L, IntRange R) {
11987 unsigned Bits = std::max(L.Width, R.Width);
11988 bool NonNegative = false;
11989 if (L.NonNegative) {
11990 Bits = std::min(Bits, L.Width);
11991 NonNegative = true;
11992 }
11993 if (R.NonNegative) {
11994 Bits = std::min(Bits, R.Width);
11995 NonNegative = true;
11996 }
11997 return IntRange(Bits, NonNegative);
11998 }
11999
12000 /// Return the range of a sum of the two ranges.
12001 static IntRange sum(IntRange L, IntRange R) {
12002 bool Unsigned = L.NonNegative && R.NonNegative;
12003 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
12004 Unsigned);
12005 }
12006
12007 /// Return the range of a difference of the two ranges.
12008 static IntRange difference(IntRange L, IntRange R) {
12009 // We need a 1-bit-wider range if:
12010 // 1) LHS can be negative: least value can be reduced.
12011 // 2) RHS can be negative: greatest value can be increased.
12012 bool CanWiden = !L.NonNegative || !R.NonNegative;
12013 bool Unsigned = L.NonNegative && R.Width == 0;
12014 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
12015 !Unsigned,
12016 Unsigned);
12017 }
12018
12019 /// Return the range of a product of the two ranges.
12020 static IntRange product(IntRange L, IntRange R) {
12021 // If both LHS and RHS can be negative, we can form
12022 // -2^L * -2^R = 2^(L + R)
12023 // which requires L + R + 1 value bits to represent.
12024 bool CanWiden = !L.NonNegative && !R.NonNegative;
12025 bool Unsigned = L.NonNegative && R.NonNegative;
12026 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12027 Unsigned);
12028 }
12029
12030 /// Return the range of a remainder operation between the two ranges.
12031 static IntRange rem(IntRange L, IntRange R) {
12032 // The result of a remainder can't be larger than the result of
12033 // either side. The sign of the result is the sign of the LHS.
12034 bool Unsigned = L.NonNegative;
12035 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
12036 Unsigned);
12037 }
12038};
12039
12040} // namespace
12041
12042static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
12043 if (value.isSigned() && value.isNegative())
12044 return IntRange(value.getSignificantBits(), false);
12045
12046 if (value.getBitWidth() > MaxWidth)
12047 value = value.trunc(MaxWidth);
12048
12049 // isNonNegative() just checks the sign bit without considering
12050 // signedness.
12051 return IntRange(value.getActiveBits(), true);
12052}
12053
12054static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
12055 if (result.isInt())
12056 return GetValueRange(result.getInt(), MaxWidth);
12057
12058 if (result.isVector()) {
12059 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
12060 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12061 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
12062 R = IntRange::join(R, El);
12063 }
12064 return R;
12065 }
12066
12067 if (result.isComplexInt()) {
12068 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
12069 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
12070 return IntRange::join(R, I);
12071 }
12072
12073 // This can happen with lossless casts to intptr_t of "based" lvalues.
12074 // Assume it might use arbitrary bits.
12075 // FIXME: The only reason we need to pass the type in here is to get
12076 // the sign right on this one case. It would be nice if APValue
12077 // preserved this.
12078 assert(result.isLValue() || result.isAddrLabelDiff());
12079 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12080}
12081
12082static QualType GetExprType(const Expr *E) {
12083 QualType Ty = E->getType();
12084 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
12085 Ty = AtomicRHS->getValueType();
12086 return Ty;
12087}
12088
12089/// Attempts to estimate an approximate range for the given integer expression.
12090/// Returns a range if successful, otherwise it returns \c std::nullopt if a
12091/// reliable estimation cannot be determined.
12092///
12093/// \param MaxWidth The width to which the value will be truncated.
12094/// \param InConstantContext If \c true, interpret the expression within a
12095/// constant context.
12096/// \param Approximate If \c true, provide a likely range of values by assuming
12097/// that arithmetic on narrower types remains within those types.
12098/// If \c false, return a range that includes all possible values
12099/// resulting from the expression.
12100/// \returns A range of values that the expression might take, or
12101/// std::nullopt if a reliable estimation cannot be determined.
12102static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12103 unsigned MaxWidth,
12104 bool InConstantContext,
12105 bool Approximate) {
12106 E = E->IgnoreParens();
12107
12108 // Try a full evaluation first.
12109 Expr::EvalResult result;
12110 if (E->EvaluateAsRValue(result, C, InConstantContext))
12111 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
12112
12113 // I think we only want to look through implicit casts here; if the
12114 // user has an explicit widening cast, we should treat the value as
12115 // being of the new, wider type.
12116 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
12117 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12118 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
12119 Approximate);
12120
12121 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
12122
12123 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12124 CE->getCastKind() == CK_BooleanToSignedIntegral;
12125
12126 // Assume that non-integer casts can span the full range of the type.
12127 if (!isIntegerCast)
12128 return OutputTypeRange;
12129
12130 std::optional<IntRange> SubRange = TryGetExprRange(
12131 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
12132 InConstantContext, Approximate);
12133 if (!SubRange)
12134 return std::nullopt;
12135
12136 // Bail out if the subexpr's range is as wide as the cast type.
12137 if (SubRange->Width >= OutputTypeRange.Width)
12138 return OutputTypeRange;
12139
12140 // Otherwise, we take the smaller width, and we're non-negative if
12141 // either the output type or the subexpr is.
12142 return IntRange(SubRange->Width,
12143 SubRange->NonNegative || OutputTypeRange.NonNegative);
12144 }
12145
12146 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12147 // If we can fold the condition, just take that operand.
12148 bool CondResult;
12149 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12150 return TryGetExprRange(
12151 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12152 InConstantContext, Approximate);
12153
12154 // Otherwise, conservatively merge.
12155 // TryGetExprRange requires an integer expression, but a throw expression
12156 // results in a void type.
12157 Expr *TrueExpr = CO->getTrueExpr();
12158 if (TrueExpr->getType()->isVoidType())
12159 return std::nullopt;
12160
12161 std::optional<IntRange> L =
12162 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
12163 if (!L)
12164 return std::nullopt;
12165
12166 Expr *FalseExpr = CO->getFalseExpr();
12167 if (FalseExpr->getType()->isVoidType())
12168 return std::nullopt;
12169
12170 std::optional<IntRange> R =
12171 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
12172 if (!R)
12173 return std::nullopt;
12174
12175 return IntRange::join(*L, *R);
12176 }
12177
12178 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12179 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12180
12181 switch (BO->getOpcode()) {
12182 case BO_Cmp:
12183 llvm_unreachable("builtin <=> should have class type");
12184
12185 // Boolean-valued operations are single-bit and positive.
12186 case BO_LAnd:
12187 case BO_LOr:
12188 case BO_LT:
12189 case BO_GT:
12190 case BO_LE:
12191 case BO_GE:
12192 case BO_EQ:
12193 case BO_NE:
12194 return IntRange::forBoolType();
12195
12196 // The type of the assignments is the type of the LHS, so the RHS
12197 // is not necessarily the same type.
12198 case BO_MulAssign:
12199 case BO_DivAssign:
12200 case BO_RemAssign:
12201 case BO_AddAssign:
12202 case BO_SubAssign:
12203 case BO_XorAssign:
12204 case BO_OrAssign:
12205 // TODO: bitfields?
12206 return IntRange::forValueOfType(C, GetExprType(E));
12207
12208 // Simple assignments just pass through the RHS, which will have
12209 // been coerced to the LHS type.
12210 case BO_Assign:
12211 // TODO: bitfields?
12212 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12213 Approximate);
12214
12215 // Operations with opaque sources are black-listed.
12216 case BO_PtrMemD:
12217 case BO_PtrMemI:
12218 return IntRange::forValueOfType(C, GetExprType(E));
12219
12220 // Bitwise-and uses the *infinum* of the two source ranges.
12221 case BO_And:
12222 case BO_AndAssign:
12223 Combine = IntRange::bit_and;
12224 break;
12225
12226 // Left shift gets black-listed based on a judgement call.
12227 case BO_Shl:
12228 // ...except that we want to treat '1 << (blah)' as logically
12229 // positive. It's an important idiom.
12230 if (IntegerLiteral *I
12231 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12232 if (I->getValue() == 1) {
12233 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12234 return IntRange(R.Width, /*NonNegative*/ true);
12235 }
12236 }
12237 [[fallthrough]];
12238
12239 case BO_ShlAssign:
12240 return IntRange::forValueOfType(C, GetExprType(E));
12241
12242 // Right shift by a constant can narrow its left argument.
12243 case BO_Shr:
12244 case BO_ShrAssign: {
12245 std::optional<IntRange> L = TryGetExprRange(
12246 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12247 if (!L)
12248 return std::nullopt;
12249
12250 // If the shift amount is a positive constant, drop the width by
12251 // that much.
12252 if (std::optional<llvm::APSInt> shift =
12253 BO->getRHS()->getIntegerConstantExpr(C)) {
12254 if (shift->isNonNegative()) {
12255 if (shift->uge(L->Width))
12256 L->Width = (L->NonNegative ? 0 : 1);
12257 else
12258 L->Width -= shift->getZExtValue();
12259 }
12260 }
12261
12262 return L;
12263 }
12264
12265 // Comma acts as its right operand.
12266 case BO_Comma:
12267 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12268 Approximate);
12269
12270 case BO_Add:
12271 if (!Approximate)
12272 Combine = IntRange::sum;
12273 break;
12274
12275 case BO_Sub:
12276 if (BO->getLHS()->getType()->isPointerType())
12277 return IntRange::forValueOfType(C, GetExprType(E));
12278 if (!Approximate)
12279 Combine = IntRange::difference;
12280 break;
12281
12282 case BO_Mul:
12283 if (!Approximate)
12284 Combine = IntRange::product;
12285 break;
12286
12287 // The width of a division result is mostly determined by the size
12288 // of the LHS.
12289 case BO_Div: {
12290 // Don't 'pre-truncate' the operands.
12291 unsigned opWidth = C.getIntWidth(GetExprType(E));
12292 std::optional<IntRange> L = TryGetExprRange(
12293 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12294 if (!L)
12295 return std::nullopt;
12296
12297 // If the divisor is constant, use that.
12298 if (std::optional<llvm::APSInt> divisor =
12299 BO->getRHS()->getIntegerConstantExpr(C)) {
12300 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12301 if (log2 >= L->Width)
12302 L->Width = (L->NonNegative ? 0 : 1);
12303 else
12304 L->Width = std::min(L->Width - log2, MaxWidth);
12305 return L;
12306 }
12307
12308 // Otherwise, just use the LHS's width.
12309 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12310 // could be -1.
12311 std::optional<IntRange> R = TryGetExprRange(
12312 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12313 if (!R)
12314 return std::nullopt;
12315
12316 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12317 }
12318
12319 case BO_Rem:
12320 Combine = IntRange::rem;
12321 break;
12322
12323 // The default behavior is okay for these.
12324 case BO_Xor:
12325 case BO_Or:
12326 break;
12327 }
12328
12329 // Combine the two ranges, but limit the result to the type in which we
12330 // performed the computation.
12331 QualType T = GetExprType(E);
12332 unsigned opWidth = C.getIntWidth(T);
12333 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12334 InConstantContext, Approximate);
12335 if (!L)
12336 return std::nullopt;
12337
12338 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12339 InConstantContext, Approximate);
12340 if (!R)
12341 return std::nullopt;
12342
12343 IntRange C = Combine(*L, *R);
12344 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12345 C.Width = std::min(C.Width, MaxWidth);
12346 return C;
12347 }
12348
12349 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12350 switch (UO->getOpcode()) {
12351 // Boolean-valued operations are white-listed.
12352 case UO_LNot:
12353 return IntRange::forBoolType();
12354
12355 // Operations with opaque sources are black-listed.
12356 case UO_Deref:
12357 case UO_AddrOf: // should be impossible
12358 return IntRange::forValueOfType(C, GetExprType(E));
12359
12360 case UO_Minus: {
12361 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12362 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12363 Approximate);
12364 }
12365
12366 std::optional<IntRange> SubRange = TryGetExprRange(
12367 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12368
12369 if (!SubRange)
12370 return std::nullopt;
12371
12372 // If the range was previously non-negative, we need an extra bit for the
12373 // sign bit. Otherwise, we need an extra bit because the negation of the
12374 // most-negative value is one bit wider than that value.
12375 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12376 }
12377
12378 case UO_Not: {
12379 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12380 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12381 Approximate);
12382 }
12383
12384 std::optional<IntRange> SubRange = TryGetExprRange(
12385 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12386
12387 if (!SubRange)
12388 return std::nullopt;
12389
12390 // The width increments by 1 if the sub-expression cannot be negative
12391 // since it now can be.
12392 return IntRange(
12393 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12394 false);
12395 }
12396
12397 default:
12398 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12399 Approximate);
12400 }
12401 }
12402
12403 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12404 // The source expression is null for the OpaqueValueExpr that stands in for
12405 // a non-type template argument of pointer or reference type; fall back to
12406 // the range of the type in that case.
12407 if (const Expr *SourceExpr = OVE->getSourceExpr())
12408 return TryGetExprRange(C, SourceExpr, MaxWidth, InConstantContext,
12409 Approximate);
12410 }
12411
12412 if (const auto *BitField = E->getSourceBitField())
12413 return IntRange(BitField->getBitWidthValue(),
12414 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12415
12416 if (GetExprType(E)->isVoidType())
12417 return std::nullopt;
12418
12419 return IntRange::forValueOfType(C, GetExprType(E));
12420}
12421
12422static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12423 bool InConstantContext,
12424 bool Approximate) {
12425 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12426 Approximate);
12427}
12428
12429/// Checks whether the given value, which currently has the given
12430/// source semantics, has the same value when coerced through the
12431/// target semantics.
12432static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12433 const llvm::fltSemantics &Src,
12434 const llvm::fltSemantics &Tgt) {
12435 llvm::APFloat truncated = value;
12436
12437 bool ignored;
12438 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12439 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12440
12441 return truncated.bitwiseIsEqual(value);
12442}
12443
12444/// Checks whether the given value, which currently has the given
12445/// source semantics, has the same value when coerced through the
12446/// target semantics.
12447///
12448/// The value might be a vector of floats (or a complex number).
12449static bool IsSameFloatAfterCast(const APValue &value,
12450 const llvm::fltSemantics &Src,
12451 const llvm::fltSemantics &Tgt) {
12452 if (value.isFloat())
12453 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12454
12455 if (value.isVector()) {
12456 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12457 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12458 return false;
12459 return true;
12460 }
12461
12462 if (value.isMatrix()) {
12463 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12464 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12465 return false;
12466 return true;
12467 }
12468
12469 assert(value.isComplexFloat());
12470 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12471 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12472}
12473
12474static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12475 bool IsListInit = false);
12476
12477static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12478 // Suppress cases where we are comparing against an enum constant.
12479 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12480 if (isa<EnumConstantDecl>(DR->getDecl()))
12481 return true;
12482
12483 // Suppress cases where the value is expanded from a macro, unless that macro
12484 // is how a language represents a boolean literal. This is the case in both C
12485 // and Objective-C.
12486 SourceLocation BeginLoc = E->getBeginLoc();
12487 if (BeginLoc.isMacroID()) {
12488 StringRef MacroName = Lexer::getImmediateMacroName(
12489 BeginLoc, S.getSourceManager(), S.getLangOpts());
12490 return MacroName != "YES" && MacroName != "NO" &&
12491 MacroName != "true" && MacroName != "false";
12492 }
12493
12494 return false;
12495}
12496
12497static bool isKnownToHaveUnsignedValue(const Expr *E) {
12498 return E->getType()->isIntegerType() &&
12499 (!E->getType()->isSignedIntegerType() ||
12501}
12502
12503namespace {
12504/// The promoted range of values of a type. In general this has the
12505/// following structure:
12506///
12507/// |-----------| . . . |-----------|
12508/// ^ ^ ^ ^
12509/// Min HoleMin HoleMax Max
12510///
12511/// ... where there is only a hole if a signed type is promoted to unsigned
12512/// (in which case Min and Max are the smallest and largest representable
12513/// values).
12514struct PromotedRange {
12515 // Min, or HoleMax if there is a hole.
12516 llvm::APSInt PromotedMin;
12517 // Max, or HoleMin if there is a hole.
12518 llvm::APSInt PromotedMax;
12519
12520 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12521 if (R.Width == 0)
12522 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12523 else if (R.Width >= BitWidth && !Unsigned) {
12524 // Promotion made the type *narrower*. This happens when promoting
12525 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12526 // Treat all values of 'signed int' as being in range for now.
12527 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12528 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12529 } else {
12530 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12531 .extOrTrunc(BitWidth);
12532 PromotedMin.setIsUnsigned(Unsigned);
12533
12534 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12535 .extOrTrunc(BitWidth);
12536 PromotedMax.setIsUnsigned(Unsigned);
12537 }
12538 }
12539
12540 // Determine whether this range is contiguous (has no hole).
12541 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12542
12543 // Where a constant value is within the range.
12544 enum ComparisonResult {
12545 LT = 0x1,
12546 LE = 0x2,
12547 GT = 0x4,
12548 GE = 0x8,
12549 EQ = 0x10,
12550 NE = 0x20,
12551 InRangeFlag = 0x40,
12552
12553 Less = LE | LT | NE,
12554 Min = LE | InRangeFlag,
12555 InRange = InRangeFlag,
12556 Max = GE | InRangeFlag,
12557 Greater = GE | GT | NE,
12558
12559 OnlyValue = LE | GE | EQ | InRangeFlag,
12560 InHole = NE
12561 };
12562
12563 ComparisonResult compare(const llvm::APSInt &Value) const {
12564 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12565 Value.isUnsigned() == PromotedMin.isUnsigned());
12566 if (!isContiguous()) {
12567 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12568 if (Value.isMinValue()) return Min;
12569 if (Value.isMaxValue()) return Max;
12570 if (Value >= PromotedMin) return InRange;
12571 if (Value <= PromotedMax) return InRange;
12572 return InHole;
12573 }
12574
12575 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12576 case -1: return Less;
12577 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12578 case 1:
12579 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12580 case -1: return InRange;
12581 case 0: return Max;
12582 case 1: return Greater;
12583 }
12584 }
12585
12586 llvm_unreachable("impossible compare result");
12587 }
12588
12589 static std::optional<StringRef>
12590 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12591 if (Op == BO_Cmp) {
12592 ComparisonResult LTFlag = LT, GTFlag = GT;
12593 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12594
12595 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12596 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12597 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12598 return std::nullopt;
12599 }
12600
12601 ComparisonResult TrueFlag, FalseFlag;
12602 if (Op == BO_EQ) {
12603 TrueFlag = EQ;
12604 FalseFlag = NE;
12605 } else if (Op == BO_NE) {
12606 TrueFlag = NE;
12607 FalseFlag = EQ;
12608 } else {
12609 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12610 TrueFlag = LT;
12611 FalseFlag = GE;
12612 } else {
12613 TrueFlag = GT;
12614 FalseFlag = LE;
12615 }
12616 if (Op == BO_GE || Op == BO_LE)
12617 std::swap(TrueFlag, FalseFlag);
12618 }
12619 if (R & TrueFlag)
12620 return StringRef("true");
12621 if (R & FalseFlag)
12622 return StringRef("false");
12623 return std::nullopt;
12624 }
12625};
12626}
12627
12628static bool HasEnumType(const Expr *E) {
12629 // Strip off implicit integral promotions.
12630 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12631 if (ICE->getCastKind() != CK_IntegralCast &&
12632 ICE->getCastKind() != CK_NoOp)
12633 break;
12634 E = ICE->getSubExpr();
12635 }
12636
12637 return E->getType()->isEnumeralType();
12638}
12639
12641 // The values of this enumeration are used in the diagnostics
12642 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12643 enum ConstantValueKind {
12644 Miscellaneous = 0,
12645 LiteralTrue,
12646 LiteralFalse
12647 };
12648 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12649 return BL->getValue() ? ConstantValueKind::LiteralTrue
12650 : ConstantValueKind::LiteralFalse;
12651 return ConstantValueKind::Miscellaneous;
12652}
12653
12656 const llvm::APSInt &Value,
12657 bool RhsConstant) {
12659 return false;
12660
12661 Expr *OriginalOther = Other;
12662
12663 Constant = Constant->IgnoreParenImpCasts();
12664 Other = Other->IgnoreParenImpCasts();
12665
12666 // Suppress warnings on tautological comparisons between values of the same
12667 // enumeration type. There are only two ways we could warn on this:
12668 // - If the constant is outside the range of representable values of
12669 // the enumeration. In such a case, we should warn about the cast
12670 // to enumeration type, not about the comparison.
12671 // - If the constant is the maximum / minimum in-range value. For an
12672 // enumeratin type, such comparisons can be meaningful and useful.
12673 if (Constant->getType()->isEnumeralType() &&
12674 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12675 return false;
12676
12677 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12678 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12679 if (!OtherValueRange)
12680 return false;
12681
12682 QualType OtherT = Other->getType();
12683 if (const auto *AT = OtherT->getAs<AtomicType>())
12684 OtherT = AT->getValueType();
12685 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12686
12687 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12688 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12689 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12690 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12691 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12692
12693 // Whether we're treating Other as being a bool because of the form of
12694 // expression despite it having another type (typically 'int' in C).
12695 bool OtherIsBooleanDespiteType =
12696 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12697 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12698 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12699
12700 // Check if all values in the range of possible values of this expression
12701 // lead to the same comparison outcome.
12702 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12703 Value.isUnsigned());
12704 auto Cmp = OtherPromotedValueRange.compare(Value);
12705 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12706 if (!Result)
12707 return false;
12708
12709 // Also consider the range determined by the type alone. This allows us to
12710 // classify the warning under the proper diagnostic group.
12711 bool TautologicalTypeCompare = false;
12712 {
12713 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12714 Value.isUnsigned());
12715 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12716 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12717 RhsConstant)) {
12718 TautologicalTypeCompare = true;
12719 Cmp = TypeCmp;
12721 }
12722 }
12723
12724 // Don't warn if the non-constant operand actually always evaluates to the
12725 // same value.
12726 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12727 return false;
12728
12729 // Suppress the diagnostic for an in-range comparison if the constant comes
12730 // from a macro or enumerator. We don't want to diagnose
12731 //
12732 // some_long_value <= INT_MAX
12733 //
12734 // when sizeof(int) == sizeof(long).
12735 bool InRange = Cmp & PromotedRange::InRangeFlag;
12736 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12737 return false;
12738
12739 // A comparison of an unsigned bit-field against 0 is really a type problem,
12740 // even though at the type level the bit-field might promote to 'signed int'.
12741 if (Other->refersToBitField() && InRange && Value == 0 &&
12742 Other->getType()->isUnsignedIntegerOrEnumerationType())
12743 TautologicalTypeCompare = true;
12744
12745 // If this is a comparison to an enum constant, include that
12746 // constant in the diagnostic.
12747 const EnumConstantDecl *ED = nullptr;
12748 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12749 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12750
12751 // Should be enough for uint128 (39 decimal digits)
12752 SmallString<64> PrettySourceValue;
12753 llvm::raw_svector_ostream OS(PrettySourceValue);
12754 if (ED) {
12755 OS << '\'' << *ED << "' (" << Value << ")";
12756 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12757 Constant->IgnoreParenImpCasts())) {
12758 OS << (BL->getValue() ? "YES" : "NO");
12759 } else {
12760 OS << Value;
12761 }
12762
12763 if (!TautologicalTypeCompare) {
12764 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12765 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12766 << E->getOpcodeStr() << OS.str() << *Result
12767 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12768 return true;
12769 }
12770
12771 if (IsObjCSignedCharBool) {
12773 S.PDiag(diag::warn_tautological_compare_objc_bool)
12774 << OS.str() << *Result);
12775 return true;
12776 }
12777
12778 // FIXME: We use a somewhat different formatting for the in-range cases and
12779 // cases involving boolean values for historical reasons. We should pick a
12780 // consistent way of presenting these diagnostics.
12781 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12782
12784 E->getOperatorLoc(), E,
12785 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12786 : diag::warn_tautological_bool_compare)
12787 << OS.str() << classifyConstantValue(Constant) << OtherT
12788 << OtherIsBooleanDespiteType << *Result
12789 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12790 } else {
12791 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12792 unsigned Diag =
12793 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12794 ? (HasEnumType(OriginalOther)
12795 ? diag::warn_unsigned_enum_always_true_comparison
12796 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12797 : diag::warn_unsigned_always_true_comparison)
12798 : diag::warn_tautological_constant_compare;
12799
12800 S.Diag(E->getOperatorLoc(), Diag)
12801 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12802 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12803 }
12804
12805 return true;
12806}
12807
12808/// Analyze the operands of the given comparison. Implements the
12809/// fallback case from AnalyzeComparison.
12814
12815/// Implements -Wsign-compare.
12816///
12817/// \param E the binary operator to check for warnings
12819 // The type the comparison is being performed in.
12820 QualType T = E->getLHS()->getType();
12821
12822 // Only analyze comparison operators where both sides have been converted to
12823 // the same type.
12825 return AnalyzeImpConvsInComparison(S, E);
12826
12827 // Don't analyze value-dependent comparisons directly.
12828 if (E->isValueDependent())
12829 return AnalyzeImpConvsInComparison(S, E);
12830
12831 Expr *LHS = E->getLHS();
12832 Expr *RHS = E->getRHS();
12833
12834 if (T->isIntegralType(S.Context)) {
12835 std::optional<llvm::APSInt> RHSValue =
12837 std::optional<llvm::APSInt> LHSValue =
12839
12840 // We don't care about expressions whose result is a constant.
12841 if (RHSValue && LHSValue)
12842 return AnalyzeImpConvsInComparison(S, E);
12843
12844 // We only care about expressions where just one side is literal
12845 if ((bool)RHSValue ^ (bool)LHSValue) {
12846 // Is the constant on the RHS or LHS?
12847 const bool RhsConstant = (bool)RHSValue;
12848 Expr *Const = RhsConstant ? RHS : LHS;
12849 Expr *Other = RhsConstant ? LHS : RHS;
12850 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12851
12852 // Check whether an integer constant comparison results in a value
12853 // of 'true' or 'false'.
12854 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12855 return AnalyzeImpConvsInComparison(S, E);
12856 }
12857 }
12858
12859 if (!T->hasUnsignedIntegerRepresentation()) {
12860 // We don't do anything special if this isn't an unsigned integral
12861 // comparison: we're only interested in integral comparisons, and
12862 // signed comparisons only happen in cases we don't care to warn about.
12863 return AnalyzeImpConvsInComparison(S, E);
12864 }
12865
12866 LHS = LHS->IgnoreParenImpCasts();
12867 RHS = RHS->IgnoreParenImpCasts();
12868
12869 if (!S.getLangOpts().CPlusPlus) {
12870 // Avoid warning about comparison of integers with different signs when
12871 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12872 // the type of `E`.
12873 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12874 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12875 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12876 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12877 }
12878
12879 // Check to see if one of the (unmodified) operands is of different
12880 // signedness.
12881 Expr *signedOperand, *unsignedOperand;
12883 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12884 "unsigned comparison between two signed integer expressions?");
12885 signedOperand = LHS;
12886 unsignedOperand = RHS;
12887 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12888 signedOperand = RHS;
12889 unsignedOperand = LHS;
12890 } else {
12891 return AnalyzeImpConvsInComparison(S, E);
12892 }
12893
12894 // Otherwise, calculate the effective range of the signed operand.
12895 std::optional<IntRange> signedRange =
12897 /*Approximate=*/true);
12898 if (!signedRange)
12899 return;
12900
12901 // Go ahead and analyze implicit conversions in the operands. Note
12902 // that we skip the implicit conversions on both sides.
12905
12906 // If the signed range is non-negative, -Wsign-compare won't fire.
12907 if (signedRange->NonNegative)
12908 return;
12909
12910 // For (in)equality comparisons, if the unsigned operand is a
12911 // constant which cannot collide with a overflowed signed operand,
12912 // then reinterpreting the signed operand as unsigned will not
12913 // change the result of the comparison.
12914 if (E->isEqualityOp()) {
12915 unsigned comparisonWidth = S.Context.getIntWidth(T);
12916 std::optional<IntRange> unsignedRange = TryGetExprRange(
12917 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12918 /*Approximate=*/true);
12919 if (!unsignedRange)
12920 return;
12921
12922 // We should never be unable to prove that the unsigned operand is
12923 // non-negative.
12924 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12925
12926 if (unsignedRange->Width < comparisonWidth)
12927 return;
12928 }
12929
12931 S.PDiag(diag::warn_mixed_sign_comparison)
12932 << LHS->getType() << RHS->getType()
12933 << LHS->getSourceRange() << RHS->getSourceRange());
12934}
12935
12936/// Analyzes an attempt to assign the given value to a bitfield.
12937///
12938/// Returns true if there was something fishy about the attempt.
12940 SourceLocation InitLoc) {
12941 assert(Bitfield->isBitField());
12942 if (Bitfield->isInvalidDecl())
12943 return false;
12944
12945 // White-list bool bitfields.
12946 QualType BitfieldType = Bitfield->getType();
12947 if (BitfieldType->isBooleanType())
12948 return false;
12949
12950 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12951 // If the underlying enum type was not explicitly specified as an unsigned
12952 // type and the enum contain only positive values, MSVC++ will cause an
12953 // inconsistency by storing this as a signed type.
12954 if (S.getLangOpts().CPlusPlus11 &&
12955 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12956 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12957 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12958 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12959 << BitfieldEnumDecl;
12960 }
12961 }
12962
12963 // Ignore value- or type-dependent expressions.
12964 if (Bitfield->getBitWidth()->isValueDependent() ||
12965 Bitfield->getBitWidth()->isTypeDependent() ||
12966 Init->isValueDependent() ||
12967 Init->isTypeDependent())
12968 return false;
12969
12970 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12971 unsigned FieldWidth = Bitfield->getBitWidthValue();
12972
12974 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12976 // The RHS is not constant. If the RHS has an enum type, make sure the
12977 // bitfield is wide enough to hold all the values of the enum without
12978 // truncation.
12979 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12980 const PreferredTypeAttr *PTAttr = nullptr;
12981 if (!ED) {
12982 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12983 if (PTAttr)
12984 ED = PTAttr->getType()->getAsEnumDecl();
12985 }
12986 if (ED) {
12987 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12988
12989 // Enum types are implicitly signed on Windows, so check if there are any
12990 // negative enumerators to see if the enum was intended to be signed or
12991 // not.
12992 bool SignedEnum = ED->getNumNegativeBits() > 0;
12993
12994 // Check for surprising sign changes when assigning enum values to a
12995 // bitfield of different signedness. If the bitfield is signed and we
12996 // have exactly the right number of bits to store this unsigned enum,
12997 // suggest changing the enum to an unsigned type. This typically happens
12998 // on Windows where unfixed enums always use an underlying type of 'int'.
12999 unsigned DiagID = 0;
13000 if (SignedEnum && !SignedBitfield) {
13001 DiagID =
13002 PTAttr == nullptr
13003 ? diag::warn_unsigned_bitfield_assigned_signed_enum
13004 : diag::
13005 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
13006 } else if (SignedBitfield && !SignedEnum &&
13007 ED->getNumPositiveBits() == FieldWidth) {
13008 DiagID =
13009 PTAttr == nullptr
13010 ? diag::warn_signed_bitfield_enum_conversion
13011 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
13012 }
13013 if (DiagID) {
13014 S.Diag(InitLoc, DiagID) << Bitfield << ED;
13015 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
13016 SourceRange TypeRange =
13017 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
13018 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
13019 << SignedEnum << TypeRange;
13020 if (PTAttr)
13021 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13022 << ED;
13023 }
13024
13025 // Compute the required bitwidth. If the enum has negative values, we need
13026 // one more bit than the normal number of positive bits to represent the
13027 // sign bit.
13028 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
13029 ED->getNumNegativeBits())
13030 : ED->getNumPositiveBits();
13031
13032 // Check the bitwidth.
13033 if (BitsNeeded > FieldWidth) {
13034 Expr *WidthExpr = Bitfield->getBitWidth();
13035 auto DiagID =
13036 PTAttr == nullptr
13037 ? diag::warn_bitfield_too_small_for_enum
13038 : diag::warn_preferred_type_bitfield_too_small_for_enum;
13039 S.Diag(InitLoc, DiagID) << Bitfield << ED;
13040 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
13041 << BitsNeeded << ED << WidthExpr->getSourceRange();
13042 if (PTAttr)
13043 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13044 << ED;
13045 }
13046 }
13047
13048 return false;
13049 }
13050
13051 llvm::APSInt Value = Result.Val.getInt();
13052
13053 unsigned OriginalWidth = Value.getBitWidth();
13054
13055 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
13056 // false positives where the user is demonstrating they intend to use the
13057 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
13058 // to a one-bit bit-field to see if the value came from a macro named 'true'.
13059 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
13060 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
13061 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
13062 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
13063 S.findMacroSpelling(MaybeMacroLoc, "true"))
13064 return false;
13065 }
13066
13067 if (!Value.isSigned() || Value.isNegative())
13068 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
13069 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
13070 OriginalWidth = Value.getSignificantBits();
13071
13072 if (OriginalWidth <= FieldWidth)
13073 return false;
13074
13075 // Compute the value which the bitfield will contain.
13076 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
13077 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
13078
13079 // Check whether the stored value is equal to the original value.
13080 TruncatedValue = TruncatedValue.extend(OriginalWidth);
13081 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
13082 return false;
13083
13084 std::string PrettyValue = toString(Value, 10);
13085 std::string PrettyTrunc = toString(TruncatedValue, 10);
13086
13087 S.Diag(InitLoc, OneAssignedToOneBitBitfield
13088 ? diag::warn_impcast_single_bit_bitield_precision_constant
13089 : diag::warn_impcast_bitfield_precision_constant)
13090 << PrettyValue << PrettyTrunc << OriginalInit->getType()
13091 << Init->getSourceRange();
13092
13093 return true;
13094}
13095
13096/// Analyze the given simple or compound assignment for warning-worthy
13097/// operations.
13099 // Just recurse on the LHS.
13101
13102 // We want to recurse on the RHS as normal unless we're assigning to
13103 // a bitfield.
13104 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
13105 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
13106 E->getOperatorLoc())) {
13107 // Recurse, ignoring any implicit conversions on the RHS.
13109 E->getOperatorLoc());
13110 }
13111 }
13112
13113 // Set context flag for overflow behavior type assignment analysis, use RAII
13114 // pattern to handle nested assignments.
13115 llvm::SaveAndRestore OBTAssignmentContext(
13117
13119
13120 // Diagnose implicitly sequentially-consistent atomic assignment.
13121 if (E->getLHS()->getType()->isAtomicType())
13122 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13123}
13124
13125/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13126static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13127 QualType T, SourceLocation CContext, unsigned diag,
13128 bool PruneControlFlow = false) {
13129 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13130 // address space annotations isn't really useful. The warnings aren't because
13131 // you're converting a `private int` to `unsigned int`, it is because you're
13132 // conerting `int` to `unsigned int`.
13133 if (SourceType.hasAddressSpace())
13134 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
13135 if (T.hasAddressSpace())
13137 if (PruneControlFlow) {
13139 S.PDiag(diag)
13140 << SourceType << T << E->getSourceRange()
13141 << SourceRange(CContext));
13142 return;
13143 }
13144 S.Diag(E->getExprLoc(), diag)
13145 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13146}
13147
13148/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13149static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13150 SourceLocation CContext, unsigned diag,
13151 bool PruneControlFlow = false) {
13152 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
13153}
13154
13155/// Diagnose an implicit cast from a floating point value to an integer value.
13156static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13157 SourceLocation CContext) {
13158 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13159 bool PruneWarnings = S.inTemplateInstantiation();
13160
13161 const Expr *InnerE = E->IgnoreParenImpCasts();
13162 // We also want to warn on, e.g., "int i = -1.234"
13163 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13164 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13165 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13166
13167 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13168
13169 llvm::APFloat Value(0.0);
13170 bool IsConstant =
13172 if (!IsConstant) {
13173 if (S.ObjC().isSignedCharBool(T)) {
13175 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13176 << E->getType());
13177 }
13178
13179 return DiagnoseImpCast(S, E, T, CContext,
13180 diag::warn_impcast_float_integer, PruneWarnings);
13181 }
13182
13183 bool isExact = false;
13184
13185 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13186 T->hasUnsignedIntegerRepresentation());
13187 llvm::APFloat::opStatus Result = Value.convertToInteger(
13188 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13189
13190 // FIXME: Force the precision of the source value down so we don't print
13191 // digits which are usually useless (we don't really care here if we
13192 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13193 // would automatically print the shortest representation, but it's a bit
13194 // tricky to implement.
13195 SmallString<16> PrettySourceValue;
13196 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13197 precision = (precision * 59 + 195) / 196;
13198 Value.toString(PrettySourceValue, precision);
13199
13200 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
13202 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13203 << PrettySourceValue);
13204 }
13205
13206 if (Result == llvm::APFloat::opOK && isExact) {
13207 if (IsLiteral) return;
13208 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13209 PruneWarnings);
13210 }
13211
13212 // Conversion of a floating-point value to a non-bool integer where the
13213 // integral part cannot be represented by the integer type is undefined.
13214 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13215 return DiagnoseImpCast(
13216 S, E, T, CContext,
13217 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13218 : diag::warn_impcast_float_to_integer_out_of_range,
13219 PruneWarnings);
13220
13221 unsigned DiagID = 0;
13222 if (IsLiteral) {
13223 // Warn on floating point literal to integer.
13224 DiagID = diag::warn_impcast_literal_float_to_integer;
13225 } else if (IntegerValue == 0) {
13226 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13227 return DiagnoseImpCast(S, E, T, CContext,
13228 diag::warn_impcast_float_integer, PruneWarnings);
13229 }
13230 // Warn on non-zero to zero conversion.
13231 DiagID = diag::warn_impcast_float_to_integer_zero;
13232 } else {
13233 if (IntegerValue.isUnsigned()) {
13234 if (!IntegerValue.isMaxValue()) {
13235 return DiagnoseImpCast(S, E, T, CContext,
13236 diag::warn_impcast_float_integer, PruneWarnings);
13237 }
13238 } else { // IntegerValue.isSigned()
13239 if (!IntegerValue.isMaxSignedValue() &&
13240 !IntegerValue.isMinSignedValue()) {
13241 return DiagnoseImpCast(S, E, T, CContext,
13242 diag::warn_impcast_float_integer, PruneWarnings);
13243 }
13244 }
13245 // Warn on evaluatable floating point expression to integer conversion.
13246 DiagID = diag::warn_impcast_float_to_integer;
13247 }
13248
13249 SmallString<16> PrettyTargetValue;
13250 if (IsBool)
13251 PrettyTargetValue = Value.isZero() ? "false" : "true";
13252 else
13253 IntegerValue.toString(PrettyTargetValue);
13254
13255 if (PruneWarnings) {
13257 S.PDiag(DiagID)
13258 << E->getType() << T.getUnqualifiedType()
13259 << PrettySourceValue << PrettyTargetValue
13260 << E->getSourceRange() << SourceRange(CContext));
13261 } else {
13262 S.Diag(E->getExprLoc(), DiagID)
13263 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13264 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13265 }
13266}
13267
13268/// Analyze the given compound assignment for the possible losing of
13269/// floating-point precision.
13271 assert(isa<CompoundAssignOperator>(E) &&
13272 "Must be compound assignment operation");
13273 // Recurse on the LHS and RHS in here
13276
13277 if (E->getLHS()->getType()->isAtomicType())
13278 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13279
13280 // Now check the outermost expression
13281 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13282 const auto *RBT = cast<CompoundAssignOperator>(E)
13283 ->getComputationResultType()
13284 ->getAs<BuiltinType>();
13285
13286 // The below checks assume source is floating point.
13287 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13288
13289 // If source is floating point but target is an integer.
13290 if (ResultBT->isInteger())
13291 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13292 E->getExprLoc(), diag::warn_impcast_float_integer);
13293
13294 if (!ResultBT->isFloatingPoint())
13295 return;
13296
13297 // If both source and target are floating points, warn about losing precision.
13299 QualType(ResultBT, 0), QualType(RBT, 0));
13300 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13301 // warn about dropping FP rank.
13302 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13303 diag::warn_impcast_float_result_precision);
13304}
13305
13306static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13307 IntRange Range) {
13308 if (!Range.Width) return "0";
13309
13310 llvm::APSInt ValueInRange = Value;
13311 ValueInRange.setIsSigned(!Range.NonNegative);
13312 ValueInRange = ValueInRange.trunc(Range.Width);
13313 return toString(ValueInRange, 10);
13314}
13315
13316static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13317 bool ToBool) {
13318 if (!isa<ImplicitCastExpr>(Ex))
13319 return false;
13320
13321 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13323 const Type *Source =
13325 if (Target->isDependentType())
13326 return false;
13327
13328 const auto *FloatCandidateBT =
13329 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13330 const Type *BoolCandidateType = ToBool ? Target : Source;
13331
13332 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13333 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13334}
13335
13336static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13337 SourceLocation CC) {
13338 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13339 const Expr *CurrA = TheCall->getArg(I);
13340 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13341 continue;
13342
13343 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13344 S, TheCall->getArg(I - 1), false));
13345 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13346 S, TheCall->getArg(I + 1), false));
13347 if (IsSwapped) {
13348 // Warn on this floating-point to bool conversion.
13350 CurrA->getType(), CC,
13351 diag::warn_impcast_floating_point_to_bool);
13352 }
13353 }
13354}
13355
13357 SourceLocation CC) {
13358 // Don't warn on functions which have return type nullptr_t.
13359 if (isa<CallExpr>(E))
13360 return;
13361
13362 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13363 const Expr *NewE = E->IgnoreParenImpCasts();
13364 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13365 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13366 if (!IsGNUNullExpr && !HasNullPtrType)
13367 return;
13368
13369 // Return if target type is a safe conversion.
13370 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13371 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13372 return;
13373
13374 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13375 E->getExprLoc()))
13376 return;
13377
13379
13380 // Venture through the macro stacks to get to the source of macro arguments.
13381 // The new location is a better location than the complete location that was
13382 // passed in.
13383 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13385
13386 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13387 if (IsGNUNullExpr && Loc.isMacroID()) {
13388 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13389 Loc, S.SourceMgr, S.getLangOpts());
13390 if (MacroName == "NULL")
13392 }
13393
13394 // Only warn if the null and context location are in the same macro expansion.
13395 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13396 return;
13397
13398 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13399 << HasNullPtrType << T << SourceRange(CC)
13402}
13403
13404// Helper function to filter out cases for constant width constant conversion.
13405// Don't warn on unsigned char array initialization or for non-decimal
13406// values.
13408 SourceLocation CC) {
13409 // If initializing from a constant, and the constant starts with '0',
13410 // then it is a binary, octal, or hexadecimal. Allow these constants
13411 // to fill all the bits, even if there is a sign change.
13412 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13413 const char FirstLiteralCharacter =
13414 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13415 if (FirstLiteralCharacter == '0')
13416 return false;
13417 }
13418
13419 // If the CC location points to a '{' and the type is an unsigned char
13420 // type, assume it is an array initialization.
13421 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13422 const char FirstContextCharacter =
13424 if (FirstContextCharacter == '{')
13425 return false;
13426 }
13427
13428 return true;
13429}
13430
13432 const auto *IL = dyn_cast<IntegerLiteral>(E);
13433 if (!IL) {
13434 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13435 if (UO->getOpcode() == UO_Minus)
13436 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13437 }
13438 }
13439
13440 return IL;
13441}
13442
13444 E = E->IgnoreParenImpCasts();
13445 SourceLocation ExprLoc = E->getExprLoc();
13446
13447 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13448 BinaryOperator::Opcode Opc = BO->getOpcode();
13450 // Do not diagnose unsigned shifts.
13451 if (Opc == BO_Shl) {
13452 const auto *LHS = getIntegerLiteral(BO->getLHS());
13453 const auto *RHS = getIntegerLiteral(BO->getRHS());
13454 if (LHS && LHS->getValue() == 0)
13455 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13456 else if (!E->isValueDependent() && LHS && RHS &&
13457 RHS->getValue().isNonNegative() &&
13459 S.Diag(ExprLoc, diag::warn_left_shift_always)
13460 << (Result.Val.getInt() != 0);
13461 else if (E->getType()->isSignedIntegerType())
13462 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13465 ") != 0");
13466 }
13467 }
13468
13469 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13470 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13471 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13472 if (!LHS || !RHS)
13473 return;
13474 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13475 (RHS->getValue() == 0 || RHS->getValue() == 1))
13476 // Do not diagnose common idioms.
13477 return;
13478 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13479 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13480 }
13481}
13482
13484 const Type *Target, Expr *E,
13485 QualType T,
13486 SourceLocation CC) {
13487 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13488 Source != Target);
13489
13490 // Lone surrogates have a distinct representation in UTF-32.
13491 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13492 // so don't warn on such conversion.
13493 if (Source->isChar16Type() && Target->isChar32Type())
13494 return;
13495
13499 llvm::APSInt Value(32);
13500 Value = Result.Val.getInt();
13501 bool IsASCII = Value <= 0x7F;
13502 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13503 bool ConversionPreservesSemantics =
13504 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13505
13506 if (!ConversionPreservesSemantics) {
13507 auto IsSingleCodeUnitCP = [](const QualType &T,
13508 const llvm::APSInt &Value) {
13509 if (T->isChar8Type())
13510 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13511 if (T->isChar16Type())
13512 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13513 assert(T->isChar32Type());
13514 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13515 };
13516
13517 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13518 << E->getType() << T
13519 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13520 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13521 }
13522 } else {
13523 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13525 DiagnoseImpCast(S, E, T, CC,
13526 LosesPrecision ? diag::warn_impcast_unicode_precision
13527 : diag::warn_impcast_unicode_char_type);
13528 }
13529}
13530
13532 From = Context.getCanonicalType(From);
13533 To = Context.getCanonicalType(To);
13534 QualType MaybePointee = From->getPointeeType();
13535 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13536 From = MaybePointee;
13537 MaybePointee = To->getPointeeType();
13538 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13539 To = MaybePointee;
13540
13541 if (const auto *FromFn = From->getAs<FunctionType>()) {
13542 if (const auto *ToFn = To->getAs<FunctionType>()) {
13543 if (FromFn->getCFIUncheckedCalleeAttr() &&
13544 !ToFn->getCFIUncheckedCalleeAttr())
13545 return true;
13546 }
13547 }
13548 return false;
13549}
13550
13552 bool *ICContext, bool IsListInit) {
13553 if (E->isTypeDependent() || E->isValueDependent()) return;
13554
13555 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13556 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13557 if (Source == Target) return;
13558 if (Target->isDependentType()) return;
13559
13560 // If the conversion context location is invalid don't complain. We also
13561 // don't want to emit a warning if the issue occurs from the expansion of
13562 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13563 // delay this check as long as possible. Once we detect we are in that
13564 // scenario, we just return.
13565 if (CC.isInvalid())
13566 return;
13567
13568 if (Source->isAtomicType())
13569 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13570
13571 // Diagnose implicit casts to bool.
13572 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13573 if (isa<StringLiteral>(E))
13574 // Warn on string literal to bool. Checks for string literals in logical
13575 // and expressions, for instance, assert(0 && "error here"), are
13576 // prevented by a check in AnalyzeImplicitConversions().
13577 return DiagnoseImpCast(*this, E, T, CC,
13578 diag::warn_impcast_string_literal_to_bool);
13581 // This covers the literal expressions that evaluate to Objective-C
13582 // objects.
13583 return DiagnoseImpCast(*this, E, T, CC,
13584 diag::warn_impcast_objective_c_literal_to_bool);
13585 }
13586 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13587 // Warn on pointer to bool conversion that is always true.
13589 SourceRange(CC));
13590 }
13591 }
13592
13594
13595 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13596 // is a typedef for signed char (macOS), then that constant value has to be 1
13597 // or 0.
13598 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13601 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13603 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13604 << toString(Result.Val.getInt(), 10));
13605 }
13606 return;
13607 }
13608 }
13609
13610 // Check implicit casts from Objective-C collection literals to specialized
13611 // collection types, e.g., NSArray<NSString *> *.
13612 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13613 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13614 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13615 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13616
13617 // Strip complex types.
13618 if (isa<ComplexType>(Source)) {
13619 if (!isa<ComplexType>(Target)) {
13620 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13621 return;
13622
13623 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13624 return DiagnoseImpCast(*this, E, T, CC,
13625 diag::err_impcast_incompatible_type);
13626 }
13627
13628 return DiagnoseImpCast(*this, E, T, CC,
13630 ? diag::err_impcast_complex_scalar
13631 : diag::warn_impcast_complex_scalar);
13632 }
13633
13634 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13635 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13636 }
13637
13638 // Strip vector types.
13639 if (isa<VectorType>(Source)) {
13640 if (Target->isSveVLSBuiltinType() &&
13641 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13642 QualType(Source, 0)) ||
13643 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13644 QualType(Source, 0))))
13645 return;
13646
13647 if (Target->isRVVVLSBuiltinType() &&
13648 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13649 QualType(Source, 0)) ||
13650 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13651 QualType(Source, 0))))
13652 return;
13653
13654 if (!isa<VectorType>(Target)) {
13655 if (SourceMgr.isInSystemMacro(CC))
13656 return;
13657 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13658 }
13659 if (getLangOpts().HLSL &&
13660 Target->castAs<VectorType>()->getNumElements() <
13661 Source->castAs<VectorType>()->getNumElements()) {
13662 // Diagnose vector truncation but don't return. We may also want to
13663 // diagnose an element conversion.
13664 DiagnoseImpCast(*this, E, T, CC,
13665 diag::warn_hlsl_impcast_vector_truncation);
13666 }
13667
13668 // If the vector cast is cast between two vectors of the same size, it is
13669 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13670 if (!getLangOpts().HLSL &&
13671 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13672 return;
13673
13674 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13675 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13676 }
13677 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13678 Target = VecTy->getElementType().getTypePtr();
13679
13680 // Strip matrix types.
13681 if (isa<ConstantMatrixType>(Source)) {
13682 if (Target->isScalarType())
13683 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13684
13687 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13688 // Diagnose Matrix truncation but don't return. We may also want to
13689 // diagnose an element conversion.
13690 DiagnoseImpCast(*this, E, T, CC,
13691 diag::warn_hlsl_impcast_matrix_truncation);
13692 }
13693
13694 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13695 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13696 }
13697 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13698 Target = MatTy->getElementType().getTypePtr();
13699
13700 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13701 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13702
13703 // Strip SVE vector types
13704 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13705 // Need the original target type for vector type checks
13706 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13707 // Handle conversion from scalable to fixed when msve-vector-bits is
13708 // specified
13709 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13710 QualType(Source, 0)) ||
13711 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13712 QualType(Source, 0)))
13713 return;
13714
13715 // If the vector cast is cast between two vectors of the same size, it is
13716 // a bitcast, not a conversion.
13717 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13718 return;
13719
13720 Source = SourceBT->getSveEltType(Context).getTypePtr();
13721 }
13722
13723 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13724 Target = TargetBT->getSveEltType(Context).getTypePtr();
13725
13726 // Nothing to diagnose if stripping the wrappers left identical element types
13727 // (e.g. a scalar splatted to a vector of its own type).
13728 if (Source == Target)
13729 return;
13730
13731 // If the source is floating point...
13732 if (SourceBT && SourceBT->isFloatingPoint()) {
13733 // ...and the target is floating point...
13734 if (TargetBT && TargetBT->isFloatingPoint()) {
13735 // ...then warn if we're dropping FP rank.
13736
13738 QualType(SourceBT, 0), QualType(TargetBT, 0));
13739 if (Order > 0) {
13740 // Don't warn about float constants that are precisely
13741 // representable in the target type.
13742 Expr::EvalResult result;
13743 if (E->EvaluateAsRValue(result, Context)) {
13744 // Value might be a float, a float vector, or a float complex.
13746 result.Val,
13747 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13748 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13749 return;
13750 }
13751
13752 if (SourceMgr.isInSystemMacro(CC))
13753 return;
13754
13755 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13756 }
13757 // ... or possibly if we're increasing rank, too
13758 else if (Order < 0) {
13759 if (SourceMgr.isInSystemMacro(CC))
13760 return;
13761
13762 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13763 }
13764 return;
13765 }
13766
13767 // If the target is integral, always warn.
13768 if (TargetBT && TargetBT->isInteger()) {
13769 if (SourceMgr.isInSystemMacro(CC))
13770 return;
13771
13772 DiagnoseFloatingImpCast(*this, E, T, CC);
13773 }
13774
13775 // Detect the case where a call result is converted from floating-point to
13776 // to bool, and the final argument to the call is converted from bool, to
13777 // discover this typo:
13778 //
13779 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13780 //
13781 // FIXME: This is an incredibly special case; is there some more general
13782 // way to detect this class of misplaced-parentheses bug?
13783 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13784 // Check last argument of function call to see if it is an
13785 // implicit cast from a type matching the type the result
13786 // is being cast to.
13787 CallExpr *CEx = cast<CallExpr>(E);
13788 if (unsigned NumArgs = CEx->getNumArgs()) {
13789 Expr *LastA = CEx->getArg(NumArgs - 1);
13790 Expr *InnerE = LastA->IgnoreParenImpCasts();
13791 if (isa<ImplicitCastExpr>(LastA) &&
13792 InnerE->getType()->isBooleanType()) {
13793 // Warn on this floating-point to bool conversion
13794 DiagnoseImpCast(*this, E, T, CC,
13795 diag::warn_impcast_floating_point_to_bool);
13796 }
13797 }
13798 }
13799 return;
13800 }
13801
13802 // Valid casts involving fixed point types should be accounted for here.
13803 if (Source->isFixedPointType()) {
13804 if (Target->isUnsaturatedFixedPointType()) {
13808 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13809 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13810 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13811 if (Value > MaxVal || Value < MinVal) {
13813 PDiag(diag::warn_impcast_fixed_point_range)
13814 << Value.toString() << T
13815 << E->getSourceRange()
13816 << clang::SourceRange(CC));
13817 return;
13818 }
13819 }
13820 } else if (Target->isIntegerType()) {
13824 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13825
13826 bool Overflowed;
13827 llvm::APSInt IntResult = FXResult.convertToInt(
13828 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13829 &Overflowed);
13830
13831 if (Overflowed) {
13833 PDiag(diag::warn_impcast_fixed_point_range)
13834 << FXResult.toString() << T
13835 << E->getSourceRange()
13836 << clang::SourceRange(CC));
13837 return;
13838 }
13839 }
13840 }
13841 } else if (Target->isUnsaturatedFixedPointType()) {
13842 if (Source->isIntegerType()) {
13846 llvm::APSInt Value = Result.Val.getInt();
13847
13848 bool Overflowed;
13849 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13850 Value, Context.getFixedPointSemantics(T), &Overflowed);
13851
13852 if (Overflowed) {
13854 PDiag(diag::warn_impcast_fixed_point_range)
13855 << toString(Value, /*Radix=*/10) << T
13856 << E->getSourceRange()
13857 << clang::SourceRange(CC));
13858 return;
13859 }
13860 }
13861 }
13862 }
13863
13864 // If we are casting an integer type to a floating point type without
13865 // initialization-list syntax, we might lose accuracy if the floating
13866 // point type has a narrower significand than the integer type.
13867 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13868 TargetBT->isFloatingType() && !IsListInit) {
13869 // Determine the number of precision bits in the source integer type.
13870 std::optional<IntRange> SourceRange =
13872 /*Approximate=*/true);
13873 if (!SourceRange)
13874 return;
13875 unsigned int SourcePrecision = SourceRange->Width;
13876
13877 // Determine the number of precision bits in the
13878 // target floating point type.
13879 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13880 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13881
13882 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13883 SourcePrecision > TargetPrecision) {
13884
13885 if (std::optional<llvm::APSInt> SourceInt =
13887 // If the source integer is a constant, convert it to the target
13888 // floating point type. Issue a warning if the value changes
13889 // during the whole conversion.
13890 llvm::APFloat TargetFloatValue(
13891 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13892 llvm::APFloat::opStatus ConversionStatus =
13893 TargetFloatValue.convertFromAPInt(
13894 *SourceInt, SourceBT->isSignedInteger(),
13895 llvm::APFloat::rmNearestTiesToEven);
13896
13897 if (ConversionStatus != llvm::APFloat::opOK) {
13898 SmallString<32> PrettySourceValue;
13899 SourceInt->toString(PrettySourceValue, 10);
13900 SmallString<32> PrettyTargetValue;
13901 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13902
13904 E->getExprLoc(), E,
13905 PDiag(diag::warn_impcast_integer_float_precision_constant)
13906 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13907 << E->getSourceRange() << clang::SourceRange(CC));
13908 }
13909 } else {
13910 // Otherwise, the implicit conversion may lose precision.
13911 DiagnoseImpCast(*this, E, T, CC,
13912 diag::warn_impcast_integer_float_precision);
13913 }
13914 }
13915 }
13916
13917 DiagnoseNullConversion(*this, E, T, CC);
13918
13920
13921 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13922 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13923 return;
13924 }
13925
13926 if (Target->isBooleanType())
13927 DiagnoseIntInBoolContext(*this, E);
13928
13930 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13931 << QualType(Source, 0) << QualType(Target, 0);
13932 }
13933
13934 if (!Source->isIntegerType() || !Target->isIntegerType())
13935 return;
13936
13937 // TODO: remove this early return once the false positives for constant->bool
13938 // in templates, macros, etc, are reduced or removed.
13939 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13940 return;
13941
13942 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13943 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13945 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13946 << E->getType());
13947 }
13948 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13949 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13950 if (!LikelySourceRange)
13951 return;
13952
13953 IntRange SourceTypeRange =
13954 IntRange::forTargetOfCanonicalType(Context, Source);
13955 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13956
13957 if (LikelySourceRange->Width > TargetRange.Width) {
13958 // Check if target is a wrapping OBT - if so, don't warn about constant
13959 // conversion as this type may be used intentionally with implicit
13960 // truncation, especially during assignments.
13961 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13962 if (TargetOBT->isWrapKind()) {
13963 return;
13964 }
13965 }
13966
13967 // Check if source expression has an explicit __ob_wrap cast because if so,
13968 // wrapping was explicitly requested and we shouldn't warn
13969 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13970 if (SourceOBT->isWrapKind()) {
13971 return;
13972 }
13973 }
13974
13975 // If the source is a constant, use a default-on diagnostic.
13976 // TODO: this should happen for bitfield stores, too.
13980 llvm::APSInt Value(32);
13981 Value = Result.Val.getInt();
13982
13983 if (SourceMgr.isInSystemMacro(CC))
13984 return;
13985
13986 std::string PrettySourceValue = toString(Value, 10);
13987 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13988
13990 PDiag(diag::warn_impcast_integer_precision_constant)
13991 << PrettySourceValue << PrettyTargetValue
13992 << E->getType() << T << E->getSourceRange()
13993 << SourceRange(CC));
13994 return;
13995 }
13996
13997 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13998 if (SourceMgr.isInSystemMacro(CC))
13999 return;
14000
14001 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
14002 if (UO->getOpcode() == UO_Minus)
14003 return DiagnoseImpCast(
14004 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
14005 }
14006
14007 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
14008 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
14009 /* pruneControlFlow */ true);
14010 return DiagnoseImpCast(*this, E, T, CC,
14011 diag::warn_impcast_integer_precision);
14012 }
14013
14014 if (TargetRange.Width > SourceTypeRange.Width) {
14015 if (auto *UO = dyn_cast<UnaryOperator>(E))
14016 if (UO->getOpcode() == UO_Minus)
14017 if (Source->isUnsignedIntegerType()) {
14018 if (Target->isUnsignedIntegerType())
14019 return DiagnoseImpCast(*this, E, T, CC,
14020 diag::warn_impcast_high_order_zero_bits);
14021 if (Target->isSignedIntegerType())
14022 return DiagnoseImpCast(*this, E, T, CC,
14023 diag::warn_impcast_nonnegative_result);
14024 }
14025 }
14026
14027 if (TargetRange.Width == LikelySourceRange->Width &&
14028 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14029 Source->isSignedIntegerType()) {
14030 // Warn when doing a signed to signed conversion, warn if the positive
14031 // source value is exactly the width of the target type, which will
14032 // cause a negative value to be stored.
14033
14036 !SourceMgr.isInSystemMacro(CC)) {
14037 llvm::APSInt Value = Result.Val.getInt();
14038 if (isSameWidthConstantConversion(*this, E, T, CC)) {
14039 std::string PrettySourceValue = toString(Value, 10);
14040 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
14041
14042 Diag(E->getExprLoc(),
14043 PDiag(diag::warn_impcast_integer_precision_constant)
14044 << PrettySourceValue << PrettyTargetValue << E->getType() << T
14045 << E->getSourceRange() << SourceRange(CC));
14046 return;
14047 }
14048 }
14049
14050 // Fall through for non-constants to give a sign conversion warning.
14051 }
14052
14053 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
14054 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
14055 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14056 LikelySourceRange->Width == TargetRange.Width))) {
14057 if (SourceMgr.isInSystemMacro(CC))
14058 return;
14059
14060 if (SourceBT && SourceBT->isInteger() && TargetBT &&
14061 TargetBT->isInteger() &&
14062 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
14063 return;
14064 }
14065
14066 unsigned DiagID = diag::warn_impcast_integer_sign;
14067
14068 // Traditionally, gcc has warned about this under -Wsign-compare.
14069 // We also want to warn about it in -Wconversion.
14070 // So if -Wconversion is off, use a completely identical diagnostic
14071 // in the sign-compare group.
14072 // The conditional-checking code will
14073 if (ICContext) {
14074 DiagID = diag::warn_impcast_integer_sign_conditional;
14075 *ICContext = true;
14076 }
14077
14078 DiagnoseImpCast(*this, E, T, CC, DiagID);
14079 }
14080
14081 // If we're implicitly converting from an integer into an enumeration, that
14082 // is valid in C but invalid in C++.
14083 QualType SourceType = E->getEnumCoercedType(Context);
14084 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
14085 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
14086 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
14087
14088 // Diagnose conversions between different enumeration types.
14089 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
14090 // type, to give us better diagnostics.
14091 Source = Context.getCanonicalType(SourceType).getTypePtr();
14092
14093 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
14094 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
14095 if (SourceEnum->getDecl()->hasNameForLinkage() &&
14096 TargetEnum->getDecl()->hasNameForLinkage() &&
14097 SourceEnum != TargetEnum) {
14098 if (SourceMgr.isInSystemMacro(CC))
14099 return;
14100
14101 return DiagnoseImpCast(*this, E, SourceType, T, CC,
14102 diag::warn_impcast_different_enum_types);
14103 }
14104}
14105
14108
14110 SourceLocation CC, bool &ICContext) {
14111 E = E->IgnoreParenImpCasts();
14112 // Diagnose incomplete type for second or third operand in C.
14113 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
14114 S.RequireCompleteExprType(E, diag::err_incomplete_type);
14115
14116 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
14117 return CheckConditionalOperator(S, CO, CC, T);
14118
14120 if (E->getType() != T)
14121 return S.CheckImplicitConversion(E, T, CC, &ICContext);
14122}
14123
14127
14128 Expr *TrueExpr = E->getTrueExpr();
14129 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
14130 TrueExpr = BCO->getCommon();
14131
14132 bool Suspicious = false;
14133 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
14134 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
14135
14136 if (T->isBooleanType())
14138
14139 // If -Wconversion would have warned about either of the candidates
14140 // for a signedness conversion to the context type...
14141 if (!Suspicious) return;
14142
14143 // ...but it's currently ignored...
14144 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
14145 return;
14146
14147 // ...then check whether it would have warned about either of the
14148 // candidates for a signedness conversion to the condition type.
14149 if (E->getType() == T) return;
14150
14151 Suspicious = false;
14152 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
14153 &Suspicious);
14154 if (!Suspicious)
14156 E->getType(), CC, &Suspicious);
14157}
14158
14159/// Check conversion of given expression to boolean.
14160/// Input argument E is a logical expression.
14162 // Run the bool-like conversion checks only for C since there bools are
14163 // still not used as the return type from "boolean" operators or as the input
14164 // type for conditional operators.
14165 if (S.getLangOpts().CPlusPlus)
14166 return;
14168 return;
14170}
14171
14172namespace {
14173struct AnalyzeImplicitConversionsWorkItem {
14174 Expr *E;
14175 SourceLocation CC;
14176 bool IsListInit;
14177};
14178}
14179
14181 Sema &S, Expr *E, QualType T, SourceLocation CC,
14182 bool ExtraCheckForImplicitConversion,
14184 E = E->IgnoreParenImpCasts();
14185 WorkList.push_back({E, CC, false});
14186
14187 if (ExtraCheckForImplicitConversion && E->getType() != T)
14188 S.CheckImplicitConversion(E, T, CC);
14189}
14190
14191/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14192/// that should be visited are added to WorkList.
14194 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14196 Expr *OrigE = Item.E;
14197 SourceLocation CC = Item.CC;
14198
14199 QualType T = OrigE->getType();
14200 Expr *E = OrigE->IgnoreParenImpCasts();
14201
14202 // Propagate whether we are in a C++ list initialization expression.
14203 // If so, we do not issue warnings for implicit int-float conversion
14204 // precision loss, because C++11 narrowing already handles it.
14205 //
14206 // HLSL's initialization lists are special, so they shouldn't observe the C++
14207 // behavior here.
14208 bool IsListInit =
14209 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
14210 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14211
14212 if (E->isTypeDependent() || E->isValueDependent())
14213 return;
14214
14215 Expr *SourceExpr = E;
14216 // Examine, but don't traverse into the source expression of an
14217 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14218 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14219 // evaluate it in the context of checking the specific conversion to T though.
14220 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14221 if (auto *Src = OVE->getSourceExpr())
14222 SourceExpr = Src;
14223
14224 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14225 if (UO->getOpcode() == UO_Not &&
14226 UO->getSubExpr()->isKnownToHaveBooleanValue())
14227 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14228 << OrigE->getSourceRange() << T->isBooleanType()
14229 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14230
14231 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14232 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14233 BO->getLHS()->isKnownToHaveBooleanValue() &&
14234 BO->getRHS()->isKnownToHaveBooleanValue() &&
14235 BO->getLHS()->HasSideEffects(S.Context) &&
14236 BO->getRHS()->HasSideEffects(S.Context)) {
14238 const LangOptions &LO = S.getLangOpts();
14239 SourceLocation BLoc = BO->getOperatorLoc();
14240 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
14241 StringRef SR = clang::Lexer::getSourceText(
14242 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
14243 // To reduce false positives, only issue the diagnostic if the operator
14244 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14245 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14246 // in C, along with other macro spellings the user might invent.
14247 if (SR.str() == "&" || SR.str() == "|") {
14248
14249 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14250 << (BO->getOpcode() == BO_And ? "&" : "|")
14251 << OrigE->getSourceRange()
14253 BO->getOperatorLoc(),
14254 (BO->getOpcode() == BO_And ? "&&" : "||"));
14255 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14256 }
14257 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14258 /// Analyze the given comma operator. The basic idea behind the analysis
14259 /// is to analyze the left and right operands slightly differently. The
14260 /// left operand needs to check whether the operand itself has an implicit
14261 /// conversion, but not whether the left operand induces an implicit
14262 /// conversion for the entire comma expression itself. This is similar to
14263 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14264 /// were directly used for the implicit conversion check.
14265 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
14266 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14267 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
14268 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14269 return;
14270 }
14271 }
14272
14273 // For conditional operators, we analyze the arguments as if they
14274 // were being fed directly into the output.
14275 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14276 CheckConditionalOperator(S, CO, CC, T);
14277 return;
14278 }
14279
14280 // Check implicit argument conversions for function calls.
14281 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14283
14284 // Go ahead and check any implicit conversions we might have skipped.
14285 // The non-canonical typecheck is just an optimization;
14286 // CheckImplicitConversion will filter out dead implicit conversions.
14287 if (SourceExpr->getType() != T)
14288 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14289
14290 // Now continue drilling into this expression.
14291
14292 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14293 // The bound subexpressions in a PseudoObjectExpr are not reachable
14294 // as transitive children.
14295 // FIXME: Use a more uniform representation for this.
14296 for (auto *SE : POE->semantics())
14297 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14298 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14299 }
14300
14301 // Skip past explicit casts.
14302 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14303 E = CE->getSubExpr();
14304 // In the special case of a C++ function-style cast with braces,
14305 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14306 // initializer. This InitListExpr basically belongs to the cast itself, so
14307 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14309 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14310 if (InitListE->getNumInits() == 1) {
14311 E = InitListE->getInit(0);
14312 }
14313 }
14314 }
14315 E = E->IgnoreParenImpCasts();
14316 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14317 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14318 WorkList.push_back({E, CC, IsListInit});
14319 return;
14320 }
14321
14322 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14323 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14324 // The base expression is only used to initialize the parameter for
14325 // arguments to `inout` parameters, so we only traverse down the base
14326 // expression for `inout` cases.
14327 if (OutArgE->isInOut())
14328 WorkList.push_back(
14329 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14330 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14331 return;
14332 }
14333
14334 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14335 // Do a somewhat different check with comparison operators.
14336 if (BO->isComparisonOp())
14337 return AnalyzeComparison(S, BO);
14338
14339 // And with simple assignments.
14340 if (BO->getOpcode() == BO_Assign)
14341 return AnalyzeAssignment(S, BO);
14342 // And with compound assignments.
14343 if (BO->isAssignmentOp())
14344 return AnalyzeCompoundAssignment(S, BO);
14345 }
14346
14347 // These break the otherwise-useful invariant below. Fortunately,
14348 // we don't really need to recurse into them, because any internal
14349 // expressions should have been analyzed already when they were
14350 // built into statements.
14351 if (isa<StmtExpr>(E)) return;
14352
14353 // Don't descend into unevaluated contexts.
14354 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14355
14356 // Now just recurse over the expression's children.
14357 CC = E->getExprLoc();
14358 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14359 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14360 for (Stmt *SubStmt : E->children()) {
14361 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14362 if (!ChildExpr)
14363 continue;
14364
14365 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14366 if (ChildExpr == CSE->getOperand())
14367 // Do not recurse over a CoroutineSuspendExpr's operand.
14368 // The operand is also a subexpression of getCommonExpr(), and
14369 // recursing into it directly would produce duplicate diagnostics.
14370 continue;
14371
14372 if (IsLogicalAndOperator &&
14374 // Ignore checking string literals that are in logical and operators.
14375 // This is a common pattern for asserts.
14376 continue;
14377 WorkList.push_back({ChildExpr, CC, IsListInit});
14378 }
14379
14380 if (BO && BO->isLogicalOp()) {
14381 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14382 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14383 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14384
14385 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14386 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14387 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14388 }
14389
14390 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14391 if (U->getOpcode() == UO_LNot) {
14392 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14393 } else if (U->getOpcode() != UO_AddrOf) {
14394 if (U->getSubExpr()->getType()->isAtomicType())
14395 S.Diag(U->getSubExpr()->getBeginLoc(),
14396 diag::warn_atomic_implicit_seq_cst);
14397 }
14398 }
14399}
14400
14401/// AnalyzeImplicitConversions - Find and report any interesting
14402/// implicit conversions in the given expression. There are a couple
14403/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14405 bool IsListInit/*= false*/) {
14407 WorkList.push_back({OrigE, CC, IsListInit});
14408 while (!WorkList.empty())
14409 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14410}
14411
14412// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14413// Returns true when emitting a warning about taking the address of a reference.
14414static bool CheckForReference(Sema &SemaRef, const Expr *E,
14415 const PartialDiagnostic &PD) {
14416 E = E->IgnoreParenImpCasts();
14417
14418 const FunctionDecl *FD = nullptr;
14419
14420 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14421 if (!DRE->getDecl()->getType()->isReferenceType())
14422 return false;
14423 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14424 if (!M->getMemberDecl()->getType()->isReferenceType())
14425 return false;
14426 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14427 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14428 return false;
14429 FD = Call->getDirectCallee();
14430 } else {
14431 return false;
14432 }
14433
14434 SemaRef.Diag(E->getExprLoc(), PD);
14435
14436 // If possible, point to location of function.
14437 if (FD) {
14438 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14439 }
14440
14441 return true;
14442}
14443
14444// Returns true if the SourceLocation is expanded from any macro body.
14445// Returns false if the SourceLocation is invalid, is from not in a macro
14446// expansion, or is from expanded from a top-level macro argument.
14447static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14448 if (Loc.isInvalid())
14449 return false;
14450
14451 while (Loc.isMacroID()) {
14452 if (SM.isMacroBodyExpansion(Loc))
14453 return true;
14454 Loc = SM.getImmediateMacroCallerLoc(Loc);
14455 }
14456
14457 return false;
14458}
14459
14462 bool IsEqual, SourceRange Range) {
14463 if (!E)
14464 return;
14465
14466 // Don't warn inside macros.
14467 if (E->getExprLoc().isMacroID()) {
14468 const SourceManager &SM = getSourceManager();
14469 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14470 IsInAnyMacroBody(SM, Range.getBegin()))
14471 return;
14472 }
14473 E = E->IgnoreImpCasts();
14474
14475 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14476
14477 if (isa<CXXThisExpr>(E)) {
14478 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14479 : diag::warn_this_bool_conversion;
14480 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14481 return;
14482 }
14483
14484 bool IsAddressOf = false;
14485
14486 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14487 if (UO->getOpcode() != UO_AddrOf)
14488 return;
14489 IsAddressOf = true;
14490 E = UO->getSubExpr();
14491 }
14492
14493 if (IsAddressOf) {
14494 unsigned DiagID = IsCompare
14495 ? diag::warn_address_of_reference_null_compare
14496 : diag::warn_address_of_reference_bool_conversion;
14497 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14498 << IsEqual;
14499 if (CheckForReference(*this, E, PD)) {
14500 return;
14501 }
14502 }
14503
14504 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14505 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14506 std::string Str;
14507 llvm::raw_string_ostream S(Str);
14508 E->printPretty(S, nullptr, getPrintingPolicy());
14509 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14510 : diag::warn_cast_nonnull_to_bool;
14511 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14512 << E->getSourceRange() << Range << IsEqual;
14513 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14514 };
14515
14516 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14517 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14518 if (auto *Callee = Call->getDirectCallee()) {
14519 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14520 ComplainAboutNonnullParamOrCall(A);
14521 return;
14522 }
14523 }
14524 }
14525
14526 // Complain if we are converting a lambda expression to a boolean value
14527 // outside of instantiation.
14528 if (!inTemplateInstantiation()) {
14529 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14530 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14531 MRecordDecl && MRecordDecl->isLambda()) {
14532 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14533 << /*LambdaPointerConversionOperatorType=*/3
14534 << MRecordDecl->getSourceRange() << Range << IsEqual;
14535 return;
14536 }
14537 }
14538 }
14539
14540 // Expect to find a single Decl. Skip anything more complicated.
14541 ValueDecl *D = nullptr;
14542 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14543 D = R->getDecl();
14544 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14545 D = M->getMemberDecl();
14546 }
14547
14548 // Weak Decls can be null.
14549 if (!D || D->isWeak())
14550 return;
14551
14552 // Check for parameter decl with nonnull attribute
14553 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14554 if (getCurFunction() &&
14555 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14556 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14557 ComplainAboutNonnullParamOrCall(A);
14558 return;
14559 }
14560
14561 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14562 // Skip function template not specialized yet.
14564 return;
14565 auto ParamIter = llvm::find(FD->parameters(), PV);
14566 assert(ParamIter != FD->param_end());
14567 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14568
14569 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14570 if (!NonNull->args_size()) {
14571 ComplainAboutNonnullParamOrCall(NonNull);
14572 return;
14573 }
14574
14575 for (const ParamIdx &ArgNo : NonNull->args()) {
14576 if (ArgNo.getASTIndex() == ParamNo) {
14577 ComplainAboutNonnullParamOrCall(NonNull);
14578 return;
14579 }
14580 }
14581 }
14582 }
14583 }
14584 }
14585
14586 QualType T = D->getType();
14587 // A reference to a function is never null either; look through it.
14588 const bool IsFunctionReference =
14589 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14590 if (IsFunctionReference)
14591 T = T->getPointeeType();
14592 const bool IsArray = T->isArrayType();
14593 const bool IsFunction = T->isFunctionType();
14594
14595 // Address of function is used to silence the function warning.
14596 if (IsAddressOf && IsFunction) {
14597 return;
14598 }
14599
14600 // Found nothing.
14601 if (!IsAddressOf && !IsFunction && !IsArray)
14602 return;
14603
14604 // Pretty print the expression for the diagnostic.
14605 std::string Str;
14606 llvm::raw_string_ostream S(Str);
14607 E->printPretty(S, nullptr, getPrintingPolicy());
14608
14609 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14610 : diag::warn_impcast_pointer_to_bool;
14611 enum {
14612 AddressOf,
14613 FunctionPointer,
14614 ArrayPointer
14615 } DiagType;
14616 if (IsAddressOf)
14617 DiagType = AddressOf;
14618 else if (IsFunction)
14619 DiagType = FunctionPointer;
14620 else if (IsArray)
14621 DiagType = ArrayPointer;
14622 else
14623 llvm_unreachable("Could not determine diagnostic.");
14624 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14625 << Range << IsEqual;
14626
14627 // The fix-it notes below only apply to a bare function name, not a reference.
14628 if (!IsFunction || IsFunctionReference)
14629 return;
14630
14631 // Suggest '&' to silence the function warning.
14632 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14634
14635 // Check to see if '()' fixit should be emitted.
14636 QualType ReturnType;
14637 UnresolvedSet<4> NonTemplateOverloads;
14638 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14639 if (ReturnType.isNull())
14640 return;
14641
14642 if (IsCompare) {
14643 // There are two cases here. If there is null constant, the only suggest
14644 // for a pointer return type. If the null is 0, then suggest if the return
14645 // type is a pointer or an integer type.
14646 if (!ReturnType->isPointerType()) {
14647 if (NullKind == Expr::NPCK_ZeroExpression ||
14648 NullKind == Expr::NPCK_ZeroLiteral) {
14649 if (!ReturnType->isIntegerType())
14650 return;
14651 } else {
14652 return;
14653 }
14654 }
14655 } else { // !IsCompare
14656 // For function to bool, only suggest if the function pointer has bool
14657 // return type.
14658 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14659 return;
14660 }
14661 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14663}
14664
14666 SourceLocation CC) {
14667 QualType Source = E->getType();
14668 QualType Target = T;
14669
14670 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14671 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14672 // Overflow behavior type is being stripped - issue warning
14673 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14674 Target->isUnsignedIntegerType()) {
14675 // For unsigned wrap to unsigned conversions, use pedantic version
14676 unsigned DiagId =
14678 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14679 : diag::warn_impcast_overflow_behavior_pedantic;
14680 DiagnoseImpCast(*this, E, T, CC, DiagId);
14681 } else {
14682 unsigned DiagId = InOverflowBehaviorAssignmentContext
14683 ? diag::warn_impcast_overflow_behavior_assignment
14684 : diag::warn_impcast_overflow_behavior;
14685 DiagnoseImpCast(*this, E, T, CC, DiagId);
14686 }
14687 }
14688 }
14689
14690 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14691 if (TargetOBT->isWrapKind()) {
14692 return true;
14693 }
14694 }
14695
14696 return false;
14697}
14698
14699void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14700 // Don't diagnose in unevaluated contexts.
14702 return;
14703
14704 // Don't diagnose for value- or type-dependent expressions.
14705 if (E->isTypeDependent() || E->isValueDependent())
14706 return;
14707
14708 // Check for array bounds violations in cases where the check isn't triggered
14709 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14710 // ArraySubscriptExpr is on the RHS of a variable initialization.
14711 CheckArrayAccess(E);
14712
14713 // This is not the right CC for (e.g.) a variable initialization.
14714 AnalyzeImplicitConversions(*this, E, CC);
14715}
14716
14717void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14718 ::CheckBoolLikeConversion(*this, E, CC);
14719}
14720
14721void Sema::CheckForIntOverflow (const Expr *E) {
14722 // Use a work list to deal with nested struct initializers.
14723 SmallVector<const Expr *, 2> Exprs(1, E);
14724
14725 do {
14726 const Expr *OriginalE = Exprs.pop_back_val();
14727 const Expr *E = OriginalE->IgnoreParenCasts();
14728
14729 if (isa<BinaryOperator>(E) ||
14730 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14732 continue;
14733 }
14734
14735 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14736 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14737 else if (isa<ObjCBoxedExpr>(OriginalE))
14739 else if (const auto *Call = dyn_cast<CallExpr>(E))
14740 Exprs.append(Call->arg_begin(), Call->arg_end());
14741 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14742 Exprs.append(Message->arg_begin(), Message->arg_end());
14743 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14744 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14745 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14746 Exprs.push_back(Temporary->getSubExpr());
14747 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14748 Exprs.push_back(Array->getIdx());
14749 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14750 Exprs.push_back(Compound->getInitializer());
14751 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14752 New && New->isArray()) {
14753 if (auto ArraySize = New->getArraySize())
14754 Exprs.push_back(*ArraySize);
14755 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14756 Exprs.push_back(MTE->getSubExpr());
14757 } while (!Exprs.empty());
14758}
14759
14760namespace {
14761
14762/// Visitor for expressions which looks for unsequenced operations on the
14763/// same object.
14764class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14765 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14766
14767 /// A tree of sequenced regions within an expression. Two regions are
14768 /// unsequenced if one is an ancestor or a descendent of the other. When we
14769 /// finish processing an expression with sequencing, such as a comma
14770 /// expression, we fold its tree nodes into its parent, since they are
14771 /// unsequenced with respect to nodes we will visit later.
14772 class SequenceTree {
14773 struct Value {
14774 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14775 unsigned Parent : 31;
14776 LLVM_PREFERRED_TYPE(bool)
14777 unsigned Merged : 1;
14778 };
14779 SmallVector<Value, 8> Values;
14780
14781 public:
14782 /// A region within an expression which may be sequenced with respect
14783 /// to some other region.
14784 class Seq {
14785 friend class SequenceTree;
14786
14787 unsigned Index;
14788
14789 explicit Seq(unsigned N) : Index(N) {}
14790
14791 public:
14792 Seq() : Index(0) {}
14793 };
14794
14795 SequenceTree() { Values.push_back(Value(0)); }
14796 Seq root() const { return Seq(0); }
14797
14798 /// Create a new sequence of operations, which is an unsequenced
14799 /// subset of \p Parent. This sequence of operations is sequenced with
14800 /// respect to other children of \p Parent.
14801 Seq allocate(Seq Parent) {
14802 Values.push_back(Value(Parent.Index));
14803 return Seq(Values.size() - 1);
14804 }
14805
14806 /// Merge a sequence of operations into its parent.
14807 void merge(Seq S) {
14808 Values[S.Index].Merged = true;
14809 }
14810
14811 /// Determine whether two operations are unsequenced. This operation
14812 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14813 /// should have been merged into its parent as appropriate.
14814 bool isUnsequenced(Seq Cur, Seq Old) {
14815 unsigned C = representative(Cur.Index);
14816 unsigned Target = representative(Old.Index);
14817 while (C >= Target) {
14818 if (C == Target)
14819 return true;
14820 C = Values[C].Parent;
14821 }
14822 return false;
14823 }
14824
14825 private:
14826 /// Pick a representative for a sequence.
14827 unsigned representative(unsigned K) {
14828 if (Values[K].Merged)
14829 // Perform path compression as we go.
14830 return Values[K].Parent = representative(Values[K].Parent);
14831 return K;
14832 }
14833 };
14834
14835 /// An object for which we can track unsequenced uses.
14836 using Object = const NamedDecl *;
14837
14838 /// Different flavors of object usage which we track. We only track the
14839 /// least-sequenced usage of each kind.
14840 enum UsageKind {
14841 /// A read of an object. Multiple unsequenced reads are OK.
14842 UK_Use,
14843
14844 /// A modification of an object which is sequenced before the value
14845 /// computation of the expression, such as ++n in C++.
14846 UK_ModAsValue,
14847
14848 /// A modification of an object which is not sequenced before the value
14849 /// computation of the expression, such as n++.
14850 UK_ModAsSideEffect,
14851
14852 UK_Count = UK_ModAsSideEffect + 1
14853 };
14854
14855 /// Bundle together a sequencing region and the expression corresponding
14856 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14857 struct Usage {
14858 const Expr *UsageExpr = nullptr;
14859 SequenceTree::Seq Seq;
14860
14861 Usage() = default;
14862 };
14863
14864 struct UsageInfo {
14865 Usage Uses[UK_Count];
14866
14867 /// Have we issued a diagnostic for this object already?
14868 bool Diagnosed = false;
14869
14870 UsageInfo();
14871 };
14872 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14873
14874 Sema &SemaRef;
14875
14876 /// Sequenced regions within the expression.
14877 SequenceTree Tree;
14878
14879 /// Declaration modifications and references which we have seen.
14880 UsageInfoMap UsageMap;
14881
14882 /// The region we are currently within.
14883 SequenceTree::Seq Region;
14884
14885 /// Filled in with declarations which were modified as a side-effect
14886 /// (that is, post-increment operations).
14887 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14888
14889 /// Expressions to check later. We defer checking these to reduce
14890 /// stack usage.
14891 SmallVectorImpl<const Expr *> &WorkList;
14892
14893 /// RAII object wrapping the visitation of a sequenced subexpression of an
14894 /// expression. At the end of this process, the side-effects of the evaluation
14895 /// become sequenced with respect to the value computation of the result, so
14896 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14897 /// UK_ModAsValue.
14898 struct SequencedSubexpression {
14899 SequencedSubexpression(SequenceChecker &Self)
14900 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14901 Self.ModAsSideEffect = &ModAsSideEffect;
14902 }
14903
14904 ~SequencedSubexpression() {
14905 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14906 // Add a new usage with usage kind UK_ModAsValue, and then restore
14907 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14908 // the previous one was empty).
14909 UsageInfo &UI = Self.UsageMap[M.first];
14910 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14911 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14912 SideEffectUsage = M.second;
14913 }
14914 Self.ModAsSideEffect = OldModAsSideEffect;
14915 }
14916
14917 SequenceChecker &Self;
14918 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14919 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14920 };
14921
14922 /// RAII object wrapping the visitation of a subexpression which we might
14923 /// choose to evaluate as a constant. If any subexpression is evaluated and
14924 /// found to be non-constant, this allows us to suppress the evaluation of
14925 /// the outer expression.
14926 class EvaluationTracker {
14927 public:
14928 EvaluationTracker(SequenceChecker &Self)
14929 : Self(Self), Prev(Self.EvalTracker) {
14930 Self.EvalTracker = this;
14931 }
14932
14933 ~EvaluationTracker() {
14934 Self.EvalTracker = Prev;
14935 if (Prev)
14936 Prev->EvalOK &= EvalOK;
14937 }
14938
14939 bool evaluate(const Expr *E, bool &Result) {
14940 if (!EvalOK || E->isValueDependent())
14941 return false;
14942 EvalOK = E->EvaluateAsBooleanCondition(
14943 Result, Self.SemaRef.Context,
14944 Self.SemaRef.isConstantEvaluatedContext());
14945 return EvalOK;
14946 }
14947
14948 private:
14949 SequenceChecker &Self;
14950 EvaluationTracker *Prev;
14951 bool EvalOK = true;
14952 } *EvalTracker = nullptr;
14953
14954 /// Find the object which is produced by the specified expression,
14955 /// if any.
14956 Object getObject(const Expr *E, bool Mod) const {
14957 E = E->IgnoreParenCasts();
14958 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14959 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14960 return getObject(UO->getSubExpr(), Mod);
14961 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14962 if (BO->getOpcode() == BO_Comma)
14963 return getObject(BO->getRHS(), Mod);
14964 if (Mod && BO->isAssignmentOp())
14965 return getObject(BO->getLHS(), Mod);
14966 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14967 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14968 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14969 return ME->getMemberDecl();
14970 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14971 // FIXME: If this is a reference, map through to its value.
14972 return DRE->getDecl();
14973 return nullptr;
14974 }
14975
14976 /// Note that an object \p O was modified or used by an expression
14977 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14978 /// the object \p O as obtained via the \p UsageMap.
14979 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14980 // Get the old usage for the given object and usage kind.
14981 Usage &U = UI.Uses[UK];
14982 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14983 // If we have a modification as side effect and are in a sequenced
14984 // subexpression, save the old Usage so that we can restore it later
14985 // in SequencedSubexpression::~SequencedSubexpression.
14986 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14987 ModAsSideEffect->push_back(std::make_pair(O, U));
14988 // Then record the new usage with the current sequencing region.
14989 U.UsageExpr = UsageExpr;
14990 U.Seq = Region;
14991 }
14992 }
14993
14994 /// Check whether a modification or use of an object \p O in an expression
14995 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14996 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14997 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14998 /// usage and false we are checking for a mod-use unsequenced usage.
14999 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
15000 UsageKind OtherKind, bool IsModMod) {
15001 if (UI.Diagnosed)
15002 return;
15003
15004 const Usage &U = UI.Uses[OtherKind];
15005 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
15006 return;
15007
15008 const Expr *Mod = U.UsageExpr;
15009 const Expr *ModOrUse = UsageExpr;
15010 if (OtherKind == UK_Use)
15011 std::swap(Mod, ModOrUse);
15012
15013 SemaRef.DiagRuntimeBehavior(
15014 Mod->getExprLoc(), {Mod, ModOrUse},
15015 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
15016 : diag::warn_unsequenced_mod_use)
15017 << O << SourceRange(ModOrUse->getExprLoc()));
15018 UI.Diagnosed = true;
15019 }
15020
15021 // A note on note{Pre, Post}{Use, Mod}:
15022 //
15023 // (It helps to follow the algorithm with an expression such as
15024 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
15025 // operations before C++17 and both are well-defined in C++17).
15026 //
15027 // When visiting a node which uses/modify an object we first call notePreUse
15028 // or notePreMod before visiting its sub-expression(s). At this point the
15029 // children of the current node have not yet been visited and so the eventual
15030 // uses/modifications resulting from the children of the current node have not
15031 // been recorded yet.
15032 //
15033 // We then visit the children of the current node. After that notePostUse or
15034 // notePostMod is called. These will 1) detect an unsequenced modification
15035 // as side effect (as in "k++ + k") and 2) add a new usage with the
15036 // appropriate usage kind.
15037 //
15038 // We also have to be careful that some operation sequences modification as
15039 // side effect as well (for example: || or ,). To account for this we wrap
15040 // the visitation of such a sub-expression (for example: the LHS of || or ,)
15041 // with SequencedSubexpression. SequencedSubexpression is an RAII object
15042 // which record usages which are modifications as side effect, and then
15043 // downgrade them (or more accurately restore the previous usage which was a
15044 // modification as side effect) when exiting the scope of the sequenced
15045 // subexpression.
15046
15047 void notePreUse(Object O, const Expr *UseExpr) {
15048 UsageInfo &UI = UsageMap[O];
15049 // Uses conflict with other modifications.
15050 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
15051 }
15052
15053 void notePostUse(Object O, const Expr *UseExpr) {
15054 UsageInfo &UI = UsageMap[O];
15055 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
15056 /*IsModMod=*/false);
15057 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
15058 }
15059
15060 void notePreMod(Object O, const Expr *ModExpr) {
15061 UsageInfo &UI = UsageMap[O];
15062 // Modifications conflict with other modifications and with uses.
15063 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
15064 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
15065 }
15066
15067 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
15068 UsageInfo &UI = UsageMap[O];
15069 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
15070 /*IsModMod=*/true);
15071 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
15072 }
15073
15074public:
15075 SequenceChecker(Sema &S, const Expr *E,
15076 SmallVectorImpl<const Expr *> &WorkList)
15077 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
15078 Visit(E);
15079 // Silence a -Wunused-private-field since WorkList is now unused.
15080 // TODO: Evaluate if it can be used, and if not remove it.
15081 (void)this->WorkList;
15082 }
15083
15084 void VisitStmt(const Stmt *S) {
15085 // Skip all statements which aren't expressions for now.
15086 }
15087
15088 void VisitExpr(const Expr *E) {
15089 // By default, just recurse to evaluated subexpressions.
15090 Base::VisitStmt(E);
15091 }
15092
15093 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
15094 for (auto *Sub : CSE->children()) {
15095 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
15096 if (!ChildExpr)
15097 continue;
15098
15099 if (ChildExpr == CSE->getOperand())
15100 // Do not recurse over a CoroutineSuspendExpr's operand.
15101 // The operand is also a subexpression of getCommonExpr(), and
15102 // recursing into it directly could confuse object management
15103 // for the sake of sequence tracking.
15104 continue;
15105
15106 Visit(Sub);
15107 }
15108 }
15109
15110 void VisitCastExpr(const CastExpr *E) {
15111 Object O = Object();
15112 if (E->getCastKind() == CK_LValueToRValue)
15113 O = getObject(E->getSubExpr(), false);
15114
15115 if (O)
15116 notePreUse(O, E);
15117 VisitExpr(E);
15118 if (O)
15119 notePostUse(O, E);
15120 }
15121
15122 void VisitSequencedExpressions(const Expr *SequencedBefore,
15123 const Expr *SequencedAfter) {
15124 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
15125 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
15126 SequenceTree::Seq OldRegion = Region;
15127
15128 {
15129 SequencedSubexpression SeqBefore(*this);
15130 Region = BeforeRegion;
15131 Visit(SequencedBefore);
15132 }
15133
15134 Region = AfterRegion;
15135 Visit(SequencedAfter);
15136
15137 Region = OldRegion;
15138
15139 Tree.merge(BeforeRegion);
15140 Tree.merge(AfterRegion);
15141 }
15142
15143 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15144 // C++17 [expr.sub]p1:
15145 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15146 // expression E1 is sequenced before the expression E2.
15147 if (SemaRef.getLangOpts().CPlusPlus17)
15148 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
15149 else {
15150 Visit(ASE->getLHS());
15151 Visit(ASE->getRHS());
15152 }
15153 }
15154
15155 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15156 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15157 void VisitBinPtrMem(const BinaryOperator *BO) {
15158 // C++17 [expr.mptr.oper]p4:
15159 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15160 // the expression E1 is sequenced before the expression E2.
15161 if (SemaRef.getLangOpts().CPlusPlus17)
15162 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15163 else {
15164 Visit(BO->getLHS());
15165 Visit(BO->getRHS());
15166 }
15167 }
15168
15169 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15170 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15171 void VisitBinShlShr(const BinaryOperator *BO) {
15172 // C++17 [expr.shift]p4:
15173 // The expression E1 is sequenced before the expression E2.
15174 if (SemaRef.getLangOpts().CPlusPlus17)
15175 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15176 else {
15177 Visit(BO->getLHS());
15178 Visit(BO->getRHS());
15179 }
15180 }
15181
15182 void VisitBinComma(const BinaryOperator *BO) {
15183 // C++11 [expr.comma]p1:
15184 // Every value computation and side effect associated with the left
15185 // expression is sequenced before every value computation and side
15186 // effect associated with the right expression.
15187 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15188 }
15189
15190 void VisitBinAssign(const BinaryOperator *BO) {
15191 SequenceTree::Seq RHSRegion;
15192 SequenceTree::Seq LHSRegion;
15193 if (SemaRef.getLangOpts().CPlusPlus17) {
15194 RHSRegion = Tree.allocate(Region);
15195 LHSRegion = Tree.allocate(Region);
15196 } else {
15197 RHSRegion = Region;
15198 LHSRegion = Region;
15199 }
15200 SequenceTree::Seq OldRegion = Region;
15201
15202 // C++11 [expr.ass]p1:
15203 // [...] the assignment is sequenced after the value computation
15204 // of the right and left operands, [...]
15205 //
15206 // so check it before inspecting the operands and update the
15207 // map afterwards.
15208 Object O = getObject(BO->getLHS(), /*Mod=*/true);
15209 if (O)
15210 notePreMod(O, BO);
15211
15212 if (SemaRef.getLangOpts().CPlusPlus17) {
15213 // C++17 [expr.ass]p1:
15214 // [...] The right operand is sequenced before the left operand. [...]
15215 {
15216 SequencedSubexpression SeqBefore(*this);
15217 Region = RHSRegion;
15218 Visit(BO->getRHS());
15219 }
15220
15221 Region = LHSRegion;
15222 Visit(BO->getLHS());
15223
15224 if (O && isa<CompoundAssignOperator>(BO))
15225 notePostUse(O, BO);
15226
15227 } else {
15228 // C++11 does not specify any sequencing between the LHS and RHS.
15229 Region = LHSRegion;
15230 Visit(BO->getLHS());
15231
15232 if (O && isa<CompoundAssignOperator>(BO))
15233 notePostUse(O, BO);
15234
15235 Region = RHSRegion;
15236 Visit(BO->getRHS());
15237 }
15238
15239 // C++11 [expr.ass]p1:
15240 // the assignment is sequenced [...] before the value computation of the
15241 // assignment expression.
15242 // C11 6.5.16/3 has no such rule.
15243 Region = OldRegion;
15244 if (O)
15245 notePostMod(O, BO,
15246 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15247 : UK_ModAsSideEffect);
15248 if (SemaRef.getLangOpts().CPlusPlus17) {
15249 Tree.merge(RHSRegion);
15250 Tree.merge(LHSRegion);
15251 }
15252 }
15253
15254 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15255 VisitBinAssign(CAO);
15256 }
15257
15258 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15259 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15260 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15261 Object O = getObject(UO->getSubExpr(), true);
15262 if (!O)
15263 return VisitExpr(UO);
15264
15265 notePreMod(O, UO);
15266 Visit(UO->getSubExpr());
15267 // C++11 [expr.pre.incr]p1:
15268 // the expression ++x is equivalent to x+=1
15269 notePostMod(O, UO,
15270 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15271 : UK_ModAsSideEffect);
15272 }
15273
15274 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15275 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15276 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15277 Object O = getObject(UO->getSubExpr(), true);
15278 if (!O)
15279 return VisitExpr(UO);
15280
15281 notePreMod(O, UO);
15282 Visit(UO->getSubExpr());
15283 notePostMod(O, UO, UK_ModAsSideEffect);
15284 }
15285
15286 void VisitBinLOr(const BinaryOperator *BO) {
15287 // C++11 [expr.log.or]p2:
15288 // If the second expression is evaluated, every value computation and
15289 // side effect associated with the first expression is sequenced before
15290 // every value computation and side effect associated with the
15291 // second expression.
15292 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15293 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15294 SequenceTree::Seq OldRegion = Region;
15295
15296 EvaluationTracker Eval(*this);
15297 {
15298 SequencedSubexpression Sequenced(*this);
15299 Region = LHSRegion;
15300 Visit(BO->getLHS());
15301 }
15302
15303 // C++11 [expr.log.or]p1:
15304 // [...] the second operand is not evaluated if the first operand
15305 // evaluates to true.
15306 bool EvalResult = false;
15307 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15308 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15309 if (ShouldVisitRHS) {
15310 Region = RHSRegion;
15311 Visit(BO->getRHS());
15312 }
15313
15314 Region = OldRegion;
15315 Tree.merge(LHSRegion);
15316 Tree.merge(RHSRegion);
15317 }
15318
15319 void VisitBinLAnd(const BinaryOperator *BO) {
15320 // C++11 [expr.log.and]p2:
15321 // If the second expression is evaluated, every value computation and
15322 // side effect associated with the first expression is sequenced before
15323 // every value computation and side effect associated with the
15324 // second expression.
15325 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15326 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15327 SequenceTree::Seq OldRegion = Region;
15328
15329 EvaluationTracker Eval(*this);
15330 {
15331 SequencedSubexpression Sequenced(*this);
15332 Region = LHSRegion;
15333 Visit(BO->getLHS());
15334 }
15335
15336 // C++11 [expr.log.and]p1:
15337 // [...] the second operand is not evaluated if the first operand is false.
15338 bool EvalResult = false;
15339 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15340 bool ShouldVisitRHS = !EvalOK || EvalResult;
15341 if (ShouldVisitRHS) {
15342 Region = RHSRegion;
15343 Visit(BO->getRHS());
15344 }
15345
15346 Region = OldRegion;
15347 Tree.merge(LHSRegion);
15348 Tree.merge(RHSRegion);
15349 }
15350
15351 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15352 // C++11 [expr.cond]p1:
15353 // [...] Every value computation and side effect associated with the first
15354 // expression is sequenced before every value computation and side effect
15355 // associated with the second or third expression.
15356 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15357
15358 // No sequencing is specified between the true and false expression.
15359 // However since exactly one of both is going to be evaluated we can
15360 // consider them to be sequenced. This is needed to avoid warning on
15361 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15362 // both the true and false expressions because we can't evaluate x.
15363 // This will still allow us to detect an expression like (pre C++17)
15364 // "(x ? y += 1 : y += 2) = y".
15365 //
15366 // We don't wrap the visitation of the true and false expression with
15367 // SequencedSubexpression because we don't want to downgrade modifications
15368 // as side effect in the true and false expressions after the visition
15369 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15370 // not warn between the two "y++", but we should warn between the "y++"
15371 // and the "y".
15372 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15373 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15374 SequenceTree::Seq OldRegion = Region;
15375
15376 EvaluationTracker Eval(*this);
15377 {
15378 SequencedSubexpression Sequenced(*this);
15379 Region = ConditionRegion;
15380 Visit(CO->getCond());
15381 }
15382
15383 // C++11 [expr.cond]p1:
15384 // [...] The first expression is contextually converted to bool (Clause 4).
15385 // It is evaluated and if it is true, the result of the conditional
15386 // expression is the value of the second expression, otherwise that of the
15387 // third expression. Only one of the second and third expressions is
15388 // evaluated. [...]
15389 bool EvalResult = false;
15390 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15391 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15392 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15393 if (ShouldVisitTrueExpr) {
15394 Region = TrueRegion;
15395 Visit(CO->getTrueExpr());
15396 }
15397 if (ShouldVisitFalseExpr) {
15398 Region = FalseRegion;
15399 Visit(CO->getFalseExpr());
15400 }
15401
15402 Region = OldRegion;
15403 Tree.merge(ConditionRegion);
15404 Tree.merge(TrueRegion);
15405 Tree.merge(FalseRegion);
15406 }
15407
15408 void VisitCallExpr(const CallExpr *CE) {
15409 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15410
15411 if (CE->isUnevaluatedBuiltinCall(Context))
15412 return;
15413
15414 // C++11 [intro.execution]p15:
15415 // When calling a function [...], every value computation and side effect
15416 // associated with any argument expression, or with the postfix expression
15417 // designating the called function, is sequenced before execution of every
15418 // expression or statement in the body of the function [and thus before
15419 // the value computation of its result].
15420 SequencedSubexpression Sequenced(*this);
15421 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15422 // C++17 [expr.call]p5
15423 // The postfix-expression is sequenced before each expression in the
15424 // expression-list and any default argument. [...]
15425 SequenceTree::Seq CalleeRegion;
15426 SequenceTree::Seq OtherRegion;
15427 if (SemaRef.getLangOpts().CPlusPlus17) {
15428 CalleeRegion = Tree.allocate(Region);
15429 OtherRegion = Tree.allocate(Region);
15430 } else {
15431 CalleeRegion = Region;
15432 OtherRegion = Region;
15433 }
15434 SequenceTree::Seq OldRegion = Region;
15435
15436 // Visit the callee expression first.
15437 Region = CalleeRegion;
15438 if (SemaRef.getLangOpts().CPlusPlus17) {
15439 SequencedSubexpression Sequenced(*this);
15440 Visit(CE->getCallee());
15441 } else {
15442 Visit(CE->getCallee());
15443 }
15444
15445 // Then visit the argument expressions.
15446 Region = OtherRegion;
15447 for (const Expr *Argument : CE->arguments())
15448 Visit(Argument);
15449
15450 Region = OldRegion;
15451 if (SemaRef.getLangOpts().CPlusPlus17) {
15452 Tree.merge(CalleeRegion);
15453 Tree.merge(OtherRegion);
15454 }
15455 });
15456 }
15457
15458 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15459 // C++17 [over.match.oper]p2:
15460 // [...] the operator notation is first transformed to the equivalent
15461 // function-call notation as summarized in Table 12 (where @ denotes one
15462 // of the operators covered in the specified subclause). However, the
15463 // operands are sequenced in the order prescribed for the built-in
15464 // operator (Clause 8).
15465 //
15466 // From the above only overloaded binary operators and overloaded call
15467 // operators have sequencing rules in C++17 that we need to handle
15468 // separately.
15469 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15470 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15471 return VisitCallExpr(CXXOCE);
15472
15473 enum {
15474 NoSequencing,
15475 LHSBeforeRHS,
15476 RHSBeforeLHS,
15477 LHSBeforeRest
15478 } SequencingKind;
15479 switch (CXXOCE->getOperator()) {
15480 case OO_Equal:
15481 case OO_PlusEqual:
15482 case OO_MinusEqual:
15483 case OO_StarEqual:
15484 case OO_SlashEqual:
15485 case OO_PercentEqual:
15486 case OO_CaretEqual:
15487 case OO_AmpEqual:
15488 case OO_PipeEqual:
15489 case OO_LessLessEqual:
15490 case OO_GreaterGreaterEqual:
15491 SequencingKind = RHSBeforeLHS;
15492 break;
15493
15494 case OO_LessLess:
15495 case OO_GreaterGreater:
15496 case OO_AmpAmp:
15497 case OO_PipePipe:
15498 case OO_Comma:
15499 case OO_ArrowStar:
15500 case OO_Subscript:
15501 SequencingKind = LHSBeforeRHS;
15502 break;
15503
15504 case OO_Call:
15505 SequencingKind = LHSBeforeRest;
15506 break;
15507
15508 default:
15509 SequencingKind = NoSequencing;
15510 break;
15511 }
15512
15513 if (SequencingKind == NoSequencing)
15514 return VisitCallExpr(CXXOCE);
15515
15516 // This is a call, so all subexpressions are sequenced before the result.
15517 SequencedSubexpression Sequenced(*this);
15518
15519 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15520 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15521 "Should only get there with C++17 and above!");
15522 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15523 "Should only get there with an overloaded binary operator"
15524 " or an overloaded call operator!");
15525
15526 if (SequencingKind == LHSBeforeRest) {
15527 assert(CXXOCE->getOperator() == OO_Call &&
15528 "We should only have an overloaded call operator here!");
15529
15530 // This is very similar to VisitCallExpr, except that we only have the
15531 // C++17 case. The postfix-expression is the first argument of the
15532 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15533 // are in the following arguments.
15534 //
15535 // Note that we intentionally do not visit the callee expression since
15536 // it is just a decayed reference to a function.
15537 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15538 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15539 SequenceTree::Seq OldRegion = Region;
15540
15541 assert(CXXOCE->getNumArgs() >= 1 &&
15542 "An overloaded call operator must have at least one argument"
15543 " for the postfix-expression!");
15544 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15545 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15546 CXXOCE->getNumArgs() - 1);
15547
15548 // Visit the postfix-expression first.
15549 {
15550 Region = PostfixExprRegion;
15551 SequencedSubexpression Sequenced(*this);
15552 Visit(PostfixExpr);
15553 }
15554
15555 // Then visit the argument expressions.
15556 Region = ArgsRegion;
15557 for (const Expr *Arg : Args)
15558 Visit(Arg);
15559
15560 Region = OldRegion;
15561 Tree.merge(PostfixExprRegion);
15562 Tree.merge(ArgsRegion);
15563 } else {
15564 assert(CXXOCE->getNumArgs() == 2 &&
15565 "Should only have two arguments here!");
15566 assert((SequencingKind == LHSBeforeRHS ||
15567 SequencingKind == RHSBeforeLHS) &&
15568 "Unexpected sequencing kind!");
15569
15570 // We do not visit the callee expression since it is just a decayed
15571 // reference to a function.
15572 const Expr *E1 = CXXOCE->getArg(0);
15573 const Expr *E2 = CXXOCE->getArg(1);
15574 if (SequencingKind == RHSBeforeLHS)
15575 std::swap(E1, E2);
15576
15577 return VisitSequencedExpressions(E1, E2);
15578 }
15579 });
15580 }
15581
15582 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15583 // This is a call, so all subexpressions are sequenced before the result.
15584 SequencedSubexpression Sequenced(*this);
15585
15586 if (!CCE->isListInitialization())
15587 return VisitExpr(CCE);
15588
15589 // In C++11, list initializations are sequenced.
15590 SequenceExpressionsInOrder(
15591 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15592 }
15593
15594 void VisitInitListExpr(const InitListExpr *ILE) {
15595 if (!SemaRef.getLangOpts().CPlusPlus11)
15596 return VisitExpr(ILE);
15597
15598 // In C++11, list initializations are sequenced.
15599 SequenceExpressionsInOrder(ILE->inits());
15600 }
15601
15602 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15603 // C++20 parenthesized list initializations are sequenced. See C++20
15604 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15605 SequenceExpressionsInOrder(PLIE->getInitExprs());
15606 }
15607
15608private:
15609 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15611 SequenceTree::Seq Parent = Region;
15612 for (const Expr *E : ExpressionList) {
15613 if (!E)
15614 continue;
15615 Region = Tree.allocate(Parent);
15616 Elts.push_back(Region);
15617 Visit(E);
15618 }
15619
15620 // Forget that the initializers are sequenced.
15621 Region = Parent;
15622 for (unsigned I = 0; I < Elts.size(); ++I)
15623 Tree.merge(Elts[I]);
15624 }
15625};
15626
15627SequenceChecker::UsageInfo::UsageInfo() = default;
15628
15629} // namespace
15630
15631void Sema::CheckUnsequencedOperations(const Expr *E) {
15632 SmallVector<const Expr *, 8> WorkList;
15633 WorkList.push_back(E);
15634 while (!WorkList.empty()) {
15635 const Expr *Item = WorkList.pop_back_val();
15636 SequenceChecker(*this, Item, WorkList);
15637 }
15638}
15639
15640void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15641 bool IsConstexpr) {
15642 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15643 IsConstexpr || isa<ConstantExpr>(E));
15644 CheckImplicitConversions(E, CheckLoc);
15645 if (!E->isInstantiationDependent())
15646 CheckUnsequencedOperations(E);
15647 if (!IsConstexpr && !E->isValueDependent())
15648 CheckForIntOverflow(E);
15649}
15650
15651void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15652 FieldDecl *BitField,
15653 Expr *Init) {
15654 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15655}
15656
15658 SourceLocation Loc) {
15659 if (!PType->isVariablyModifiedType())
15660 return;
15661 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15662 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15663 return;
15664 }
15665 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15666 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15667 return;
15668 }
15669 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15670 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15671 return;
15672 }
15673
15674 const ArrayType *AT = S.Context.getAsArrayType(PType);
15675 if (!AT)
15676 return;
15677
15680 return;
15681 }
15682
15683 S.Diag(Loc, diag::err_array_star_in_function_definition);
15684}
15685
15687 bool CheckParameterNames) {
15688 bool HasInvalidParm = false;
15689 for (ParmVarDecl *Param : Parameters) {
15690 assert(Param && "null in a parameter list");
15691 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15692 // function declarator that is part of a function definition of
15693 // that function shall not have incomplete type.
15694 //
15695 // C++23 [dcl.fct.def.general]/p2
15696 // The type of a parameter [...] for a function definition
15697 // shall not be a (possibly cv-qualified) class type that is incomplete
15698 // or abstract within the function body unless the function is deleted.
15699 if (!Param->isInvalidDecl() &&
15700 (RequireCompleteType(Param->getLocation(), Param->getType(),
15701 diag::err_typecheck_decl_incomplete_type) ||
15702 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15703 diag::err_abstract_type_in_decl,
15705 Param->setInvalidDecl();
15706 HasInvalidParm = true;
15707 }
15708
15709 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15710 // declaration of each parameter shall include an identifier.
15711 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15712 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15713 // Diagnose this as an extension in C17 and earlier.
15714 if (!getLangOpts().C23)
15715 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15716 }
15717
15718 // C99 6.7.5.3p12:
15719 // If the function declarator is not part of a definition of that
15720 // function, parameters may have incomplete type and may use the [*]
15721 // notation in their sequences of declarator specifiers to specify
15722 // variable length array types.
15723 QualType PType = Param->getOriginalType();
15724 // FIXME: This diagnostic should point the '[*]' if source-location
15725 // information is added for it.
15726 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15727
15728 // If the parameter is a c++ class type and it has to be destructed in the
15729 // callee function, declare the destructor so that it can be called by the
15730 // callee function. Do not perform any direct access check on the dtor here.
15731 if (!Param->isInvalidDecl()) {
15732 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15733 if (!ClassDecl->isInvalidDecl() &&
15734 !ClassDecl->hasIrrelevantDestructor() &&
15735 !ClassDecl->isDependentContext() &&
15736 ClassDecl->isParamDestroyedInCallee()) {
15738 MarkFunctionReferenced(Param->getLocation(), Destructor);
15739 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15740 }
15741 }
15742 }
15743
15744 // Parameters with the pass_object_size attribute only need to be marked
15745 // constant at function definitions. Because we lack information about
15746 // whether we're on a declaration or definition when we're instantiating the
15747 // attribute, we need to check for constness here.
15748 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15749 if (!Param->getType().isConstQualified())
15750 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15751 << Attr->getSpelling() << 1;
15752
15753 // Check for parameter names shadowing fields from the class.
15754 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15755 // The owning context for the parameter should be the function, but we
15756 // want to see if this function's declaration context is a record.
15757 DeclContext *DC = Param->getDeclContext();
15758 if (DC && DC->isFunctionOrMethod()) {
15759 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15760 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15761 RD, /*DeclIsField*/ false);
15762 }
15763 }
15764
15765 if (!Param->isInvalidDecl() &&
15766 Param->getOriginalType()->isWebAssemblyTableType()) {
15767 Param->setInvalidDecl();
15768 HasInvalidParm = true;
15769 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15770 }
15771 }
15772
15773 return HasInvalidParm;
15774}
15775
15776std::optional<std::pair<
15778 *E,
15780 &Ctx);
15781
15782/// Compute the alignment and offset of the base class object given the
15783/// derived-to-base cast expression and the alignment and offset of the derived
15784/// class object.
15785static std::pair<CharUnits, CharUnits>
15787 CharUnits BaseAlignment, CharUnits Offset,
15788 ASTContext &Ctx) {
15789 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15790 ++PathI) {
15791 const CXXBaseSpecifier *Base = *PathI;
15792 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15793 if (Base->isVirtual()) {
15794 // The complete object may have a lower alignment than the non-virtual
15795 // alignment of the base, in which case the base may be misaligned. Choose
15796 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15797 // conservative lower bound of the complete object alignment.
15798 CharUnits NonVirtualAlignment =
15800 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15801 Offset = CharUnits::Zero();
15802 } else {
15803 const ASTRecordLayout &RL =
15804 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15805 Offset += RL.getBaseClassOffset(BaseDecl);
15806 }
15807 DerivedType = Base->getType();
15808 }
15809
15810 return std::make_pair(BaseAlignment, Offset);
15811}
15812
15813/// Compute the alignment and offset of a binary additive operator.
15814static std::optional<std::pair<CharUnits, CharUnits>>
15816 bool IsSub, ASTContext &Ctx) {
15817 QualType PointeeType = PtrE->getType()->getPointeeType();
15818
15819 if (!PointeeType->isConstantSizeType())
15820 return std::nullopt;
15821
15822 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15823
15824 if (!P)
15825 return std::nullopt;
15826
15827 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15828 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15829 CharUnits Offset = EltSize * IdxRes->getExtValue();
15830 if (IsSub)
15831 Offset = -Offset;
15832 return std::make_pair(P->first, P->second + Offset);
15833 }
15834
15835 // If the integer expression isn't a constant expression, compute the lower
15836 // bound of the alignment using the alignment and offset of the pointer
15837 // expression and the element size.
15838 return std::make_pair(
15839 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15840 CharUnits::Zero());
15841}
15842
15843/// This helper function takes an lvalue expression and returns the alignment of
15844/// a VarDecl and a constant offset from the VarDecl.
15845std::optional<std::pair<
15846 CharUnits,
15848 ASTContext &Ctx) {
15849 E = E->IgnoreParens();
15850 switch (E->getStmtClass()) {
15851 default:
15852 break;
15853 case Stmt::CStyleCastExprClass:
15854 case Stmt::CXXStaticCastExprClass:
15855 case Stmt::ImplicitCastExprClass: {
15856 auto *CE = cast<CastExpr>(E);
15857 const Expr *From = CE->getSubExpr();
15858 switch (CE->getCastKind()) {
15859 default:
15860 break;
15861 case CK_NoOp:
15862 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15863 case CK_UncheckedDerivedToBase:
15864 case CK_DerivedToBase: {
15865 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15866 if (!P)
15867 break;
15868 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15869 P->second, Ctx);
15870 }
15871 }
15872 break;
15873 }
15874 case Stmt::ArraySubscriptExprClass: {
15875 auto *ASE = cast<ArraySubscriptExpr>(E);
15877 false, Ctx);
15878 }
15879 case Stmt::DeclRefExprClass: {
15880 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15881 // FIXME: If VD is captured by copy or is an escaping __block variable,
15882 // use the alignment of VD's type.
15883 if (!VD->getType()->isReferenceType()) {
15884 // Dependent alignment cannot be resolved -> bail out.
15885 if (VD->hasDependentAlignment())
15886 break;
15887 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15888 }
15889 if (VD->hasInit())
15890 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15891 }
15892 break;
15893 }
15894 case Stmt::MemberExprClass: {
15895 auto *ME = cast<MemberExpr>(E);
15896 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15897 if (!FD || FD->getType()->isReferenceType() ||
15899 break;
15900 std::optional<std::pair<CharUnits, CharUnits>> P;
15901 if (ME->isArrow())
15902 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15903 else
15904 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15905 if (!P)
15906 break;
15907 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15908 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15909 return std::make_pair(P->first,
15910 P->second + CharUnits::fromQuantity(Offset));
15911 }
15912 case Stmt::UnaryOperatorClass: {
15913 auto *UO = cast<UnaryOperator>(E);
15914 switch (UO->getOpcode()) {
15915 default:
15916 break;
15917 case UO_Deref:
15919 }
15920 break;
15921 }
15922 case Stmt::BinaryOperatorClass: {
15923 auto *BO = cast<BinaryOperator>(E);
15924 auto Opcode = BO->getOpcode();
15925 switch (Opcode) {
15926 default:
15927 break;
15928 case BO_Comma:
15930 }
15931 break;
15932 }
15933 }
15934 return std::nullopt;
15935}
15936
15937/// This helper function takes a pointer expression and returns the alignment of
15938/// a VarDecl and a constant offset from the VarDecl.
15939std::optional<std::pair<
15941 *E,
15943 &Ctx) {
15944 E = E->IgnoreParens();
15945 switch (E->getStmtClass()) {
15946 default:
15947 break;
15948 case Stmt::CStyleCastExprClass:
15949 case Stmt::CXXStaticCastExprClass:
15950 case Stmt::ImplicitCastExprClass: {
15951 auto *CE = cast<CastExpr>(E);
15952 const Expr *From = CE->getSubExpr();
15953 switch (CE->getCastKind()) {
15954 default:
15955 break;
15956 case CK_NoOp:
15957 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15958 case CK_ArrayToPointerDecay:
15959 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15960 case CK_UncheckedDerivedToBase:
15961 case CK_DerivedToBase: {
15962 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15963 if (!P)
15964 break;
15966 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15967 }
15968 }
15969 break;
15970 }
15971 case Stmt::CXXThisExprClass: {
15972 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15974 return std::make_pair(Alignment, CharUnits::Zero());
15975 }
15976 case Stmt::UnaryOperatorClass: {
15977 auto *UO = cast<UnaryOperator>(E);
15978 if (UO->getOpcode() == UO_AddrOf)
15980 break;
15981 }
15982 case Stmt::BinaryOperatorClass: {
15983 auto *BO = cast<BinaryOperator>(E);
15984 auto Opcode = BO->getOpcode();
15985 switch (Opcode) {
15986 default:
15987 break;
15988 case BO_Add:
15989 case BO_Sub: {
15990 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15991 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15992 std::swap(LHS, RHS);
15993 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15994 Ctx);
15995 }
15996 case BO_Comma:
15997 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15998 }
15999 break;
16000 }
16001 }
16002 return std::nullopt;
16003}
16004
16006 // See if we can compute the alignment of a VarDecl and an offset from it.
16007 std::optional<std::pair<CharUnits, CharUnits>> P =
16009
16010 if (P)
16011 return P->first.alignmentAtOffset(P->second);
16012
16013 // If that failed, return the type's alignment.
16015}
16016
16018 // This is actually a lot of work to potentially be doing on every
16019 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
16020 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
16021 return;
16022
16023 // Ignore dependent types.
16024 if (T->isDependentType() || Op->getType()->isDependentType())
16025 return;
16026
16027 // Require that the destination be a pointer type.
16028 const PointerType *DestPtr = T->getAs<PointerType>();
16029 if (!DestPtr) return;
16030
16031 // If the destination has alignment 1, we're done.
16032 QualType DestPointee = DestPtr->getPointeeType();
16033 if (DestPointee->isIncompleteType()) return;
16034 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
16035 if (DestAlign.isOne()) return;
16036
16037 // Require that the source be a pointer type.
16038 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
16039 if (!SrcPtr) return;
16040 QualType SrcPointee = SrcPtr->getPointeeType();
16041
16042 // Explicitly allow casts from cv void*. We already implicitly
16043 // allowed casts to cv void*, since they have alignment 1.
16044 // Also allow casts involving incomplete types, which implicitly
16045 // includes 'void'.
16046 if (SrcPointee->isIncompleteType()) return;
16047
16048 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
16049
16050 if (SrcAlign >= DestAlign) return;
16051
16052 Diag(TRange.getBegin(), diag::warn_cast_align)
16053 << Op->getType() << T
16054 << static_cast<unsigned>(SrcAlign.getQuantity())
16055 << static_cast<unsigned>(DestAlign.getQuantity())
16056 << TRange << Op->getSourceRange();
16057}
16058
16059void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
16060 const ArraySubscriptExpr *ASE,
16061 bool AllowOnePastEnd, bool IndexNegated) {
16062 // Already diagnosed by the constant evaluator.
16064 return;
16065
16066 IndexExpr = IndexExpr->IgnoreParenImpCasts();
16067 if (IndexExpr->isValueDependent())
16068 return;
16069
16070 const Type *EffectiveType =
16072 BaseExpr = BaseExpr->IgnoreParenCasts();
16073 const ConstantArrayType *ArrayTy =
16074 Context.getAsConstantArrayType(BaseExpr->getType());
16075
16077 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
16078
16079 const Type *BaseType =
16080 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
16081 bool IsUnboundedArray =
16082 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
16083 Context, StrictFlexArraysLevel,
16084 /*IgnoreTemplateOrMacroSubstitution=*/true);
16085 if (EffectiveType->isDependentType() ||
16086 (!IsUnboundedArray && BaseType->isDependentType()))
16087 return;
16088
16090 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
16091 return;
16092
16093 llvm::APSInt index = Result.Val.getInt();
16094 if (IndexNegated) {
16095 index.setIsUnsigned(false);
16096 index = -index;
16097 }
16098
16099 if (IsUnboundedArray) {
16100 if (EffectiveType->isFunctionType())
16101 return;
16102 if (index.isUnsigned() || !index.isNegative()) {
16103 const auto &ASTC = getASTContext();
16104 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
16105 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
16106 if (index.getBitWidth() < AddrBits)
16107 index = index.zext(AddrBits);
16108 std::optional<CharUnits> ElemCharUnits =
16109 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
16110 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
16111 // pointer) bounds-checking isn't meaningful.
16112 if (!ElemCharUnits || ElemCharUnits->isZero())
16113 return;
16114 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
16115 // If index has more active bits than address space, we already know
16116 // we have a bounds violation to warn about. Otherwise, compute
16117 // address of (index + 1)th element, and warn about bounds violation
16118 // only if that address exceeds address space.
16119 if (index.getActiveBits() <= AddrBits) {
16120 bool Overflow;
16121 llvm::APInt Product(index);
16122 Product += 1;
16123 Product = Product.umul_ov(ElemBytes, Overflow);
16124 if (!Overflow && Product.getActiveBits() <= AddrBits)
16125 return;
16126 }
16127
16128 // Need to compute max possible elements in address space, since that
16129 // is included in diag message.
16130 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
16131 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
16132 MaxElems += 1;
16133 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
16134 MaxElems = MaxElems.udiv(ElemBytes);
16135
16136 unsigned DiagID =
16137 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16138 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16139
16140 // Diag message shows element size in bits and in "bytes" (platform-
16141 // dependent CharUnits)
16142 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16143 PDiag(DiagID) << index << AddrBits
16144 << (unsigned)ASTC.toBits(*ElemCharUnits)
16145 << ElemBytes << MaxElems
16146 << MaxElems.getZExtValue()
16147 << IndexExpr->getSourceRange());
16148
16149 const NamedDecl *ND = nullptr;
16150 // Try harder to find a NamedDecl to point at in the note.
16151 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16152 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16153 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16154 ND = DRE->getDecl();
16155 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16156 ND = ME->getMemberDecl();
16157
16158 if (ND)
16159 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16160 PDiag(diag::note_array_declared_here) << ND);
16161 }
16162 return;
16163 }
16164
16165 if (index.isUnsigned() || !index.isNegative()) {
16166 // It is possible that the type of the base expression after
16167 // IgnoreParenCasts is incomplete, even though the type of the base
16168 // expression before IgnoreParenCasts is complete (see PR39746 for an
16169 // example). In this case we have no information about whether the array
16170 // access exceeds the array bounds. However we can still diagnose an array
16171 // access which precedes the array bounds.
16172 if (BaseType->isIncompleteType())
16173 return;
16174
16175 llvm::APInt size = ArrayTy->getSize();
16176
16177 if (BaseType != EffectiveType) {
16178 // Make sure we're comparing apples to apples when comparing index to
16179 // size.
16180 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
16181 uint64_t array_typesize = Context.getTypeSize(BaseType);
16182
16183 // Handle ptrarith_typesize being zero, such as when casting to void*.
16184 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16185 if (!ptrarith_typesize)
16186 ptrarith_typesize = Context.getCharWidth();
16187
16188 if (ptrarith_typesize != array_typesize) {
16189 // There's a cast to a different size type involved.
16190 uint64_t ratio = array_typesize / ptrarith_typesize;
16191
16192 // TODO: Be smarter about handling cases where array_typesize is not a
16193 // multiple of ptrarith_typesize.
16194 if (ptrarith_typesize * ratio == array_typesize)
16195 size *= llvm::APInt(size.getBitWidth(), ratio);
16196 }
16197 }
16198
16199 if (size.getBitWidth() > index.getBitWidth())
16200 index = index.zext(size.getBitWidth());
16201 else if (size.getBitWidth() < index.getBitWidth())
16202 size = size.zext(index.getBitWidth());
16203
16204 // For array subscripting the index must be less than size, but for pointer
16205 // arithmetic also allow the index (offset) to be equal to size since
16206 // computing the next address after the end of the array is legal and
16207 // commonly done e.g. in C++ iterators and range-based for loops.
16208 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16209 return;
16210
16211 // Suppress the warning if the subscript expression (as identified by the
16212 // ']' location) and the index expression are both from macro expansions
16213 // within a system header.
16214 if (ASE) {
16215 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16216 ASE->getRBracketLoc());
16217 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
16218 SourceLocation IndexLoc =
16219 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
16220 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16221 return;
16222 }
16223 }
16224
16225 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16226 : diag::warn_ptr_arith_exceeds_bounds;
16227 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16228 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16229
16230 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16231 PDiag(DiagID)
16232 << index << ArrayTy->desugar() << CastMsg
16233 << CastMsgTy << IndexExpr->getSourceRange());
16234 } else {
16235 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16236 if (!ASE) {
16237 DiagID = diag::warn_ptr_arith_precedes_bounds;
16238 if (index.isNegative()) index = -index;
16239 }
16240
16241 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16242 PDiag(DiagID) << index << IndexExpr->getSourceRange());
16243 }
16244
16245 const NamedDecl *ND = nullptr;
16246 // Try harder to find a NamedDecl to point at in the note.
16247 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16248 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16249 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16250 ND = DRE->getDecl();
16251 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16252 ND = ME->getMemberDecl();
16253
16254 if (ND)
16255 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16256 PDiag(diag::note_array_declared_here) << ND);
16257}
16258
16259void Sema::CheckArrayAccess(const Expr *expr) {
16260 int AllowOnePastEnd = 0;
16261 while (expr) {
16262 expr = expr->IgnoreParenImpCasts();
16263 switch (expr->getStmtClass()) {
16264 case Stmt::ArraySubscriptExprClass: {
16265 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16266 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16267 AllowOnePastEnd > 0);
16268 expr = ASE->getBase();
16269 break;
16270 }
16271 case Stmt::MemberExprClass: {
16272 expr = cast<MemberExpr>(expr)->getBase();
16273 break;
16274 }
16275 case Stmt::CXXMemberCallExprClass: {
16276 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16277 break;
16278 }
16279 case Stmt::ArraySectionExprClass: {
16280 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16281 // FIXME: We should probably be checking all of the elements to the
16282 // 'length' here as well.
16283 if (ASE->getLowerBound())
16284 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16285 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16286 return;
16287 }
16288 case Stmt::UnaryOperatorClass: {
16289 // Only unwrap the * and & unary operators
16290 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16291 expr = UO->getSubExpr();
16292 switch (UO->getOpcode()) {
16293 case UO_AddrOf:
16294 AllowOnePastEnd++;
16295 break;
16296 case UO_Deref:
16297 AllowOnePastEnd--;
16298 break;
16299 default:
16300 return;
16301 }
16302 break;
16303 }
16304 case Stmt::ConditionalOperatorClass: {
16305 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16306 if (const Expr *lhs = cond->getLHS())
16307 CheckArrayAccess(lhs);
16308 if (const Expr *rhs = cond->getRHS())
16309 CheckArrayAccess(rhs);
16310 return;
16311 }
16312 case Stmt::CXXOperatorCallExprClass: {
16313 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16314 for (const auto *Arg : OCE->arguments())
16315 CheckArrayAccess(Arg);
16316 return;
16317 }
16318 default:
16319 return;
16320 }
16321 }
16322}
16323
16325 Expr *RHS, bool isProperty) {
16326 // Check if RHS is an Objective-C object literal, which also can get
16327 // immediately zapped in a weak reference. Note that we explicitly
16328 // allow ObjCStringLiterals, since those are designed to never really die.
16329 RHS = RHS->IgnoreParenImpCasts();
16330
16331 // This enum needs to match with the 'select' in
16332 // warn_objc_arc_literal_assign (off-by-1).
16334 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16335 return false;
16336
16337 S.Diag(Loc, diag::warn_arc_literal_assign)
16338 << (unsigned) Kind
16339 << (isProperty ? 0 : 1)
16340 << RHS->getSourceRange();
16341
16342 return true;
16343}
16344
16347 Expr *RHS, bool isProperty) {
16348 // Strip off any implicit cast added to get to the one ARC-specific.
16349 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16350 if (cast->getCastKind() == CK_ARCConsumeObject) {
16351 S.Diag(Loc, diag::warn_arc_retained_assign)
16353 << (isProperty ? 0 : 1)
16354 << RHS->getSourceRange();
16355 return true;
16356 }
16357 RHS = cast->getSubExpr();
16358 }
16359
16360 if (LT == Qualifiers::OCL_Weak &&
16361 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16362 return true;
16363
16364 return false;
16365}
16366
16368 QualType LHS, Expr *RHS) {
16370
16372 return false;
16373
16374 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16375 return true;
16376
16377 return false;
16378}
16379
16381 Expr *LHS, Expr *RHS) {
16382 QualType LHSType;
16383 // PropertyRef on LHS type need be directly obtained from
16384 // its declaration as it has a PseudoType.
16386 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16387 if (PRE && !PRE->isImplicitProperty()) {
16388 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16389 if (PD)
16390 LHSType = PD->getType();
16391 }
16392
16393 if (LHSType.isNull())
16394 LHSType = LHS->getType();
16395
16397
16398 if (LT == Qualifiers::OCL_Weak) {
16399 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16401 }
16402
16403 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16404 return;
16405
16406 // FIXME. Check for other life times.
16407 if (LT != Qualifiers::OCL_None)
16408 return;
16409
16410 if (PRE) {
16411 if (PRE->isImplicitProperty())
16412 return;
16413 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16414 if (!PD)
16415 return;
16416
16417 unsigned Attributes = PD->getPropertyAttributes();
16418 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16419 // when 'assign' attribute was not explicitly specified
16420 // by user, ignore it and rely on property type itself
16421 // for lifetime info.
16422 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16423 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16424 LHSType->isObjCRetainableType())
16425 return;
16426
16427 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16428 if (cast->getCastKind() == CK_ARCConsumeObject) {
16429 Diag(Loc, diag::warn_arc_retained_property_assign)
16430 << RHS->getSourceRange();
16431 return;
16432 }
16433 RHS = cast->getSubExpr();
16434 }
16435 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16436 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16437 return;
16438 }
16439 }
16440}
16441
16442//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16443
16444static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16445 SourceLocation StmtLoc,
16446 const NullStmt *Body) {
16447 // Do not warn if the body is a macro that expands to nothing, e.g:
16448 //
16449 // #define CALL(x)
16450 // if (condition)
16451 // CALL(0);
16452 if (Body->hasLeadingEmptyMacro())
16453 return false;
16454
16455 // Get line numbers of statement and body.
16456 bool StmtLineInvalid;
16457 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16458 &StmtLineInvalid);
16459 if (StmtLineInvalid)
16460 return false;
16461
16462 bool BodyLineInvalid;
16463 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16464 &BodyLineInvalid);
16465 if (BodyLineInvalid)
16466 return false;
16467
16468 // Warn if null statement and body are on the same line.
16469 if (StmtLine != BodyLine)
16470 return false;
16471
16472 return true;
16473}
16474
16476 const Stmt *Body,
16477 unsigned DiagID) {
16478 // Since this is a syntactic check, don't emit diagnostic for template
16479 // instantiations, this just adds noise.
16481 return;
16482
16483 // The body should be a null statement.
16484 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16485 if (!NBody)
16486 return;
16487
16488 // Do the usual checks.
16489 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16490 return;
16491
16492 Diag(NBody->getSemiLoc(), DiagID);
16493 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16494}
16495
16497 const Stmt *PossibleBody) {
16498 assert(!CurrentInstantiationScope); // Ensured by caller
16499
16500 SourceLocation StmtLoc;
16501 const Stmt *Body;
16502 unsigned DiagID;
16503 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16504 StmtLoc = FS->getRParenLoc();
16505 Body = FS->getBody();
16506 DiagID = diag::warn_empty_for_body;
16507 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16508 StmtLoc = WS->getRParenLoc();
16509 Body = WS->getBody();
16510 DiagID = diag::warn_empty_while_body;
16511 } else
16512 return; // Neither `for' nor `while'.
16513
16514 // The body should be a null statement.
16515 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16516 if (!NBody)
16517 return;
16518
16519 // Skip expensive checks if diagnostic is disabled.
16520 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16521 return;
16522
16523 // Do the usual checks.
16524 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16525 return;
16526
16527 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16528 // noise level low, emit diagnostics only if for/while is followed by a
16529 // CompoundStmt, e.g.:
16530 // for (int i = 0; i < n; i++);
16531 // {
16532 // a(i);
16533 // }
16534 // or if for/while is followed by a statement with more indentation
16535 // than for/while itself:
16536 // for (int i = 0; i < n; i++);
16537 // a(i);
16538 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16539 if (!ProbableTypo) {
16540 bool BodyColInvalid;
16541 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16542 PossibleBody->getBeginLoc(), &BodyColInvalid);
16543 if (BodyColInvalid)
16544 return;
16545
16546 bool StmtColInvalid;
16547 unsigned StmtCol =
16548 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16549 if (StmtColInvalid)
16550 return;
16551
16552 if (BodyCol > StmtCol)
16553 ProbableTypo = true;
16554 }
16555
16556 if (ProbableTypo) {
16557 Diag(NBody->getSemiLoc(), DiagID);
16558 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16559 }
16560}
16561
16562//===--- CHECK: Warn on self move with std::move. -------------------------===//
16563
16564void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16565 SourceLocation OpLoc) {
16566 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16567 return;
16568
16570 return;
16571
16572 // Strip parens and casts away.
16573 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16574 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16575
16576 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16577 // which we can treat as an inlined std::move
16578 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16579 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16580 RHSExpr = CE->getArg(0);
16581 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16582 CXXSCE && CXXSCE->isXValue())
16583 RHSExpr = CXXSCE->getSubExpr();
16584 else
16585 return;
16586
16587 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16588 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16589
16590 // Two DeclRefExpr's, check that the decls are the same.
16591 if (LHSDeclRef && RHSDeclRef) {
16592 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16593 return;
16594 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16595 RHSDeclRef->getDecl()->getCanonicalDecl())
16596 return;
16597
16598 auto D = Diag(OpLoc, diag::warn_self_move)
16599 << LHSExpr->getType() << LHSExpr->getSourceRange()
16600 << RHSExpr->getSourceRange();
16601 if (const FieldDecl *F =
16603 D << 1 << F
16604 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16605 else
16606 D << 0;
16607 return;
16608 }
16609
16610 // Member variables require a different approach to check for self moves.
16611 // MemberExpr's are the same if every nested MemberExpr refers to the same
16612 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16613 // the base Expr's are CXXThisExpr's.
16614 const Expr *LHSBase = LHSExpr;
16615 const Expr *RHSBase = RHSExpr;
16616 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16617 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16618 if (!LHSME || !RHSME)
16619 return;
16620
16621 while (LHSME && RHSME) {
16622 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16623 RHSME->getMemberDecl()->getCanonicalDecl())
16624 return;
16625
16626 LHSBase = LHSME->getBase();
16627 RHSBase = RHSME->getBase();
16628 LHSME = dyn_cast<MemberExpr>(LHSBase);
16629 RHSME = dyn_cast<MemberExpr>(RHSBase);
16630 }
16631
16632 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16633 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16634 if (LHSDeclRef && RHSDeclRef) {
16635 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16636 return;
16637 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16638 RHSDeclRef->getDecl()->getCanonicalDecl())
16639 return;
16640
16641 Diag(OpLoc, diag::warn_self_move)
16642 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16643 << RHSExpr->getSourceRange();
16644 return;
16645 }
16646
16647 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16648 Diag(OpLoc, diag::warn_self_move)
16649 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16650 << RHSExpr->getSourceRange();
16651}
16652
16653//===--- Layout compatibility ----------------------------------------------//
16654
16655static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16656
16657/// Check if two enumeration types are layout-compatible.
16658static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16659 const EnumDecl *ED2) {
16660 // C++11 [dcl.enum] p8:
16661 // Two enumeration types are layout-compatible if they have the same
16662 // underlying type.
16663 return ED1->isComplete() && ED2->isComplete() &&
16664 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16665}
16666
16667/// Check if two fields are layout-compatible.
16668/// Can be used on union members, which are exempt from alignment requirement
16669/// of common initial sequence.
16670static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16671 const FieldDecl *Field2,
16672 bool AreUnionMembers = false) {
16673#ifndef NDEBUG
16674 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16675 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16676 assert(((Field1Parent->isStructureOrClassType() &&
16677 Field2Parent->isStructureOrClassType()) ||
16678 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16679 "Can't evaluate layout compatibility between a struct field and a "
16680 "union field.");
16681 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16682 (AreUnionMembers && Field1Parent->isUnionType())) &&
16683 "AreUnionMembers should be 'true' for union fields (only).");
16684#endif
16685
16686 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16687 return false;
16688
16689 if (Field1->isBitField() != Field2->isBitField())
16690 return false;
16691
16692 if (Field1->isBitField()) {
16693 // Make sure that the bit-fields are the same length.
16694 unsigned Bits1 = Field1->getBitWidthValue();
16695 unsigned Bits2 = Field2->getBitWidthValue();
16696
16697 if (Bits1 != Bits2)
16698 return false;
16699 }
16700
16701 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16702 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16703 return false;
16704
16705 if (!AreUnionMembers &&
16706 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16707 return false;
16708
16709 return true;
16710}
16711
16712/// Check if two standard-layout structs are layout-compatible.
16713/// (C++11 [class.mem] p17)
16714static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16715 const RecordDecl *RD2) {
16716 // Get to the class where the fields are declared
16717 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16718 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16719
16720 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16721 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16722
16723 // Check the fields.
16724 return llvm::equal(RD1->fields(), RD2->fields(),
16725 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16726 return isLayoutCompatible(C, F1, F2);
16727 });
16728}
16729
16730/// Check if two standard-layout unions are layout-compatible.
16731/// (C++11 [class.mem] p18)
16732static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16733 const RecordDecl *RD2) {
16734 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16735 RD2->fields());
16736
16737 for (auto *Field1 : RD1->fields()) {
16738 auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
16739 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
16740 });
16741 if (It == UnmatchedFields.end())
16742 return false;
16743 [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
16744 assert(Result);
16745 }
16746
16747 return UnmatchedFields.empty();
16748}
16749
16750static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16751 const RecordDecl *RD2) {
16752 if (RD1->isUnion() != RD2->isUnion())
16753 return false;
16754
16755 if (RD1->isUnion())
16756 return isLayoutCompatibleUnion(C, RD1, RD2);
16757 else
16758 return isLayoutCompatibleStruct(C, RD1, RD2);
16759}
16760
16761/// Check if two types are layout-compatible in C++11 sense.
16762static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16763 if (T1.isNull() || T2.isNull())
16764 return false;
16765
16766 // C++20 [basic.types] p11:
16767 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16768 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16769 // or layout-compatible standard-layout class types (11.4).
16772
16773 if (C.hasSameType(T1, T2))
16774 return true;
16775
16776 const Type::TypeClass TC1 = T1->getTypeClass();
16777 const Type::TypeClass TC2 = T2->getTypeClass();
16778
16779 if (TC1 != TC2)
16780 return false;
16781
16782 if (TC1 == Type::Enum)
16783 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16784 if (TC1 == Type::Record) {
16785 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16786 return false;
16787
16789 T2->castAsRecordDecl());
16790 }
16791
16792 return false;
16793}
16794
16796 return isLayoutCompatible(getASTContext(), T1, T2);
16797}
16798
16799//===-------------- Pointer interconvertibility ----------------------------//
16800
16802 const TypeSourceInfo *Derived) {
16803 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16804 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16805
16806 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16807 getASTContext().hasSameType(BaseT, DerivedT))
16808 return true;
16809
16810 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16811 return false;
16812
16813 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16814 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16815 return true;
16816
16817 return false;
16818}
16819
16820//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16821
16822/// Given a type tag expression find the type tag itself.
16823///
16824/// \param TypeExpr Type tag expression, as it appears in user's code.
16825///
16826/// \param VD Declaration of an identifier that appears in a type tag.
16827///
16828/// \param MagicValue Type tag magic value.
16829///
16830/// \param isConstantEvaluated whether the evalaution should be performed in
16831
16832/// constant context.
16833static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16834 const ValueDecl **VD, uint64_t *MagicValue,
16835 bool isConstantEvaluated) {
16836 while(true) {
16837 if (!TypeExpr)
16838 return false;
16839
16840 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16841
16842 switch (TypeExpr->getStmtClass()) {
16843 case Stmt::UnaryOperatorClass: {
16844 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16845 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16846 TypeExpr = UO->getSubExpr();
16847 continue;
16848 }
16849 return false;
16850 }
16851
16852 case Stmt::DeclRefExprClass: {
16853 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16854 *VD = DRE->getDecl();
16855 return true;
16856 }
16857
16858 case Stmt::IntegerLiteralClass: {
16859 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16860 llvm::APInt MagicValueAPInt = IL->getValue();
16861 if (MagicValueAPInt.getActiveBits() <= 64) {
16862 *MagicValue = MagicValueAPInt.getZExtValue();
16863 return true;
16864 } else
16865 return false;
16866 }
16867
16868 case Stmt::BinaryConditionalOperatorClass:
16869 case Stmt::ConditionalOperatorClass: {
16870 const AbstractConditionalOperator *ACO =
16872 bool Result;
16873 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16874 isConstantEvaluated)) {
16875 if (Result)
16876 TypeExpr = ACO->getTrueExpr();
16877 else
16878 TypeExpr = ACO->getFalseExpr();
16879 continue;
16880 }
16881 return false;
16882 }
16883
16884 case Stmt::BinaryOperatorClass: {
16885 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16886 if (BO->getOpcode() == BO_Comma) {
16887 TypeExpr = BO->getRHS();
16888 continue;
16889 }
16890 return false;
16891 }
16892
16893 default:
16894 return false;
16895 }
16896 }
16897}
16898
16899/// Retrieve the C type corresponding to type tag TypeExpr.
16900///
16901/// \param TypeExpr Expression that specifies a type tag.
16902///
16903/// \param MagicValues Registered magic values.
16904///
16905/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16906/// kind.
16907///
16908/// \param TypeInfo Information about the corresponding C type.
16909///
16910/// \param isConstantEvaluated whether the evalaution should be performed in
16911/// constant context.
16912///
16913/// \returns true if the corresponding C type was found.
16915 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16916 const ASTContext &Ctx,
16917 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16918 *MagicValues,
16919 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16920 bool isConstantEvaluated) {
16921 FoundWrongKind = false;
16922
16923 // Variable declaration that has type_tag_for_datatype attribute.
16924 const ValueDecl *VD = nullptr;
16925
16926 uint64_t MagicValue;
16927
16928 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16929 return false;
16930
16931 if (VD) {
16932 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16933 if (I->getArgumentKind() != ArgumentKind) {
16934 FoundWrongKind = true;
16935 return false;
16936 }
16937 TypeInfo.Type = I->getMatchingCType();
16938 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16939 TypeInfo.MustBeNull = I->getMustBeNull();
16940 return true;
16941 }
16942 return false;
16943 }
16944
16945 if (!MagicValues)
16946 return false;
16947
16948 llvm::DenseMap<Sema::TypeTagMagicValue,
16950 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16951 if (I == MagicValues->end())
16952 return false;
16953
16954 TypeInfo = I->second;
16955 return true;
16956}
16957
16959 uint64_t MagicValue, QualType Type,
16960 bool LayoutCompatible,
16961 bool MustBeNull) {
16962 if (!TypeTagForDatatypeMagicValues)
16963 TypeTagForDatatypeMagicValues.reset(
16964 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16965
16966 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16967 (*TypeTagForDatatypeMagicValues)[Magic] =
16968 TypeTagData(Type, LayoutCompatible, MustBeNull);
16969}
16970
16971static bool IsSameCharType(QualType T1, QualType T2) {
16972 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16973 if (!BT1)
16974 return false;
16975
16976 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16977 if (!BT2)
16978 return false;
16979
16980 BuiltinType::Kind T1Kind = BT1->getKind();
16981 BuiltinType::Kind T2Kind = BT2->getKind();
16982
16983 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16984 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16985 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16986 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16987}
16988
16989void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16990 const ArrayRef<const Expr *> ExprArgs,
16991 SourceLocation CallSiteLoc) {
16992 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16993 bool IsPointerAttr = Attr->getIsPointer();
16994
16995 // Retrieve the argument representing the 'type_tag'.
16996 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16997 if (TypeTagIdxAST >= ExprArgs.size()) {
16998 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16999 << 0 << Attr->getTypeTagIdx().getSourceIndex();
17000 return;
17001 }
17002 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17003 bool FoundWrongKind;
17004 TypeTagData TypeInfo;
17005 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
17006 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17007 TypeInfo, isConstantEvaluatedContext())) {
17008 if (FoundWrongKind)
17009 Diag(TypeTagExpr->getExprLoc(),
17010 diag::warn_type_tag_for_datatype_wrong_kind)
17011 << TypeTagExpr->getSourceRange();
17012 return;
17013 }
17014
17015 // Retrieve the argument representing the 'arg_idx'.
17016 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17017 if (ArgumentIdxAST >= ExprArgs.size()) {
17018 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17019 << 1 << Attr->getArgumentIdx().getSourceIndex();
17020 return;
17021 }
17022 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17023 if (IsPointerAttr) {
17024 // Skip implicit cast of pointer to `void *' (as a function argument).
17025 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
17026 if (ICE->getType()->isVoidPointerType() &&
17027 ICE->getCastKind() == CK_BitCast)
17028 ArgumentExpr = ICE->getSubExpr();
17029 }
17030 QualType ArgumentType = ArgumentExpr->getType();
17031
17032 // Passing a `void*' pointer shouldn't trigger a warning.
17033 if (IsPointerAttr && ArgumentType->isVoidPointerType())
17034 return;
17035
17036 if (TypeInfo.MustBeNull) {
17037 // Type tag with matching void type requires a null pointer.
17038 if (!ArgumentExpr->isNullPointerConstant(Context,
17040 Diag(ArgumentExpr->getExprLoc(),
17041 diag::warn_type_safety_null_pointer_required)
17042 << ArgumentKind->getName()
17043 << ArgumentExpr->getSourceRange()
17044 << TypeTagExpr->getSourceRange();
17045 }
17046 return;
17047 }
17048
17049 QualType RequiredType = TypeInfo.Type;
17050 if (IsPointerAttr)
17051 RequiredType = Context.getPointerType(RequiredType);
17052
17053 bool mismatch = false;
17054 if (!TypeInfo.LayoutCompatible) {
17055 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
17056
17057 // C++11 [basic.fundamental] p1:
17058 // Plain char, signed char, and unsigned char are three distinct types.
17059 //
17060 // But we treat plain `char' as equivalent to `signed char' or `unsigned
17061 // char' depending on the current char signedness mode.
17062 if (mismatch)
17063 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
17064 RequiredType->getPointeeType())) ||
17065 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
17066 mismatch = false;
17067 } else
17068 if (IsPointerAttr)
17069 mismatch = !isLayoutCompatible(Context,
17070 ArgumentType->getPointeeType(),
17071 RequiredType->getPointeeType());
17072 else
17073 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
17074
17075 if (mismatch)
17076 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
17077 << ArgumentType << ArgumentKind
17078 << TypeInfo.LayoutCompatible << RequiredType
17079 << ArgumentExpr->getSourceRange()
17080 << TypeTagExpr->getSourceRange();
17081}
17082
17083void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17084 CharUnits Alignment) {
17085 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
17086 Alignment);
17087}
17088
17090 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
17091 const NamedDecl *ND = m.RD;
17092 if (ND->getName().empty()) {
17093 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17094 ND = TD;
17095 }
17096 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
17097 << m.MD << ND << m.E->getSourceRange();
17098 }
17100}
17101
17103 E = E->IgnoreParens();
17104 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
17105 return;
17106 if (isa<UnaryOperator>(E) &&
17107 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
17108 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
17109 if (isa<MemberExpr>(Op)) {
17110 auto &MisalignedMembersForExpr =
17112 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
17113 if (MA != MisalignedMembersForExpr.end() &&
17114 (T->isDependentType() || T->isIntegerType() ||
17115 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17116 Context.getTypeAlignInChars(
17117 T->getPointeeType()) <= MA->Alignment))))
17118 MisalignedMembersForExpr.erase(MA);
17119 }
17120 }
17121}
17122
17124 Expr *E,
17125 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17126 Action) {
17127 const auto *ME = dyn_cast<MemberExpr>(E);
17128 if (!ME)
17129 return;
17130
17131 // No need to check expressions with an __unaligned-qualified type.
17132 if (E->getType().getQualifiers().hasUnaligned())
17133 return;
17134
17135 // For a chain of MemberExpr like "a.b.c.d" this list
17136 // will keep FieldDecl's like [d, c, b].
17137 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17138 const MemberExpr *TopME = nullptr;
17139 bool AnyIsPacked = false;
17140 do {
17141 QualType BaseType = ME->getBase()->getType();
17142 if (BaseType->isDependentType())
17143 return;
17144 if (ME->isArrow())
17145 BaseType = BaseType->getPointeeType();
17146 auto *RD = BaseType->castAsRecordDecl();
17147 if (RD->isInvalidDecl())
17148 return;
17149
17150 ValueDecl *MD = ME->getMemberDecl();
17151 auto *FD = dyn_cast<FieldDecl>(MD);
17152 // We do not care about non-data members.
17153 if (!FD || FD->isInvalidDecl())
17154 return;
17155
17156 AnyIsPacked =
17157 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17158 ReverseMemberChain.push_back(FD);
17159
17160 TopME = ME;
17161 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17162 } while (ME);
17163 assert(TopME && "We did not compute a topmost MemberExpr!");
17164
17165 // Not the scope of this diagnostic.
17166 if (!AnyIsPacked)
17167 return;
17168
17169 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17170 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17171 // TODO: The innermost base of the member expression may be too complicated.
17172 // For now, just disregard these cases. This is left for future
17173 // improvement.
17174 if (!DRE && !isa<CXXThisExpr>(TopBase))
17175 return;
17176
17177 // Alignment expected by the whole expression.
17178 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17179
17180 // No need to do anything else with this case.
17181 if (ExpectedAlignment.isOne())
17182 return;
17183
17184 // Synthesize offset of the whole access.
17185 CharUnits Offset;
17186 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17187 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17188
17189 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17190 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17191 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17192
17193 // The base expression of the innermost MemberExpr may give
17194 // stronger guarantees than the class containing the member.
17195 if (DRE && !TopME->isArrow()) {
17196 const ValueDecl *VD = DRE->getDecl();
17197 if (!VD->getType()->isReferenceType())
17198 CompleteObjectAlignment =
17199 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17200 }
17201
17202 // Check if the synthesized offset fulfills the alignment.
17203 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17204 // It may fulfill the offset it but the effective alignment may still be
17205 // lower than the expected expression alignment.
17206 CompleteObjectAlignment < ExpectedAlignment) {
17207 // If this happens, we want to determine a sensible culprit of this.
17208 // Intuitively, watching the chain of member expressions from right to
17209 // left, we start with the required alignment (as required by the field
17210 // type) but some packed attribute in that chain has reduced the alignment.
17211 // It may happen that another packed structure increases it again. But if
17212 // we are here such increase has not been enough. So pointing the first
17213 // FieldDecl that either is packed or else its RecordDecl is,
17214 // seems reasonable.
17215 FieldDecl *FD = nullptr;
17216 CharUnits Alignment;
17217 for (FieldDecl *FDI : ReverseMemberChain) {
17218 if (FDI->hasAttr<PackedAttr>() ||
17219 FDI->getParent()->hasAttr<PackedAttr>()) {
17220 FD = FDI;
17221 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
17222 Context.getTypeAlignInChars(
17223 Context.getCanonicalTagType(FD->getParent())));
17224 break;
17225 }
17226 }
17227 assert(FD && "We did not find a packed FieldDecl!");
17228 Action(E, FD->getParent(), FD, Alignment);
17229 }
17230}
17231
17232void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17233 using namespace std::placeholders;
17234
17236 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17237 _2, _3, _4));
17238}
17239
17241 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17242 if (checkArgCount(TheCall, 1))
17243 return true;
17244
17245 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
17246 if (A.isInvalid())
17247 return true;
17248
17249 TheCall->setArg(0, A.get());
17250 QualType TyA = A.get()->getType();
17251
17252 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
17253 ArgTyRestr, 1))
17254 return true;
17255
17256 TheCall->setType(TyA);
17257 return false;
17258}
17259
17260bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17261 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17262 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17263 TheCall->setType(*Res);
17264 return false;
17265 }
17266 return true;
17267}
17268
17270 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17271 if (!Res)
17272 return true;
17273
17274 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17275 TheCall->setType(VecTy0->getElementType());
17276 else
17277 TheCall->setType(*Res);
17278
17279 return false;
17280}
17281
17283 SourceLocation Loc) {
17285 R = RHS->getEnumCoercedType(S.Context);
17286 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17288 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17289 << LHS->getSourceRange() << RHS->getSourceRange()
17290 << /*Arithmetic Between*/ 0 << L << R;
17291 }
17292 return false;
17293}
17294
17295/// Check if all arguments have the same type. If the types don't match, emit an
17296/// error message and return true. Otherwise return false.
17297///
17298/// For scalars we directly compare their unqualified types. But even if we
17299/// compare unqualified vector types, a difference in qualifiers in the element
17300/// types can make the vector types be considered not equal. For example,
17301/// vector of 4 'const float' values vs vector of 4 'float' values.
17302/// So we compare unqualified types of their elements and number of elements.
17304 ArrayRef<Expr *> Args) {
17305 assert(!Args.empty() && "Should have at least one argument.");
17306
17307 Expr *Arg0 = Args.front();
17308 QualType Ty0 = Arg0->getType();
17309
17310 auto EmitError = [&](Expr *ArgI) {
17311 SemaRef.Diag(Arg0->getBeginLoc(),
17312 diag::err_typecheck_call_different_arg_types)
17313 << Arg0->getType() << ArgI->getType();
17314 };
17315
17316 // Compare scalar types.
17317 if (!Ty0->isVectorType()) {
17318 for (Expr *ArgI : Args.drop_front())
17319 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17320 EmitError(ArgI);
17321 return true;
17322 }
17323
17324 return false;
17325 }
17326
17327 // Compare vector types.
17328 const auto *Vec0 = Ty0->castAs<VectorType>();
17329 for (Expr *ArgI : Args.drop_front()) {
17330 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17331 if (!VecI ||
17332 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17333 VecI->getElementType()) ||
17334 Vec0->getNumElements() != VecI->getNumElements()) {
17335 EmitError(ArgI);
17336 return true;
17337 }
17338 }
17339
17340 return false;
17341}
17342
17343std::optional<QualType>
17345 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17346 if (checkArgCount(TheCall, 2))
17347 return std::nullopt;
17348
17350 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17351 return std::nullopt;
17352
17353 Expr *Args[2];
17354 for (int I = 0; I < 2; ++I) {
17355 ExprResult Converted =
17356 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17357 if (Converted.isInvalid())
17358 return std::nullopt;
17359 Args[I] = Converted.get();
17360 }
17361
17362 SourceLocation LocA = Args[0]->getBeginLoc();
17363 QualType TyA = Args[0]->getType();
17364
17365 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17366 return std::nullopt;
17367
17368 if (checkBuiltinVectorMathArgTypes(*this, Args))
17369 return std::nullopt;
17370
17371 TheCall->setArg(0, Args[0]);
17372 TheCall->setArg(1, Args[1]);
17373 return TyA;
17374}
17375
17377 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17378 if (checkArgCount(TheCall, 3))
17379 return true;
17380
17381 SourceLocation Loc = TheCall->getExprLoc();
17382 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17383 TheCall->getArg(1), Loc) ||
17384 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17385 TheCall->getArg(2), Loc))
17386 return true;
17387
17388 Expr *Args[3];
17389 for (int I = 0; I < 3; ++I) {
17390 ExprResult Converted =
17391 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17392 if (Converted.isInvalid())
17393 return true;
17394 Args[I] = Converted.get();
17395 }
17396
17397 int ArgOrdinal = 1;
17398 for (Expr *Arg : Args) {
17399 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17400 ArgTyRestr, ArgOrdinal++))
17401 return true;
17402 }
17403
17404 if (checkBuiltinVectorMathArgTypes(*this, Args))
17405 return true;
17406
17407 for (int I = 0; I < 3; ++I)
17408 TheCall->setArg(I, Args[I]);
17409
17410 TheCall->setType(Args[0]->getType());
17411 return false;
17412}
17413
17414bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17415 if (checkArgCount(TheCall, 1))
17416 return true;
17417
17418 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17419 if (A.isInvalid())
17420 return true;
17421
17422 TheCall->setArg(0, A.get());
17423 return false;
17424}
17425
17426bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17427 if (checkArgCount(TheCall, 1))
17428 return true;
17429
17430 ExprResult Arg = TheCall->getArg(0);
17431 QualType TyArg = Arg.get()->getType();
17432
17433 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17434 return Diag(TheCall->getArg(0)->getBeginLoc(),
17435 diag::err_builtin_invalid_arg_type)
17436 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17437
17438 TheCall->setType(TyArg);
17439 return false;
17440}
17441
17442ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17443 ExprResult CallResult) {
17444 if (checkArgCount(TheCall, 1))
17445 return ExprError();
17446
17447 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17448 if (MatrixArg.isInvalid())
17449 return MatrixArg;
17450 Expr *Matrix = MatrixArg.get();
17451
17452 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17453 if (!MType) {
17454 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17455 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17456 << Matrix->getType();
17457 return ExprError();
17458 }
17459
17460 // Create returned matrix type by swapping rows and columns of the argument
17461 // matrix type.
17462 QualType ResultType = Context.getConstantMatrixType(
17463 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17464
17465 // Change the return type to the type of the returned matrix.
17466 TheCall->setType(ResultType);
17467
17468 // Update call argument to use the possibly converted matrix argument.
17469 TheCall->setArg(0, Matrix);
17470 return CallResult;
17471}
17472
17473// Get and verify the matrix dimensions.
17474static std::optional<unsigned>
17476 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17477 if (!Value) {
17478 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17479 << Name;
17480 return {};
17481 }
17482 uint64_t Dim = Value->getZExtValue();
17483 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17484 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17485 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17486 return {};
17487 }
17488 return Dim;
17489}
17490
17491ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17492 ExprResult CallResult) {
17493 if (!getLangOpts().MatrixTypes) {
17494 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17495 return ExprError();
17496 }
17497
17498 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17500 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17501 << /*column*/ 1 << /*load*/ 0;
17502 return ExprError();
17503 }
17504
17505 if (checkArgCount(TheCall, 4))
17506 return ExprError();
17507
17508 unsigned PtrArgIdx = 0;
17509 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17510 Expr *RowsExpr = TheCall->getArg(1);
17511 Expr *ColumnsExpr = TheCall->getArg(2);
17512 Expr *StrideExpr = TheCall->getArg(3);
17513
17514 bool ArgError = false;
17515
17516 // Check pointer argument.
17517 {
17519 if (PtrConv.isInvalid())
17520 return PtrConv;
17521 PtrExpr = PtrConv.get();
17522 TheCall->setArg(0, PtrExpr);
17523 if (PtrExpr->isTypeDependent()) {
17524 TheCall->setType(Context.DependentTy);
17525 return TheCall;
17526 }
17527 }
17528
17529 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17530 QualType ElementTy;
17531 if (!PtrTy) {
17532 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17533 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17534 << PtrExpr->getType();
17535 ArgError = true;
17536 } else {
17537 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17538
17540 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17541 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17542 << /* no fp */ 0 << PtrExpr->getType();
17543 ArgError = true;
17544 }
17545 }
17546
17547 // Apply default Lvalue conversions and convert the expression to size_t.
17548 auto ApplyArgumentConversions = [this](Expr *E) {
17550 if (Conv.isInvalid())
17551 return Conv;
17552
17553 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17554 };
17555
17556 // Apply conversion to row and column expressions.
17557 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17558 if (!RowsConv.isInvalid()) {
17559 RowsExpr = RowsConv.get();
17560 TheCall->setArg(1, RowsExpr);
17561 } else
17562 RowsExpr = nullptr;
17563
17564 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17565 if (!ColumnsConv.isInvalid()) {
17566 ColumnsExpr = ColumnsConv.get();
17567 TheCall->setArg(2, ColumnsExpr);
17568 } else
17569 ColumnsExpr = nullptr;
17570
17571 // If any part of the result matrix type is still pending, just use
17572 // Context.DependentTy, until all parts are resolved.
17573 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17574 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17575 TheCall->setType(Context.DependentTy);
17576 return CallResult;
17577 }
17578
17579 // Check row and column dimensions.
17580 std::optional<unsigned> MaybeRows;
17581 if (RowsExpr)
17582 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17583
17584 std::optional<unsigned> MaybeColumns;
17585 if (ColumnsExpr)
17586 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17587
17588 // Check stride argument.
17589 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17590 if (StrideConv.isInvalid())
17591 return ExprError();
17592 StrideExpr = StrideConv.get();
17593 TheCall->setArg(3, StrideExpr);
17594
17595 if (MaybeRows) {
17596 if (std::optional<llvm::APSInt> Value =
17597 StrideExpr->getIntegerConstantExpr(Context)) {
17598 uint64_t Stride = Value->getZExtValue();
17599 if (Stride < *MaybeRows) {
17600 Diag(StrideExpr->getBeginLoc(),
17601 diag::err_builtin_matrix_stride_too_small);
17602 ArgError = true;
17603 }
17604 }
17605 }
17606
17607 if (ArgError || !MaybeRows || !MaybeColumns)
17608 return ExprError();
17609
17610 TheCall->setType(
17611 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17612 return CallResult;
17613}
17614
17615ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17616 ExprResult CallResult) {
17617 if (!getLangOpts().MatrixTypes) {
17618 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17619 return ExprError();
17620 }
17621
17622 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17624 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17625 << /*column*/ 1 << /*store*/ 1;
17626 return ExprError();
17627 }
17628
17629 if (checkArgCount(TheCall, 3))
17630 return ExprError();
17631
17632 unsigned PtrArgIdx = 1;
17633 Expr *MatrixExpr = TheCall->getArg(0);
17634 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17635 Expr *StrideExpr = TheCall->getArg(2);
17636
17637 bool ArgError = false;
17638
17639 {
17640 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17641 if (MatrixConv.isInvalid())
17642 return MatrixConv;
17643 MatrixExpr = MatrixConv.get();
17644 TheCall->setArg(0, MatrixExpr);
17645 }
17646 if (MatrixExpr->isTypeDependent()) {
17647 TheCall->setType(Context.DependentTy);
17648 return TheCall;
17649 }
17650
17651 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17652 if (!MatrixTy) {
17653 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17654 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17655 ArgError = true;
17656 }
17657
17658 {
17660 if (PtrConv.isInvalid())
17661 return PtrConv;
17662 PtrExpr = PtrConv.get();
17663 TheCall->setArg(1, PtrExpr);
17664 if (PtrExpr->isTypeDependent()) {
17665 TheCall->setType(Context.DependentTy);
17666 return TheCall;
17667 }
17668 }
17669
17670 // Check pointer argument.
17671 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17672 if (!PtrTy) {
17673 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17674 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17675 << PtrExpr->getType();
17676 ArgError = true;
17677 } else {
17678 QualType ElementTy = PtrTy->getPointeeType();
17679 if (ElementTy.isConstQualified()) {
17680 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17681 ArgError = true;
17682 }
17683 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17684 if (MatrixTy &&
17685 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17686 Diag(PtrExpr->getBeginLoc(),
17687 diag::err_builtin_matrix_pointer_arg_mismatch)
17688 << ElementTy << MatrixTy->getElementType();
17689 ArgError = true;
17690 }
17691 }
17692
17693 // Apply default Lvalue conversions and convert the stride expression to
17694 // size_t.
17695 {
17696 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17697 if (StrideConv.isInvalid())
17698 return StrideConv;
17699
17700 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17701 if (StrideConv.isInvalid())
17702 return StrideConv;
17703 StrideExpr = StrideConv.get();
17704 TheCall->setArg(2, StrideExpr);
17705 }
17706
17707 // Check stride argument.
17708 if (MatrixTy) {
17709 if (std::optional<llvm::APSInt> Value =
17710 StrideExpr->getIntegerConstantExpr(Context)) {
17711 uint64_t Stride = Value->getZExtValue();
17712 if (Stride < MatrixTy->getNumRows()) {
17713 Diag(StrideExpr->getBeginLoc(),
17714 diag::err_builtin_matrix_stride_too_small);
17715 ArgError = true;
17716 }
17717 }
17718 }
17719
17720 if (ArgError)
17721 return ExprError();
17722
17723 return CallResult;
17724}
17725
17727 const NamedDecl *Callee) {
17728 // This warning does not make sense in code that has no runtime behavior.
17730 return;
17731
17732 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17733
17734 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17735 return;
17736
17737 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17738 // all TCBs the callee is a part of.
17739 llvm::StringSet<> CalleeTCBs;
17740 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17741 CalleeTCBs.insert(A->getTCBName());
17742 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17743 CalleeTCBs.insert(A->getTCBName());
17744
17745 // Go through the TCBs the caller is a part of and emit warnings if Caller
17746 // is in a TCB that the Callee is not.
17747 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17748 StringRef CallerTCB = A->getTCBName();
17749 if (CalleeTCBs.count(CallerTCB) == 0) {
17750 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17751 << Callee << CallerTCB;
17752 }
17753 }
17754}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
Defines enumerations for traits support.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition XCore.cpp:630
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned IsFirst
Indicates that this is the first token of the file.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
llvm::json::Object Object
llvm::json::Array Array
static std::string getFunctionName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static QualType getVectorElementType(ASTContext &Context, QualType VecTy)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call)
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
@ GE_None
No error.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * getStart() const
StringRef toString() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
APSInt & getInt()
Definition APValue.h:573
bool isVector() const
Definition APValue.h:555
APSInt & getComplexIntImag()
Definition APValue.h:611
bool isComplexInt() const
Definition APValue.h:552
bool isFloat() const
Definition APValue.h:550
bool isComplexFloat() const
Definition APValue.h:553
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
unsigned getVectorLength() const
Definition APValue.h:655
bool isLValue() const
Definition APValue.h:554
bool isInt() const
Definition APValue.h:549
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:671
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
bool isMatrix() const
Definition APValue.h:556
unsigned getMatrixNumElements() const
Definition APValue.h:668
bool isAddrLabelDiff() const
Definition APValue.h:561
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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:856
Builtin::Context & BuiltinInfo
Definition ASTContext.h:858
const LangOptions & getLangOpts() const
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:909
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:975
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:4401
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4579
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4585
SourceLocation getQuestionLoc() const
Definition Expr.h:4428
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4591
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:7351
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7355
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2769
SourceLocation getRBracketLoc() const
Definition Expr.h:2817
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2798
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
QualType getElementType() const
Definition TypeBase.h:3832
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6982
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7131
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7113
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:4086
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4219
Expr * getLHS() const
Definition Expr.h:4136
SourceLocation getOperatorLoc() const
Definition Expr.h:4128
SourceLocation getExprLoc() const
Definition Expr.h:4127
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2170
Expr * getRHS() const
Definition Expr.h:4138
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4172
Opcode getOpcode() const
Definition Expr.h:4131
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4183
BinaryOperatorKind Opcode
Definition Expr.h:4091
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
bool isInteger() const
Definition TypeBase.h:3312
bool isFloatingPoint() const
Definition TypeBase.h:3324
bool isSignedInteger() const
Definition TypeBase.h:3316
bool isUnsignedInteger() const
Definition TypeBase.h:3320
Kind getKind() const
Definition TypeBase.h:3299
llvm::SmallString< 64 > getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:99
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:384
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:4017
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1635
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:159
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:116
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5195
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5235
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1235
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool isDynamicClass() const
Definition DeclCXX.h:575
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2991
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3195
SourceLocation getBeginLoc() const
Definition Expr.h:3325
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3208
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1624
arg_iterator arg_begin()
Definition Expr.h:3248
arg_iterator arg_end()
Definition Expr.h:3251
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3174
bool isCallToStdMove() const
Definition Expr.cpp:3682
Expr * getCallee()
Definition Expr.h:3138
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3182
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3284
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3185
arg_range arguments()
Definition Expr.h:3243
SourceLocation getEndLoc() const
Definition Expr.h:3344
SourceLocation getRParenLoc() const
Definition Expr.h:3322
Decl * getCalleeDecl()
Definition Expr.h:3168
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:1629
void setCallee(Expr *F)
Definition Expr.h:3140
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3227
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:3724
path_iterator path_begin()
Definition Expr.h:3794
CastKind getCastKind() const
Definition Expr.h:3768
path_iterator path_end()
Definition Expr.h:3795
Expr * getSubExpr()
Definition Expr.h:3774
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
ConditionalOperator - The ?
Definition Expr.h:4439
Expr * getLHS() const
Definition Expr.h:4473
Expr * getRHS() const
Definition Expr.h:4474
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
QualType desugar() const
Definition TypeBase.h:3959
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4517
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:5731
Expr * getOperand() const
Definition ExprCXX.h:5378
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2120
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2417
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2175
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1294
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:498
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1387
ValueDecl * getDecl()
Definition Expr.h:1362
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1492
SourceLocation getBeginLoc() const
Definition Expr.h:1373
SourceLocation getLocation() const
Definition Expr.h:1370
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:564
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2004
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:992
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3562
Represents an enum.
Definition Decl.h:4150
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4382
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4323
This represents one expression.
Definition Expr.h:113
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:695
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:692
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:212
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:855
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:859
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3113
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3121
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:3728
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:224
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:826
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:835
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:838
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:828
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:4110
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:465
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:468
QualType getType() const
Definition Expr.h:145
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:527
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:232
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:138
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4365
Represents a member of a struct/union/class.
Definition Decl.h:3299
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3402
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4827
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3535
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3415
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1690
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Represents a function declaration or definition.
Definition Decl.h:2059
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4622
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2932
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3809
param_iterator param_end()
Definition Decl.h:2918
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3917
QualType getReturnType() const
Definition Decl.h:2980
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
param_iterator param_begin()
Definition Decl.h:2917
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3124
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4378
bool isStatic() const
Definition Decl.h:3064
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4193
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4179
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3873
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
unsigned getNumParams() const
Definition TypeBase.h:5694
QualType getParamType(unsigned i) const
Definition TypeBase.h:5696
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5820
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5705
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5815
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5701
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4921
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4917
QualType getReturnType() const
Definition TypeBase.h:4952
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:3901
Describes an C or C++ initializer list.
Definition Expr.h:5356
ArrayRef< Expr * > inits() const
Definition Expr.h:5409
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:985
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1075
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1111
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:509
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1158
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:882
Represents the results of name lookup.
Definition Lookup.h:147
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4435
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4461
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3412
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3495
Expr * getBase() const
Definition Expr.h:3489
bool isArrow() const
Definition Expr.h:3596
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1944
Represent a C++ namespace.
Definition Decl.h:593
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1715
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1729
SourceLocation getSemiLoc() const
Definition Stmt.h:1726
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
QualType getType() const
Definition DeclObjC.h:810
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:833
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:821
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:649
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:738
bool isImplicitProperty() const
Definition ExprObjC.h:735
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:83
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2230
Represents a parameter to a function.
Definition Decl.h:1820
Pointer-authentication qualifiers.
Definition TypeBase.h:153
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:233
bool isAddressDiscriminated() const
Definition TypeBase.h:266
ARM8_3Key
Hardware pointer-signing keys in ARM8.3.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6858
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5238
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8530
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3094
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8572
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8486
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
void removeLocalVolatile()
Definition TypeBase.h:8562
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
void removeLocalConst()
Definition TypeBase.h:8554
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8519
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8567
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1841
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8492
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasUnaligned() const
Definition TypeBase.h:512
Represents a struct/union/class.
Definition Decl.h:4464
bool hasFlexibleArrayMember() const
Definition Decl.h:4497
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4550
field_range fields() const
Definition Decl.h:4667
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4542
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition Scope.h:602
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
bool CheckAMDGCNBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1191
@ 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:1273
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Definition SemaBPF.cpp:105
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaMIPS.cpp:25
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaNVPTX.cpp:21
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaPPC.cpp:113
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:32
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp:31
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:289
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:574
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10485
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10490
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
SemaAMDGPU & AMDGPU()
Definition Sema.h:1474
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:13287
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1165
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:2878
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9494
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9502
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9539
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:7071
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:2107
SemaHexagon & Hexagon()
Definition Sema.h:1514
SemaSYCL & SYCL()
Definition Sema.h:1584
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:1769
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:847
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1604
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:1332
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
SemaObjC & ObjC()
Definition Sema.h:1544
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1399
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:768
ASTContext & getASTContext() const
Definition Sema.h:935
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:778
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2733
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:1236
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:2840
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
Definition Sema.h:928
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
SemaBPF & BPF()
Definition Sema.h:1489
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:1504
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:1330
static const uint64_t MaximumAlignment
Definition Sema.h:1259
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:966
SemaHLSL & HLSL()
Definition Sema.h:1509
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1529
SemaRISCV & RISCV()
Definition Sema.h:1574
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool convertArgumentToType(Expr *&Value, QualType Ty)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
EltwiseBuiltinArgTyRestriction
Definition Sema.h:2906
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7107
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1781
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:1367
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:2813
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15693
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:2464
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:648
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1472
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:1554
FormatArgumentPassingKind
Definition Sema.h:2743
@ FAPK_Elsewhere
Definition Sema.h:2747
@ FAPK_Fixed
Definition Sema.h:2744
@ FAPK_Variadic
Definition Sema.h:2745
@ FAPK_VAList
Definition Sema.h:2746
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:8332
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:14184
SourceManager & getSourceManager() const
Definition Sema.h:933
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
Definition Sema.h:2735
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:1564
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:1291
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:1594
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:1335
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:797
DiagnosticsEngine & Diags
Definition Sema.h:1334
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:1539
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:647
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:6424
SemaSPIRV & SPIRV()
Definition Sema.h:1579
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:1519
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6559
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:1599
SemaARM & ARM()
Definition Sema.h:1479
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:4691
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1505
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1823
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2021
bool isUTF8() const
Definition Expr.h:1958
bool isWide() const
Definition Expr.h:1957
bool isPascal() const
Definition Expr.h:1962
unsigned getLength() const
Definition Expr.h:1948
StringLiteralKind getKind() const
Definition Expr.h:1952
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
Return a source location that points to the specified byte of this string literal.
Definition Expr.cpp:1336
bool isUTF32() const
Definition Expr.h:1960
unsigned getByteLength() const
Definition Expr.h:1946
StringRef getString() const
Definition Expr.h:1891
bool isUTF16() const
Definition Expr.h:1959
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:2022
bool isOrdinary() const
Definition Expr.h:1956
unsigned getCharByteWidth() const
Definition Expr.h:1950
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3977
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3957
bool isUnion() const
Definition Decl.h:4067
Exposes information about the current target.
Definition TargetInfo.h:228
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:396
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6326
A container of type source information.
Definition TypeBase.h:8417
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:8428
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8703
bool isVoidType() const
Definition TypeBase.h:9068
bool isBooleanType() const
Definition TypeBase.h:9209
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9259
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:920
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2483
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
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:9239
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:845
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2645
bool isArrayType() const
Definition TypeBase.h:8782
bool isFunctionPointerType() const
Definition TypeBase.h:8750
bool isPointerType() const
Definition TypeBase.h:8683
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9116
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
bool isEnumeralType() const
Definition TypeBase.h:8814
bool isScalarType() const
Definition TypeBase.h:9178
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:2080
bool isVariableArrayType() const
Definition TypeBase.h:8794
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2829
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
bool isExtVectorType() const
Definition TypeBase.h:8826
bool isExtVectorBoolType() const
Definition TypeBase.h:8830
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2868
bool isBitIntType() const
Definition TypeBase.h:8958
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9037
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8806
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8818
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2436
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2779
bool isMemberPointerType() const
Definition TypeBase.h:8764
bool isAtomicType() const
Definition TypeBase.h:8875
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8846
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3336
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:2881
bool isUnscopedEnumerationType() const
Definition Type.cpp:2312
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9352
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9215
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8679
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2525
bool isStructureOrClassType() const
Definition Type.cpp:839
bool isVectorType() const
Definition TypeBase.h:8822
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isFloatingType() const
Definition Type.cpp:2517
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:2460
bool isAnyPointerType() const
Definition TypeBase.h:8691
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isNullPtrType() const
Definition TypeBase.h:9109
bool isRecordType() const
Definition TypeBase.h:8810
bool isObjCRetainableType() const
Definition Type.cpp:5611
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2791
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5327
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2856
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3701
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2673
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2292
Expr * getSubExpr() const
Definition Expr.h:2333
Opcode getOpcode() const
Definition Expr.h:2328
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2410
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1042
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1130
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5662
Represents a variable declaration or definition.
Definition Decl.h:933
Represents a GCC generic vector type.
Definition TypeBase.h:4273
unsigned getNumElements() const
Definition TypeBase.h:4288
QualType getElementType() const
Definition TypeBase.h:4287
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
const OptionalAmount & getFieldWidth() const
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
Represents the length modifier in a format string in scanf/printf.
ArgType getArgType(ASTContext &Ctx) const
Class representing optional flags with location and representation information.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const OptionalFlag & isPrivate() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
Common components of both fprintf and fscanf format strings.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:240
@ 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:1535
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1520
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1513
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1527
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2878
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1466
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1542
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:49
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition FixIt.h:32
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:507
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:657
@ Comparison
A comparison.
Definition Sema.h:661
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
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:153
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
PointerAuthDiscArgKind
Definition Sema.h:588
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:128
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:261
@ 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:685
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:150
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:493
CastKind
CastKind - The kind of operation required for a conversion.
unsigned getFunctionOrMethodNumParams(const Decl *D, bool IncludeThis=false)
getFunctionOrMethodNumParams - Return number of function or method parameters, optionally including t...
Definition Attr.h:66
BuiltinCountedByRefKind
Definition Sema.h:515
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:164
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
StringLiteralKind
Definition Expr.h:1787
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_Win64
Definition Specifiers.h:289
@ CC_X86_64SysV
Definition Specifiers.h:290
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6035
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6028
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1775
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:650
Extra information about a function prototype.
Definition TypeBase.h:5501
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:13469
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13495
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13485
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13433
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6965
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2755
#define log2(__x)
Definition tgmath.h:970