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"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/AttrIterator.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"
25#include "clang/AST/DeclarationName.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
30#include "clang/AST/FormatString.h"
31#include "clang/AST/IgnoreExpr.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/NonTrivialTypeVisitor.h"
34#include "clang/AST/OperationKinds.h"
35#include "clang/AST/RecordLayout.h"
36#include "clang/AST/Stmt.h"
37#include "clang/AST/TemplateBase.h"
38#include "clang/AST/TemplateName.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
42#include "clang/AST/UnresolvedSet.h"
43#include "clang/Basic/AddressSpaces.h"
44#include "clang/Basic/BuiltinTraits.h"
45#include "clang/Basic/Diagnostic.h"
46#include "clang/Basic/DiagnosticSema.h"
47#include "clang/Basic/IdentifierTable.h"
48#include "clang/Basic/LLVM.h"
49#include "clang/Basic/LangOptions.h"
50#include "clang/Basic/OpenCLOptions.h"
51#include "clang/Basic/OperatorKinds.h"
52#include "clang/Basic/PartialDiagnostic.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/Specifiers.h"
56#include "clang/Basic/SyncScope.h"
57#include "clang/Basic/TargetInfo.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Initialization.h"
60#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Ownership.h"
62#include "clang/Sema/Scope.h"
63#include "clang/Sema/ScopeInfo.h"
64#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaAMDGPU.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
68#include "clang/Sema/SemaDirectX.h"
69#include "clang/Sema/SemaHLSL.h"
70#include "clang/Sema/SemaHexagon.h"
71#include "clang/Sema/SemaLoongArch.h"
72#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaNVPTX.h"
74#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaOpenCL.h"
76#include "clang/Sema/SemaPPC.h"
77#include "clang/Sema/SemaRISCV.h"
78#include "clang/Sema/SemaSPIRV.h"
79#include "clang/Sema/SemaSYCL.h"
80#include "clang/Sema/SemaSystemZ.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
125SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, SM: getSourceManager(), Features: LangOpts,
128 Target: Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
132 Sema::FormatArgumentPassingKind B) {
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(Loc: Call->getEndLoc(), DiagID: 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(Loc: Call->getEndLoc(), DiagID: 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, MinArgCount: DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(Arg: DesiredArgCount)->getBeginLoc(),
172 Call->getArg(Arg: ArgCount - 1)->getEndLoc());
173
174 return Diag(Loc: Range.getBegin(), DiagID: diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
179static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) {
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(Ctx&: 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(c: '$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
204bool Sema::convertArgumentToType(Expr *&Value, QualType Ty) {
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
209 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
210 ExprResult Result =
211 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Value);
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(Call: TheCall, DesiredArgCount: 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(Arg: 0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(Loc: ValArg->getBeginLoc(), DiagID: 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(Arg: 1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(Val: StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(Loc: StrArg->getBeginLoc(), DiagID: 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(Loc: TheCall->getEndLoc(), DiagID: 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>(Val: Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Loc: Arg->getBeginLoc(), DiagID: 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(Call: TheCall, DesiredArgCount: 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(Arg: 0));
275
276 // Unlike '&', nothing resolves the overload set later, so resolve it now.
277 // FIXME: Resolve the overload set from the target type, like '&' does.
278 if (Arg.get()->getType() == S.Context.OverloadTy) {
279 Arg = S.CheckPlaceholderExpr(E: Arg.get());
280 if (Arg.isInvalid())
281 return true;
282 }
283
284 QualType ResultType = S.CheckAddressOfOperand(Operand&: Arg, OpLoc: TheCall->getBeginLoc());
285 if (ResultType.isNull())
286 return true;
287
288 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
289 TheCall->setType(ResultType);
290 return false;
291}
292
293/// Check that the argument to __builtin_function_start is a function.
294static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
295 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
296 return true;
297
298 if (TheCall->getArg(Arg: 0)->containsErrors())
299 return true;
300
301 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
302 if (Arg.isInvalid())
303 return true;
304
305 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
306 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
307 Val: Arg.get()->getAsBuiltinConstantDeclRef(Context: S.getASTContext()));
308
309 if (!FD) {
310 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_function_start_invalid_type)
311 << TheCall->getSourceRange();
312 return true;
313 }
314
315 return !S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
316 Loc: TheCall->getBeginLoc());
317}
318
319/// Check the number of arguments and set the result type to
320/// the argument type.
321static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
322 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
323 return true;
324
325 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
326 return false;
327}
328
329/// Check that the value argument for __builtin_is_aligned(value, alignment) and
330/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
331/// type (but not a function pointer) and that the alignment is a power-of-two.
332static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
333 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
334 return true;
335
336 clang::Expr *Source = TheCall->getArg(Arg: 0);
337 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
338
339 auto IsValidIntegerType = [](QualType Ty) {
340 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
341 };
342 QualType SrcTy = Source->getType();
343 // We should also be able to use it with arrays (but not functions!).
344 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
345 SrcTy = S.Context.getDecayedType(T: SrcTy);
346 }
347 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
348 SrcTy->isFunctionPointerType()) {
349 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::err_typecheck_expect_scalar_operand)
350 << SrcTy;
351 if (SrcTy->isFloatingType())
352 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_type);
353 else if (SrcTy->isMemberPointerType())
354 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_member_pointer);
355 else if (SrcTy->isFunctionPointerType())
356 S.Diag(Loc: Source->getExprLoc(),
357 DiagID: diag::note_alignment_invalid_function_pointer);
358 return true;
359 }
360
361 clang::Expr *AlignOp = TheCall->getArg(Arg: 1);
362 if (!IsValidIntegerType(AlignOp->getType())) {
363 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_typecheck_expect_int)
364 << AlignOp->getType();
365 return true;
366 }
367 Expr::EvalResult AlignResult;
368 unsigned MaxAlignmentBits = S.Context.getIntWidth(T: SrcTy) - 1;
369 // We can't check validity of alignment if it is value dependent.
370 if (!AlignOp->isValueDependent() &&
371 AlignOp->EvaluateAsInt(Result&: AlignResult, Ctx: S.Context,
372 AllowSideEffects: Expr::SE_AllowSideEffects)) {
373 llvm::APSInt AlignValue = AlignResult.Val.getInt();
374 llvm::APSInt MaxValue(
375 llvm::APInt::getOneBitSet(numBits: MaxAlignmentBits + 1, BitNo: MaxAlignmentBits));
376 if (AlignValue < 1) {
377 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_small) << 1;
378 return true;
379 }
380 if (llvm::APSInt::compareValues(I1: AlignValue, I2: MaxValue) > 0) {
381 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_big)
382 << toString(I: MaxValue, Radix: 10);
383 return true;
384 }
385 if (!AlignValue.isPowerOf2()) {
386 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_not_power_of_two);
387 return true;
388 }
389 if (AlignValue == 1) {
390 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::warn_alignment_builtin_useless)
391 << IsBooleanAlignBuiltin;
392 }
393 }
394
395 ExprResult SrcArg = S.PerformCopyInitialization(
396 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Type: SrcTy, Consumed: false),
397 EqualLoc: SourceLocation(), Init: Source);
398 if (SrcArg.isInvalid())
399 return true;
400 TheCall->setArg(Arg: 0, ArgExpr: SrcArg.get());
401 ExprResult AlignArg =
402 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
403 Context&: S.Context, Type: AlignOp->getType(), Consumed: false),
404 EqualLoc: SourceLocation(), Init: AlignOp);
405 if (AlignArg.isInvalid())
406 return true;
407 TheCall->setArg(Arg: 1, ArgExpr: AlignArg.get());
408 // For align_up/align_down, the return type is the same as the (potentially
409 // decayed) argument type including qualifiers. For is_aligned(), the result
410 // is always bool.
411 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
412 return false;
413}
414
415static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
416 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
417 return true;
418
419 std::pair<unsigned, const char *> Builtins[] = {
420 { Builtin::BI__builtin_add_overflow, "ckd_add" },
421 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
422 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
423 };
424
425 bool CkdOperation = llvm::any_of(Range&: Builtins, P: [&](const std::pair<unsigned,
426 const char *> &P) {
427 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
428 Lexer::getImmediateMacroName(Loc: TheCall->getExprLoc(),
429 SM: S.getSourceManager(), LangOpts: S.getLangOpts()) == P.second;
430 });
431
432 auto ValidCkdIntType = [](QualType QT) {
433 // A valid checked integer type is an integer type other than a plain char,
434 // bool, a bit-precise type, or an enumeration type.
435 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
436 return (BT->getKind() >= BuiltinType::Short &&
437 BT->getKind() <= BuiltinType::Int128) || (
438 BT->getKind() >= BuiltinType::UShort &&
439 BT->getKind() <= BuiltinType::UInt128) ||
440 BT->getKind() == BuiltinType::UChar ||
441 BT->getKind() == BuiltinType::SChar;
442 return false;
443 };
444
445 // First two arguments should be integers.
446 for (unsigned I = 0; I < 2; ++I) {
447 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: I));
448 if (Arg.isInvalid()) return true;
449 TheCall->setArg(Arg: I, ArgExpr: Arg.get());
450
451 QualType Ty = Arg.get()->getType();
452 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
453 if (!IsValid) {
454 S.Diag(Loc: Arg.get()->getBeginLoc(), DiagID: diag::err_overflow_builtin_must_be_int)
455 << CkdOperation << Ty << Arg.get()->getSourceRange();
456 return true;
457 }
458 }
459
460 // Third argument should be a pointer to a non-const integer.
461 // IRGen correctly handles volatile, restrict, and address spaces, and
462 // the other qualifiers aren't possible.
463 {
464 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 2));
465 if (Arg.isInvalid()) return true;
466 TheCall->setArg(Arg: 2, ArgExpr: Arg.get());
467
468 QualType Ty = Arg.get()->getType();
469 const auto *PtrTy = Ty->getAs<PointerType>();
470 if (!PtrTy ||
471 !PtrTy->getPointeeType()->isIntegerType() ||
472 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
473 PtrTy->getPointeeType().isConstQualified()) {
474 S.Diag(Loc: Arg.get()->getBeginLoc(),
475 DiagID: diag::err_overflow_builtin_must_be_ptr_int)
476 << CkdOperation << Ty << Arg.get()->getSourceRange();
477 return true;
478 }
479 }
480
481 // Disallow signed bit-precise integer args larger than 128 bits to mul
482 // function until we improve backend support.
483 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
484 for (unsigned I = 0; I < 3; ++I) {
485 const auto Arg = TheCall->getArg(Arg: I);
486 // Third argument will be a pointer.
487 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
488 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
489 S.getASTContext().getIntWidth(T: Ty) > 128)
490 return S.Diag(Loc: Arg->getBeginLoc(),
491 DiagID: diag::err_overflow_builtin_bit_int_max_size)
492 << 128;
493 }
494 }
495
496 return false;
497}
498
499namespace {
500struct BuiltinDumpStructGenerator {
501 Sema &S;
502 CallExpr *TheCall;
503 SourceLocation Loc = TheCall->getBeginLoc();
504 SmallVector<Expr *, 32> Actions;
505 DiagnosticErrorTrap ErrorTracker;
506 PrintingPolicy Policy;
507
508 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
509 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
510 Policy(S.Context.getPrintingPolicy()) {
511 Policy.AnonymousTagNameStyle =
512 llvm::to_underlying(E: PrintingPolicy::AnonymousTagMode::Plain);
513 }
514
515 Expr *makeOpaqueValueExpr(Expr *Inner) {
516 auto *OVE = new (S.Context)
517 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
518 Inner->getObjectKind(), Inner);
519 Actions.push_back(Elt: OVE);
520 return OVE;
521 }
522
523 Expr *getStringLiteral(llvm::StringRef Str) {
524 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Key: Str);
525 // Wrap the literal in parentheses to attach a source location.
526 return new (S.Context) ParenExpr(Loc, Loc, Lit);
527 }
528
529 bool callPrintFunction(llvm::StringRef Format,
530 llvm::ArrayRef<Expr *> Exprs = {}) {
531 SmallVector<Expr *, 8> Args;
532 assert(TheCall->getNumArgs() >= 2);
533 Args.reserve(N: (TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
534 Args.assign(in_start: TheCall->arg_begin() + 2, in_end: TheCall->arg_end());
535 Args.push_back(Elt: getStringLiteral(Str: Format));
536 llvm::append_range(C&: Args, R&: Exprs);
537
538 // Register a note to explain why we're performing the call.
539 Sema::CodeSynthesisContext Ctx;
540 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
541 Ctx.PointOfInstantiation = Loc;
542 Ctx.CallArgs = Args.data();
543 Ctx.NumCallArgs = Args.size();
544 S.pushCodeSynthesisContext(Ctx);
545
546 ExprResult RealCall =
547 S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: TheCall->getArg(Arg: 1),
548 LParenLoc: TheCall->getBeginLoc(), ArgExprs: Args, RParenLoc: TheCall->getRParenLoc());
549
550 S.popCodeSynthesisContext();
551 if (!RealCall.isInvalid())
552 Actions.push_back(Elt: RealCall.get());
553 // Bail out if we've hit any unrecoverable errors, even if we managed
554 // to build the call.
555 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
556 }
557
558 Expr *getIndentString(unsigned Depth) {
559 if (!Depth)
560 return nullptr;
561
562 llvm::SmallString<32> Indent;
563 Indent.resize(N: Depth * Policy.Indentation, NV: ' ');
564 return getStringLiteral(Str: Indent);
565 }
566
567 Expr *getTypeString(QualType T) {
568 return getStringLiteral(Str: T.getAsString(Policy));
569 }
570
571 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
572 llvm::raw_svector_ostream OS(Str);
573
574 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
575 // than trying to print a single character.
576 if (auto *BT = T->getAs<BuiltinType>()) {
577 switch (BT->getKind()) {
578 case BuiltinType::Bool:
579 OS << "%d";
580 return true;
581 case BuiltinType::Char_U:
582 case BuiltinType::UChar:
583 OS << "%hhu";
584 return true;
585 case BuiltinType::Char_S:
586 case BuiltinType::SChar:
587 OS << "%hhd";
588 return true;
589 default:
590 break;
591 }
592 }
593
594 analyze_printf::PrintfSpecifier Specifier;
595 if (Specifier.fixType(QT: T, LangOpt: S.getLangOpts(), Ctx&: S.Context, /*IsObjCLiteral=*/false)) {
596 // We were able to guess how to format this.
597 if (Specifier.getConversionSpecifier().getKind() ==
598 analyze_printf::PrintfConversionSpecifier::sArg) {
599 // Wrap double-quotes around a '%s' specifier and limit its maximum
600 // length. Ideally we'd also somehow escape special characters in the
601 // contents but printf doesn't support that.
602 // FIXME: '%s' formatting is not safe in general.
603 OS << '"';
604 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
605 Specifier.toString(os&: OS);
606 OS << '"';
607 // FIXME: It would be nice to include a '...' if the string doesn't fit
608 // in the length limit.
609 } else {
610 Specifier.toString(os&: OS);
611 }
612 return true;
613 }
614
615 if (T->isPointerType()) {
616 // Format all pointers with '%p'.
617 OS << "%p";
618 return true;
619 }
620
621 return false;
622 }
623
624 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
625 Expr *IndentLit = getIndentString(Depth);
626 Expr *TypeLit = getTypeString(T: S.Context.getCanonicalTagType(TD: RD));
627 if (IndentLit ? callPrintFunction(Format: "%s%s", Exprs: {IndentLit, TypeLit})
628 : callPrintFunction(Format: "%s", Exprs: {TypeLit}))
629 return true;
630
631 return dumpRecordValue(RD, E, RecordIndent: IndentLit, Depth);
632 }
633
634 // Dump a record value. E should be a pointer or lvalue referring to an RD.
635 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
636 unsigned Depth) {
637 // FIXME: Decide what to do if RD is a union. At least we should probably
638 // turn off printing `const char*` members with `%s`, because that is very
639 // likely to crash if that's not the active member. Whatever we decide, we
640 // should document it.
641
642 // Build an OpaqueValueExpr so we can refer to E more than once without
643 // triggering re-evaluation.
644 Expr *RecordArg = makeOpaqueValueExpr(Inner: E);
645 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
646
647 if (callPrintFunction(Format: " {\n"))
648 return true;
649
650 // Dump each base class, regardless of whether they're aggregates.
651 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
652 for (const auto &Base : CXXRD->bases()) {
653 QualType BaseType =
654 RecordArgIsPtr ? S.Context.getPointerType(T: Base.getType())
655 : S.Context.getLValueReferenceType(T: Base.getType());
656 ExprResult BasePtr = S.BuildCStyleCastExpr(
657 LParenLoc: Loc, Ty: S.Context.getTrivialTypeSourceInfo(T: BaseType, Loc), RParenLoc: Loc,
658 Op: RecordArg);
659 if (BasePtr.isInvalid() ||
660 dumpUnnamedRecord(RD: Base.getType()->getAsRecordDecl(), E: BasePtr.get(),
661 Depth: Depth + 1))
662 return true;
663 }
664 }
665
666 Expr *FieldIndentArg = getIndentString(Depth: Depth + 1);
667
668 // Dump each field.
669 for (auto *D : RD->decls()) {
670 auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D);
671 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(Val: D);
672 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
673 continue;
674
675 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
676 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
677 getTypeString(T: FD->getType()),
678 getStringLiteral(Str: FD->getName())};
679
680 if (FD->isBitField()) {
681 Format += ": %zu ";
682 QualType SizeT = S.Context.getSizeType();
683 llvm::APInt BitWidth(S.Context.getIntWidth(T: SizeT),
684 FD->getBitWidthValue());
685 Args.push_back(Elt: IntegerLiteral::Create(C: S.Context, V: BitWidth, type: SizeT, l: Loc));
686 }
687
688 Format += "=";
689
690 ExprResult Field =
691 IFD ? S.BuildAnonymousStructUnionMemberReference(
692 SS: CXXScopeSpec(), nameLoc: Loc, indirectField: IFD,
693 FoundDecl: DeclAccessPair::make(D: IFD, AS: AS_public), baseObjectExpr: RecordArg, opLoc: Loc)
694 : S.BuildFieldReferenceExpr(
695 BaseExpr: RecordArg, IsArrow: RecordArgIsPtr, OpLoc: Loc, SS: CXXScopeSpec(), Field: FD,
696 FoundDecl: DeclAccessPair::make(D: FD, AS: AS_public),
697 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
698 if (Field.isInvalid())
699 return true;
700
701 auto *InnerRD = FD->getType()->getAsRecordDecl();
702 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(Val: InnerRD);
703 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
704 // Recursively print the values of members of aggregate record type.
705 if (callPrintFunction(Format, Exprs: Args) ||
706 dumpRecordValue(RD: InnerRD, E: Field.get(), RecordIndent: FieldIndentArg, Depth: Depth + 1))
707 return true;
708 } else {
709 Format += " ";
710 if (appendFormatSpecifier(T: FD->getType(), Str&: Format)) {
711 // We know how to print this field.
712 Args.push_back(Elt: Field.get());
713 } else {
714 // We don't know how to print this field. Print out its address
715 // with a format specifier that a smart tool will be able to
716 // recognize and treat specially.
717 Format += "*%p";
718 ExprResult FieldAddr =
719 S.BuildUnaryOp(S: nullptr, OpLoc: Loc, Opc: UO_AddrOf, Input: Field.get());
720 if (FieldAddr.isInvalid())
721 return true;
722 Args.push_back(Elt: FieldAddr.get());
723 }
724 Format += "\n";
725 if (callPrintFunction(Format, Exprs: Args))
726 return true;
727 }
728 }
729
730 return RecordIndent ? callPrintFunction(Format: "%s}\n", Exprs: RecordIndent)
731 : callPrintFunction(Format: "}\n");
732 }
733
734 Expr *buildWrapper() {
735 auto *Wrapper = PseudoObjectExpr::Create(Context: S.Context, syntactic: TheCall, semantic: Actions,
736 resultIndex: PseudoObjectExpr::NoResult);
737 TheCall->setType(Wrapper->getType());
738 TheCall->setValueKind(Wrapper->getValueKind());
739 return Wrapper;
740 }
741};
742} // namespace
743
744static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
745 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 2))
746 return ExprError();
747
748 ExprResult PtrArgResult = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
749 if (PtrArgResult.isInvalid())
750 return ExprError();
751 TheCall->setArg(Arg: 0, ArgExpr: PtrArgResult.get());
752
753 // First argument should be a pointer to a struct.
754 QualType PtrArgType = PtrArgResult.get()->getType();
755 if (!PtrArgType->isPointerType() ||
756 !PtrArgType->getPointeeType()->isRecordType()) {
757 S.Diag(Loc: PtrArgResult.get()->getBeginLoc(),
758 DiagID: diag::err_expected_struct_pointer_argument)
759 << 1 << TheCall->getDirectCallee() << PtrArgType;
760 return ExprError();
761 }
762 QualType Pointee = PtrArgType->getPointeeType();
763 const RecordDecl *RD = Pointee->getAsRecordDecl();
764 // Try to instantiate the class template as appropriate; otherwise, access to
765 // its data() may lead to a crash.
766 if (S.RequireCompleteType(Loc: PtrArgResult.get()->getBeginLoc(), T: Pointee,
767 DiagID: diag::err_incomplete_type))
768 return ExprError();
769 // Second argument is a callable, but we can't fully validate it until we try
770 // calling it.
771 QualType FnArgType = TheCall->getArg(Arg: 1)->getType();
772 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
773 !FnArgType->isBlockPointerType() &&
774 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
775 auto *BT = FnArgType->getAs<BuiltinType>();
776 switch (BT ? BT->getKind() : BuiltinType::Void) {
777 case BuiltinType::Dependent:
778 case BuiltinType::Overload:
779 case BuiltinType::BoundMember:
780 case BuiltinType::PseudoObject:
781 case BuiltinType::UnknownAny:
782 case BuiltinType::BuiltinFn:
783 // This might be a callable.
784 break;
785
786 default:
787 S.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
788 DiagID: diag::err_expected_callable_argument)
789 << 2 << TheCall->getDirectCallee() << FnArgType;
790 return ExprError();
791 }
792 }
793
794 BuiltinDumpStructGenerator Generator(S, TheCall);
795
796 // Wrap parentheses around the given pointer. This is not necessary for
797 // correct code generation, but it means that when we pretty-print the call
798 // arguments in our diagnostics we will produce '(&s)->n' instead of the
799 // incorrect '&s->n'.
800 Expr *PtrArg = PtrArgResult.get();
801 PtrArg = new (S.Context)
802 ParenExpr(PtrArg->getBeginLoc(),
803 S.getLocForEndOfToken(Loc: PtrArg->getEndLoc()), PtrArg);
804 if (Generator.dumpUnnamedRecord(RD, E: PtrArg, Depth: 0))
805 return ExprError();
806
807 return Generator.buildWrapper();
808}
809
810static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
811 if (S.checkArgCount(Call: BuiltinCall, DesiredArgCount: 2))
812 return true;
813
814 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
815 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
816 Expr *Call = BuiltinCall->getArg(Arg: 0);
817 Expr *Chain = BuiltinCall->getArg(Arg: 1);
818
819 if (Call->getStmtClass() != Stmt::CallExprClass) {
820 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_not_call)
821 << Call->getSourceRange();
822 return true;
823 }
824
825 auto CE = cast<CallExpr>(Val: Call);
826 if (CE->getCallee()->getType()->isBlockPointerType()) {
827 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_block_call)
828 << Call->getSourceRange();
829 return true;
830 }
831
832 const Decl *TargetDecl = CE->getCalleeDecl();
833 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
834 if (FD->getBuiltinID()) {
835 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_builtin_call)
836 << Call->getSourceRange();
837 return true;
838 }
839
840 if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens())) {
841 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_pdtor_call)
842 << Call->getSourceRange();
843 return true;
844 }
845
846 ExprResult ChainResult = S.UsualUnaryConversions(E: Chain);
847 if (ChainResult.isInvalid())
848 return true;
849 if (!ChainResult.get()->getType()->isPointerType()) {
850 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_second_argument_to_cwsc_not_pointer)
851 << Chain->getSourceRange();
852 return true;
853 }
854
855 QualType ReturnTy = CE->getCallReturnType(Ctx: S.Context);
856 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
857 QualType BuiltinTy = S.Context.getFunctionType(
858 ResultTy: ReturnTy, Args: ArgTys, EPI: FunctionProtoType::ExtProtoInfo());
859 QualType BuiltinPtrTy = S.Context.getPointerType(T: BuiltinTy);
860
861 Builtin =
862 S.ImpCastExprToType(E: Builtin, Type: BuiltinPtrTy, CK: CK_BuiltinFnToFnPtr).get();
863
864 BuiltinCall->setType(CE->getType());
865 BuiltinCall->setValueKind(CE->getValueKind());
866 BuiltinCall->setObjectKind(CE->getObjectKind());
867 BuiltinCall->setCallee(Builtin);
868 BuiltinCall->setArg(Arg: 1, ArgExpr: ChainResult.get());
869
870 return false;
871}
872
873namespace {
874
875class ScanfDiagnosticFormatHandler
876 : public analyze_format_string::FormatStringHandler {
877 // Accepts the argument index (relative to the first destination index) of the
878 // argument whose size we want.
879 using ComputeSizeFunction =
880 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
881
882 // Accepts the argument index (relative to the first destination index), the
883 // destination size, and the source size).
884 using DiagnoseFunction =
885 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
886
887 ComputeSizeFunction ComputeSizeArgument;
888 DiagnoseFunction Diagnose;
889
890public:
891 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
892 DiagnoseFunction Diagnose)
893 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
894
895 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
896 const char *StartSpecifier,
897 unsigned specifierLen) override {
898 if (!FS.consumesDataArgument())
899 return true;
900
901 unsigned NulByte = 0;
902 switch ((FS.getConversionSpecifier().getKind())) {
903 default:
904 return true;
905 case analyze_format_string::ConversionSpecifier::sArg:
906 case analyze_format_string::ConversionSpecifier::ScanListArg:
907 NulByte = 1;
908 break;
909 case analyze_format_string::ConversionSpecifier::cArg:
910 break;
911 }
912
913 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
914 if (FW.getHowSpecified() !=
915 analyze_format_string::OptionalAmount::HowSpecified::Constant)
916 return true;
917
918 unsigned SourceSize = FW.getConstantAmount() + NulByte;
919
920 std::optional<llvm::APSInt> DestSizeAPS =
921 ComputeSizeArgument(FS.getArgIndex());
922 if (!DestSizeAPS)
923 return true;
924
925 unsigned DestSize = DestSizeAPS->getZExtValue();
926
927 if (DestSize < SourceSize)
928 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
929
930 return true;
931 }
932};
933
934class EstimateSizeFormatHandler
935 : public analyze_format_string::FormatStringHandler {
936 size_t Size;
937 /// Whether the format string contains Linux kernel's format specifier
938 /// extension.
939 bool IsKernelCompatible = true;
940
941public:
942 EstimateSizeFormatHandler(StringRef Format)
943 : Size(std::min(a: Format.find(C: 0), b: Format.size()) +
944 1 /* null byte always written by sprintf */) {}
945
946 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
947 const char *, unsigned SpecifierLen,
948 const TargetInfo &) override {
949
950 const size_t FieldWidth = computeFieldWidth(FS);
951 const size_t Precision = computePrecision(FS);
952
953 // The actual format.
954 switch (FS.getConversionSpecifier().getKind()) {
955 // Just a char.
956 case analyze_format_string::ConversionSpecifier::cArg:
957 case analyze_format_string::ConversionSpecifier::CArg:
958 Size += std::max(a: FieldWidth, b: (size_t)1);
959 break;
960 // Just an integer.
961 case analyze_format_string::ConversionSpecifier::dArg:
962 case analyze_format_string::ConversionSpecifier::DArg:
963 case analyze_format_string::ConversionSpecifier::iArg:
964 case analyze_format_string::ConversionSpecifier::oArg:
965 case analyze_format_string::ConversionSpecifier::OArg:
966 case analyze_format_string::ConversionSpecifier::uArg:
967 case analyze_format_string::ConversionSpecifier::UArg:
968 case analyze_format_string::ConversionSpecifier::xArg:
969 case analyze_format_string::ConversionSpecifier::XArg:
970 Size += std::max(a: FieldWidth, b: Precision);
971 break;
972
973 // %g style conversion switches between %f or %e style dynamically.
974 // %g removes trailing zeros, and does not print decimal point if there are
975 // no digits that follow it. Thus %g can print a single digit.
976 // FIXME: If it is alternative form:
977 // For g and G conversions, trailing zeros are not removed from the result.
978 case analyze_format_string::ConversionSpecifier::gArg:
979 case analyze_format_string::ConversionSpecifier::GArg:
980 Size += 1;
981 break;
982
983 // Floating point number in the form '[+]ddd.ddd'.
984 case analyze_format_string::ConversionSpecifier::fArg:
985 case analyze_format_string::ConversionSpecifier::FArg:
986 Size += std::max(a: FieldWidth, b: 1 /* integer part */ +
987 (Precision ? 1 + Precision
988 : 0) /* period + decimal */);
989 break;
990
991 // Floating point number in the form '[-]d.ddde[+-]dd'.
992 case analyze_format_string::ConversionSpecifier::eArg:
993 case analyze_format_string::ConversionSpecifier::EArg:
994 Size +=
995 std::max(a: FieldWidth,
996 b: 1 /* integer part */ +
997 (Precision ? 1 + Precision : 0) /* period + decimal */ +
998 1 /* e or E letter */ + 2 /* exponent */);
999 break;
1000
1001 // Floating point number in the form '[-]0xh.hhhhp±dd'.
1002 case analyze_format_string::ConversionSpecifier::aArg:
1003 case analyze_format_string::ConversionSpecifier::AArg:
1004 Size +=
1005 std::max(a: FieldWidth,
1006 b: 2 /* 0x */ + 1 /* integer part */ +
1007 (Precision ? 1 + Precision : 0) /* period + decimal */ +
1008 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1009 break;
1010
1011 // Just a string.
1012 case analyze_format_string::ConversionSpecifier::sArg:
1013 case analyze_format_string::ConversionSpecifier::SArg:
1014 Size += FieldWidth;
1015 break;
1016
1017 // Just a pointer in the form '0xddd'.
1018 case analyze_format_string::ConversionSpecifier::pArg:
1019 // Linux kernel has its own extension for `%p` specifier.
1020 // Kernel Document:
1021 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1022 IsKernelCompatible = false;
1023 Size += std::max(a: FieldWidth, b: 2 /* leading 0x */ + Precision);
1024 break;
1025
1026 // A plain percent.
1027 case analyze_format_string::ConversionSpecifier::PercentArg:
1028 Size += 1;
1029 break;
1030
1031 default:
1032 break;
1033 }
1034
1035 // If field width is specified, the sign/space is already accounted for
1036 // within the field width, so no additional size is needed.
1037 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1038 Size += 1;
1039
1040 if (FS.hasAlternativeForm()) {
1041 switch (FS.getConversionSpecifier().getKind()) {
1042 // For o conversion, it increases the precision, if and only if necessary,
1043 // to force the first digit of the result to be a zero
1044 // (if the value and precision are both 0, a single 0 is printed)
1045 case analyze_format_string::ConversionSpecifier::oArg:
1046 // For b conversion, a nonzero result has 0b prefixed to it.
1047 case analyze_format_string::ConversionSpecifier::bArg:
1048 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1049 // it.
1050 case analyze_format_string::ConversionSpecifier::xArg:
1051 case analyze_format_string::ConversionSpecifier::XArg:
1052 // Note: even when the prefix is added, if
1053 // (prefix_width <= FieldWidth - formatted_length) holds,
1054 // the prefix does not increase the format
1055 // size. e.g.(("%#3x", 0xf) is "0xf")
1056
1057 // If the result is zero, o, b, x, X adds nothing.
1058 break;
1059 // For a, A, e, E, f, F, g, and G conversions,
1060 // the result of converting a floating-point number always contains a
1061 // decimal-point
1062 case analyze_format_string::ConversionSpecifier::aArg:
1063 case analyze_format_string::ConversionSpecifier::AArg:
1064 case analyze_format_string::ConversionSpecifier::eArg:
1065 case analyze_format_string::ConversionSpecifier::EArg:
1066 case analyze_format_string::ConversionSpecifier::fArg:
1067 case analyze_format_string::ConversionSpecifier::FArg:
1068 case analyze_format_string::ConversionSpecifier::gArg:
1069 case analyze_format_string::ConversionSpecifier::GArg:
1070 Size += (Precision ? 0 : 1);
1071 break;
1072 // For other conversions, the behavior is undefined.
1073 default:
1074 break;
1075 }
1076 }
1077 assert(SpecifierLen <= Size && "no underflow");
1078 Size -= SpecifierLen;
1079 return true;
1080 }
1081
1082 size_t getSizeLowerBound() const { return Size; }
1083 bool isKernelCompatible() const { return IsKernelCompatible; }
1084
1085private:
1086 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1087 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1088 size_t FieldWidth = 0;
1089 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
1090 FieldWidth = FW.getConstantAmount();
1091 return FieldWidth;
1092 }
1093
1094 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1095 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1096 size_t Precision = 0;
1097
1098 // See man 3 printf for default precision value based on the specifier.
1099 switch (FW.getHowSpecified()) {
1100 case analyze_format_string::OptionalAmount::NotSpecified:
1101 switch (FS.getConversionSpecifier().getKind()) {
1102 default:
1103 break;
1104 case analyze_format_string::ConversionSpecifier::dArg: // %d
1105 case analyze_format_string::ConversionSpecifier::DArg: // %D
1106 case analyze_format_string::ConversionSpecifier::iArg: // %i
1107 Precision = 1;
1108 break;
1109 case analyze_format_string::ConversionSpecifier::oArg: // %d
1110 case analyze_format_string::ConversionSpecifier::OArg: // %D
1111 case analyze_format_string::ConversionSpecifier::uArg: // %d
1112 case analyze_format_string::ConversionSpecifier::UArg: // %D
1113 case analyze_format_string::ConversionSpecifier::xArg: // %d
1114 case analyze_format_string::ConversionSpecifier::XArg: // %D
1115 Precision = 1;
1116 break;
1117 case analyze_format_string::ConversionSpecifier::fArg: // %f
1118 case analyze_format_string::ConversionSpecifier::FArg: // %F
1119 case analyze_format_string::ConversionSpecifier::eArg: // %e
1120 case analyze_format_string::ConversionSpecifier::EArg: // %E
1121 case analyze_format_string::ConversionSpecifier::gArg: // %g
1122 case analyze_format_string::ConversionSpecifier::GArg: // %G
1123 Precision = 6;
1124 break;
1125 case analyze_format_string::ConversionSpecifier::pArg: // %d
1126 Precision = 1;
1127 break;
1128 }
1129 break;
1130 case analyze_format_string::OptionalAmount::Constant:
1131 Precision = FW.getConstantAmount();
1132 break;
1133 default:
1134 break;
1135 }
1136 return Precision;
1137 }
1138};
1139
1140} // namespace
1141
1142static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1143 StringRef &FormatStrRef, size_t &StrLen,
1144 ASTContext &Context) {
1145 if (const auto *Format = dyn_cast<StringLiteral>(Val: FormatExpr);
1146 Format && (Format->isOrdinary() || Format->isUTF8())) {
1147 FormatStrRef = Format->getString();
1148 const ConstantArrayType *T =
1149 Context.getAsConstantArrayType(T: Format->getType());
1150 assert(T && "String literal not of constant array type!");
1151 size_t TypeSize = T->getZExtSize();
1152 // In case there's a null byte somewhere.
1153 StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: FormatStrRef.find(C: 0));
1154 return true;
1155 }
1156 return false;
1157}
1158
1159namespace {
1160/// Helper class for buffer overflow/overread checking in fortified functions.
1161class FortifiedBufferChecker {
1162public:
1163 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1164 : S(S), TheCall(TheCall), FD(FD),
1165 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1166 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1167 SizeTypeWidth = TI.getTypeWidth(T: TI.getSizeType());
1168 }
1169
1170 std::optional<unsigned> TranslateIndex(unsigned Index) {
1171 // If we refer to a diagnose_as_builtin attribute, we need to change the
1172 // argument index to refer to the arguments of the called function. Unless
1173 // the index is out of bounds, which presumably means it's a variadic
1174 // function.
1175 unsigned NewIndex = Index;
1176 if (DABAttr) {
1177 unsigned DABIndices = DABAttr->argIndices_size();
1178 NewIndex = Index < DABIndices ? DABAttr->argIndices_begin()[Index]
1179 : Index - DABIndices + FD->getNumParams();
1180 }
1181 if (NewIndex >= TheCall->getNumArgs())
1182 return std::nullopt;
1183 return NewIndex;
1184 }
1185
1186 /// Evaluate the argument at Index as an integer constant while preserving
1187 /// its signedness, or return std::nullopt if it cannot be evaluated.
1188 std::optional<llvm::APSInt> EvaluateIntegerArgument(unsigned Index) {
1189 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1190 if (!IndexOptional)
1191 return std::nullopt;
1192 Expr::EvalResult Result;
1193 Expr *Arg = TheCall->getArg(Arg: *IndexOptional);
1194 if (!Arg->EvaluateAsInt(Result, Ctx: S.getASTContext()))
1195 return std::nullopt;
1196
1197 return Result.Val.getInt();
1198 }
1199
1200 std::optional<llvm::APSInt>
1201 ComputeExplicitObjectSizeArgument(unsigned Index) {
1202 std::optional<llvm::APSInt> Integer = EvaluateIntegerArgument(Index);
1203 if (!Integer)
1204 return std::nullopt;
1205 *Integer = Integer->extOrTrunc(width: SizeTypeWidth);
1206 Integer->setIsUnsigned(true);
1207 return Integer;
1208 }
1209
1210 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1211 // If the parameter has a pass_object_size attribute, then we should use its
1212 // (potentially) more strict checking mode. Otherwise, conservatively assume
1213 // type 0.
1214 int BOSType = 0;
1215 // This check can fail for variadic functions.
1216 if (Index < FD->getNumParams()) {
1217 if (const auto *POS =
1218 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1219 BOSType = POS->getType();
1220 }
1221
1222 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1223 if (!IndexOptional)
1224 return std::nullopt;
1225
1226 const Expr *ObjArg = TheCall->getArg(Arg: *IndexOptional);
1227 if (std::optional<uint64_t> ObjSize =
1228 ObjArg->tryEvaluateObjectSize(Ctx: S.getASTContext(), Type: BOSType)) {
1229 // Get the object size in the target's size_t width.
1230 return llvm::APSInt::getUnsigned(X: *ObjSize).extOrTrunc(width: SizeTypeWidth);
1231 }
1232 return std::nullopt;
1233 }
1234
1235 std::optional<llvm::APSInt>
1236 ComputeExplicitObjectSizeArgumentProduct(unsigned LIndex, unsigned RIndex) {
1237 auto L = ComputeExplicitObjectSizeArgument(Index: LIndex);
1238 auto R = ComputeExplicitObjectSizeArgument(Index: RIndex);
1239 if (!L || !R)
1240 return std::nullopt;
1241
1242 unsigned W =
1243 2 * std::max(l: {L->getBitWidth(), R->getBitWidth(), SizeTypeWidth});
1244
1245 llvm::APSInt LE = L->extOrTrunc(width: W);
1246 llvm::APSInt RE = R->extOrTrunc(width: W);
1247
1248 return LE * RE;
1249 }
1250
1251 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1252 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1253 if (!IndexOptional)
1254 return std::nullopt;
1255 unsigned NewIndex = *IndexOptional;
1256
1257 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1258
1259 if (std::optional<uint64_t> Result =
1260 ObjArg->tryEvaluateStrLen(Ctx: S.getASTContext())) {
1261 // Add 1 for null byte.
1262 return llvm::APSInt::getUnsigned(X: *Result + 1).extOrTrunc(width: SizeTypeWidth);
1263 }
1264 return std::nullopt;
1265 }
1266
1267 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1268
1269 unsigned getBuiltinID() const {
1270 const FunctionDecl *UseDecl = FD;
1271 if (DABAttr) {
1272 UseDecl = DABAttr->getFunction();
1273 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1274 }
1275 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1276 }
1277
1278 /// Return function name after stripping __builtin_ and _chk affixes.
1279 std::string getFunctionName() const {
1280 unsigned ID = getBuiltinID();
1281 if (!ID) {
1282 // Use callee name directly if not a builtin.
1283 const FunctionDecl *Callee = TheCall->getDirectCallee();
1284 assert(Callee && "expected callee");
1285 return Callee->getName().str();
1286 }
1287 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1288 StringRef Ref = Name;
1289 // Strip __builtin___*_chk or __builtin_ prefix.
1290 if (!(Ref.consume_front(Prefix: "__builtin___") && Ref.consume_back(Suffix: "_chk")))
1291 Ref.consume_front(Prefix: "__builtin_");
1292 assert(!Ref.empty() && "expected non-empty function name");
1293 return Ref.str();
1294 }
1295
1296 /// Check for source buffer overread in memory functions.
1297 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1298 if (S.isConstantEvaluatedContext())
1299 return;
1300
1301 const Expr *SrcArg = TheCall->getArg(Arg: SrcArgIdx);
1302 const Expr *SizeArg = TheCall->getArg(Arg: SizeArgIdx);
1303 if (SrcArg->isInstantiationDependent() ||
1304 SizeArg->isInstantiationDependent())
1305 return;
1306
1307 std::optional<llvm::APSInt> CopyLen =
1308 ComputeExplicitObjectSizeArgument(Index: SizeArgIdx);
1309 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(Index: SrcArgIdx);
1310
1311 if (!CopyLen || !SrcBufSize)
1312 return;
1313
1314 // Warn only if copy length exceeds source buffer size.
1315 if (llvm::APSInt::compareValues(I1: *CopyLen, I2: *SrcBufSize) <= 0)
1316 return;
1317
1318 S.DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1319 PD: S.PDiag(DiagID: diag::warn_stringop_overread)
1320 << getFunctionName() << CopyLen->getZExtValue()
1321 << SrcBufSize->getZExtValue());
1322 }
1323
1324private:
1325 Sema &S;
1326 CallExpr *TheCall;
1327 FunctionDecl *FD;
1328 const DiagnoseAsBuiltinAttr *DABAttr;
1329 unsigned SizeTypeWidth;
1330};
1331} // anonymous namespace
1332
1333void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1334 CallExpr *TheCall) {
1335 if (TheCall->isInstantiationDependent() || isConstantEvaluatedContext())
1336 return;
1337
1338 FortifiedBufferChecker Checker(*this, FD, TheCall);
1339
1340 unsigned BuiltinID = Checker.getBuiltinID();
1341 if (!BuiltinID)
1342 return;
1343
1344 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1345
1346 std::optional<llvm::APSInt> AccessSize;
1347 std::optional<llvm::APSInt> BufferSize;
1348 unsigned DiagID = 0;
1349
1350 switch (BuiltinID) {
1351 default:
1352 return;
1353 case Builtin::BI__builtin_strcat:
1354 case Builtin::BIstrcat:
1355 case Builtin::BI__builtin_stpcpy:
1356 case Builtin::BIstpcpy:
1357 case Builtin::BI__builtin_strcpy:
1358 case Builtin::BIstrcpy: {
1359 DiagID = diag::warn_fortify_strlen_overflow;
1360 AccessSize = Checker.ComputeStrLenArgument(Index: 1);
1361 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1362 break;
1363 }
1364
1365 case Builtin::BI__builtin___strcat_chk:
1366 case Builtin::BI__builtin___stpcpy_chk:
1367 case Builtin::BI__builtin___strcpy_chk: {
1368 DiagID = diag::warn_fortify_strlen_overflow;
1369 AccessSize = Checker.ComputeStrLenArgument(Index: 1);
1370 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1371 break;
1372 }
1373
1374 case Builtin::BIscanf:
1375 case Builtin::BIfscanf:
1376 case Builtin::BIsscanf: {
1377 unsigned FormatIndex = 1;
1378 unsigned DataIndex = 2;
1379 if (BuiltinID == Builtin::BIscanf) {
1380 FormatIndex = 0;
1381 DataIndex = 1;
1382 }
1383
1384 const auto *FormatExpr =
1385 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1386
1387 StringRef FormatStrRef;
1388 size_t StrLen;
1389 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1390 return;
1391
1392 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1393 unsigned SourceSize) {
1394 DiagID = diag::warn_fortify_scanf_overflow;
1395 unsigned Index = ArgIndex + DataIndex;
1396 std::string FunctionName = Checker.getFunctionName();
1397 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1398 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1399 << DestSize << SourceSize);
1400 };
1401
1402 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1403 return Checker.ComputeSizeArgument(Index: Index + DataIndex);
1404 };
1405 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1406 const char *FormatBytes = FormatStrRef.data();
1407 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1408 end: FormatBytes + StrLen, LO: getLangOpts(),
1409 Target: Context.getTargetInfo());
1410
1411 // Unlike the other cases, in this one we have already issued the diagnostic
1412 // here, so no need to continue (because unlike the other cases, here the
1413 // diagnostic refers to the argument number).
1414 return;
1415 }
1416
1417 case Builtin::BIsprintf:
1418 case Builtin::BI__builtin_sprintf:
1419 case Builtin::BI__builtin___sprintf_chk:
1420 case Builtin::BIvsprintf:
1421 case Builtin::BI__builtin_vsprintf:
1422 case Builtin::BI__builtin___vsprintf_chk: {
1423 bool IsChk = BuiltinID == Builtin::BI__builtin___sprintf_chk ||
1424 BuiltinID == Builtin::BI__builtin___vsprintf_chk;
1425 std::optional<unsigned> FormatIndex = Checker.TranslateIndex(Index: IsChk ? 3 : 1);
1426 if (!FormatIndex)
1427 return;
1428 const auto *FormatExpr =
1429 TheCall->getArg(Arg: *FormatIndex)->IgnoreParenImpCasts();
1430
1431 StringRef FormatStrRef;
1432 size_t StrLen;
1433 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1434 EstimateSizeFormatHandler H(FormatStrRef);
1435 const char *FormatBytes = FormatStrRef.data();
1436 if (!analyze_format_string::ParsePrintfString(
1437 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1438 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1439 DiagID = H.isKernelCompatible()
1440 ? diag::warn_format_overflow
1441 : diag::warn_format_overflow_non_kprintf;
1442 AccessSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1443 .extOrTrunc(width: SizeTypeWidth);
1444 if (IsChk) {
1445 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1446 } else {
1447 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1448 }
1449 break;
1450 }
1451 }
1452 return;
1453 }
1454 case Builtin::BI__builtin___memcpy_chk:
1455 case Builtin::BI__builtin___memmove_chk:
1456 case Builtin::BI__builtin___memset_chk:
1457 case Builtin::BI__builtin___strlcat_chk:
1458 case Builtin::BI__builtin___strlcpy_chk:
1459 case Builtin::BI__builtin___strncat_chk:
1460 case Builtin::BI__builtin___strncpy_chk:
1461 case Builtin::BI__builtin___stpncpy_chk:
1462 case Builtin::BI__builtin___memccpy_chk:
1463 case Builtin::BI__builtin___mempcpy_chk: {
1464 DiagID = diag::warn_builtin_chk_overflow;
1465 AccessSize =
1466 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 2);
1467 BufferSize =
1468 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1469
1470 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1471 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1472 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1473 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1474 }
1475 break;
1476 }
1477
1478 case Builtin::BI__builtin___snprintf_chk:
1479 case Builtin::BI__builtin___vsnprintf_chk: {
1480 DiagID = diag::warn_builtin_chk_overflow;
1481 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1482 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 3);
1483 break;
1484 }
1485
1486 case Builtin::BImemccpy: {
1487 // Whether memccpy overflows depends on whether the stop character appears
1488 // in the source buffer before reaching n, not just the buffer size.
1489 DiagID = diag::warn_fortify_source_size_mismatch;
1490 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 3);
1491 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1492 break;
1493 }
1494
1495 case Builtin::BIstrncat:
1496 case Builtin::BI__builtin_strncat:
1497 case Builtin::BIstrncpy:
1498 case Builtin::BI__builtin_strncpy:
1499 case Builtin::BIstpncpy:
1500 case Builtin::BI__builtin_stpncpy:
1501 case Builtin::BIstrlcat:
1502 case Builtin::BI__builtin_strlcat:
1503 case Builtin::BIstrlcpy:
1504 case Builtin::BI__builtin_strlcpy: {
1505 // Whether these functions overflow depends on the runtime strlen of the
1506 // string, not just the buffer size, so emitting the "always overflow"
1507 // diagnostic isn't quite right. We should still diagnose passing a buffer
1508 // size larger than the destination buffer though; this is a runtime abort
1509 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1510 DiagID = diag::warn_fortify_source_size_mismatch;
1511 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1512 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1513 break;
1514 }
1515
1516 case Builtin::BIrecv:
1517 case Builtin::BIrecvfrom: {
1518 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1519 if (TheCall->getNumArgs() != ExpectedArgs ||
1520 !TheCall->getArg(Arg: 1)->getType()->isPointerType() ||
1521 !TheCall->getArg(Arg: 2)->getType()->isIntegerType())
1522 return;
1523 DiagID = diag::warn_fortify_source_size_mismatch;
1524 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1525 BufferSize = Checker.ComputeSizeArgument(Index: 1);
1526 break;
1527 }
1528
1529 case Builtin::BIpoll:
1530 case Builtin::BIppoll:
1531 case Builtin::BIppoll64: {
1532 unsigned ExpectedArgs = BuiltinID == Builtin::BIpoll ? 3 : 4;
1533 if (TheCall->getNumArgs() != ExpectedArgs ||
1534 !TheCall->getArg(Arg: 1)->getType()->isIntegerType())
1535 return;
1536 QualType PointeeTy = TheCall->getArg(Arg: 0)->getType()->getPointeeType();
1537 if (PointeeTy.isNull())
1538 return;
1539 const RecordDecl *RD = PointeeTy->getAsRecordDecl();
1540 if (!RD || !RD->getIdentifier() || RD->getName() != "pollfd")
1541 return;
1542 if (BuiltinID == Builtin::BIpoll) {
1543 if (!TheCall->getArg(Arg: 2)->getType()->isIntegerType())
1544 return;
1545 } else {
1546 QualType TmoPointeeTy = TheCall->getArg(Arg: 2)->getType()->getPointeeType();
1547 if (TmoPointeeTy.isNull())
1548 return;
1549 const RecordDecl *TmoRD = TmoPointeeTy->getAsRecordDecl();
1550 if (!TmoRD || !TmoRD->getIdentifier() || TmoRD->getName() != "timespec" ||
1551 !TheCall->getArg(Arg: 3)->getType()->isPointerType())
1552 return;
1553 }
1554 std::optional<CharUnits> ElemSize =
1555 Context.getTypeSizeInCharsIfKnown(Ty: PointeeTy);
1556 if (!ElemSize)
1557 return;
1558 std::optional<llvm::APSInt> Count =
1559 Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1560 if (!Count)
1561 return;
1562 DiagID = diag::warn_fortify_source_size_mismatch;
1563 unsigned WideWidth = SizeTypeWidth * 2;
1564 AccessSize = Count->extOrTrunc(width: WideWidth) *
1565 llvm::APSInt(llvm::APInt(WideWidth, ElemSize->getQuantity()),
1566 /*isUnsigned=*/true);
1567 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1568 break;
1569 }
1570
1571 case Builtin::BIbzero:
1572 case Builtin::BI__builtin_bzero:
1573 case Builtin::BIexplicit_bzero: {
1574 DiagID = diag::warn_fortify_source_overflow;
1575 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1576 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1577 break;
1578 }
1579
1580 case Builtin::BImemcpy:
1581 case Builtin::BI__builtin_memcpy:
1582 case Builtin::BImemmove:
1583 case Builtin::BI__builtin_memmove:
1584 case Builtin::BImemset:
1585 case Builtin::BI__builtin_memset:
1586 case Builtin::BImemset_explicit:
1587 case Builtin::BImempcpy:
1588 case Builtin::BI__builtin_mempcpy: {
1589 DiagID = diag::warn_fortify_source_overflow;
1590 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1591 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1592
1593 // Buffer overread doesn't make sense for memset.
1594 if (BuiltinID != Builtin::BImemset &&
1595 BuiltinID != Builtin::BI__builtin_memset &&
1596 BuiltinID != Builtin::BImemset_explicit) {
1597 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1598 }
1599 break;
1600 }
1601 case Builtin::BIbcopy:
1602 case Builtin::BI__builtin_bcopy: {
1603 DiagID = diag::warn_fortify_source_overflow;
1604 AccessSize =
1605 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1606 BufferSize = Checker.ComputeSizeArgument(Index: 1);
1607 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1608 break;
1609 }
1610 case Builtin::BIfread: {
1611 DiagID = diag::warn_fortify_source_overflow;
1612 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(LIndex: 1, RIndex: 2);
1613 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1614 break;
1615 }
1616 case Builtin::BIfwrite: {
1617 DiagID = diag::warn_fortify_source_overread;
1618 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(LIndex: 1, RIndex: 2);
1619 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1620 break;
1621 }
1622 case Builtin::BIfgets: {
1623 AccessSize = Checker.EvaluateIntegerArgument(Index: 1);
1624
1625 if (AccessSize && AccessSize->isNegative()) {
1626 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1627 PD: PDiag(DiagID: diag::warn_fortify_source_negative_size)
1628 << Checker.getFunctionName());
1629 return;
1630 }
1631
1632 DiagID = diag::warn_fortify_source_size_mismatch;
1633 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1634 break;
1635 }
1636 // memchr(buf, val, size)
1637 case Builtin::BImemchr:
1638 case Builtin::BI__builtin_memchr: {
1639 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1640 return;
1641 }
1642
1643 // memcmp/bcmp(buf0, buf1, size)
1644 // Two checks since each buffer is read
1645 case Builtin::BImemcmp:
1646 case Builtin::BI__builtin_memcmp:
1647 case Builtin::BIbcmp:
1648 case Builtin::BI__builtin_bcmp: {
1649 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1650 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1651 return;
1652 }
1653 case Builtin::BIsnprintf:
1654 case Builtin::BI__builtin_snprintf:
1655 case Builtin::BIvsnprintf:
1656 case Builtin::BI__builtin_vsnprintf: {
1657 DiagID = diag::warn_fortify_source_size_mismatch;
1658 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1659 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1660 StringRef FormatStrRef;
1661 size_t StrLen;
1662 if (AccessSize &&
1663 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1664 EstimateSizeFormatHandler H(FormatStrRef);
1665 const char *FormatBytes = FormatStrRef.data();
1666 if (!analyze_format_string::ParsePrintfString(
1667 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1668 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1669 llvm::APSInt FormatSize =
1670 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1671 .extOrTrunc(width: SizeTypeWidth);
1672 if (FormatSize > *AccessSize && *AccessSize != 0) {
1673 unsigned TruncationDiagID =
1674 H.isKernelCompatible() ? diag::warn_format_truncation
1675 : diag::warn_format_truncation_non_kprintf;
1676 SmallString<16> SpecifiedSizeStr;
1677 SmallString<16> FormatSizeStr;
1678 AccessSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1679 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1680 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1681 PD: PDiag(DiagID: TruncationDiagID)
1682 << Checker.getFunctionName()
1683 << SpecifiedSizeStr << FormatSizeStr);
1684 }
1685 }
1686 }
1687 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1688 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1689 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1690 IdentifierInfo *FnInfo = FD->getIdentifier();
1691 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1692 }
1693 }
1694
1695 if (!AccessSize || !BufferSize ||
1696 llvm::APSInt::compareValues(I1: *AccessSize, I2: *BufferSize) <= 0)
1697 return;
1698
1699 std::string FunctionName = Checker.getFunctionName();
1700
1701 SmallString<16> BufferSizeStr;
1702 SmallString<16> AccessSizeStr;
1703 BufferSize->toString(Str&: BufferSizeStr, /*Radix=*/10);
1704 AccessSize->toString(Str&: AccessSizeStr, /*Radix=*/10);
1705 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1706 PD: PDiag(DiagID)
1707 << FunctionName << BufferSizeStr << AccessSizeStr);
1708}
1709
1710void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1711 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1712 return;
1713
1714 // Recognize the libc function by builtin identity rather than by name and
1715 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1716 // builtin id is attached to any file-scope, C-linkage declaration of umask
1717 // regardless of the libc's mode_t spelling -- including a hand-written
1718 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1719 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1720 if (FD->getBuiltinID() != Builtin::BIumask)
1721 return;
1722
1723 // umask(mode_t): warn when the constant-evaluated argument has bits set
1724 // outside the file-permission mask (0777). Those bits are ignored.
1725 if (TheCall->getNumArgs() != 1)
1726 return;
1727 Expr *Arg = TheCall->getArg(Arg: 0);
1728 if (!Arg->getType()->isIntegerType())
1729 return;
1730 Expr::EvalResult R;
1731 if (!Arg->EvaluateAsInt(Result&: R, Ctx: getASTContext()))
1732 return;
1733 // Operate on the raw two's-complement bit pattern so that negative literals
1734 // (which convert to large unsigned mode_t values) are caught.
1735 llvm::APInt RawValue = R.Val.getInt();
1736 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1737 llvm::APInt Extra = RawValue & ~Mask;
1738 if (Extra == 0)
1739 return;
1740 SmallString<16> ExtraStr;
1741 Extra.toString(Str&: ExtraStr, /*Radix=*/8, /*Signed=*/false);
1742 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fortify_umask_unused_bits)
1743 << ExtraStr;
1744}
1745
1746static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1747 Scope::ScopeFlags NeededScopeFlags,
1748 unsigned DiagID) {
1749 // Scopes aren't available during instantiation. Fortunately, builtin
1750 // functions cannot be template args so they cannot be formed through template
1751 // instantiation. Therefore checking once during the parse is sufficient.
1752 if (SemaRef.inTemplateInstantiation())
1753 return false;
1754
1755 Scope *S = SemaRef.getCurScope();
1756 while (S && !S->isSEHExceptScope())
1757 S = S->getParent();
1758 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1759 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1760 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1761 << DRE->getDecl()->getIdentifier();
1762 return true;
1763 }
1764
1765 return false;
1766}
1767
1768// In OpenCL, __builtin_alloca_* should return a pointer to address space
1769// that corresponds to the stack address space i.e private address space.
1770static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1771 QualType RT = TheCall->getType();
1772 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1773 "__builtin_alloca has invalid address space");
1774
1775 RT = RT->getPointeeType();
1776 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1777 TheCall->setType(S.Context.getPointerType(T: RT));
1778}
1779
1780static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1781 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1782 return true;
1783
1784 for (Expr *Arg : TheCall->arguments()) {
1785 // If argument is dependent on a template parameter, we can't resolve now.
1786 if (Arg->isTypeDependent() || Arg->isValueDependent())
1787 continue;
1788 // Reject void types.
1789 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1790 if (ArgTy->isVoidType())
1791 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1792 }
1793
1794 TheCall->setType(S.Context.getSizeType());
1795 return false;
1796}
1797
1798namespace {
1799enum PointerAuthOpKind {
1800 PAO_Strip,
1801 PAO_Sign,
1802 PAO_Auth,
1803 PAO_SignGeneric,
1804 PAO_Discriminator,
1805 PAO_BlendPointer,
1806 PAO_BlendInteger,
1807 PAO_BlendPC
1808};
1809}
1810
1811bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1812 if (getLangOpts().PointerAuthIntrinsics)
1813 return false;
1814
1815 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1816 return true;
1817}
1818
1819static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1820 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1821}
1822
1823static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1824 // Convert it to type 'int'.
1825 if (S.convertArgumentToType(Value&: Arg, Ty: S.Context.IntTy))
1826 return true;
1827
1828 // Value-dependent expressions are okay; wait for template instantiation.
1829 if (Arg->isValueDependent())
1830 return false;
1831
1832 unsigned KeyValue;
1833 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1834}
1835
1836bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1837 // Attempt to constant-evaluate the expression.
1838 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1839 if (!KeyValue) {
1840 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1841 << 0 << Arg->getSourceRange();
1842 return true;
1843 }
1844
1845 // Ask the target to validate the key parameter.
1846 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1847 llvm::SmallString<32> Value;
1848 {
1849 llvm::raw_svector_ostream Str(Value);
1850 Str << *KeyValue;
1851 }
1852
1853 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1854 << Value << Arg->getSourceRange();
1855 return true;
1856 }
1857
1858 Result = KeyValue->getZExtValue();
1859 return false;
1860}
1861
1862bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1863 PointerAuthDiscArgKind Kind,
1864 unsigned &IntVal) {
1865 if (!Arg) {
1866 IntVal = 0;
1867 return true;
1868 }
1869
1870 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1871 if (!Result) {
1872 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1873 return false;
1874 }
1875
1876 unsigned Max;
1877 bool IsAddrDiscArg = false;
1878
1879 switch (Kind) {
1880 case PointerAuthDiscArgKind::Addr:
1881 Max = 1;
1882 IsAddrDiscArg = true;
1883 break;
1884 case PointerAuthDiscArgKind::Extra:
1885 Max = PointerAuthQualifier::MaxDiscriminator;
1886 break;
1887 };
1888
1889 if (*Result < 0 || *Result > Max) {
1890 if (IsAddrDiscArg)
1891 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1892 << Result->getExtValue();
1893 else
1894 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1895 << Result->getExtValue() << Max;
1896
1897 return false;
1898 };
1899
1900 IntVal = Result->getZExtValue();
1901 return true;
1902}
1903
1904static std::pair<const ValueDecl *, CharUnits>
1905findConstantBaseAndOffset(Sema &S, Expr *E) {
1906 // Must evaluate as a pointer.
1907 Expr::EvalResult Result;
1908 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1909 return {nullptr, CharUnits()};
1910
1911 const auto *BaseDecl =
1912 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1913 if (!BaseDecl)
1914 return {nullptr, CharUnits()};
1915
1916 return {BaseDecl, Result.Val.getLValueOffset()};
1917}
1918
1919static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1920 bool RequireConstant = false) {
1921 if (Arg->hasPlaceholderType()) {
1922 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1923 if (R.isInvalid())
1924 return true;
1925 Arg = R.get();
1926 }
1927
1928 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1929 return OpKind != PAO_BlendInteger;
1930 };
1931 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1932 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1933 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1934 };
1935
1936 // Require the value to have the right range of type.
1937 QualType ExpectedTy;
1938 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1939 ExpectedTy = Arg->getType().getUnqualifiedType();
1940 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1941 ExpectedTy = S.Context.VoidPtrTy;
1942 } else if (AllowsInteger(OpKind) &&
1943 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1944 ExpectedTy = S.Context.getUIntPtrType();
1945
1946 } else {
1947 // Diagnose the failures.
1948 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1949 << unsigned(OpKind == PAO_Discriminator ? 1
1950 : OpKind == PAO_BlendPointer ? 2
1951 : OpKind == PAO_BlendInteger ? 3
1952 : OpKind == PAO_BlendPC ? 4
1953 : 0)
1954 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1955 << Arg->getType() << Arg->getSourceRange();
1956 return true;
1957 }
1958
1959 // Convert to that type. This should just be an lvalue-to-rvalue
1960 // conversion.
1961 if (S.convertArgumentToType(Value&: Arg, Ty: ExpectedTy))
1962 return true;
1963
1964 if (!RequireConstant) {
1965 // Warn about null pointers for non-generic sign and auth operations.
1966 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1967 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1968 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1969 ? diag::warn_ptrauth_sign_null_pointer
1970 : diag::warn_ptrauth_auth_null_pointer)
1971 << Arg->getSourceRange();
1972 }
1973
1974 return false;
1975 }
1976
1977 // Perform special checking on the arguments to ptrauth_sign_constant.
1978
1979 // The main argument.
1980 if (OpKind == PAO_Sign) {
1981 // Require the value we're signing to have a special form.
1982 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1983 bool Invalid;
1984
1985 // Must be rooted in a declaration reference.
1986 if (!BaseDecl)
1987 Invalid = true;
1988
1989 // If it's a function declaration, we can't have an offset.
1990 else if (isa<FunctionDecl>(Val: BaseDecl))
1991 Invalid = !Offset.isZero();
1992
1993 // Otherwise we're fine.
1994 else
1995 Invalid = false;
1996
1997 if (Invalid)
1998 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1999 return Invalid;
2000 }
2001
2002 // The discriminator argument.
2003 assert(OpKind == PAO_Discriminator);
2004
2005 // Must be a pointer or integer or blend thereof.
2006 Expr *Pointer = nullptr;
2007 Expr *Integer = nullptr;
2008 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
2009 if (Call->getBuiltinCallee() ==
2010 Builtin::BI__builtin_ptrauth_blend_discriminator) {
2011 Pointer = Call->getArg(Arg: 0);
2012 Integer = Call->getArg(Arg: 1);
2013 }
2014 }
2015 if (!Pointer && !Integer) {
2016 if (Arg->getType()->isPointerType())
2017 Pointer = Arg;
2018 else
2019 Integer = Arg;
2020 }
2021
2022 // Check the pointer.
2023 bool Invalid = false;
2024 if (Pointer) {
2025 assert(Pointer->getType()->isPointerType());
2026
2027 // TODO: if we're initializing a global, check that the address is
2028 // somehow related to what we're initializing. This probably will
2029 // never really be feasible and we'll have to catch it at link-time.
2030 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
2031 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
2032 Invalid = true;
2033 }
2034
2035 // Check the integer.
2036 if (Integer) {
2037 assert(Integer->getType()->isIntegerType());
2038 if (!Integer->isEvaluatable(Ctx: S.Context))
2039 Invalid = true;
2040 }
2041
2042 if (Invalid)
2043 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
2044 return Invalid;
2045}
2046
2047static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
2048 if (S.checkArgCount(Call, DesiredArgCount: 2))
2049 return ExprError();
2050 if (checkPointerAuthEnabled(S, E: Call))
2051 return ExprError();
2052 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
2053 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
2054 return ExprError();
2055
2056 Call->setType(Call->getArgs()[0]->getType());
2057 return Call;
2058}
2059
2060static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
2061 if (S.checkArgCount(Call, DesiredArgCount: 2))
2062 return ExprError();
2063 if (checkPointerAuthEnabled(S, E: Call))
2064 return ExprError();
2065 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
2066 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
2067 return ExprError();
2068
2069 Call->setType(S.Context.getUIntPtrType());
2070 return Call;
2071}
2072
2073static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
2074 if (S.checkArgCount(Call, DesiredArgCount: 2))
2075 return ExprError();
2076 if (checkPointerAuthEnabled(S, E: Call))
2077 return ExprError();
2078 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
2079 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
2080 return ExprError();
2081
2082 Call->setType(S.Context.getUIntPtrType());
2083 return Call;
2084}
2085
2086static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
2087 PointerAuthOpKind OpKind,
2088 bool RequireConstant) {
2089 if (S.checkArgCount(Call, DesiredArgCount: 3))
2090 return ExprError();
2091 if (checkPointerAuthEnabled(S, E: Call))
2092 return ExprError();
2093 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
2094 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2095 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
2096 RequireConstant))
2097 return ExprError();
2098
2099 Call->setType(Call->getArgs()[0]->getType());
2100 return Call;
2101}
2102
2103static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
2104 if (S.checkArgCount(Call, DesiredArgCount: 5))
2105 return ExprError();
2106 if (checkPointerAuthEnabled(S, E: Call))
2107 return ExprError();
2108 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2109 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2110 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2111 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2112 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
2113 return ExprError();
2114
2115 Call->setType(Call->getArgs()[0]->getType());
2116 return Call;
2117}
2118
2119static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call) {
2120 if (S.checkArgCount(Call, DesiredArgCount: 6))
2121 return ExprError();
2122 if (checkPointerAuthEnabled(S, E: Call))
2123 return ExprError();
2124 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2125 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2126 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2127 checkPointerAuthValue(S, Arg&: Call->getArgs()[3], OpKind: PAO_BlendPC) ||
2128 checkPointerAuthKey(S, Arg&: Call->getArgs()[4]) ||
2129 checkPointerAuthValue(S, Arg&: Call->getArgs()[5], OpKind: PAO_Discriminator))
2130 return ExprError();
2131
2132 // Validate that the oldKey is IA or IB, not DA or DB.
2133 // This enforces the constraint that auth_with_pc_and_resign only supports
2134 // IA/IB keys for authentication, as only those keys support the PC-based
2135 // signing instructions (paciasppc/pacibsppc).
2136 unsigned OldKey = 0;
2137 if (!S.checkConstantPointerAuthKey(Arg: Call->getArgs()[1], Result&: OldKey)) {
2138 using AK = PointerAuthSchema::ARM8_3Key;
2139 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2140 OldKey != static_cast<unsigned>(AK::ASIB)) {
2141 S.Diag(Loc: Call->getArgs()[1]->getExprLoc(),
2142 DiagID: diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2143 << OldKey << Call->getArgs()[1]->getSourceRange();
2144 return ExprError();
2145 }
2146 }
2147
2148 Call->setType(Call->getArgs()[0]->getType());
2149 return Call;
2150}
2151
2152static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
2153 if (S.checkArgCount(Call, DesiredArgCount: 6))
2154 return ExprError();
2155 if (checkPointerAuthEnabled(S, E: Call))
2156 return ExprError();
2157 const Expr *AddendExpr = Call->getArg(Arg: 5);
2158 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
2159 if (!AddendIsConstInt) {
2160 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
2161 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
2162 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
2163 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
2164 << FDecl->getDeclName() << Arg->getSourceRange();
2165 }
2166 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2167 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2168 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2169 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2170 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
2171 !AddendIsConstInt)
2172 return ExprError();
2173
2174 Call->setType(Call->getArgs()[0]->getType());
2175 return Call;
2176}
2177
2178static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
2179 if (checkPointerAuthEnabled(S, E: Call))
2180 return ExprError();
2181
2182 // We've already performed normal call type-checking.
2183 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
2184
2185 // Operand must be an ordinary or UTF-8 string literal.
2186 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
2187 if (!Literal || Literal->getCharByteWidth() != 1) {
2188 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
2189 << (Literal ? 1 : 0) << Arg->getSourceRange();
2190 return ExprError();
2191 }
2192
2193 return Call;
2194}
2195
2196static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
2197 if (S.checkArgCount(Call, DesiredArgCount: 1))
2198 return ExprError();
2199 Expr *FirstArg = Call->getArg(Arg: 0);
2200 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
2201 if (FirstValue.isInvalid())
2202 return ExprError();
2203 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
2204 QualType FirstArgType = FirstArg->getType();
2205 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2206 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
2207
2208 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2209 if (!FirstArgRecord) {
2210 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2211 << /*isPolymorphic=*/0 << FirstArgType;
2212 return ExprError();
2213 }
2214 if (S.RequireCompleteType(
2215 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
2216 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
2217 return ExprError();
2218 }
2219
2220 if (!FirstArgRecord->isPolymorphic()) {
2221 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2222 << /*isPolymorphic=*/1 << FirstArgRecord;
2223 return ExprError();
2224 }
2225 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
2226 Call->setType(ReturnType);
2227 return Call;
2228}
2229
2230static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
2231 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2232 return ExprError();
2233
2234 // Compute __builtin_launder's parameter type from the argument.
2235 // The parameter type is:
2236 // * The type of the argument if it's not an array or function type,
2237 // Otherwise,
2238 // * The decayed argument type.
2239 QualType ParamTy = [&]() {
2240 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
2241 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2242 return S.Context.getPointerType(T: Ty->getElementType());
2243 if (ArgTy->isFunctionType()) {
2244 return S.Context.getPointerType(T: ArgTy);
2245 }
2246 return ArgTy;
2247 }();
2248
2249 TheCall->setType(ParamTy);
2250
2251 auto DiagSelect = [&]() -> std::optional<unsigned> {
2252 if (!ParamTy->isPointerType())
2253 return 0;
2254 if (ParamTy->isFunctionPointerType())
2255 return 1;
2256 if (ParamTy->isVoidPointerType())
2257 return 2;
2258 return std::optional<unsigned>{};
2259 }();
2260 if (DiagSelect) {
2261 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
2262 << *DiagSelect << TheCall->getSourceRange();
2263 return ExprError();
2264 }
2265
2266 // We either have an incomplete class type, or we have a class template
2267 // whose instantiation has not been forced. Example:
2268 //
2269 // template <class T> struct Foo { T value; };
2270 // Foo<int> *p = nullptr;
2271 // auto *d = __builtin_launder(p);
2272 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
2273 DiagID: diag::err_incomplete_type))
2274 return ExprError();
2275
2276 assert(ParamTy->getPointeeType()->isObjectType() &&
2277 "Unhandled non-object pointer case");
2278
2279 InitializedEntity Entity =
2280 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
2281 ExprResult Arg =
2282 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
2283 if (Arg.isInvalid())
2284 return ExprError();
2285 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2286
2287 return TheCall;
2288}
2289
2290static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
2291 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2292 return ExprError();
2293
2294 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
2295 if (Arg.isInvalid())
2296 return ExprError();
2297 QualType ParamTy = Arg.get()->getType();
2298 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2299 TheCall->setType(S.Context.BoolTy);
2300
2301 // Only accept pointers to objects as arguments, which should have object
2302 // pointer or void pointer types.
2303 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2304 // LWG4138: Function pointer types not allowed
2305 if (PT->getPointeeType()->isFunctionType()) {
2306 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2307 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2308 << 1;
2309 return ExprError();
2310 }
2311 // Disallow VLAs too since those shouldn't be able to
2312 // be a template parameter for `std::is_within_lifetime`
2313 if (PT->getPointeeType()->isVariableArrayType()) {
2314 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2315 << 1 << "__builtin_is_within_lifetime";
2316 return ExprError();
2317 }
2318 } else {
2319 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2320 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2321 << 0;
2322 return ExprError();
2323 }
2324 return TheCall;
2325}
2326
2327static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2328 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2329 return ExprError();
2330
2331 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2332 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2333 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2334 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2335 << /*a pointer*/ 0;
2336 return ExprError();
2337 }
2338
2339 QualType T = Dest->getPointeeType();
2340 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2341 DiagID: diag::err_incomplete_type))
2342 return ExprError();
2343
2344 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2345 T->isIncompleteArrayType()) {
2346 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2347 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2348 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2349 return ExprError();
2350 }
2351
2352 TheCall->setType(Dest);
2353
2354 QualType Src = TheCall->getArg(Arg: 1)->getType();
2355 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2356 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2357 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2358 << /*the same*/ 3;
2359 return ExprError();
2360 }
2361
2362 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2363 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2364 if (Size.isInvalid())
2365 return ExprError();
2366
2367 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2368 if (Size.isInvalid())
2369 return ExprError();
2370 SizeExpr = Size.get();
2371 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2372
2373 return TheCall;
2374}
2375
2376// Emit an error and return true if the current object format type is in the
2377// list of unsupported types.
2378static bool CheckBuiltinTargetNotInUnsupported(
2379 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2380 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2381 llvm::Triple::ObjectFormatType CurObjFormat =
2382 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2383 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2384 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2385 << TheCall->getSourceRange();
2386 return true;
2387 }
2388 return false;
2389}
2390
2391// Emit an error and return true if the current architecture is not in the list
2392// of supported architectures.
2393static bool
2394CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2395 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2396 llvm::Triple::ArchType CurArch =
2397 S.getASTContext().getTargetInfo().getTriple().getArch();
2398 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2399 return false;
2400 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2401 << TheCall->getSourceRange();
2402 return true;
2403}
2404
2405static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2406 SourceLocation CallSiteLoc);
2407
2408bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2409 CallExpr *TheCall) {
2410 switch (TI.getTriple().getArch()) {
2411 default:
2412 // Some builtins don't require additional checking, so just consider these
2413 // acceptable.
2414 return false;
2415 case llvm::Triple::arm:
2416 case llvm::Triple::armeb:
2417 case llvm::Triple::thumb:
2418 case llvm::Triple::thumbeb:
2419 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2420 case llvm::Triple::aarch64:
2421 case llvm::Triple::aarch64_32:
2422 case llvm::Triple::aarch64_be:
2423 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2424 case llvm::Triple::bpfeb:
2425 case llvm::Triple::bpfel:
2426 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2427 case llvm::Triple::dxil:
2428 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2429 case llvm::Triple::hexagon:
2430 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2431 case llvm::Triple::mips:
2432 case llvm::Triple::mipsel:
2433 case llvm::Triple::mips64:
2434 case llvm::Triple::mips64el:
2435 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2436 case llvm::Triple::spirv:
2437 case llvm::Triple::spirv32:
2438 case llvm::Triple::spirv64:
2439 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2440 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2441 return false;
2442 case llvm::Triple::systemz:
2443 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2444 case llvm::Triple::x86:
2445 case llvm::Triple::x86_64:
2446 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2447 case llvm::Triple::ppc:
2448 case llvm::Triple::ppcle:
2449 case llvm::Triple::ppc64:
2450 case llvm::Triple::ppc64le:
2451 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2452 case llvm::Triple::amdgpu:
2453 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2454 case llvm::Triple::riscv32:
2455 case llvm::Triple::riscv64:
2456 case llvm::Triple::riscv32be:
2457 case llvm::Triple::riscv64be:
2458 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2459 case llvm::Triple::loongarch32:
2460 case llvm::Triple::loongarch64:
2461 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2462 TheCall);
2463 case llvm::Triple::wasm32:
2464 case llvm::Triple::wasm64:
2465 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2466 case llvm::Triple::nvptx:
2467 case llvm::Triple::nvptx64:
2468 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2469 }
2470}
2471
2472static bool isValidMathElementType(QualType T) {
2473 return T->isDependentType() ||
2474 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2475}
2476
2477// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2478// not a valid type, emit an error message and return true. Otherwise return
2479// false.
2480static bool
2481checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2482 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2483 int ArgOrdinal) {
2484 clang::QualType EltTy =
2485 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2486 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2487 : ArgTy;
2488
2489 switch (ArgTyRestr) {
2490 case Sema::EltwiseBuiltinArgTyRestriction::None:
2491 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2492 !isValidMathElementType(T: ArgTy)) {
2493 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2494 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2495 << ArgTy;
2496 }
2497 break;
2498 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2499 if (!EltTy->isRealFloatingType()) {
2500 // FIXME: make diagnostic's wording correct for matrices
2501 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2502 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2503 << /* floating-point */ 1 << ArgTy;
2504 }
2505 break;
2506 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2507 if (!EltTy->isIntegerType()) {
2508 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2509 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2510 << /* no fp */ 0 << ArgTy;
2511 }
2512 break;
2513 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2514 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2515 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2516 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2517 << /* or fp */ 1 << ArgTy;
2518 }
2519 break;
2520 }
2521
2522 return false;
2523}
2524
2525/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2526/// This checks that the target supports the builtin and that the string
2527/// argument is constant and valid.
2528static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2529 const TargetInfo *AuxTI, unsigned BuiltinID) {
2530 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2531 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2532 "Expecting __builtin_cpu_...");
2533
2534 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2535 const TargetInfo *TheTI = &TI;
2536 auto SupportsBI = [=](const TargetInfo *TInfo) {
2537 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2538 (!IsCPUSupports && TInfo->supportsCpuIs()));
2539 };
2540 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2541 TheTI = AuxTI;
2542
2543 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2544 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2545 return S.Diag(Loc: TheCall->getBeginLoc(),
2546 DiagID: TI.getTriple().isOSAIX()
2547 ? diag::err_builtin_aix_os_unsupported
2548 : diag::err_builtin_target_unsupported)
2549 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2550
2551 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2552 // Check if the argument is a string literal.
2553 if (!isa<StringLiteral>(Val: Arg))
2554 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2555 << Arg->getSourceRange();
2556
2557 // Check the contents of the string.
2558 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2559 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2560 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2561 << Arg->getSourceRange();
2562 return false;
2563 }
2564 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2565 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2566 << Arg->getSourceRange();
2567 return false;
2568}
2569
2570/// Checks that __builtin_bswapg was called with a single argument, which is an
2571/// unsigned integer, and overrides the return value type to the integer type.
2572static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2573 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2574 return true;
2575 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2576 if (ArgRes.isInvalid())
2577 return true;
2578
2579 Expr *Arg = ArgRes.get();
2580 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2581 if (Arg->isTypeDependent())
2582 return false;
2583
2584 QualType ArgTy = Arg->getType();
2585
2586 if (!ArgTy->isIntegerType()) {
2587 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2588 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2589 << ArgTy;
2590 return true;
2591 }
2592 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2593 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2594 BT->getNumBits() != 1) {
2595 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2596 << ArgTy << BT->getNumBits();
2597 return true;
2598 }
2599 }
2600 TheCall->setType(ArgTy);
2601 return false;
2602}
2603
2604/// Checks that __builtin_bitreverseg was called with a single argument, which
2605/// is an integer
2606static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2607 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2608 return true;
2609 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2610 if (ArgRes.isInvalid())
2611 return true;
2612
2613 Expr *Arg = ArgRes.get();
2614 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2615 if (Arg->isTypeDependent())
2616 return false;
2617
2618 QualType ArgTy = Arg->getType();
2619
2620 if (!ArgTy->isIntegerType()) {
2621 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2622 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2623 << ArgTy;
2624 return true;
2625 }
2626 TheCall->setType(ArgTy);
2627 return false;
2628}
2629
2630/// Checks that __builtin_popcountg was called with a single argument, which is
2631/// an unsigned integer.
2632static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2633 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2634 return true;
2635
2636 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2637 if (ArgRes.isInvalid())
2638 return true;
2639
2640 Expr *Arg = ArgRes.get();
2641 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2642
2643 QualType ArgTy = Arg->getType();
2644
2645 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2646 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2647 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2648 << ArgTy;
2649 return true;
2650 }
2651 return false;
2652}
2653
2654/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2655/// argument and return either int, bool, or the argument type.
2656static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2657 QualType ReturnType) {
2658 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2659 return true;
2660
2661 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2662 if (ArgRes.isInvalid())
2663 return true;
2664
2665 Expr *Arg = ArgRes.get();
2666 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2667
2668 QualType ArgTy = Arg->getType();
2669 // C23 stdbit.h functions do not permit bool or enumeration types.
2670 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2671 return S.Diag(Loc: Arg->getBeginLoc(),
2672 DiagID: diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2673 << 1 /*1st argument*/ << ArgTy;
2674 if (!ArgTy->isUnsignedIntegerType())
2675 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_invalid_arg_type)
2676 << 1 /*1st argument*/ << ArgTy;
2677
2678 // For builtins returning unsigned int, verify the argument's bit width fits.
2679 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2680 // produce a count that overflows the return type.
2681 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2682 uint64_t ArgWidth = S.Context.getIntWidth(T: ArgTy);
2683 uint64_t ReturnTypeWidth = S.Context.getIntWidth(T: S.Context.UnsignedIntTy);
2684 if (!llvm::isUIntN(N: ReturnTypeWidth, x: ArgWidth))
2685 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_result_overflow)
2686 << ArgTy;
2687 }
2688
2689 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2690 return false;
2691}
2692
2693/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2694/// an unsigned integer, and an optional second argument, which is promoted to
2695/// an 'int'.
2696static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2697 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2698 return true;
2699
2700 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2701 if (Arg0Res.isInvalid())
2702 return true;
2703
2704 Expr *Arg0 = Arg0Res.get();
2705 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2706
2707 QualType Arg0Ty = Arg0->getType();
2708
2709 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2710 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2711 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2712 << Arg0Ty;
2713 return true;
2714 }
2715
2716 if (TheCall->getNumArgs() > 1) {
2717 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2718 if (Arg1Res.isInvalid())
2719 return true;
2720
2721 Expr *Arg1 = Arg1Res.get();
2722 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2723
2724 QualType Arg1Ty = Arg1->getType();
2725
2726 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2727 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2728 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2729 return true;
2730 }
2731 }
2732
2733 return false;
2734}
2735
2736class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2737 unsigned ArgIndex;
2738 bool OnlyUnsigned;
2739
2740 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2741 QualType T) {
2742 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2743 << ArgIndex << /*scalar*/ 1
2744 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2745 << /*no fp*/ 0 << T;
2746 }
2747
2748public:
2749 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2750 : ContextualImplicitConverter(/*Suppress=*/false,
2751 /*SuppressConversion=*/true),
2752 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2753
2754 bool match(QualType T) override {
2755 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2756 }
2757
2758 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2759 QualType T) override {
2760 return emitError(S, Loc, T);
2761 }
2762
2763 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2764 QualType T) override {
2765 return emitError(S, Loc, T);
2766 }
2767
2768 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2769 QualType T,
2770 QualType ConvTy) override {
2771 return emitError(S, Loc, T);
2772 }
2773
2774 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2775 QualType ConvTy) override {
2776 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2777 }
2778
2779 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2780 QualType T) override {
2781 return emitError(S, Loc, T);
2782 }
2783
2784 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2785 QualType ConvTy) override {
2786 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2787 }
2788
2789 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2790 QualType T,
2791 QualType ConvTy) override {
2792 llvm_unreachable("conversion functions are permitted");
2793 }
2794};
2795
2796/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2797/// arguments, that the first argument is an unsigned integer type, and that
2798/// the second argument is an integer type.
2799static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2800 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2801 return true;
2802
2803 // First argument (value to rotate) must be unsigned integer type.
2804 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2805 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2806 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2807 if (Arg0Res.isInvalid())
2808 return true;
2809
2810 Expr *Arg0 = Arg0Res.get();
2811 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2812
2813 QualType Arg0Ty = Arg0->getType();
2814 if (!Arg0Ty->isUnsignedIntegerType())
2815 return true;
2816
2817 // Second argument (rotation count) must be integer type.
2818 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2819 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2820 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2821 if (Arg1Res.isInvalid())
2822 return true;
2823
2824 Expr *Arg1 = Arg1Res.get();
2825 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2826
2827 QualType Arg1Ty = Arg1->getType();
2828 if (!Arg1Ty->isIntegerType())
2829 return true;
2830
2831 TheCall->setType(Arg0Ty);
2832 return false;
2833}
2834
2835static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2836 unsigned Pos, bool AllowConst,
2837 bool AllowAS) {
2838 QualType MaskTy = MaskArg->getType();
2839 if (!MaskTy->isExtVectorBoolType())
2840 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2841 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2842 << MaskTy;
2843
2844 QualType PtrTy = PtrArg->getType();
2845 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2846 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2847 << Pos << "scalar pointer";
2848
2849 QualType PointeeTy = PtrTy->getPointeeType();
2850 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2851 (!AllowConst && PointeeTy.isConstQualified()) ||
2852 (!AllowAS && PointeeTy.hasAddressSpace())) {
2853 QualType Target =
2854 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2855 return S.Diag(Loc: PtrArg->getExprLoc(),
2856 DiagID: diag::err_typecheck_convert_incompatible)
2857 << PtrTy << Target << /*different qualifiers=*/5
2858 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2859 << PtrTy << Target;
2860 }
2861 return false;
2862}
2863
2864static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2865 bool TypeDependent = false;
2866 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2867 ExprResult Converted =
2868 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2869 if (Converted.isInvalid())
2870 return true;
2871 TheCall->setArg(Arg, ArgExpr: Converted.get());
2872 TypeDependent |= Converted.get()->isTypeDependent();
2873 }
2874
2875 if (TypeDependent)
2876 TheCall->setType(S.Context.DependentTy);
2877 return false;
2878}
2879
2880static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2881 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2882 return ExprError();
2883
2884 if (ConvertMaskedBuiltinArgs(S, TheCall))
2885 return ExprError();
2886
2887 Expr *MaskArg = TheCall->getArg(Arg: 0);
2888 Expr *PtrArg = TheCall->getArg(Arg: 1);
2889 if (TheCall->isTypeDependent())
2890 return TheCall;
2891
2892 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2893 AllowAS: TheCall->getBuiltinCallee() ==
2894 Builtin::BI__builtin_masked_load))
2895 return ExprError();
2896
2897 QualType MaskTy = MaskArg->getType();
2898 QualType PtrTy = PtrArg->getType();
2899 QualType PointeeTy = PtrTy->getPointeeType();
2900 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2901
2902 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2903 NumElts: MaskVecTy->getNumElements());
2904 if (TheCall->getNumArgs() == 3) {
2905 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2906 QualType PassThruTy = PassThruArg->getType();
2907 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2908 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2909 << /* third argument */ 3 << RetTy;
2910 }
2911
2912 TheCall->setType(RetTy);
2913 return TheCall;
2914}
2915
2916static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2917 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2918 return ExprError();
2919
2920 if (ConvertMaskedBuiltinArgs(S, TheCall))
2921 return ExprError();
2922
2923 Expr *MaskArg = TheCall->getArg(Arg: 0);
2924 Expr *ValArg = TheCall->getArg(Arg: 1);
2925 Expr *PtrArg = TheCall->getArg(Arg: 2);
2926 if (TheCall->isTypeDependent())
2927 return TheCall;
2928
2929 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2930 AllowAS: TheCall->getBuiltinCallee() ==
2931 Builtin::BI__builtin_masked_store))
2932 return ExprError();
2933
2934 QualType MaskTy = MaskArg->getType();
2935 QualType PtrTy = PtrArg->getType();
2936 QualType ValTy = ValArg->getType();
2937 if (!ValTy->isVectorType())
2938 return ExprError(
2939 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2940 << 2 << "vector");
2941
2942 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2943 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2944
2945 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2946 return ExprError(
2947 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2948 << S.getASTContext().BuiltinInfo.getQuotedName(
2949 ID: TheCall->getBuiltinCallee())
2950 << MaskTy << ValTy);
2951 }
2952
2953 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2954 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2955 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2956 DiagID: diag::err_vec_builtin_incompatible_vector)
2957 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2958 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2959 TheCall->getArg(Arg: 1)->getEndLoc()));
2960
2961 TheCall->setType(S.Context.VoidTy);
2962 return TheCall;
2963}
2964
2965static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2966 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2967 return ExprError();
2968
2969 if (ConvertMaskedBuiltinArgs(S, TheCall))
2970 return ExprError();
2971
2972 Expr *MaskArg = TheCall->getArg(Arg: 0);
2973 Expr *IdxArg = TheCall->getArg(Arg: 1);
2974 Expr *PtrArg = TheCall->getArg(Arg: 2);
2975 if (TheCall->isTypeDependent())
2976 return TheCall;
2977
2978 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2979 /*AllowAS=*/true))
2980 return ExprError();
2981
2982 QualType IdxTy = IdxArg->getType();
2983 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2984 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2985 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2986 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2987 << IdxTy;
2988
2989 QualType MaskTy = MaskArg->getType();
2990 QualType PtrTy = PtrArg->getType();
2991 QualType PointeeTy = PtrTy->getPointeeType();
2992 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2993 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2994 return ExprError(
2995 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2996 << S.getASTContext().BuiltinInfo.getQuotedName(
2997 ID: TheCall->getBuiltinCallee())
2998 << MaskTy << IdxTy);
2999
3000 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
3001 NumElts: MaskVecTy->getNumElements());
3002 if (TheCall->getNumArgs() == 4) {
3003 Expr *PassThruArg = TheCall->getArg(Arg: 3);
3004 QualType PassThruTy = PassThruArg->getType();
3005 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
3006 return S.Diag(Loc: PassThruArg->getExprLoc(),
3007 DiagID: diag::err_vec_masked_load_store_ptr)
3008 << /* fourth argument */ 4 << RetTy;
3009 }
3010
3011 TheCall->setType(RetTy);
3012 return TheCall;
3013}
3014
3015static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
3016 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
3017 return ExprError();
3018
3019 if (ConvertMaskedBuiltinArgs(S, TheCall))
3020 return ExprError();
3021
3022 Expr *MaskArg = TheCall->getArg(Arg: 0);
3023 Expr *IdxArg = TheCall->getArg(Arg: 1);
3024 Expr *ValArg = TheCall->getArg(Arg: 2);
3025 Expr *PtrArg = TheCall->getArg(Arg: 3);
3026 if (TheCall->isTypeDependent())
3027 return TheCall;
3028
3029 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
3030 /*AllowAS=*/true))
3031 return ExprError();
3032
3033 QualType IdxTy = IdxArg->getType();
3034 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
3035 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
3036 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3037 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
3038 << IdxTy;
3039
3040 QualType ValTy = ValArg->getType();
3041 QualType MaskTy = MaskArg->getType();
3042 QualType PtrTy = PtrArg->getType();
3043
3044 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
3045 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
3046 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
3047 return ExprError(
3048 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
3049 << S.getASTContext().BuiltinInfo.getQuotedName(
3050 ID: TheCall->getBuiltinCallee())
3051 << MaskTy << IdxTy);
3052 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
3053 return ExprError(
3054 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
3055 << S.getASTContext().BuiltinInfo.getQuotedName(
3056 ID: TheCall->getBuiltinCallee())
3057 << MaskTy << ValTy);
3058
3059 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
3060 T2: PtrTy->getPointeeType().getUnqualifiedType()))
3061 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
3062 DiagID: diag::err_vec_builtin_incompatible_vector)
3063 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
3064 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
3065 TheCall->getArg(Arg: 1)->getEndLoc()));
3066
3067 TheCall->setType(S.Context.VoidTy);
3068 return TheCall;
3069}
3070
3071static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
3072 SourceLocation Loc = TheCall->getBeginLoc();
3073 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
3074 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
3075
3076 if (Args.size() == 0) {
3077 S.Diag(Loc: TheCall->getBeginLoc(),
3078 DiagID: diag::err_typecheck_call_too_few_args_at_least)
3079 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
3080 << /*is_non_object=*/0 << TheCall->getSourceRange();
3081 return ExprError();
3082 }
3083
3084 QualType FuncT = Args[0]->getType();
3085
3086 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
3087 if (Args.size() < 2) {
3088 S.Diag(Loc: TheCall->getBeginLoc(),
3089 DiagID: diag::err_typecheck_call_too_few_args_at_least)
3090 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
3091 << /*is_non_object=*/0 << TheCall->getSourceRange();
3092 return ExprError();
3093 }
3094
3095 const Type *MemPtrClass = MPT->getQualifier().getAsType();
3096 QualType ObjectT = Args[1]->getType();
3097
3098 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
3099 return ExprError();
3100
3101 ExprResult ObjectArg = [&]() -> ExprResult {
3102 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
3103 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3104 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3105 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
3106 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3107 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3108 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
3109 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
3110 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
3111 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
3112 return Args[1];
3113 }
3114
3115 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
3116 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
3117 // reference_wrapper;
3118 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
3119 if (RD->isInStdNamespace() &&
3120 RD->getDeclName().getAsString() == "reference_wrapper") {
3121 CXXScopeSpec SS;
3122 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
3123 UnqualifiedId GetID;
3124 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
3125
3126 ExprResult MemExpr = S.ActOnMemberAccessExpr(
3127 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
3128 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
3129
3130 if (MemExpr.isInvalid())
3131 return ExprError();
3132
3133 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
3134 }
3135 }
3136
3137 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3138 // class T and t1 does not satisfy the previous two items;
3139
3140 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
3141 }();
3142
3143 if (ObjectArg.isInvalid())
3144 return ExprError();
3145
3146 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
3147 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
3148 if (BinOp.isInvalid())
3149 return ExprError();
3150
3151 if (MPT->isMemberDataPointer())
3152 return BinOp;
3153
3154 // Give the synthesized expression a valid source range for diagnostics.
3155 auto *MemCall = new (S.Context)
3156 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3157
3158 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
3159 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
3160 }
3161 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
3162 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
3163}
3164
3165// Performs a similar job to Sema::UsualUnaryConversions, but without any
3166// implicit promotion of integral/enumeration types.
3167static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
3168 // First, convert to an r-value.
3169 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
3170 if (Res.isInvalid())
3171 return ExprError();
3172
3173 // Promote floating-point types.
3174 return S.UsualUnaryFPConversions(E: Res.get());
3175}
3176
3177static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
3178 if (const auto *TyA = VecTy->getAs<VectorType>())
3179 return TyA->getElementType();
3180 if (VecTy->isSizelessVectorType())
3181 return VecTy->getSizelessVectorEltType(Ctx: Context);
3182 return QualType();
3183}
3184
3185static bool checkConstantArgValueRange(Sema &S, CallExpr *TheCall,
3186 unsigned ArgNum,
3187 const llvm::APSInt &Result, int Low,
3188 int High, bool RangeIsError) {
3189 if (S.isConstantEvaluatedContext())
3190 return false;
3191
3192 // We can't check the value of a dependent argument.
3193 Expr *Arg = TheCall->getArg(Arg: ArgNum);
3194 if (Arg->isTypeDependent() || Arg->isValueDependent())
3195 return false;
3196
3197 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
3198 if (RangeIsError) {
3199 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
3200 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
3201 }
3202
3203 // Defer the warning until we know if the code will be emitted so that
3204 // dead code can ignore this.
3205 S.DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
3206 PD: S.PDiag(DiagID: diag::warn_argument_invalid_range)
3207 << toString(I: Result, Radix: 10) << Low << High
3208 << Arg->getSourceRange());
3209 }
3210
3211 return false;
3212}
3213
3214ExprResult
3215Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3216 CallExpr *TheCall) {
3217 ExprResult TheCallResult(TheCall);
3218
3219 // Find out if any arguments are required to be integer constant expressions.
3220 unsigned ICEArguments = 0;
3221 ASTContext::GetBuiltinTypeError Error;
3222 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
3223 SmallVector<Builtin::Context::ArgRange, 2> ArgRanges;
3224 if (Error != ASTContext::GE_None)
3225 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3226 else if (ICEArguments)
3227 Context.BuiltinInfo.getArgRanges(ID: BuiltinID, Ranges&: ArgRanges);
3228
3229 // If any arguments are required to be ICE's, check and diagnose.
3230 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3231 // Skip arguments not required to be ICE's.
3232 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3233
3234 ICEArguments &= ~(1 << ArgNo);
3235
3236 // If we don't have enough arguments, continue so we can issue better
3237 // diagnostic in checkArgCount(...)
3238 if (ArgNo >= TheCall->getNumArgs())
3239 continue;
3240
3241 llvm::APSInt Result;
3242 if (BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
3243 return true;
3244
3245 for (const Builtin::Context::ArgRange &Range : ArgRanges) {
3246 if (Range.Index == ArgNo &&
3247 checkConstantArgValueRange(S&: *this, TheCall, ArgNum: ArgNo, Result, Low: Range.Lower,
3248 High: Range.Upper - 1,
3249 /*RangeIsError=*/true))
3250 return true;
3251 }
3252 }
3253
3254 FPOptions FPO;
3255 switch (BuiltinID) {
3256 case Builtin::BI__builtin___get_unsafe_stack_start:
3257 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3258 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3259 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3260 << "__safestack_get_unsafe_stack_bottom";
3261 break;
3262 case Builtin::BI__builtin___get_unsafe_stack_top:
3263 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3264 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3265 << "__safestack_get_unsafe_stack_top";
3266 break;
3267 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3268 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3269 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3270 << "__safestack_get_unsafe_stack_ptr";
3271 break;
3272 case Builtin::BI__builtin_cpu_supports:
3273 case Builtin::BI__builtin_cpu_is:
3274 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
3275 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
3276 return ExprError();
3277 break;
3278 case Builtin::BI__builtin_cpu_init:
3279 if (!Context.getTargetInfo().supportsCpuInit()) {
3280 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3281 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3282 return ExprError();
3283 }
3284 break;
3285 case Builtin::BI__builtin___CFStringMakeConstantString:
3286 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3287 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3288 if (CheckBuiltinTargetNotInUnsupported(
3289 S&: *this, BuiltinID, TheCall,
3290 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3291 return ExprError();
3292 assert(TheCall->getNumArgs() == 1 &&
3293 "Wrong # arguments to builtin CFStringMakeConstantString");
3294 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
3295 return ExprError();
3296 break;
3297 case Builtin::BI__builtin_ms_va_start:
3298 case Builtin::BI__builtin_zos_va_start:
3299 case Builtin::BI__builtin_stdarg_start:
3300 case Builtin::BI__builtin_va_start:
3301 case Builtin::BI__builtin_c23_va_start:
3302 if (BuiltinVAStart(BuiltinID, TheCall))
3303 return ExprError();
3304 break;
3305 case Builtin::BI__va_start: {
3306 switch (Context.getTargetInfo().getTriple().getArch()) {
3307 case llvm::Triple::aarch64:
3308 case llvm::Triple::arm:
3309 case llvm::Triple::thumb:
3310 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
3311 return ExprError();
3312 break;
3313 default:
3314 if (BuiltinVAStart(BuiltinID, TheCall))
3315 return ExprError();
3316 break;
3317 }
3318 break;
3319 }
3320
3321 // The acquire, release, and no fence variants are ARM and AArch64 only.
3322 case Builtin::BI_interlockedbittestandset_acq:
3323 case Builtin::BI_interlockedbittestandset_rel:
3324 case Builtin::BI_interlockedbittestandset_nf:
3325 case Builtin::BI_interlockedbittestandreset_acq:
3326 case Builtin::BI_interlockedbittestandreset_rel:
3327 case Builtin::BI_interlockedbittestandreset_nf:
3328 if (CheckBuiltinTargetInSupported(
3329 S&: *this, TheCall,
3330 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3331 return ExprError();
3332 break;
3333
3334 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3335 case Builtin::BI_bittest64:
3336 case Builtin::BI_bittestandcomplement64:
3337 case Builtin::BI_bittestandreset64:
3338 case Builtin::BI_bittestandset64:
3339 case Builtin::BI_interlockedbittestandreset64:
3340 case Builtin::BI_interlockedbittestandset64:
3341 if (CheckBuiltinTargetInSupported(
3342 S&: *this, TheCall,
3343 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3344 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3345 return ExprError();
3346 break;
3347
3348 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3349 case Builtin::BI_interlockedbittestandreset64_acq:
3350 case Builtin::BI_interlockedbittestandreset64_rel:
3351 case Builtin::BI_interlockedbittestandreset64_nf:
3352 case Builtin::BI_interlockedbittestandset64_acq:
3353 case Builtin::BI_interlockedbittestandset64_rel:
3354 case Builtin::BI_interlockedbittestandset64_nf:
3355 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
3356 return ExprError();
3357 break;
3358
3359 case Builtin::BI__builtin_set_flt_rounds:
3360 if (CheckBuiltinTargetInSupported(
3361 S&: *this, TheCall,
3362 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3363 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3364 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3365 llvm::Triple::ppc64le}))
3366 return ExprError();
3367 break;
3368
3369 case Builtin::BI__builtin_isgreater:
3370 case Builtin::BI__builtin_isgreaterequal:
3371 case Builtin::BI__builtin_isless:
3372 case Builtin::BI__builtin_islessequal:
3373 case Builtin::BI__builtin_islessgreater:
3374 case Builtin::BI__builtin_isunordered:
3375 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3376 return ExprError();
3377 break;
3378 case Builtin::BI__builtin_fpclassify:
3379 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
3380 return ExprError();
3381 break;
3382 case Builtin::BI__builtin_isfpclass:
3383 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
3384 return ExprError();
3385 break;
3386 case Builtin::BI__builtin_isfinite:
3387 case Builtin::BI__builtin_isinf:
3388 case Builtin::BI__builtin_isinf_sign:
3389 case Builtin::BI__builtin_isnan:
3390 case Builtin::BI__builtin_issignaling:
3391 case Builtin::BI__builtin_isnormal:
3392 case Builtin::BI__builtin_issubnormal:
3393 case Builtin::BI__builtin_iszero:
3394 case Builtin::BI__builtin_signbit:
3395 case Builtin::BI__builtin_signbitf:
3396 case Builtin::BI__builtin_signbitl:
3397 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
3398 return ExprError();
3399 break;
3400 case Builtin::BI__builtin_shufflevector:
3401 return BuiltinShuffleVector(TheCall);
3402 // TheCall will be freed by the smart pointer here, but that's fine, since
3403 // BuiltinShuffleVector guts it, but then doesn't release it.
3404 case Builtin::BI__builtin_masked_load:
3405 case Builtin::BI__builtin_masked_expand_load:
3406 return BuiltinMaskedLoad(S&: *this, TheCall);
3407 case Builtin::BI__builtin_masked_store:
3408 case Builtin::BI__builtin_masked_compress_store:
3409 return BuiltinMaskedStore(S&: *this, TheCall);
3410 case Builtin::BI__builtin_masked_gather:
3411 return BuiltinMaskedGather(S&: *this, TheCall);
3412 case Builtin::BI__builtin_masked_scatter:
3413 return BuiltinMaskedScatter(S&: *this, TheCall);
3414 case Builtin::BI__builtin_invoke:
3415 return BuiltinInvoke(S&: *this, TheCall);
3416 case Builtin::BI__builtin_prefetch:
3417 if (BuiltinPrefetch(TheCall))
3418 return ExprError();
3419 break;
3420 case Builtin::BI__builtin_alloca_with_align:
3421 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3422 if (BuiltinAllocaWithAlign(TheCall))
3423 return ExprError();
3424 [[fallthrough]];
3425 case Builtin::BI__builtin_alloca:
3426 case Builtin::BI__builtin_alloca_uninitialized:
3427 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3428 << TheCall->getDirectCallee();
3429 if (getLangOpts().OpenCL) {
3430 builtinAllocaAddrSpace(S&: *this, TheCall);
3431 }
3432 break;
3433 case Builtin::BI__builtin_infer_alloc_token:
3434 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3435 return ExprError();
3436 break;
3437 case Builtin::BI__arithmetic_fence:
3438 if (BuiltinArithmeticFence(TheCall))
3439 return ExprError();
3440 break;
3441 case Builtin::BI__assume:
3442 case Builtin::BI__builtin_assume:
3443 if (BuiltinAssume(TheCall))
3444 return ExprError();
3445 break;
3446 case Builtin::BI__builtin_assume_aligned:
3447 if (BuiltinAssumeAligned(TheCall))
3448 return ExprError();
3449 break;
3450 case Builtin::BI__builtin_dynamic_object_size:
3451 case Builtin::BI__builtin_object_size:
3452 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3453 return ExprError();
3454 break;
3455 case Builtin::BI__builtin_longjmp:
3456 if (BuiltinLongjmp(TheCall))
3457 return ExprError();
3458 break;
3459 case Builtin::BI__builtin_setjmp:
3460 if (BuiltinSetjmp(TheCall))
3461 return ExprError();
3462 break;
3463 case Builtin::BI__builtin_complex:
3464 if (BuiltinComplex(TheCall))
3465 return ExprError();
3466 break;
3467 case Builtin::BI__builtin_classify_type:
3468 case Builtin::BI__builtin_constant_p: {
3469 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3470 return true;
3471 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3472 if (Arg.isInvalid()) return true;
3473 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3474 TheCall->setType(Context.IntTy);
3475 break;
3476 }
3477 case Builtin::BI__builtin_launder:
3478 return BuiltinLaunder(S&: *this, TheCall);
3479 case Builtin::BI__builtin_is_within_lifetime:
3480 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3481 case Builtin::BI__builtin_trivially_relocate:
3482 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3483 case Builtin::BI__builtin_clear_padding: {
3484 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3485 return ExprError();
3486
3487 const Expr *PtrArg = TheCall->getArg(Arg: 0);
3488 const QualType PtrArgType = PtrArg->getType();
3489 if (!PtrArgType->isPointerType()) {
3490 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
3491 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3492 << "pointer";
3493 return ExprError();
3494 }
3495 QualType PointeeType = PtrArgType->getPointeeType();
3496 if (PointeeType.isConstQualified()) {
3497 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_assign_const)
3498 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3499 return ExprError();
3500 }
3501 if (RequireCompleteType(Loc: PtrArg->getBeginLoc(), T: PointeeType,
3502 DiagID: diag::err_typecheck_decl_incomplete_type))
3503 return ExprError();
3504
3505 // For non trivially copyable types, we try to match gcc's behaviour.
3506 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3507 // object, either a local variable or a function parameter passed by value
3508 auto IsAddrOfDeclExpr = [&]() {
3509 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Ctx: Context);
3510 const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: Inner);
3511 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3512 return false;
3513
3514 const Expr *Operand =
3515 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Ctx: Context);
3516 const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Operand);
3517 if (!DeclRef)
3518 return false;
3519
3520 const auto *VarDecl = dyn_cast<::clang::VarDecl>(Val: DeclRef->getDecl());
3521 if (!VarDecl || VarDecl->getType()->isReferenceType())
3522 return false;
3523
3524 // matching GCC behaviour
3525 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3526 QualType VarQType = VarDecl->getType();
3527 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3528 Context.hasSameUnqualifiedType(T1: PointeeType, T2: VarQType);
3529 };
3530
3531 if (!PointeeType.isTriviallyCopyableType(Context) &&
3532 !PointeeType->isAtomicType() // _Atomic is not copyable
3533 && !IsAddrOfDeclExpr()) {
3534 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_needs_trivial_copy)
3535 << PtrArg->getType() << PtrArg->getSourceRange();
3536 return ExprError();
3537 }
3538
3539 if (auto *Record = PointeeType->getAsRecordDecl();
3540 Record && Record->hasFlexibleArrayMember()) {
3541 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_no_flexible_array)
3542 << PointeeType << PtrArg->getSourceRange();
3543 return ExprError();
3544 }
3545
3546 break;
3547 }
3548 case Builtin::BI__sync_fetch_and_add:
3549 case Builtin::BI__sync_fetch_and_add_1:
3550 case Builtin::BI__sync_fetch_and_add_2:
3551 case Builtin::BI__sync_fetch_and_add_4:
3552 case Builtin::BI__sync_fetch_and_add_8:
3553 case Builtin::BI__sync_fetch_and_add_16:
3554 case Builtin::BI__sync_fetch_and_sub:
3555 case Builtin::BI__sync_fetch_and_sub_1:
3556 case Builtin::BI__sync_fetch_and_sub_2:
3557 case Builtin::BI__sync_fetch_and_sub_4:
3558 case Builtin::BI__sync_fetch_and_sub_8:
3559 case Builtin::BI__sync_fetch_and_sub_16:
3560 case Builtin::BI__sync_fetch_and_or:
3561 case Builtin::BI__sync_fetch_and_or_1:
3562 case Builtin::BI__sync_fetch_and_or_2:
3563 case Builtin::BI__sync_fetch_and_or_4:
3564 case Builtin::BI__sync_fetch_and_or_8:
3565 case Builtin::BI__sync_fetch_and_or_16:
3566 case Builtin::BI__sync_fetch_and_and:
3567 case Builtin::BI__sync_fetch_and_and_1:
3568 case Builtin::BI__sync_fetch_and_and_2:
3569 case Builtin::BI__sync_fetch_and_and_4:
3570 case Builtin::BI__sync_fetch_and_and_8:
3571 case Builtin::BI__sync_fetch_and_and_16:
3572 case Builtin::BI__sync_fetch_and_xor:
3573 case Builtin::BI__sync_fetch_and_xor_1:
3574 case Builtin::BI__sync_fetch_and_xor_2:
3575 case Builtin::BI__sync_fetch_and_xor_4:
3576 case Builtin::BI__sync_fetch_and_xor_8:
3577 case Builtin::BI__sync_fetch_and_xor_16:
3578 case Builtin::BI__sync_fetch_and_nand:
3579 case Builtin::BI__sync_fetch_and_nand_1:
3580 case Builtin::BI__sync_fetch_and_nand_2:
3581 case Builtin::BI__sync_fetch_and_nand_4:
3582 case Builtin::BI__sync_fetch_and_nand_8:
3583 case Builtin::BI__sync_fetch_and_nand_16:
3584 case Builtin::BI__sync_add_and_fetch:
3585 case Builtin::BI__sync_add_and_fetch_1:
3586 case Builtin::BI__sync_add_and_fetch_2:
3587 case Builtin::BI__sync_add_and_fetch_4:
3588 case Builtin::BI__sync_add_and_fetch_8:
3589 case Builtin::BI__sync_add_and_fetch_16:
3590 case Builtin::BI__sync_sub_and_fetch:
3591 case Builtin::BI__sync_sub_and_fetch_1:
3592 case Builtin::BI__sync_sub_and_fetch_2:
3593 case Builtin::BI__sync_sub_and_fetch_4:
3594 case Builtin::BI__sync_sub_and_fetch_8:
3595 case Builtin::BI__sync_sub_and_fetch_16:
3596 case Builtin::BI__sync_and_and_fetch:
3597 case Builtin::BI__sync_and_and_fetch_1:
3598 case Builtin::BI__sync_and_and_fetch_2:
3599 case Builtin::BI__sync_and_and_fetch_4:
3600 case Builtin::BI__sync_and_and_fetch_8:
3601 case Builtin::BI__sync_and_and_fetch_16:
3602 case Builtin::BI__sync_or_and_fetch:
3603 case Builtin::BI__sync_or_and_fetch_1:
3604 case Builtin::BI__sync_or_and_fetch_2:
3605 case Builtin::BI__sync_or_and_fetch_4:
3606 case Builtin::BI__sync_or_and_fetch_8:
3607 case Builtin::BI__sync_or_and_fetch_16:
3608 case Builtin::BI__sync_xor_and_fetch:
3609 case Builtin::BI__sync_xor_and_fetch_1:
3610 case Builtin::BI__sync_xor_and_fetch_2:
3611 case Builtin::BI__sync_xor_and_fetch_4:
3612 case Builtin::BI__sync_xor_and_fetch_8:
3613 case Builtin::BI__sync_xor_and_fetch_16:
3614 case Builtin::BI__sync_nand_and_fetch:
3615 case Builtin::BI__sync_nand_and_fetch_1:
3616 case Builtin::BI__sync_nand_and_fetch_2:
3617 case Builtin::BI__sync_nand_and_fetch_4:
3618 case Builtin::BI__sync_nand_and_fetch_8:
3619 case Builtin::BI__sync_nand_and_fetch_16:
3620 case Builtin::BI__sync_val_compare_and_swap:
3621 case Builtin::BI__sync_val_compare_and_swap_1:
3622 case Builtin::BI__sync_val_compare_and_swap_2:
3623 case Builtin::BI__sync_val_compare_and_swap_4:
3624 case Builtin::BI__sync_val_compare_and_swap_8:
3625 case Builtin::BI__sync_val_compare_and_swap_16:
3626 case Builtin::BI__sync_bool_compare_and_swap:
3627 case Builtin::BI__sync_bool_compare_and_swap_1:
3628 case Builtin::BI__sync_bool_compare_and_swap_2:
3629 case Builtin::BI__sync_bool_compare_and_swap_4:
3630 case Builtin::BI__sync_bool_compare_and_swap_8:
3631 case Builtin::BI__sync_bool_compare_and_swap_16:
3632 case Builtin::BI__sync_lock_test_and_set:
3633 case Builtin::BI__sync_lock_test_and_set_1:
3634 case Builtin::BI__sync_lock_test_and_set_2:
3635 case Builtin::BI__sync_lock_test_and_set_4:
3636 case Builtin::BI__sync_lock_test_and_set_8:
3637 case Builtin::BI__sync_lock_test_and_set_16:
3638 case Builtin::BI__sync_lock_release:
3639 case Builtin::BI__sync_lock_release_1:
3640 case Builtin::BI__sync_lock_release_2:
3641 case Builtin::BI__sync_lock_release_4:
3642 case Builtin::BI__sync_lock_release_8:
3643 case Builtin::BI__sync_lock_release_16:
3644 case Builtin::BI__sync_swap:
3645 case Builtin::BI__sync_swap_1:
3646 case Builtin::BI__sync_swap_2:
3647 case Builtin::BI__sync_swap_4:
3648 case Builtin::BI__sync_swap_8:
3649 case Builtin::BI__sync_swap_16:
3650 return BuiltinAtomicOverloaded(TheCallResult);
3651 case Builtin::BI__sync_synchronize:
3652 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3653 << TheCall->getCallee()->getSourceRange();
3654 break;
3655 case Builtin::BI__builtin_nontemporal_load:
3656 case Builtin::BI__builtin_nontemporal_store:
3657 return BuiltinNontemporalOverloaded(TheCallResult);
3658 case Builtin::BI__builtin_memcpy_inline: {
3659 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3660 // We warn about copying to or from `nullptr` pointers when `size` is
3661 // greater than 0. When `size` is value dependent we cannot evaluate its
3662 // value so we bail out.
3663 if (SizeOp->isValueDependent())
3664 break;
3665 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3666 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3667 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3668 }
3669 break;
3670 }
3671 case Builtin::BI__builtin_memset_inline: {
3672 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3673 // We warn about filling to `nullptr` pointers when `size` is greater than
3674 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3675 // out.
3676 if (SizeOp->isValueDependent())
3677 break;
3678 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3679 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3680 break;
3681 }
3682#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3683 case Builtin::BI##ID: \
3684 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3685#include "clang/Basic/Builtins.inc"
3686 case Builtin::BI__annotation: {
3687 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3688 if (!TT.isOSWindows() && !TT.isUEFI()) {
3689 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3690 << TheCall->getSourceRange();
3691 return ExprError();
3692 }
3693 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3694 return ExprError();
3695 break;
3696 }
3697 case Builtin::BI__builtin_annotation:
3698 if (BuiltinAnnotation(S&: *this, TheCall))
3699 return ExprError();
3700 break;
3701 case Builtin::BI__builtin_addressof:
3702 if (BuiltinAddressof(S&: *this, TheCall))
3703 return ExprError();
3704 break;
3705 case Builtin::BI__builtin_function_start:
3706 if (BuiltinFunctionStart(S&: *this, TheCall))
3707 return ExprError();
3708 break;
3709 case Builtin::BI__builtin_is_aligned:
3710 case Builtin::BI__builtin_align_up:
3711 case Builtin::BI__builtin_align_down:
3712 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3713 return ExprError();
3714 break;
3715 case Builtin::BI__builtin_add_overflow:
3716 case Builtin::BI__builtin_sub_overflow:
3717 case Builtin::BI__builtin_mul_overflow:
3718 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3719 return ExprError();
3720 break;
3721 case Builtin::BI__builtin_operator_new:
3722 case Builtin::BI__builtin_operator_delete: {
3723 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3724 ExprResult Res =
3725 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3726 return Res;
3727 }
3728 case Builtin::BI__builtin_dump_struct:
3729 return BuiltinDumpStruct(S&: *this, TheCall);
3730 case Builtin::BI__builtin_expect_with_probability: {
3731 // We first want to ensure we are called with 3 arguments
3732 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3733 return ExprError();
3734 // then check probability is constant float in range [0.0, 1.0]
3735 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3736 SmallVector<PartialDiagnosticAt, 8> Notes;
3737 Expr::EvalResult Eval;
3738 Eval.Diag = &Notes;
3739 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3740 !Eval.Val.isFloat()) {
3741 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3742 << ProbArg->getSourceRange();
3743 for (const PartialDiagnosticAt &PDiag : Notes)
3744 Diag(Loc: PDiag.first, PD: PDiag.second);
3745 return ExprError();
3746 }
3747 llvm::APFloat Probability = Eval.Val.getFloat();
3748 bool LoseInfo = false;
3749 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3750 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3751 if (!(Probability >= llvm::APFloat(0.0) &&
3752 Probability <= llvm::APFloat(1.0))) {
3753 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3754 << ProbArg->getSourceRange();
3755 return ExprError();
3756 }
3757 break;
3758 }
3759 case Builtin::BI__builtin_preserve_access_index:
3760 if (BuiltinPreserveAI(S&: *this, TheCall))
3761 return ExprError();
3762 break;
3763 case Builtin::BI__builtin_call_with_static_chain:
3764 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3765 return ExprError();
3766 break;
3767 case Builtin::BI__exception_code:
3768 case Builtin::BI_exception_code:
3769 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3770 DiagID: diag::err_seh___except_block))
3771 return ExprError();
3772 break;
3773 case Builtin::BI__exception_info:
3774 case Builtin::BI_exception_info:
3775 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3776 DiagID: diag::err_seh___except_filter))
3777 return ExprError();
3778 break;
3779 case Builtin::BI__GetExceptionInfo:
3780 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3781 return ExprError();
3782
3783 if (CheckCXXThrowOperand(
3784 ThrowLoc: TheCall->getBeginLoc(),
3785 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3786 E: TheCall))
3787 return ExprError();
3788
3789 TheCall->setType(Context.VoidPtrTy);
3790 break;
3791 case Builtin::BIaddressof:
3792 case Builtin::BI__addressof:
3793 case Builtin::BIforward:
3794 case Builtin::BIforward_like:
3795 case Builtin::BImove:
3796 case Builtin::BImove_if_noexcept:
3797 case Builtin::BIas_const: {
3798 // These are all expected to be of the form
3799 // T &/&&/* f(U &/&&)
3800 // where T and U only differ in qualification.
3801 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3802 return ExprError();
3803 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3804 QualType Result = FDecl->getReturnType();
3805 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3806 BuiltinID == Builtin::BI__addressof;
3807 if (!(Param->isReferenceType() &&
3808 (ReturnsPointer ? Result->isAnyPointerType()
3809 : Result->isReferenceType()) &&
3810 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3811 T2: Result->getPointeeType()))) {
3812 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3813 << FDecl;
3814 return ExprError();
3815 }
3816 break;
3817 }
3818 case Builtin::BI__builtin_ptrauth_strip:
3819 return PointerAuthStrip(S&: *this, Call: TheCall);
3820 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3821 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3822 case Builtin::BI__builtin_ptrauth_sign_constant:
3823 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3824 /*RequireConstant=*/true);
3825 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3826 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3827 /*RequireConstant=*/false);
3828 case Builtin::BI__builtin_ptrauth_auth:
3829 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3830 /*RequireConstant=*/false);
3831 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3832 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3833 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3834 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3835 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3836 return PointerAuthAuthWithPCAndResign(S&: *this, Call: TheCall);
3837 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3838 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3839 case Builtin::BI__builtin_ptrauth_string_discriminator:
3840 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3841
3842 case Builtin::BI__builtin_get_vtable_pointer:
3843 return GetVTablePointer(S&: *this, Call: TheCall);
3844
3845 // OpenCL v2.0, s6.13.16 - Pipe functions
3846 case Builtin::BIread_pipe:
3847 case Builtin::BIwrite_pipe:
3848 // Since those two functions are declared with var args, we need a semantic
3849 // check for the argument.
3850 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3851 return ExprError();
3852 break;
3853 case Builtin::BIreserve_read_pipe:
3854 case Builtin::BIreserve_write_pipe:
3855 case Builtin::BIwork_group_reserve_read_pipe:
3856 case Builtin::BIwork_group_reserve_write_pipe:
3857 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3858 return ExprError();
3859 break;
3860 case Builtin::BIsub_group_reserve_read_pipe:
3861 case Builtin::BIsub_group_reserve_write_pipe:
3862 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3863 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3864 return ExprError();
3865 break;
3866 case Builtin::BIcommit_read_pipe:
3867 case Builtin::BIcommit_write_pipe:
3868 case Builtin::BIwork_group_commit_read_pipe:
3869 case Builtin::BIwork_group_commit_write_pipe:
3870 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3871 return ExprError();
3872 break;
3873 case Builtin::BIsub_group_commit_read_pipe:
3874 case Builtin::BIsub_group_commit_write_pipe:
3875 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3876 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3877 return ExprError();
3878 break;
3879 case Builtin::BIget_pipe_num_packets:
3880 case Builtin::BIget_pipe_max_packets:
3881 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3882 return ExprError();
3883 break;
3884 case Builtin::BIto_global:
3885 case Builtin::BIto_local:
3886 case Builtin::BIto_private:
3887 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3888 return ExprError();
3889 break;
3890 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3891 case Builtin::BIenqueue_kernel:
3892 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3893 return ExprError();
3894 break;
3895 case Builtin::BIget_kernel_work_group_size:
3896 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3897 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3898 return ExprError();
3899 break;
3900 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3901 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3902 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3903 return ExprError();
3904 break;
3905 case Builtin::BI__builtin_os_log_format:
3906 Cleanup.setExprNeedsCleanups(true);
3907 [[fallthrough]];
3908 case Builtin::BI__builtin_os_log_format_buffer_size:
3909 if (BuiltinOSLogFormat(TheCall))
3910 return ExprError();
3911 break;
3912 case Builtin::BI__builtin_frame_address:
3913 case Builtin::BI__builtin_return_address: {
3914 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3915 return ExprError();
3916
3917 // -Wframe-address warning if non-zero passed to builtin
3918 // return/frame address.
3919 Expr::EvalResult Result;
3920 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3921 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3922 Result.Val.getInt() != 0)
3923 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3924 << ((BuiltinID == Builtin::BI__builtin_return_address)
3925 ? "__builtin_return_address"
3926 : "__builtin_frame_address")
3927 << TheCall->getSourceRange();
3928 break;
3929 }
3930
3931 case Builtin::BI__builtin_nondeterministic_value: {
3932 if (BuiltinNonDeterministicValue(TheCall))
3933 return ExprError();
3934 break;
3935 }
3936
3937 // __builtin_elementwise_abs restricts the element type to signed integers or
3938 // floating point types only.
3939 case Builtin::BI__builtin_elementwise_abs:
3940 if (PrepareBuiltinElementwiseMathOneArgCall(
3941 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3942 return ExprError();
3943 break;
3944
3945 // These builtins restrict the element type to floating point
3946 // types only.
3947 case Builtin::BI__builtin_elementwise_acos:
3948 case Builtin::BI__builtin_elementwise_asin:
3949 case Builtin::BI__builtin_elementwise_atan:
3950 case Builtin::BI__builtin_elementwise_ceil:
3951 case Builtin::BI__builtin_elementwise_cos:
3952 case Builtin::BI__builtin_elementwise_cosh:
3953 case Builtin::BI__builtin_elementwise_exp:
3954 case Builtin::BI__builtin_elementwise_exp2:
3955 case Builtin::BI__builtin_elementwise_exp10:
3956 case Builtin::BI__builtin_elementwise_floor:
3957 case Builtin::BI__builtin_elementwise_log:
3958 case Builtin::BI__builtin_elementwise_log2:
3959 case Builtin::BI__builtin_elementwise_log10:
3960 case Builtin::BI__builtin_elementwise_roundeven:
3961 case Builtin::BI__builtin_elementwise_round:
3962 case Builtin::BI__builtin_elementwise_rint:
3963 case Builtin::BI__builtin_elementwise_nearbyint:
3964 case Builtin::BI__builtin_elementwise_sin:
3965 case Builtin::BI__builtin_elementwise_sinh:
3966 case Builtin::BI__builtin_elementwise_sqrt:
3967 case Builtin::BI__builtin_elementwise_tan:
3968 case Builtin::BI__builtin_elementwise_tanh:
3969 case Builtin::BI__builtin_elementwise_trunc:
3970 case Builtin::BI__builtin_elementwise_canonicalize:
3971 if (PrepareBuiltinElementwiseMathOneArgCall(
3972 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3973 return ExprError();
3974 break;
3975 case Builtin::BI__builtin_elementwise_fma:
3976 if (BuiltinElementwiseTernaryMath(TheCall))
3977 return ExprError();
3978 break;
3979
3980 case Builtin::BI__builtin_elementwise_ldexp: {
3981 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3982 return ExprError();
3983
3984 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3985 if (A.isInvalid())
3986 return ExprError();
3987 QualType TyA = A.get()->getType();
3988 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3989 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3990 return ExprError();
3991
3992 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3993 if (Exp.isInvalid())
3994 return ExprError();
3995 QualType TyExp = Exp.get()->getType();
3996 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3997 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3998 ArgOrdinal: 2))
3999 return ExprError();
4000
4001 // Check the two arguments are either scalars or vectors of equal length.
4002 const auto *Vec0 = TyA->getAs<VectorType>();
4003 const auto *Vec1 = TyExp->getAs<VectorType>();
4004 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
4005 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
4006 if (Arg0Length != Arg1Length) {
4007 Diag(Loc: Exp.get()->getBeginLoc(),
4008 DiagID: diag::err_typecheck_vector_lengths_not_equal)
4009 << TyA << TyExp << A.get()->getSourceRange()
4010 << Exp.get()->getSourceRange();
4011 return ExprError();
4012 }
4013
4014 TheCall->setArg(Arg: 0, ArgExpr: A.get());
4015 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
4016 TheCall->setType(TyA);
4017 break;
4018 }
4019
4020 // These builtins restrict the element type to floating point
4021 // types only, and take in two arguments.
4022 case Builtin::BI__builtin_elementwise_minnum:
4023 case Builtin::BI__builtin_elementwise_maxnum:
4024 case Builtin::BI__builtin_elementwise_minimum:
4025 case Builtin::BI__builtin_elementwise_maximum:
4026 case Builtin::BI__builtin_elementwise_minimumnum:
4027 case Builtin::BI__builtin_elementwise_maximumnum:
4028 case Builtin::BI__builtin_elementwise_atan2:
4029 case Builtin::BI__builtin_elementwise_fmod:
4030 case Builtin::BI__builtin_elementwise_pow:
4031 if (BuiltinElementwiseMath(TheCall,
4032 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
4033 return ExprError();
4034 break;
4035 // These builtins restrict the element type to integer
4036 // types only.
4037 case Builtin::BI__builtin_elementwise_add_sat:
4038 case Builtin::BI__builtin_elementwise_sub_sat:
4039 case Builtin::BI__builtin_elementwise_clmul:
4040 case Builtin::BI__builtin_elementwise_pext:
4041 case Builtin::BI__builtin_elementwise_pdep:
4042 if (BuiltinElementwiseMath(TheCall,
4043 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4044 return ExprError();
4045 break;
4046 case Builtin::BI__builtin_elementwise_fshl:
4047 case Builtin::BI__builtin_elementwise_fshr:
4048 if (BuiltinElementwiseTernaryMath(
4049 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4050 return ExprError();
4051 break;
4052 case Builtin::BI__builtin_elementwise_min:
4053 case Builtin::BI__builtin_elementwise_max: {
4054 if (BuiltinElementwiseMath(TheCall))
4055 return ExprError();
4056 Expr *Arg0 = TheCall->getArg(Arg: 0);
4057 Expr *Arg1 = TheCall->getArg(Arg: 1);
4058 QualType Ty0 = Arg0->getType();
4059 QualType Ty1 = Arg1->getType();
4060 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
4061 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
4062 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
4063 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
4064 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
4065 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
4066 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
4067 break;
4068 }
4069 case Builtin::BI__builtin_elementwise_popcount:
4070 case Builtin::BI__builtin_elementwise_bitreverse:
4071 if (PrepareBuiltinElementwiseMathOneArgCall(
4072 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4073 return ExprError();
4074 break;
4075 case Builtin::BI__builtin_elementwise_copysign: {
4076 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
4077 return ExprError();
4078
4079 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4080 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4081 if (Magnitude.isInvalid() || Sign.isInvalid())
4082 return ExprError();
4083
4084 QualType MagnitudeTy = Magnitude.get()->getType();
4085 QualType SignTy = Sign.get()->getType();
4086 if (checkMathBuiltinElementType(
4087 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
4088 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
4089 checkMathBuiltinElementType(
4090 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
4091 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
4092 return ExprError();
4093 }
4094
4095 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
4096 return Diag(Loc: Sign.get()->getBeginLoc(),
4097 DiagID: diag::err_typecheck_call_different_arg_types)
4098 << MagnitudeTy << SignTy;
4099 }
4100
4101 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
4102 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
4103 TheCall->setType(Magnitude.get()->getType());
4104 break;
4105 }
4106 case Builtin::BI__builtin_elementwise_clzg:
4107 case Builtin::BI__builtin_elementwise_ctzg:
4108 // These builtins can be unary or binary. Note for empty calls we call the
4109 // unary checker in order to not emit an error that says the function
4110 // expects 2 arguments, which would be misleading.
4111 if (TheCall->getNumArgs() <= 1) {
4112 if (PrepareBuiltinElementwiseMathOneArgCall(
4113 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4114 return ExprError();
4115 } else if (BuiltinElementwiseMath(
4116 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4117 return ExprError();
4118 break;
4119 case Builtin::BI__builtin_reduce_max:
4120 case Builtin::BI__builtin_reduce_min:
4121 case Builtin::BI__builtin_reduce_maximum:
4122 case Builtin::BI__builtin_reduce_minimum:
4123 // These builtins support vectors of integers only.
4124 // TODO: ADD/MUL should support floating-point types.
4125 case Builtin::BI__builtin_reduce_add:
4126 case Builtin::BI__builtin_reduce_mul:
4127 case Builtin::BI__builtin_reduce_xor:
4128 case Builtin::BI__builtin_reduce_or:
4129 case Builtin::BI__builtin_reduce_and: {
4130 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4131 return ExprError();
4132
4133 const Expr *Arg = TheCall->getArg(Arg: 0);
4134 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
4135
4136 bool FloatOnly = BuiltinID == Builtin::BI__builtin_reduce_maximum ||
4137 BuiltinID == Builtin::BI__builtin_reduce_minimum;
4138
4139 bool IntOnly = BuiltinID == Builtin::BI__builtin_reduce_add ||
4140 BuiltinID == Builtin::BI__builtin_reduce_mul ||
4141 BuiltinID == Builtin::BI__builtin_reduce_xor ||
4142 BuiltinID == Builtin::BI__builtin_reduce_or ||
4143 BuiltinID == Builtin::BI__builtin_reduce_and;
4144
4145 if (FloatOnly) {
4146 if (ElTy.isNull() || !ElTy->isFloatingType()) {
4147 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4148 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4149 << Arg->getType();
4150 return ExprError();
4151 }
4152 } else if (IntOnly) {
4153 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4154 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4155 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4156 << Arg->getType();
4157 return ExprError();
4158 }
4159 } else if (ElTy.isNull()) {
4160 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4161 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
4162 << Arg->getType();
4163 return ExprError();
4164 }
4165
4166 TheCall->setType(ElTy);
4167 break;
4168 }
4169
4170 case Builtin::BI__builtin_reduce_assoc_fadd:
4171 case Builtin::BI__builtin_reduce_in_order_fadd: {
4172 // For in-order reductions require the user to specify the start value.
4173 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4174 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
4175 return ExprError();
4176
4177 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4178 if (Vec.isInvalid())
4179 return ExprError();
4180
4181 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
4182
4183 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
4184 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4185 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4186 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4187 << Vec.get()->getType();
4188 return ExprError();
4189 }
4190
4191 if (TheCall->getNumArgs() == 2) {
4192 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4193 if (StartValue.isInvalid())
4194 return ExprError();
4195
4196 if (!StartValue.get()->getType()->isRealFloatingType()) {
4197 Diag(Loc: StartValue.get()->getBeginLoc(),
4198 DiagID: diag::err_builtin_invalid_arg_type)
4199 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4200 << StartValue.get()->getType();
4201 return ExprError();
4202 }
4203 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
4204 }
4205
4206 TheCall->setType(ElTy);
4207 break;
4208 }
4209
4210 case Builtin::BI__builtin_matrix_transpose:
4211 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
4212
4213 case Builtin::BI__builtin_matrix_column_major_load:
4214 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
4215
4216 case Builtin::BI__builtin_matrix_column_major_store:
4217 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
4218
4219 case Builtin::BI__builtin_verbose_trap:
4220 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
4221 return ExprError();
4222 break;
4223
4224 case Builtin::BI__builtin_get_device_side_mangled_name: {
4225 auto Check = [](CallExpr *TheCall) {
4226 if (TheCall->getNumArgs() != 1)
4227 return false;
4228 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
4229 if (!DRE)
4230 return false;
4231 auto *D = DRE->getDecl();
4232 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
4233 return false;
4234 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4235 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4236 };
4237 if (!Check(TheCall)) {
4238 Diag(Loc: TheCall->getBeginLoc(),
4239 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
4240 return ExprError();
4241 }
4242 break;
4243 }
4244 case Builtin::BI__builtin_bswapg:
4245 if (BuiltinBswapg(S&: *this, TheCall))
4246 return ExprError();
4247 break;
4248 case Builtin::BI__builtin_bitreverseg:
4249 if (BuiltinBitreverseg(S&: *this, TheCall))
4250 return ExprError();
4251 break;
4252 case Builtin::BI__builtin_popcountg:
4253 if (BuiltinPopcountg(S&: *this, TheCall))
4254 return ExprError();
4255 break;
4256 case Builtin::BI__builtin_clzg:
4257 case Builtin::BI__builtin_ctzg:
4258 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
4259 return ExprError();
4260 break;
4261
4262 case Builtin::BI__builtin_stdc_rotate_left:
4263 case Builtin::BI__builtin_stdc_rotate_right:
4264 if (BuiltinRotateGeneric(S&: *this, TheCall))
4265 return ExprError();
4266 break;
4267
4268 case Builtin::BI__builtin_stdc_memreverse8:
4269 case Builtin::BIstdc_memreverse8:
4270 case Builtin::BIstdc_memreverse8u8:
4271 case Builtin::BIstdc_memreverse8u16:
4272 case Builtin::BIstdc_memreverse8u32:
4273 case Builtin::BIstdc_memreverse8u64:
4274 case Builtin::BIstdc_load8_leu8:
4275 case Builtin::BIstdc_load8_leu16:
4276 case Builtin::BIstdc_load8_leu32:
4277 case Builtin::BIstdc_load8_leu64:
4278 case Builtin::BIstdc_load8_les8:
4279 case Builtin::BIstdc_load8_les16:
4280 case Builtin::BIstdc_load8_les32:
4281 case Builtin::BIstdc_load8_les64:
4282 case Builtin::BIstdc_load8_beu8:
4283 case Builtin::BIstdc_load8_beu16:
4284 case Builtin::BIstdc_load8_beu32:
4285 case Builtin::BIstdc_load8_beu64:
4286 case Builtin::BIstdc_load8_bes8:
4287 case Builtin::BIstdc_load8_bes16:
4288 case Builtin::BIstdc_load8_bes32:
4289 case Builtin::BIstdc_load8_bes64:
4290 case Builtin::BIstdc_load8_aligned_leu8:
4291 case Builtin::BIstdc_load8_aligned_leu16:
4292 case Builtin::BIstdc_load8_aligned_leu32:
4293 case Builtin::BIstdc_load8_aligned_leu64:
4294 case Builtin::BIstdc_load8_aligned_les8:
4295 case Builtin::BIstdc_load8_aligned_les16:
4296 case Builtin::BIstdc_load8_aligned_les32:
4297 case Builtin::BIstdc_load8_aligned_les64:
4298 case Builtin::BIstdc_load8_aligned_beu8:
4299 case Builtin::BIstdc_load8_aligned_beu16:
4300 case Builtin::BIstdc_load8_aligned_beu32:
4301 case Builtin::BIstdc_load8_aligned_beu64:
4302 case Builtin::BIstdc_load8_aligned_bes8:
4303 case Builtin::BIstdc_load8_aligned_bes16:
4304 case Builtin::BIstdc_load8_aligned_bes32:
4305 case Builtin::BIstdc_load8_aligned_bes64:
4306 if (Context.getTargetInfo().getCharWidth() != 8) {
4307 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_requires_char_bit_8)
4308 << TheCall->getDirectCallee()->getName();
4309 return ExprError();
4310 }
4311 break;
4312
4313 case Builtin::BI__builtin_stdc_bit_floor:
4314 case Builtin::BI__builtin_stdc_bit_ceil:
4315 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: QualType()))
4316 return ExprError();
4317 break;
4318 case Builtin::BI__builtin_stdc_has_single_bit:
4319 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.BoolTy))
4320 return ExprError();
4321 break;
4322 case Builtin::BI__builtin_stdc_leading_zeros:
4323 case Builtin::BI__builtin_stdc_leading_ones:
4324 case Builtin::BI__builtin_stdc_trailing_zeros:
4325 case Builtin::BI__builtin_stdc_trailing_ones:
4326 case Builtin::BI__builtin_stdc_first_leading_zero:
4327 case Builtin::BI__builtin_stdc_first_leading_one:
4328 case Builtin::BI__builtin_stdc_first_trailing_zero:
4329 case Builtin::BI__builtin_stdc_first_trailing_one:
4330 case Builtin::BI__builtin_stdc_count_zeros:
4331 case Builtin::BI__builtin_stdc_count_ones:
4332 case Builtin::BI__builtin_stdc_bit_width:
4333 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.UnsignedIntTy))
4334 return ExprError();
4335 break;
4336
4337 case Builtin::BI__builtin_allow_runtime_check: {
4338 Expr *Arg = TheCall->getArg(Arg: 0);
4339 // Check if the argument is a string literal.
4340 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
4341 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4342 << Arg->getSourceRange();
4343 return ExprError();
4344 }
4345 break;
4346 }
4347
4348 case Builtin::BI__builtin_allow_sanitize_check: {
4349 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
4350 return ExprError();
4351
4352 Expr *Arg = TheCall->getArg(Arg: 0);
4353 // Check if the argument is a string literal.
4354 const StringLiteral *SanitizerName =
4355 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
4356 if (!SanitizerName) {
4357 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4358 << Arg->getSourceRange();
4359 return ExprError();
4360 }
4361 // Validate the sanitizer name.
4362 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4363 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
4364 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4365 Value: true)
4366 .Default(Value: false)) {
4367 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
4368 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4369 << Arg->getSourceRange();
4370 return ExprError();
4371 }
4372 break;
4373 }
4374 case Builtin::BI__builtin_counted_by_ref:
4375 if (BuiltinCountedByRef(TheCall))
4376 return ExprError();
4377 break;
4378 }
4379
4380 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4381 return ExprError();
4382
4383 // Since the target specific builtins for each arch overlap, only check those
4384 // of the arch we are compiling for.
4385 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
4386 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
4387 assert(Context.getAuxTargetInfo() &&
4388 "Aux Target Builtin, but not an aux target?");
4389
4390 // Host target builtins cannot be lowered for a SYCL device. Defer the
4391 // diagnostic so that they are still accepted in code that is not
4392 // reachable from device code.
4393 if (getLangOpts().SYCLIsDevice && !isUnevaluatedContext())
4394 SYCL().DiagIfDeviceCode(Loc: TheCall->getBeginLoc(),
4395 DiagID: diag::err_builtin_target_unsupported)
4396 << TheCall->getSourceRange();
4397
4398 if (CheckTSBuiltinFunctionCall(
4399 TI: *Context.getAuxTargetInfo(),
4400 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
4401 return ExprError();
4402 } else {
4403 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
4404 TheCall))
4405 return ExprError();
4406 }
4407 }
4408
4409 return TheCallResult;
4410}
4411
4412bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4413 llvm::APSInt Result;
4414 // We can't check the value of a dependent argument.
4415 Expr *Arg = TheCall->getArg(Arg: ArgNum);
4416 if (Arg->isTypeDependent() || Arg->isValueDependent())
4417 return false;
4418
4419 // Check constant-ness first.
4420 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4421 return true;
4422
4423 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4424 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4425 return false;
4426
4427 return Diag(Loc: TheCall->getBeginLoc(),
4428 DiagID: diag::err_argument_not_contiguous_bit_field)
4429 << ArgNum << Arg->getSourceRange();
4430}
4431
4432bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4433 unsigned FirstArg, FormatStringInfo *FSI) {
4434 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4435 bool IsVariadic = false;
4436 if (const FunctionType *FnTy = D->getFunctionType())
4437 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
4438 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
4439 IsVariadic = BD->isVariadic();
4440 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
4441 IsVariadic = OMD->isVariadic();
4442
4443 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4444 IsVariadic, FSI);
4445}
4446
4447bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4448 bool HasImplicitThisParam, bool IsVariadic,
4449 FormatStringInfo *FSI) {
4450 if (FirstArg == 0)
4451 FSI->ArgPassingKind = FAPK_VAList;
4452 else if (IsVariadic)
4453 FSI->ArgPassingKind = FAPK_Variadic;
4454 else
4455 FSI->ArgPassingKind = FAPK_Fixed;
4456 FSI->FormatIdx = FormatIdx - 1;
4457 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4458
4459 // The way the format attribute works in GCC, the implicit this argument
4460 // of member functions is counted. However, it doesn't appear in our own
4461 // lists, so decrement format_idx in that case.
4462 if (HasImplicitThisParam) {
4463 if(FSI->FormatIdx == 0)
4464 return false;
4465 --FSI->FormatIdx;
4466 if (FSI->FirstDataArg != 0)
4467 --FSI->FirstDataArg;
4468 }
4469 return true;
4470}
4471
4472/// Checks if a the given expression evaluates to null.
4473///
4474/// Returns true if the value evaluates to null.
4475static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4476 // Treat (smart) pointers constructed from nullptr as null, whether we can
4477 // const-evaluate them or not.
4478 // This must happen first: the smart pointer expr might have _Nonnull type!
4479 if (isa<CXXNullPtrLiteralExpr>(
4480 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
4481 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
4482 return true;
4483
4484 // If the expression has non-null type, it doesn't evaluate to null.
4485 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4486 if (*nullability == NullabilityKind::NonNull)
4487 return false;
4488 }
4489
4490 // As a special case, transparent unions initialized with zero are
4491 // considered null for the purposes of the nonnull attribute.
4492 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4493 UT &&
4494 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4495 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
4496 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
4497 Expr = ILE->getInit(Init: 0);
4498 }
4499
4500 bool Result;
4501 return (!Expr->isValueDependent() &&
4502 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
4503 !Result);
4504}
4505
4506static void CheckNonNullArgument(Sema &S,
4507 const Expr *ArgExpr,
4508 SourceLocation CallSiteLoc) {
4509 if (CheckNonNullExpr(S, Expr: ArgExpr))
4510 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
4511 PD: S.PDiag(DiagID: diag::warn_null_arg)
4512 << ArgExpr->getSourceRange());
4513}
4514
4515/// Determine whether the given type has a non-null nullability annotation.
4516static bool isNonNullType(QualType type) {
4517 if (auto nullability = type->getNullability())
4518 return *nullability == NullabilityKind::NonNull;
4519
4520 return false;
4521}
4522
4523static void CheckNonNullArguments(Sema &S,
4524 const NamedDecl *FDecl,
4525 const FunctionProtoType *Proto,
4526 ArrayRef<const Expr *> Args,
4527 SourceLocation CallSiteLoc) {
4528 assert((FDecl || Proto) && "Need a function declaration or prototype");
4529
4530 // Already checked by constant evaluator.
4531 if (S.isConstantEvaluatedContext())
4532 return;
4533 // Check the attributes attached to the method/function itself.
4534 llvm::SmallBitVector NonNullArgs;
4535 if (FDecl) {
4536 // Handle the nonnull attribute on the function/method declaration itself.
4537 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4538 if (!NonNull->args_size()) {
4539 // Easy case: all pointer arguments are nonnull.
4540 for (const auto *Arg : Args)
4541 if (S.isValidPointerAttrType(T: Arg->getType()))
4542 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4543 return;
4544 }
4545
4546 for (const ParamIdx &Idx : NonNull->args()) {
4547 unsigned IdxAST = Idx.getASTIndex();
4548 if (IdxAST >= Args.size())
4549 continue;
4550 if (NonNullArgs.empty())
4551 NonNullArgs.resize(N: Args.size());
4552 NonNullArgs.set(IdxAST);
4553 }
4554 }
4555 }
4556
4557 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4558 // Handle the nonnull attribute on the parameters of the
4559 // function/method.
4560 ArrayRef<ParmVarDecl*> parms;
4561 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4562 parms = FD->parameters();
4563 else
4564 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4565
4566 unsigned ParamIndex = 0;
4567 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4568 I != E; ++I, ++ParamIndex) {
4569 const ParmVarDecl *PVD = *I;
4570 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4571 if (NonNullArgs.empty())
4572 NonNullArgs.resize(N: Args.size());
4573
4574 NonNullArgs.set(ParamIndex);
4575 }
4576 }
4577 } else {
4578 // If we have a non-function, non-method declaration but no
4579 // function prototype, try to dig out the function prototype.
4580 if (!Proto) {
4581 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4582 QualType type = VD->getType().getNonReferenceType();
4583 if (auto pointerType = type->getAs<PointerType>())
4584 type = pointerType->getPointeeType();
4585 else if (auto blockType = type->getAs<BlockPointerType>())
4586 type = blockType->getPointeeType();
4587 // FIXME: data member pointers?
4588
4589 // Dig out the function prototype, if there is one.
4590 Proto = type->getAs<FunctionProtoType>();
4591 }
4592 }
4593
4594 // Fill in non-null argument information from the nullability
4595 // information on the parameter types (if we have them).
4596 if (Proto) {
4597 unsigned Index = 0;
4598 for (auto paramType : Proto->getParamTypes()) {
4599 if (isNonNullType(type: paramType)) {
4600 if (NonNullArgs.empty())
4601 NonNullArgs.resize(N: Args.size());
4602
4603 NonNullArgs.set(Index);
4604 }
4605
4606 ++Index;
4607 }
4608 }
4609 }
4610
4611 // Check for non-null arguments.
4612 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4613 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4614 if (NonNullArgs[ArgIndex])
4615 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4616 }
4617}
4618
4619void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4620 StringRef ParamName, QualType ArgTy,
4621 QualType ParamTy) {
4622
4623 // If a function accepts a pointer or reference type
4624 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4625 return;
4626
4627 // If the parameter is a pointer type, get the pointee type for the
4628 // argument too. If the parameter is a reference type, don't try to get
4629 // the pointee type for the argument.
4630 if (ParamTy->isPointerType())
4631 ArgTy = ArgTy->getPointeeType();
4632
4633 // Remove reference or pointer
4634 ParamTy = ParamTy->getPointeeType();
4635
4636 // Find expected alignment, and the actual alignment of the passed object.
4637 // getTypeAlignInChars requires complete types
4638 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4639 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4640 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4641 return;
4642
4643 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4644 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4645
4646 // If the argument is less aligned than the parameter, there is a
4647 // potential alignment issue.
4648 if (ArgAlign < ParamAlign)
4649 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4650 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4651 << ParamName << (FDecl != nullptr) << FDecl;
4652}
4653
4654void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4655 const Expr *ThisArg,
4656 ArrayRef<const Expr *> Args) {
4657 if (!FD || Args.empty())
4658 return;
4659 auto GetArgAt = [&](int Idx) -> const Expr * {
4660 if (Idx == LifetimeCaptureByAttr::Global ||
4661 Idx == LifetimeCaptureByAttr::Unknown)
4662 return nullptr;
4663 if (IsMemberFunction && Idx == 0)
4664 return ThisArg;
4665 return Args[Idx - IsMemberFunction];
4666 };
4667 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4668 unsigned ArgIdx) {
4669 if (!Attr)
4670 return;
4671
4672 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4673 for (int CapturingParamIdx : Attr->params()) {
4674 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4675 continue;
4676 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4677 // initialization codepath.
4678 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4679 isa<CXXConstructorDecl>(Val: FD))
4680 continue;
4681 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4682 CapturingEntity CE{.Entity: Capturing};
4683 // Ensure that 'Captured' outlives the 'Capturing' entity.
4684 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4685 }
4686 };
4687 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4688 for (const auto *A :
4689 FD->getParamDecl(i: I)->specific_attrs<LifetimeCaptureByAttr>())
4690 HandleCaptureByAttr(A, I + IsMemberFunction);
4691 // Check when the implicit object param is captured.
4692 if (IsMemberFunction) {
4693 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4694 if (!TSI)
4695 return;
4696 AttributedTypeLoc ATL;
4697 for (TypeLoc TL = TSI->getTypeLoc();
4698 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4699 TL = ATL.getModifiedLoc())
4700 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4701 }
4702}
4703
4704void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4705 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4706 bool IsMemberFunction, SourceLocation Loc,
4707 SourceRange Range, VariadicCallType CallType) {
4708
4709 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4710 llvm::any_of(Range&: Args, P: [](const Expr *E) {
4711 return E && E->isInstantiationDependent();
4712 }))
4713 return;
4714
4715 // Printf and scanf checking.
4716 llvm::SmallBitVector CheckedVarArgs;
4717 if (FDecl) {
4718 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4719 // Only create vector if there are format attributes.
4720 CheckedVarArgs.resize(N: Args.size());
4721 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4722 CheckedVarArgs);
4723 }
4724
4725 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4726 CheckedVarArgs.resize(N: Args.size());
4727 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4728 CheckedVarArgs);
4729 }
4730 }
4731
4732 // Refuse POD arguments that weren't caught by the format string
4733 // checks above.
4734 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4735 if (CallType != VariadicCallType::DoesNotApply &&
4736 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4737 unsigned NumParams = Proto ? Proto->getNumParams()
4738 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4739 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4740 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4741 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4742 : 0;
4743
4744 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4745 // Args[ArgIdx] can be null in malformed code.
4746 if (const Expr *Arg = Args[ArgIdx]) {
4747 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4748 checkVariadicArgument(E: Arg, CT: CallType);
4749 }
4750 }
4751 }
4752 if (FD)
4753 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4754 if (FDecl || Proto) {
4755 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4756
4757 // Type safety checking.
4758 if (FDecl) {
4759 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4760 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4761 }
4762 }
4763
4764 // Check that passed arguments match the alignment of original arguments.
4765 // Try to get the missing prototype from the declaration.
4766 if (!Proto && FDecl) {
4767 const auto *FT = FDecl->getFunctionType();
4768 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4769 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4770 }
4771 if (Proto) {
4772 // For variadic functions, we may have more args than parameters.
4773 // For some K&R functions, we may have less args than parameters.
4774 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4775 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4776 bool IsScalableArg = false;
4777 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4778 // Args[ArgIdx] can be null in malformed code.
4779 if (const Expr *Arg = Args[ArgIdx]) {
4780 if (Arg->containsErrors())
4781 continue;
4782
4783 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4784 FDecl->hasLinkage() &&
4785 FDecl->getFormalLinkage() != Linkage::Internal &&
4786 CallType == VariadicCallType::DoesNotApply)
4787 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4788
4789 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4790 if (ParamTy->isSizelessVectorType())
4791 IsScalableArg = true;
4792 QualType ArgTy = Arg->getType();
4793 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4794 ArgTy, ParamTy);
4795 }
4796 }
4797
4798 // If the callee has an AArch64 SME attribute to indicate that it is an
4799 // __arm_streaming function, then the caller requires SME to be available.
4800 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4801 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4802 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4803 llvm::StringMap<bool> CallerFeatureMap;
4804 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4805 if (!CallerFeatureMap.contains(Key: "sme"))
4806 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4807 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4808 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4809 }
4810 }
4811
4812 // If the call requires a streaming-mode change and has scalable vector
4813 // arguments or return values, then warn the user that the streaming and
4814 // non-streaming vector lengths may be different.
4815 // When both streaming and non-streaming vector lengths are defined and
4816 // mismatched, produce an error.
4817 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4818 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4819 (IsScalableArg || IsScalableRet)) {
4820 bool IsCalleeStreaming =
4821 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4822 bool IsCalleeStreamingCompatible =
4823 ExtInfo.AArch64SMEAttributes &
4824 FunctionType::SME_PStateSMCompatibleMask;
4825 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4826 if (!IsCalleeStreamingCompatible &&
4827 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4828 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4829 const LangOptions &LO = getLangOpts();
4830 unsigned VL = LO.VScaleMin * 128;
4831 unsigned SVL = LO.VScaleStreamingMin * 128;
4832 bool IsVLMismatch = VL && SVL && VL != SVL;
4833
4834 auto EmitDiag = [&](bool IsArg) {
4835 if (IsVLMismatch) {
4836 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4837 // Emit warning for streaming-compatible callers
4838 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4839 << IsArg << IsCalleeStreaming << SVL << VL;
4840 else
4841 // Emit error otherwise
4842 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4843 << IsArg << SVL << VL;
4844 } else
4845 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4846 << IsArg;
4847 };
4848
4849 if (IsScalableArg)
4850 EmitDiag(true);
4851 if (IsScalableRet)
4852 EmitDiag(false);
4853 }
4854 }
4855
4856 FunctionType::ArmStateValue CalleeArmZAState =
4857 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4858 FunctionType::ArmStateValue CalleeArmZT0State =
4859 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4860 if (CalleeArmZAState != FunctionType::ARM_None ||
4861 CalleeArmZT0State != FunctionType::ARM_None) {
4862 bool CallerHasZAState = false;
4863 bool CallerHasZT0State = false;
4864 if (CallerFD) {
4865 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4866 if (Attr && Attr->isNewZA())
4867 CallerHasZAState = true;
4868 if (Attr && Attr->isNewZT0())
4869 CallerHasZT0State = true;
4870 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4871 CallerHasZAState |=
4872 FunctionType::getArmZAState(
4873 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4874 FunctionType::ARM_None;
4875 CallerHasZT0State |=
4876 FunctionType::getArmZT0State(
4877 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4878 FunctionType::ARM_None;
4879 }
4880 }
4881
4882 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4883 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4884
4885 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4886 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4887
4888 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4889 CalleeArmZT0State != FunctionType::ARM_None) {
4890 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4891 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4892 }
4893 }
4894 }
4895
4896 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4897 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4898 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4899 if (!Arg->isValueDependent()) {
4900 Expr::EvalResult Align;
4901 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4902 const llvm::APSInt &I = Align.Val.getInt();
4903 if (!I.isPowerOf2())
4904 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4905 << Arg->getSourceRange();
4906
4907 if (I > Sema::MaximumAlignment)
4908 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4909 << Arg->getSourceRange() << Sema::MaximumAlignment;
4910 }
4911 }
4912 }
4913
4914 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4915 !isUnevaluatedContext())
4916 SYCL().DiagIfDeviceCode(Loc, DiagID: diag::err_variadic_device_fn)
4917 << diag::OffloadLang::SYCL;
4918
4919 // A calling convention that is supported only by the host is accepted on the
4920 // declaration, but cannot be used for a call from device code.
4921 if (Proto && getLangOpts().SYCLIsDevice && !isUnevaluatedContext()) {
4922 CallingConv CC = Proto->getCallConv();
4923 if (Context.getTargetInfo().checkCallingConvention(CC) !=
4924 TargetInfo::CCCR_OK)
4925 SYCL().DiagIfDeviceCode(Loc, DiagID: diag::warn_cconv_unsupported)
4926 << &Context.Idents.get(Name: FunctionType::getNameForCallConv(CC))
4927 << (int)CallingConventionIgnoredReason::ForThisTarget;
4928 }
4929
4930 if (FD)
4931 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4932}
4933
4934void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4935 if (TemplateDecl *Decl =
4936 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4937 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4938 }
4939}
4940
4941void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4942 ArrayRef<const Expr *> Args,
4943 const FunctionProtoType *Proto,
4944 SourceLocation Loc) {
4945 VariadicCallType CallType = Proto->isVariadic()
4946 ? VariadicCallType::Constructor
4947 : VariadicCallType::DoesNotApply;
4948
4949 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4950 CheckArgAlignment(
4951 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4952 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4953
4954 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4955 Loc, Range: SourceRange(), CallType);
4956}
4957
4958bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4959 const FunctionProtoType *Proto) {
4960 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4961 isa<CXXMethodDecl>(Val: FDecl);
4962 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4963 IsMemberOperatorCall;
4964 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4965 Fn: TheCall->getCallee());
4966 Expr** Args = TheCall->getArgs();
4967 unsigned NumArgs = TheCall->getNumArgs();
4968
4969 Expr *ImplicitThis = nullptr;
4970 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4971 // If this is a call to a member operator, hide the first
4972 // argument from checkCall.
4973 // FIXME: Our choice of AST representation here is less than ideal.
4974 ImplicitThis = Args[0];
4975 ++Args;
4976 --NumArgs;
4977 } else if (IsMemberFunction && !FDecl->isStatic() &&
4978 !FDecl->hasCXXExplicitFunctionObjectParameter())
4979 ImplicitThis =
4980 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4981
4982 if (ImplicitThis) {
4983 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4984 // used.
4985 QualType ThisType = ImplicitThis->getType();
4986 if (!ThisType->isPointerType()) {
4987 assert(!ThisType->isReferenceType());
4988 ThisType = Context.getPointerType(T: ThisType);
4989 }
4990
4991 QualType ThisTypeFromDecl = Context.getPointerType(
4992 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4993
4994 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4995 ParamTy: ThisTypeFromDecl);
4996 }
4997
4998 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4999 IsMemberFunction, Loc: TheCall->getRParenLoc(),
5000 Range: TheCall->getCallee()->getSourceRange(), CallType);
5001
5002 IdentifierInfo *FnInfo = FDecl->getIdentifier();
5003 // None of the checks below are needed for functions that don't have
5004 // simple names (e.g., C++ conversion functions).
5005 if (!FnInfo)
5006 return false;
5007
5008 // Enforce TCB except for builtin calls, which are always allowed.
5009 if (FDecl->getBuiltinID() == 0)
5010 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
5011
5012 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
5013 CheckMaxUnsignedZero(Call: TheCall, FDecl);
5014 CheckInfNaNFunction(Call: TheCall, FDecl);
5015
5016 if (getLangOpts().ObjC)
5017 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
5018
5019 unsigned CMId = FDecl->getMemoryFunctionKind();
5020
5021 // Handle memory setting and copying functions.
5022 switch (CMId) {
5023 case 0:
5024 return false;
5025 case Builtin::BIstrlcpy: // fallthrough
5026 case Builtin::BIstrlcat:
5027 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
5028 break;
5029 case Builtin::BIstrncat:
5030 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
5031 break;
5032 case Builtin::BIfree:
5033 CheckFreeArguments(E: TheCall);
5034 break;
5035 default:
5036 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
5037 }
5038
5039 return false;
5040}
5041
5042bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5043 const FunctionProtoType *Proto) {
5044 QualType Ty;
5045 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
5046 Ty = V->getType().getNonReferenceType();
5047 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
5048 Ty = F->getType().getNonReferenceType();
5049 else
5050 return false;
5051
5052 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5053 !Ty->isFunctionProtoType())
5054 return false;
5055
5056 VariadicCallType CallType;
5057 if (!Proto || !Proto->isVariadic()) {
5058 CallType = VariadicCallType::DoesNotApply;
5059 } else if (Ty->isBlockPointerType()) {
5060 CallType = VariadicCallType::Block;
5061 } else { // Ty->isFunctionPointerType()
5062 CallType = VariadicCallType::Function;
5063 }
5064
5065 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
5066 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5067 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
5068 Range: TheCall->getCallee()->getSourceRange(), CallType);
5069
5070 return false;
5071}
5072
5073bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5074 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5075 Fn: TheCall->getCallee());
5076 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5077 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5078 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
5079 Range: TheCall->getCallee()->getSourceRange(), CallType);
5080
5081 return false;
5082}
5083
5084static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5085 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
5086 return false;
5087
5088 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5089 switch (Op) {
5090 case AtomicExpr::AO__c11_atomic_init:
5091 case AtomicExpr::AO__opencl_atomic_init:
5092 llvm_unreachable("There is no ordering argument for an init");
5093
5094 case AtomicExpr::AO__c11_atomic_load:
5095 case AtomicExpr::AO__opencl_atomic_load:
5096 case AtomicExpr::AO__hip_atomic_load:
5097 case AtomicExpr::AO__atomic_load_n:
5098 case AtomicExpr::AO__atomic_load:
5099 case AtomicExpr::AO__scoped_atomic_load_n:
5100 case AtomicExpr::AO__scoped_atomic_load:
5101 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5102 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5103
5104 case AtomicExpr::AO__c11_atomic_store:
5105 case AtomicExpr::AO__opencl_atomic_store:
5106 case AtomicExpr::AO__hip_atomic_store:
5107 case AtomicExpr::AO__atomic_store:
5108 case AtomicExpr::AO__atomic_store_n:
5109 case AtomicExpr::AO__scoped_atomic_store:
5110 case AtomicExpr::AO__scoped_atomic_store_n:
5111 case AtomicExpr::AO__atomic_clear:
5112 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5113 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5114 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5115
5116 default:
5117 return true;
5118 }
5119}
5120
5121ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
5122 AtomicExpr::AtomicOp Op) {
5123 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
5124 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5125 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5126 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
5127 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
5128 Op);
5129}
5130
5131/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
5132/// equivalents. Provide a fixit when the scope is a compile-time constant and
5133/// there is a direct mapping from the HIP builtin to a Clang builtin. The
5134/// compare_exchange builtins differ in how they accept the desired value, so
5135/// only a warning (without a fixit) is emitted for those.
5136static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange,
5137 MultiExprArg Args,
5138 AtomicExpr::AtomicOp Op) {
5139 StringRef OldName;
5140 StringRef NewName;
5141 bool CanFixIt;
5142
5143 switch (Op) {
5144#define HIP_ATOMIC_FIXABLE(hip, scoped) \
5145 case AtomicExpr::AO__hip_atomic_##hip: \
5146 OldName = "__hip_atomic_" #hip; \
5147 NewName = "__scoped_atomic_" #scoped; \
5148 CanFixIt = true; \
5149 break;
5150 HIP_ATOMIC_FIXABLE(load, load_n)
5151 HIP_ATOMIC_FIXABLE(store, store_n)
5152 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
5153 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
5154 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
5155 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
5156 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
5157 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
5158 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
5159 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
5160#undef HIP_ATOMIC_FIXABLE
5161 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5162 OldName = "__hip_atomic_compare_exchange_weak";
5163 NewName = "__scoped_atomic_compare_exchange";
5164 CanFixIt = false;
5165 break;
5166 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5167 OldName = "__hip_atomic_compare_exchange_strong";
5168 NewName = "__scoped_atomic_compare_exchange";
5169 CanFixIt = false;
5170 break;
5171 default:
5172 llvm_unreachable("unhandled HIP atomic op");
5173 }
5174
5175 auto DB = S.Diag(Loc: ExprRange.getBegin(), DiagID: diag::warn_hip_deprecated_builtin)
5176 << OldName << NewName;
5177 if (!CanFixIt)
5178 return;
5179
5180 DB << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: NewName);
5181
5182 Expr *Scope = Args[Args.size() - 1];
5183 std::optional<llvm::APSInt> ScopeVal =
5184 Scope->getIntegerConstantExpr(Ctx: S.Context);
5185 if (!ScopeVal)
5186 return;
5187
5188 StringRef ScopeName;
5189 switch (ScopeVal->getZExtValue()) {
5190 case AtomicScopeHIPModel::SingleThread:
5191 ScopeName = "__MEMORY_SCOPE_SINGLE";
5192 break;
5193 case AtomicScopeHIPModel::Wavefront:
5194 ScopeName = "__MEMORY_SCOPE_WVFRNT";
5195 break;
5196 case AtomicScopeHIPModel::Workgroup:
5197 ScopeName = "__MEMORY_SCOPE_WRKGRP";
5198 break;
5199 case AtomicScopeHIPModel::Agent:
5200 ScopeName = "__MEMORY_SCOPE_DEVICE";
5201 break;
5202 case AtomicScopeHIPModel::System:
5203 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5204 break;
5205 case AtomicScopeHIPModel::Cluster:
5206 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5207 break;
5208 default:
5209 return;
5210 }
5211
5212 DB << FixItHint::CreateReplacement(
5213 RemoveRange: CharSourceRange::getTokenRange(R: Scope->getSourceRange()), Code: ScopeName);
5214}
5215
5216ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5217 SourceLocation RParenLoc, MultiExprArg Args,
5218 AtomicExpr::AtomicOp Op,
5219 AtomicArgumentOrder ArgOrder) {
5220 // All the non-OpenCL operations take one of the following forms.
5221 // The OpenCL operations take the __c11 forms with one extra argument for
5222 // synchronization scope.
5223 enum {
5224 // C __c11_atomic_init(A *, C)
5225 Init,
5226
5227 // C __c11_atomic_load(A *, int)
5228 Load,
5229
5230 // void __atomic_load(A *, CP, int)
5231 LoadCopy,
5232
5233 // void __atomic_store(A *, CP, int)
5234 Copy,
5235
5236 // C __c11_atomic_add(A *, M, int)
5237 Arithmetic,
5238
5239 // C __atomic_exchange_n(A *, CP, int)
5240 Xchg,
5241
5242 // void __atomic_exchange(A *, C *, CP, int)
5243 GNUXchg,
5244
5245 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5246 C11CmpXchg,
5247
5248 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5249 GNUCmpXchg,
5250
5251 // bool __atomic_test_and_set(A *, int)
5252 TestAndSetByte,
5253
5254 // void __atomic_clear(A *, int)
5255 ClearByte,
5256 } Form = Init;
5257
5258 const unsigned NumForm = ClearByte + 1;
5259 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5260 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5261 // where:
5262 // C is an appropriate type,
5263 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5264 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5265 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5266 // the int parameters are for orderings.
5267
5268 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5269 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5270 "need to update code for modified forms");
5271 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5272 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5273 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5274 "need to update code for modified C11 atomics");
5275 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5276 Op <= AtomicExpr::AO__opencl_atomic_store;
5277 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5278 Op <= AtomicExpr::AO__hip_atomic_store;
5279 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5280 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5281 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5282 Op <= AtomicExpr::AO__c11_atomic_store) ||
5283 IsOpenCL;
5284 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5285 Op == AtomicExpr::AO__atomic_store_n ||
5286 Op == AtomicExpr::AO__atomic_exchange_n ||
5287 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5288 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5289 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5290 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5291 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5292 // Bit mask for extra allowed value types other than integers for atomic
5293 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5294 // allow floating point.
5295 enum ArithOpExtraValueType {
5296 AOEVT_None = 0,
5297 AOEVT_Pointer = 1,
5298 AOEVT_FP = 2,
5299 AOEVT_Int = 4,
5300 };
5301 unsigned ArithAllows = AOEVT_None;
5302
5303 switch (Op) {
5304 case AtomicExpr::AO__c11_atomic_init:
5305 case AtomicExpr::AO__opencl_atomic_init:
5306 Form = Init;
5307 break;
5308
5309 case AtomicExpr::AO__c11_atomic_load:
5310 case AtomicExpr::AO__opencl_atomic_load:
5311 case AtomicExpr::AO__hip_atomic_load:
5312 case AtomicExpr::AO__atomic_load_n:
5313 case AtomicExpr::AO__scoped_atomic_load_n:
5314 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5315 Form = Load;
5316 break;
5317
5318 case AtomicExpr::AO__atomic_load:
5319 case AtomicExpr::AO__scoped_atomic_load:
5320 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5321 Form = LoadCopy;
5322 break;
5323
5324 case AtomicExpr::AO__c11_atomic_store:
5325 case AtomicExpr::AO__opencl_atomic_store:
5326 case AtomicExpr::AO__hip_atomic_store:
5327 case AtomicExpr::AO__atomic_store:
5328 case AtomicExpr::AO__atomic_store_n:
5329 case AtomicExpr::AO__scoped_atomic_store:
5330 case AtomicExpr::AO__scoped_atomic_store_n:
5331 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5332 Form = Copy;
5333 break;
5334 case AtomicExpr::AO__atomic_fetch_add:
5335 case AtomicExpr::AO__atomic_fetch_sub:
5336 case AtomicExpr::AO__atomic_add_fetch:
5337 case AtomicExpr::AO__atomic_sub_fetch:
5338 case AtomicExpr::AO__scoped_atomic_fetch_add:
5339 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5340 case AtomicExpr::AO__scoped_atomic_add_fetch:
5341 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5342 case AtomicExpr::AO__c11_atomic_fetch_add:
5343 case AtomicExpr::AO__c11_atomic_fetch_sub:
5344 case AtomicExpr::AO__opencl_atomic_fetch_add:
5345 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5346 case AtomicExpr::AO__hip_atomic_fetch_add:
5347 case AtomicExpr::AO__hip_atomic_fetch_sub:
5348 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5349 Form = Arithmetic;
5350 break;
5351 case AtomicExpr::AO__atomic_fetch_fminimum:
5352 case AtomicExpr::AO__atomic_fetch_fmaximum:
5353 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5354 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5355 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5356 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5357 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5358 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5359 ArithAllows = AOEVT_FP;
5360 Form = Arithmetic;
5361 break;
5362 case AtomicExpr::AO__atomic_fetch_max:
5363 case AtomicExpr::AO__atomic_fetch_min:
5364 case AtomicExpr::AO__atomic_max_fetch:
5365 case AtomicExpr::AO__atomic_min_fetch:
5366 case AtomicExpr::AO__scoped_atomic_fetch_max:
5367 case AtomicExpr::AO__scoped_atomic_fetch_min:
5368 case AtomicExpr::AO__scoped_atomic_max_fetch:
5369 case AtomicExpr::AO__scoped_atomic_min_fetch:
5370 case AtomicExpr::AO__c11_atomic_fetch_max:
5371 case AtomicExpr::AO__c11_atomic_fetch_min:
5372 case AtomicExpr::AO__opencl_atomic_fetch_max:
5373 case AtomicExpr::AO__opencl_atomic_fetch_min:
5374 case AtomicExpr::AO__hip_atomic_fetch_max:
5375 case AtomicExpr::AO__hip_atomic_fetch_min:
5376 ArithAllows = AOEVT_Int | AOEVT_FP;
5377 Form = Arithmetic;
5378 break;
5379 case AtomicExpr::AO__c11_atomic_fetch_and:
5380 case AtomicExpr::AO__c11_atomic_fetch_or:
5381 case AtomicExpr::AO__c11_atomic_fetch_xor:
5382 case AtomicExpr::AO__hip_atomic_fetch_and:
5383 case AtomicExpr::AO__hip_atomic_fetch_or:
5384 case AtomicExpr::AO__hip_atomic_fetch_xor:
5385 case AtomicExpr::AO__c11_atomic_fetch_nand:
5386 case AtomicExpr::AO__opencl_atomic_fetch_and:
5387 case AtomicExpr::AO__opencl_atomic_fetch_or:
5388 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5389 case AtomicExpr::AO__atomic_fetch_and:
5390 case AtomicExpr::AO__atomic_fetch_or:
5391 case AtomicExpr::AO__atomic_fetch_xor:
5392 case AtomicExpr::AO__atomic_fetch_nand:
5393 case AtomicExpr::AO__atomic_and_fetch:
5394 case AtomicExpr::AO__atomic_or_fetch:
5395 case AtomicExpr::AO__atomic_xor_fetch:
5396 case AtomicExpr::AO__atomic_nand_fetch:
5397 case AtomicExpr::AO__atomic_fetch_uinc:
5398 case AtomicExpr::AO__atomic_fetch_udec:
5399 case AtomicExpr::AO__scoped_atomic_fetch_and:
5400 case AtomicExpr::AO__scoped_atomic_fetch_or:
5401 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5402 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5403 case AtomicExpr::AO__scoped_atomic_and_fetch:
5404 case AtomicExpr::AO__scoped_atomic_or_fetch:
5405 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5406 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5407 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5408 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5409 Form = Arithmetic;
5410 break;
5411
5412 case AtomicExpr::AO__c11_atomic_exchange:
5413 case AtomicExpr::AO__hip_atomic_exchange:
5414 case AtomicExpr::AO__opencl_atomic_exchange:
5415 case AtomicExpr::AO__atomic_exchange_n:
5416 case AtomicExpr::AO__scoped_atomic_exchange_n:
5417 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5418 Form = Xchg;
5419 break;
5420
5421 case AtomicExpr::AO__atomic_exchange:
5422 case AtomicExpr::AO__scoped_atomic_exchange:
5423 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5424 Form = GNUXchg;
5425 break;
5426
5427 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5428 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5429 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5430 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5431 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5432 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5433 Form = C11CmpXchg;
5434 break;
5435
5436 case AtomicExpr::AO__atomic_compare_exchange:
5437 case AtomicExpr::AO__atomic_compare_exchange_n:
5438 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5439 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5440 ArithAllows = AOEVT_Pointer;
5441 Form = GNUCmpXchg;
5442 break;
5443
5444 case AtomicExpr::AO__atomic_test_and_set:
5445 Form = TestAndSetByte;
5446 break;
5447
5448 case AtomicExpr::AO__atomic_clear:
5449 Form = ClearByte;
5450 break;
5451 }
5452
5453 unsigned AdjustedNumArgs = NumArgs[Form];
5454 if ((IsOpenCL || IsHIP || IsScoped) &&
5455 Op != AtomicExpr::AO__opencl_atomic_init)
5456 ++AdjustedNumArgs;
5457 // Check we have the right number of arguments.
5458 if (Args.size() < AdjustedNumArgs) {
5459 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
5460 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5461 << /*is non object*/ 0 << ExprRange;
5462 return ExprError();
5463 } else if (Args.size() > AdjustedNumArgs) {
5464 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
5465 DiagID: diag::err_typecheck_call_too_many_args)
5466 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5467 << /*is non object*/ 0 << ExprRange;
5468 return ExprError();
5469 }
5470
5471 // Inspect the first argument of the atomic operation.
5472 Expr *Ptr = Args[0];
5473 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
5474 if (ConvertedPtr.isInvalid())
5475 return ExprError();
5476
5477 Ptr = ConvertedPtr.get();
5478 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5479 if (!pointerType) {
5480 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5481 << Ptr->getType() << 0 << Ptr->getSourceRange();
5482 return ExprError();
5483 }
5484
5485 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5486 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5487 QualType ValType = AtomTy; // 'C'
5488 if (IsC11) {
5489 if (!AtomTy->isAtomicType()) {
5490 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
5491 << Ptr->getType() << Ptr->getSourceRange();
5492 return ExprError();
5493 }
5494 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5495 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5496 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
5497 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5498 << Ptr->getSourceRange();
5499 return ExprError();
5500 }
5501 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5502 } else if (Form != Load && Form != LoadCopy) {
5503 if (ValType.isConstQualified()) {
5504 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
5505 << Ptr->getType() << Ptr->getSourceRange();
5506 return ExprError();
5507 }
5508 }
5509
5510 if (Form != TestAndSetByte && Form != ClearByte) {
5511 // Pointer to object of size zero is not allowed.
5512 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
5513 DiagID: diag::err_incomplete_type))
5514 return ExprError();
5515
5516 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
5517 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5518 << Ptr->getType() << 1 << Ptr->getSourceRange();
5519 return ExprError();
5520 }
5521 } else {
5522 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5523 // non-const pointer type, including void* and pointers to incomplete
5524 // structs, but only access the first byte.
5525 AtomTy = Context.CharTy;
5526 AtomTy = AtomTy.withCVRQualifiers(
5527 CVR: pointerType->getPointeeType().getCVRQualifiers());
5528 QualType PointerQT = Context.getPointerType(T: AtomTy);
5529 pointerType = PointerQT->getAs<PointerType>();
5530 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
5531 ValType = AtomTy;
5532 }
5533
5534 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5535 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5536 Diag(Loc: ExprRange.getBegin(),
5537 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5538 << 0 << Ptr->getType() << Ptr->getSourceRange();
5539 return ExprError();
5540 }
5541
5542 // For an arithmetic operation, the implied arithmetic must be well-formed.
5543 // For _n operations, the value type must also be a valid atomic type.
5544 if (Form == Arithmetic || IsN) {
5545 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5546 // trivial type errors.
5547 auto IsAllowedValueType = [&](QualType ValType,
5548 unsigned AllowedType) -> bool {
5549 bool IsX87LongDouble =
5550 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
5551 &Context.getTargetInfo().getLongDoubleFormat() ==
5552 &llvm::APFloat::x87DoubleExtended();
5553 if (ValType->isIntegerType())
5554 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5555 // integers. Explicit AOEVT_Int or other combinations allow integers.
5556 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5557 if (ValType->isPointerType())
5558 return AllowedType & AOEVT_Pointer;
5559 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5560 return false;
5561 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5562 if (IsX87LongDouble)
5563 return false;
5564 return true;
5565 };
5566 if (!IsAllowedValueType(ValType, ArithAllows)) {
5567 auto DID =
5568 ArithAllows == AOEVT_FP
5569 ? diag::err_atomic_op_needs_atomic_fp
5570 : (ArithAllows & AOEVT_FP
5571 ? (ArithAllows & AOEVT_Pointer
5572 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5573 : diag::err_atomic_op_needs_atomic_int_or_fp)
5574 : (ArithAllows & AOEVT_Pointer
5575 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5576 : diag::err_atomic_op_needs_atomic_int));
5577 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
5578 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5579 return ExprError();
5580 }
5581 if (IsC11 && ValType->isPointerType() &&
5582 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
5583 DiagID: diag::err_incomplete_type)) {
5584 return ExprError();
5585 }
5586 }
5587
5588 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5589 !AtomTy->isScalarType()) {
5590 // For GNU atomics, require a trivially-copyable type. This is not part of
5591 // the GNU atomics specification but we enforce it for consistency with
5592 // other atomics which generally all require a trivially-copyable type. This
5593 // is because atomics just copy bits.
5594 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
5595 << Ptr->getType() << Ptr->getSourceRange();
5596 return ExprError();
5597 }
5598
5599 switch (ValType.getObjCLifetime()) {
5600 case Qualifiers::OCL_None:
5601 case Qualifiers::OCL_ExplicitNone:
5602 // okay
5603 break;
5604
5605 case Qualifiers::OCL_Weak:
5606 case Qualifiers::OCL_Strong:
5607 case Qualifiers::OCL_Autoreleasing:
5608 // FIXME: Can this happen? By this point, ValType should be known
5609 // to be trivially copyable.
5610 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
5611 << ValType << Ptr->getSourceRange();
5612 return ExprError();
5613 }
5614
5615 // All atomic operations have an overload which takes a pointer to a volatile
5616 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5617 // into the result or the other operands. Similarly atomic_load takes a
5618 // pointer to a const 'A'.
5619 ValType.removeLocalVolatile();
5620 ValType.removeLocalConst();
5621 QualType ResultType = ValType;
5622 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5623 Form == ClearByte)
5624 ResultType = Context.VoidTy;
5625 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5626 ResultType = Context.BoolTy;
5627
5628 // The type of a parameter passed 'by value'. In the GNU atomics, such
5629 // arguments are actually passed as pointers.
5630 QualType ByValType = ValType; // 'CP'
5631 bool IsPassedByAddress = false;
5632 if (!IsC11 && !IsHIP && !IsN) {
5633 ByValType = Ptr->getType();
5634 IsPassedByAddress = true;
5635 }
5636
5637 SmallVector<Expr *, 5> APIOrderedArgs;
5638 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5639 APIOrderedArgs.push_back(Elt: Args[0]);
5640 switch (Form) {
5641 case Init:
5642 case Load:
5643 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
5644 break;
5645 case LoadCopy:
5646 case Copy:
5647 case Arithmetic:
5648 case Xchg:
5649 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5650 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5651 break;
5652 case GNUXchg:
5653 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5654 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
5655 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5656 break;
5657 case C11CmpXchg:
5658 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5659 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5660 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5661 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5662 break;
5663 case GNUCmpXchg:
5664 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5665 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5666 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5667 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5668 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5669 break;
5670 case TestAndSetByte:
5671 case ClearByte:
5672 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5673 break;
5674 }
5675 } else
5676 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5677
5678 // The first argument's non-CV pointer type is used to deduce the type of
5679 // subsequent arguments, except for:
5680 // - weak flag (always converted to bool)
5681 // - memory order (always converted to int)
5682 // - scope (always converted to int)
5683 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5684 QualType Ty;
5685 if (i < NumVals[Form] + 1) {
5686 switch (i) {
5687 case 0:
5688 // The first argument is always a pointer. It has a fixed type.
5689 // It is always dereferenced, a nullptr is undefined.
5690 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5691 // Nothing else to do: we already know all we want about this pointer.
5692 continue;
5693 case 1:
5694 // The second argument is the non-atomic operand. For arithmetic, this
5695 // is always passed by value, and for a compare_exchange it is always
5696 // passed by address. For the rest, GNU uses by-address and C11 uses
5697 // by-value.
5698 assert(Form != Load);
5699 if (Form == Arithmetic && ValType->isPointerType())
5700 Ty = Context.getPointerDiffType();
5701 else if (Form == Init || Form == Arithmetic)
5702 Ty = ValType;
5703 else if (Form == Copy || Form == Xchg) {
5704 if (IsPassedByAddress) {
5705 // The value pointer is always dereferenced, a nullptr is undefined.
5706 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5707 CallSiteLoc: ExprRange.getBegin());
5708 }
5709 Ty = ByValType;
5710 } else {
5711 Expr *ValArg = APIOrderedArgs[i];
5712 // The value pointer is always dereferenced, a nullptr is undefined.
5713 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5714 LangAS AS = LangAS::Default;
5715 // Keep address space of non-atomic pointer type.
5716 if (const PointerType *PtrTy =
5717 ValArg->getType()->getAs<PointerType>()) {
5718 AS = PtrTy->getPointeeType().getAddressSpace();
5719 }
5720 Ty = Context.getPointerType(
5721 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5722 }
5723 break;
5724 case 2:
5725 // The third argument to compare_exchange / GNU exchange is the desired
5726 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5727 if (IsPassedByAddress)
5728 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5729 Ty = ByValType;
5730 break;
5731 case 3:
5732 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5733 Ty = Context.BoolTy;
5734 break;
5735 }
5736 } else {
5737 // The order(s) and scope are always converted to int.
5738 Ty = Context.IntTy;
5739 }
5740
5741 InitializedEntity Entity =
5742 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5743 ExprResult Arg = APIOrderedArgs[i];
5744 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5745 if (Arg.isInvalid())
5746 return true;
5747 APIOrderedArgs[i] = Arg.get();
5748 }
5749
5750 // Permute the arguments into a 'consistent' order.
5751 SmallVector<Expr*, 5> SubExprs;
5752 SubExprs.push_back(Elt: Ptr);
5753 switch (Form) {
5754 case Init:
5755 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5756 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5757 break;
5758 case Load:
5759 case TestAndSetByte:
5760 case ClearByte:
5761 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5762 break;
5763 case LoadCopy:
5764 case Copy:
5765 case Arithmetic:
5766 case Xchg:
5767 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5768 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5769 break;
5770 case GNUXchg:
5771 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5772 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5773 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5774 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5775 break;
5776 case C11CmpXchg:
5777 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5778 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5779 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5780 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5781 break;
5782 case GNUCmpXchg:
5783 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5784 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5785 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5786 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5787 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5788 break;
5789 }
5790
5791 // If the memory orders are constants, check they are valid.
5792 if (SubExprs.size() >= 2 && Form != Init) {
5793 std::optional<llvm::APSInt> Success =
5794 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5795 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5796 Diag(Loc: SubExprs[1]->getBeginLoc(),
5797 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5798 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5799 << SubExprs[1]->getSourceRange();
5800 }
5801 if (SubExprs.size() >= 5) {
5802 if (std::optional<llvm::APSInt> Failure =
5803 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5804 if (!llvm::is_contained(
5805 Set: {llvm::AtomicOrderingCABI::relaxed,
5806 llvm::AtomicOrderingCABI::consume,
5807 llvm::AtomicOrderingCABI::acquire,
5808 llvm::AtomicOrderingCABI::seq_cst},
5809 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5810 Diag(Loc: SubExprs[3]->getBeginLoc(),
5811 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5812 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5813 }
5814 }
5815 }
5816 }
5817
5818 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5819 auto *Scope = Args[Args.size() - 1];
5820 if (std::optional<llvm::APSInt> Result =
5821 Scope->getIntegerConstantExpr(Ctx: Context)) {
5822 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5823 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5824 << Scope->getSourceRange();
5825 }
5826 SubExprs.push_back(Elt: Scope);
5827 }
5828
5829 if (IsHIP)
5830 DiagnoseDeprecatedHIPAtomic(S&: *this, ExprRange, Args, Op);
5831
5832 AtomicExpr *AE = new (Context)
5833 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5834
5835 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5836 Op == AtomicExpr::AO__c11_atomic_store ||
5837 Op == AtomicExpr::AO__opencl_atomic_load ||
5838 Op == AtomicExpr::AO__hip_atomic_load ||
5839 Op == AtomicExpr::AO__opencl_atomic_store ||
5840 Op == AtomicExpr::AO__hip_atomic_store) &&
5841 Context.AtomicUsesUnsupportedLibcall(E: AE))
5842 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5843 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5844 Op == AtomicExpr::AO__opencl_atomic_load ||
5845 Op == AtomicExpr::AO__hip_atomic_load)
5846 ? 0
5847 : 1);
5848
5849 if (ValType->isBitIntType()) {
5850 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5851 return ExprError();
5852 }
5853
5854 return AE;
5855}
5856
5857/// checkBuiltinArgument - Given a call to a builtin function, perform
5858/// normal type-checking on the given argument, updating the call in
5859/// place. This is useful when a builtin function requires custom
5860/// type-checking for some of its arguments but not necessarily all of
5861/// them.
5862///
5863/// Returns true on error.
5864static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5865 FunctionDecl *Fn = E->getDirectCallee();
5866 assert(Fn && "builtin call without direct callee!");
5867
5868 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5869 InitializedEntity Entity =
5870 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5871
5872 ExprResult Arg = E->getArg(Arg: ArgIndex);
5873 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5874 if (Arg.isInvalid())
5875 return true;
5876
5877 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5878 return false;
5879}
5880
5881ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5882 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5883 Expr *Callee = TheCall->getCallee();
5884 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5885 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5886
5887 // Ensure that we have at least one argument to do type inference from.
5888 if (TheCall->getNumArgs() < 1) {
5889 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5890 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5891 << Callee->getSourceRange();
5892 return ExprError();
5893 }
5894
5895 // Inspect the first argument of the atomic builtin. This should always be
5896 // a pointer type, whose element is an integral scalar or pointer type.
5897 // Because it is a pointer type, we don't have to worry about any implicit
5898 // casts here.
5899 // FIXME: We don't allow floating point scalars as input.
5900 Expr *FirstArg = TheCall->getArg(Arg: 0);
5901 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5902 if (FirstArgResult.isInvalid())
5903 return ExprError();
5904 FirstArg = FirstArgResult.get();
5905 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5906
5907 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5908 if (!pointerType) {
5909 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5910 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5911 return ExprError();
5912 }
5913
5914 QualType ValType = pointerType->getPointeeType();
5915 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5916 !ValType->isBlockPointerType()) {
5917 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5918 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5919 return ExprError();
5920 }
5921 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5922 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5923 Diag(Loc: FirstArg->getBeginLoc(),
5924 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5925 << 1 << ValType << FirstArg->getSourceRange();
5926 return ExprError();
5927 }
5928
5929 if (ValType.isConstQualified()) {
5930 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5931 << FirstArg->getType() << FirstArg->getSourceRange();
5932 return ExprError();
5933 }
5934
5935 switch (ValType.getObjCLifetime()) {
5936 case Qualifiers::OCL_None:
5937 case Qualifiers::OCL_ExplicitNone:
5938 // okay
5939 break;
5940
5941 case Qualifiers::OCL_Weak:
5942 case Qualifiers::OCL_Strong:
5943 case Qualifiers::OCL_Autoreleasing:
5944 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5945 << ValType << FirstArg->getSourceRange();
5946
5947 return ExprError();
5948 }
5949
5950 // Strip any qualifiers off ValType.
5951 ValType = ValType.getUnqualifiedType();
5952
5953 // The majority of builtins return a value, but a few have special return
5954 // types, so allow them to override appropriately below.
5955 QualType ResultType = ValType;
5956
5957 // We need to figure out which concrete builtin this maps onto. For example,
5958 // __sync_fetch_and_add with a 2 byte object turns into
5959 // __sync_fetch_and_add_2.
5960#define BUILTIN_ROW(x) \
5961 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5962 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5963
5964 static const unsigned BuiltinIndices[][5] = {
5965 BUILTIN_ROW(__sync_fetch_and_add),
5966 BUILTIN_ROW(__sync_fetch_and_sub),
5967 BUILTIN_ROW(__sync_fetch_and_or),
5968 BUILTIN_ROW(__sync_fetch_and_and),
5969 BUILTIN_ROW(__sync_fetch_and_xor),
5970 BUILTIN_ROW(__sync_fetch_and_nand),
5971
5972 BUILTIN_ROW(__sync_add_and_fetch),
5973 BUILTIN_ROW(__sync_sub_and_fetch),
5974 BUILTIN_ROW(__sync_and_and_fetch),
5975 BUILTIN_ROW(__sync_or_and_fetch),
5976 BUILTIN_ROW(__sync_xor_and_fetch),
5977 BUILTIN_ROW(__sync_nand_and_fetch),
5978
5979 BUILTIN_ROW(__sync_val_compare_and_swap),
5980 BUILTIN_ROW(__sync_bool_compare_and_swap),
5981 BUILTIN_ROW(__sync_lock_test_and_set),
5982 BUILTIN_ROW(__sync_lock_release),
5983 BUILTIN_ROW(__sync_swap)
5984 };
5985#undef BUILTIN_ROW
5986
5987 // Determine the index of the size.
5988 unsigned SizeIndex;
5989 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5990 case 1: SizeIndex = 0; break;
5991 case 2: SizeIndex = 1; break;
5992 case 4: SizeIndex = 2; break;
5993 case 8: SizeIndex = 3; break;
5994 case 16: SizeIndex = 4; break;
5995 default:
5996 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5997 << FirstArg->getType() << FirstArg->getSourceRange();
5998 return ExprError();
5999 }
6000
6001 // Each of these builtins has one pointer argument, followed by some number of
6002 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
6003 // that we ignore. Find out which row of BuiltinIndices to read from as well
6004 // as the number of fixed args.
6005 unsigned BuiltinID = FDecl->getBuiltinID();
6006 unsigned BuiltinIndex, NumFixed = 1;
6007 bool WarnAboutSemanticsChange = false;
6008 switch (BuiltinID) {
6009 default: llvm_unreachable("Unknown overloaded atomic builtin!");
6010 case Builtin::BI__sync_fetch_and_add:
6011 case Builtin::BI__sync_fetch_and_add_1:
6012 case Builtin::BI__sync_fetch_and_add_2:
6013 case Builtin::BI__sync_fetch_and_add_4:
6014 case Builtin::BI__sync_fetch_and_add_8:
6015 case Builtin::BI__sync_fetch_and_add_16:
6016 BuiltinIndex = 0;
6017 break;
6018
6019 case Builtin::BI__sync_fetch_and_sub:
6020 case Builtin::BI__sync_fetch_and_sub_1:
6021 case Builtin::BI__sync_fetch_and_sub_2:
6022 case Builtin::BI__sync_fetch_and_sub_4:
6023 case Builtin::BI__sync_fetch_and_sub_8:
6024 case Builtin::BI__sync_fetch_and_sub_16:
6025 BuiltinIndex = 1;
6026 break;
6027
6028 case Builtin::BI__sync_fetch_and_or:
6029 case Builtin::BI__sync_fetch_and_or_1:
6030 case Builtin::BI__sync_fetch_and_or_2:
6031 case Builtin::BI__sync_fetch_and_or_4:
6032 case Builtin::BI__sync_fetch_and_or_8:
6033 case Builtin::BI__sync_fetch_and_or_16:
6034 BuiltinIndex = 2;
6035 break;
6036
6037 case Builtin::BI__sync_fetch_and_and:
6038 case Builtin::BI__sync_fetch_and_and_1:
6039 case Builtin::BI__sync_fetch_and_and_2:
6040 case Builtin::BI__sync_fetch_and_and_4:
6041 case Builtin::BI__sync_fetch_and_and_8:
6042 case Builtin::BI__sync_fetch_and_and_16:
6043 BuiltinIndex = 3;
6044 break;
6045
6046 case Builtin::BI__sync_fetch_and_xor:
6047 case Builtin::BI__sync_fetch_and_xor_1:
6048 case Builtin::BI__sync_fetch_and_xor_2:
6049 case Builtin::BI__sync_fetch_and_xor_4:
6050 case Builtin::BI__sync_fetch_and_xor_8:
6051 case Builtin::BI__sync_fetch_and_xor_16:
6052 BuiltinIndex = 4;
6053 break;
6054
6055 case Builtin::BI__sync_fetch_and_nand:
6056 case Builtin::BI__sync_fetch_and_nand_1:
6057 case Builtin::BI__sync_fetch_and_nand_2:
6058 case Builtin::BI__sync_fetch_and_nand_4:
6059 case Builtin::BI__sync_fetch_and_nand_8:
6060 case Builtin::BI__sync_fetch_and_nand_16:
6061 BuiltinIndex = 5;
6062 WarnAboutSemanticsChange = true;
6063 break;
6064
6065 case Builtin::BI__sync_add_and_fetch:
6066 case Builtin::BI__sync_add_and_fetch_1:
6067 case Builtin::BI__sync_add_and_fetch_2:
6068 case Builtin::BI__sync_add_and_fetch_4:
6069 case Builtin::BI__sync_add_and_fetch_8:
6070 case Builtin::BI__sync_add_and_fetch_16:
6071 BuiltinIndex = 6;
6072 break;
6073
6074 case Builtin::BI__sync_sub_and_fetch:
6075 case Builtin::BI__sync_sub_and_fetch_1:
6076 case Builtin::BI__sync_sub_and_fetch_2:
6077 case Builtin::BI__sync_sub_and_fetch_4:
6078 case Builtin::BI__sync_sub_and_fetch_8:
6079 case Builtin::BI__sync_sub_and_fetch_16:
6080 BuiltinIndex = 7;
6081 break;
6082
6083 case Builtin::BI__sync_and_and_fetch:
6084 case Builtin::BI__sync_and_and_fetch_1:
6085 case Builtin::BI__sync_and_and_fetch_2:
6086 case Builtin::BI__sync_and_and_fetch_4:
6087 case Builtin::BI__sync_and_and_fetch_8:
6088 case Builtin::BI__sync_and_and_fetch_16:
6089 BuiltinIndex = 8;
6090 break;
6091
6092 case Builtin::BI__sync_or_and_fetch:
6093 case Builtin::BI__sync_or_and_fetch_1:
6094 case Builtin::BI__sync_or_and_fetch_2:
6095 case Builtin::BI__sync_or_and_fetch_4:
6096 case Builtin::BI__sync_or_and_fetch_8:
6097 case Builtin::BI__sync_or_and_fetch_16:
6098 BuiltinIndex = 9;
6099 break;
6100
6101 case Builtin::BI__sync_xor_and_fetch:
6102 case Builtin::BI__sync_xor_and_fetch_1:
6103 case Builtin::BI__sync_xor_and_fetch_2:
6104 case Builtin::BI__sync_xor_and_fetch_4:
6105 case Builtin::BI__sync_xor_and_fetch_8:
6106 case Builtin::BI__sync_xor_and_fetch_16:
6107 BuiltinIndex = 10;
6108 break;
6109
6110 case Builtin::BI__sync_nand_and_fetch:
6111 case Builtin::BI__sync_nand_and_fetch_1:
6112 case Builtin::BI__sync_nand_and_fetch_2:
6113 case Builtin::BI__sync_nand_and_fetch_4:
6114 case Builtin::BI__sync_nand_and_fetch_8:
6115 case Builtin::BI__sync_nand_and_fetch_16:
6116 BuiltinIndex = 11;
6117 WarnAboutSemanticsChange = true;
6118 break;
6119
6120 case Builtin::BI__sync_val_compare_and_swap:
6121 case Builtin::BI__sync_val_compare_and_swap_1:
6122 case Builtin::BI__sync_val_compare_and_swap_2:
6123 case Builtin::BI__sync_val_compare_and_swap_4:
6124 case Builtin::BI__sync_val_compare_and_swap_8:
6125 case Builtin::BI__sync_val_compare_and_swap_16:
6126 BuiltinIndex = 12;
6127 NumFixed = 2;
6128 break;
6129
6130 case Builtin::BI__sync_bool_compare_and_swap:
6131 case Builtin::BI__sync_bool_compare_and_swap_1:
6132 case Builtin::BI__sync_bool_compare_and_swap_2:
6133 case Builtin::BI__sync_bool_compare_and_swap_4:
6134 case Builtin::BI__sync_bool_compare_and_swap_8:
6135 case Builtin::BI__sync_bool_compare_and_swap_16:
6136 BuiltinIndex = 13;
6137 NumFixed = 2;
6138 ResultType = Context.BoolTy;
6139 break;
6140
6141 case Builtin::BI__sync_lock_test_and_set:
6142 case Builtin::BI__sync_lock_test_and_set_1:
6143 case Builtin::BI__sync_lock_test_and_set_2:
6144 case Builtin::BI__sync_lock_test_and_set_4:
6145 case Builtin::BI__sync_lock_test_and_set_8:
6146 case Builtin::BI__sync_lock_test_and_set_16:
6147 BuiltinIndex = 14;
6148 break;
6149
6150 case Builtin::BI__sync_lock_release:
6151 case Builtin::BI__sync_lock_release_1:
6152 case Builtin::BI__sync_lock_release_2:
6153 case Builtin::BI__sync_lock_release_4:
6154 case Builtin::BI__sync_lock_release_8:
6155 case Builtin::BI__sync_lock_release_16:
6156 BuiltinIndex = 15;
6157 NumFixed = 0;
6158 ResultType = Context.VoidTy;
6159 break;
6160
6161 case Builtin::BI__sync_swap:
6162 case Builtin::BI__sync_swap_1:
6163 case Builtin::BI__sync_swap_2:
6164 case Builtin::BI__sync_swap_4:
6165 case Builtin::BI__sync_swap_8:
6166 case Builtin::BI__sync_swap_16:
6167 BuiltinIndex = 16;
6168 break;
6169 }
6170
6171 // Now that we know how many fixed arguments we expect, first check that we
6172 // have at least that many.
6173 if (TheCall->getNumArgs() < 1+NumFixed) {
6174 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
6175 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
6176 << Callee->getSourceRange();
6177 return ExprError();
6178 }
6179
6180 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
6181 << Callee->getSourceRange();
6182
6183 if (WarnAboutSemanticsChange) {
6184 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
6185 << Callee->getSourceRange();
6186 }
6187
6188 // Get the decl for the concrete builtin from this, we can tell what the
6189 // concrete integer type we should convert to is.
6190 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6191 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
6192 FunctionDecl *NewBuiltinDecl;
6193 if (NewBuiltinID == BuiltinID)
6194 NewBuiltinDecl = FDecl;
6195 else {
6196 // Perform builtin lookup to avoid redeclaring it.
6197 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
6198 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6199 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
6200 assert(Res.getFoundDecl());
6201 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
6202 if (!NewBuiltinDecl)
6203 return ExprError();
6204 }
6205
6206 // The first argument --- the pointer --- has a fixed type; we
6207 // deduce the types of the rest of the arguments accordingly. Walk
6208 // the remaining arguments, converting them to the deduced value type.
6209 for (unsigned i = 0; i != NumFixed; ++i) {
6210 ExprResult Arg = TheCall->getArg(Arg: i+1);
6211
6212 // GCC does an implicit conversion to the pointer or integer ValType. This
6213 // can fail in some cases (1i -> int**), check for this error case now.
6214 // Initialize the argument.
6215 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6216 Type: ValType, /*consume*/ Consumed: false);
6217 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6218 if (Arg.isInvalid())
6219 return ExprError();
6220
6221 // Okay, we have something that *can* be converted to the right type. Check
6222 // to see if there is a potentially weird extension going on here. This can
6223 // happen when you do an atomic operation on something like an char* and
6224 // pass in 42. The 42 gets converted to char. This is even more strange
6225 // for things like 45.123 -> char, etc.
6226 // FIXME: Do this check.
6227 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
6228 }
6229
6230 // Create a new DeclRefExpr to refer to the new decl.
6231 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6232 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
6233 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
6234 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6235
6236 // Set the callee in the CallExpr.
6237 // FIXME: This loses syntactic information.
6238 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
6239 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
6240 CK: CK_BuiltinFnToFnPtr);
6241 TheCall->setCallee(PromotedCall.get());
6242
6243 // Change the result type of the call to match the original value type. This
6244 // is arbitrary, but the codegen for these builtins ins design to handle it
6245 // gracefully.
6246 TheCall->setType(ResultType);
6247
6248 // Prohibit problematic uses of bit-precise integer types with atomic
6249 // builtins. The arguments would have already been converted to the first
6250 // argument's type, so only need to check the first argument.
6251 const auto *BitIntValType = ValType->getAs<BitIntType>();
6252 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
6253 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
6254 return ExprError();
6255 }
6256
6257 return TheCallResult;
6258}
6259
6260ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6261 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6262 DeclRefExpr *DRE =
6263 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6264 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6265 unsigned BuiltinID = FDecl->getBuiltinID();
6266 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6267 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6268 "Unexpected nontemporal load/store builtin!");
6269 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6270 unsigned numArgs = isStore ? 2 : 1;
6271
6272 // Ensure that we have the proper number of arguments.
6273 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
6274 return ExprError();
6275
6276 // Inspect the last argument of the nontemporal builtin. This should always
6277 // be a pointer type, from which we imply the type of the memory access.
6278 // Because it is a pointer type, we don't have to worry about any implicit
6279 // casts here.
6280 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
6281 ExprResult PointerArgResult =
6282 DefaultFunctionArrayLvalueConversion(E: PointerArg);
6283
6284 if (PointerArgResult.isInvalid())
6285 return ExprError();
6286 PointerArg = PointerArgResult.get();
6287 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
6288
6289 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6290 if (!pointerType) {
6291 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
6292 << PointerArg->getType() << PointerArg->getSourceRange();
6293 return ExprError();
6294 }
6295
6296 QualType ValType = pointerType->getPointeeType();
6297
6298 // Strip any qualifiers off ValType.
6299 ValType = ValType.getUnqualifiedType();
6300 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6301 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6302 !ValType->isVectorType()) {
6303 Diag(Loc: DRE->getBeginLoc(),
6304 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6305 << PointerArg->getType() << PointerArg->getSourceRange();
6306 return ExprError();
6307 }
6308
6309 if (!isStore) {
6310 TheCall->setType(ValType);
6311 return TheCallResult;
6312 }
6313
6314 ExprResult ValArg = TheCall->getArg(Arg: 0);
6315 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6316 Context, Type: ValType, /*consume*/ Consumed: false);
6317 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
6318 if (ValArg.isInvalid())
6319 return ExprError();
6320
6321 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
6322 TheCall->setType(Context.VoidTy);
6323 return TheCallResult;
6324}
6325
6326/// CheckObjCString - Checks that the format string argument to the os_log()
6327/// and os_trace() functions is correct, and converts it to const char *.
6328ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6329 Arg = Arg->IgnoreParenCasts();
6330 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
6331 if (!Literal) {
6332 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
6333 Literal = ObjcLiteral->getString();
6334 }
6335 }
6336
6337 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6338 return ExprError(
6339 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
6340 << Arg->getSourceRange());
6341 }
6342
6343 ExprResult Result(Literal);
6344 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
6345 InitializedEntity Entity =
6346 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
6347 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
6348 return Result;
6349}
6350
6351/// Check that the user is calling the appropriate va_start builtin for the
6352/// target and calling convention.
6353static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6354 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6355 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6356 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6357 TT.getArch() == llvm::Triple::aarch64_32);
6358 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6359 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6360 if (IsX64 || IsAArch64) {
6361 CallingConv CC = CC_C;
6362 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6363 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6364 if (IsMSVAStart) {
6365 // Don't allow this in System V ABI functions.
6366 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6367 return S.Diag(Loc: Fn->getBeginLoc(),
6368 DiagID: diag::err_ms_va_start_used_in_sysv_function);
6369 } else {
6370 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6371 // On x64 Windows, don't allow this in System V ABI functions.
6372 // (Yes, that means there's no corresponding way to support variadic
6373 // System V ABI functions on Windows.)
6374 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6375 (!IsWindowsOrUEFI && CC == CC_Win64))
6376 return S.Diag(Loc: Fn->getBeginLoc(),
6377 DiagID: diag::err_va_start_used_in_wrong_abi_function)
6378 << !IsWindowsOrUEFI;
6379 }
6380 return false;
6381 }
6382
6383 if (IsMSVAStart)
6384 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
6385 return false;
6386}
6387
6388static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6389 ParmVarDecl **LastParam = nullptr) {
6390 // Determine whether the current function, block, or obj-c method is variadic
6391 // and get its parameter list.
6392 bool IsVariadic = false;
6393 ArrayRef<ParmVarDecl *> Params;
6394 DeclContext *Caller =
6395 S.CurContext->getEnclosingNonExpansionStatementContext();
6396 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
6397 IsVariadic = Block->isVariadic();
6398 Params = Block->parameters();
6399 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
6400 IsVariadic = FD->isVariadic();
6401 Params = FD->parameters();
6402 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
6403 IsVariadic = MD->isVariadic();
6404 // FIXME: This isn't correct for methods (results in bogus warning).
6405 Params = MD->parameters();
6406 } else if (isa<CapturedDecl>(Val: Caller)) {
6407 // We don't support va_start in a CapturedDecl.
6408 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
6409 return true;
6410 } else {
6411 // This must be some other declcontext that parses exprs.
6412 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
6413 return true;
6414 }
6415
6416 if (!IsVariadic) {
6417 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
6418 return true;
6419 }
6420
6421 if (LastParam)
6422 *LastParam = Params.empty() ? nullptr : Params.back();
6423
6424 return false;
6425}
6426
6427bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6428 Expr *Fn = TheCall->getCallee();
6429 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
6430 return true;
6431
6432 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6433 // This builtin requires one argument (the va_list), allows two arguments,
6434 // but diagnoses more than two arguments. e.g.,
6435 // __builtin_c23_va_start(); // error
6436 // __builtin_c23_va_start(list); // ok
6437 // __builtin_c23_va_start(list, param); // ok
6438 // __builtin_c23_va_start(list, anything, anything); // error
6439 // This differs from the GCC behavior in that they accept the last case
6440 // with a warning, but it doesn't seem like a useful behavior to allow.
6441 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
6442 return true;
6443 } else {
6444 // In C23 mode, va_start only needs one argument. However, the builtin still
6445 // requires two arguments (which matches the behavior of the GCC builtin),
6446 // <stdarg.h> passes `0` as the second argument in C23 mode.
6447 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6448 return true;
6449 }
6450
6451 // Type-check the first argument normally.
6452 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
6453 return true;
6454
6455 // Check that the current function is variadic, and get its last parameter.
6456 ParmVarDecl *LastParam;
6457 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
6458 return true;
6459
6460 // Verify that the second argument to the builtin is the last non-variadic
6461 // argument of the current function or method. In C23 mode, if the call is
6462 // not to __builtin_c23_va_start, and the second argument is an integer
6463 // constant expression with value 0, then we don't bother with this check.
6464 // For __builtin_c23_va_start, we only perform the check for the second
6465 // argument being the last argument to the current function if there is a
6466 // second argument present.
6467 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6468 TheCall->getNumArgs() < 2) {
6469 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6470 return false;
6471 }
6472
6473 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
6474 if (std::optional<llvm::APSInt> Val =
6475 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
6476 Val && LangOpts.C23 && *Val == 0 &&
6477 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6478 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6479 return false;
6480 }
6481
6482 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6483 // next block.
6484 QualType Type;
6485 SourceLocation ParamLoc;
6486 bool IsCRegister = false;
6487 bool SecondArgIsLastNonVariadicArgument = false;
6488 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
6489 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
6490 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6491
6492 Type = PV->getType();
6493 ParamLoc = PV->getLocation();
6494 IsCRegister =
6495 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6496 }
6497 }
6498
6499 if (!SecondArgIsLastNonVariadicArgument)
6500 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
6501 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6502 else if (IsCRegister || Type->isReferenceType() ||
6503 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
6504 // Promotable integers are UB, but enumerations need a bit of
6505 // extra checking to see what their promotable type actually is.
6506 if (!Context.isPromotableIntegerType(T: Type))
6507 return false;
6508 const auto *ED = Type->getAsEnumDecl();
6509 if (!ED)
6510 return true;
6511 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
6512 }()) {
6513 unsigned Reason = 0;
6514 if (Type->isReferenceType()) Reason = 1;
6515 else if (IsCRegister) Reason = 2;
6516 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
6517 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
6518 }
6519
6520 return false;
6521}
6522
6523bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6524 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6525 const LangOptions &LO = getLangOpts();
6526
6527 if (LO.CPlusPlus)
6528 return Arg->getType()
6529 .getCanonicalType()
6530 .getTypePtr()
6531 ->getPointeeType()
6532 .withoutLocalFastQualifiers() == Context.CharTy;
6533
6534 // In C, allow aliasing through `char *`, this is required for AArch64 at
6535 // least.
6536 return true;
6537 };
6538
6539 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6540 // const char *named_addr);
6541
6542 Expr *Func = Call->getCallee();
6543
6544 if (Call->getNumArgs() < 3)
6545 return Diag(Loc: Call->getEndLoc(),
6546 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6547 << 0 /*function call*/ << 3 << Call->getNumArgs()
6548 << /*is non object*/ 0;
6549
6550 // Type-check the first argument normally.
6551 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
6552 return true;
6553
6554 // Check that the current function is variadic.
6555 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
6556 return true;
6557
6558 // __va_start on Windows does not validate the parameter qualifiers
6559
6560 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
6561 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6562
6563 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
6564 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6565
6566 const QualType &ConstCharPtrTy =
6567 Context.getPointerType(T: Context.CharTy.withConst());
6568 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6569 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6570 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6571 << 0 /* qualifier difference */
6572 << 3 /* parameter mismatch */
6573 << 2 << Arg1->getType() << ConstCharPtrTy;
6574
6575 const QualType SizeTy = Context.getSizeType();
6576 if (!Context.hasSameType(
6577 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
6578 T2: SizeTy))
6579 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6580 << Arg2->getType() << SizeTy << 1 /* different class */
6581 << 0 /* qualifier difference */
6582 << 3 /* parameter mismatch */
6583 << 3 << Arg2->getType() << SizeTy;
6584
6585 return false;
6586}
6587
6588bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6589 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6590 return true;
6591
6592 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6593 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
6594 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6595 << 1 << 0 << TheCall->getSourceRange();
6596
6597 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
6598 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
6599
6600 // Do standard promotions between the two arguments, returning their common
6601 // type.
6602 QualType Res = UsualArithmeticConversions(
6603 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
6604 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6605 return true;
6606
6607 // Make sure any conversions are pushed back into the call; this is
6608 // type safe since unordered compare builtins are declared as "_Bool
6609 // foo(...)".
6610 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
6611 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
6612
6613 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6614 return false;
6615
6616 // If the common type isn't a real floating type, then the arguments were
6617 // invalid for this operation.
6618 if (Res.isNull() || !Res->isRealFloatingType())
6619 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
6620 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
6621 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6622 << SourceRange(OrigArg0.get()->getBeginLoc(),
6623 OrigArg1.get()->getEndLoc());
6624
6625 return false;
6626}
6627
6628bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6629 unsigned BuiltinID) {
6630 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
6631 return true;
6632
6633 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
6634 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6635 BuiltinID == Builtin::BI__builtin_isinf ||
6636 BuiltinID == Builtin::BI__builtin_isinf_sign))
6637 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6638 << 0 << 0 << TheCall->getSourceRange();
6639
6640 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6641 BuiltinID == Builtin::BI__builtin_isunordered))
6642 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6643 << 1 << 0 << TheCall->getSourceRange();
6644
6645 bool IsFPClass = NumArgs == 2;
6646
6647 // Find out position of floating-point argument.
6648 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6649
6650 // We can count on all parameters preceding the floating-point just being int.
6651 // Try all of those.
6652 for (unsigned i = 0; i < FPArgNo; ++i) {
6653 Expr *Arg = TheCall->getArg(Arg: i);
6654
6655 if (Arg->isTypeDependent())
6656 return false;
6657
6658 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
6659 Action: AssignmentAction::Passing);
6660
6661 if (Res.isInvalid())
6662 return true;
6663 TheCall->setArg(Arg: i, ArgExpr: Res.get());
6664 }
6665
6666 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
6667
6668 if (OrigArg->isTypeDependent())
6669 return false;
6670
6671 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6672 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6673 if (!Res.isUsable())
6674 return true;
6675 OrigArg = Res.get();
6676
6677 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6678
6679 QualType VectorResultTy;
6680 QualType ElementTy = OrigArg->getType();
6681 // TODO: When all classification function are implemented with is_fpclass,
6682 // vector argument can be supported in all of them.
6683 if (ElementTy->isVectorType() && IsFPClass) {
6684 VectorResultTy = GetSignedVectorType(V: ElementTy);
6685 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6686 }
6687
6688 // This operation requires a non-_Complex floating-point number.
6689 if (!ElementTy->isRealFloatingType())
6690 return Diag(Loc: OrigArg->getBeginLoc(),
6691 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6692 << OrigArg->getType() << OrigArg->getSourceRange();
6693
6694 // __builtin_isfpclass has integer parameter that specify test mask. It is
6695 // passed in (...), so it should be analyzed completely here.
6696 if (IsFPClass) {
6697 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6698 return true;
6699
6700 ExprResult MaskRes = PerformImplicitConversion(
6701 From: TheCall->getArg(Arg: NumArgs - 1), ToType: Context.IntTy, Action: AssignmentAction::Passing);
6702 if (!MaskRes.isUsable())
6703 return true;
6704 TheCall->setArg(Arg: NumArgs - 1, ArgExpr: MaskRes.get());
6705 }
6706
6707 // TODO: enable this code to all classification functions.
6708 if (IsFPClass) {
6709 QualType ResultTy;
6710 if (!VectorResultTy.isNull())
6711 ResultTy = VectorResultTy;
6712 else
6713 ResultTy = Context.IntTy;
6714 TheCall->setType(ResultTy);
6715 }
6716
6717 return false;
6718}
6719
6720bool Sema::BuiltinComplex(CallExpr *TheCall) {
6721 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6722 return true;
6723
6724 bool Dependent = false;
6725 for (unsigned I = 0; I != 2; ++I) {
6726 Expr *Arg = TheCall->getArg(Arg: I);
6727 QualType T = Arg->getType();
6728 if (T->isDependentType()) {
6729 Dependent = true;
6730 continue;
6731 }
6732
6733 // Despite supporting _Complex int, GCC requires a real floating point type
6734 // for the operands of __builtin_complex.
6735 if (!T->isRealFloatingType()) {
6736 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6737 << Arg->getType() << Arg->getSourceRange();
6738 }
6739
6740 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6741 if (Converted.isInvalid())
6742 return true;
6743 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6744 }
6745
6746 if (Dependent) {
6747 TheCall->setType(Context.DependentTy);
6748 return false;
6749 }
6750
6751 Expr *Real = TheCall->getArg(Arg: 0);
6752 Expr *Imag = TheCall->getArg(Arg: 1);
6753 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6754 return Diag(Loc: Real->getBeginLoc(),
6755 DiagID: diag::err_typecheck_call_different_arg_types)
6756 << Real->getType() << Imag->getType()
6757 << Real->getSourceRange() << Imag->getSourceRange();
6758 }
6759
6760 TheCall->setType(Context.getComplexType(T: Real->getType()));
6761 return false;
6762}
6763
6764/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6765// This is declared to take (...), so we have to check everything.
6766ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6767 unsigned NumArgs = TheCall->getNumArgs();
6768 if (NumArgs < 2)
6769 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6770 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6771 << 0 /*function call*/ << 2 << NumArgs
6772 << /*is non object*/ 0 << TheCall->getSourceRange());
6773
6774 // Determine which of the following types of shufflevector we're checking:
6775 // 1) unary, vector mask: (lhs, mask)
6776 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6777 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6778 unsigned NumElements = 0;
6779
6780 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6781 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6782 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6783 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6784
6785 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6786 return ExprError(
6787 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6788 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6789 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6790 TheCall->getArg(Arg: 1)->getEndLoc()));
6791
6792 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6793 unsigned NumResElements = NumArgs - 2;
6794
6795 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6796 // with mask. If so, verify that RHS is an integer vector type with the
6797 // same number of elts as lhs.
6798 if (NumArgs == 2) {
6799 auto *RHSVecType = RHSType->castAs<VectorType>();
6800 if (RHSVecType->getElementType()->isBooleanType() ||
6801 !RHSVecType->getElementType()->isIntegerType()) {
6802 return ExprError(
6803 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
6804 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6805 << /*no fp*/ 0 << RHSType
6806 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6807 TheCall->getArg(Arg: 1)->getEndLoc()));
6808 }
6809
6810 if (RHSVecType->getNumElements() != NumElements)
6811 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6812 DiagID: diag::err_typecheck_vector_lengths_not_equal)
6813 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6814 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6815 TheCall->getArg(Arg: 1)->getEndLoc()));
6816 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6817 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6818 DiagID: diag::err_vec_builtin_incompatible_vector)
6819 << TheCall->getDirectCallee()
6820 << /*isMoreThanTwoArgs*/ false
6821 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6822 TheCall->getArg(Arg: 1)->getEndLoc()));
6823 } else if (NumElements != NumResElements) {
6824 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6825 ResType = ResType->isExtVectorType()
6826 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6827 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6828 VecKind: VectorKind::Generic);
6829 }
6830 }
6831
6832 for (unsigned I = 2; I != NumArgs; ++I) {
6833 Expr *Arg = TheCall->getArg(Arg: I);
6834 if (Arg->isTypeDependent() || Arg->isValueDependent())
6835 continue;
6836
6837 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6838 if (!Result)
6839 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6840 DiagID: diag::err_shufflevector_nonconstant_argument)
6841 << Arg->getSourceRange());
6842
6843 // Allow -1 which will be translated to undef in the IR.
6844 if (Result->isSigned() && Result->isAllOnes())
6845 ;
6846 else if (Result->getActiveBits() > 64 ||
6847 Result->getZExtValue() >= NumElements * 2)
6848 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6849 DiagID: diag::err_shufflevector_argument_too_large)
6850 << Arg->getSourceRange());
6851
6852 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6853 }
6854
6855 auto *Result = new (Context) ShuffleVectorExpr(
6856 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6857 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6858
6859 // All moved to Result.
6860 TheCall->shrinkNumArgs(NewNumArgs: 0);
6861 return Result;
6862}
6863
6864ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6865 SourceLocation BuiltinLoc,
6866 SourceLocation RParenLoc) {
6867 ExprValueKind VK = VK_PRValue;
6868 ExprObjectKind OK = OK_Ordinary;
6869 QualType DstTy = TInfo->getType();
6870 QualType SrcTy = E->getType();
6871
6872 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6873 return ExprError(Diag(Loc: BuiltinLoc,
6874 DiagID: diag::err_convertvector_non_vector)
6875 << E->getSourceRange());
6876 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6877 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6878 << "second"
6879 << "__builtin_convertvector");
6880
6881 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6882 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6883 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6884 if (SrcElts != DstElts)
6885 return ExprError(Diag(Loc: BuiltinLoc,
6886 DiagID: diag::err_convertvector_incompatible_vector)
6887 << E->getSourceRange());
6888 }
6889
6890 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6891 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6892}
6893
6894bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6895 unsigned NumArgs = TheCall->getNumArgs();
6896
6897 if (NumArgs > 3)
6898 return Diag(Loc: TheCall->getEndLoc(),
6899 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6900 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6901 << TheCall->getSourceRange();
6902
6903 // Argument 0 is checked for us and the remaining arguments must be
6904 // constant integers.
6905 for (unsigned i = 1; i != NumArgs; ++i) {
6906 if (convertArgumentToType(Value&: TheCall->getArgs()[i], Ty: Context.IntTy))
6907 return true;
6908 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6909 return true;
6910 }
6911
6912 return false;
6913}
6914
6915bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6916 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6917 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6918 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6919 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6920 return true;
6921 Expr *Arg = TheCall->getArg(Arg: 0);
6922 if (Arg->isInstantiationDependent())
6923 return false;
6924
6925 QualType ArgTy = Arg->getType();
6926 if (!ArgTy->hasFloatingRepresentation())
6927 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6928 << ArgTy;
6929 if (Arg->isLValue()) {
6930 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6931 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6932 }
6933 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6934 return false;
6935}
6936
6937bool Sema::BuiltinAssume(CallExpr *TheCall) {
6938 Expr *Arg = TheCall->getArg(Arg: 0);
6939 if (Arg->isInstantiationDependent()) return false;
6940
6941 if (Arg->HasSideEffects(Ctx: Context))
6942 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6943 << Arg->getSourceRange()
6944 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6945
6946 return false;
6947}
6948
6949bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6950 // The alignment must be a constant integer.
6951 Expr *Arg = TheCall->getArg(Arg: 1);
6952
6953 // We can't check the value of a dependent argument.
6954 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6955 if (const auto *UE =
6956 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6957 if (UE->getKind() == UETT_AlignOf ||
6958 UE->getKind() == UETT_PreferredAlignOf)
6959 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6960 << Arg->getSourceRange();
6961
6962 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6963
6964 if (!Result.isPowerOf2())
6965 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6966 << Arg->getSourceRange();
6967
6968 if (Result < Context.getCharWidth())
6969 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6970 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6971
6972 if (Result > std::numeric_limits<int32_t>::max())
6973 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6974 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6975 }
6976
6977 return false;
6978}
6979
6980bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6981 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6982 return true;
6983
6984 unsigned NumArgs = TheCall->getNumArgs();
6985 Expr *FirstArg = TheCall->getArg(Arg: 0);
6986
6987 {
6988 ExprResult FirstArgResult =
6989 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6990 if (FirstArgResult.isInvalid())
6991 return true;
6992 if (!FirstArgResult.get()->getType()->isPointerType()) {
6993 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6994 << TheCall->getSourceRange();
6995 return true;
6996 }
6997 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6998 }
6999
7000 // The alignment must be a constant integer.
7001 Expr *SecondArg = TheCall->getArg(Arg: 1);
7002
7003 // We can't check the value of a dependent argument.
7004 if (!SecondArg->isValueDependent()) {
7005 llvm::APSInt Result;
7006 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
7007 return true;
7008
7009 if (!Result.isPowerOf2())
7010 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
7011 << SecondArg->getSourceRange();
7012
7013 if (Result > Sema::MaximumAlignment)
7014 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
7015 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
7016
7017 TheCall->setArg(Arg: 1,
7018 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
7019 }
7020
7021 if (NumArgs > 2) {
7022 Expr *ThirdArg = TheCall->getArg(Arg: 2);
7023 if (convertArgumentToType(Value&: ThirdArg, Ty: Context.getSizeType()))
7024 return true;
7025 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
7026 }
7027
7028 return false;
7029}
7030
7031bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
7032 unsigned BuiltinID =
7033 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
7034 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7035
7036 unsigned NumArgs = TheCall->getNumArgs();
7037 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7038 if (NumArgs < NumRequiredArgs) {
7039 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
7040 << 0 /* function call */ << NumRequiredArgs << NumArgs
7041 << /*is non object*/ 0 << TheCall->getSourceRange();
7042 }
7043 if (NumArgs >= NumRequiredArgs + 0x100) {
7044 return Diag(Loc: TheCall->getEndLoc(),
7045 DiagID: diag::err_typecheck_call_too_many_args_at_most)
7046 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7047 << /*is non object*/ 0 << TheCall->getSourceRange();
7048 }
7049 unsigned i = 0;
7050
7051 // For formatting call, check buffer arg.
7052 if (!IsSizeCall) {
7053 ExprResult Arg(TheCall->getArg(Arg: i));
7054 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7055 Context, Type: Context.VoidPtrTy, Consumed: false);
7056 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7057 if (Arg.isInvalid())
7058 return true;
7059 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
7060 i++;
7061 }
7062
7063 // Check string literal arg.
7064 unsigned FormatIdx = i;
7065 {
7066 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
7067 if (Arg.isInvalid())
7068 return true;
7069 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
7070 i++;
7071 }
7072
7073 // Make sure variadic args are scalar.
7074 unsigned FirstDataArg = i;
7075 while (i < NumArgs) {
7076 ExprResult Arg = DefaultVariadicArgumentPromotion(
7077 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
7078 if (Arg.isInvalid())
7079 return true;
7080 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
7081 if (ArgSize.getQuantity() >= 0x100) {
7082 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
7083 << i << (int)ArgSize.getQuantity() << 0xff
7084 << TheCall->getSourceRange();
7085 }
7086 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
7087 i++;
7088 }
7089
7090 // Check formatting specifiers. NOTE: We're only doing this for the non-size
7091 // call to avoid duplicate diagnostics.
7092 if (!IsSizeCall) {
7093 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7094 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7095 bool Success = CheckFormatArguments(
7096 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
7097 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
7098 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
7099 if (!Success)
7100 return true;
7101 }
7102
7103 if (IsSizeCall) {
7104 TheCall->setType(Context.getSizeType());
7105 } else {
7106 TheCall->setType(Context.VoidPtrTy);
7107 }
7108 return false;
7109}
7110
7111bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
7112 llvm::APSInt &Result) {
7113 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7114
7115 if (Arg->isTypeDependent() || Arg->isValueDependent())
7116 return false;
7117
7118 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
7119 if (!R) {
7120 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
7121 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
7122 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
7123 << FDecl->getDeclName() << Arg->getSourceRange();
7124 BPF().notePreserveAIEnumerator(E: Arg);
7125 return true;
7126 }
7127 Result = *R;
7128
7129 return false;
7130}
7131
7132bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
7133 int High, bool RangeIsError) {
7134 if (isConstantEvaluatedContext())
7135 return false;
7136
7137 // Check constant-ness first.
7138 llvm::APSInt Result;
7139 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7140 return true;
7141
7142 return checkConstantArgValueRange(S&: *this, TheCall, ArgNum, Result, Low, High,
7143 RangeIsError);
7144}
7145
7146bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
7147 unsigned Num) {
7148 llvm::APSInt Result;
7149
7150 // We can't check the value of a dependent argument.
7151 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7152 if (Arg->isTypeDependent() || Arg->isValueDependent())
7153 return false;
7154
7155 // Check constant-ness first.
7156 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7157 return true;
7158
7159 if (Result.getSExtValue() % Num != 0)
7160 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
7161 << Num << Arg->getSourceRange();
7162
7163 return false;
7164}
7165
7166bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
7167 llvm::APSInt Result;
7168
7169 // We can't check the value of a dependent argument.
7170 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7171 if (Arg->isTypeDependent() || Arg->isValueDependent())
7172 return false;
7173
7174 // Check constant-ness first.
7175 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7176 return true;
7177
7178 if (Result.isPowerOf2())
7179 return false;
7180
7181 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
7182 << Arg->getSourceRange();
7183}
7184
7185static bool IsShiftedByte(llvm::APSInt Value) {
7186 if (Value.isNegative())
7187 return false;
7188
7189 // Check if it's a shifted byte, by shifting it down
7190 while (true) {
7191 // If the value fits in the bottom byte, the check passes.
7192 if (Value < 0x100)
7193 return true;
7194
7195 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7196 // fails.
7197 if ((Value & 0xFF) != 0)
7198 return false;
7199
7200 // If the bottom 8 bits are all 0, but something above that is nonzero,
7201 // then shifting the value right by 8 bits won't affect whether it's a
7202 // shifted byte or not. So do that, and go round again.
7203 Value >>= 8;
7204 }
7205}
7206
7207bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7208 unsigned ArgBits) {
7209 llvm::APSInt Result;
7210
7211 // We can't check the value of a dependent argument.
7212 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7213 if (Arg->isTypeDependent() || Arg->isValueDependent())
7214 return false;
7215
7216 // Check constant-ness first.
7217 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7218 return true;
7219
7220 // Truncate to the given size.
7221 Result = Result.getLoBits(numBits: ArgBits);
7222 Result.setIsUnsigned(true);
7223
7224 if (IsShiftedByte(Value: Result))
7225 return false;
7226
7227 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
7228 << Arg->getSourceRange();
7229}
7230
7231bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7232 unsigned ArgNum,
7233 unsigned ArgBits) {
7234 llvm::APSInt Result;
7235
7236 // We can't check the value of a dependent argument.
7237 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7238 if (Arg->isTypeDependent() || Arg->isValueDependent())
7239 return false;
7240
7241 // Check constant-ness first.
7242 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7243 return true;
7244
7245 // Truncate to the given size.
7246 Result = Result.getLoBits(numBits: ArgBits);
7247 Result.setIsUnsigned(true);
7248
7249 // Check to see if it's in either of the required forms.
7250 if (IsShiftedByte(Value: Result) ||
7251 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7252 return false;
7253
7254 return Diag(Loc: TheCall->getBeginLoc(),
7255 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
7256 << Arg->getSourceRange();
7257}
7258
7259bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7260 if (!Context.getTargetInfo().hasSjLjLowering())
7261 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
7262 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7263
7264 Expr *Arg = TheCall->getArg(Arg: 1);
7265 llvm::APSInt Result;
7266
7267 // TODO: This is less than ideal. Overload this to take a value.
7268 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
7269 return true;
7270
7271 if (Result != 1)
7272 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
7273 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7274
7275 return false;
7276}
7277
7278bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7279 if (!Context.getTargetInfo().hasSjLjLowering())
7280 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
7281 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7282 return false;
7283}
7284
7285bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7286 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
7287 return true;
7288
7289 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
7290 if (ArgRes.isInvalid())
7291 return true;
7292
7293 // For simplicity, we support only limited expressions for the argument.
7294 // Specifically a flexible array member or a pointer with counted_by:
7295 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7296 // complex casting, which really shouldn't be a huge problem.
7297 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7298 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7299 return Diag(Loc: Arg->getBeginLoc(),
7300 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7301 << Arg->getSourceRange();
7302
7303 if (Arg->HasSideEffects(Ctx: Context))
7304 return Diag(Loc: Arg->getBeginLoc(),
7305 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
7306 << Arg->getSourceRange();
7307
7308 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
7309 const auto *CATy =
7310 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7311
7312 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7313 // Member has counted_by attribute - return pointer to count field
7314 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
7315 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7316 if (CountFD->isBitField()) {
7317 Diag(Loc: ME->getBeginLoc(),
7318 DiagID: diag::err_builtin_counted_by_ref_counter_field_is_bitfield)
7319 << Arg << CountFD << ME->getSourceRange();
7320 return Diag(Loc: CountFD->getBeginLoc(),
7321 DiagID: diag::note_counted_by_counter_field)
7322 << CountFD << CountFD->getSourceRange();
7323 }
7324
7325 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
7326 return false;
7327 }
7328 }
7329
7330 // FAMs and pointers without counted_by return void*
7331 QualType MemberTy = ME->getMemberDecl()->getType();
7332 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7333 return Diag(Loc: Arg->getBeginLoc(),
7334 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7335 << Arg->getSourceRange();
7336 } else {
7337 return Diag(Loc: Arg->getBeginLoc(),
7338 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7339 << Arg->getSourceRange();
7340 }
7341
7342 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
7343 return false;
7344}
7345
7346/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7347/// It allows leaking and modification of bounds safety information.
7348bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7349 BuiltinCountedByRefKind K) {
7350 const CallExpr *CE =
7351 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
7352 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7353 return false;
7354
7355 switch (K) {
7356 case BuiltinCountedByRefKind::Assignment:
7357 case BuiltinCountedByRefKind::Initializer:
7358 Diag(Loc: E->getExprLoc(),
7359 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7360 << 0 << E->getSourceRange();
7361 break;
7362 case BuiltinCountedByRefKind::FunctionArg:
7363 Diag(Loc: E->getExprLoc(),
7364 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7365 << 1 << E->getSourceRange();
7366 break;
7367 case BuiltinCountedByRefKind::ReturnArg:
7368 Diag(Loc: E->getExprLoc(),
7369 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7370 << 2 << E->getSourceRange();
7371 break;
7372 case BuiltinCountedByRefKind::ArraySubscript:
7373 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7374 << 0 << E->getSourceRange();
7375 break;
7376 case BuiltinCountedByRefKind::BinaryExpr:
7377 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7378 << 1 << E->getSourceRange();
7379 break;
7380 }
7381
7382 return true;
7383}
7384
7385namespace {
7386
7387class UncoveredArgHandler {
7388 enum { Unknown = -1, AllCovered = -2 };
7389
7390 signed FirstUncoveredArg = Unknown;
7391 SmallVector<const Expr *, 4> DiagnosticExprs;
7392
7393public:
7394 UncoveredArgHandler() = default;
7395
7396 bool hasUncoveredArg() const {
7397 return (FirstUncoveredArg >= 0);
7398 }
7399
7400 unsigned getUncoveredArg() const {
7401 assert(hasUncoveredArg() && "no uncovered argument");
7402 return FirstUncoveredArg;
7403 }
7404
7405 void setAllCovered() {
7406 // A string has been found with all arguments covered, so clear out
7407 // the diagnostics.
7408 DiagnosticExprs.clear();
7409 FirstUncoveredArg = AllCovered;
7410 }
7411
7412 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7413 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7414
7415 // Don't update if a previous string covers all arguments.
7416 if (FirstUncoveredArg == AllCovered)
7417 return;
7418
7419 // UncoveredArgHandler tracks the highest uncovered argument index
7420 // and with it all the strings that match this index.
7421 if (NewFirstUncoveredArg == FirstUncoveredArg)
7422 DiagnosticExprs.push_back(Elt: StrExpr);
7423 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7424 DiagnosticExprs.clear();
7425 DiagnosticExprs.push_back(Elt: StrExpr);
7426 FirstUncoveredArg = NewFirstUncoveredArg;
7427 }
7428 }
7429
7430 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7431};
7432
7433enum StringLiteralCheckType {
7434 SLCT_NotALiteral,
7435 SLCT_UncheckedLiteral,
7436 SLCT_CheckedLiteral
7437};
7438
7439} // namespace
7440
7441static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7442 BinaryOperatorKind BinOpKind,
7443 bool AddendIsRight) {
7444 unsigned BitWidth = Offset.getBitWidth();
7445 unsigned AddendBitWidth = Addend.getBitWidth();
7446 // There might be negative interim results.
7447 if (Addend.isUnsigned()) {
7448 Addend = Addend.zext(width: ++AddendBitWidth);
7449 Addend.setIsSigned(true);
7450 }
7451 // Adjust the bit width of the APSInts.
7452 if (AddendBitWidth > BitWidth) {
7453 Offset = Offset.sext(width: AddendBitWidth);
7454 BitWidth = AddendBitWidth;
7455 } else if (BitWidth > AddendBitWidth) {
7456 Addend = Addend.sext(width: BitWidth);
7457 }
7458
7459 bool Ov = false;
7460 llvm::APSInt ResOffset = Offset;
7461 if (BinOpKind == BO_Add)
7462 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
7463 else {
7464 assert(AddendIsRight && BinOpKind == BO_Sub &&
7465 "operator must be add or sub with addend on the right");
7466 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
7467 }
7468
7469 // We add an offset to a pointer here so we should support an offset as big as
7470 // possible.
7471 if (Ov) {
7472 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7473 "index (intermediate) result too big");
7474 Offset = Offset.sext(width: 2 * BitWidth);
7475 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7476 return;
7477 }
7478
7479 Offset = std::move(ResOffset);
7480}
7481
7482namespace {
7483
7484// This is a wrapper class around StringLiteral to support offsetted string
7485// literals as format strings. It takes the offset into account when returning
7486// the string and its length or the source locations to display notes correctly.
7487class FormatStringLiteral {
7488 const StringLiteral *FExpr;
7489 int64_t Offset;
7490
7491public:
7492 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7493 : FExpr(fexpr), Offset(Offset) {}
7494
7495 const StringLiteral *getFormatString() const { return FExpr; }
7496
7497 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
7498
7499 unsigned getByteLength() const {
7500 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7501 }
7502
7503 unsigned getLength() const { return FExpr->getLength() - Offset; }
7504 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7505
7506 StringLiteralKind getKind() const { return FExpr->getKind(); }
7507
7508 QualType getType() const { return FExpr->getType(); }
7509
7510 bool isAscii() const { return FExpr->isOrdinary(); }
7511 bool isWide() const { return FExpr->isWide(); }
7512 bool isUTF8() const { return FExpr->isUTF8(); }
7513 bool isUTF16() const { return FExpr->isUTF16(); }
7514 bool isUTF32() const { return FExpr->isUTF32(); }
7515 bool isPascal() const { return FExpr->isPascal(); }
7516
7517 SourceLocation getLocationOfByte(
7518 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7519 const TargetInfo &Target, unsigned *StartToken = nullptr,
7520 unsigned *StartTokenByteOffset = nullptr) const {
7521 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
7522 StartToken, StartTokenByteOffset);
7523 }
7524
7525 SourceLocation getBeginLoc() const LLVM_READONLY {
7526 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7527 }
7528
7529 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7530};
7531
7532} // namespace
7533
7534static void CheckFormatString(
7535 Sema &S, const FormatStringLiteral *FExpr,
7536 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7537 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7538 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7539 bool inFunctionCall, VariadicCallType CallType,
7540 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7541 bool IgnoreStringsWithoutSpecifiers);
7542
7543static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7544 const Expr *E);
7545
7546// Determine if an expression is a string literal or constant string.
7547// If this function returns false on the arguments to a function expecting a
7548// format string, we will usually need to emit a warning.
7549// True string literals are then checked by CheckFormatString.
7550static StringLiteralCheckType
7551checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7552 const Expr *E, ArrayRef<const Expr *> Args,
7553 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7554 unsigned firstDataArg, FormatStringType Type,
7555 VariadicCallType CallType, bool InFunctionCall,
7556 llvm::SmallBitVector &CheckedVarArgs,
7557 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7558 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7559 bool IgnoreStringsWithoutSpecifiers = false) {
7560 if (S.isConstantEvaluatedContext())
7561 return SLCT_NotALiteral;
7562tryAgain:
7563 assert(Offset.isSigned() && "invalid offset");
7564
7565 if (E->isTypeDependent() || E->isValueDependent())
7566 return SLCT_NotALiteral;
7567
7568 E = E->IgnoreParenCasts();
7569
7570 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
7571 // Technically -Wformat-nonliteral does not warn about this case.
7572 // The behavior of printf and friends in this case is implementation
7573 // dependent. Ideally if the format string cannot be null then
7574 // it should have a 'nonnull' attribute in the function prototype.
7575 return SLCT_UncheckedLiteral;
7576
7577 switch (E->getStmtClass()) {
7578 case Stmt::InitListExprClass:
7579 // Handle expressions like {"foobar"}.
7580 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
7581 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7582 format_idx, firstDataArg, Type, CallType,
7583 /*InFunctionCall*/ false, CheckedVarArgs,
7584 UncoveredArg, Offset, CallerFormatParamIdx,
7585 IgnoreStringsWithoutSpecifiers);
7586 }
7587 return SLCT_NotALiteral;
7588 case Stmt::BinaryConditionalOperatorClass:
7589 case Stmt::ConditionalOperatorClass: {
7590 // The expression is a literal if both sub-expressions were, and it was
7591 // completely checked only if both sub-expressions were checked.
7592 const AbstractConditionalOperator *C =
7593 cast<AbstractConditionalOperator>(Val: E);
7594
7595 // Determine whether it is necessary to check both sub-expressions, for
7596 // example, because the condition expression is a constant that can be
7597 // evaluated at compile time.
7598 bool CheckLeft = true, CheckRight = true;
7599
7600 bool Cond;
7601 if (C->getCond()->EvaluateAsBooleanCondition(
7602 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
7603 if (Cond)
7604 CheckRight = false;
7605 else
7606 CheckLeft = false;
7607 }
7608
7609 // We need to maintain the offsets for the right and the left hand side
7610 // separately to check if every possible indexed expression is a valid
7611 // string literal. They might have different offsets for different string
7612 // literals in the end.
7613 StringLiteralCheckType Left;
7614 if (!CheckLeft)
7615 Left = SLCT_UncheckedLiteral;
7616 else {
7617 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
7618 Args, APK, format_idx, firstDataArg, Type,
7619 CallType, InFunctionCall, CheckedVarArgs,
7620 UncoveredArg, Offset, CallerFormatParamIdx,
7621 IgnoreStringsWithoutSpecifiers);
7622 if (Left == SLCT_NotALiteral || !CheckRight) {
7623 return Left;
7624 }
7625 }
7626
7627 StringLiteralCheckType Right = checkFormatStringExpr(
7628 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
7629 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7630 UncoveredArg, Offset, CallerFormatParamIdx,
7631 IgnoreStringsWithoutSpecifiers);
7632
7633 return (CheckLeft && Left < Right) ? Left : Right;
7634 }
7635
7636 case Stmt::ImplicitCastExprClass:
7637 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
7638 goto tryAgain;
7639
7640 case Stmt::OpaqueValueExprClass:
7641 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
7642 E = src;
7643 goto tryAgain;
7644 }
7645 return SLCT_NotALiteral;
7646
7647 case Stmt::PredefinedExprClass:
7648 // While __func__, etc., are technically not string literals, they
7649 // cannot contain format specifiers and thus are not a security
7650 // liability.
7651 return SLCT_UncheckedLiteral;
7652
7653 case Stmt::DeclRefExprClass: {
7654 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
7655
7656 // As an exception, do not flag errors for variables binding to
7657 // const string literals.
7658 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
7659 bool isConstant = false;
7660 QualType T = DR->getType();
7661
7662 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7663 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
7664 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7665 isConstant = T.isConstant(Ctx: S.Context) &&
7666 PT->getPointeeType().isConstant(Ctx: S.Context);
7667 } else if (T->isObjCObjectPointerType()) {
7668 // In ObjC, there is usually no "const ObjectPointer" type,
7669 // so don't check if the pointee type is constant.
7670 isConstant = T.isConstant(Ctx: S.Context);
7671 }
7672
7673 if (isConstant) {
7674 if (const Expr *Init = VD->getAnyInitializer()) {
7675 // Look through initializers like const char c[] = { "foo" }
7676 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7677 if (InitList->isStringLiteralInit())
7678 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7679 }
7680 return checkFormatStringExpr(
7681 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7682 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7683 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7684 }
7685 }
7686
7687 // When the format argument is an argument of this function, and this
7688 // function also has the format attribute, there are several interactions
7689 // for which there shouldn't be a warning. For instance, when calling
7690 // v*printf from a function that has the printf format attribute, we
7691 // should not emit a warning about using `fmt`, even though it's not
7692 // constant, because the arguments have already been checked for the
7693 // caller of `logmessage`:
7694 //
7695 // __attribute__((format(printf, 1, 2)))
7696 // void logmessage(char const *fmt, ...) {
7697 // va_list ap;
7698 // va_start(ap, fmt);
7699 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7700 // ...
7701 // }
7702 //
7703 // Another interaction that we need to support is using a format string
7704 // specified by the format_matches attribute:
7705 //
7706 // __attribute__((format_matches(printf, 1, "%s %d")))
7707 // void logmessage(char const *fmt, const char *a, int b) {
7708 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7709 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7710 // ...
7711 // }
7712 //
7713 // Yet another interaction that we need to support is calling a variadic
7714 // format function from a format function that has fixed arguments. For
7715 // instance:
7716 //
7717 // __attribute__((format(printf, 1, 2)))
7718 // void logstring(char const *fmt, char const *str) {
7719 // printf(fmt, str); /* do not emit a warning about "fmt" */
7720 // }
7721 //
7722 // Same (and perhaps more relatably) for the variadic template case:
7723 //
7724 // template<typename... Args>
7725 // __attribute__((format(printf, 1, 2)))
7726 // void log(const char *fmt, Args&&... args) {
7727 // printf(fmt, forward<Args>(args)...);
7728 // /* do not emit a warning about "fmt" */
7729 // }
7730 //
7731 // Due to implementation difficulty, we only check the format, not the
7732 // format arguments, in all cases.
7733 //
7734 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7735 if (CallerFormatParamIdx)
7736 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7737 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7738 for (const auto *PVFormatMatches :
7739 D->specific_attrs<FormatMatchesAttr>()) {
7740 Sema::FormatStringInfo CalleeFSI;
7741 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7742 FirstArg: 0, FSI: &CalleeFSI))
7743 continue;
7744 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7745 // If using the wrong type of format string, emit a diagnostic
7746 // here and stop checking to avoid irrelevant diagnostics.
7747 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7748 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7749 DiagID: diag::warn_format_string_type_incompatible)
7750 << PVFormatMatches->getType()->getName()
7751 << S.GetFormatStringTypeName(FST: Type);
7752 if (!InFunctionCall) {
7753 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7754 DiagID: diag::note_format_string_defined);
7755 }
7756 return SLCT_UncheckedLiteral;
7757 }
7758 return checkFormatStringExpr(
7759 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7760 Args, APK, format_idx, firstDataArg, Type, CallType,
7761 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7762 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7763 }
7764 }
7765
7766 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7767 Sema::FormatStringInfo CallerFSI;
7768 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7769 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7770 continue;
7771 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7772 // We also check if the formats are compatible.
7773 // We can't pass a 'scanf' string to a 'printf' function.
7774 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7775 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7776 DiagID: diag::warn_format_string_type_incompatible)
7777 << PVFormat->getType()->getName()
7778 << S.GetFormatStringTypeName(FST: Type);
7779 if (!InFunctionCall) {
7780 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7781 }
7782 return SLCT_UncheckedLiteral;
7783 }
7784 // Lastly, check that argument passing kinds transition in a
7785 // way that makes sense:
7786 // from a caller with FAPK_VAList, allow FAPK_VAList
7787 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7788 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7789 // from a caller with FAPK_Variadic, allow FAPK_VAList
7790 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7791 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7792 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7793 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7794 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7795 return SLCT_UncheckedLiteral;
7796 }
7797 }
7798 }
7799 }
7800 }
7801 }
7802
7803 return SLCT_NotALiteral;
7804 }
7805
7806 case Stmt::CallExprClass:
7807 case Stmt::CXXMemberCallExprClass: {
7808 const CallExpr *CE = cast<CallExpr>(Val: E);
7809 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7810 bool IsFirst = true;
7811 StringLiteralCheckType CommonResult;
7812 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7813 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7814 StringLiteralCheckType Result = checkFormatStringExpr(
7815 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7816 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7817 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7818 if (IsFirst) {
7819 CommonResult = Result;
7820 IsFirst = false;
7821 }
7822 }
7823 if (!IsFirst)
7824 return CommonResult;
7825
7826 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7827 unsigned BuiltinID = FD->getBuiltinID();
7828 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7829 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7830 const Expr *Arg = CE->getArg(Arg: 0);
7831 return checkFormatStringExpr(
7832 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7833 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7834 UncoveredArg, Offset, CallerFormatParamIdx,
7835 IgnoreStringsWithoutSpecifiers);
7836 }
7837 }
7838 }
7839 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7840 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7841 format_idx, firstDataArg, Type, CallType,
7842 /*InFunctionCall*/ false, CheckedVarArgs,
7843 UncoveredArg, Offset, CallerFormatParamIdx,
7844 IgnoreStringsWithoutSpecifiers);
7845 return SLCT_NotALiteral;
7846 }
7847 case Stmt::ObjCMessageExprClass: {
7848 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7849 if (const auto *MD = ME->getMethodDecl()) {
7850 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7851 // As a special case heuristic, if we're using the method -[NSBundle
7852 // localizedStringForKey:value:table:], ignore any key strings that lack
7853 // format specifiers. The idea is that if the key doesn't have any
7854 // format specifiers then its probably just a key to map to the
7855 // localized strings. If it does have format specifiers though, then its
7856 // likely that the text of the key is the format string in the
7857 // programmer's language, and should be checked.
7858 const ObjCInterfaceDecl *IFace;
7859 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7860 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7861 MD->getSelector().isKeywordSelector(
7862 Names: {"localizedStringForKey", "value", "table"})) {
7863 IgnoreStringsWithoutSpecifiers = true;
7864 }
7865
7866 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7867 return checkFormatStringExpr(
7868 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7869 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7870 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7871 }
7872 }
7873
7874 return SLCT_NotALiteral;
7875 }
7876 case Stmt::ObjCStringLiteralClass:
7877 case Stmt::StringLiteralClass: {
7878 const StringLiteral *StrE = nullptr;
7879
7880 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7881 StrE = ObjCFExpr->getString();
7882 else
7883 StrE = cast<StringLiteral>(Val: E);
7884
7885 if (StrE) {
7886 if (Offset.isNegative() || Offset > StrE->getLength()) {
7887 // TODO: It would be better to have an explicit warning for out of
7888 // bounds literals.
7889 return SLCT_NotALiteral;
7890 }
7891 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7892 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7893 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7894 CallType, CheckedVarArgs, UncoveredArg,
7895 IgnoreStringsWithoutSpecifiers);
7896 return SLCT_CheckedLiteral;
7897 }
7898
7899 return SLCT_NotALiteral;
7900 }
7901 case Stmt::BinaryOperatorClass: {
7902 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7903
7904 // A string literal + an int offset is still a string literal.
7905 if (BinOp->isAdditiveOp()) {
7906 Expr::EvalResult LResult, RResult;
7907
7908 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7909 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7910 InConstantContext: S.isConstantEvaluatedContext());
7911 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7912 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7913 InConstantContext: S.isConstantEvaluatedContext());
7914
7915 if (LIsInt != RIsInt) {
7916 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7917
7918 if (LIsInt) {
7919 if (BinOpKind == BO_Add) {
7920 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7921 E = BinOp->getRHS();
7922 goto tryAgain;
7923 }
7924 } else {
7925 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7926 E = BinOp->getLHS();
7927 goto tryAgain;
7928 }
7929 }
7930 }
7931
7932 return SLCT_NotALiteral;
7933 }
7934 case Stmt::UnaryOperatorClass: {
7935 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7936 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7937 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7938 Expr::EvalResult IndexResult;
7939 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7940 AllowSideEffects: Expr::SE_NoSideEffects,
7941 InConstantContext: S.isConstantEvaluatedContext())) {
7942 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7943 /*RHS is int*/ AddendIsRight: true);
7944 E = ASE->getBase();
7945 goto tryAgain;
7946 }
7947 }
7948
7949 return SLCT_NotALiteral;
7950 }
7951
7952 default:
7953 return SLCT_NotALiteral;
7954 }
7955}
7956
7957// If this expression can be evaluated at compile-time,
7958// check if the result is a StringLiteral and return it
7959// otherwise return nullptr
7960static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7961 const Expr *E) {
7962 Expr::EvalResult Result;
7963 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7964 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7965 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7966 return LVE;
7967 }
7968 return nullptr;
7969}
7970
7971StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7972 switch (FST) {
7973 case FormatStringType::Scanf:
7974 return "scanf";
7975 case FormatStringType::Printf:
7976 return "printf";
7977 case FormatStringType::NSString:
7978 return "NSString";
7979 case FormatStringType::Strftime:
7980 return "strftime";
7981 case FormatStringType::Strfmon:
7982 return "strfmon";
7983 case FormatStringType::Kprintf:
7984 return "kprintf";
7985 case FormatStringType::FreeBSDKPrintf:
7986 return "freebsd_kprintf";
7987 case FormatStringType::OSLog:
7988 return "os_log";
7989 default:
7990 return "<unknown>";
7991 }
7992}
7993
7994FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7995 return llvm::StringSwitch<FormatStringType>(Flavor)
7996 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7997 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7998 Value: FormatStringType::Printf)
7999 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
8000 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
8001 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
8002 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
8003 Value: FormatStringType::Kprintf)
8004 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
8005 .Case(S: "os_trace", Value: FormatStringType::OSLog)
8006 .Case(S: "os_log", Value: FormatStringType::OSLog)
8007 .Default(Value: FormatStringType::Unknown);
8008}
8009
8010FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8011 return GetFormatStringType(Flavor: Format->getType()->getName());
8012}
8013
8014FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
8015 return GetFormatStringType(Flavor: Format->getType()->getName());
8016}
8017
8018bool Sema::CheckFormatArguments(const FormatAttr *Format,
8019 ArrayRef<const Expr *> Args, bool IsCXXMember,
8020 VariadicCallType CallType, SourceLocation Loc,
8021 SourceRange Range,
8022 llvm::SmallBitVector &CheckedVarArgs) {
8023 FormatStringInfo FSI;
8024 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
8025 HasImplicitThisParam: IsCXXMember,
8026 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
8027 return CheckFormatArguments(
8028 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
8029 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
8030 return false;
8031}
8032
8033bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
8034 ArrayRef<const Expr *> Args, bool IsCXXMember,
8035 VariadicCallType CallType, SourceLocation Loc,
8036 SourceRange Range,
8037 llvm::SmallBitVector &CheckedVarArgs) {
8038 FormatStringInfo FSI;
8039 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
8040 FSI: &FSI)) {
8041 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
8042 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
8043 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
8044 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
8045 CallType, Loc, range: Range, CheckedVarArgs);
8046 }
8047 return false;
8048}
8049
8050static bool CheckMissingFormatAttribute(
8051 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
8052 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
8053 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
8054 SourceLocation Loc) {
8055 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
8056 return false;
8057
8058 DeclContext *DC = S->CurContext->getEnclosingNonExpansionStatementContext();
8059 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
8060 return false;
8061 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
8062
8063 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
8064
8065 // Find the offset to convert between attribute and parameter indexes.
8066 unsigned CallerArgumentIndexOffset =
8067 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
8068
8069 unsigned FirstArgumentIndex = -1;
8070 switch (APK) {
8071 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
8072 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
8073 // As an extension, clang allows the format attribute on non-variadic
8074 // functions.
8075 // Caller must have fixed arguments to pass them to a fixed or variadic
8076 // function. Try to match caller and callee arguments. If successful, then
8077 // emit a diag with the caller idx, otherwise we can't determine the callee
8078 // arguments.
8079 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
8080 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
8081 // There aren't enough arguments in the caller to pass to callee.
8082 return false;
8083 }
8084 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
8085 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
8086 const auto *Arg =
8087 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
8088 if (!Arg)
8089 return false;
8090 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
8091 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
8092 return false;
8093 }
8094 FirstArgumentIndex =
8095 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
8096 break;
8097 }
8098 case Sema::FormatArgumentPassingKind::FAPK_VAList:
8099 // Caller arguments are either variadic or a va_list.
8100 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
8101 ? (NumCallerParams + CallerArgumentIndexOffset)
8102 : 0;
8103 break;
8104 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
8105 // The callee has a format_matches attribute. We will emit that instead.
8106 if (!ReferenceFormatString)
8107 return false;
8108 break;
8109 }
8110
8111 // Emit the diagnostic and fixit.
8112 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
8113 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
8114 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
8115 do {
8116 std::string Attr, Fixit;
8117 llvm::raw_string_ostream AttrOS(Attr);
8118 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
8119 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
8120 << FirstArgumentIndex << ")";
8121 } else {
8122 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
8123 << ", \"";
8124 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
8125 AttrOS << "\")";
8126 }
8127 AttrOS.flush();
8128 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
8129 if (ND)
8130 DB << ND;
8131 else
8132 DB << "block";
8133
8134 // Blocks don't provide a correct end loc, so skip emitting a fixit.
8135 if (isa<BlockDecl>(Val: Caller))
8136 break;
8137
8138 SourceLocation SL;
8139 llvm::raw_string_ostream IS(Fixit);
8140 // The attribute goes at the start of the declaration in C/C++ functions
8141 // and methods, but after the declaration for Objective-C methods.
8142 if (isa<ObjCMethodDecl>(Val: Caller)) {
8143 IS << ' ';
8144 SL = Caller->getEndLoc();
8145 }
8146 const LangOptions &LO = S->getLangOpts();
8147 if (LO.C23 || LO.CPlusPlus11)
8148 IS << "[[gnu::" << Attr << "]]";
8149 else if (LO.ObjC || LO.GNUMode)
8150 IS << "__attribute__((" << Attr << "))";
8151 else
8152 break;
8153 if (!isa<ObjCMethodDecl>(Val: Caller)) {
8154 IS << ' ';
8155 SL = Caller->getBeginLoc();
8156 }
8157 IS.flush();
8158
8159 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
8160 } while (false);
8161
8162 // Add implicit format or format_matches attribute.
8163 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
8164 Caller->addAttr(A: FormatAttr::CreateImplicit(
8165 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
8166 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
8167 } else {
8168 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
8169 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
8170 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
8171 }
8172
8173 {
8174 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
8175 if (ND)
8176 DB << ND;
8177 else
8178 DB << "block";
8179 }
8180 return true;
8181}
8182
8183bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8184 Sema::FormatArgumentPassingKind APK,
8185 StringLiteral *ReferenceFormatString,
8186 unsigned format_idx, unsigned firstDataArg,
8187 FormatStringType Type,
8188 VariadicCallType CallType, SourceLocation Loc,
8189 SourceRange Range,
8190 llvm::SmallBitVector &CheckedVarArgs) {
8191 // CHECK: printf/scanf-like function is called with no format string.
8192 if (format_idx >= Args.size()) {
8193 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
8194 return false;
8195 }
8196
8197 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8198
8199 // CHECK: format string is not a string literal.
8200 //
8201 // Dynamically generated format strings are difficult to
8202 // automatically vet at compile time. Requiring that format strings
8203 // are string literals: (1) permits the checking of format strings by
8204 // the compiler and thereby (2) can practically remove the source of
8205 // many format string exploits.
8206
8207 // Format string can be either ObjC string (e.g. @"%d") or
8208 // C string (e.g. "%d")
8209 // ObjC string uses the same format specifiers as C string, so we can use
8210 // the same format string checking logic for both ObjC and C strings.
8211 UncoveredArgHandler UncoveredArg;
8212 std::optional<unsigned> CallerParamIdx;
8213 StringLiteralCheckType CT = checkFormatStringExpr(
8214 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
8215 firstDataArg, Type, CallType,
8216 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
8217 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
8218
8219 // Generate a diagnostic where an uncovered argument is detected.
8220 if (UncoveredArg.hasUncoveredArg()) {
8221 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8222 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8223 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
8224 }
8225
8226 if (CT != SLCT_NotALiteral)
8227 // Literal format string found, check done!
8228 return CT == SLCT_CheckedLiteral;
8229
8230 // Do not emit diag when the string param is a macro expansion and the
8231 // format is either NSString or CFString. This is a hack to prevent
8232 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8233 // which are usually used in place of NS and CF string literals.
8234 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8235 if (Type == FormatStringType::NSString &&
8236 SourceMgr.isInSystemMacro(loc: FormatLoc))
8237 return false;
8238
8239 if (CallerParamIdx && CheckMissingFormatAttribute(
8240 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
8241 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
8242 return false;
8243
8244 // Strftime is particular as it always uses a single 'time' argument,
8245 // so it is safe to pass a non-literal string.
8246 if (Type == FormatStringType::Strftime)
8247 return false;
8248
8249 // If there are no arguments specified, warn with -Wformat-security, otherwise
8250 // warn only with -Wformat-nonliteral.
8251 if (Args.size() == firstDataArg) {
8252 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
8253 << OrigFormatExpr->getSourceRange();
8254 switch (Type) {
8255 default:
8256 break;
8257 case FormatStringType::Kprintf:
8258 case FormatStringType::FreeBSDKPrintf:
8259 case FormatStringType::Printf:
8260 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8261 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
8262 break;
8263 case FormatStringType::NSString:
8264 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8265 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
8266 break;
8267 }
8268 } else {
8269 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
8270 << OrigFormatExpr->getSourceRange();
8271 }
8272 return false;
8273}
8274
8275namespace {
8276
8277class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8278protected:
8279 Sema &S;
8280 const FormatStringLiteral *FExpr;
8281 const Expr *OrigFormatExpr;
8282 const FormatStringType FSType;
8283 const unsigned FirstDataArg;
8284 const unsigned NumDataArgs;
8285 const char *Beg; // Start of format string.
8286 const Sema::FormatArgumentPassingKind ArgPassingKind;
8287 ArrayRef<const Expr *> Args;
8288 unsigned FormatIdx;
8289 llvm::SmallBitVector CoveredArgs;
8290 bool usesPositionalArgs = false;
8291 bool atFirstArg = true;
8292 bool inFunctionCall;
8293 VariadicCallType CallType;
8294 llvm::SmallBitVector &CheckedVarArgs;
8295 UncoveredArgHandler &UncoveredArg;
8296
8297public:
8298 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8299 const Expr *origFormatExpr, const FormatStringType type,
8300 unsigned firstDataArg, unsigned numDataArgs,
8301 const char *beg, Sema::FormatArgumentPassingKind APK,
8302 ArrayRef<const Expr *> Args, unsigned formatIdx,
8303 bool inFunctionCall, VariadicCallType callType,
8304 llvm::SmallBitVector &CheckedVarArgs,
8305 UncoveredArgHandler &UncoveredArg)
8306 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8307 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8308 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8309 inFunctionCall(inFunctionCall), CallType(callType),
8310 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8311 CoveredArgs.resize(N: numDataArgs);
8312 CoveredArgs.reset();
8313 }
8314
8315 bool HasFormatArguments() const {
8316 return ArgPassingKind == Sema::FAPK_Fixed ||
8317 ArgPassingKind == Sema::FAPK_Variadic;
8318 }
8319
8320 void DoneProcessing();
8321
8322 void HandleIncompleteSpecifier(const char *startSpecifier,
8323 unsigned specifierLen) override;
8324
8325 void HandleInvalidLengthModifier(
8326 const analyze_format_string::FormatSpecifier &FS,
8327 const analyze_format_string::ConversionSpecifier &CS,
8328 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8329
8330 void HandleNonStandardLengthModifier(
8331 const analyze_format_string::FormatSpecifier &FS,
8332 const char *startSpecifier, unsigned specifierLen);
8333
8334 void HandleNonStandardConversionSpecifier(
8335 const analyze_format_string::ConversionSpecifier &CS,
8336 const char *startSpecifier, unsigned specifierLen);
8337
8338 void HandlePosition(const char *startPos, unsigned posLen) override;
8339
8340 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8341 analyze_format_string::PositionContext p) override;
8342
8343 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8344
8345 void HandleNullChar(const char *nullCharacter) override;
8346
8347 template <typename Range>
8348 static void
8349 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8350 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8351 bool IsStringLocation, Range StringRange,
8352 ArrayRef<FixItHint> Fixit = {});
8353
8354protected:
8355 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8356 const char *startSpec,
8357 unsigned specifierLen,
8358 const char *csStart, unsigned csLen);
8359
8360 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8361 const char *startSpec,
8362 unsigned specifierLen);
8363
8364 SourceRange getFormatStringRange();
8365 CharSourceRange getSpecifierRange(const char *startSpecifier,
8366 unsigned specifierLen);
8367 SourceLocation getLocationOfByte(const char *x);
8368
8369 const Expr *getDataArg(unsigned i) const;
8370
8371 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8372 const analyze_format_string::ConversionSpecifier &CS,
8373 const char *startSpecifier, unsigned specifierLen,
8374 unsigned argIndex);
8375
8376 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8377 const Expr *E, const char *startSpecifier,
8378 unsigned specifierLen);
8379
8380 template <typename Range>
8381 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8382 bool IsStringLocation, Range StringRange,
8383 ArrayRef<FixItHint> Fixit = {});
8384};
8385
8386} // namespace
8387
8388SourceRange CheckFormatHandler::getFormatStringRange() {
8389 return OrigFormatExpr->getSourceRange();
8390}
8391
8392CharSourceRange
8393CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8394 unsigned specifierLen) {
8395 SourceLocation Start = getLocationOfByte(x: startSpecifier);
8396 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
8397
8398 // Advance the end SourceLocation by one due to half-open ranges.
8399 End = End.getLocWithOffset(Offset: 1);
8400
8401 return CharSourceRange::getCharRange(B: Start, E: End);
8402}
8403
8404SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8405 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
8406 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
8407}
8408
8409void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8410 unsigned specifierLen) {
8411 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
8412 Loc: getLocationOfByte(x: startSpecifier),
8413 /*IsStringLocation*/ true,
8414 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8415}
8416
8417bool CheckFormatHandler::CheckUnsupportedType(
8418 const analyze_format_string::ArgType &AT, const Expr *E,
8419 const char *StartSpecifier, unsigned SpecifierLen) {
8420 if (!AT.isUnsupported())
8421 return false;
8422
8423 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_unsupported_type)
8424 << AT.getRepresentativeTypeName(C&: S.Context),
8425 Loc: E->getExprLoc(), /*IsStringLocation=*/false,
8426 StringRange: getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen));
8427 return true;
8428}
8429
8430void CheckFormatHandler::HandleInvalidLengthModifier(
8431 const analyze_format_string::FormatSpecifier &FS,
8432 const analyze_format_string::ConversionSpecifier &CS,
8433 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8434 using namespace analyze_format_string;
8435
8436 const LengthModifier &LM = FS.getLengthModifier();
8437 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8438
8439 // See if we know how to fix this length modifier.
8440 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8441 if (FixedLM) {
8442 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8443 Loc: getLocationOfByte(x: LM.getStart()),
8444 /*IsStringLocation*/ true,
8445 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8446
8447 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8448 << FixedLM->toString()
8449 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8450
8451 } else {
8452 FixItHint Hint;
8453 if (DiagID == diag::warn_format_nonsensical_length)
8454 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
8455
8456 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8457 Loc: getLocationOfByte(x: LM.getStart()),
8458 /*IsStringLocation*/ true,
8459 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: Hint);
8460 }
8461}
8462
8463void CheckFormatHandler::HandleNonStandardLengthModifier(
8464 const analyze_format_string::FormatSpecifier &FS,
8465 const char *startSpecifier, unsigned specifierLen) {
8466 using namespace analyze_format_string;
8467
8468 const LengthModifier &LM = FS.getLengthModifier();
8469 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8470
8471 // See if we know how to fix this length modifier.
8472 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8473 if (FixedLM) {
8474 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8475 << LM.toString() << 0,
8476 Loc: getLocationOfByte(x: LM.getStart()),
8477 /*IsStringLocation*/ true,
8478 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8479
8480 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8481 << FixedLM->toString()
8482 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8483
8484 } else {
8485 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8486 << LM.toString() << 0,
8487 Loc: getLocationOfByte(x: LM.getStart()),
8488 /*IsStringLocation*/ true,
8489 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8490 }
8491}
8492
8493void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8494 const analyze_format_string::ConversionSpecifier &CS,
8495 const char *startSpecifier, unsigned specifierLen) {
8496 using namespace analyze_format_string;
8497
8498 // See if we know how to fix this conversion specifier.
8499 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8500 if (FixedCS) {
8501 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8502 << CS.toString() << /*conversion specifier*/ 1,
8503 Loc: getLocationOfByte(x: CS.getStart()),
8504 /*IsStringLocation*/ true,
8505 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8506
8507 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
8508 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
8509 << FixedCS->toString()
8510 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
8511 } else {
8512 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8513 << CS.toString() << /*conversion specifier*/ 1,
8514 Loc: getLocationOfByte(x: CS.getStart()),
8515 /*IsStringLocation*/ true,
8516 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8517 }
8518}
8519
8520void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8521 if (!S.getDiagnostics().isIgnored(
8522 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
8523 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
8524 Loc: getLocationOfByte(x: startPos),
8525 /*IsStringLocation*/ true,
8526 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8527}
8528
8529void CheckFormatHandler::HandleInvalidPosition(
8530 const char *startSpecifier, unsigned specifierLen,
8531 analyze_format_string::PositionContext p) {
8532 if (!S.getDiagnostics().isIgnored(
8533 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
8534 EmitFormatDiagnostic(
8535 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8536 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
8537 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8538}
8539
8540void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8541 unsigned posLen) {
8542 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
8543 Loc: SourceLocation()))
8544 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
8545 Loc: getLocationOfByte(x: startPos),
8546 /*IsStringLocation*/ true,
8547 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8548}
8549
8550void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8551 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
8552 // The presence of a null character is likely an error.
8553 EmitFormatDiagnostic(
8554 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
8555 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/ true,
8556 StringRange: getFormatStringRange());
8557 }
8558}
8559
8560// Note that this may return NULL if there was an error parsing or building
8561// one of the argument expressions.
8562const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8563 return Args[FirstDataArg + i];
8564}
8565
8566void CheckFormatHandler::DoneProcessing() {
8567 // Does the number of data arguments exceed the number of
8568 // format conversions in the format string?
8569 if (HasFormatArguments()) {
8570 // Find any arguments that weren't covered.
8571 CoveredArgs.flip();
8572 signed notCoveredArg = CoveredArgs.find_first();
8573 if (notCoveredArg >= 0) {
8574 assert((unsigned)notCoveredArg < NumDataArgs);
8575 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
8576 } else {
8577 UncoveredArg.setAllCovered();
8578 }
8579 }
8580}
8581
8582void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8583 const Expr *ArgExpr) {
8584 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8585
8586 if (!ArgExpr)
8587 return;
8588
8589 SourceLocation Loc = ArgExpr->getBeginLoc();
8590
8591 if (S.getSourceManager().isInSystemMacro(loc: Loc))
8592 return;
8593
8594 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
8595 for (auto E : DiagnosticExprs)
8596 PDiag << E->getSourceRange();
8597
8598 CheckFormatHandler::EmitFormatDiagnostic(
8599 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0], PDiag, Loc,
8600 /*IsStringLocation*/ false, StringRange: DiagnosticExprs[0]->getSourceRange());
8601}
8602
8603bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8604 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8605 unsigned specifierLen, const char *csStart, unsigned csLen) {
8606 bool keepGoing = true;
8607 if (argIndex < NumDataArgs) {
8608 // Consider the argument coverered, even though the specifier doesn't
8609 // make sense.
8610 CoveredArgs.set(argIndex);
8611 } else {
8612 // If argIndex exceeds the number of data arguments we
8613 // don't issue a warning because that is just a cascade of warnings (and
8614 // they may have intended '%%' anyway). We don't want to continue processing
8615 // the format string after this point, however, as we will like just get
8616 // gibberish when trying to match arguments.
8617 keepGoing = false;
8618 }
8619
8620 StringRef Specifier(csStart, csLen);
8621
8622 // If the specifier in non-printable, it could be the first byte of a UTF-8
8623 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8624 // hex value.
8625 std::string CodePointStr;
8626 if (!llvm::sys::locale::isPrint(c: *csStart)) {
8627 llvm::UTF32 CodePoint;
8628 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8629 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8630 llvm::ConversionResult Result =
8631 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
8632
8633 if (Result != llvm::conversionOK) {
8634 unsigned char FirstChar = *csStart;
8635 CodePoint = (llvm::UTF32)FirstChar;
8636 }
8637
8638 llvm::raw_string_ostream OS(CodePointStr);
8639 if (CodePoint < 256)
8640 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
8641 else if (CodePoint <= 0xFFFF)
8642 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
8643 else
8644 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
8645 Specifier = CodePointStr;
8646 }
8647
8648 EmitFormatDiagnostic(
8649 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
8650 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8651
8652 return keepGoing;
8653}
8654
8655void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8656 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8657 EmitFormatDiagnostic(
8658 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args), Loc,
8659 /*isStringLoc*/ IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8660}
8661
8662bool CheckFormatHandler::CheckNumArgs(
8663 const analyze_format_string::FormatSpecifier &FS,
8664 const analyze_format_string::ConversionSpecifier &CS,
8665 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8666
8667 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8668 PartialDiagnostic PDiag =
8669 FS.usesPositionalArg()
8670 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
8671 << (argIndex + 1) << NumDataArgs)
8672 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
8673 EmitFormatDiagnostic(PDiag, Loc: getLocationOfByte(x: CS.getStart()),
8674 /*IsStringLocation*/ true,
8675 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8676
8677 // Since more arguments than conversion tokens are given, by extension
8678 // all arguments are covered, so mark this as so.
8679 UncoveredArg.setAllCovered();
8680 return false;
8681 }
8682 return true;
8683}
8684
8685template <typename Range>
8686void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8687 SourceLocation Loc,
8688 bool IsStringLocation,
8689 Range StringRange,
8690 ArrayRef<FixItHint> FixIt) {
8691 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8692 IsStringLocation, StringRange, FixIt);
8693}
8694
8695/// If the format string is not within the function call, emit a note
8696/// so that the function call and string are in diagnostic messages.
8697///
8698/// \param InFunctionCall if true, the format string is within the function
8699/// call and only one diagnostic message will be produced. Otherwise, an
8700/// extra note will be emitted pointing to location of the format string.
8701///
8702/// \param ArgumentExpr the expression that is passed as the format string
8703/// argument in the function call. Used for getting locations when two
8704/// diagnostics are emitted.
8705///
8706/// \param PDiag the callee should already have provided any strings for the
8707/// diagnostic message. This function only adds locations and fixits
8708/// to diagnostics.
8709///
8710/// \param Loc primary location for diagnostic. If two diagnostics are
8711/// required, one will be at Loc and a new SourceLocation will be created for
8712/// the other one.
8713///
8714/// \param IsStringLocation if true, Loc points to the format string should be
8715/// used for the note. Otherwise, Loc points to the argument list and will
8716/// be used with PDiag.
8717///
8718/// \param StringRange some or all of the string to highlight. This is
8719/// templated so it can accept either a CharSourceRange or a SourceRange.
8720///
8721/// \param FixIt optional fix it hint for the format string.
8722template <typename Range>
8723void CheckFormatHandler::EmitFormatDiagnostic(
8724 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8725 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8726 Range StringRange, ArrayRef<FixItHint> FixIt) {
8727 if (InFunctionCall) {
8728 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8729 D << StringRange;
8730 D << FixIt;
8731 } else {
8732 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8733 << ArgumentExpr->getSourceRange();
8734
8735 const Sema::SemaDiagnosticBuilder &Note =
8736 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8737 diag::note_format_string_defined);
8738
8739 Note << StringRange;
8740 Note << FixIt;
8741 }
8742}
8743
8744//===--- CHECK: Printf format string checking -----------------------------===//
8745
8746namespace {
8747
8748class CheckPrintfHandler : public CheckFormatHandler {
8749public:
8750 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8751 const Expr *origFormatExpr, const FormatStringType type,
8752 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8753 const char *beg, Sema::FormatArgumentPassingKind APK,
8754 ArrayRef<const Expr *> Args, unsigned formatIdx,
8755 bool inFunctionCall, VariadicCallType CallType,
8756 llvm::SmallBitVector &CheckedVarArgs,
8757 UncoveredArgHandler &UncoveredArg)
8758 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8759 numDataArgs, beg, APK, Args, formatIdx,
8760 inFunctionCall, CallType, CheckedVarArgs,
8761 UncoveredArg) {}
8762
8763 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8764
8765 /// Returns true if '%@' specifiers are allowed in the format string.
8766 bool allowsObjCArg() const {
8767 return FSType == FormatStringType::NSString ||
8768 FSType == FormatStringType::OSLog ||
8769 FSType == FormatStringType::OSTrace;
8770 }
8771
8772 bool HandleInvalidPrintfConversionSpecifier(
8773 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8774 unsigned specifierLen) override;
8775
8776 void handleInvalidMaskType(StringRef MaskType) override;
8777
8778 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8779 const char *startSpecifier, unsigned specifierLen,
8780 const TargetInfo &Target) override;
8781 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8782 const char *StartSpecifier, unsigned SpecifierLen,
8783 const Expr *E);
8784
8785 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8786 unsigned k, const char *startSpecifier,
8787 unsigned specifierLen);
8788 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8789 const analyze_printf::OptionalAmount &Amt,
8790 unsigned type, const char *startSpecifier,
8791 unsigned specifierLen);
8792 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8793 const analyze_printf::OptionalFlag &flag,
8794 const char *startSpecifier, unsigned specifierLen);
8795 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8796 const analyze_printf::OptionalFlag &ignoredFlag,
8797 const analyze_printf::OptionalFlag &flag,
8798 const char *startSpecifier, unsigned specifierLen);
8799 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8800
8801 void HandleEmptyObjCModifierFlag(const char *startFlag,
8802 unsigned flagLen) override;
8803
8804 void HandleInvalidObjCModifierFlag(const char *startFlag,
8805 unsigned flagLen) override;
8806
8807 void
8808 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8809 const char *flagsEnd,
8810 const char *conversionPosition) override;
8811};
8812
8813/// Keeps around the information needed to verify that two specifiers are
8814/// compatible.
8815class EquatableFormatArgument {
8816public:
8817 enum SpecifierSensitivity : unsigned {
8818 SS_None,
8819 SS_Private,
8820 SS_Public,
8821 SS_Sensitive
8822 };
8823
8824 enum FormatArgumentRole : unsigned {
8825 FAR_Data,
8826 FAR_FieldWidth,
8827 FAR_Precision,
8828 FAR_Auxiliary, // FreeBSD kernel %b and %D
8829 };
8830
8831private:
8832 analyze_format_string::ArgType ArgType;
8833 analyze_format_string::LengthModifier LengthMod;
8834 StringRef SpecifierLetter;
8835 CharSourceRange Range;
8836 SourceLocation ElementLoc;
8837 FormatArgumentRole Role : 2;
8838 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8839 unsigned Position : 14;
8840 unsigned ModifierFor : 14; // not set for FAR_Data
8841
8842 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8843 bool InFunctionCall) const;
8844
8845public:
8846 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8847 analyze_format_string::LengthModifier LengthMod,
8848 StringRef SpecifierLetter,
8849 analyze_format_string::ArgType ArgType,
8850 FormatArgumentRole Role,
8851 SpecifierSensitivity Sensitivity, unsigned Position,
8852 unsigned ModifierFor)
8853 : ArgType(ArgType), LengthMod(LengthMod),
8854 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8855 Role(Role), Sensitivity(Sensitivity), Position(Position),
8856 ModifierFor(ModifierFor) {}
8857
8858 unsigned getPosition() const { return Position; }
8859 SourceLocation getSourceLocation() const { return ElementLoc; }
8860 CharSourceRange getSourceRange() const { return Range; }
8861 analyze_format_string::LengthModifier getLengthModifier() const {
8862 return LengthMod;
8863 }
8864 void setModifierFor(unsigned V) { ModifierFor = V; }
8865
8866 std::string buildFormatSpecifier() const {
8867 std::string result;
8868 llvm::raw_string_ostream(result)
8869 << getLengthModifier().toString() << SpecifierLetter;
8870 return result;
8871 }
8872
8873 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8874 const Expr *FmtExpr, bool InFunctionCall) const;
8875};
8876
8877/// Turns format strings into lists of EquatableSpecifier objects.
8878class DecomposePrintfHandler : public CheckPrintfHandler {
8879 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8880 bool HadError;
8881
8882 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8883 const Expr *origFormatExpr,
8884 const FormatStringType type, unsigned firstDataArg,
8885 unsigned numDataArgs, bool isObjC, const char *beg,
8886 Sema::FormatArgumentPassingKind APK,
8887 ArrayRef<const Expr *> Args, unsigned formatIdx,
8888 bool inFunctionCall, VariadicCallType CallType,
8889 llvm::SmallBitVector &CheckedVarArgs,
8890 UncoveredArgHandler &UncoveredArg,
8891 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8892 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8893 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8894 inFunctionCall, CallType, CheckedVarArgs,
8895 UncoveredArg),
8896 Specs(Specs), HadError(false) {}
8897
8898public:
8899 static bool
8900 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8901 FormatStringType type, bool IsObjC, bool InFunctionCall,
8902 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8903
8904 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8905 const char *startSpecifier,
8906 unsigned specifierLen,
8907 const TargetInfo &Target) override;
8908};
8909
8910} // namespace
8911
8912bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8913 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8914 unsigned specifierLen) {
8915 const analyze_printf::PrintfConversionSpecifier &CS =
8916 FS.getConversionSpecifier();
8917
8918 return HandleInvalidConversionSpecifier(
8919 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
8920 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
8921}
8922
8923void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8924 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8925}
8926
8927// Error out if struct or complex type argments are passed to os_log.
8928static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8929 QualType T) {
8930 if (FSType != FormatStringType::OSLog)
8931 return false;
8932 return T->isRecordType() || T->isComplexType();
8933}
8934
8935bool CheckPrintfHandler::HandleAmount(
8936 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8937 const char *startSpecifier, unsigned specifierLen) {
8938 if (Amt.hasDataArgument()) {
8939 if (HasFormatArguments()) {
8940 unsigned argIndex = Amt.getArgIndex();
8941 if (argIndex >= NumDataArgs) {
8942 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8943 << k,
8944 Loc: getLocationOfByte(x: Amt.getStart()),
8945 /*IsStringLocation*/ true,
8946 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8947 // Don't do any more checking. We will just emit
8948 // spurious errors.
8949 return false;
8950 }
8951
8952 // Type check the data argument. It should be an 'int'.
8953 // Although not in conformance with C99, we also allow the argument to be
8954 // an 'unsigned int' as that is a reasonably safe case. GCC also
8955 // doesn't emit a warning for that case.
8956 CoveredArgs.set(argIndex);
8957 const Expr *Arg = getDataArg(i: argIndex);
8958 if (!Arg)
8959 return false;
8960
8961 QualType T = Arg->getType();
8962
8963 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8964 assert(AT.isValid());
8965
8966 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8967 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8968 ? diag::err_printf_asterisk_wrong_type
8969 : diag::warn_printf_asterisk_wrong_type;
8970 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8971 << k << AT.getRepresentativeTypeName(C&: S.Context)
8972 << T << Arg->getSourceRange(),
8973 Loc: getLocationOfByte(x: Amt.getStart()),
8974 /*IsStringLocation*/ true,
8975 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8976 // Don't do any more checking. We will just emit
8977 // spurious errors.
8978 return false;
8979 }
8980 }
8981 }
8982 return true;
8983}
8984
8985void CheckPrintfHandler::HandleInvalidAmount(
8986 const analyze_printf::PrintfSpecifier &FS,
8987 const analyze_printf::OptionalAmount &Amt, unsigned type,
8988 const char *startSpecifier, unsigned specifierLen) {
8989 const analyze_printf::PrintfConversionSpecifier &CS =
8990 FS.getConversionSpecifier();
8991
8992 FixItHint fixit =
8993 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8994 ? FixItHint::CreateRemoval(
8995 RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength()))
8996 : FixItHint();
8997
8998 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8999 << type << CS.toString(),
9000 Loc: getLocationOfByte(x: Amt.getStart()),
9001 /*IsStringLocation*/ true,
9002 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: fixit);
9003}
9004
9005void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
9006 const analyze_printf::OptionalFlag &flag,
9007 const char *startSpecifier,
9008 unsigned specifierLen) {
9009 // Warn about pointless flag with a fixit removal.
9010 const analyze_printf::PrintfConversionSpecifier &CS =
9011 FS.getConversionSpecifier();
9012 EmitFormatDiagnostic(
9013 PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
9014 << flag.toString() << CS.toString(),
9015 Loc: getLocationOfByte(x: flag.getPosition()),
9016 /*IsStringLocation*/ true,
9017 StringRange: getSpecifierRange(startSpecifier, specifierLen),
9018 FixIt: FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
9019}
9020
9021void CheckPrintfHandler::HandleIgnoredFlag(
9022 const analyze_printf::PrintfSpecifier &FS,
9023 const analyze_printf::OptionalFlag &ignoredFlag,
9024 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
9025 unsigned specifierLen) {
9026 // Warn about ignored flag with a fixit removal.
9027 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
9028 << ignoredFlag.toString() << flag.toString(),
9029 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
9030 /*IsStringLocation*/ true,
9031 StringRange: getSpecifierRange(startSpecifier, specifierLen),
9032 FixIt: FixItHint::CreateRemoval(
9033 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
9034}
9035
9036void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9037 unsigned flagLen) {
9038 // Warn about an empty flag.
9039 EmitFormatDiagnostic(
9040 PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag), Loc: getLocationOfByte(x: startFlag),
9041 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
9042}
9043
9044void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9045 unsigned flagLen) {
9046 // Warn about an invalid flag.
9047 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
9048 StringRef flag(startFlag, flagLen);
9049 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
9050 Loc: getLocationOfByte(x: startFlag),
9051 /*IsStringLocation*/ true, StringRange: Range,
9052 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
9053}
9054
9055void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9056 const char *flagsStart, const char *flagsEnd,
9057 const char *conversionPosition) {
9058 // Warn about using '[...]' without a '@' conversion.
9059 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
9060 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9061 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
9062 Loc: getLocationOfByte(x: conversionPosition),
9063 /*IsStringLocation*/ true, StringRange: Range,
9064 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
9065}
9066
9067void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
9068 const Expr *FmtExpr,
9069 bool InFunctionCall) const {
9070 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
9071 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
9072}
9073
9074bool EquatableFormatArgument::VerifyCompatible(
9075 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
9076 bool InFunctionCall) const {
9077 using MK = analyze_format_string::ArgType::MatchKind;
9078 if (Role != Other.Role) {
9079 // diagnose and stop
9080 EmitDiagnostic(
9081 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
9082 FmtExpr, InFunctionCall);
9083 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
9084 return false;
9085 }
9086
9087 if (Role != FAR_Data) {
9088 if (ModifierFor != Other.ModifierFor) {
9089 // diagnose and stop
9090 EmitDiagnostic(S,
9091 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
9092 << (ModifierFor + 1) << (Other.ModifierFor + 1),
9093 FmtExpr, InFunctionCall);
9094 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
9095 return false;
9096 }
9097 return true;
9098 }
9099
9100 bool HadError = false;
9101 if (Sensitivity != Other.Sensitivity) {
9102 // diagnose and continue
9103 EmitDiagnostic(S,
9104 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
9105 << Sensitivity << Other.Sensitivity,
9106 FmtExpr, InFunctionCall);
9107 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9108 << 0 << Other.Range;
9109 }
9110
9111 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
9112 case MK::Match:
9113 break;
9114
9115 case MK::MatchPromotion:
9116 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
9117 // MatchPromotion is treated as a failure by format_matches.
9118 case MK::NoMatch:
9119 case MK::NoMatchTypeConfusion:
9120 case MK::NoMatchPromotionTypeConfusion:
9121 EmitDiagnostic(S,
9122 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
9123 << buildFormatSpecifier()
9124 << Other.buildFormatSpecifier(),
9125 FmtExpr, InFunctionCall);
9126 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9127 << 0 << Other.Range;
9128 break;
9129
9130 case MK::NoMatchPedantic:
9131 EmitDiagnostic(S,
9132 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
9133 << buildFormatSpecifier()
9134 << Other.buildFormatSpecifier(),
9135 FmtExpr, InFunctionCall);
9136 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9137 << 0 << Other.Range;
9138 break;
9139
9140 case MK::NoMatchSignedness:
9141 EmitDiagnostic(S,
9142 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
9143 << buildFormatSpecifier()
9144 << Other.buildFormatSpecifier(),
9145 FmtExpr, InFunctionCall);
9146 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9147 << 0 << Other.Range;
9148 break;
9149 }
9150 return !HadError;
9151}
9152
9153bool DecomposePrintfHandler::GetSpecifiers(
9154 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
9155 FormatStringType Type, bool IsObjC, bool InFunctionCall,
9156 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
9157 StringRef Data = FSL->getString();
9158 const char *Str = Data.data();
9159 llvm::SmallBitVector BV;
9160 UncoveredArgHandler UA;
9161 const Expr *PrintfArgs[] = {FSL->getFormatString()};
9162 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
9163 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
9164 InFunctionCall, VariadicCallType::DoesNotApply, BV,
9165 UA, Args);
9166
9167 if (!analyze_format_string::ParsePrintfString(
9168 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
9169 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
9170 H.DoneProcessing();
9171 if (H.HadError)
9172 return false;
9173
9174 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
9175 const EquatableFormatArgument &B) {
9176 return A.getPosition() < B.getPosition();
9177 });
9178 return true;
9179}
9180
9181bool DecomposePrintfHandler::HandlePrintfSpecifier(
9182 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9183 unsigned specifierLen, const TargetInfo &Target) {
9184 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
9185 specifierLen, Target)) {
9186 HadError = true;
9187 return false;
9188 }
9189
9190 // Do not add any specifiers to the list for %%. This is possibly incorrect
9191 // if using a precision/width with a data argument, but that combination is
9192 // meaningless and we wouldn't know which format to attach the
9193 // precision/width to.
9194 const auto &CS = FS.getConversionSpecifier();
9195 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
9196 return true;
9197
9198 // have to patch these to have the right ModifierFor if they are used
9199 const unsigned Unset = ~0;
9200 unsigned FieldWidthIndex = Unset;
9201 unsigned PrecisionIndex = Unset;
9202
9203 // field width?
9204 const auto &FieldWidth = FS.getFieldWidth();
9205 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9206 FieldWidthIndex = Specs.size();
9207 Specs.emplace_back(
9208 Args: getSpecifierRange(startSpecifier, specifierLen),
9209 Args: getLocationOfByte(x: FieldWidth.getStart()),
9210 Args: analyze_format_string::LengthModifier(), Args: FieldWidth.getCharacters(),
9211 Args: FieldWidth.getArgType(Ctx&: S.Context),
9212 Args: EquatableFormatArgument::FAR_FieldWidth,
9213 Args: EquatableFormatArgument::SS_None,
9214 Args: FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9215 : FieldWidthIndex,
9216 Args: 0);
9217 }
9218 // precision?
9219 const auto &Precision = FS.getPrecision();
9220 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9221 PrecisionIndex = Specs.size();
9222 Specs.emplace_back(
9223 Args: getSpecifierRange(startSpecifier, specifierLen),
9224 Args: getLocationOfByte(x: Precision.getStart()),
9225 Args: analyze_format_string::LengthModifier(), Args: Precision.getCharacters(),
9226 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
9227 Args: EquatableFormatArgument::SS_None,
9228 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9229 : PrecisionIndex,
9230 Args: 0);
9231 }
9232
9233 // this specifier
9234 unsigned SpecIndex =
9235 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9236 if (FieldWidthIndex != Unset)
9237 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9238 if (PrecisionIndex != Unset)
9239 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9240
9241 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9242 if (FS.isPrivate())
9243 Sensitivity = EquatableFormatArgument::SS_Private;
9244 else if (FS.isPublic())
9245 Sensitivity = EquatableFormatArgument::SS_Public;
9246 else if (FS.isSensitive())
9247 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9248 else
9249 Sensitivity = EquatableFormatArgument::SS_None;
9250
9251 Specs.emplace_back(
9252 Args: getSpecifierRange(startSpecifier, specifierLen),
9253 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier(),
9254 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
9255 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
9256
9257 // auxiliary argument?
9258 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
9259 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
9260 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
9261 Args: getLocationOfByte(x: CS.getStart()),
9262 Args: analyze_format_string::LengthModifier(),
9263 Args: CS.getCharacters(),
9264 Args: analyze_format_string::ArgType::CStrTy,
9265 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
9266 Args: SpecIndex + 1, Args&: SpecIndex);
9267 }
9268 return true;
9269}
9270
9271// Determines if the specified is a C++ class or struct containing
9272// a member with the specified name and kind (e.g. a CXXMethodDecl named
9273// "c_str()").
9274template<typename MemberKind>
9275static llvm::SmallPtrSet<MemberKind*, 1>
9276CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9277 auto *RD = Ty->getAsCXXRecordDecl();
9278 llvm::SmallPtrSet<MemberKind*, 1> Results;
9279
9280 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9281 return Results;
9282
9283 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9284 Sema::LookupMemberName);
9285 R.suppressDiagnostics();
9286
9287 // We just need to include all members of the right kind turned up by the
9288 // filter, at this point.
9289 if (S.LookupQualifiedName(R, LookupCtx: RD))
9290 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9291 NamedDecl *decl = (*I)->getUnderlyingDecl();
9292 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9293 Results.insert(FK);
9294 }
9295 return Results;
9296}
9297
9298/// Check if we could call '.c_str()' on an object.
9299///
9300/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9301/// allow the call, or if it would be ambiguous).
9302bool Sema::hasCStrMethod(const Expr *E) {
9303 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9304
9305 MethodSet Results =
9306 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
9307 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9308 MI != ME; ++MI)
9309 if ((*MI)->getMinRequiredArguments() == 0)
9310 return true;
9311 return false;
9312}
9313
9314// Check if a (w)string was passed when a (w)char* was needed, and offer a
9315// better diagnostic if so. AT is assumed to be valid.
9316// Returns true when a c_str() conversion method is found.
9317bool CheckPrintfHandler::checkForCStrMembers(
9318 const analyze_printf::ArgType &AT, const Expr *E) {
9319 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9320
9321 MethodSet Results =
9322 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
9323
9324 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9325 MI != ME; ++MI) {
9326 const CXXMethodDecl *Method = *MI;
9327 if (Method->getMinRequiredArguments() == 0 &&
9328 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
9329 // FIXME: Suggest parens if the expression needs them.
9330 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
9331 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
9332 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
9333 return true;
9334 }
9335 }
9336
9337 return false;
9338}
9339
9340bool CheckPrintfHandler::HandlePrintfSpecifier(
9341 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9342 unsigned specifierLen, const TargetInfo &Target) {
9343 using namespace analyze_format_string;
9344 using namespace analyze_printf;
9345
9346 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9347
9348 if (FS.consumesDataArgument()) {
9349 if (atFirstArg) {
9350 atFirstArg = false;
9351 usesPositionalArgs = FS.usesPositionalArg();
9352 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9353 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9354 startSpec: startSpecifier, specifierLen);
9355 return false;
9356 }
9357 }
9358
9359 // First check if the field width, precision, and conversion specifier
9360 // have matching data arguments.
9361 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0, startSpecifier,
9362 specifierLen)) {
9363 return false;
9364 }
9365
9366 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1, startSpecifier,
9367 specifierLen)) {
9368 return false;
9369 }
9370
9371 if (!CS.consumesDataArgument()) {
9372 // FIXME: Technically specifying a precision or field width here
9373 // makes no sense. Worth issuing a warning at some point.
9374 return true;
9375 }
9376
9377 // Consume the argument.
9378 unsigned argIndex = FS.getArgIndex();
9379 if (argIndex < NumDataArgs) {
9380 // The check to see if the argIndex is valid will come later.
9381 // We set the bit here because we may exit early from this
9382 // function if we encounter some other error.
9383 CoveredArgs.set(argIndex);
9384 }
9385
9386 // FreeBSD kernel extensions.
9387 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9388 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9389 // We need at least two arguments.
9390 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
9391 return false;
9392
9393 if (HasFormatArguments()) {
9394 // Claim the second argument.
9395 CoveredArgs.set(argIndex + 1);
9396
9397 // Type check the first argument (int for %b, pointer for %D)
9398 const Expr *Ex = getDataArg(i: argIndex);
9399 const analyze_printf::ArgType &AT =
9400 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9401 ? ArgType(S.Context.IntTy)
9402 : ArgType::CPointerTy;
9403 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
9404 EmitFormatDiagnostic(
9405 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9406 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9407 << false << Ex->getSourceRange(),
9408 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9409 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9410
9411 // Type check the second argument (char * for both %b and %D)
9412 Ex = getDataArg(i: argIndex + 1);
9413 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9414 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
9415 EmitFormatDiagnostic(
9416 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9417 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9418 << false << Ex->getSourceRange(),
9419 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9420 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9421 }
9422 return true;
9423 }
9424
9425 // Check for using an Objective-C specific conversion specifier
9426 // in a non-ObjC literal.
9427 if (!allowsObjCArg() && CS.isObjCArg()) {
9428 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9429 specifierLen);
9430 }
9431
9432 // %P can only be used with os_log.
9433 if (FSType != FormatStringType::OSLog &&
9434 CS.getKind() == ConversionSpecifier::PArg) {
9435 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9436 specifierLen);
9437 }
9438
9439 // %n is not allowed with os_log.
9440 if (FSType == FormatStringType::OSLog &&
9441 CS.getKind() == ConversionSpecifier::nArg) {
9442 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
9443 Loc: getLocationOfByte(x: CS.getStart()),
9444 /*IsStringLocation*/ false,
9445 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9446
9447 return true;
9448 }
9449
9450 // Only scalars are allowed for os_trace.
9451 if (FSType == FormatStringType::OSTrace &&
9452 (CS.getKind() == ConversionSpecifier::PArg ||
9453 CS.getKind() == ConversionSpecifier::sArg ||
9454 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9455 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9456 specifierLen);
9457 }
9458
9459 // Check for use of public/private annotation outside of os_log().
9460 if (FSType != FormatStringType::OSLog) {
9461 if (FS.isPublic().isSet()) {
9462 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9463 << "public",
9464 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
9465 /*IsStringLocation*/ false,
9466 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9467 }
9468 if (FS.isPrivate().isSet()) {
9469 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9470 << "private",
9471 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
9472 /*IsStringLocation*/ false,
9473 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9474 }
9475 }
9476
9477 const llvm::Triple &Triple = Target.getTriple();
9478 if (CS.getKind() == ConversionSpecifier::nArg &&
9479 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9480 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
9481 Loc: getLocationOfByte(x: CS.getStart()),
9482 /*IsStringLocation*/ false,
9483 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9484 }
9485
9486 // Check for invalid use of field width
9487 if (!FS.hasValidFieldWidth()) {
9488 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
9489 startSpecifier, specifierLen);
9490 }
9491
9492 // Check for invalid use of precision
9493 if (!FS.hasValidPrecision()) {
9494 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
9495 startSpecifier, specifierLen);
9496 }
9497
9498 // Precision is mandatory for %P specifier.
9499 if (CS.getKind() == ConversionSpecifier::PArg &&
9500 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9501 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
9502 Loc: getLocationOfByte(x: startSpecifier),
9503 /*IsStringLocation*/ false,
9504 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9505 }
9506
9507 // Check each flag does not conflict with any other component.
9508 if (!FS.hasValidThousandsGroupingPrefix())
9509 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9510 if (!FS.hasValidLeadingZeros())
9511 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
9512 if (!FS.hasValidPlusPrefix())
9513 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
9514 if (!FS.hasValidSpacePrefix())
9515 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
9516 if (!FS.hasValidAlternativeForm())
9517 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
9518 if (!FS.hasValidLeftJustified())
9519 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
9520
9521 // Check that flags are not ignored by another flag
9522 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9523 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
9524 startSpecifier, specifierLen);
9525 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9526 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
9527 startSpecifier, specifierLen);
9528
9529 // Check the length modifier is valid with the given conversion specifier.
9530 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9531 LO: S.getLangOpts()))
9532 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9533 DiagID: diag::warn_format_nonsensical_length);
9534 else if (!FS.hasStandardLengthModifier())
9535 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9536 else if (!FS.hasStandardLengthConversionCombination())
9537 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9538 DiagID: diag::warn_format_non_standard_conversion_spec);
9539
9540 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9541 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9542
9543 // The remaining checks depend on the data arguments.
9544 if (!HasFormatArguments())
9545 return true;
9546
9547 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9548 return false;
9549
9550 const Expr *Arg = getDataArg(i: argIndex);
9551 if (!Arg)
9552 return true;
9553
9554 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
9555}
9556
9557static bool requiresParensToAddCast(const Expr *E) {
9558 // FIXME: We should have a general way to reason about operator
9559 // precedence and whether parens are actually needed here.
9560 // Take care of a few common cases where they aren't.
9561 const Expr *Inside = E->IgnoreImpCasts();
9562 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
9563 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9564
9565 switch (Inside->getStmtClass()) {
9566 case Stmt::ArraySubscriptExprClass:
9567 case Stmt::CallExprClass:
9568 case Stmt::CharacterLiteralClass:
9569 case Stmt::CXXBoolLiteralExprClass:
9570 case Stmt::DeclRefExprClass:
9571 case Stmt::FloatingLiteralClass:
9572 case Stmt::IntegerLiteralClass:
9573 case Stmt::MemberExprClass:
9574 case Stmt::ObjCArrayLiteralClass:
9575 case Stmt::ObjCBoolLiteralExprClass:
9576 case Stmt::ObjCBoxedExprClass:
9577 case Stmt::ObjCDictionaryLiteralClass:
9578 case Stmt::ObjCEncodeExprClass:
9579 case Stmt::ObjCIvarRefExprClass:
9580 case Stmt::ObjCMessageExprClass:
9581 case Stmt::ObjCPropertyRefExprClass:
9582 case Stmt::ObjCStringLiteralClass:
9583 case Stmt::ObjCSubscriptRefExprClass:
9584 case Stmt::ParenExprClass:
9585 case Stmt::StringLiteralClass:
9586 case Stmt::UnaryOperatorClass:
9587 return false;
9588 default:
9589 return true;
9590 }
9591}
9592
9593static std::pair<QualType, StringRef>
9594shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9595 const Expr *E) {
9596 // Use a 'while' to peel off layers of typedefs.
9597 QualType TyTy = IntendedTy;
9598 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9599 StringRef Name = UserTy->getDecl()->getName();
9600 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9601 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
9602 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
9603 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
9604 .Case(S: "SInt32", Value: Context.IntTy)
9605 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
9606 .Default(Value: QualType());
9607
9608 if (!CastTy.isNull())
9609 return std::make_pair(x&: CastTy, y&: Name);
9610
9611 TyTy = UserTy->desugar();
9612 }
9613
9614 // Strip parens if necessary.
9615 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
9616 return shouldNotPrintDirectly(Context, IntendedTy: PE->getSubExpr()->getType(),
9617 E: PE->getSubExpr());
9618
9619 // If this is a conditional expression, then its result type is constructed
9620 // via usual arithmetic conversions and thus there might be no necessary
9621 // typedef sugar there. Recurse to operands to check for NSInteger &
9622 // Co. usage condition.
9623 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
9624 QualType TrueTy, FalseTy;
9625 StringRef TrueName, FalseName;
9626
9627 std::tie(args&: TrueTy, args&: TrueName) = shouldNotPrintDirectly(
9628 Context, IntendedTy: CO->getTrueExpr()->getType(), E: CO->getTrueExpr());
9629 std::tie(args&: FalseTy, args&: FalseName) = shouldNotPrintDirectly(
9630 Context, IntendedTy: CO->getFalseExpr()->getType(), E: CO->getFalseExpr());
9631
9632 if (TrueTy == FalseTy)
9633 return std::make_pair(x&: TrueTy, y&: TrueName);
9634 else if (TrueTy.isNull())
9635 return std::make_pair(x&: FalseTy, y&: FalseName);
9636 else if (FalseTy.isNull())
9637 return std::make_pair(x&: TrueTy, y&: TrueName);
9638 }
9639
9640 return std::make_pair(x: QualType(), y: StringRef());
9641}
9642
9643/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9644/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9645/// type do not count.
9646static bool isArithmeticArgumentPromotion(Sema &S,
9647 const ImplicitCastExpr *ICE) {
9648 QualType From = ICE->getSubExpr()->getType();
9649 QualType To = ICE->getType();
9650 // It's an integer promotion if the destination type is the promoted
9651 // source type.
9652 if (ICE->getCastKind() == CK_IntegralCast &&
9653 S.Context.isPromotableIntegerType(T: From) &&
9654 S.Context.getPromotedIntegerType(PromotableType: From) == To)
9655 return true;
9656 // Look through vector types, since we do default argument promotion for
9657 // those in OpenCL.
9658 if (const auto *VecTy = From->getAs<ExtVectorType>())
9659 From = VecTy->getElementType();
9660 if (const auto *VecTy = To->getAs<ExtVectorType>())
9661 To = VecTy->getElementType();
9662 // It's a floating promotion if the source type is a lower rank.
9663 return ICE->getCastKind() == CK_FloatingCast &&
9664 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9665}
9666
9667static analyze_format_string::ArgType::MatchKind
9668handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9669 DiagnosticsEngine &Diags, SourceLocation Loc) {
9670 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9671 if (Diags.isIgnored(
9672 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9673 Loc) ||
9674 Diags.isIgnored(
9675 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9676 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9677 return analyze_format_string::ArgType::Match;
9678 }
9679 }
9680 return Match;
9681}
9682
9683bool CheckPrintfHandler::checkFormatExpr(
9684 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9685 unsigned SpecifierLen, const Expr *E) {
9686 using namespace analyze_format_string;
9687 using namespace analyze_printf;
9688
9689 // Now type check the data expression that matches the
9690 // format specifier.
9691 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9692 if (!AT.isValid())
9693 return true;
9694
9695 QualType ExprTy = E->getType();
9696 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9697 ExprTy = TET->getUnderlyingExpr()->getType();
9698 }
9699
9700 if (const OverflowBehaviorType *OBT =
9701 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9702 ExprTy = OBT->getUnderlyingType();
9703
9704 // When using the format attribute in C++, you can receive a function or an
9705 // array that will necessarily decay to a pointer when passed to the final
9706 // format consumer. Apply decay before type comparison.
9707 if (ExprTy->canDecayToPointerType())
9708 ExprTy = S.Context.getDecayedType(T: ExprTy);
9709
9710 // Diagnose attempts to print a boolean value as a character. Unlike other
9711 // -Wformat diagnostics, this is fine from a type perspective, but it still
9712 // doesn't make sense.
9713 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9714 E->isKnownToHaveBooleanValue()) {
9715 const CharSourceRange &CSR =
9716 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9717 SmallString<4> FSString;
9718 llvm::raw_svector_ostream os(FSString);
9719 FS.toString(os);
9720 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9721 << FSString,
9722 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9723 return true;
9724 }
9725
9726 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9727 // dumping raw class data (like is-a pointer), not actual data.
9728 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9729 ExprTy->isObjCObjectPointerType()) {
9730 const CharSourceRange &CSR =
9731 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9732 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9733 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9734 return true;
9735 }
9736
9737 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9738 return true;
9739
9740 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9741 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9742 ArgType::MatchKind OrigMatch = Match;
9743
9744 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9745 if (Match == ArgType::Match)
9746 return true;
9747
9748 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9749 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9750
9751 // Look through argument promotions for our error message's reported type.
9752 // This includes the integral and floating promotions, but excludes array
9753 // and function pointer decay (seeing that an argument intended to be a
9754 // string has type 'char [6]' is probably more confusing than 'char *') and
9755 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9756 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9757 if (isArithmeticArgumentPromotion(S, ICE)) {
9758 E = ICE->getSubExpr();
9759 ExprTy = E->getType();
9760
9761 // Check if we didn't match because of an implicit cast from a 'char'
9762 // or 'short' to an 'int'. This is done because printf is a varargs
9763 // function.
9764 if (ICE->getType() == S.Context.IntTy ||
9765 ICE->getType() == S.Context.UnsignedIntTy) {
9766 // All further checking is done on the subexpression
9767 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9768 if (OrigMatch == ArgType::NoMatchSignedness &&
9769 ImplicitMatch != ArgType::NoMatchSignedness)
9770 // If the original match was a signedness match this match on the
9771 // implicit cast type also need to be signedness match otherwise we
9772 // might introduce new unexpected warnings from -Wformat-signedness.
9773 return true;
9774 ImplicitMatch = handleFormatSignedness(
9775 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9776 if (ImplicitMatch == ArgType::Match)
9777 return true;
9778 }
9779 }
9780 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9781 // Special case for 'a', which has type 'int' in C.
9782 // Note, however, that we do /not/ want to treat multibyte constants like
9783 // 'MooV' as characters! This form is deprecated but still exists. In
9784 // addition, don't treat expressions as of type 'char' if one byte length
9785 // modifier is provided.
9786 if (ExprTy == S.Context.IntTy &&
9787 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9788 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9789 ExprTy = S.Context.CharTy;
9790 // To improve check results, we consider a character literal in C
9791 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9792 // more likely a type confusion situation, so we will suggest to
9793 // use '%hhd' instead by discarding the MatchPromotion.
9794 if (Match == ArgType::MatchPromotion)
9795 Match = ArgType::NoMatch;
9796 }
9797 }
9798 if (Match == ArgType::MatchPromotion) {
9799 // WG14 N2562 only clarified promotions in *printf
9800 // For NSLog in ObjC, just preserve -Wformat behavior
9801 if (!S.getLangOpts().ObjC &&
9802 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9803 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9804 return true;
9805 Match = ArgType::NoMatch;
9806 }
9807 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9808 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9809 Match = ImplicitMatch;
9810 assert(Match != ArgType::MatchPromotion);
9811
9812 // Look through unscoped enums to their underlying type.
9813 bool IsEnum = false;
9814 bool IsScopedEnum = false;
9815 QualType IntendedTy = ExprTy;
9816 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9817 IntendedTy = ED->getIntegerType();
9818 if (!ED->isScoped()) {
9819 ExprTy = IntendedTy;
9820 // This controls whether we're talking about the underlying type or not,
9821 // which we only want to do when it's an unscoped enum.
9822 IsEnum = true;
9823 } else {
9824 IsScopedEnum = true;
9825 }
9826 }
9827
9828 // %C in an Objective-C context prints a unichar, not a wchar_t.
9829 // If the argument is an integer of some kind, believe the %C and suggest
9830 // a cast instead of changing the conversion specifier.
9831 if (isObjCContext() &&
9832 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9833 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9834 !ExprTy->isCharType()) {
9835 // 'unichar' is defined as a typedef of unsigned short, but we should
9836 // prefer using the typedef if it is visible.
9837 IntendedTy = S.Context.UnsignedShortTy;
9838
9839 // While we are here, check if the value is an IntegerLiteral that happens
9840 // to be within the valid range.
9841 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9842 const llvm::APInt &V = IL->getValue();
9843 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9844 return true;
9845 }
9846
9847 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9848 Sema::LookupOrdinaryName);
9849 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9850 NamedDecl *ND = Result.getFoundDecl();
9851 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9852 if (TD->getUnderlyingType() == IntendedTy)
9853 IntendedTy =
9854 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9855 /*Qualifier=*/std::nullopt, Decl: TD);
9856 }
9857 }
9858 }
9859
9860 // Special-case some of Darwin's platform-independence types by suggesting
9861 // casts to primitive types that are known to be large enough.
9862 bool ShouldNotPrintDirectly = false;
9863 StringRef CastTyName;
9864 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9865 QualType CastTy;
9866 std::tie(args&: CastTy, args&: CastTyName) =
9867 shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9868 if (!CastTy.isNull()) {
9869 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9870 // (long in ASTContext). Only complain to pedants or when they're the
9871 // underlying type of a scoped enum (which always needs a cast).
9872 if (!IsScopedEnum &&
9873 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9874 (AT.isSizeT() || AT.isPtrdiffT()) &&
9875 AT.matchesType(C&: S.Context, argTy: CastTy))
9876 Match = ArgType::NoMatchPedantic;
9877 IntendedTy = CastTy;
9878 ShouldNotPrintDirectly = true;
9879 }
9880 }
9881
9882 // We may be able to offer a FixItHint if it is a supported type.
9883 PrintfSpecifier fixedFS = FS;
9884 bool Success =
9885 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9886
9887 if (Success) {
9888 // Get the fix string from the fixed format specifier
9889 SmallString<16> buf;
9890 llvm::raw_svector_ostream os(buf);
9891 fixedFS.toString(os);
9892
9893 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9894
9895 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9896 unsigned Diag;
9897 switch (Match) {
9898 case ArgType::Match:
9899 case ArgType::MatchPromotion:
9900 case ArgType::NoMatchPromotionTypeConfusion:
9901 llvm_unreachable("expected non-matching");
9902 case ArgType::NoMatchSignedness:
9903 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9904 break;
9905 case ArgType::NoMatchPedantic:
9906 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9907 break;
9908 case ArgType::NoMatchTypeConfusion:
9909 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9910 break;
9911 case ArgType::NoMatch:
9912 Diag = diag::warn_format_conversion_argument_type_mismatch;
9913 break;
9914 }
9915
9916 // In this case, the specifier is wrong and should be changed to match
9917 // the argument.
9918 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9919 << AT.getRepresentativeTypeName(C&: S.Context)
9920 << IntendedTy << IsEnum << E->getSourceRange(),
9921 Loc: E->getBeginLoc(),
9922 /*IsStringLocation*/ false, StringRange: SpecRange,
9923 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9924 } else {
9925 // The canonical type for formatting this value is different from the
9926 // actual type of the expression. (This occurs, for example, with Darwin's
9927 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9928 // should be printed as 'long' for 64-bit compatibility.)
9929 // Rather than emitting a normal format/argument mismatch, we want to
9930 // add a cast to the recommended type (and correct the format string
9931 // if necessary). We should also do so for scoped enumerations.
9932 SmallString<16> CastBuf;
9933 llvm::raw_svector_ostream CastFix(CastBuf);
9934 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9935 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9936 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9937
9938 SmallVector<FixItHint, 4> Hints;
9939 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9940 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9941 Loc: E->getExprLoc());
9942 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9943 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9944
9945 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9946 // If there's already a cast present, just replace it.
9947 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9948 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9949
9950 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9951 // If the expression has high enough precedence,
9952 // just write the C-style cast.
9953 Hints.push_back(
9954 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9955 } else {
9956 // Otherwise, add parens around the expression as well as the cast.
9957 CastFix << "(";
9958 Hints.push_back(
9959 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9960
9961 // We don't use getLocForEndOfToken because it returns invalid source
9962 // locations for macro expansions (by design).
9963 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9964 SourceLocation After = EndLoc.getLocWithOffset(
9965 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9966 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9967 }
9968
9969 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9970 // The expression has a type that should not be printed directly.
9971 // We extract the name from the typedef because we don't want to show
9972 // the underlying type in the diagnostic.
9973 StringRef Name;
9974 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9975 Name = TypedefTy->getDecl()->getName();
9976 else
9977 Name = CastTyName;
9978 unsigned Diag = Match == ArgType::NoMatchPedantic
9979 ? diag::warn_format_argument_needs_cast_pedantic
9980 : diag::warn_format_argument_needs_cast;
9981 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9982 << E->getSourceRange(),
9983 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9984 StringRange: SpecRange, FixIt: Hints);
9985 } else {
9986 // In this case, the expression could be printed using a different
9987 // specifier, but we've decided that the specifier is probably correct
9988 // and we should cast instead. Just use the normal warning message.
9989
9990 unsigned Diag =
9991 IsScopedEnum
9992 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9993 : diag::warn_format_conversion_argument_type_mismatch;
9994
9995 EmitFormatDiagnostic(
9996 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9997 << IsEnum << E->getSourceRange(),
9998 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9999 }
10000 }
10001 } else {
10002 const CharSourceRange &CSR =
10003 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
10004 // Since the warning for passing non-POD types to variadic functions
10005 // was deferred until now, we emit a warning for non-POD
10006 // arguments here.
10007 bool EmitTypeMismatch = false;
10008 // Record and complex type arguments cannot be code generated for os_log
10009 // and would crash CodeGen, so they are rejected with a hard error emitted
10010 // after the switch below.
10011 bool EmitOSLogError = false;
10012 switch (S.isValidVarArgType(Ty: ExprTy)) {
10013 case VarArgKind::Valid:
10014 case VarArgKind::ValidInCXX11: {
10015 unsigned Diag;
10016 switch (Match) {
10017 case ArgType::Match:
10018 case ArgType::MatchPromotion:
10019 case ArgType::NoMatchPromotionTypeConfusion:
10020 llvm_unreachable("expected non-matching");
10021 case ArgType::NoMatchSignedness:
10022 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
10023 break;
10024 case ArgType::NoMatchPedantic:
10025 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
10026 break;
10027 case ArgType::NoMatchTypeConfusion:
10028 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
10029 break;
10030 case ArgType::NoMatch:
10031 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy);
10032 Diag = diag::warn_format_conversion_argument_type_mismatch;
10033 break;
10034 }
10035
10036 if (!EmitOSLogError)
10037 EmitFormatDiagnostic(
10038 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
10039 << IsEnum << CSR << E->getSourceRange(),
10040 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
10041 break;
10042 }
10043 case VarArgKind::Undefined:
10044 case VarArgKind::MSVCUndefined:
10045 if (CallType == VariadicCallType::DoesNotApply) {
10046 EmitTypeMismatch = true;
10047 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)) {
10048 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
10049 // does not stop compilation.
10050 EmitOSLogError = true;
10051 } else {
10052 EmitFormatDiagnostic(
10053 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
10054 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10055 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
10056 << E->getSourceRange(),
10057 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
10058 checkForCStrMembers(AT, E);
10059 }
10060 break;
10061
10062 case VarArgKind::Invalid:
10063 if (CallType == VariadicCallType::DoesNotApply)
10064 EmitTypeMismatch = true;
10065 else if (ExprTy->isObjCObjectType())
10066 EmitFormatDiagnostic(
10067 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
10068 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10069 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
10070 << E->getSourceRange(),
10071 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
10072 else
10073 // FIXME: If this is an initializer list, suggest removing the braces
10074 // or inserting a cast to the target type.
10075 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
10076 << isa<InitListExpr>(Val: E) << ExprTy << CallType
10077 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
10078 break;
10079 }
10080
10081 if (EmitOSLogError)
10082 EmitFormatDiagnostic(
10083 PDiag: S.PDiag(DiagID: diag::err_format_conversion_argument_type_mismatch)
10084 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << IsEnum
10085 << CSR << E->getSourceRange(),
10086 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
10087
10088 if (EmitTypeMismatch) {
10089 // The function is not variadic, so we do not generate warnings about
10090 // being allowed to pass that object as a variadic argument. Instead,
10091 // since there are inherently no printf specifiers for types which cannot
10092 // be passed as variadic arguments, emit a plain old specifier mismatch
10093 // argument.
10094 EmitFormatDiagnostic(
10095 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
10096 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
10097 << E->getSourceRange(),
10098 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
10099 }
10100
10101 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10102 "format string specifier index out of range");
10103 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10104 }
10105
10106 return true;
10107}
10108
10109//===--- CHECK: Scanf format string checking ------------------------------===//
10110
10111namespace {
10112
10113class CheckScanfHandler : public CheckFormatHandler {
10114public:
10115 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10116 const Expr *origFormatExpr, FormatStringType type,
10117 unsigned firstDataArg, unsigned numDataArgs,
10118 const char *beg, Sema::FormatArgumentPassingKind APK,
10119 ArrayRef<const Expr *> Args, unsigned formatIdx,
10120 bool inFunctionCall, VariadicCallType CallType,
10121 llvm::SmallBitVector &CheckedVarArgs,
10122 UncoveredArgHandler &UncoveredArg)
10123 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10124 numDataArgs, beg, APK, Args, formatIdx,
10125 inFunctionCall, CallType, CheckedVarArgs,
10126 UncoveredArg) {}
10127
10128 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10129 const char *startSpecifier,
10130 unsigned specifierLen) override;
10131
10132 bool
10133 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10134 const char *startSpecifier,
10135 unsigned specifierLen) override;
10136
10137 void HandleIncompleteScanList(const char *start, const char *end) override;
10138};
10139
10140} // namespace
10141
10142void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10143 const char *end) {
10144 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
10145 Loc: getLocationOfByte(x: end), /*IsStringLocation*/ true,
10146 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
10147}
10148
10149bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10150 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10151 unsigned specifierLen) {
10152 const analyze_scanf::ScanfConversionSpecifier &CS =
10153 FS.getConversionSpecifier();
10154
10155 return HandleInvalidConversionSpecifier(
10156 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
10157 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
10158}
10159
10160bool CheckScanfHandler::HandleScanfSpecifier(
10161 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10162 unsigned specifierLen) {
10163 using namespace analyze_scanf;
10164 using namespace analyze_format_string;
10165
10166 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10167
10168 // Handle case where '%' and '*' don't consume an argument. These shouldn't
10169 // be used to decide if we are using positional arguments consistently.
10170 if (FS.consumesDataArgument()) {
10171 if (atFirstArg) {
10172 atFirstArg = false;
10173 usesPositionalArgs = FS.usesPositionalArg();
10174 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
10175 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
10176 startSpec: startSpecifier, specifierLen);
10177 return false;
10178 }
10179 }
10180
10181 // Check if the field with is non-zero.
10182 const OptionalAmount &Amt = FS.getFieldWidth();
10183 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
10184 if (Amt.getConstantAmount() == 0) {
10185 const CharSourceRange &R =
10186 getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength());
10187 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
10188 Loc: getLocationOfByte(x: Amt.getStart()),
10189 /*IsStringLocation*/ true, StringRange: R,
10190 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
10191 }
10192 }
10193
10194 if (!FS.consumesDataArgument()) {
10195 // FIXME: Technically specifying a precision or field width here
10196 // makes no sense. Worth issuing a warning at some point.
10197 return true;
10198 }
10199
10200 // Consume the argument.
10201 unsigned argIndex = FS.getArgIndex();
10202 if (argIndex < NumDataArgs) {
10203 // The check to see if the argIndex is valid will come later.
10204 // We set the bit here because we may exit early from this
10205 // function if we encounter some other error.
10206 CoveredArgs.set(argIndex);
10207 }
10208
10209 // Check the length modifier is valid with the given conversion specifier.
10210 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
10211 LO: S.getLangOpts()))
10212 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10213 DiagID: diag::warn_format_nonsensical_length);
10214 else if (!FS.hasStandardLengthModifier())
10215 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10216 else if (!FS.hasStandardLengthConversionCombination())
10217 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10218 DiagID: diag::warn_format_non_standard_conversion_spec);
10219
10220 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
10221 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10222
10223 // The remaining checks depend on the data arguments.
10224 if (!HasFormatArguments())
10225 return true;
10226
10227 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10228 return false;
10229
10230 // Check that the argument type matches the format specifier.
10231 const Expr *Ex = getDataArg(i: argIndex);
10232 if (!Ex)
10233 return true;
10234
10235 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
10236
10237 if (!AT.isValid()) {
10238 return true;
10239 }
10240
10241 if (CheckUnsupportedType(AT, E: Ex, StartSpecifier: startSpecifier, SpecifierLen: specifierLen))
10242 return true;
10243
10244 analyze_format_string::ArgType::MatchKind Match =
10245 AT.matchesType(C&: S.Context, argTy: Ex->getType());
10246 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
10247 if (Match == analyze_format_string::ArgType::Match)
10248 return true;
10249 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10250 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
10251
10252 ScanfSpecifier fixedFS = FS;
10253 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
10254 LangOpt: S.getLangOpts(), Ctx&: S.Context);
10255
10256 unsigned Diag =
10257 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10258 : Signedness
10259 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10260 : diag::warn_format_conversion_argument_type_mismatch;
10261
10262 if (Success) {
10263 // Get the fix string from the fixed format specifier.
10264 SmallString<128> buf;
10265 llvm::raw_svector_ostream os(buf);
10266 fixedFS.toString(os);
10267
10268 EmitFormatDiagnostic(
10269 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
10270 << Ex->getType() << false << Ex->getSourceRange(),
10271 Loc: Ex->getBeginLoc(),
10272 /*IsStringLocation*/ false,
10273 StringRange: getSpecifierRange(startSpecifier, specifierLen),
10274 FixIt: FixItHint::CreateReplacement(
10275 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
10276 } else {
10277 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
10278 << AT.getRepresentativeTypeName(C&: S.Context)
10279 << Ex->getType() << false << Ex->getSourceRange(),
10280 Loc: Ex->getBeginLoc(),
10281 /*IsStringLocation*/ false,
10282 StringRange: getSpecifierRange(startSpecifier, specifierLen));
10283 }
10284
10285 return true;
10286}
10287
10288static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10289 ArrayRef<EquatableFormatArgument> RefArgs,
10290 const StringLiteral *Fmt,
10291 ArrayRef<EquatableFormatArgument> FmtArgs,
10292 const Expr *FmtExpr, bool InFunctionCall) {
10293 bool HadError = false;
10294 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10295 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10296 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10297 // In positional-style format strings, the same specifier can appear
10298 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10299 // are sorted by getPosition(), and we process each range of equal
10300 // getPosition() values as one group.
10301 // RefArgs are taken from a string literal that was given to
10302 // attribute(format_matches), and if we got this far, we have already
10303 // verified that if it has positional specifiers that appear in multiple
10304 // locations, then they are all mutually compatible. What's left for us to
10305 // do is verify that all specifiers with the same position in FmtArgs are
10306 // compatible with the RefArgs specifiers. We check each specifier from
10307 // FmtArgs against the first member of the RefArgs group.
10308 for (; FmtIter < FmtEnd; ++FmtIter) {
10309 // Clang does not diagnose missing format specifiers in positional-style
10310 // strings (TODO: which it probably should do, as it is UB to skip over a
10311 // format argument). Skip specifiers if needed.
10312 if (FmtIter->getPosition() < RefIter->getPosition())
10313 continue;
10314
10315 // Delimits a new getPosition() value.
10316 if (FmtIter->getPosition() > RefIter->getPosition())
10317 break;
10318
10319 HadError |=
10320 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
10321 }
10322
10323 // Jump RefIter to the start of the next group.
10324 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
10325 return Arg.getPosition() != RefIter->getPosition();
10326 });
10327 }
10328
10329 if (FmtIter < FmtEnd) {
10330 CheckFormatHandler::EmitFormatDiagnostic(
10331 S, InFunctionCall, ArgumentExpr: FmtExpr,
10332 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
10333 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
10334 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
10335 } else if (RefIter < RefEnd) {
10336 CheckFormatHandler::EmitFormatDiagnostic(
10337 S, InFunctionCall, ArgumentExpr: FmtExpr,
10338 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
10339 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
10340 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
10341 << 1 << RefIter->getSourceRange();
10342 }
10343 return !HadError;
10344}
10345
10346static void CheckFormatString(
10347 Sema &S, const FormatStringLiteral *FExpr,
10348 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10349 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
10350 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10351 bool inFunctionCall, VariadicCallType CallType,
10352 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10353 bool IgnoreStringsWithoutSpecifiers) {
10354 // CHECK: is the format string a wide literal?
10355 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10356 CheckFormatHandler::EmitFormatDiagnostic(
10357 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10358 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
10359 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10360 return;
10361 }
10362
10363 // Str - The format string. NOTE: this is NOT null-terminated!
10364 StringRef StrRef = FExpr->getString();
10365 const char *Str = StrRef.data();
10366 // Account for cases where the string literal is truncated in a declaration.
10367 const ConstantArrayType *T =
10368 S.Context.getAsConstantArrayType(T: FExpr->getType());
10369 assert(T && "String literal not of constant array type!");
10370 size_t TypeSize = T->getZExtSize();
10371 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10372 const unsigned numDataArgs = Args.size() - firstDataArg;
10373
10374 if (IgnoreStringsWithoutSpecifiers &&
10375 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10376 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10377 return;
10378
10379 // Emit a warning if the string literal is truncated and does not contain an
10380 // embedded null character.
10381 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
10382 CheckFormatHandler::EmitFormatDiagnostic(
10383 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10384 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
10385 Loc: FExpr->getBeginLoc(),
10386 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
10387 return;
10388 }
10389
10390 // CHECK: empty format string?
10391 if (StrLen == 0 && numDataArgs > 0) {
10392 CheckFormatHandler::EmitFormatDiagnostic(
10393 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10394 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
10395 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10396 return;
10397 }
10398
10399 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
10400 Type == FormatStringType::Kprintf ||
10401 Type == FormatStringType::FreeBSDKPrintf ||
10402 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
10403 bool IsObjC =
10404 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10405 if (ReferenceFormatString == nullptr) {
10406 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10407 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10408 inFunctionCall, CallType, CheckedVarArgs,
10409 UncoveredArg);
10410
10411 if (!analyze_format_string::ParsePrintfString(
10412 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
10413 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
10414 Type == FormatStringType::FreeBSDKPrintf))
10415 H.DoneProcessing();
10416 } else {
10417 S.CheckFormatStringsCompatible(
10418 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
10419 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
10420 }
10421 } else if (Type == FormatStringType::Scanf) {
10422 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10423 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10424 CallType, CheckedVarArgs, UncoveredArg);
10425
10426 if (!analyze_format_string::ParseScanfString(
10427 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10428 H.DoneProcessing();
10429 } // TODO: handle other formats
10430}
10431
10432bool Sema::CheckFormatStringsCompatible(
10433 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10434 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10435 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10436 Type != FormatStringType::Kprintf &&
10437 Type != FormatStringType::FreeBSDKPrintf &&
10438 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10439 return true;
10440
10441 bool IsObjC =
10442 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10443 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
10444 FormatStringLiteral RefLit = AuthoritativeFormatString;
10445 FormatStringLiteral TestLit = TestedFormatString;
10446 const Expr *Arg;
10447 bool DiagAtStringLiteral;
10448 if (FunctionCallArg) {
10449 Arg = FunctionCallArg;
10450 DiagAtStringLiteral = false;
10451 } else {
10452 Arg = TestedFormatString;
10453 DiagAtStringLiteral = true;
10454 }
10455 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
10456 FmtExpr: AuthoritativeFormatString, Type,
10457 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
10458 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
10459 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
10460 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
10461 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
10462 InFunctionCall: DiagAtStringLiteral);
10463 }
10464 return false;
10465}
10466
10467bool Sema::ValidateFormatString(FormatStringType Type,
10468 const StringLiteral *Str) {
10469 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10470 Type != FormatStringType::Kprintf &&
10471 Type != FormatStringType::FreeBSDKPrintf &&
10472 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10473 return true;
10474
10475 FormatStringLiteral RefLit = Str;
10476 llvm::SmallVector<EquatableFormatArgument, 9> Args;
10477 bool IsObjC =
10478 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10479 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
10480 InFunctionCall: true, Args))
10481 return false;
10482
10483 // Group arguments by getPosition() value, and check that each member of the
10484 // group is compatible with the first member. This verifies that when
10485 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10486 // are mutually compatible. As an optimization, don't test the first member
10487 // against itself.
10488 bool HadError = false;
10489 auto Iter = Args.begin();
10490 auto End = Args.end();
10491 while (Iter != End) {
10492 const auto &FirstInGroup = *Iter;
10493 for (++Iter;
10494 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10495 ++Iter) {
10496 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
10497 }
10498 }
10499 return !HadError;
10500}
10501
10502bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10503 // Str - The format string. NOTE: this is NOT null-terminated!
10504 StringRef StrRef = FExpr->getString();
10505 const char *Str = StrRef.data();
10506 // Account for cases where the string literal is truncated in a declaration.
10507 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
10508 assert(T && "String literal not of constant array type!");
10509 size_t TypeSize = T->getZExtSize();
10510 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10511 return analyze_format_string::ParseFormatStringHasSArg(
10512 beg: Str, end: Str + StrLen, LO: getLangOpts(), Target: Context.getTargetInfo());
10513}
10514
10515//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10516
10517// Returns the related absolute value function that is larger, of 0 if one
10518// does not exist.
10519static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10520 switch (AbsFunction) {
10521 default:
10522 return 0;
10523
10524 case Builtin::BI__builtin_abs:
10525 return Builtin::BI__builtin_labs;
10526 case Builtin::BI__builtin_labs:
10527 return Builtin::BI__builtin_llabs;
10528 case Builtin::BI__builtin_llabs:
10529 return 0;
10530
10531 case Builtin::BI__builtin_fabsf:
10532 return Builtin::BI__builtin_fabs;
10533 case Builtin::BI__builtin_fabs:
10534 return Builtin::BI__builtin_fabsl;
10535 case Builtin::BI__builtin_fabsl:
10536 return 0;
10537
10538 case Builtin::BI__builtin_cabsf:
10539 return Builtin::BI__builtin_cabs;
10540 case Builtin::BI__builtin_cabs:
10541 return Builtin::BI__builtin_cabsl;
10542 case Builtin::BI__builtin_cabsl:
10543 return 0;
10544
10545 case Builtin::BIabs:
10546 return Builtin::BIlabs;
10547 case Builtin::BIlabs:
10548 return Builtin::BIllabs;
10549 case Builtin::BIllabs:
10550 return 0;
10551
10552 case Builtin::BIfabsf:
10553 return Builtin::BIfabs;
10554 case Builtin::BIfabs:
10555 return Builtin::BIfabsl;
10556 case Builtin::BIfabsl:
10557 return 0;
10558
10559 case Builtin::BIcabsf:
10560 return Builtin::BIcabs;
10561 case Builtin::BIcabs:
10562 return Builtin::BIcabsl;
10563 case Builtin::BIcabsl:
10564 return 0;
10565 }
10566}
10567
10568// Returns the argument type of the absolute value function.
10569static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10570 unsigned AbsType) {
10571 if (AbsType == 0)
10572 return QualType();
10573
10574 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10575 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
10576 if (Error != ASTContext::GE_None)
10577 return QualType();
10578
10579 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10580 if (!FT)
10581 return QualType();
10582
10583 if (FT->getNumParams() != 1)
10584 return QualType();
10585
10586 return FT->getParamType(i: 0);
10587}
10588
10589// Returns the best absolute value function, or zero, based on type and
10590// current absolute value function.
10591static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10592 unsigned AbsFunctionKind) {
10593 unsigned BestKind = 0;
10594 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
10595 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10596 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
10597 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
10598 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
10599 if (BestKind == 0)
10600 BestKind = Kind;
10601 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
10602 BestKind = Kind;
10603 break;
10604 }
10605 }
10606 }
10607 return BestKind;
10608}
10609
10610enum AbsoluteValueKind {
10611 AVK_Integer,
10612 AVK_Floating,
10613 AVK_Complex
10614};
10615
10616static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10617 if (T->isIntegralOrEnumerationType())
10618 return AVK_Integer;
10619 if (T->isRealFloatingType())
10620 return AVK_Floating;
10621 if (T->isAnyComplexType())
10622 return AVK_Complex;
10623
10624 llvm_unreachable("Type not integer, floating, or complex");
10625}
10626
10627// Changes the absolute value function to a different type. Preserves whether
10628// the function is a builtin.
10629static unsigned changeAbsFunction(unsigned AbsKind,
10630 AbsoluteValueKind ValueKind) {
10631 switch (ValueKind) {
10632 case AVK_Integer:
10633 switch (AbsKind) {
10634 default:
10635 return 0;
10636 case Builtin::BI__builtin_fabsf:
10637 case Builtin::BI__builtin_fabs:
10638 case Builtin::BI__builtin_fabsl:
10639 case Builtin::BI__builtin_cabsf:
10640 case Builtin::BI__builtin_cabs:
10641 case Builtin::BI__builtin_cabsl:
10642 return Builtin::BI__builtin_abs;
10643 case Builtin::BIfabsf:
10644 case Builtin::BIfabs:
10645 case Builtin::BIfabsl:
10646 case Builtin::BIcabsf:
10647 case Builtin::BIcabs:
10648 case Builtin::BIcabsl:
10649 return Builtin::BIabs;
10650 }
10651 case AVK_Floating:
10652 switch (AbsKind) {
10653 default:
10654 return 0;
10655 case Builtin::BI__builtin_abs:
10656 case Builtin::BI__builtin_labs:
10657 case Builtin::BI__builtin_llabs:
10658 case Builtin::BI__builtin_cabsf:
10659 case Builtin::BI__builtin_cabs:
10660 case Builtin::BI__builtin_cabsl:
10661 return Builtin::BI__builtin_fabsf;
10662 case Builtin::BIabs:
10663 case Builtin::BIlabs:
10664 case Builtin::BIllabs:
10665 case Builtin::BIcabsf:
10666 case Builtin::BIcabs:
10667 case Builtin::BIcabsl:
10668 return Builtin::BIfabsf;
10669 }
10670 case AVK_Complex:
10671 switch (AbsKind) {
10672 default:
10673 return 0;
10674 case Builtin::BI__builtin_abs:
10675 case Builtin::BI__builtin_labs:
10676 case Builtin::BI__builtin_llabs:
10677 case Builtin::BI__builtin_fabsf:
10678 case Builtin::BI__builtin_fabs:
10679 case Builtin::BI__builtin_fabsl:
10680 return Builtin::BI__builtin_cabsf;
10681 case Builtin::BIabs:
10682 case Builtin::BIlabs:
10683 case Builtin::BIllabs:
10684 case Builtin::BIfabsf:
10685 case Builtin::BIfabs:
10686 case Builtin::BIfabsl:
10687 return Builtin::BIcabsf;
10688 }
10689 }
10690 llvm_unreachable("Unable to convert function");
10691}
10692
10693static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10694 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10695 if (!FnInfo)
10696 return 0;
10697
10698 switch (FDecl->getBuiltinID()) {
10699 default:
10700 return 0;
10701 case Builtin::BI__builtin_abs:
10702 case Builtin::BI__builtin_fabs:
10703 case Builtin::BI__builtin_fabsf:
10704 case Builtin::BI__builtin_fabsl:
10705 case Builtin::BI__builtin_labs:
10706 case Builtin::BI__builtin_llabs:
10707 case Builtin::BI__builtin_cabs:
10708 case Builtin::BI__builtin_cabsf:
10709 case Builtin::BI__builtin_cabsl:
10710 case Builtin::BIabs:
10711 case Builtin::BIlabs:
10712 case Builtin::BIllabs:
10713 case Builtin::BIfabs:
10714 case Builtin::BIfabsf:
10715 case Builtin::BIfabsl:
10716 case Builtin::BIcabs:
10717 case Builtin::BIcabsf:
10718 case Builtin::BIcabsl:
10719 return FDecl->getBuiltinID();
10720 }
10721 llvm_unreachable("Unknown Builtin type");
10722}
10723
10724// If the replacement is valid, emit a note with replacement function.
10725// Additionally, suggest including the proper header if not already included.
10726static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10727 unsigned AbsKind, QualType ArgType) {
10728 bool EmitHeaderHint = true;
10729 const char *HeaderName = nullptr;
10730 std::string FunctionName;
10731 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10732 FunctionName = "std::abs";
10733 if (ArgType->isIntegralOrEnumerationType()) {
10734 HeaderName = "cstdlib";
10735 } else if (ArgType->isRealFloatingType()) {
10736 HeaderName = "cmath";
10737 } else {
10738 llvm_unreachable("Invalid Type");
10739 }
10740
10741 // Lookup all std::abs
10742 if (NamespaceDecl *Std = S.getStdNamespace()) {
10743 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10744 R.suppressDiagnostics();
10745 S.LookupQualifiedName(R, LookupCtx: Std);
10746
10747 for (const auto *I : R) {
10748 const FunctionDecl *FDecl = nullptr;
10749 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10750 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10751 } else {
10752 FDecl = dyn_cast<FunctionDecl>(Val: I);
10753 }
10754 if (!FDecl)
10755 continue;
10756
10757 // Found std::abs(), check that they are the right ones.
10758 if (FDecl->getNumParams() != 1)
10759 continue;
10760
10761 // Check that the parameter type can handle the argument.
10762 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10763 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10764 S.Context.getTypeSize(T: ArgType) <=
10765 S.Context.getTypeSize(T: ParamType)) {
10766 // Found a function, don't need the header hint.
10767 EmitHeaderHint = false;
10768 break;
10769 }
10770 }
10771 }
10772 } else {
10773 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10774 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10775
10776 if (HeaderName) {
10777 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10778 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10779 R.suppressDiagnostics();
10780 S.LookupName(R, S: S.getCurScope());
10781
10782 if (R.isSingleResult()) {
10783 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10784 if (FD && FD->getBuiltinID() == AbsKind) {
10785 EmitHeaderHint = false;
10786 } else {
10787 return;
10788 }
10789 } else if (!R.empty()) {
10790 return;
10791 }
10792 }
10793 }
10794
10795 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10796 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10797
10798 if (!HeaderName)
10799 return;
10800
10801 if (!EmitHeaderHint)
10802 return;
10803
10804 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10805 << FunctionName;
10806}
10807
10808template <std::size_t StrLen>
10809static bool IsStdFunction(const FunctionDecl *FDecl,
10810 const char (&Str)[StrLen]) {
10811 if (!FDecl)
10812 return false;
10813 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10814 return false;
10815 if (!FDecl->isInStdNamespace())
10816 return false;
10817
10818 return true;
10819}
10820
10821enum class MathCheck { NaN, Inf };
10822static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10823 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10824 return llvm::is_contained(Set: names, Element: calleeName);
10825 };
10826
10827 switch (Check) {
10828 case MathCheck::NaN:
10829 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10830 "__builtin_nanf16", "__builtin_nanf128"});
10831 case MathCheck::Inf:
10832 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10833 "__builtin_inff16", "__builtin_inff128"});
10834 }
10835 llvm_unreachable("unknown MathCheck");
10836}
10837
10838static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10839 if (FDecl->getName() != "infinity")
10840 return false;
10841
10842 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10843 const CXXRecordDecl *RDecl = MDecl->getParent();
10844 if (RDecl->getName() != "numeric_limits")
10845 return false;
10846
10847 if (const NamespaceDecl *NSDecl =
10848 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10849 return NSDecl->isStdNamespace();
10850 }
10851
10852 return false;
10853}
10854
10855void Sema::CheckInfNaNFunction(const CallExpr *Call,
10856 const FunctionDecl *FDecl) {
10857 if (!FDecl->getIdentifier())
10858 return;
10859
10860 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10861 if (FPO.getNoHonorNaNs() &&
10862 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10863 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10864 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10865 << 1 << 0 << Call->getSourceRange();
10866 return;
10867 }
10868
10869 if (FPO.getNoHonorInfs() &&
10870 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10871 IsInfinityFunction(FDecl) ||
10872 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10873 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10874 << 0 << 0 << Call->getSourceRange();
10875 }
10876}
10877
10878void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10879 const FunctionDecl *FDecl) {
10880 if (Call->getNumArgs() != 1)
10881 return;
10882
10883 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10884 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10885 if (AbsKind == 0 && !IsStdAbs)
10886 return;
10887
10888 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10889 QualType ParamType = Call->getArg(Arg: 0)->getType();
10890
10891 // Unsigned types cannot be negative. Suggest removing the absolute value
10892 // function call.
10893 if (ArgType->isUnsignedIntegerType()) {
10894 std::string FunctionName =
10895 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10896 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10897 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10898 << FunctionName
10899 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10900 return;
10901 }
10902
10903 // Taking the absolute value of a pointer is very suspicious, they probably
10904 // wanted to index into an array, dereference a pointer, call a function, etc.
10905 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10906 unsigned DiagType = 0;
10907 if (ArgType->isFunctionType())
10908 DiagType = 1;
10909 else if (ArgType->isArrayType())
10910 DiagType = 2;
10911
10912 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10913 return;
10914 }
10915
10916 // std::abs has overloads which prevent most of the absolute value problems
10917 // from occurring.
10918 if (IsStdAbs)
10919 return;
10920
10921 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10922 // types.
10923 if (!ArgType->isIntegralOrEnumerationType() &&
10924 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10925 return;
10926
10927 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10928 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10929
10930 // The argument and parameter are the same kind. Check if they are the right
10931 // size.
10932 if (ArgValueKind == ParamValueKind) {
10933 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10934 return;
10935
10936 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10937 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10938 << FDecl << ArgType << ParamType;
10939
10940 if (NewAbsKind == 0)
10941 return;
10942
10943 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10944 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10945 return;
10946 }
10947
10948 // ArgValueKind != ParamValueKind
10949 // The wrong type of absolute value function was used. Attempt to find the
10950 // proper one.
10951 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10952 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10953 if (NewAbsKind == 0)
10954 return;
10955
10956 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10957 << FDecl << ParamValueKind << ArgValueKind;
10958
10959 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10960 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10961}
10962
10963//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10964void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10965 const FunctionDecl *FDecl) {
10966 if (!Call || !FDecl) return;
10967
10968 // Ignore template specializations and macros.
10969 if (inTemplateInstantiation()) return;
10970 if (Call->getExprLoc().isMacroID()) return;
10971
10972 // Only care about the one template argument, two function parameter std::max
10973 if (Call->getNumArgs() != 2) return;
10974 if (!IsStdFunction(FDecl, Str: "max")) return;
10975 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10976 if (!ArgList) return;
10977 if (ArgList->size() != 1) return;
10978
10979 // Check that template type argument is unsigned integer.
10980 const auto& TA = ArgList->get(Idx: 0);
10981 if (TA.getKind() != TemplateArgument::Type) return;
10982 QualType ArgType = TA.getAsType();
10983 if (!ArgType->isUnsignedIntegerType()) return;
10984
10985 // See if either argument is a literal zero.
10986 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10987 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10988 if (!MTE) return false;
10989 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10990 if (!Num) return false;
10991 if (Num->getValue() != 0) return false;
10992 return true;
10993 };
10994
10995 const Expr *FirstArg = Call->getArg(Arg: 0);
10996 const Expr *SecondArg = Call->getArg(Arg: 1);
10997 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10998 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10999
11000 // Only warn when exactly one argument is zero.
11001 if (IsFirstArgZero == IsSecondArgZero) return;
11002
11003 SourceRange FirstRange = FirstArg->getSourceRange();
11004 SourceRange SecondRange = SecondArg->getSourceRange();
11005
11006 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
11007
11008 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
11009 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
11010
11011 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
11012 SourceRange RemovalRange;
11013 if (IsFirstArgZero) {
11014 RemovalRange = SourceRange(FirstRange.getBegin(),
11015 SecondRange.getBegin().getLocWithOffset(Offset: -1));
11016 } else {
11017 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
11018 SecondRange.getEnd());
11019 }
11020
11021 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
11022 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
11023 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
11024}
11025
11026//===--- CHECK: Standard memory functions ---------------------------------===//
11027
11028/// Takes the expression passed to the size_t parameter of functions
11029/// such as memcmp, strncat, etc and warns if it's a comparison.
11030///
11031/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
11032static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
11033 const IdentifierInfo *FnName,
11034 SourceLocation FnLoc,
11035 SourceLocation RParenLoc) {
11036 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
11037 if (!Size)
11038 return false;
11039
11040 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
11041 if (!Size->isComparisonOp() && !Size->isLogicalOp())
11042 return false;
11043
11044 SourceRange SizeRange = Size->getSourceRange();
11045 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
11046 << SizeRange << FnName;
11047 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
11048 << FnName
11049 << FixItHint::CreateInsertion(
11050 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
11051 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
11052 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
11053 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
11054 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
11055 Code: ")");
11056
11057 return true;
11058}
11059
11060/// Determine whether the given type is or contains a dynamic class type
11061/// (e.g., whether it has a vtable).
11062static const CXXRecordDecl *getContainedDynamicClass(QualType T,
11063 bool &IsContained) {
11064 // Look through array types while ignoring qualifiers.
11065 const Type *Ty = T->getBaseElementTypeUnsafe();
11066 IsContained = false;
11067
11068 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
11069 RD = RD ? RD->getDefinition() : nullptr;
11070 if (!RD || RD->isInvalidDecl())
11071 return nullptr;
11072
11073 if (RD->isDynamicClass())
11074 return RD;
11075
11076 // Check all the fields. If any bases were dynamic, the class is dynamic.
11077 // It's impossible for a class to transitively contain itself by value, so
11078 // infinite recursion is impossible.
11079 for (auto *FD : RD->fields()) {
11080 bool SubContained;
11081 if (const CXXRecordDecl *ContainedRD =
11082 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
11083 IsContained = true;
11084 return ContainedRD;
11085 }
11086 }
11087
11088 return nullptr;
11089}
11090
11091static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
11092 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
11093 if (Unary->getKind() == UETT_SizeOf)
11094 return Unary;
11095 return nullptr;
11096}
11097
11098/// If E is a sizeof expression, returns its argument expression,
11099/// otherwise returns NULL.
11100static const Expr *getSizeOfExprArg(const Expr *E) {
11101 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11102 if (!SizeOf->isArgumentType())
11103 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11104 return nullptr;
11105}
11106
11107/// If E is a sizeof expression, returns its argument type.
11108static QualType getSizeOfArgType(const Expr *E) {
11109 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11110 return SizeOf->getTypeOfArgument();
11111 return QualType();
11112}
11113
11114namespace {
11115
11116struct SearchNonTrivialToInitializeField
11117 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11118 using Super =
11119 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11120
11121 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11122
11123 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11124 SourceLocation SL) {
11125 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
11126 asDerived().visitArray(PDIK, AT, SL);
11127 return;
11128 }
11129
11130 Super::visitWithKind(PDIK, FT, Args&: SL);
11131 }
11132
11133 void visitARCStrong(QualType FT, SourceLocation SL) {
11134 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
11135 }
11136 void visitARCWeak(QualType FT, SourceLocation SL) {
11137 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
11138 }
11139 void visitStruct(QualType FT, SourceLocation SL) {
11140 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11141 visit(FT: FD->getType(), Args: FD->getLocation());
11142 }
11143 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11144 const ArrayType *AT, SourceLocation SL) {
11145 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
11146 }
11147 void visitTrivial(QualType FT, SourceLocation SL) {}
11148
11149 static void diag(QualType RT, const Expr *E, Sema &S) {
11150 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
11151 }
11152
11153 ASTContext &getContext() { return S.getASTContext(); }
11154
11155 const Expr *E;
11156 Sema &S;
11157};
11158
11159struct SearchNonTrivialToCopyField
11160 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11161 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11162
11163 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11164
11165 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11166 SourceLocation SL) {
11167 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
11168 asDerived().visitArray(PCK, AT, SL);
11169 return;
11170 }
11171
11172 Super::visitWithKind(PCK, FT, Args&: SL);
11173 }
11174
11175 void visitARCStrong(QualType FT, SourceLocation SL) {
11176 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11177 }
11178 void visitARCWeak(QualType FT, SourceLocation SL) {
11179 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11180 }
11181 void visitPtrAuth(QualType FT, SourceLocation SL) {
11182 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11183 }
11184 void visitStruct(QualType FT, SourceLocation SL) {
11185 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11186 visit(FT: FD->getType(), Args: FD->getLocation());
11187 }
11188 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11189 SourceLocation SL) {
11190 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
11191 }
11192 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11193 SourceLocation SL) {}
11194 void visitTrivial(QualType FT, SourceLocation SL) {}
11195 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11196
11197 static void diag(QualType RT, const Expr *E, Sema &S) {
11198 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
11199 }
11200
11201 ASTContext &getContext() { return S.getASTContext(); }
11202
11203 const Expr *E;
11204 Sema &S;
11205};
11206
11207}
11208
11209/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11210static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11211 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11212
11213 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
11214 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11215 return false;
11216
11217 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
11218 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
11219 }
11220
11221 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
11222}
11223
11224/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11225///
11226/// \code
11227/// #define MACRO 0
11228/// foo(MACRO);
11229/// foo(0);
11230/// \endcode
11231///
11232/// This should return true for the first call to foo, but not for the second
11233/// (regardless of whether foo is a macro or function).
11234static bool isArgumentExpandedFromMacro(SourceManager &SM,
11235 SourceLocation CallLoc,
11236 SourceLocation ArgLoc) {
11237 if (!CallLoc.isMacroID())
11238 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
11239
11240 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
11241 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
11242}
11243
11244/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11245/// last two arguments transposed.
11246static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11247 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11248 return;
11249
11250 const Expr *SizeArg =
11251 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11252
11253 auto isLiteralZero = [](const Expr *E) {
11254 return (isa<IntegerLiteral>(Val: E) &&
11255 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
11256 (isa<CharacterLiteral>(Val: E) &&
11257 cast<CharacterLiteral>(Val: E)->getValue() == 0);
11258 };
11259
11260 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11261 SourceLocation CallLoc = Call->getRParenLoc();
11262 SourceManager &SM = S.getSourceManager();
11263 if (isLiteralZero(SizeArg) &&
11264 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
11265
11266 SourceLocation DiagLoc = SizeArg->getExprLoc();
11267
11268 // Some platforms #define bzero to __builtin_memset. See if this is the
11269 // case, and if so, emit a better diagnostic.
11270 if (BId == Builtin::BIbzero ||
11271 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
11272 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
11273 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
11274 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
11275 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
11276 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
11277 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
11278 }
11279 return;
11280 }
11281
11282 // If the second argument to a memset is a sizeof expression and the third
11283 // isn't, this is also likely an error. This should catch
11284 // 'memset(buf, sizeof(buf), 0xff)'.
11285 if (BId == Builtin::BImemset &&
11286 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
11287 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
11288 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
11289 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
11290 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
11291 return;
11292 }
11293}
11294
11295void Sema::CheckMemaccessArguments(const CallExpr *Call,
11296 unsigned BId,
11297 IdentifierInfo *FnName) {
11298 assert(BId != 0);
11299
11300 // It is possible to have a non-standard definition of memset. Validate
11301 // we have enough arguments, and if not, abort further checking.
11302 unsigned ExpectedNumArgs =
11303 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11304 if (Call->getNumArgs() < ExpectedNumArgs)
11305 return;
11306
11307 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11308 BId == Builtin::BIstrndup ? 1 : 2);
11309 unsigned LenArg =
11310 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11311 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
11312
11313 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
11314 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11315 return;
11316
11317 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11318 CheckMemaccessSize(S&: *this, BId, Call);
11319
11320 // We have special checking when the length is a sizeof expression.
11321 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
11322
11323 // Although widely used, 'bzero' is not a standard function. Be more strict
11324 // with the argument types before allowing diagnostics and only allow the
11325 // form bzero(ptr, sizeof(...)).
11326 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
11327 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11328 return;
11329
11330 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11331 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
11332 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
11333
11334 QualType DestTy = Dest->getType();
11335 QualType PointeeTy;
11336 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11337 PointeeTy = DestPtrTy->getPointeeType();
11338
11339 // Never warn about void type pointers. This can be used to suppress
11340 // false positives.
11341 if (PointeeTy->isVoidType())
11342 continue;
11343
11344 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11345 // actually comparing the expressions for equality. Because computing the
11346 // expression IDs can be expensive, we only do this if the diagnostic is
11347 // enabled.
11348 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
11349 break;
11350
11351 // Also check for cases where the sizeof argument is the exact same
11352 // type as the memory argument, and where it points to a user-defined
11353 // record type.
11354 if (SizeOfArgTy != QualType()) {
11355 if (PointeeTy->isRecordType() &&
11356 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
11357 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
11358 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
11359 << FnName << SizeOfArgTy << ArgIdx
11360 << PointeeTy << Dest->getSourceRange()
11361 << LenExpr->getSourceRange());
11362 break;
11363 }
11364 }
11365 } else if (DestTy->isArrayType()) {
11366 PointeeTy = DestTy;
11367 }
11368
11369 if (PointeeTy == QualType())
11370 continue;
11371
11372 // Always complain about dynamic classes.
11373 bool IsContained;
11374 if (const CXXRecordDecl *ContainedRD =
11375 getContainedDynamicClass(T: PointeeTy, IsContained)) {
11376
11377 unsigned OperationType = 0;
11378 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11379 // "overwritten" if we're warning about the destination for any call
11380 // but memcmp; otherwise a verb appropriate to the call.
11381 if (ArgIdx != 0 || IsCmp) {
11382 if (BId == Builtin::BImemcpy)
11383 OperationType = 1;
11384 else if(BId == Builtin::BImemmove)
11385 OperationType = 2;
11386 else if (IsCmp)
11387 OperationType = 3;
11388 }
11389
11390 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11391 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
11392 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11393 << IsContained << ContainedRD << OperationType
11394 << Call->getCallee()->getSourceRange());
11395 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11396 BId != Builtin::BImemset)
11397 DiagRuntimeBehavior(
11398 Loc: Dest->getExprLoc(), Statement: Dest,
11399 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
11400 << ArgIdx << FnName << PointeeTy
11401 << Call->getCallee()->getSourceRange());
11402 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11403
11404 // FIXME: Do not consider incomplete types even though they may be
11405 // completed later. GCC does not diagnose such code, but we may want to
11406 // consider diagnosing it in the future, perhaps under a different, but
11407 // related, diagnostic group.
11408 bool NonTriviallyCopyableCXXRecord =
11409 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11410 !PointeeTy.isTriviallyCopyableType(Context);
11411
11412 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11413 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
11414 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11415 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11416 << ArgIdx << FnName << PointeeTy << 0);
11417 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
11418 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11419 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11420 // FIXME: Limiting this warning to dest argument until we decide
11421 // whether it's valid for source argument too.
11422 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11423 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11424 << FnName << PointeeTy);
11425 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11426 RD->isNonTrivialToPrimitiveCopy()) {
11427 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11428 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11429 << ArgIdx << FnName << PointeeTy << 1);
11430 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
11431 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11432 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11433 // FIXME: Limiting this warning to dest argument until we decide
11434 // whether it's valid for source argument too.
11435 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11436 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11437 << FnName << PointeeTy);
11438 } else {
11439 continue;
11440 }
11441 } else
11442 continue;
11443
11444 DiagRuntimeBehavior(
11445 Loc: Dest->getExprLoc(), Statement: Dest,
11446 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
11447 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
11448 break;
11449 }
11450}
11451
11452bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11453 IdentifierInfo *FnName) {
11454 llvm::FoldingSetNodeID SizeOfArgID;
11455 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
11456 if (!SizeOfArg)
11457 return false;
11458 // Computing this warning is expensive, so we only do so if the warning is
11459 // enabled.
11460 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
11461 Loc: SizeOfArg->getExprLoc()))
11462 return false;
11463 QualType DestTy = Dest->getType();
11464 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11465 if (!DestPtrTy)
11466 return false;
11467
11468 QualType PointeeTy = DestPtrTy->getPointeeType();
11469
11470 if (SizeOfArgID == llvm::FoldingSetNodeID())
11471 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
11472
11473 llvm::FoldingSetNodeID DestID;
11474 Dest->Profile(ID&: DestID, Context, Canonical: true);
11475 if (DestID == SizeOfArgID) {
11476 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11477 // over sizeof(src) as well.
11478 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11479 StringRef ReadableName = FnName->getName();
11480
11481 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
11482 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11483 ActionIdx = 1; // If its an address-of operator, just remove it.
11484 if (!PointeeTy->isIncompleteType() &&
11485 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
11486 ActionIdx = 2; // If the pointee's size is sizeof(char),
11487 // suggest an explicit length.
11488
11489 // If the function is defined as a builtin macro, do not show macro
11490 // expansion.
11491 SourceLocation SL = SizeOfArg->getExprLoc();
11492 SourceRange DSR = Dest->getSourceRange();
11493 SourceRange SSR = SizeOfArg->getSourceRange();
11494 SourceManager &SM = getSourceManager();
11495
11496 if (SM.isMacroArgExpansion(Loc: SL)) {
11497 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
11498 SL = SM.getSpellingLoc(Loc: SL);
11499 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
11500 SM.getSpellingLoc(Loc: DSR.getEnd()));
11501 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
11502 SM.getSpellingLoc(Loc: SSR.getEnd()));
11503 }
11504
11505 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11506 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
11507 << ReadableName << PointeeTy << DestTy << DSR
11508 << SSR);
11509 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11510 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
11511 << ActionIdx << SSR);
11512 return true;
11513 }
11514 return false;
11515}
11516
11517// A little helper routine: ignore addition and subtraction of integer literals.
11518// This intentionally does not ignore all integer constant expressions because
11519// we don't want to remove sizeof().
11520static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11521 Ex = Ex->IgnoreParenCasts();
11522
11523 while (true) {
11524 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
11525 if (!BO || !BO->isAdditiveOp())
11526 break;
11527
11528 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11529 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11530
11531 if (isa<IntegerLiteral>(Val: RHS))
11532 Ex = LHS;
11533 else if (isa<IntegerLiteral>(Val: LHS))
11534 Ex = RHS;
11535 else
11536 break;
11537 }
11538
11539 return Ex;
11540}
11541
11542static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11543 ASTContext &Context) {
11544 // Only handle constant-sized or VLAs, but not flexible members.
11545 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
11546 // Only issue the FIXIT for arrays of size > 1.
11547 if (CAT->getZExtSize() <= 1)
11548 return false;
11549 } else if (!Ty->isVariableArrayType()) {
11550 return false;
11551 }
11552 return true;
11553}
11554
11555void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11556 IdentifierInfo *FnName) {
11557
11558 // Don't crash if the user has the wrong number of arguments
11559 unsigned NumArgs = Call->getNumArgs();
11560 if ((NumArgs != 3) && (NumArgs != 4))
11561 return;
11562
11563 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
11564 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
11565 const Expr *CompareWithSrc = nullptr;
11566
11567 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
11568 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11569 return;
11570
11571 // Look for 'strlcpy(dst, x, sizeof(x))'
11572 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
11573 CompareWithSrc = Ex;
11574 else {
11575 // Look for 'strlcpy(dst, x, strlen(x))'
11576 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
11577 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11578 SizeCall->getNumArgs() == 1)
11579 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
11580 }
11581 }
11582
11583 if (!CompareWithSrc)
11584 return;
11585
11586 // Determine if the argument to sizeof/strlen is equal to the source
11587 // argument. In principle there's all kinds of things you could do
11588 // here, for instance creating an == expression and evaluating it with
11589 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11590 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
11591 if (!SrcArgDRE)
11592 return;
11593
11594 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
11595 if (!CompareWithSrcDRE ||
11596 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11597 return;
11598
11599 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
11600 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
11601 << OriginalSizeArg->getSourceRange() << FnName;
11602
11603 // Output a FIXIT hint if the destination is an array (rather than a
11604 // pointer to an array). This could be enhanced to handle some
11605 // pointers if we know the actual size, like if DstArg is 'array+2'
11606 // we could say 'sizeof(array)-2'.
11607 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
11608 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
11609 return;
11610
11611 SmallString<128> sizeString;
11612 llvm::raw_svector_ostream OS(sizeString);
11613 OS << "sizeof(";
11614 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11615 OS << ")";
11616
11617 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
11618 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
11619 Code: OS.str());
11620}
11621
11622/// Check if two expressions refer to the same declaration.
11623static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11624 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
11625 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
11626 return D1->getDecl() == D2->getDecl();
11627 return false;
11628}
11629
11630static const Expr *getStrlenExprArg(const Expr *E) {
11631 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
11632 const FunctionDecl *FD = CE->getDirectCallee();
11633 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11634 return nullptr;
11635 return CE->getArg(Arg: 0)->IgnoreParenCasts();
11636 }
11637 return nullptr;
11638}
11639
11640void Sema::CheckStrncatArguments(const CallExpr *CE,
11641 const IdentifierInfo *FnName) {
11642 // Don't crash if the user has the wrong number of arguments.
11643 if (CE->getNumArgs() < 3)
11644 return;
11645 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
11646 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
11647 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
11648
11649 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
11650 RParenLoc: CE->getRParenLoc()))
11651 return;
11652
11653 // Identify common expressions, which are wrongly used as the size argument
11654 // to strncat and may lead to buffer overflows.
11655 unsigned PatternType = 0;
11656 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
11657 // - sizeof(dst)
11658 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
11659 PatternType = 1;
11660 // - sizeof(src)
11661 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
11662 PatternType = 2;
11663 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
11664 if (BE->getOpcode() == BO_Sub) {
11665 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11666 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11667 // - sizeof(dst) - strlen(dst)
11668 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
11669 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
11670 PatternType = 1;
11671 // - sizeof(src) - (anything)
11672 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
11673 PatternType = 2;
11674 }
11675 }
11676
11677 if (PatternType == 0)
11678 return;
11679
11680 // Generate the diagnostic.
11681 SourceLocation SL = LenArg->getBeginLoc();
11682 SourceRange SR = LenArg->getSourceRange();
11683 SourceManager &SM = getSourceManager();
11684
11685 // If the function is defined as a builtin macro, do not show macro expansion.
11686 if (SM.isMacroArgExpansion(Loc: SL)) {
11687 SL = SM.getSpellingLoc(Loc: SL);
11688 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11689 SM.getSpellingLoc(Loc: SR.getEnd()));
11690 }
11691
11692 // Check if the destination is an array (rather than a pointer to an array).
11693 QualType DstTy = DstArg->getType();
11694 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11695 Context);
11696 if (!isKnownSizeArray) {
11697 if (PatternType == 1)
11698 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11699 else
11700 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11701 return;
11702 }
11703
11704 if (PatternType == 1)
11705 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11706 else
11707 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11708
11709 SmallString<128> sizeString;
11710 llvm::raw_svector_ostream OS(sizeString);
11711 OS << "sizeof(";
11712 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11713 OS << ") - ";
11714 OS << "strlen(";
11715 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11716 OS << ") - 1";
11717
11718 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11719 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11720}
11721
11722namespace {
11723void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11724 const UnaryOperator *UnaryExpr, const Decl *D) {
11725 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11726 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11727 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11728 return;
11729 }
11730}
11731
11732void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11733 const UnaryOperator *UnaryExpr) {
11734 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11735 const Decl *D = Lvalue->getDecl();
11736 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11737 if (!DD->getType()->isReferenceType())
11738 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11739 }
11740 }
11741
11742 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11743 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11744 D: Lvalue->getMemberDecl());
11745}
11746
11747void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11748 const UnaryOperator *UnaryExpr) {
11749 const auto *Lambda = dyn_cast<LambdaExpr>(
11750 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11751 if (!Lambda)
11752 return;
11753
11754 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11755 << CalleeName << 2 /*object: lambda expression*/;
11756}
11757
11758void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11759 const DeclRefExpr *Lvalue) {
11760 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11761 if (Var == nullptr)
11762 return;
11763
11764 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11765 << CalleeName << 0 /*object: */ << Var;
11766}
11767
11768void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11769 const CastExpr *Cast) {
11770 SmallString<128> SizeString;
11771 llvm::raw_svector_ostream OS(SizeString);
11772
11773 clang::CastKind Kind = Cast->getCastKind();
11774 if (Kind == clang::CK_BitCast &&
11775 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11776 return;
11777 if (Kind == clang::CK_IntegralToPointer &&
11778 !isa<IntegerLiteral>(
11779 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11780 return;
11781
11782 switch (Cast->getCastKind()) {
11783 case clang::CK_BitCast:
11784 case clang::CK_IntegralToPointer:
11785 case clang::CK_FunctionToPointerDecay:
11786 OS << '\'';
11787 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11788 OS << '\'';
11789 break;
11790 default:
11791 return;
11792 }
11793
11794 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11795 << CalleeName << 0 /*object: */ << OS.str();
11796}
11797} // namespace
11798
11799void Sema::CheckFreeArguments(const CallExpr *E) {
11800 const std::string CalleeName =
11801 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11802
11803 { // Prefer something that doesn't involve a cast to make things simpler.
11804 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11805 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11806 switch (UnaryExpr->getOpcode()) {
11807 case UnaryOperator::Opcode::UO_AddrOf:
11808 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11809 case UnaryOperator::Opcode::UO_Plus:
11810 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11811 default:
11812 break;
11813 }
11814
11815 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11816 if (Lvalue->getType()->isArrayType())
11817 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11818
11819 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11820 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11821 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11822 return;
11823 }
11824
11825 if (isa<BlockExpr>(Val: Arg)) {
11826 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11827 << CalleeName << 1 /*object: block*/;
11828 return;
11829 }
11830 }
11831 // Maybe the cast was important, check after the other cases.
11832 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11833 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11834}
11835
11836void
11837Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11838 SourceLocation ReturnLoc,
11839 bool isObjCMethod,
11840 const AttrVec *Attrs,
11841 const FunctionDecl *FD) {
11842 // Check if the return value is null but should not be.
11843 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11844 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11845 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11846 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11847 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11848
11849 // C++11 [basic.stc.dynamic.allocation]p4:
11850 // If an allocation function declared with a non-throwing
11851 // exception-specification fails to allocate storage, it shall return
11852 // a null pointer. Any other allocation function that fails to allocate
11853 // storage shall indicate failure only by throwing an exception [...]
11854 if (FD) {
11855 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11856 if (Op == OO_New || Op == OO_Array_New) {
11857 const FunctionProtoType *Proto
11858 = FD->getType()->castAs<FunctionProtoType>();
11859 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11860 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11861 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11862 << FD << getLangOpts().CPlusPlus11;
11863 }
11864 }
11865
11866 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11867 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11868 }
11869
11870 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11871 // here prevent the user from using a PPC MMA type as trailing return type.
11872 if (Context.getTargetInfo().getTriple().isPPC64())
11873 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11874}
11875
11876void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11877 const Expr *RHS, BinaryOperatorKind Opcode) {
11878 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11879 return;
11880
11881 // Match and capture subexpressions such as "(float) X == 0.1".
11882 const FloatingLiteral *FPLiteral;
11883 const CastExpr *FPCast;
11884 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11885 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11886 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11887 return FPLiteral && FPCast;
11888 };
11889
11890 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11891 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11892 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11893 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11894 TargetTy->isFloatingPoint()) {
11895 bool Lossy;
11896 llvm::APFloat TargetC = FPLiteral->getValue();
11897 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11898 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11899 if (Lossy) {
11900 // If the literal cannot be represented in the source type, then a
11901 // check for == is always false and check for != is always true.
11902 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11903 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11904 << LHS->getSourceRange() << RHS->getSourceRange();
11905 return;
11906 }
11907 }
11908 }
11909
11910 // Match a more general floating-point equality comparison (-Wfloat-equal).
11911 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11912 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11913
11914 // Special case: check for x == x (which is OK).
11915 // Do not emit warnings for such cases.
11916 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11917 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11918 if (DRL->getDecl() == DRR->getDecl())
11919 return;
11920
11921 // Special case: check for comparisons against literals that can be exactly
11922 // represented by APFloat. In such cases, do not emit a warning. This
11923 // is a heuristic: often comparison against such literals are used to
11924 // detect if a value in a variable has not changed. This clearly can
11925 // lead to false negatives.
11926 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11927 if (FLL->isExact())
11928 return;
11929 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11930 if (FLR->isExact())
11931 return;
11932
11933 // Check for comparisons with builtin types.
11934 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11935 CL && CL->getBuiltinCallee())
11936 return;
11937
11938 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11939 CR && CR->getBuiltinCallee())
11940 return;
11941
11942 // Emit the diagnostic.
11943 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11944 << LHS->getSourceRange() << RHS->getSourceRange();
11945}
11946
11947//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11948//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11949
11950namespace {
11951
11952/// Structure recording the 'active' range of an integer-valued
11953/// expression.
11954struct IntRange {
11955 /// The number of bits active in the int. Note that this includes exactly one
11956 /// sign bit if !NonNegative.
11957 unsigned Width;
11958
11959 /// True if the int is known not to have negative values. If so, all leading
11960 /// bits before Width are known zero, otherwise they are known to be the
11961 /// same as the MSB within Width.
11962 bool NonNegative;
11963
11964 IntRange(unsigned Width, bool NonNegative)
11965 : Width(Width), NonNegative(NonNegative) {}
11966
11967 /// Number of bits excluding the sign bit.
11968 unsigned valueBits() const {
11969 return NonNegative ? Width : Width - 1;
11970 }
11971
11972 /// Returns the range of the bool type.
11973 static IntRange forBoolType() {
11974 return IntRange(1, true);
11975 }
11976
11977 /// Returns the range of an opaque value of the given integral type.
11978 static IntRange forValueOfType(ASTContext &C, QualType T) {
11979 return forValueOfCanonicalType(C,
11980 T: T->getCanonicalTypeInternal().getTypePtr());
11981 }
11982
11983 /// Returns the range of an opaque value of a canonical integral type.
11984 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11985 assert(T->isCanonicalUnqualified());
11986
11987 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11988 T = VT->getElementType().getTypePtr();
11989 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11990 T = MT->getElementType().getTypePtr();
11991 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11992 T = CT->getElementType().getTypePtr();
11993 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11994 T = AT->getValueType().getTypePtr();
11995 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11996 T = OBT->getUnderlyingType().getTypePtr();
11997
11998 if (!C.getLangOpts().CPlusPlus) {
11999 // For enum types in C code, use the underlying datatype.
12000 if (const auto *ED = T->getAsEnumDecl())
12001 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
12002 } else if (auto *Enum = T->getAsEnumDecl()) {
12003 // For enum types in C++, use the known bit width of the enumerators.
12004 // In C++11, enums can have a fixed underlying type. Use this type to
12005 // compute the range.
12006 if (Enum->isFixed()) {
12007 return IntRange(C.getIntWidth(T: QualType(T, 0)),
12008 !Enum->getIntegerType()->isSignedIntegerType());
12009 }
12010
12011 unsigned NumPositive = Enum->getNumPositiveBits();
12012 unsigned NumNegative = Enum->getNumNegativeBits();
12013
12014 if (NumNegative == 0)
12015 return IntRange(NumPositive, true/*NonNegative*/);
12016 else
12017 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
12018 false/*NonNegative*/);
12019 }
12020
12021 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
12022 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12023
12024 const BuiltinType *BT = cast<BuiltinType>(Val: T);
12025 assert(BT->isInteger());
12026
12027 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
12028 }
12029
12030 /// Returns the "target" range of a canonical integral type, i.e.
12031 /// the range of values expressible in the type.
12032 ///
12033 /// This matches forValueOfCanonicalType except that enums have the
12034 /// full range of their type, not the range of their enumerators.
12035 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
12036 assert(T->isCanonicalUnqualified());
12037
12038 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
12039 T = VT->getElementType().getTypePtr();
12040 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
12041 T = MT->getElementType().getTypePtr();
12042 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
12043 T = CT->getElementType().getTypePtr();
12044 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
12045 T = AT->getValueType().getTypePtr();
12046 if (const auto *ED = T->getAsEnumDecl())
12047 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
12048 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
12049 T = OBT->getUnderlyingType().getTypePtr();
12050
12051 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
12052 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12053
12054 const BuiltinType *BT = cast<BuiltinType>(Val: T);
12055 assert(BT->isInteger());
12056
12057 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
12058 }
12059
12060 /// Returns the supremum of two ranges: i.e. their conservative merge.
12061 static IntRange join(IntRange L, IntRange R) {
12062 bool Unsigned = L.NonNegative && R.NonNegative;
12063 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
12064 L.NonNegative && R.NonNegative);
12065 }
12066
12067 /// Return the range of a bitwise-AND of the two ranges.
12068 static IntRange bit_and(IntRange L, IntRange R) {
12069 unsigned Bits = std::max(a: L.Width, b: R.Width);
12070 bool NonNegative = false;
12071 if (L.NonNegative) {
12072 Bits = std::min(a: Bits, b: L.Width);
12073 NonNegative = true;
12074 }
12075 if (R.NonNegative) {
12076 Bits = std::min(a: Bits, b: R.Width);
12077 NonNegative = true;
12078 }
12079 return IntRange(Bits, NonNegative);
12080 }
12081
12082 /// Return the range of a sum of the two ranges.
12083 static IntRange sum(IntRange L, IntRange R) {
12084 bool Unsigned = L.NonNegative && R.NonNegative;
12085 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
12086 Unsigned);
12087 }
12088
12089 /// Return the range of a difference of the two ranges.
12090 static IntRange difference(IntRange L, IntRange R) {
12091 // We need a 1-bit-wider range if:
12092 // 1) LHS can be negative: least value can be reduced.
12093 // 2) RHS can be negative: greatest value can be increased.
12094 bool CanWiden = !L.NonNegative || !R.NonNegative;
12095 bool Unsigned = L.NonNegative && R.Width == 0;
12096 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
12097 !Unsigned,
12098 Unsigned);
12099 }
12100
12101 /// Return the range of a product of the two ranges.
12102 static IntRange product(IntRange L, IntRange R) {
12103 // If both LHS and RHS can be negative, we can form
12104 // -2^L * -2^R = 2^(L + R)
12105 // which requires L + R + 1 value bits to represent.
12106 bool CanWiden = !L.NonNegative && !R.NonNegative;
12107 bool Unsigned = L.NonNegative && R.NonNegative;
12108 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12109 Unsigned);
12110 }
12111
12112 /// Return the range of a remainder operation between the two ranges.
12113 static IntRange rem(IntRange L, IntRange R) {
12114 // The result of a remainder can't be larger than the result of
12115 // either side. The sign of the result is the sign of the LHS.
12116 bool Unsigned = L.NonNegative;
12117 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
12118 Unsigned);
12119 }
12120};
12121
12122} // namespace
12123
12124static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
12125 if (value.isSigned() && value.isNegative())
12126 return IntRange(value.getSignificantBits(), false);
12127
12128 if (value.getBitWidth() > MaxWidth)
12129 value = value.trunc(width: MaxWidth);
12130
12131 // isNonNegative() just checks the sign bit without considering
12132 // signedness.
12133 return IntRange(value.getActiveBits(), true);
12134}
12135
12136static std::optional<IntRange> GetValueRange(APValue &result, QualType Ty,
12137 unsigned MaxWidth) {
12138 if (result.isInt())
12139 return GetValueRange(value&: result.getInt(), MaxWidth);
12140
12141 if (result.isVector()) {
12142 std::optional<IntRange> R =
12143 GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
12144 if (!R)
12145 return std::nullopt;
12146 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12147 std::optional<IntRange> El =
12148 GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
12149 if (!El)
12150 return std::nullopt;
12151 R = IntRange::join(L: *R, R: *El);
12152 }
12153 return R;
12154 }
12155
12156 if (result.isComplexInt()) {
12157 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
12158 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
12159 return IntRange::join(L: R, R: I);
12160 }
12161
12162 // This can happen with lossless casts to intptr_t of "based" lvalues.
12163 // Assume it might use arbitrary bits.
12164 // FIXME: The only reason we need to pass the type in here is to get
12165 // the sign right on this one case. It would be nice if APValue
12166 // preserved this.
12167 if (result.isLValue() || result.isAddrLabelDiff())
12168 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12169
12170 // Unsupported APValue kinds (e.g. floating) have no integer range.
12171 return std::nullopt;
12172}
12173
12174static QualType GetExprType(const Expr *E) {
12175 QualType Ty = E->getType();
12176 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
12177 Ty = AtomicRHS->getValueType();
12178 return Ty;
12179}
12180
12181/// Attempts to estimate an approximate range for the given integer expression.
12182/// Returns a range if successful, otherwise it returns \c std::nullopt if a
12183/// reliable estimation cannot be determined.
12184///
12185/// \param MaxWidth The width to which the value will be truncated.
12186/// \param InConstantContext If \c true, interpret the expression within a
12187/// constant context.
12188/// \param Approximate If \c true, provide a likely range of values by assuming
12189/// that arithmetic on narrower types remains within those types.
12190/// If \c false, return a range that includes all possible values
12191/// resulting from the expression.
12192/// \returns A range of values that the expression might take, or
12193/// std::nullopt if a reliable estimation cannot be determined.
12194static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12195 unsigned MaxWidth,
12196 bool InConstantContext,
12197 bool Approximate) {
12198 E = E->IgnoreParens();
12199
12200 // Try a full evaluation first.
12201 Expr::EvalResult result;
12202 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
12203 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
12204
12205 // I think we only want to look through implicit casts here; if the
12206 // user has an explicit widening cast, we should treat the value as
12207 // being of the new, wider type.
12208 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12209 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12210 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
12211 Approximate);
12212
12213 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
12214
12215 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12216 CE->getCastKind() == CK_BooleanToSignedIntegral;
12217
12218 // Assume that non-integer casts can span the full range of the type.
12219 if (!isIntegerCast)
12220 return OutputTypeRange;
12221
12222 std::optional<IntRange> SubRange = TryGetExprRange(
12223 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
12224 InConstantContext, Approximate);
12225 if (!SubRange)
12226 return std::nullopt;
12227
12228 // Bail out if the subexpr's range is as wide as the cast type.
12229 if (SubRange->Width >= OutputTypeRange.Width)
12230 return OutputTypeRange;
12231
12232 // Otherwise, we take the smaller width, and we're non-negative if
12233 // either the output type or the subexpr is.
12234 return IntRange(SubRange->Width,
12235 SubRange->NonNegative || OutputTypeRange.NonNegative);
12236 }
12237
12238 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12239 // If we can fold the condition, just take that operand.
12240 bool CondResult;
12241 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
12242 return TryGetExprRange(
12243 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12244 InConstantContext, Approximate);
12245
12246 // Otherwise, conservatively merge.
12247 // TryGetExprRange requires an integer expression, but a throw expression
12248 // results in a void type.
12249 Expr *TrueExpr = CO->getTrueExpr();
12250 if (TrueExpr->getType()->isVoidType())
12251 return std::nullopt;
12252
12253 std::optional<IntRange> L =
12254 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
12255 if (!L)
12256 return std::nullopt;
12257
12258 Expr *FalseExpr = CO->getFalseExpr();
12259 if (FalseExpr->getType()->isVoidType())
12260 return std::nullopt;
12261
12262 std::optional<IntRange> R =
12263 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
12264 if (!R)
12265 return std::nullopt;
12266
12267 return IntRange::join(L: *L, R: *R);
12268 }
12269
12270 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12271 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12272
12273 switch (BO->getOpcode()) {
12274 case BO_Cmp:
12275 llvm_unreachable("builtin <=> should have class type");
12276
12277 // Boolean-valued operations are single-bit and positive.
12278 case BO_LAnd:
12279 case BO_LOr:
12280 case BO_LT:
12281 case BO_GT:
12282 case BO_LE:
12283 case BO_GE:
12284 case BO_EQ:
12285 case BO_NE:
12286 return IntRange::forBoolType();
12287
12288 // The type of the assignments is the type of the LHS, so the RHS
12289 // is not necessarily the same type.
12290 case BO_MulAssign:
12291 case BO_DivAssign:
12292 case BO_RemAssign:
12293 case BO_AddAssign:
12294 case BO_SubAssign:
12295 case BO_XorAssign:
12296 case BO_OrAssign:
12297 // TODO: bitfields?
12298 return IntRange::forValueOfType(C, T: GetExprType(E));
12299
12300 // Simple assignments just pass through the RHS, which will have
12301 // been coerced to the LHS type.
12302 case BO_Assign:
12303 // TODO: bitfields?
12304 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12305 Approximate);
12306
12307 // Operations with opaque sources are black-listed.
12308 case BO_PtrMemD:
12309 case BO_PtrMemI:
12310 return IntRange::forValueOfType(C, T: GetExprType(E));
12311
12312 // Bitwise-and uses the *infinum* of the two source ranges.
12313 case BO_And:
12314 case BO_AndAssign:
12315 Combine = IntRange::bit_and;
12316 break;
12317
12318 // Left shift gets black-listed based on a judgement call.
12319 case BO_Shl:
12320 // ...except that we want to treat '1 << (blah)' as logically
12321 // positive. It's an important idiom.
12322 if (IntegerLiteral *I
12323 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
12324 if (I->getValue() == 1) {
12325 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
12326 return IntRange(R.Width, /*NonNegative*/ true);
12327 }
12328 }
12329 [[fallthrough]];
12330
12331 case BO_ShlAssign:
12332 return IntRange::forValueOfType(C, T: GetExprType(E));
12333
12334 // Right shift by a constant can narrow its left argument.
12335 case BO_Shr:
12336 case BO_ShrAssign: {
12337 std::optional<IntRange> L = TryGetExprRange(
12338 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12339 if (!L)
12340 return std::nullopt;
12341
12342 // If the shift amount is a positive constant, drop the width by
12343 // that much.
12344 if (std::optional<llvm::APSInt> shift =
12345 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12346 if (shift->isNonNegative()) {
12347 if (shift->uge(RHS: L->Width))
12348 L->Width = (L->NonNegative ? 0 : 1);
12349 else
12350 L->Width -= shift->getZExtValue();
12351 }
12352 }
12353
12354 return L;
12355 }
12356
12357 // Comma acts as its right operand.
12358 case BO_Comma:
12359 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12360 Approximate);
12361
12362 case BO_Add:
12363 if (!Approximate)
12364 Combine = IntRange::sum;
12365 break;
12366
12367 case BO_Sub:
12368 if (BO->getLHS()->getType()->isPointerType())
12369 return IntRange::forValueOfType(C, T: GetExprType(E));
12370 if (!Approximate)
12371 Combine = IntRange::difference;
12372 break;
12373
12374 case BO_Mul:
12375 if (!Approximate)
12376 Combine = IntRange::product;
12377 break;
12378
12379 // The width of a division result is mostly determined by the size
12380 // of the LHS.
12381 case BO_Div: {
12382 // Don't 'pre-truncate' the operands.
12383 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
12384 std::optional<IntRange> L = TryGetExprRange(
12385 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12386 if (!L)
12387 return std::nullopt;
12388
12389 // If the divisor is constant, use that.
12390 if (std::optional<llvm::APSInt> divisor =
12391 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12392 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12393 if (log2 >= L->Width)
12394 L->Width = (L->NonNegative ? 0 : 1);
12395 else
12396 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
12397 return L;
12398 }
12399
12400 // Otherwise, just use the LHS's width.
12401 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12402 // could be -1.
12403 std::optional<IntRange> R = TryGetExprRange(
12404 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12405 if (!R)
12406 return std::nullopt;
12407
12408 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12409 }
12410
12411 case BO_Rem:
12412 Combine = IntRange::rem;
12413 break;
12414
12415 // The default behavior is okay for these.
12416 case BO_Xor:
12417 case BO_Or:
12418 break;
12419 }
12420
12421 // Combine the two ranges, but limit the result to the type in which we
12422 // performed the computation.
12423 QualType T = GetExprType(E);
12424 unsigned opWidth = C.getIntWidth(T);
12425 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
12426 InConstantContext, Approximate);
12427 if (!L)
12428 return std::nullopt;
12429
12430 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
12431 InConstantContext, Approximate);
12432 if (!R)
12433 return std::nullopt;
12434
12435 IntRange C = Combine(*L, *R);
12436 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12437 C.Width = std::min(a: C.Width, b: MaxWidth);
12438 return C;
12439 }
12440
12441 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12442 switch (UO->getOpcode()) {
12443 // Boolean-valued operations are white-listed.
12444 case UO_LNot:
12445 return IntRange::forBoolType();
12446
12447 // Operations with opaque sources are black-listed.
12448 case UO_Deref:
12449 case UO_AddrOf: // should be impossible
12450 return IntRange::forValueOfType(C, T: GetExprType(E));
12451
12452 case UO_Minus: {
12453 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12454 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12455 Approximate);
12456 }
12457
12458 std::optional<IntRange> SubRange = TryGetExprRange(
12459 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12460
12461 if (!SubRange)
12462 return std::nullopt;
12463
12464 // If the range was previously non-negative, we need an extra bit for the
12465 // sign bit. Otherwise, we need an extra bit because the negation of the
12466 // most-negative value is one bit wider than that value.
12467 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
12468 }
12469
12470 case UO_Not: {
12471 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12472 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12473 Approximate);
12474 }
12475
12476 std::optional<IntRange> SubRange = TryGetExprRange(
12477 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12478
12479 if (!SubRange)
12480 return std::nullopt;
12481
12482 // The width increments by 1 if the sub-expression cannot be negative
12483 // since it now can be.
12484 return IntRange(
12485 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
12486 false);
12487 }
12488
12489 default:
12490 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12491 Approximate);
12492 }
12493 }
12494
12495 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12496 // The source expression is null for the OpaqueValueExpr that stands in for
12497 // a non-type template argument of pointer or reference type; fall back to
12498 // the range of the type in that case.
12499 if (const Expr *SourceExpr = OVE->getSourceExpr())
12500 return TryGetExprRange(C, E: SourceExpr, MaxWidth, InConstantContext,
12501 Approximate);
12502 }
12503
12504 if (const auto *BitField = E->getSourceBitField())
12505 return IntRange(BitField->getBitWidthValue(),
12506 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12507
12508 if (GetExprType(E)->isVoidType())
12509 return std::nullopt;
12510
12511 return IntRange::forValueOfType(C, T: GetExprType(E));
12512}
12513
12514static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12515 bool InConstantContext,
12516 bool Approximate) {
12517 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
12518 Approximate);
12519}
12520
12521/// Checks whether the given value, which currently has the given
12522/// source semantics, has the same value when coerced through the
12523/// target semantics.
12524static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12525 const llvm::fltSemantics &Src,
12526 const llvm::fltSemantics &Tgt) {
12527 llvm::APFloat truncated = value;
12528
12529 bool ignored;
12530 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12531 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12532
12533 return truncated.bitwiseIsEqual(RHS: value);
12534}
12535
12536/// Checks whether the given value, which currently has the given
12537/// source semantics, has the same value when coerced through the
12538/// target semantics.
12539///
12540/// The value might be a vector of floats (or a complex number).
12541static bool IsSameFloatAfterCast(const APValue &value,
12542 const llvm::fltSemantics &Src,
12543 const llvm::fltSemantics &Tgt) {
12544 if (value.isFloat())
12545 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
12546
12547 if (value.isVector()) {
12548 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12549 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
12550 return false;
12551 return true;
12552 }
12553
12554 if (value.isMatrix()) {
12555 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12556 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
12557 return false;
12558 return true;
12559 }
12560
12561 assert(value.isComplexFloat());
12562 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
12563 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
12564}
12565
12566static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12567 bool IsListInit = false);
12568
12569static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12570 // Suppress cases where we are comparing against an enum constant.
12571 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
12572 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
12573 return true;
12574
12575 // Suppress cases where the value is expanded from a macro, unless that macro
12576 // is how a language represents a boolean literal. This is the case in both C
12577 // and Objective-C.
12578 SourceLocation BeginLoc = E->getBeginLoc();
12579 if (BeginLoc.isMacroID()) {
12580 StringRef MacroName = Lexer::getImmediateMacroName(
12581 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
12582 return MacroName != "YES" && MacroName != "NO" &&
12583 MacroName != "true" && MacroName != "false";
12584 }
12585
12586 return false;
12587}
12588
12589static bool isKnownToHaveUnsignedValue(const Expr *E) {
12590 return E->getType()->isIntegerType() &&
12591 (!E->getType()->isSignedIntegerType() ||
12592 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12593}
12594
12595namespace {
12596/// The promoted range of values of a type. In general this has the
12597/// following structure:
12598///
12599/// |-----------| . . . |-----------|
12600/// ^ ^ ^ ^
12601/// Min HoleMin HoleMax Max
12602///
12603/// ... where there is only a hole if a signed type is promoted to unsigned
12604/// (in which case Min and Max are the smallest and largest representable
12605/// values).
12606struct PromotedRange {
12607 // Min, or HoleMax if there is a hole.
12608 llvm::APSInt PromotedMin;
12609 // Max, or HoleMin if there is a hole.
12610 llvm::APSInt PromotedMax;
12611
12612 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12613 if (R.Width == 0)
12614 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12615 else if (R.Width >= BitWidth && !Unsigned) {
12616 // Promotion made the type *narrower*. This happens when promoting
12617 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12618 // Treat all values of 'signed int' as being in range for now.
12619 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
12620 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
12621 } else {
12622 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
12623 .extOrTrunc(width: BitWidth);
12624 PromotedMin.setIsUnsigned(Unsigned);
12625
12626 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
12627 .extOrTrunc(width: BitWidth);
12628 PromotedMax.setIsUnsigned(Unsigned);
12629 }
12630 }
12631
12632 // Determine whether this range is contiguous (has no hole).
12633 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12634
12635 // Where a constant value is within the range.
12636 enum ComparisonResult {
12637 LT = 0x1,
12638 LE = 0x2,
12639 GT = 0x4,
12640 GE = 0x8,
12641 EQ = 0x10,
12642 NE = 0x20,
12643 InRangeFlag = 0x40,
12644
12645 Less = LE | LT | NE,
12646 Min = LE | InRangeFlag,
12647 InRange = InRangeFlag,
12648 Max = GE | InRangeFlag,
12649 Greater = GE | GT | NE,
12650
12651 OnlyValue = LE | GE | EQ | InRangeFlag,
12652 InHole = NE
12653 };
12654
12655 ComparisonResult compare(const llvm::APSInt &Value) const {
12656 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12657 Value.isUnsigned() == PromotedMin.isUnsigned());
12658 if (!isContiguous()) {
12659 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12660 if (Value.isMinValue()) return Min;
12661 if (Value.isMaxValue()) return Max;
12662 if (Value >= PromotedMin) return InRange;
12663 if (Value <= PromotedMax) return InRange;
12664 return InHole;
12665 }
12666
12667 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
12668 case -1: return Less;
12669 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12670 case 1:
12671 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
12672 case -1: return InRange;
12673 case 0: return Max;
12674 case 1: return Greater;
12675 }
12676 }
12677
12678 llvm_unreachable("impossible compare result");
12679 }
12680
12681 static std::optional<StringRef>
12682 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12683 if (Op == BO_Cmp) {
12684 ComparisonResult LTFlag = LT, GTFlag = GT;
12685 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
12686
12687 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12688 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12689 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12690 return std::nullopt;
12691 }
12692
12693 ComparisonResult TrueFlag, FalseFlag;
12694 if (Op == BO_EQ) {
12695 TrueFlag = EQ;
12696 FalseFlag = NE;
12697 } else if (Op == BO_NE) {
12698 TrueFlag = NE;
12699 FalseFlag = EQ;
12700 } else {
12701 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12702 TrueFlag = LT;
12703 FalseFlag = GE;
12704 } else {
12705 TrueFlag = GT;
12706 FalseFlag = LE;
12707 }
12708 if (Op == BO_GE || Op == BO_LE)
12709 std::swap(a&: TrueFlag, b&: FalseFlag);
12710 }
12711 if (R & TrueFlag)
12712 return StringRef("true");
12713 if (R & FalseFlag)
12714 return StringRef("false");
12715 return std::nullopt;
12716 }
12717};
12718}
12719
12720static bool HasEnumType(const Expr *E) {
12721 // Strip off implicit integral promotions.
12722 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12723 if (ICE->getCastKind() != CK_IntegralCast &&
12724 ICE->getCastKind() != CK_NoOp)
12725 break;
12726 E = ICE->getSubExpr();
12727 }
12728
12729 return E->getType()->isEnumeralType();
12730}
12731
12732static int classifyConstantValue(Expr *Constant) {
12733 // The values of this enumeration are used in the diagnostics
12734 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12735 enum ConstantValueKind {
12736 Miscellaneous = 0,
12737 LiteralTrue,
12738 LiteralFalse
12739 };
12740 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12741 return BL->getValue() ? ConstantValueKind::LiteralTrue
12742 : ConstantValueKind::LiteralFalse;
12743 return ConstantValueKind::Miscellaneous;
12744}
12745
12746static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12747 Expr *Constant, Expr *Other,
12748 const llvm::APSInt &Value,
12749 bool RhsConstant) {
12750 if (S.inTemplateInstantiation())
12751 return false;
12752
12753 Expr *OriginalOther = Other;
12754
12755 Constant = Constant->IgnoreParenImpCasts();
12756 Other = Other->IgnoreParenImpCasts();
12757
12758 // Suppress warnings on tautological comparisons between values of the same
12759 // enumeration type. There are only two ways we could warn on this:
12760 // - If the constant is outside the range of representable values of
12761 // the enumeration. In such a case, we should warn about the cast
12762 // to enumeration type, not about the comparison.
12763 // - If the constant is the maximum / minimum in-range value. For an
12764 // enumeratin type, such comparisons can be meaningful and useful.
12765 if (Constant->getType()->isEnumeralType() &&
12766 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12767 return false;
12768
12769 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12770 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12771 if (!OtherValueRange)
12772 return false;
12773
12774 QualType OtherT = Other->getType();
12775 if (const auto *AT = OtherT->getAs<AtomicType>())
12776 OtherT = AT->getValueType();
12777 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12778
12779 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12780 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12781 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12782 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12783 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12784
12785 // Whether we're treating Other as being a bool because of the form of
12786 // expression despite it having another type (typically 'int' in C).
12787 bool OtherIsBooleanDespiteType =
12788 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12789 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12790 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12791
12792 // Check if all values in the range of possible values of this expression
12793 // lead to the same comparison outcome.
12794 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12795 Value.isUnsigned());
12796 auto Cmp = OtherPromotedValueRange.compare(Value);
12797 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12798 if (!Result)
12799 return false;
12800
12801 // Also consider the range determined by the type alone. This allows us to
12802 // classify the warning under the proper diagnostic group.
12803 bool TautologicalTypeCompare = false;
12804 {
12805 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12806 Value.isUnsigned());
12807 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12808 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12809 ConstantOnRHS: RhsConstant)) {
12810 TautologicalTypeCompare = true;
12811 Cmp = TypeCmp;
12812 Result = TypeResult;
12813 }
12814 }
12815
12816 // Don't warn if the non-constant operand actually always evaluates to the
12817 // same value.
12818 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12819 return false;
12820
12821 // Suppress the diagnostic for an in-range comparison if the constant comes
12822 // from a macro or enumerator. We don't want to diagnose
12823 //
12824 // some_long_value <= INT_MAX
12825 //
12826 // when sizeof(int) == sizeof(long).
12827 bool InRange = Cmp & PromotedRange::InRangeFlag;
12828 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12829 return false;
12830
12831 // A comparison of an unsigned bit-field against 0 is really a type problem,
12832 // even though at the type level the bit-field might promote to 'signed int'.
12833 if (Other->refersToBitField() && InRange && Value == 0 &&
12834 Other->getType()->isUnsignedIntegerOrEnumerationType())
12835 TautologicalTypeCompare = true;
12836
12837 // If this is a comparison to an enum constant, include that
12838 // constant in the diagnostic.
12839 const EnumConstantDecl *ED = nullptr;
12840 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12841 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12842
12843 // Should be enough for uint128 (39 decimal digits)
12844 SmallString<64> PrettySourceValue;
12845 llvm::raw_svector_ostream OS(PrettySourceValue);
12846 if (ED) {
12847 OS << '\'' << *ED << "' (" << Value << ")";
12848 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12849 Val: Constant->IgnoreParenImpCasts())) {
12850 OS << (BL->getValue() ? "YES" : "NO");
12851 } else {
12852 OS << Value;
12853 }
12854
12855 if (!TautologicalTypeCompare) {
12856 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12857 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12858 << E->getOpcodeStr() << OS.str() << *Result
12859 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12860 return true;
12861 }
12862
12863 if (IsObjCSignedCharBool) {
12864 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12865 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12866 << OS.str() << *Result);
12867 return true;
12868 }
12869
12870 // FIXME: We use a somewhat different formatting for the in-range cases and
12871 // cases involving boolean values for historical reasons. We should pick a
12872 // consistent way of presenting these diagnostics.
12873 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12874
12875 S.DiagRuntimeBehavior(
12876 Loc: E->getOperatorLoc(), Statement: E,
12877 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12878 : diag::warn_tautological_bool_compare)
12879 << OS.str() << classifyConstantValue(Constant) << OtherT
12880 << OtherIsBooleanDespiteType << *Result
12881 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12882 } else {
12883 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12884 unsigned Diag =
12885 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12886 ? (HasEnumType(E: OriginalOther)
12887 ? diag::warn_unsigned_enum_always_true_comparison
12888 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12889 : diag::warn_unsigned_always_true_comparison)
12890 : diag::warn_tautological_constant_compare;
12891
12892 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12893 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12894 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12895 }
12896
12897 return true;
12898}
12899
12900/// Analyze the operands of the given comparison. Implements the
12901/// fallback case from AnalyzeComparison.
12902static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12903 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12904 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12905}
12906
12907/// Implements -Wsign-compare.
12908///
12909/// \param E the binary operator to check for warnings
12910static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12911 // The type the comparison is being performed in.
12912 QualType T = E->getLHS()->getType();
12913
12914 // Only analyze comparison operators where both sides have been converted to
12915 // the same type.
12916 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12917 return AnalyzeImpConvsInComparison(S, E);
12918
12919 // Don't analyze value-dependent comparisons directly.
12920 if (E->isValueDependent())
12921 return AnalyzeImpConvsInComparison(S, E);
12922
12923 Expr *LHS = E->getLHS();
12924 Expr *RHS = E->getRHS();
12925
12926 if (T->isIntegralType(Ctx: S.Context)) {
12927 std::optional<llvm::APSInt> RHSValue =
12928 RHS->getIntegerConstantExpr(Ctx: S.Context);
12929 std::optional<llvm::APSInt> LHSValue =
12930 LHS->getIntegerConstantExpr(Ctx: S.Context);
12931
12932 // We don't care about expressions whose result is a constant.
12933 if (RHSValue && LHSValue)
12934 return AnalyzeImpConvsInComparison(S, E);
12935
12936 // We only care about expressions where just one side is literal
12937 if ((bool)RHSValue ^ (bool)LHSValue) {
12938 // Is the constant on the RHS or LHS?
12939 const bool RhsConstant = (bool)RHSValue;
12940 Expr *Const = RhsConstant ? RHS : LHS;
12941 Expr *Other = RhsConstant ? LHS : RHS;
12942 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12943
12944 // Check whether an integer constant comparison results in a value
12945 // of 'true' or 'false'.
12946 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12947 return AnalyzeImpConvsInComparison(S, E);
12948 }
12949 }
12950
12951 if (!T->hasUnsignedIntegerRepresentation()) {
12952 // We don't do anything special if this isn't an unsigned integral
12953 // comparison: we're only interested in integral comparisons, and
12954 // signed comparisons only happen in cases we don't care to warn about.
12955 return AnalyzeImpConvsInComparison(S, E);
12956 }
12957
12958 LHS = LHS->IgnoreParenImpCasts();
12959 RHS = RHS->IgnoreParenImpCasts();
12960
12961 if (!S.getLangOpts().CPlusPlus) {
12962 // Avoid warning about comparison of integers with different signs when
12963 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12964 // the type of `E`.
12965 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12966 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12967 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12968 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12969 }
12970
12971 // Check to see if one of the (unmodified) operands is of different
12972 // signedness.
12973 Expr *signedOperand, *unsignedOperand;
12974 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12975 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12976 "unsigned comparison between two signed integer expressions?");
12977 signedOperand = LHS;
12978 unsignedOperand = RHS;
12979 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12980 signedOperand = RHS;
12981 unsignedOperand = LHS;
12982 } else {
12983 return AnalyzeImpConvsInComparison(S, E);
12984 }
12985
12986 // Otherwise, calculate the effective range of the signed operand.
12987 std::optional<IntRange> signedRange =
12988 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12989 /*Approximate=*/true);
12990 if (!signedRange)
12991 return;
12992
12993 // Go ahead and analyze implicit conversions in the operands. Note
12994 // that we skip the implicit conversions on both sides.
12995 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12996 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12997
12998 // If the signed range is non-negative, -Wsign-compare won't fire.
12999 if (signedRange->NonNegative)
13000 return;
13001
13002 // For (in)equality comparisons, if the unsigned operand is a
13003 // constant which cannot collide with a overflowed signed operand,
13004 // then reinterpreting the signed operand as unsigned will not
13005 // change the result of the comparison.
13006 if (E->isEqualityOp()) {
13007 unsigned comparisonWidth = S.Context.getIntWidth(T);
13008 std::optional<IntRange> unsignedRange = TryGetExprRange(
13009 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
13010 /*Approximate=*/true);
13011 if (!unsignedRange)
13012 return;
13013
13014 // We should never be unable to prove that the unsigned operand is
13015 // non-negative.
13016 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
13017
13018 if (unsignedRange->Width < comparisonWidth)
13019 return;
13020 }
13021
13022 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
13023 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
13024 << LHS->getType() << RHS->getType()
13025 << LHS->getSourceRange() << RHS->getSourceRange());
13026}
13027
13028/// Analyzes an attempt to assign the given value to a bitfield.
13029///
13030/// Returns true if there was something fishy about the attempt.
13031static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
13032 SourceLocation InitLoc) {
13033 assert(Bitfield->isBitField());
13034 if (Bitfield->isInvalidDecl())
13035 return false;
13036
13037 // White-list bool bitfields.
13038 QualType BitfieldType = Bitfield->getType();
13039 if (BitfieldType->isBooleanType())
13040 return false;
13041
13042 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
13043 // If the underlying enum type was not explicitly specified as an unsigned
13044 // type and the enum contain only positive values, MSVC++ will cause an
13045 // inconsistency by storing this as a signed type.
13046 if (S.getLangOpts().CPlusPlus11 &&
13047 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
13048 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
13049 BitfieldEnumDecl->getNumNegativeBits() == 0) {
13050 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
13051 << BitfieldEnumDecl;
13052 }
13053 }
13054
13055 // Ignore value- or type-dependent expressions.
13056 if (Bitfield->getBitWidth()->isValueDependent() ||
13057 Bitfield->getBitWidth()->isTypeDependent() ||
13058 Init->isValueDependent() ||
13059 Init->isTypeDependent())
13060 return false;
13061
13062 Expr *OriginalInit = Init->IgnoreParenImpCasts();
13063 unsigned FieldWidth = Bitfield->getBitWidthValue();
13064
13065 Expr::EvalResult Result;
13066 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
13067 AllowSideEffects: Expr::SE_AllowSideEffects)) {
13068 // The RHS is not constant. If the RHS has an enum type, make sure the
13069 // bitfield is wide enough to hold all the values of the enum without
13070 // truncation.
13071 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
13072 const PreferredTypeAttr *PTAttr = nullptr;
13073 if (!ED) {
13074 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
13075 if (PTAttr)
13076 ED = PTAttr->getType()->getAsEnumDecl();
13077 }
13078 if (ED) {
13079 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
13080
13081 // Enum types are implicitly signed on Windows, so check if there are any
13082 // negative enumerators to see if the enum was intended to be signed or
13083 // not.
13084 bool SignedEnum = ED->getNumNegativeBits() > 0;
13085
13086 // Check for surprising sign changes when assigning enum values to a
13087 // bitfield of different signedness. If the bitfield is signed and we
13088 // have exactly the right number of bits to store this unsigned enum,
13089 // suggest changing the enum to an unsigned type. This typically happens
13090 // on Windows where unfixed enums always use an underlying type of 'int'.
13091 unsigned DiagID = 0;
13092 if (SignedEnum && !SignedBitfield) {
13093 DiagID =
13094 PTAttr == nullptr
13095 ? diag::warn_unsigned_bitfield_assigned_signed_enum
13096 : diag::
13097 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
13098 } else if (SignedBitfield && !SignedEnum &&
13099 ED->getNumPositiveBits() == FieldWidth) {
13100 DiagID =
13101 PTAttr == nullptr
13102 ? diag::warn_signed_bitfield_enum_conversion
13103 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
13104 }
13105 if (DiagID) {
13106 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
13107 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
13108 SourceRange TypeRange =
13109 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
13110 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
13111 << SignedEnum << TypeRange;
13112 if (PTAttr)
13113 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
13114 << ED;
13115 }
13116
13117 // Compute the required bitwidth. If the enum has negative values, we need
13118 // one more bit than the normal number of positive bits to represent the
13119 // sign bit.
13120 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
13121 b: ED->getNumNegativeBits())
13122 : ED->getNumPositiveBits();
13123
13124 // Check the bitwidth.
13125 if (BitsNeeded > FieldWidth) {
13126 Expr *WidthExpr = Bitfield->getBitWidth();
13127 auto DiagID =
13128 PTAttr == nullptr
13129 ? diag::warn_bitfield_too_small_for_enum
13130 : diag::warn_preferred_type_bitfield_too_small_for_enum;
13131 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
13132 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
13133 << BitsNeeded << ED << WidthExpr->getSourceRange();
13134 if (PTAttr)
13135 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
13136 << ED;
13137 }
13138 }
13139
13140 return false;
13141 }
13142
13143 llvm::APSInt Value = Result.Val.getInt();
13144
13145 unsigned OriginalWidth = Value.getBitWidth();
13146
13147 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
13148 // false positives where the user is demonstrating they intend to use the
13149 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
13150 // to a one-bit bit-field to see if the value came from a macro named 'true'.
13151 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
13152 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
13153 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
13154 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
13155 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
13156 return false;
13157 }
13158
13159 if (!Value.isSigned() || Value.isNegative())
13160 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
13161 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
13162 OriginalWidth = Value.getSignificantBits();
13163
13164 if (OriginalWidth <= FieldWidth)
13165 return false;
13166
13167 // Compute the value which the bitfield will contain.
13168 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
13169 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
13170
13171 // Check whether the stored value is equal to the original value.
13172 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
13173 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
13174 return false;
13175
13176 std::string PrettyValue = toString(I: Value, Radix: 10);
13177 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
13178
13179 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
13180 ? diag::warn_impcast_single_bit_bitield_precision_constant
13181 : diag::warn_impcast_bitfield_precision_constant)
13182 << PrettyValue << PrettyTrunc << OriginalInit->getType()
13183 << Init->getSourceRange();
13184
13185 return true;
13186}
13187
13188/// Analyze the given simple or compound assignment for warning-worthy
13189/// operations.
13190static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
13191 // Just recurse on the LHS.
13192 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13193
13194 // We want to recurse on the RHS as normal unless we're assigning to
13195 // a bitfield.
13196 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
13197 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
13198 InitLoc: E->getOperatorLoc())) {
13199 // Recurse, ignoring any implicit conversions on the RHS.
13200 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
13201 CC: E->getOperatorLoc());
13202 }
13203 }
13204
13205 // Set context flag for overflow behavior type assignment analysis, use RAII
13206 // pattern to handle nested assignments.
13207 llvm::SaveAndRestore OBTAssignmentContext(
13208 S.InOverflowBehaviorAssignmentContext, true);
13209
13210 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13211
13212 // Diagnose implicitly sequentially-consistent atomic assignment.
13213 if (E->getLHS()->getType()->isAtomicType())
13214 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13215}
13216
13217/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13218static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13219 QualType T, SourceLocation CContext, unsigned diag,
13220 bool PruneControlFlow = false) {
13221 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13222 // address space annotations isn't really useful. The warnings aren't because
13223 // you're converting a `private int` to `unsigned int`, it is because you're
13224 // conerting `int` to `unsigned int`.
13225 if (SourceType.hasAddressSpace())
13226 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
13227 if (T.hasAddressSpace())
13228 T = S.getASTContext().removeAddrSpaceQualType(T);
13229 if (PruneControlFlow) {
13230 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13231 PD: S.PDiag(DiagID: diag)
13232 << SourceType << T << E->getSourceRange()
13233 << SourceRange(CContext));
13234 return;
13235 }
13236 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
13237 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13238}
13239
13240/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13241static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13242 SourceLocation CContext, unsigned diag,
13243 bool PruneControlFlow = false) {
13244 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
13245}
13246
13247/// Diagnose an implicit cast from a floating point value to an integer value.
13248static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13249 SourceLocation CContext) {
13250 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
13251 bool PruneWarnings = S.inTemplateInstantiation();
13252
13253 const Expr *InnerE = E->IgnoreParenImpCasts();
13254 // We also want to warn on, e.g., "int i = -1.234"
13255 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
13256 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13257 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13258
13259 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
13260
13261 llvm::APFloat Value(0.0);
13262 bool IsConstant =
13263 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
13264 if (!IsConstant) {
13265 if (S.ObjC().isSignedCharBool(Ty: T)) {
13266 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13267 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
13268 << E->getType());
13269 }
13270
13271 return DiagnoseImpCast(S, E, T, CContext,
13272 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13273 }
13274
13275 bool isExact = false;
13276
13277 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13278 T->hasUnsignedIntegerRepresentation());
13279 llvm::APFloat::opStatus Result = Value.convertToInteger(
13280 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
13281
13282 // FIXME: Force the precision of the source value down so we don't print
13283 // digits which are usually useless (we don't really care here if we
13284 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13285 // would automatically print the shortest representation, but it's a bit
13286 // tricky to implement.
13287 SmallString<16> PrettySourceValue;
13288 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13289 precision = (precision * 59 + 195) / 196;
13290 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
13291
13292 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
13293 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13294 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13295 << PrettySourceValue);
13296 }
13297
13298 if (Result == llvm::APFloat::opOK && isExact) {
13299 if (IsLiteral) return;
13300 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
13301 PruneControlFlow: PruneWarnings);
13302 }
13303
13304 // Conversion of a floating-point value to a non-bool integer where the
13305 // integral part cannot be represented by the integer type is undefined.
13306 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13307 return DiagnoseImpCast(
13308 S, E, T, CContext,
13309 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13310 : diag::warn_impcast_float_to_integer_out_of_range,
13311 PruneControlFlow: PruneWarnings);
13312
13313 unsigned DiagID = 0;
13314 if (IsLiteral) {
13315 // Warn on floating point literal to integer.
13316 DiagID = diag::warn_impcast_literal_float_to_integer;
13317 } else if (IntegerValue == 0) {
13318 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13319 return DiagnoseImpCast(S, E, T, CContext,
13320 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13321 }
13322 // Warn on non-zero to zero conversion.
13323 DiagID = diag::warn_impcast_float_to_integer_zero;
13324 } else {
13325 if (IntegerValue.isUnsigned()) {
13326 if (!IntegerValue.isMaxValue()) {
13327 return DiagnoseImpCast(S, E, T, CContext,
13328 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13329 }
13330 } else { // IntegerValue.isSigned()
13331 if (!IntegerValue.isMaxSignedValue() &&
13332 !IntegerValue.isMinSignedValue()) {
13333 return DiagnoseImpCast(S, E, T, CContext,
13334 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13335 }
13336 }
13337 // Warn on evaluatable floating point expression to integer conversion.
13338 DiagID = diag::warn_impcast_float_to_integer;
13339 }
13340
13341 SmallString<16> PrettyTargetValue;
13342 if (IsBool)
13343 PrettyTargetValue = Value.isZero() ? "false" : "true";
13344 else
13345 IntegerValue.toString(Str&: PrettyTargetValue);
13346
13347 if (PruneWarnings) {
13348 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13349 PD: S.PDiag(DiagID)
13350 << E->getType() << T.getUnqualifiedType()
13351 << PrettySourceValue << PrettyTargetValue
13352 << E->getSourceRange() << SourceRange(CContext));
13353 } else {
13354 S.Diag(Loc: E->getExprLoc(), DiagID)
13355 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13356 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13357 }
13358}
13359
13360/// Analyze the given compound assignment for the possible losing of
13361/// floating-point precision.
13362static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13363 assert(isa<CompoundAssignOperator>(E) &&
13364 "Must be compound assignment operation");
13365 // Recurse on the LHS and RHS in here
13366 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13367 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13368
13369 if (E->getLHS()->getType()->isAtomicType())
13370 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13371
13372 // Now check the outermost expression
13373 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13374 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
13375 ->getComputationResultType()
13376 ->getAs<BuiltinType>();
13377
13378 // The below checks assume source is floating point.
13379 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13380
13381 // If source is floating point but target is an integer.
13382 if (ResultBT->isInteger())
13383 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
13384 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
13385
13386 if (!ResultBT->isFloatingPoint())
13387 return;
13388
13389 // If both source and target are floating points, warn about losing precision.
13390 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13391 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
13392 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
13393 // warn about dropping FP rank.
13394 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
13395 diag: diag::warn_impcast_float_result_precision);
13396}
13397
13398static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13399 IntRange Range) {
13400 if (!Range.Width) return "0";
13401
13402 llvm::APSInt ValueInRange = Value;
13403 ValueInRange.setIsSigned(!Range.NonNegative);
13404 ValueInRange = ValueInRange.trunc(width: Range.Width);
13405 return toString(I: ValueInRange, Radix: 10);
13406}
13407
13408static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13409 bool ToBool) {
13410 if (!isa<ImplicitCastExpr>(Val: Ex))
13411 return false;
13412
13413 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13414 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
13415 const Type *Source =
13416 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
13417 if (Target->isDependentType())
13418 return false;
13419
13420 const auto *FloatCandidateBT =
13421 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
13422 const Type *BoolCandidateType = ToBool ? Target : Source;
13423
13424 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
13425 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13426}
13427
13428static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13429 SourceLocation CC) {
13430 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13431 const Expr *CurrA = TheCall->getArg(Arg: I);
13432 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
13433 continue;
13434
13435 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13436 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
13437 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13438 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
13439 if (IsSwapped) {
13440 // Warn on this floating-point to bool conversion.
13441 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
13442 T: CurrA->getType(), CContext: CC,
13443 diag: diag::warn_impcast_floating_point_to_bool);
13444 }
13445 }
13446}
13447
13448static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13449 SourceLocation CC) {
13450 // Don't warn on functions which have return type nullptr_t.
13451 if (isa<CallExpr>(Val: E))
13452 return;
13453
13454 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13455 const Expr *NewE = E->IgnoreParenImpCasts();
13456 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
13457 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13458 if (!IsGNUNullExpr && !HasNullPtrType)
13459 return;
13460
13461 // Return if target type is a safe conversion.
13462 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13463 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13464 return;
13465
13466 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
13467 Loc: E->getExprLoc()))
13468 return;
13469
13470 SourceLocation Loc = E->getSourceRange().getBegin();
13471
13472 // Venture through the macro stacks to get to the source of macro arguments.
13473 // The new location is a better location than the complete location that was
13474 // passed in.
13475 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13476 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
13477
13478 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13479 if (IsGNUNullExpr && Loc.isMacroID()) {
13480 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13481 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
13482 if (MacroName == "NULL")
13483 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13484 }
13485
13486 // Only warn if the null and context location are in the same macro expansion.
13487 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
13488 return;
13489
13490 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
13491 << HasNullPtrType << T << SourceRange(CC)
13492 << FixItHint::CreateReplacement(RemoveRange: Loc,
13493 Code: S.getFixItZeroLiteralForType(T, Loc));
13494}
13495
13496// Helper function to filter out cases for constant width constant conversion.
13497// Don't warn on unsigned char array initialization or for non-decimal
13498// values.
13499static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13500 SourceLocation CC) {
13501 // If initializing from a constant, and the constant starts with '0',
13502 // then it is a binary, octal, or hexadecimal. Allow these constants
13503 // to fill all the bits, even if there is a sign change.
13504 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
13505 const char FirstLiteralCharacter =
13506 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
13507 if (FirstLiteralCharacter == '0')
13508 return false;
13509 }
13510
13511 // If the CC location points to a '{' and the type is an unsigned char
13512 // type, assume it is an array initialization.
13513 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13514 const char FirstContextCharacter =
13515 S.getSourceManager().getCharacterData(SL: CC)[0];
13516 if (FirstContextCharacter == '{')
13517 return false;
13518 }
13519
13520 return true;
13521}
13522
13523static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13524 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
13525 if (!IL) {
13526 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13527 if (UO->getOpcode() == UO_Minus)
13528 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13529 }
13530 }
13531
13532 return IL;
13533}
13534
13535static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13536 E = E->IgnoreParenImpCasts();
13537 SourceLocation ExprLoc = E->getExprLoc();
13538
13539 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
13540 BinaryOperator::Opcode Opc = BO->getOpcode();
13541 Expr::EvalResult Result;
13542 // Do not diagnose unsigned shifts.
13543 if (Opc == BO_Shl) {
13544 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
13545 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
13546 if (LHS && LHS->getValue() == 0)
13547 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
13548 else if (!E->isValueDependent() && LHS && RHS &&
13549 RHS->getValue().isNonNegative() &&
13550 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
13551 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
13552 << (Result.Val.getInt() != 0);
13553 else if (E->getType()->isSignedIntegerType())
13554 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
13555 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
13556 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
13557 Code: ") != 0");
13558 }
13559 }
13560
13561 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13562 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
13563 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
13564 if (!LHS || !RHS)
13565 return;
13566 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13567 (RHS->getValue() == 0 || RHS->getValue() == 1))
13568 // Do not diagnose common idioms.
13569 return;
13570 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13571 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
13572 }
13573}
13574
13575static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
13576 const Type *Target, Expr *E,
13577 QualType T,
13578 SourceLocation CC) {
13579 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13580 Source != Target);
13581
13582 // Lone surrogates have a distinct representation in UTF-32.
13583 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13584 // so don't warn on such conversion.
13585 if (Source->isChar16Type() && Target->isChar32Type())
13586 return;
13587
13588 Expr::EvalResult Result;
13589 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
13590 InConstantContext: S.isConstantEvaluatedContext())) {
13591 llvm::APSInt Value(32);
13592 Value = Result.Val.getInt();
13593 bool IsASCII = Value <= 0x7F;
13594 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13595 bool ConversionPreservesSemantics =
13596 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13597
13598 if (!ConversionPreservesSemantics) {
13599 auto IsSingleCodeUnitCP = [](const QualType &T,
13600 const llvm::APSInt &Value) {
13601 if (T->isChar8Type())
13602 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13603 if (T->isChar16Type())
13604 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13605 assert(T->isChar32Type());
13606 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13607 };
13608
13609 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
13610 << E->getType() << T
13611 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13612 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
13613 }
13614 } else {
13615 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
13616 S.getASTContext().getIntWidth(T);
13617 DiagnoseImpCast(S, E, T, CContext: CC,
13618 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
13619 : diag::warn_impcast_unicode_char_type);
13620 }
13621}
13622
13623bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
13624 From = Context.getCanonicalType(T: From);
13625 To = Context.getCanonicalType(T: To);
13626 QualType MaybePointee = From->getPointeeType();
13627 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13628 From = MaybePointee;
13629 MaybePointee = To->getPointeeType();
13630 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13631 To = MaybePointee;
13632
13633 if (const auto *FromFn = From->getAs<FunctionType>()) {
13634 if (const auto *ToFn = To->getAs<FunctionType>()) {
13635 if (FromFn->getCFIUncheckedCalleeAttr() &&
13636 !ToFn->getCFIUncheckedCalleeAttr())
13637 return true;
13638 }
13639 }
13640 return false;
13641}
13642
13643void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
13644 bool *ICContext, bool IsListInit) {
13645 if (E->isTypeDependent() || E->isValueDependent()) return;
13646
13647 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
13648 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13649 if (Source == Target) return;
13650 if (Target->isDependentType()) return;
13651
13652 // If the conversion context location is invalid don't complain. We also
13653 // don't want to emit a warning if the issue occurs from the expansion of
13654 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13655 // delay this check as long as possible. Once we detect we are in that
13656 // scenario, we just return.
13657 if (CC.isInvalid())
13658 return;
13659
13660 if (Source->isAtomicType())
13661 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13662
13663 // Diagnose implicit casts to bool.
13664 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
13665 if (isa<StringLiteral>(Val: E))
13666 // Warn on string literal to bool. Checks for string literals in logical
13667 // and expressions, for instance, assert(0 && "error here"), are
13668 // prevented by a check in AnalyzeImplicitConversions().
13669 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13670 diag: diag::warn_impcast_string_literal_to_bool);
13671 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
13672 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
13673 // This covers the literal expressions that evaluate to Objective-C
13674 // objects.
13675 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13676 diag: diag::warn_impcast_objective_c_literal_to_bool);
13677 }
13678 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13679 // Warn on pointer to bool conversion that is always true.
13680 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
13681 Range: SourceRange(CC));
13682 }
13683 }
13684
13685 CheckOverflowBehaviorTypeConversion(E, T, CC);
13686
13687 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13688 // is a typedef for signed char (macOS), then that constant value has to be 1
13689 // or 0.
13690 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
13691 Expr::EvalResult Result;
13692 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
13693 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13694 ObjC().adornBoolConversionDiagWithTernaryFixit(
13695 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13696 << toString(I: Result.Val.getInt(), Radix: 10));
13697 }
13698 return;
13699 }
13700 }
13701
13702 // Check implicit casts from Objective-C collection literals to specialized
13703 // collection types, e.g., NSArray<NSString *> *.
13704 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13705 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13706 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13707 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13708
13709 // Strip complex types.
13710 if (isa<ComplexType>(Val: Source)) {
13711 if (!isa<ComplexType>(Val: Target)) {
13712 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13713 return;
13714
13715 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13716 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13717 diag: diag::err_impcast_incompatible_type);
13718 }
13719
13720 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13721 diag: getLangOpts().CPlusPlus
13722 ? diag::err_impcast_complex_scalar
13723 : diag::warn_impcast_complex_scalar);
13724 }
13725
13726 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13727 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13728 }
13729
13730 // Strip vector types.
13731 if (isa<VectorType>(Val: Source)) {
13732 if (Target->isSveVLSBuiltinType() &&
13733 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13734 SecondType: QualType(Source, 0)) ||
13735 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13736 SecondType: QualType(Source, 0))))
13737 return;
13738
13739 if (Target->isRVVVLSBuiltinType() &&
13740 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13741 SecondType: QualType(Source, 0)) ||
13742 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13743 SecondType: QualType(Source, 0))))
13744 return;
13745
13746 if (!isa<VectorType>(Val: Target)) {
13747 if (SourceMgr.isInSystemMacro(loc: CC))
13748 return;
13749 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13750 }
13751 if (getLangOpts().HLSL &&
13752 Target->castAs<VectorType>()->getNumElements() <
13753 Source->castAs<VectorType>()->getNumElements()) {
13754 // Diagnose vector truncation but don't return. We may also want to
13755 // diagnose an element conversion.
13756 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13757 diag: diag::warn_hlsl_impcast_vector_truncation);
13758 }
13759
13760 // If the vector cast is cast between two vectors of the same size, it is
13761 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13762 if (!getLangOpts().HLSL &&
13763 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13764 return;
13765
13766 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13767 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13768 }
13769 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13770 Target = VecTy->getElementType().getTypePtr();
13771
13772 // Strip matrix types.
13773 if (isa<ConstantMatrixType>(Val: Source)) {
13774 if (Target->isScalarType())
13775 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13776
13777 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13778 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13779 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13780 // Diagnose Matrix truncation but don't return. We may also want to
13781 // diagnose an element conversion.
13782 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13783 diag: diag::warn_hlsl_impcast_matrix_truncation);
13784 }
13785
13786 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13787 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13788 }
13789 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13790 Target = MatTy->getElementType().getTypePtr();
13791
13792 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13793 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13794
13795 // Strip SVE vector types
13796 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13797 // Need the original target type for vector type checks
13798 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13799 // Handle conversion from scalable to fixed when msve-vector-bits is
13800 // specified
13801 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13802 SecondType: QualType(Source, 0)) ||
13803 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13804 SecondType: QualType(Source, 0)))
13805 return;
13806
13807 // If the vector cast is cast between two vectors of the same size, it is
13808 // a bitcast, not a conversion.
13809 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13810 return;
13811
13812 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13813 }
13814
13815 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13816 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13817
13818 // Nothing to diagnose if stripping the wrappers left identical element types
13819 // (e.g. a scalar splatted to a vector of its own type).
13820 if (Source == Target)
13821 return;
13822
13823 // If the source is floating point...
13824 if (SourceBT && SourceBT->isFloatingPoint()) {
13825 // ...and the target is floating point...
13826 if (TargetBT && TargetBT->isFloatingPoint()) {
13827 // ...then warn if we're dropping FP rank.
13828
13829 int Order = getASTContext().getFloatingTypeSemanticOrder(
13830 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13831 if (Order > 0) {
13832 // Don't warn about float constants that are precisely
13833 // representable in the target type.
13834 Expr::EvalResult result;
13835 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13836 // Value might be a float, a float vector, or a float complex.
13837 if (IsSameFloatAfterCast(
13838 value: result.Val,
13839 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13840 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13841 return;
13842 }
13843
13844 if (SourceMgr.isInSystemMacro(loc: CC))
13845 return;
13846
13847 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13848 }
13849 // ... or possibly if we're increasing rank, too
13850 else if (Order < 0) {
13851 if (SourceMgr.isInSystemMacro(loc: CC))
13852 return;
13853
13854 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13855 }
13856 return;
13857 }
13858
13859 // If the target is integral, always warn.
13860 if (TargetBT && TargetBT->isInteger()) {
13861 if (SourceMgr.isInSystemMacro(loc: CC))
13862 return;
13863
13864 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13865 }
13866
13867 // Detect the case where a call result is converted from floating-point to
13868 // to bool, and the final argument to the call is converted from bool, to
13869 // discover this typo:
13870 //
13871 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13872 //
13873 // FIXME: This is an incredibly special case; is there some more general
13874 // way to detect this class of misplaced-parentheses bug?
13875 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13876 // Check last argument of function call to see if it is an
13877 // implicit cast from a type matching the type the result
13878 // is being cast to.
13879 CallExpr *CEx = cast<CallExpr>(Val: E);
13880 if (unsigned NumArgs = CEx->getNumArgs()) {
13881 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13882 Expr *InnerE = LastA->IgnoreParenImpCasts();
13883 if (isa<ImplicitCastExpr>(Val: LastA) &&
13884 InnerE->getType()->isBooleanType()) {
13885 // Warn on this floating-point to bool conversion
13886 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13887 diag: diag::warn_impcast_floating_point_to_bool);
13888 }
13889 }
13890 }
13891 return;
13892 }
13893
13894 // Valid casts involving fixed point types should be accounted for here.
13895 if (Source->isFixedPointType()) {
13896 if (Target->isUnsaturatedFixedPointType()) {
13897 Expr::EvalResult Result;
13898 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13899 InConstantContext: isConstantEvaluatedContext())) {
13900 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13901 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13902 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13903 if (Value > MaxVal || Value < MinVal) {
13904 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13905 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13906 << Value.toString() << T
13907 << E->getSourceRange()
13908 << clang::SourceRange(CC));
13909 return;
13910 }
13911 }
13912 } else if (Target->isIntegerType()) {
13913 Expr::EvalResult Result;
13914 if (!isConstantEvaluatedContext() &&
13915 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13916 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13917
13918 bool Overflowed;
13919 llvm::APSInt IntResult = FXResult.convertToInt(
13920 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13921 Overflow: &Overflowed);
13922
13923 if (Overflowed) {
13924 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13925 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13926 << FXResult.toString() << T
13927 << E->getSourceRange()
13928 << clang::SourceRange(CC));
13929 return;
13930 }
13931 }
13932 }
13933 } else if (Target->isUnsaturatedFixedPointType()) {
13934 if (Source->isIntegerType()) {
13935 Expr::EvalResult Result;
13936 if (!isConstantEvaluatedContext() &&
13937 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13938 llvm::APSInt Value = Result.Val.getInt();
13939
13940 bool Overflowed;
13941 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13942 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13943
13944 if (Overflowed) {
13945 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13946 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13947 << toString(I: Value, /*Radix=*/10) << T
13948 << E->getSourceRange()
13949 << clang::SourceRange(CC));
13950 return;
13951 }
13952 }
13953 }
13954 }
13955
13956 // If we are casting an integer type to a floating point type without
13957 // initialization-list syntax, we might lose accuracy if the floating
13958 // point type has a narrower significand than the integer type.
13959 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13960 TargetBT->isFloatingType() && !IsListInit) {
13961 // Determine the number of precision bits in the source integer type.
13962 std::optional<IntRange> SourceRange =
13963 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13964 /*Approximate=*/true);
13965 if (!SourceRange)
13966 return;
13967 unsigned int SourcePrecision = SourceRange->Width;
13968
13969 // Determine the number of precision bits in the
13970 // target floating point type.
13971 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13972 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13973
13974 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13975 SourcePrecision > TargetPrecision) {
13976
13977 if (std::optional<llvm::APSInt> SourceInt =
13978 E->getIntegerConstantExpr(Ctx: Context)) {
13979 // If the source integer is a constant, convert it to the target
13980 // floating point type. Issue a warning if the value changes
13981 // during the whole conversion.
13982 llvm::APFloat TargetFloatValue(
13983 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13984 llvm::APFloat::opStatus ConversionStatus =
13985 TargetFloatValue.convertFromAPInt(
13986 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13987 RM: llvm::APFloat::rmNearestTiesToEven);
13988
13989 if (ConversionStatus != llvm::APFloat::opOK) {
13990 SmallString<32> PrettySourceValue;
13991 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13992 SmallString<32> PrettyTargetValue;
13993 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13994
13995 DiagRuntimeBehavior(
13996 Loc: E->getExprLoc(), Statement: E,
13997 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13998 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13999 << E->getSourceRange() << clang::SourceRange(CC));
14000 }
14001 } else {
14002 // Otherwise, the implicit conversion may lose precision.
14003 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14004 diag: diag::warn_impcast_integer_float_precision);
14005 }
14006 }
14007 }
14008
14009 DiagnoseNullConversion(S&: *this, E, T, CC);
14010
14011 DiscardMisalignedMemberAddress(T: Target, E);
14012
14013 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
14014 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
14015 return;
14016 }
14017
14018 if (Target->isBooleanType())
14019 DiagnoseIntInBoolContext(S&: *this, E);
14020
14021 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
14022 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
14023 << QualType(Source, 0) << QualType(Target, 0);
14024 }
14025
14026 if (!Source->isIntegerType() || !Target->isIntegerType())
14027 return;
14028
14029 // TODO: remove this early return once the false positives for constant->bool
14030 // in templates, macros, etc, are reduced or removed.
14031 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
14032 return;
14033
14034 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
14035 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
14036 return ObjC().adornBoolConversionDiagWithTernaryFixit(
14037 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
14038 << E->getType());
14039 }
14040 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
14041 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
14042 if (!LikelySourceRange)
14043 return;
14044
14045 IntRange SourceTypeRange =
14046 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
14047 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
14048
14049 if (LikelySourceRange->Width > TargetRange.Width) {
14050 // Check if target is a wrapping OBT - if so, don't warn about constant
14051 // conversion as this type may be used intentionally with implicit
14052 // truncation, especially during assignments.
14053 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14054 if (TargetOBT->isWrapKind()) {
14055 return;
14056 }
14057 }
14058
14059 // Check if source expression has an explicit __ob_wrap cast because if so,
14060 // wrapping was explicitly requested and we shouldn't warn
14061 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
14062 if (SourceOBT->isWrapKind()) {
14063 return;
14064 }
14065 }
14066
14067 // If the source is a constant, use a default-on diagnostic.
14068 // TODO: this should happen for bitfield stores, too.
14069 Expr::EvalResult Result;
14070 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
14071 InConstantContext: isConstantEvaluatedContext())) {
14072 llvm::APSInt Value(32);
14073 Value = Result.Val.getInt();
14074
14075 if (SourceMgr.isInSystemMacro(loc: CC))
14076 return;
14077
14078 std::string PrettySourceValue = toString(I: Value, Radix: 10);
14079 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
14080
14081 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
14082 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
14083 << PrettySourceValue << PrettyTargetValue
14084 << E->getType() << T << E->getSourceRange()
14085 << SourceRange(CC));
14086 return;
14087 }
14088
14089 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
14090 if (SourceMgr.isInSystemMacro(loc: CC))
14091 return;
14092
14093 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
14094 if (UO->getOpcode() == UO_Minus)
14095 return DiagnoseImpCast(
14096 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
14097 }
14098
14099 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
14100 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
14101 /* pruneControlFlow */ PruneControlFlow: true);
14102 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14103 diag: diag::warn_impcast_integer_precision);
14104 }
14105
14106 if (TargetRange.Width > SourceTypeRange.Width) {
14107 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
14108 if (UO->getOpcode() == UO_Minus)
14109 if (Source->isUnsignedIntegerType()) {
14110 if (Target->isUnsignedIntegerType())
14111 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14112 diag: diag::warn_impcast_high_order_zero_bits);
14113 if (Target->isSignedIntegerType())
14114 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14115 diag: diag::warn_impcast_nonnegative_result);
14116 }
14117 }
14118
14119 if (TargetRange.Width == LikelySourceRange->Width &&
14120 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14121 Source->isSignedIntegerType()) {
14122 // Warn when doing a signed to signed conversion, warn if the positive
14123 // source value is exactly the width of the target type, which will
14124 // cause a negative value to be stored.
14125
14126 Expr::EvalResult Result;
14127 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
14128 !SourceMgr.isInSystemMacro(loc: CC)) {
14129 llvm::APSInt Value = Result.Val.getInt();
14130 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
14131 std::string PrettySourceValue = toString(I: Value, Radix: 10);
14132 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
14133
14134 Diag(Loc: E->getExprLoc(),
14135 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
14136 << PrettySourceValue << PrettyTargetValue << E->getType() << T
14137 << E->getSourceRange() << SourceRange(CC));
14138 return;
14139 }
14140 }
14141
14142 // Fall through for non-constants to give a sign conversion warning.
14143 }
14144
14145 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
14146 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
14147 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14148 LikelySourceRange->Width == TargetRange.Width))) {
14149 if (SourceMgr.isInSystemMacro(loc: CC))
14150 return;
14151
14152 if (SourceBT && SourceBT->isInteger() && TargetBT &&
14153 TargetBT->isInteger() &&
14154 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
14155 return;
14156 }
14157
14158 unsigned DiagID = diag::warn_impcast_integer_sign;
14159
14160 // Traditionally, gcc has warned about this under -Wsign-compare.
14161 // We also want to warn about it in -Wconversion.
14162 // So if -Wconversion is off, use a completely identical diagnostic
14163 // in the sign-compare group.
14164 // The conditional-checking code will
14165 if (ICContext) {
14166 DiagID = diag::warn_impcast_integer_sign_conditional;
14167 *ICContext = true;
14168 }
14169
14170 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
14171 }
14172
14173 // If we're implicitly converting from an integer into an enumeration, that
14174 // is valid in C but invalid in C++.
14175 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
14176 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
14177 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
14178 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
14179
14180 // Diagnose conversions between different enumeration types.
14181 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
14182 // type, to give us better diagnostics.
14183 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
14184
14185 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
14186 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
14187 if (SourceEnum->getDecl()->hasNameForLinkage() &&
14188 TargetEnum->getDecl()->hasNameForLinkage() &&
14189 SourceEnum != TargetEnum) {
14190 if (SourceMgr.isInSystemMacro(loc: CC))
14191 return;
14192
14193 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
14194 diag: diag::warn_impcast_different_enum_types);
14195 }
14196}
14197
14198static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
14199 SourceLocation CC, QualType T);
14200
14201static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
14202 SourceLocation CC, bool &ICContext) {
14203 E = E->IgnoreParenImpCasts();
14204 // Diagnose incomplete type for second or third operand in C.
14205 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
14206 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
14207
14208 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
14209 return CheckConditionalOperator(S, E: CO, CC, T);
14210
14211 AnalyzeImplicitConversions(S, E, CC);
14212 if (E->getType() != T)
14213 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
14214}
14215
14216static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
14217 SourceLocation CC, QualType T) {
14218 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
14219
14220 Expr *TrueExpr = E->getTrueExpr();
14221 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
14222 TrueExpr = BCO->getCommon();
14223
14224 bool Suspicious = false;
14225 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
14226 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
14227
14228 if (T->isBooleanType())
14229 DiagnoseIntInBoolContext(S, E);
14230
14231 // If -Wconversion would have warned about either of the candidates
14232 // for a signedness conversion to the context type...
14233 if (!Suspicious) return;
14234
14235 // ...but it's currently ignored...
14236 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
14237 return;
14238
14239 // ...then check whether it would have warned about either of the
14240 // candidates for a signedness conversion to the condition type.
14241 if (E->getType() == T) return;
14242
14243 Suspicious = false;
14244 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
14245 ICContext: &Suspicious);
14246 if (!Suspicious)
14247 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
14248 T: E->getType(), CC, ICContext: &Suspicious);
14249}
14250
14251/// Check conversion of given expression to boolean.
14252/// Input argument E is a logical expression.
14253static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
14254 // Run the bool-like conversion checks only for C since there bools are
14255 // still not used as the return type from "boolean" operators or as the input
14256 // type for conditional operators.
14257 if (S.getLangOpts().CPlusPlus)
14258 return;
14259 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
14260 return;
14261 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
14262}
14263
14264namespace {
14265struct AnalyzeImplicitConversionsWorkItem {
14266 Expr *E;
14267 SourceLocation CC;
14268 bool IsListInit;
14269};
14270}
14271
14272static void CheckCommaOperand(
14273 Sema &S, Expr *E, QualType T, SourceLocation CC,
14274 bool ExtraCheckForImplicitConversion,
14275 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14276 E = E->IgnoreParenImpCasts();
14277 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
14278
14279 if (ExtraCheckForImplicitConversion && E->getType() != T)
14280 S.CheckImplicitConversion(E, T, CC);
14281}
14282
14283/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14284/// that should be visited are added to WorkList.
14285static void AnalyzeImplicitConversions(
14286 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14287 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14288 Expr *OrigE = Item.E;
14289 SourceLocation CC = Item.CC;
14290
14291 QualType T = OrigE->getType();
14292 Expr *E = OrigE->IgnoreParenImpCasts();
14293
14294 // Propagate whether we are in a C++ list initialization expression.
14295 // If so, we do not issue warnings for implicit int-float conversion
14296 // precision loss, because C++11 narrowing already handles it.
14297 //
14298 // HLSL's initialization lists are special, so they shouldn't observe the C++
14299 // behavior here.
14300 bool IsListInit =
14301 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
14302 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14303
14304 if (E->isTypeDependent() || E->isValueDependent())
14305 return;
14306
14307 Expr *SourceExpr = E;
14308 // Examine, but don't traverse into the source expression of an
14309 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14310 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14311 // evaluate it in the context of checking the specific conversion to T though.
14312 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
14313 if (auto *Src = OVE->getSourceExpr())
14314 SourceExpr = Src;
14315
14316 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
14317 if (UO->getOpcode() == UO_Not &&
14318 UO->getSubExpr()->isKnownToHaveBooleanValue())
14319 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
14320 << OrigE->getSourceRange() << T->isBooleanType()
14321 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
14322
14323 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
14324 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14325 BO->getLHS()->isKnownToHaveBooleanValue() &&
14326 BO->getRHS()->isKnownToHaveBooleanValue() &&
14327 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
14328 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
14329 SourceManager &SM = S.getSourceManager();
14330 const LangOptions &LO = S.getLangOpts();
14331 SourceLocation BLoc = BO->getOperatorLoc();
14332 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
14333 StringRef SR = clang::Lexer::getSourceText(
14334 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
14335 // To reduce false positives, only issue the diagnostic if the operator
14336 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14337 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14338 // in C, along with other macro spellings the user might invent.
14339 if (SR.str() == "&" || SR.str() == "|") {
14340
14341 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
14342 << (BO->getOpcode() == BO_And ? "&" : "|")
14343 << OrigE->getSourceRange()
14344 << FixItHint::CreateReplacement(
14345 RemoveRange: BO->getOperatorLoc(),
14346 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
14347 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
14348 }
14349 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14350 /// Analyze the given comma operator. The basic idea behind the analysis
14351 /// is to analyze the left and right operands slightly differently. The
14352 /// left operand needs to check whether the operand itself has an implicit
14353 /// conversion, but not whether the left operand induces an implicit
14354 /// conversion for the entire comma expression itself. This is similar to
14355 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14356 /// were directly used for the implicit conversion check.
14357 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
14358 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14359 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
14360 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14361 return;
14362 }
14363 }
14364
14365 // For conditional operators, we analyze the arguments as if they
14366 // were being fed directly into the output.
14367 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
14368 CheckConditionalOperator(S, E: CO, CC, T);
14369 return;
14370 }
14371
14372 // Check implicit argument conversions for function calls.
14373 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
14374 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
14375
14376 // Go ahead and check any implicit conversions we might have skipped.
14377 // The non-canonical typecheck is just an optimization;
14378 // CheckImplicitConversion will filter out dead implicit conversions.
14379 if (SourceExpr->getType() != T)
14380 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
14381
14382 // Now continue drilling into this expression.
14383
14384 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
14385 // The bound subexpressions in a PseudoObjectExpr are not reachable
14386 // as transitive children.
14387 // FIXME: Use a more uniform representation for this.
14388 for (auto *SE : POE->semantics())
14389 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
14390 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14391 }
14392
14393 // Skip past explicit casts.
14394 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
14395 E = CE->getSubExpr();
14396 // In the special case of a C++ function-style cast with braces,
14397 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14398 // initializer. This InitListExpr basically belongs to the cast itself, so
14399 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14400 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
14401 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
14402 if (InitListE->getNumInits() == 1) {
14403 E = InitListE->getInit(Init: 0);
14404 }
14405 }
14406 }
14407 E = E->IgnoreParenImpCasts();
14408 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14409 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
14410 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
14411 return;
14412 }
14413
14414 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
14415 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
14416 // The base expression is only used to initialize the parameter for
14417 // arguments to `inout` parameters, so we only traverse down the base
14418 // expression for `inout` cases.
14419 if (OutArgE->isInOut())
14420 WorkList.push_back(
14421 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14422 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
14423 return;
14424 }
14425
14426 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14427 // Do a somewhat different check with comparison operators.
14428 if (BO->isComparisonOp())
14429 return AnalyzeComparison(S, E: BO);
14430
14431 // And with simple assignments.
14432 if (BO->getOpcode() == BO_Assign)
14433 return AnalyzeAssignment(S, E: BO);
14434 // And with compound assignments.
14435 if (BO->isAssignmentOp())
14436 return AnalyzeCompoundAssignment(S, E: BO);
14437 }
14438
14439 // These break the otherwise-useful invariant below. Fortunately,
14440 // we don't really need to recurse into them, because any internal
14441 // expressions should have been analyzed already when they were
14442 // built into statements.
14443 if (isa<StmtExpr>(Val: E)) return;
14444
14445 // Don't descend into unevaluated contexts.
14446 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
14447
14448 // Now just recurse over the expression's children.
14449 CC = E->getExprLoc();
14450 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
14451 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14452 for (Stmt *SubStmt : E->children()) {
14453 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
14454 if (!ChildExpr)
14455 continue;
14456
14457 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
14458 if (ChildExpr == CSE->getOperand())
14459 // Do not recurse over a CoroutineSuspendExpr's operand.
14460 // The operand is also a subexpression of getCommonExpr(), and
14461 // recursing into it directly would produce duplicate diagnostics.
14462 continue;
14463
14464 if (IsLogicalAndOperator &&
14465 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
14466 // Ignore checking string literals that are in logical and operators.
14467 // This is a common pattern for asserts.
14468 continue;
14469 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
14470 }
14471
14472 if (BO && BO->isLogicalOp()) {
14473 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14474 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14475 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14476
14477 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14478 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14479 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14480 }
14481
14482 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
14483 if (U->getOpcode() == UO_LNot) {
14484 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
14485 } else if (U->getOpcode() != UO_AddrOf) {
14486 if (U->getSubExpr()->getType()->isAtomicType())
14487 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
14488 DiagID: diag::warn_atomic_implicit_seq_cst);
14489 }
14490 }
14491}
14492
14493/// AnalyzeImplicitConversions - Find and report any interesting
14494/// implicit conversions in the given expression. There are a couple
14495/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14496static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14497 bool IsListInit/*= false*/) {
14498 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14499 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
14500 while (!WorkList.empty())
14501 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
14502}
14503
14504// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14505// Returns true when emitting a warning about taking the address of a reference.
14506static bool CheckForReference(Sema &SemaRef, const Expr *E,
14507 const PartialDiagnostic &PD) {
14508 E = E->IgnoreParenImpCasts();
14509
14510 const FunctionDecl *FD = nullptr;
14511
14512 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14513 if (!DRE->getDecl()->getType()->isReferenceType())
14514 return false;
14515 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14516 if (!M->getMemberDecl()->getType()->isReferenceType())
14517 return false;
14518 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
14519 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
14520 return false;
14521 FD = Call->getDirectCallee();
14522 } else {
14523 return false;
14524 }
14525
14526 SemaRef.Diag(Loc: E->getExprLoc(), PD);
14527
14528 // If possible, point to location of function.
14529 if (FD) {
14530 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
14531 }
14532
14533 return true;
14534}
14535
14536// Returns true if the SourceLocation is expanded from any macro body.
14537// Returns false if the SourceLocation is invalid, is from not in a macro
14538// expansion, or is from expanded from a top-level macro argument.
14539static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14540 if (Loc.isInvalid())
14541 return false;
14542
14543 while (Loc.isMacroID()) {
14544 if (SM.isMacroBodyExpansion(Loc))
14545 return true;
14546 Loc = SM.getImmediateMacroCallerLoc(Loc);
14547 }
14548
14549 return false;
14550}
14551
14552void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14553 Expr::NullPointerConstantKind NullKind,
14554 bool IsEqual, SourceRange Range) {
14555 if (!E)
14556 return;
14557
14558 // Don't warn inside macros.
14559 if (E->getExprLoc().isMacroID()) {
14560 const SourceManager &SM = getSourceManager();
14561 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
14562 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
14563 return;
14564 }
14565 E = E->IgnoreImpCasts();
14566
14567 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14568
14569 if (isa<CXXThisExpr>(Val: E)) {
14570 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14571 : diag::warn_this_bool_conversion;
14572 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14573 return;
14574 }
14575
14576 bool IsAddressOf = false;
14577
14578 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
14579 if (UO->getOpcode() != UO_AddrOf)
14580 return;
14581 IsAddressOf = true;
14582 E = UO->getSubExpr();
14583 }
14584
14585 if (IsAddressOf) {
14586 unsigned DiagID = IsCompare
14587 ? diag::warn_address_of_reference_null_compare
14588 : diag::warn_address_of_reference_bool_conversion;
14589 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14590 << IsEqual;
14591 if (CheckForReference(SemaRef&: *this, E, PD)) {
14592 return;
14593 }
14594 }
14595
14596 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14597 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
14598 std::string Str;
14599 llvm::raw_string_ostream S(Str);
14600 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14601 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14602 : diag::warn_cast_nonnull_to_bool;
14603 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
14604 << E->getSourceRange() << Range << IsEqual;
14605 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
14606 };
14607
14608 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14609 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
14610 if (auto *Callee = Call->getDirectCallee()) {
14611 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14612 ComplainAboutNonnullParamOrCall(A);
14613 return;
14614 }
14615 }
14616 }
14617
14618 // Complain if we are converting a lambda expression to a boolean value
14619 // outside of instantiation.
14620 if (!inTemplateInstantiation()) {
14621 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
14622 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14623 MRecordDecl && MRecordDecl->isLambda()) {
14624 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
14625 << /*LambdaPointerConversionOperatorType=*/3
14626 << MRecordDecl->getSourceRange() << Range << IsEqual;
14627 return;
14628 }
14629 }
14630 }
14631
14632 // Expect to find a single Decl. Skip anything more complicated.
14633 ValueDecl *D = nullptr;
14634 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
14635 D = R->getDecl();
14636 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14637 D = M->getMemberDecl();
14638 }
14639
14640 // Weak Decls can be null.
14641 if (!D || D->isWeak())
14642 return;
14643
14644 // Check for parameter decl with nonnull attribute
14645 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
14646 if (getCurFunction() &&
14647 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
14648 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14649 ComplainAboutNonnullParamOrCall(A);
14650 return;
14651 }
14652
14653 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
14654 // Skip function template not specialized yet.
14655 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14656 return;
14657 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
14658 assert(ParamIter != FD->param_end());
14659 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
14660
14661 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14662 if (!NonNull->args_size()) {
14663 ComplainAboutNonnullParamOrCall(NonNull);
14664 return;
14665 }
14666
14667 for (const ParamIdx &ArgNo : NonNull->args()) {
14668 if (ArgNo.getASTIndex() == ParamNo) {
14669 ComplainAboutNonnullParamOrCall(NonNull);
14670 return;
14671 }
14672 }
14673 }
14674 }
14675 }
14676 }
14677
14678 QualType T = D->getType();
14679 // A reference to a function is never null either; look through it.
14680 const bool IsFunctionReference =
14681 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14682 if (IsFunctionReference)
14683 T = T->getPointeeType();
14684 const bool IsArray = T->isArrayType();
14685 const bool IsFunction = T->isFunctionType();
14686
14687 // Address of function is used to silence the function warning.
14688 if (IsAddressOf && IsFunction) {
14689 return;
14690 }
14691
14692 // Found nothing.
14693 if (!IsAddressOf && !IsFunction && !IsArray)
14694 return;
14695
14696 // Pretty print the expression for the diagnostic.
14697 std::string Str;
14698 llvm::raw_string_ostream S(Str);
14699 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14700
14701 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14702 : diag::warn_impcast_pointer_to_bool;
14703 enum {
14704 AddressOf,
14705 FunctionPointer,
14706 ArrayPointer
14707 } DiagType;
14708 if (IsAddressOf)
14709 DiagType = AddressOf;
14710 else if (IsFunction)
14711 DiagType = FunctionPointer;
14712 else if (IsArray)
14713 DiagType = ArrayPointer;
14714 else
14715 llvm_unreachable("Could not determine diagnostic.");
14716 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14717 << Range << IsEqual;
14718
14719 // The fix-it notes below only apply to a bare function name, not a reference.
14720 if (!IsFunction || IsFunctionReference)
14721 return;
14722
14723 // Suggest '&' to silence the function warning.
14724 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14725 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14726
14727 // Check to see if '()' fixit should be emitted.
14728 QualType ReturnType;
14729 UnresolvedSet<4> NonTemplateOverloads;
14730 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14731 if (ReturnType.isNull())
14732 return;
14733
14734 if (IsCompare) {
14735 // There are two cases here. If there is null constant, the only suggest
14736 // for a pointer return type. If the null is 0, then suggest if the return
14737 // type is a pointer or an integer type.
14738 if (!ReturnType->isPointerType()) {
14739 if (NullKind == Expr::NPCK_ZeroExpression ||
14740 NullKind == Expr::NPCK_ZeroLiteral) {
14741 if (!ReturnType->isIntegerType())
14742 return;
14743 } else {
14744 return;
14745 }
14746 }
14747 } else { // !IsCompare
14748 // For function to bool, only suggest if the function pointer has bool
14749 // return type.
14750 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14751 return;
14752 }
14753 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14754 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14755}
14756
14757bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14758 SourceLocation CC) {
14759 QualType Source = E->getType();
14760 QualType Target = T;
14761
14762 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14763 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14764 // Overflow behavior type is being stripped - issue warning
14765 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14766 Target->isUnsignedIntegerType()) {
14767 // For unsigned wrap to unsigned conversions, use pedantic version
14768 unsigned DiagId =
14769 InOverflowBehaviorAssignmentContext
14770 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14771 : diag::warn_impcast_overflow_behavior_pedantic;
14772 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14773 } else {
14774 unsigned DiagId = InOverflowBehaviorAssignmentContext
14775 ? diag::warn_impcast_overflow_behavior_assignment
14776 : diag::warn_impcast_overflow_behavior;
14777 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14778 }
14779 }
14780 }
14781
14782 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14783 if (TargetOBT->isWrapKind()) {
14784 return true;
14785 }
14786 }
14787
14788 return false;
14789}
14790
14791void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14792 // Don't diagnose in unevaluated contexts.
14793 if (isUnevaluatedContext())
14794 return;
14795
14796 // Don't diagnose for value- or type-dependent expressions.
14797 if (E->isTypeDependent() || E->isValueDependent())
14798 return;
14799
14800 // Check for array bounds violations in cases where the check isn't triggered
14801 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14802 // ArraySubscriptExpr is on the RHS of a variable initialization.
14803 CheckArrayAccess(E);
14804
14805 // This is not the right CC for (e.g.) a variable initialization.
14806 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14807}
14808
14809void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14810 ::CheckBoolLikeConversion(S&: *this, E, CC);
14811}
14812
14813void Sema::CheckForIntOverflow (const Expr *E) {
14814 // Use a work list to deal with nested struct initializers.
14815 SmallVector<const Expr *, 2> Exprs(1, E);
14816
14817 do {
14818 const Expr *OriginalE = Exprs.pop_back_val();
14819 const Expr *E = OriginalE->IgnoreParenCasts();
14820
14821 if (isa<BinaryOperator>(Val: E) ||
14822 (isa<UnaryOperator>(Val: E) && cast<UnaryOperator>(Val: E)->canOverflow())) {
14823 E->EvaluateForOverflow(Ctx: Context);
14824 continue;
14825 }
14826
14827 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14828 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14829 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14830 E->EvaluateForOverflow(Ctx: Context);
14831 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14832 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14833 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14834 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14835 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14836 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14837 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14838 Exprs.push_back(Elt: Temporary->getSubExpr());
14839 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14840 Exprs.push_back(Elt: Array->getIdx());
14841 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14842 Exprs.push_back(Elt: Compound->getInitializer());
14843 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14844 New && New->isArray()) {
14845 if (auto ArraySize = New->getArraySize())
14846 Exprs.push_back(Elt: *ArraySize);
14847 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14848 Exprs.push_back(Elt: MTE->getSubExpr());
14849 } while (!Exprs.empty());
14850}
14851
14852namespace {
14853
14854/// Visitor for expressions which looks for unsequenced operations on the
14855/// same object.
14856class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14857 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14858
14859 /// A tree of sequenced regions within an expression. Two regions are
14860 /// unsequenced if one is an ancestor or a descendent of the other. When we
14861 /// finish processing an expression with sequencing, such as a comma
14862 /// expression, we fold its tree nodes into its parent, since they are
14863 /// unsequenced with respect to nodes we will visit later.
14864 class SequenceTree {
14865 struct Value {
14866 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14867 unsigned Parent : 31;
14868 LLVM_PREFERRED_TYPE(bool)
14869 unsigned Merged : 1;
14870 };
14871 SmallVector<Value, 8> Values;
14872
14873 public:
14874 /// A region within an expression which may be sequenced with respect
14875 /// to some other region.
14876 class Seq {
14877 friend class SequenceTree;
14878
14879 unsigned Index;
14880
14881 explicit Seq(unsigned N) : Index(N) {}
14882
14883 public:
14884 Seq() : Index(0) {}
14885 };
14886
14887 SequenceTree() { Values.push_back(Elt: Value(0)); }
14888 Seq root() const { return Seq(0); }
14889
14890 /// Create a new sequence of operations, which is an unsequenced
14891 /// subset of \p Parent. This sequence of operations is sequenced with
14892 /// respect to other children of \p Parent.
14893 Seq allocate(Seq Parent) {
14894 Values.push_back(Elt: Value(Parent.Index));
14895 return Seq(Values.size() - 1);
14896 }
14897
14898 /// Merge a sequence of operations into its parent.
14899 void merge(Seq S) {
14900 Values[S.Index].Merged = true;
14901 }
14902
14903 /// Determine whether two operations are unsequenced. This operation
14904 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14905 /// should have been merged into its parent as appropriate.
14906 bool isUnsequenced(Seq Cur, Seq Old) {
14907 unsigned C = representative(K: Cur.Index);
14908 unsigned Target = representative(K: Old.Index);
14909 while (C >= Target) {
14910 if (C == Target)
14911 return true;
14912 C = Values[C].Parent;
14913 }
14914 return false;
14915 }
14916
14917 private:
14918 /// Pick a representative for a sequence.
14919 unsigned representative(unsigned K) {
14920 if (Values[K].Merged)
14921 // Perform path compression as we go.
14922 return Values[K].Parent = representative(K: Values[K].Parent);
14923 return K;
14924 }
14925 };
14926
14927 /// An object for which we can track unsequenced uses.
14928 using Object = const ValueDecl *;
14929
14930 /// Different flavors of object usage which we track. We only track the
14931 /// least-sequenced usage of each kind.
14932 enum UsageKind {
14933 /// A read of an object. Multiple unsequenced reads are OK.
14934 UK_Use,
14935
14936 /// A modification of an object which is sequenced before the value
14937 /// computation of the expression, such as ++n in C++.
14938 UK_ModAsValue,
14939
14940 /// A modification of an object which is not sequenced before the value
14941 /// computation of the expression, such as n++.
14942 UK_ModAsSideEffect,
14943
14944 UK_Count = UK_ModAsSideEffect + 1
14945 };
14946
14947 enum WarningKind {
14948 /// A warning message is one for unsequenced use and modification
14949 WK_UseAndMod,
14950
14951 /// A warning message is one for multiple unsequenced modification
14952 WK_ModAndMod,
14953
14954 /// A warning message is one for multiple unsequenced volatile use
14955 WK_Volatile_UseAndUse
14956 };
14957
14958 /// Bundle together a sequencing region and the expression corresponding
14959 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14960 struct Usage {
14961 const Expr *UsageExpr = nullptr;
14962 SequenceTree::Seq Seq;
14963
14964 Usage() = default;
14965 };
14966
14967 struct UsageInfo {
14968 Usage Uses[UK_Count];
14969
14970 /// Have we issued a diagnostic for this object already?
14971 bool Diagnosed = false;
14972
14973 UsageInfo();
14974 };
14975 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14976
14977 Sema &SemaRef;
14978
14979 /// Sequenced regions within the expression.
14980 SequenceTree Tree;
14981
14982 /// Declaration modifications and references which we have seen.
14983 UsageInfoMap UsageMap;
14984
14985 /// The region we are currently within.
14986 SequenceTree::Seq Region;
14987
14988 /// Filled in with declarations which were modified as a side-effect
14989 /// (that is, post-increment operations).
14990 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14991
14992 /// Expressions to check later. We defer checking these to reduce
14993 /// stack usage.
14994 SmallVectorImpl<const Expr *> &WorkList;
14995
14996 /// RAII object wrapping the visitation of a sequenced subexpression of an
14997 /// expression. At the end of this process, the side-effects of the evaluation
14998 /// become sequenced with respect to the value computation of the result, so
14999 /// we downgrade any UK_ModAsSideEffect within the evaluation to
15000 /// UK_ModAsValue.
15001 struct SequencedSubexpression {
15002 SequencedSubexpression(SequenceChecker &Self)
15003 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
15004 Self.ModAsSideEffect = &ModAsSideEffect;
15005 }
15006
15007 ~SequencedSubexpression() {
15008 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
15009 // Add a new usage with usage kind UK_ModAsValue, and then restore
15010 // the previous usage with UK_ModAsSideEffect (thus clearing it if
15011 // the previous one was empty).
15012 UsageInfo &UI = Self.UsageMap[M.first];
15013 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
15014 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
15015 SideEffectUsage = M.second;
15016 }
15017 Self.ModAsSideEffect = OldModAsSideEffect;
15018 }
15019
15020 SequenceChecker &Self;
15021 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
15022 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
15023 };
15024
15025 /// RAII object wrapping the visitation of a subexpression which we might
15026 /// choose to evaluate as a constant. If any subexpression is evaluated and
15027 /// found to be non-constant, this allows us to suppress the evaluation of
15028 /// the outer expression.
15029 class EvaluationTracker {
15030 public:
15031 EvaluationTracker(SequenceChecker &Self)
15032 : Self(Self), Prev(Self.EvalTracker) {
15033 Self.EvalTracker = this;
15034 }
15035
15036 ~EvaluationTracker() {
15037 Self.EvalTracker = Prev;
15038 if (Prev)
15039 Prev->EvalOK &= EvalOK;
15040 }
15041
15042 bool evaluate(const Expr *E, bool &Result) {
15043 if (!EvalOK || E->isValueDependent())
15044 return false;
15045 EvalOK = E->EvaluateAsBooleanCondition(
15046 Result, Ctx: Self.SemaRef.Context,
15047 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
15048 return EvalOK;
15049 }
15050
15051 private:
15052 SequenceChecker &Self;
15053 EvaluationTracker *Prev;
15054 bool EvalOK = true;
15055 } *EvalTracker = nullptr;
15056
15057 /// Find the object which is produced by the specified expression,
15058 /// if any.
15059 Object getObject(const Expr *E, bool Mod) const {
15060 E = E->IgnoreParenCasts();
15061 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
15062 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
15063 return getObject(E: UO->getSubExpr(), Mod);
15064 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
15065 if (BO->getOpcode() == BO_Comma)
15066 return getObject(E: BO->getRHS(), Mod);
15067 if (Mod && BO->isAssignmentOp())
15068 return getObject(E: BO->getLHS(), Mod);
15069 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
15070 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
15071 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
15072 return ME->getMemberDecl();
15073 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
15074 // FIXME: If this is a reference, map through to its value.
15075 return DRE->getDecl();
15076 return nullptr;
15077 }
15078
15079 /// Note that an object \p O was modified or used by an expression
15080 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
15081 /// the object \p O as obtained via the \p UsageMap.
15082 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
15083 // Get the old usage for the given object and usage kind.
15084 Usage &U = UI.Uses[UK];
15085 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
15086 // If we have a modification as side effect and are in a sequenced
15087 // subexpression, save the old Usage so that we can restore it later
15088 // in SequencedSubexpression::~SequencedSubexpression.
15089 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
15090 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
15091 // Then record the new usage with the current sequencing region.
15092 U.UsageExpr = UsageExpr;
15093 U.Seq = Region;
15094 }
15095 }
15096
15097 /// Check whether a modification or use of an object \p O in an expression
15098 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
15099 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
15100 /// The message displayed in case of a conflict depends on \p WarnKind.
15101 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
15102 UsageKind OtherKind, WarningKind WarnKind) {
15103 if (UI.Diagnosed)
15104 return;
15105
15106 const Usage &U = UI.Uses[OtherKind];
15107 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
15108 return;
15109
15110 const Expr *Mod = U.UsageExpr;
15111 const Expr *ModOrUse = UsageExpr;
15112 if (OtherKind == UK_Use)
15113 std::swap(a&: Mod, b&: ModOrUse);
15114
15115 unsigned DiagID = 0;
15116 switch (WarnKind) {
15117 case WK_UseAndMod:
15118 DiagID = diag::warn_unsequenced_mod_use;
15119 break;
15120 case WK_ModAndMod:
15121 DiagID = diag::warn_unsequenced_mod_mod;
15122 break;
15123 case WK_Volatile_UseAndUse:
15124 DiagID = diag::warn_unsequenced_use_use_volatile;
15125 break;
15126 }
15127
15128 SemaRef.DiagRuntimeBehavior(
15129 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
15130 PD: SemaRef.PDiag(DiagID) << O << SourceRange(ModOrUse->getExprLoc()));
15131 UI.Diagnosed = true;
15132 }
15133
15134 // A note on note{Pre, Post}{Use, Mod}:
15135 //
15136 // (It helps to follow the algorithm with an expression such as
15137 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
15138 // operations before C++17 and both are well-defined in C++17).
15139 //
15140 // When visiting a node which uses/modify an object we first call notePreUse
15141 // or notePreMod before visiting its sub-expression(s). At this point the
15142 // children of the current node have not yet been visited and so the eventual
15143 // uses/modifications resulting from the children of the current node have not
15144 // been recorded yet.
15145 //
15146 // We then visit the children of the current node. After that notePostUse or
15147 // notePostMod is called. These will 1) detect an unsequenced modification
15148 // as side effect (as in "k++ + k") and 2) add a new usage with the
15149 // appropriate usage kind.
15150 //
15151 // We also have to be careful that some operation sequences modification as
15152 // side effect as well (for example: || or ,). To account for this we wrap
15153 // the visitation of such a sub-expression (for example: the LHS of || or ,)
15154 // with SequencedSubexpression. SequencedSubexpression is an RAII object
15155 // which record usages which are modifications as side effect, and then
15156 // downgrade them (or more accurately restore the previous usage which was a
15157 // modification as side effect) when exiting the scope of the sequenced
15158 // subexpression.
15159
15160 void notePreUse(Object O, const Expr *UseExpr) {
15161 UsageInfo &UI = UsageMap[O];
15162 // Uses conflict with other modifications.
15163 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, WarnKind: WK_UseAndMod);
15164 // Volatile uses conflict with other uses.
15165 if (O->getType().isVolatileQualified())
15166 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_Use, WarnKind: WK_Volatile_UseAndUse);
15167 }
15168
15169 void notePostUse(Object O, const Expr *UseExpr) {
15170 UsageInfo &UI = UsageMap[O];
15171 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect, WarnKind: WK_UseAndMod);
15172 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
15173 }
15174
15175 void notePreMod(Object O, const Expr *ModExpr) {
15176 UsageInfo &UI = UsageMap[O];
15177 // Modifications conflict with other modifications and with uses.
15178 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, WarnKind: WK_ModAndMod);
15179 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, WarnKind: WK_UseAndMod);
15180 }
15181
15182 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
15183 UsageInfo &UI = UsageMap[O];
15184 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect, WarnKind: WK_ModAndMod);
15185 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
15186 }
15187
15188public:
15189 SequenceChecker(Sema &S, const Expr *E,
15190 SmallVectorImpl<const Expr *> &WorkList)
15191 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
15192 Visit(S: E);
15193 // Silence a -Wunused-private-field since WorkList is now unused.
15194 // TODO: Evaluate if it can be used, and if not remove it.
15195 (void)this->WorkList;
15196 }
15197
15198 void VisitStmt(const Stmt *S) {
15199 // Skip all statements which aren't expressions for now.
15200 }
15201
15202 void VisitExpr(const Expr *E) {
15203 // By default, just recurse to evaluated subexpressions.
15204 Base::VisitStmt(S: E);
15205 }
15206
15207 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
15208 for (auto *Sub : CSE->children()) {
15209 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
15210 if (!ChildExpr)
15211 continue;
15212
15213 if (ChildExpr == CSE->getOperand())
15214 // Do not recurse over a CoroutineSuspendExpr's operand.
15215 // The operand is also a subexpression of getCommonExpr(), and
15216 // recursing into it directly could confuse object management
15217 // for the sake of sequence tracking.
15218 continue;
15219
15220 Visit(S: Sub);
15221 }
15222 }
15223
15224 void VisitCastExpr(const CastExpr *E) {
15225 Object O = Object();
15226 if (E->getCastKind() == CK_LValueToRValue)
15227 O = getObject(E: E->getSubExpr(), Mod: false);
15228
15229 if (O)
15230 notePreUse(O, UseExpr: E);
15231 VisitExpr(E);
15232 if (O)
15233 notePostUse(O, UseExpr: E);
15234 }
15235
15236 void VisitSequencedExpressions(const Expr *SequencedBefore,
15237 const Expr *SequencedAfter) {
15238 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
15239 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
15240 SequenceTree::Seq OldRegion = Region;
15241
15242 {
15243 SequencedSubexpression SeqBefore(*this);
15244 Region = BeforeRegion;
15245 Visit(S: SequencedBefore);
15246 }
15247
15248 Region = AfterRegion;
15249 Visit(S: SequencedAfter);
15250
15251 Region = OldRegion;
15252
15253 Tree.merge(S: BeforeRegion);
15254 Tree.merge(S: AfterRegion);
15255 }
15256
15257 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15258 // C++17 [expr.sub]p1:
15259 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15260 // expression E1 is sequenced before the expression E2.
15261 if (SemaRef.getLangOpts().CPlusPlus17)
15262 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
15263 else {
15264 Visit(S: ASE->getLHS());
15265 Visit(S: ASE->getRHS());
15266 }
15267 }
15268
15269 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15270 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15271 void VisitBinPtrMem(const BinaryOperator *BO) {
15272 // C++17 [expr.mptr.oper]p4:
15273 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15274 // the expression E1 is sequenced before the expression E2.
15275 if (SemaRef.getLangOpts().CPlusPlus17)
15276 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15277 else {
15278 Visit(S: BO->getLHS());
15279 Visit(S: BO->getRHS());
15280 }
15281 }
15282
15283 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15284 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15285 void VisitBinShlShr(const BinaryOperator *BO) {
15286 // C++17 [expr.shift]p4:
15287 // The expression E1 is sequenced before the expression E2.
15288 if (SemaRef.getLangOpts().CPlusPlus17)
15289 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15290 else {
15291 Visit(S: BO->getLHS());
15292 Visit(S: BO->getRHS());
15293 }
15294 }
15295
15296 void VisitBinComma(const BinaryOperator *BO) {
15297 // C++11 [expr.comma]p1:
15298 // Every value computation and side effect associated with the left
15299 // expression is sequenced before every value computation and side
15300 // effect associated with the right expression.
15301 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15302 }
15303
15304 void VisitBinAssign(const BinaryOperator *BO) {
15305 SequenceTree::Seq RHSRegion;
15306 SequenceTree::Seq LHSRegion;
15307 if (SemaRef.getLangOpts().CPlusPlus17) {
15308 RHSRegion = Tree.allocate(Parent: Region);
15309 LHSRegion = Tree.allocate(Parent: Region);
15310 } else {
15311 RHSRegion = Region;
15312 LHSRegion = Region;
15313 }
15314 SequenceTree::Seq OldRegion = Region;
15315
15316 // C++11 [expr.ass]p1:
15317 // [...] the assignment is sequenced after the value computation
15318 // of the right and left operands, [...]
15319 //
15320 // so check it before inspecting the operands and update the
15321 // map afterwards.
15322 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
15323 if (O)
15324 notePreMod(O, ModExpr: BO);
15325
15326 if (SemaRef.getLangOpts().CPlusPlus17) {
15327 // C++17 [expr.ass]p1:
15328 // [...] The right operand is sequenced before the left operand. [...]
15329 {
15330 SequencedSubexpression SeqBefore(*this);
15331 Region = RHSRegion;
15332 Visit(S: BO->getRHS());
15333 }
15334
15335 Region = LHSRegion;
15336 Visit(S: BO->getLHS());
15337
15338 if (O && isa<CompoundAssignOperator>(Val: BO))
15339 notePostUse(O, UseExpr: BO);
15340
15341 } else {
15342 // C++11 does not specify any sequencing between the LHS and RHS.
15343 Region = LHSRegion;
15344 Visit(S: BO->getLHS());
15345
15346 if (O && isa<CompoundAssignOperator>(Val: BO))
15347 notePostUse(O, UseExpr: BO);
15348
15349 Region = RHSRegion;
15350 Visit(S: BO->getRHS());
15351 }
15352
15353 // C++11 [expr.ass]p1:
15354 // the assignment is sequenced [...] before the value computation of the
15355 // assignment expression.
15356 // C11 6.5.16/3 has no such rule.
15357 Region = OldRegion;
15358 if (O)
15359 notePostMod(O, ModExpr: BO,
15360 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15361 : UK_ModAsSideEffect);
15362 if (SemaRef.getLangOpts().CPlusPlus17) {
15363 Tree.merge(S: RHSRegion);
15364 Tree.merge(S: LHSRegion);
15365 }
15366 }
15367
15368 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15369 VisitBinAssign(BO: CAO);
15370 }
15371
15372 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15373 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15374 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15375 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15376 if (!O)
15377 return VisitExpr(E: UO);
15378
15379 notePreMod(O, ModExpr: UO);
15380 Visit(S: UO->getSubExpr());
15381 // C++11 [expr.pre.incr]p1:
15382 // the expression ++x is equivalent to x+=1
15383 notePostMod(O, ModExpr: UO,
15384 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15385 : UK_ModAsSideEffect);
15386 }
15387
15388 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15389 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15390 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15391 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15392 if (!O)
15393 return VisitExpr(E: UO);
15394
15395 notePreMod(O, ModExpr: UO);
15396 Visit(S: UO->getSubExpr());
15397 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
15398 }
15399
15400 void VisitBinLOr(const BinaryOperator *BO) {
15401 // C++11 [expr.log.or]p2:
15402 // If the second expression is evaluated, every value computation and
15403 // side effect associated with the first expression is sequenced before
15404 // every value computation and side effect associated with the
15405 // second expression.
15406 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15407 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15408 SequenceTree::Seq OldRegion = Region;
15409
15410 EvaluationTracker Eval(*this);
15411 {
15412 SequencedSubexpression Sequenced(*this);
15413 Region = LHSRegion;
15414 Visit(S: BO->getLHS());
15415 }
15416
15417 // C++11 [expr.log.or]p1:
15418 // [...] the second operand is not evaluated if the first operand
15419 // evaluates to true.
15420 bool EvalResult = false;
15421 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15422 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15423 if (ShouldVisitRHS) {
15424 Region = RHSRegion;
15425 Visit(S: BO->getRHS());
15426 }
15427
15428 Region = OldRegion;
15429 Tree.merge(S: LHSRegion);
15430 Tree.merge(S: RHSRegion);
15431 }
15432
15433 void VisitBinLAnd(const BinaryOperator *BO) {
15434 // C++11 [expr.log.and]p2:
15435 // If the second expression is evaluated, every value computation and
15436 // side effect associated with the first expression is sequenced before
15437 // every value computation and side effect associated with the
15438 // second expression.
15439 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15440 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15441 SequenceTree::Seq OldRegion = Region;
15442
15443 EvaluationTracker Eval(*this);
15444 {
15445 SequencedSubexpression Sequenced(*this);
15446 Region = LHSRegion;
15447 Visit(S: BO->getLHS());
15448 }
15449
15450 // C++11 [expr.log.and]p1:
15451 // [...] the second operand is not evaluated if the first operand is false.
15452 bool EvalResult = false;
15453 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15454 bool ShouldVisitRHS = !EvalOK || EvalResult;
15455 if (ShouldVisitRHS) {
15456 Region = RHSRegion;
15457 Visit(S: BO->getRHS());
15458 }
15459
15460 Region = OldRegion;
15461 Tree.merge(S: LHSRegion);
15462 Tree.merge(S: RHSRegion);
15463 }
15464
15465 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15466 // C++11 [expr.cond]p1:
15467 // [...] Every value computation and side effect associated with the first
15468 // expression is sequenced before every value computation and side effect
15469 // associated with the second or third expression.
15470 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
15471
15472 // No sequencing is specified between the true and false expression.
15473 // However since exactly one of both is going to be evaluated we can
15474 // consider them to be sequenced. This is needed to avoid warning on
15475 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15476 // both the true and false expressions because we can't evaluate x.
15477 // This will still allow us to detect an expression like (pre C++17)
15478 // "(x ? y += 1 : y += 2) = y".
15479 //
15480 // We don't wrap the visitation of the true and false expression with
15481 // SequencedSubexpression because we don't want to downgrade modifications
15482 // as side effect in the true and false expressions after the visition
15483 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15484 // not warn between the two "y++", but we should warn between the "y++"
15485 // and the "y".
15486 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
15487 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
15488 SequenceTree::Seq OldRegion = Region;
15489
15490 EvaluationTracker Eval(*this);
15491 {
15492 SequencedSubexpression Sequenced(*this);
15493 Region = ConditionRegion;
15494 Visit(S: CO->getCond());
15495 }
15496
15497 // C++11 [expr.cond]p1:
15498 // [...] The first expression is contextually converted to bool (Clause 4).
15499 // It is evaluated and if it is true, the result of the conditional
15500 // expression is the value of the second expression, otherwise that of the
15501 // third expression. Only one of the second and third expressions is
15502 // evaluated. [...]
15503 bool EvalResult = false;
15504 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
15505 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15506 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15507 if (ShouldVisitTrueExpr) {
15508 Region = TrueRegion;
15509 Visit(S: CO->getTrueExpr());
15510 }
15511 if (ShouldVisitFalseExpr) {
15512 Region = FalseRegion;
15513 Visit(S: CO->getFalseExpr());
15514 }
15515
15516 Region = OldRegion;
15517 Tree.merge(S: ConditionRegion);
15518 Tree.merge(S: TrueRegion);
15519 Tree.merge(S: FalseRegion);
15520 }
15521
15522 void VisitCallExpr(const CallExpr *CE) {
15523 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15524
15525 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
15526 return;
15527
15528 // C++11 [intro.execution]p15:
15529 // When calling a function [...], every value computation and side effect
15530 // associated with any argument expression, or with the postfix expression
15531 // designating the called function, is sequenced before execution of every
15532 // expression or statement in the body of the function [and thus before
15533 // the value computation of its result].
15534 SequencedSubexpression Sequenced(*this);
15535 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
15536 // C++17 [expr.call]p5
15537 // The postfix-expression is sequenced before each expression in the
15538 // expression-list and any default argument. [...]
15539 SequenceTree::Seq CalleeRegion;
15540 SequenceTree::Seq OtherRegion;
15541 if (SemaRef.getLangOpts().CPlusPlus17) {
15542 CalleeRegion = Tree.allocate(Parent: Region);
15543 OtherRegion = Tree.allocate(Parent: Region);
15544 } else {
15545 CalleeRegion = Region;
15546 OtherRegion = Region;
15547 }
15548 SequenceTree::Seq OldRegion = Region;
15549
15550 // Visit the callee expression first.
15551 Region = CalleeRegion;
15552 if (SemaRef.getLangOpts().CPlusPlus17) {
15553 SequencedSubexpression Sequenced(*this);
15554 Visit(S: CE->getCallee());
15555 } else {
15556 Visit(S: CE->getCallee());
15557 }
15558
15559 // Then visit the argument expressions.
15560 Region = OtherRegion;
15561 for (const Expr *Argument : CE->arguments())
15562 Visit(S: Argument);
15563
15564 Region = OldRegion;
15565 if (SemaRef.getLangOpts().CPlusPlus17) {
15566 Tree.merge(S: CalleeRegion);
15567 Tree.merge(S: OtherRegion);
15568 }
15569 });
15570 }
15571
15572 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15573 // C++17 [over.match.oper]p2:
15574 // [...] the operator notation is first transformed to the equivalent
15575 // function-call notation as summarized in Table 12 (where @ denotes one
15576 // of the operators covered in the specified subclause). However, the
15577 // operands are sequenced in the order prescribed for the built-in
15578 // operator (Clause 8).
15579 //
15580 // From the above only overloaded binary operators and overloaded call
15581 // operators have sequencing rules in C++17 that we need to handle
15582 // separately.
15583 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15584 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15585 return VisitCallExpr(CE: CXXOCE);
15586
15587 enum {
15588 NoSequencing,
15589 LHSBeforeRHS,
15590 RHSBeforeLHS,
15591 LHSBeforeRest
15592 } SequencingKind;
15593 switch (CXXOCE->getOperator()) {
15594 case OO_Equal:
15595 case OO_PlusEqual:
15596 case OO_MinusEqual:
15597 case OO_StarEqual:
15598 case OO_SlashEqual:
15599 case OO_PercentEqual:
15600 case OO_CaretEqual:
15601 case OO_AmpEqual:
15602 case OO_PipeEqual:
15603 case OO_LessLessEqual:
15604 case OO_GreaterGreaterEqual:
15605 SequencingKind = RHSBeforeLHS;
15606 break;
15607
15608 case OO_LessLess:
15609 case OO_GreaterGreater:
15610 case OO_AmpAmp:
15611 case OO_PipePipe:
15612 case OO_Comma:
15613 case OO_ArrowStar:
15614 case OO_Subscript:
15615 SequencingKind = LHSBeforeRHS;
15616 break;
15617
15618 case OO_Call:
15619 SequencingKind = LHSBeforeRest;
15620 break;
15621
15622 default:
15623 SequencingKind = NoSequencing;
15624 break;
15625 }
15626
15627 if (SequencingKind == NoSequencing)
15628 return VisitCallExpr(CE: CXXOCE);
15629
15630 // This is a call, so all subexpressions are sequenced before the result.
15631 SequencedSubexpression Sequenced(*this);
15632
15633 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
15634 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15635 "Should only get there with C++17 and above!");
15636 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15637 "Should only get there with an overloaded binary operator"
15638 " or an overloaded call operator!");
15639
15640 if (SequencingKind == LHSBeforeRest) {
15641 assert(CXXOCE->getOperator() == OO_Call &&
15642 "We should only have an overloaded call operator here!");
15643
15644 // This is very similar to VisitCallExpr, except that we only have the
15645 // C++17 case. The postfix-expression is the first argument of the
15646 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15647 // are in the following arguments.
15648 //
15649 // Note that we intentionally do not visit the callee expression since
15650 // it is just a decayed reference to a function.
15651 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
15652 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
15653 SequenceTree::Seq OldRegion = Region;
15654
15655 assert(CXXOCE->getNumArgs() >= 1 &&
15656 "An overloaded call operator must have at least one argument"
15657 " for the postfix-expression!");
15658 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15659 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15660 CXXOCE->getNumArgs() - 1);
15661
15662 // Visit the postfix-expression first.
15663 {
15664 Region = PostfixExprRegion;
15665 SequencedSubexpression Sequenced(*this);
15666 Visit(S: PostfixExpr);
15667 }
15668
15669 // Then visit the argument expressions.
15670 Region = ArgsRegion;
15671 for (const Expr *Arg : Args)
15672 Visit(S: Arg);
15673
15674 Region = OldRegion;
15675 Tree.merge(S: PostfixExprRegion);
15676 Tree.merge(S: ArgsRegion);
15677 } else {
15678 assert(CXXOCE->getNumArgs() == 2 &&
15679 "Should only have two arguments here!");
15680 assert((SequencingKind == LHSBeforeRHS ||
15681 SequencingKind == RHSBeforeLHS) &&
15682 "Unexpected sequencing kind!");
15683
15684 // We do not visit the callee expression since it is just a decayed
15685 // reference to a function.
15686 const Expr *E1 = CXXOCE->getArg(Arg: 0);
15687 const Expr *E2 = CXXOCE->getArg(Arg: 1);
15688 if (SequencingKind == RHSBeforeLHS)
15689 std::swap(a&: E1, b&: E2);
15690
15691 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
15692 }
15693 });
15694 }
15695
15696 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15697 // This is a call, so all subexpressions are sequenced before the result.
15698 SequencedSubexpression Sequenced(*this);
15699
15700 if (!CCE->isListInitialization())
15701 return VisitExpr(E: CCE);
15702
15703 // In C++11, list initializations are sequenced.
15704 SequenceExpressionsInOrder(
15705 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15706 }
15707
15708 void VisitInitListExpr(const InitListExpr *ILE) {
15709 if (!SemaRef.getLangOpts().CPlusPlus11)
15710 return VisitExpr(E: ILE);
15711
15712 // In C++11, list initializations are sequenced.
15713 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
15714 }
15715
15716 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15717 // C++20 parenthesized list initializations are sequenced. See C++20
15718 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15719 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
15720 }
15721
15722private:
15723 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15724 SmallVector<SequenceTree::Seq, 32> Elts;
15725 SequenceTree::Seq Parent = Region;
15726 for (const Expr *E : ExpressionList) {
15727 if (!E)
15728 continue;
15729 Region = Tree.allocate(Parent);
15730 Elts.push_back(Elt: Region);
15731 Visit(S: E);
15732 }
15733
15734 // Forget that the initializers are sequenced.
15735 Region = Parent;
15736 for (unsigned I = 0; I < Elts.size(); ++I)
15737 Tree.merge(S: Elts[I]);
15738 }
15739};
15740
15741SequenceChecker::UsageInfo::UsageInfo() = default;
15742
15743} // namespace
15744
15745void Sema::CheckUnsequencedOperations(const Expr *E) {
15746 SmallVector<const Expr *, 8> WorkList;
15747 WorkList.push_back(Elt: E);
15748 while (!WorkList.empty()) {
15749 const Expr *Item = WorkList.pop_back_val();
15750 SequenceChecker(*this, Item, WorkList);
15751 }
15752}
15753
15754void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15755 bool IsConstexpr) {
15756 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15757 IsConstexpr || isa<ConstantExpr>(Val: E));
15758 CheckImplicitConversions(E, CC: CheckLoc);
15759 if (!E->isInstantiationDependent())
15760 CheckUnsequencedOperations(E);
15761 if (!IsConstexpr && !E->isValueDependent() && !isa<ConstantExpr>(Val: E))
15762 CheckForIntOverflow(E);
15763}
15764
15765void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15766 FieldDecl *BitField,
15767 Expr *Init) {
15768 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15769}
15770
15771static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15772 SourceLocation Loc) {
15773 if (!PType->isVariablyModifiedType())
15774 return;
15775 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15776 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15777 return;
15778 }
15779 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15780 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15781 return;
15782 }
15783 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15784 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15785 return;
15786 }
15787
15788 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15789 if (!AT)
15790 return;
15791
15792 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15793 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15794 return;
15795 }
15796
15797 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15798}
15799
15800bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15801 bool CheckParameterNames) {
15802 bool HasInvalidParm = false;
15803 for (ParmVarDecl *Param : Parameters) {
15804 assert(Param && "null in a parameter list");
15805 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15806 // function declarator that is part of a function definition of
15807 // that function shall not have incomplete type.
15808 //
15809 // C++23 [dcl.fct.def.general]/p2
15810 // The type of a parameter [...] for a function definition
15811 // shall not be a (possibly cv-qualified) class type that is incomplete
15812 // or abstract within the function body unless the function is deleted.
15813 if (!Param->isInvalidDecl() &&
15814 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15815 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15816 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15817 DiagID: diag::err_abstract_type_in_decl,
15818 Args: AbstractParamType))) {
15819 Param->setInvalidDecl();
15820 HasInvalidParm = true;
15821 }
15822
15823 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15824 // declaration of each parameter shall include an identifier.
15825 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15826 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15827 // Diagnose this as an extension in C17 and earlier.
15828 if (!getLangOpts().C23)
15829 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15830 }
15831
15832 // C99 6.7.5.3p12:
15833 // If the function declarator is not part of a definition of that
15834 // function, parameters may have incomplete type and may use the [*]
15835 // notation in their sequences of declarator specifiers to specify
15836 // variable length array types.
15837 QualType PType = Param->getOriginalType();
15838 // FIXME: This diagnostic should point the '[*]' if source-location
15839 // information is added for it.
15840 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15841
15842 // If the parameter is a c++ class type and it has to be destructed in the
15843 // callee function, declare the destructor so that it can be called by the
15844 // callee function. Do not perform any direct access check on the dtor here.
15845 if (!Param->isInvalidDecl()) {
15846 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15847 if (!ClassDecl->isInvalidDecl() &&
15848 !ClassDecl->hasIrrelevantDestructor() &&
15849 !ClassDecl->isDependentContext() &&
15850 ClassDecl->isParamDestroyedInCallee()) {
15851 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15852 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15853 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15854 }
15855 }
15856 }
15857
15858 // Parameters with the pass_object_size attribute only need to be marked
15859 // constant at function definitions. Because we lack information about
15860 // whether we're on a declaration or definition when we're instantiating the
15861 // attribute, we need to check for constness here.
15862 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15863 if (!Param->getType().isConstQualified())
15864 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15865 << Attr->getSpelling() << 1;
15866
15867 // Check for parameter names shadowing fields from the class.
15868 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15869 // The owning context for the parameter should be the function, but we
15870 // want to see if this function's declaration context is a record.
15871 DeclContext *DC = Param->getDeclContext();
15872 if (DC && DC->isFunctionOrMethod()) {
15873 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15874 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15875 RD, /*DeclIsField*/ false);
15876 }
15877 }
15878
15879 if (!Param->isInvalidDecl() &&
15880 Param->getOriginalType()->isWebAssemblyTableType()) {
15881 Param->setInvalidDecl();
15882 HasInvalidParm = true;
15883 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15884 }
15885 }
15886
15887 return HasInvalidParm;
15888}
15889
15890std::optional<std::pair<
15891 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15892 *E,
15893 ASTContext
15894 &Ctx);
15895
15896/// Compute the alignment and offset of the base class object given the
15897/// derived-to-base cast expression and the alignment and offset of the derived
15898/// class object.
15899static std::pair<CharUnits, CharUnits>
15900getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15901 CharUnits BaseAlignment, CharUnits Offset,
15902 ASTContext &Ctx) {
15903 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15904 ++PathI) {
15905 const CXXBaseSpecifier *Base = *PathI;
15906 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15907 if (Base->isVirtual()) {
15908 // The complete object may have a lower alignment than the non-virtual
15909 // alignment of the base, in which case the base may be misaligned. Choose
15910 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15911 // conservative lower bound of the complete object alignment.
15912 CharUnits NonVirtualAlignment =
15913 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15914 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15915 Offset = CharUnits::Zero();
15916 } else {
15917 const ASTRecordLayout &RL =
15918 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15919 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15920 }
15921 DerivedType = Base->getType();
15922 }
15923
15924 return std::make_pair(x&: BaseAlignment, y&: Offset);
15925}
15926
15927/// Compute the alignment and offset of a binary additive operator.
15928static std::optional<std::pair<CharUnits, CharUnits>>
15929getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15930 bool IsSub, ASTContext &Ctx) {
15931 QualType PointeeType = PtrE->getType()->getPointeeType();
15932
15933 if (!PointeeType->isConstantSizeType())
15934 return std::nullopt;
15935
15936 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15937
15938 if (!P)
15939 return std::nullopt;
15940
15941 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15942 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15943 CharUnits Offset = EltSize * IdxRes->getExtValue();
15944 if (IsSub)
15945 Offset = -Offset;
15946 return std::make_pair(x&: P->first, y: P->second + Offset);
15947 }
15948
15949 // If the integer expression isn't a constant expression, compute the lower
15950 // bound of the alignment using the alignment and offset of the pointer
15951 // expression and the element size.
15952 return std::make_pair(
15953 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15954 y: CharUnits::Zero());
15955}
15956
15957/// This helper function takes an lvalue expression and returns the alignment of
15958/// a VarDecl and a constant offset from the VarDecl.
15959std::optional<std::pair<
15960 CharUnits,
15961 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15962 ASTContext &Ctx) {
15963 E = E->IgnoreParens();
15964 switch (E->getStmtClass()) {
15965 default:
15966 break;
15967 case Stmt::CStyleCastExprClass:
15968 case Stmt::CXXStaticCastExprClass:
15969 case Stmt::ImplicitCastExprClass: {
15970 auto *CE = cast<CastExpr>(Val: E);
15971 const Expr *From = CE->getSubExpr();
15972 switch (CE->getCastKind()) {
15973 default:
15974 break;
15975 case CK_NoOp:
15976 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15977 case CK_UncheckedDerivedToBase:
15978 case CK_DerivedToBase: {
15979 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15980 if (!P)
15981 break;
15982 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15983 Offset: P->second, Ctx);
15984 }
15985 }
15986 break;
15987 }
15988 case Stmt::ArraySubscriptExprClass: {
15989 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15990 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15991 IsSub: false, Ctx);
15992 }
15993 case Stmt::DeclRefExprClass: {
15994 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15995 // FIXME: If VD is captured by copy or is an escaping __block variable,
15996 // use the alignment of VD's type.
15997 if (!VD->getType()->isReferenceType()) {
15998 // Dependent alignment cannot be resolved -> bail out.
15999 if (VD->hasDependentAlignment())
16000 break;
16001 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
16002 }
16003 if (VD->hasInit())
16004 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
16005 }
16006 break;
16007 }
16008 case Stmt::MemberExprClass: {
16009 auto *ME = cast<MemberExpr>(Val: E);
16010 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
16011 if (!FD || FD->getType()->isReferenceType() ||
16012 !ASTContext::hasLayout(D: FD->getParent()))
16013 break;
16014 std::optional<std::pair<CharUnits, CharUnits>> P;
16015 if (ME->isArrow())
16016 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
16017 else
16018 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
16019 if (!P)
16020 break;
16021 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
16022 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
16023 return std::make_pair(x&: P->first,
16024 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
16025 }
16026 case Stmt::UnaryOperatorClass: {
16027 auto *UO = cast<UnaryOperator>(Val: E);
16028 switch (UO->getOpcode()) {
16029 default:
16030 break;
16031 case UO_Deref:
16032 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
16033 }
16034 break;
16035 }
16036 case Stmt::BinaryOperatorClass: {
16037 auto *BO = cast<BinaryOperator>(Val: E);
16038 auto Opcode = BO->getOpcode();
16039 switch (Opcode) {
16040 default:
16041 break;
16042 case BO_Comma:
16043 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
16044 }
16045 break;
16046 }
16047 }
16048 return std::nullopt;
16049}
16050
16051/// This helper function takes a pointer expression and returns the alignment of
16052/// a VarDecl and a constant offset from the VarDecl.
16053std::optional<std::pair<
16054 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
16055 *E,
16056 ASTContext
16057 &Ctx) {
16058 E = E->IgnoreParens();
16059 switch (E->getStmtClass()) {
16060 default:
16061 break;
16062 case Stmt::CStyleCastExprClass:
16063 case Stmt::CXXStaticCastExprClass:
16064 case Stmt::ImplicitCastExprClass: {
16065 auto *CE = cast<CastExpr>(Val: E);
16066 const Expr *From = CE->getSubExpr();
16067 switch (CE->getCastKind()) {
16068 default:
16069 break;
16070 case CK_NoOp:
16071 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
16072 case CK_ArrayToPointerDecay:
16073 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
16074 case CK_UncheckedDerivedToBase:
16075 case CK_DerivedToBase: {
16076 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
16077 if (!P)
16078 break;
16079 return getDerivedToBaseAlignmentAndOffset(
16080 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
16081 }
16082 }
16083 break;
16084 }
16085 case Stmt::CXXThisExprClass: {
16086 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
16087 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
16088 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
16089 }
16090 case Stmt::UnaryOperatorClass: {
16091 auto *UO = cast<UnaryOperator>(Val: E);
16092 if (UO->getOpcode() == UO_AddrOf)
16093 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
16094 break;
16095 }
16096 case Stmt::BinaryOperatorClass: {
16097 auto *BO = cast<BinaryOperator>(Val: E);
16098 auto Opcode = BO->getOpcode();
16099 switch (Opcode) {
16100 default:
16101 break;
16102 case BO_Add:
16103 case BO_Sub: {
16104 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
16105 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
16106 std::swap(a&: LHS, b&: RHS);
16107 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
16108 Ctx);
16109 }
16110 case BO_Comma:
16111 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
16112 }
16113 break;
16114 }
16115 }
16116 return std::nullopt;
16117}
16118
16119static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
16120 // See if we can compute the alignment of a VarDecl and an offset from it.
16121 std::optional<std::pair<CharUnits, CharUnits>> P =
16122 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
16123
16124 if (P)
16125 return P->first.alignmentAtOffset(offset: P->second);
16126
16127 // If that failed, return the type's alignment.
16128 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
16129}
16130
16131void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
16132 // This is actually a lot of work to potentially be doing on every
16133 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
16134 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
16135 return;
16136
16137 // Ignore dependent types.
16138 if (T->isDependentType() || Op->getType()->isDependentType())
16139 return;
16140
16141 // Require that the destination be a pointer type.
16142 const PointerType *DestPtr = T->getAs<PointerType>();
16143 if (!DestPtr) return;
16144
16145 // If the destination has alignment 1, we're done.
16146 QualType DestPointee = DestPtr->getPointeeType();
16147 if (DestPointee->isIncompleteType()) return;
16148 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
16149 if (DestAlign.isOne()) return;
16150
16151 // Require that the source be a pointer type.
16152 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
16153 if (!SrcPtr) return;
16154 QualType SrcPointee = SrcPtr->getPointeeType();
16155
16156 // Explicitly allow casts from cv void*. We already implicitly
16157 // allowed casts to cv void*, since they have alignment 1.
16158 // Also allow casts involving incomplete types, which implicitly
16159 // includes 'void'.
16160 if (SrcPointee->isIncompleteType()) return;
16161
16162 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
16163
16164 if (SrcAlign >= DestAlign) return;
16165
16166 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
16167 << Op->getType() << T
16168 << static_cast<unsigned>(SrcAlign.getQuantity())
16169 << static_cast<unsigned>(DestAlign.getQuantity())
16170 << TRange << Op->getSourceRange();
16171}
16172
16173void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
16174 const ArraySubscriptExpr *ASE,
16175 bool AllowOnePastEnd, bool IndexNegated) {
16176 // Already diagnosed by the constant evaluator.
16177 if (isConstantEvaluatedContext())
16178 return;
16179
16180 IndexExpr = IndexExpr->IgnoreParenImpCasts();
16181 if (IndexExpr->isValueDependent())
16182 return;
16183
16184 const Type *EffectiveType =
16185 BaseExpr->getType()->getPointeeOrArrayElementType();
16186 BaseExpr = BaseExpr->IgnoreParenCasts();
16187 const ConstantArrayType *ArrayTy =
16188 Context.getAsConstantArrayType(T: BaseExpr->getType());
16189
16190 LangOptions::StrictFlexArraysLevelKind
16191 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
16192
16193 const Type *BaseType =
16194 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
16195 bool IsUnboundedArray =
16196 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
16197 Context, StrictFlexArraysLevel,
16198 /*IgnoreTemplateOrMacroSubstitution=*/true);
16199 if (EffectiveType->isDependentType() ||
16200 (!IsUnboundedArray && BaseType->isDependentType()))
16201 return;
16202
16203 Expr::EvalResult Result;
16204 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
16205 return;
16206
16207 llvm::APSInt index = Result.Val.getInt();
16208 if (IndexNegated) {
16209 index.setIsUnsigned(false);
16210 index = -index;
16211 }
16212
16213 if (IsUnboundedArray) {
16214 if (EffectiveType->isFunctionType())
16215 return;
16216 if (index.isUnsigned() || !index.isNegative()) {
16217 const auto &ASTC = getASTContext();
16218 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
16219 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
16220 if (index.getBitWidth() < AddrBits)
16221 index = index.zext(width: AddrBits);
16222 std::optional<CharUnits> ElemCharUnits =
16223 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
16224 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
16225 // pointer) bounds-checking isn't meaningful.
16226 if (!ElemCharUnits || ElemCharUnits->isZero())
16227 return;
16228 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
16229 // If index has more active bits than address space, we already know
16230 // we have a bounds violation to warn about. Otherwise, compute
16231 // address of (index + 1)th element, and warn about bounds violation
16232 // only if that address exceeds address space.
16233 if (index.getActiveBits() <= AddrBits) {
16234 bool Overflow;
16235 llvm::APInt Product(index);
16236 Product += 1;
16237 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
16238 if (!Overflow && Product.getActiveBits() <= AddrBits)
16239 return;
16240 }
16241
16242 // Need to compute max possible elements in address space, since that
16243 // is included in diag message.
16244 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
16245 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
16246 MaxElems += 1;
16247 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
16248 MaxElems = MaxElems.udiv(RHS: ElemBytes);
16249
16250 unsigned DiagID =
16251 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16252 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16253
16254 // Diag message shows element size in bits and in "bytes" (platform-
16255 // dependent CharUnits)
16256 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16257 PD: PDiag(DiagID) << index << AddrBits
16258 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
16259 << ElemBytes << MaxElems
16260 << MaxElems.getZExtValue()
16261 << IndexExpr->getSourceRange());
16262
16263 const NamedDecl *ND = nullptr;
16264 // Try harder to find a NamedDecl to point at in the note.
16265 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16266 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16267 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16268 ND = DRE->getDecl();
16269 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16270 ND = ME->getMemberDecl();
16271
16272 if (ND)
16273 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16274 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16275 }
16276 return;
16277 }
16278
16279 if (index.isUnsigned() || !index.isNegative()) {
16280 // It is possible that the type of the base expression after
16281 // IgnoreParenCasts is incomplete, even though the type of the base
16282 // expression before IgnoreParenCasts is complete (see PR39746 for an
16283 // example). In this case we have no information about whether the array
16284 // access exceeds the array bounds. However we can still diagnose an array
16285 // access which precedes the array bounds.
16286 if (BaseType->isIncompleteType())
16287 return;
16288
16289 llvm::APInt size = ArrayTy->getSize();
16290
16291 if (BaseType != EffectiveType) {
16292 // Make sure we're comparing apples to apples when comparing index to
16293 // size.
16294 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
16295 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
16296
16297 // Handle ptrarith_typesize being zero, such as when casting to void*.
16298 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16299 if (!ptrarith_typesize)
16300 ptrarith_typesize = Context.getCharWidth();
16301
16302 if (ptrarith_typesize != array_typesize) {
16303 // There's a cast to a different size type involved.
16304 uint64_t ratio = array_typesize / ptrarith_typesize;
16305
16306 // TODO: Be smarter about handling cases where array_typesize is not a
16307 // multiple of ptrarith_typesize.
16308 if (ptrarith_typesize * ratio == array_typesize)
16309 size *= llvm::APInt(size.getBitWidth(), ratio);
16310 }
16311 }
16312
16313 if (size.getBitWidth() > index.getBitWidth())
16314 index = index.zext(width: size.getBitWidth());
16315 else if (size.getBitWidth() < index.getBitWidth())
16316 size = size.zext(width: index.getBitWidth());
16317
16318 // For array subscripting the index must be less than size, but for pointer
16319 // arithmetic also allow the index (offset) to be equal to size since
16320 // computing the next address after the end of the array is legal and
16321 // commonly done e.g. in C++ iterators and range-based for loops.
16322 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
16323 return;
16324
16325 // Suppress the warning if the subscript expression (as identified by the
16326 // ']' location) and the index expression are both from macro expansions
16327 // within a system header.
16328 if (ASE) {
16329 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16330 Loc: ASE->getRBracketLoc());
16331 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
16332 SourceLocation IndexLoc =
16333 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
16334 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
16335 return;
16336 }
16337 }
16338
16339 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16340 : diag::warn_ptr_arith_exceeds_bounds;
16341 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16342 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16343
16344 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16345 PD: PDiag(DiagID)
16346 << index << ArrayTy->desugar() << CastMsg
16347 << CastMsgTy << IndexExpr->getSourceRange());
16348 } else {
16349 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16350 if (!ASE) {
16351 DiagID = diag::warn_ptr_arith_precedes_bounds;
16352 if (index.isNegative()) index = -index;
16353 }
16354
16355 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16356 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
16357 }
16358
16359 const NamedDecl *ND = nullptr;
16360 // Try harder to find a NamedDecl to point at in the note.
16361 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16362 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16363 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16364 ND = DRE->getDecl();
16365 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16366 ND = ME->getMemberDecl();
16367
16368 if (ND)
16369 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16370 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16371}
16372
16373void Sema::CheckArrayAccess(const Expr *expr) {
16374 int AllowOnePastEnd = 0;
16375 while (expr) {
16376 expr = expr->IgnoreParenImpCasts();
16377 switch (expr->getStmtClass()) {
16378 case Stmt::ArraySubscriptExprClass: {
16379 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
16380 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
16381 AllowOnePastEnd: AllowOnePastEnd > 0);
16382 expr = ASE->getBase();
16383 break;
16384 }
16385 case Stmt::MemberExprClass: {
16386 expr = cast<MemberExpr>(Val: expr)->getBase();
16387 break;
16388 }
16389 case Stmt::CXXMemberCallExprClass: {
16390 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
16391 break;
16392 }
16393 case Stmt::ArraySectionExprClass: {
16394 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
16395 // FIXME: We should probably be checking all of the elements to the
16396 // 'length' here as well.
16397 if (ASE->getLowerBound())
16398 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
16399 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
16400 return;
16401 }
16402 case Stmt::UnaryOperatorClass: {
16403 // Only unwrap the * and & unary operators
16404 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
16405 expr = UO->getSubExpr();
16406 switch (UO->getOpcode()) {
16407 case UO_AddrOf:
16408 AllowOnePastEnd++;
16409 break;
16410 case UO_Deref:
16411 AllowOnePastEnd--;
16412 break;
16413 default:
16414 return;
16415 }
16416 break;
16417 }
16418 case Stmt::ConditionalOperatorClass: {
16419 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
16420 if (const Expr *lhs = cond->getLHS())
16421 CheckArrayAccess(expr: lhs);
16422 if (const Expr *rhs = cond->getRHS())
16423 CheckArrayAccess(expr: rhs);
16424 return;
16425 }
16426 case Stmt::CXXOperatorCallExprClass: {
16427 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
16428 for (const auto *Arg : OCE->arguments())
16429 CheckArrayAccess(expr: Arg);
16430 return;
16431 }
16432 default:
16433 return;
16434 }
16435 }
16436}
16437
16438static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16439 Expr *RHS, bool isProperty) {
16440 // Check if RHS is an Objective-C object literal, which also can get
16441 // immediately zapped in a weak reference. Note that we explicitly
16442 // allow ObjCStringLiterals, since those are designed to never really die.
16443 RHS = RHS->IgnoreParenImpCasts();
16444
16445 // This enum needs to match with the 'select' in
16446 // warn_objc_arc_literal_assign (off-by-1).
16447 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
16448 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16449 return false;
16450
16451 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
16452 << (unsigned) Kind
16453 << (isProperty ? 0 : 1)
16454 << RHS->getSourceRange();
16455
16456 return true;
16457}
16458
16459static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16460 Qualifiers::ObjCLifetime LT,
16461 Expr *RHS, bool isProperty) {
16462 // Strip off any implicit cast added to get to the one ARC-specific.
16463 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16464 if (cast->getCastKind() == CK_ARCConsumeObject) {
16465 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
16466 << (LT == Qualifiers::OCL_ExplicitNone)
16467 << (isProperty ? 0 : 1)
16468 << RHS->getSourceRange();
16469 return true;
16470 }
16471 RHS = cast->getSubExpr();
16472 }
16473
16474 if (LT == Qualifiers::OCL_Weak &&
16475 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16476 return true;
16477
16478 return false;
16479}
16480
16481bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16482 QualType LHS, Expr *RHS) {
16483 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16484
16485 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16486 return false;
16487
16488 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
16489 return true;
16490
16491 return false;
16492}
16493
16494void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16495 Expr *LHS, Expr *RHS) {
16496 QualType LHSType;
16497 // PropertyRef on LHS type need be directly obtained from
16498 // its declaration as it has a PseudoType.
16499 ObjCPropertyRefExpr *PRE
16500 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
16501 if (PRE && !PRE->isImplicitProperty()) {
16502 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16503 if (PD)
16504 LHSType = PD->getType();
16505 }
16506
16507 if (LHSType.isNull())
16508 LHSType = LHS->getType();
16509
16510 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16511
16512 if (LT == Qualifiers::OCL_Weak) {
16513 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
16514 getCurFunction()->markSafeWeakUse(E: LHS);
16515 }
16516
16517 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
16518 return;
16519
16520 // FIXME. Check for other life times.
16521 if (LT != Qualifiers::OCL_None)
16522 return;
16523
16524 if (PRE) {
16525 if (PRE->isImplicitProperty())
16526 return;
16527 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16528 if (!PD)
16529 return;
16530
16531 unsigned Attributes = PD->getPropertyAttributes();
16532 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16533 // when 'assign' attribute was not explicitly specified
16534 // by user, ignore it and rely on property type itself
16535 // for lifetime info.
16536 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16537 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16538 LHSType->isObjCRetainableType())
16539 return;
16540
16541 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16542 if (cast->getCastKind() == CK_ARCConsumeObject) {
16543 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
16544 << RHS->getSourceRange();
16545 return;
16546 }
16547 RHS = cast->getSubExpr();
16548 }
16549 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16550 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
16551 return;
16552 }
16553 }
16554}
16555
16556//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16557
16558static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16559 SourceLocation StmtLoc,
16560 const NullStmt *Body) {
16561 // Do not warn if the body is a macro that expands to nothing, e.g:
16562 //
16563 // #define CALL(x)
16564 // if (condition)
16565 // CALL(0);
16566 if (Body->hasLeadingEmptyMacro())
16567 return false;
16568
16569 // Get line numbers of statement and body.
16570 bool StmtLineInvalid;
16571 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
16572 Invalid: &StmtLineInvalid);
16573 if (StmtLineInvalid)
16574 return false;
16575
16576 bool BodyLineInvalid;
16577 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
16578 Invalid: &BodyLineInvalid);
16579 if (BodyLineInvalid)
16580 return false;
16581
16582 // Warn if null statement and body are on the same line.
16583 if (StmtLine != BodyLine)
16584 return false;
16585
16586 return true;
16587}
16588
16589void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16590 const Stmt *Body,
16591 unsigned DiagID) {
16592 // Since this is a syntactic check, don't emit diagnostic for template
16593 // instantiations, this just adds noise.
16594 if (CurrentInstantiationScope)
16595 return;
16596
16597 // The body should be a null statement.
16598 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16599 if (!NBody)
16600 return;
16601
16602 // Do the usual checks.
16603 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16604 return;
16605
16606 Diag(Loc: NBody->getSemiLoc(), DiagID);
16607 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16608}
16609
16610void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16611 const Stmt *PossibleBody) {
16612 assert(!CurrentInstantiationScope); // Ensured by caller
16613
16614 SourceLocation StmtLoc;
16615 const Stmt *Body;
16616 unsigned DiagID;
16617 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
16618 StmtLoc = FS->getRParenLoc();
16619 Body = FS->getBody();
16620 DiagID = diag::warn_empty_for_body;
16621 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
16622 StmtLoc = WS->getRParenLoc();
16623 Body = WS->getBody();
16624 DiagID = diag::warn_empty_while_body;
16625 } else
16626 return; // Neither `for' nor `while'.
16627
16628 // The body should be a null statement.
16629 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16630 if (!NBody)
16631 return;
16632
16633 // Skip expensive checks if diagnostic is disabled.
16634 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
16635 return;
16636
16637 // Do the usual checks.
16638 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16639 return;
16640
16641 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16642 // noise level low, emit diagnostics only if for/while is followed by a
16643 // CompoundStmt, e.g.:
16644 // for (int i = 0; i < n; i++);
16645 // {
16646 // a(i);
16647 // }
16648 // or if for/while is followed by a statement with more indentation
16649 // than for/while itself:
16650 // for (int i = 0; i < n; i++);
16651 // a(i);
16652 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
16653 if (!ProbableTypo) {
16654 bool BodyColInvalid;
16655 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16656 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
16657 if (BodyColInvalid)
16658 return;
16659
16660 bool StmtColInvalid;
16661 unsigned StmtCol =
16662 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
16663 if (StmtColInvalid)
16664 return;
16665
16666 if (BodyCol > StmtCol)
16667 ProbableTypo = true;
16668 }
16669
16670 if (ProbableTypo) {
16671 Diag(Loc: NBody->getSemiLoc(), DiagID);
16672 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16673 }
16674}
16675
16676//===--- CHECK: Warn on self move with std::move. -------------------------===//
16677
16678void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16679 SourceLocation OpLoc) {
16680 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
16681 return;
16682
16683 if (inTemplateInstantiation())
16684 return;
16685
16686 // Strip parens and casts away.
16687 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16688 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16689
16690 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16691 // which we can treat as an inlined std::move
16692 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
16693 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16694 RHSExpr = CE->getArg(Arg: 0);
16695 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
16696 CXXSCE && CXXSCE->isXValue())
16697 RHSExpr = CXXSCE->getSubExpr();
16698 else
16699 return;
16700
16701 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
16702 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
16703
16704 // Two DeclRefExpr's, check that the decls are the same.
16705 if (LHSDeclRef && RHSDeclRef) {
16706 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16707 return;
16708 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16709 RHSDeclRef->getDecl()->getCanonicalDecl())
16710 return;
16711
16712 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16713 << LHSExpr->getType() << LHSExpr->getSourceRange()
16714 << RHSExpr->getSourceRange();
16715 if (const FieldDecl *F =
16716 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
16717 D << 1 << F
16718 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
16719 else
16720 D << 0;
16721 return;
16722 }
16723
16724 // Member variables require a different approach to check for self moves.
16725 // MemberExpr's are the same if every nested MemberExpr refers to the same
16726 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16727 // the base Expr's are CXXThisExpr's.
16728 const Expr *LHSBase = LHSExpr;
16729 const Expr *RHSBase = RHSExpr;
16730 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
16731 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
16732 if (!LHSME || !RHSME)
16733 return;
16734
16735 while (LHSME && RHSME) {
16736 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16737 RHSME->getMemberDecl()->getCanonicalDecl())
16738 return;
16739
16740 LHSBase = LHSME->getBase();
16741 RHSBase = RHSME->getBase();
16742 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16743 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16744 }
16745
16746 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16747 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16748 if (LHSDeclRef && RHSDeclRef) {
16749 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16750 return;
16751 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16752 RHSDeclRef->getDecl()->getCanonicalDecl())
16753 return;
16754
16755 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16756 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16757 << RHSExpr->getSourceRange();
16758 return;
16759 }
16760
16761 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16762 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16763 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16764 << RHSExpr->getSourceRange();
16765}
16766
16767//===--- Layout compatibility ----------------------------------------------//
16768
16769static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16770
16771/// Check if two enumeration types are layout-compatible.
16772static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16773 const EnumDecl *ED2) {
16774 // C++11 [dcl.enum] p8:
16775 // Two enumeration types are layout-compatible if they have the same
16776 // underlying type.
16777 return ED1->isComplete() && ED2->isComplete() &&
16778 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16779}
16780
16781/// Check if two fields are layout-compatible.
16782/// Can be used on union members, which are exempt from alignment requirement
16783/// of common initial sequence.
16784static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16785 const FieldDecl *Field2,
16786 bool AreUnionMembers = false) {
16787#ifndef NDEBUG
16788 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16789 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16790 assert(((Field1Parent->isStructureOrClassType() &&
16791 Field2Parent->isStructureOrClassType()) ||
16792 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16793 "Can't evaluate layout compatibility between a struct field and a "
16794 "union field.");
16795 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16796 (AreUnionMembers && Field1Parent->isUnionType())) &&
16797 "AreUnionMembers should be 'true' for union fields (only).");
16798#endif
16799
16800 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16801 return false;
16802
16803 if (Field1->isBitField() != Field2->isBitField())
16804 return false;
16805
16806 if (Field1->isBitField()) {
16807 // Make sure that the bit-fields are the same length.
16808 unsigned Bits1 = Field1->getBitWidthValue();
16809 unsigned Bits2 = Field2->getBitWidthValue();
16810
16811 if (Bits1 != Bits2)
16812 return false;
16813 }
16814
16815 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16816 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16817 return false;
16818
16819 if (!AreUnionMembers &&
16820 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16821 return false;
16822
16823 return true;
16824}
16825
16826/// Check if two standard-layout structs are layout-compatible.
16827/// (C++11 [class.mem] p17)
16828static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16829 const RecordDecl *RD2) {
16830 // Get to the class where the fields are declared
16831 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16832 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16833
16834 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16835 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16836
16837 // Check the fields.
16838 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16839 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16840 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16841 });
16842}
16843
16844/// Check if two standard-layout unions are layout-compatible.
16845/// (C++11 [class.mem] p18)
16846static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16847 const RecordDecl *RD2) {
16848 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16849 RD2->fields());
16850
16851 for (auto *Field1 : RD1->fields()) {
16852 auto It = llvm::find_if(Range&: UnmatchedFields, P: [&](const FieldDecl *Field2) {
16853 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/AreUnionMembers: true);
16854 });
16855 if (It == UnmatchedFields.end())
16856 return false;
16857 [[maybe_unused]] bool Result = UnmatchedFields.erase(Ptr: *It);
16858 assert(Result);
16859 }
16860
16861 return UnmatchedFields.empty();
16862}
16863
16864static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16865 const RecordDecl *RD2) {
16866 if (RD1->isUnion() != RD2->isUnion())
16867 return false;
16868
16869 if (RD1->isUnion())
16870 return isLayoutCompatibleUnion(C, RD1, RD2);
16871 else
16872 return isLayoutCompatibleStruct(C, RD1, RD2);
16873}
16874
16875/// Check if two types are layout-compatible in C++11 sense.
16876static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16877 if (T1.isNull() || T2.isNull())
16878 return false;
16879
16880 // C++20 [basic.types] p11:
16881 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16882 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16883 // or layout-compatible standard-layout class types (11.4).
16884 T1 = T1.getCanonicalType().getUnqualifiedType();
16885 T2 = T2.getCanonicalType().getUnqualifiedType();
16886
16887 if (C.hasSameType(T1, T2))
16888 return true;
16889
16890 const Type::TypeClass TC1 = T1->getTypeClass();
16891 const Type::TypeClass TC2 = T2->getTypeClass();
16892
16893 if (TC1 != TC2)
16894 return false;
16895
16896 if (TC1 == Type::Enum)
16897 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16898 if (TC1 == Type::Record) {
16899 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16900 return false;
16901
16902 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16903 RD2: T2->castAsRecordDecl());
16904 }
16905
16906 return false;
16907}
16908
16909bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16910 return isLayoutCompatible(C: getASTContext(), T1, T2);
16911}
16912
16913//===-------------- Pointer interconvertibility ----------------------------//
16914
16915bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16916 const TypeSourceInfo *Derived) {
16917 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16918 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16919
16920 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16921 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16922 return true;
16923
16924 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16925 return false;
16926
16927 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16928 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16929 return true;
16930
16931 return false;
16932}
16933
16934//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16935
16936/// Given a type tag expression find the type tag itself.
16937///
16938/// \param TypeExpr Type tag expression, as it appears in user's code.
16939///
16940/// \param VD Declaration of an identifier that appears in a type tag.
16941///
16942/// \param MagicValue Type tag magic value.
16943///
16944/// \param isConstantEvaluated whether the evalaution should be performed in
16945
16946/// constant context.
16947static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16948 const ValueDecl **VD, uint64_t *MagicValue,
16949 bool isConstantEvaluated) {
16950 while(true) {
16951 if (!TypeExpr)
16952 return false;
16953
16954 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16955
16956 switch (TypeExpr->getStmtClass()) {
16957 case Stmt::UnaryOperatorClass: {
16958 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16959 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16960 TypeExpr = UO->getSubExpr();
16961 continue;
16962 }
16963 return false;
16964 }
16965
16966 case Stmt::DeclRefExprClass: {
16967 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16968 *VD = DRE->getDecl();
16969 return true;
16970 }
16971
16972 case Stmt::IntegerLiteralClass: {
16973 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16974 llvm::APInt MagicValueAPInt = IL->getValue();
16975 if (MagicValueAPInt.getActiveBits() <= 64) {
16976 *MagicValue = MagicValueAPInt.getZExtValue();
16977 return true;
16978 } else
16979 return false;
16980 }
16981
16982 case Stmt::BinaryConditionalOperatorClass:
16983 case Stmt::ConditionalOperatorClass: {
16984 const AbstractConditionalOperator *ACO =
16985 cast<AbstractConditionalOperator>(Val: TypeExpr);
16986 bool Result;
16987 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16988 InConstantContext: isConstantEvaluated)) {
16989 if (Result)
16990 TypeExpr = ACO->getTrueExpr();
16991 else
16992 TypeExpr = ACO->getFalseExpr();
16993 continue;
16994 }
16995 return false;
16996 }
16997
16998 case Stmt::BinaryOperatorClass: {
16999 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
17000 if (BO->getOpcode() == BO_Comma) {
17001 TypeExpr = BO->getRHS();
17002 continue;
17003 }
17004 return false;
17005 }
17006
17007 default:
17008 return false;
17009 }
17010 }
17011}
17012
17013/// Retrieve the C type corresponding to type tag TypeExpr.
17014///
17015/// \param TypeExpr Expression that specifies a type tag.
17016///
17017/// \param MagicValues Registered magic values.
17018///
17019/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
17020/// kind.
17021///
17022/// \param TypeInfo Information about the corresponding C type.
17023///
17024/// \param isConstantEvaluated whether the evalaution should be performed in
17025/// constant context.
17026///
17027/// \returns true if the corresponding C type was found.
17028static bool GetMatchingCType(
17029 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
17030 const ASTContext &Ctx,
17031 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
17032 *MagicValues,
17033 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
17034 bool isConstantEvaluated) {
17035 FoundWrongKind = false;
17036
17037 // Variable declaration that has type_tag_for_datatype attribute.
17038 const ValueDecl *VD = nullptr;
17039
17040 uint64_t MagicValue;
17041
17042 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
17043 return false;
17044
17045 if (VD) {
17046 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
17047 if (I->getArgumentKind() != ArgumentKind) {
17048 FoundWrongKind = true;
17049 return false;
17050 }
17051 TypeInfo.Type = I->getMatchingCType();
17052 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
17053 TypeInfo.MustBeNull = I->getMustBeNull();
17054 return true;
17055 }
17056 return false;
17057 }
17058
17059 if (!MagicValues)
17060 return false;
17061
17062 llvm::DenseMap<Sema::TypeTagMagicValue,
17063 Sema::TypeTagData>::const_iterator I =
17064 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
17065 if (I == MagicValues->end())
17066 return false;
17067
17068 TypeInfo = I->second;
17069 return true;
17070}
17071
17072void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
17073 uint64_t MagicValue, QualType Type,
17074 bool LayoutCompatible,
17075 bool MustBeNull) {
17076 if (!TypeTagForDatatypeMagicValues)
17077 TypeTagForDatatypeMagicValues.reset(
17078 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
17079
17080 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
17081 (*TypeTagForDatatypeMagicValues)[Magic] =
17082 TypeTagData(Type, LayoutCompatible, MustBeNull);
17083}
17084
17085static bool IsSameCharType(QualType T1, QualType T2) {
17086 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
17087 if (!BT1)
17088 return false;
17089
17090 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
17091 if (!BT2)
17092 return false;
17093
17094 BuiltinType::Kind T1Kind = BT1->getKind();
17095 BuiltinType::Kind T2Kind = BT2->getKind();
17096
17097 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
17098 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
17099 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
17100 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
17101}
17102
17103void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
17104 const ArrayRef<const Expr *> ExprArgs,
17105 SourceLocation CallSiteLoc) {
17106 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
17107 bool IsPointerAttr = Attr->getIsPointer();
17108
17109 // Retrieve the argument representing the 'type_tag'.
17110 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
17111 if (TypeTagIdxAST >= ExprArgs.size()) {
17112 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
17113 << 0 << Attr->getTypeTagIdx().getSourceIndex();
17114 return;
17115 }
17116 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17117 bool FoundWrongKind;
17118 TypeTagData TypeInfo;
17119 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
17120 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17121 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
17122 if (FoundWrongKind)
17123 Diag(Loc: TypeTagExpr->getExprLoc(),
17124 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
17125 << TypeTagExpr->getSourceRange();
17126 return;
17127 }
17128
17129 // Retrieve the argument representing the 'arg_idx'.
17130 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17131 if (ArgumentIdxAST >= ExprArgs.size()) {
17132 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
17133 << 1 << Attr->getArgumentIdx().getSourceIndex();
17134 return;
17135 }
17136 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17137 if (IsPointerAttr) {
17138 // Skip implicit cast of pointer to `void *' (as a function argument).
17139 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
17140 if (ICE->getType()->isVoidPointerType() &&
17141 ICE->getCastKind() == CK_BitCast)
17142 ArgumentExpr = ICE->getSubExpr();
17143 }
17144 QualType ArgumentType = ArgumentExpr->getType();
17145
17146 // Passing a `void*' pointer shouldn't trigger a warning.
17147 if (IsPointerAttr && ArgumentType->isVoidPointerType())
17148 return;
17149
17150 if (TypeInfo.MustBeNull) {
17151 // Type tag with matching void type requires a null pointer.
17152 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
17153 NPC: Expr::NPC_ValueDependentIsNotNull)) {
17154 Diag(Loc: ArgumentExpr->getExprLoc(),
17155 DiagID: diag::warn_type_safety_null_pointer_required)
17156 << ArgumentKind->getName()
17157 << ArgumentExpr->getSourceRange()
17158 << TypeTagExpr->getSourceRange();
17159 }
17160 return;
17161 }
17162
17163 QualType RequiredType = TypeInfo.Type;
17164 if (IsPointerAttr)
17165 RequiredType = Context.getPointerType(T: RequiredType);
17166
17167 bool mismatch = false;
17168 if (!TypeInfo.LayoutCompatible) {
17169 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
17170
17171 // C++11 [basic.fundamental] p1:
17172 // Plain char, signed char, and unsigned char are three distinct types.
17173 //
17174 // But we treat plain `char' as equivalent to `signed char' or `unsigned
17175 // char' depending on the current char signedness mode.
17176 if (mismatch)
17177 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
17178 T2: RequiredType->getPointeeType())) ||
17179 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
17180 mismatch = false;
17181 } else
17182 if (IsPointerAttr)
17183 mismatch = !isLayoutCompatible(C: Context,
17184 T1: ArgumentType->getPointeeType(),
17185 T2: RequiredType->getPointeeType());
17186 else
17187 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
17188
17189 if (mismatch)
17190 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
17191 << ArgumentType << ArgumentKind
17192 << TypeInfo.LayoutCompatible << RequiredType
17193 << ArgumentExpr->getSourceRange()
17194 << TypeTagExpr->getSourceRange();
17195}
17196
17197void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17198 CharUnits Alignment) {
17199 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
17200 Args&: Alignment);
17201}
17202
17203void Sema::DiagnoseMisalignedMembers() {
17204 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
17205 const NamedDecl *ND = m.RD;
17206 if (ND->getName().empty()) {
17207 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17208 ND = TD;
17209 }
17210 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
17211 << m.MD << ND << m.E->getSourceRange();
17212 }
17213 currentEvaluationContext().MisalignedMembers.clear();
17214}
17215
17216void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
17217 E = E->IgnoreParens();
17218 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
17219 return;
17220 if (isa<UnaryOperator>(Val: E) &&
17221 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
17222 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
17223 if (isa<MemberExpr>(Val: Op)) {
17224 auto &MisalignedMembersForExpr =
17225 currentEvaluationContext().MisalignedMembers;
17226 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
17227 if (MA != MisalignedMembersForExpr.end() &&
17228 (T->isDependentType() || T->isIntegerType() ||
17229 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17230 Context.getTypeAlignInChars(
17231 T: T->getPointeeType()) <= MA->Alignment))))
17232 MisalignedMembersForExpr.erase(CI: MA);
17233 }
17234 }
17235}
17236
17237void Sema::RefersToMemberWithReducedAlignment(
17238 Expr *E,
17239 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17240 Action) {
17241 const auto *ME = dyn_cast<MemberExpr>(Val: E);
17242 if (!ME)
17243 return;
17244
17245 // No need to check expressions with an __unaligned-qualified type.
17246 if (E->getType().getQualifiers().hasUnaligned())
17247 return;
17248
17249 // For a chain of MemberExpr like "a.b.c.d" this list
17250 // will keep FieldDecl's like [d, c, b].
17251 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17252 const MemberExpr *TopME = nullptr;
17253 bool AnyIsPacked = false;
17254 do {
17255 QualType BaseType = ME->getBase()->getType();
17256 if (BaseType->isDependentType())
17257 return;
17258 if (ME->isArrow())
17259 BaseType = BaseType->getPointeeType();
17260 auto *RD = BaseType->castAsRecordDecl();
17261 if (RD->isInvalidDecl())
17262 return;
17263
17264 ValueDecl *MD = ME->getMemberDecl();
17265 auto *FD = dyn_cast<FieldDecl>(Val: MD);
17266 // We do not care about non-data members.
17267 if (!FD || FD->isInvalidDecl())
17268 return;
17269
17270 AnyIsPacked =
17271 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17272 ReverseMemberChain.push_back(Elt: FD);
17273
17274 TopME = ME;
17275 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
17276 } while (ME);
17277 assert(TopME && "We did not compute a topmost MemberExpr!");
17278
17279 // Not the scope of this diagnostic.
17280 if (!AnyIsPacked)
17281 return;
17282
17283 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17284 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
17285 // TODO: The innermost base of the member expression may be too complicated.
17286 // For now, just disregard these cases. This is left for future
17287 // improvement.
17288 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
17289 return;
17290
17291 // Alignment expected by the whole expression.
17292 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
17293
17294 // No need to do anything else with this case.
17295 if (ExpectedAlignment.isOne())
17296 return;
17297
17298 // Synthesize offset of the whole access.
17299 CharUnits Offset;
17300 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
17301 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
17302
17303 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17304 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17305 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
17306
17307 // The base expression of the innermost MemberExpr may give
17308 // stronger guarantees than the class containing the member.
17309 if (DRE && !TopME->isArrow()) {
17310 const ValueDecl *VD = DRE->getDecl();
17311 if (!VD->getType()->isReferenceType())
17312 CompleteObjectAlignment =
17313 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
17314 }
17315
17316 // Check if the synthesized offset fulfills the alignment.
17317 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
17318 // It may fulfill the offset it but the effective alignment may still be
17319 // lower than the expected expression alignment.
17320 CompleteObjectAlignment < ExpectedAlignment) {
17321 // If this happens, we want to determine a sensible culprit of this.
17322 // Intuitively, watching the chain of member expressions from right to
17323 // left, we start with the required alignment (as required by the field
17324 // type) but some packed attribute in that chain has reduced the alignment.
17325 // It may happen that another packed structure increases it again. But if
17326 // we are here such increase has not been enough. So pointing the first
17327 // FieldDecl that either is packed or else its RecordDecl is,
17328 // seems reasonable.
17329 FieldDecl *FD = nullptr;
17330 CharUnits Alignment;
17331 for (FieldDecl *FDI : ReverseMemberChain) {
17332 if (FDI->hasAttr<PackedAttr>() ||
17333 FDI->getParent()->hasAttr<PackedAttr>()) {
17334 FD = FDI;
17335 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
17336 b: Context.getTypeAlignInChars(
17337 T: Context.getCanonicalTagType(TD: FD->getParent())));
17338 break;
17339 }
17340 }
17341 assert(FD && "We did not find a packed FieldDecl!");
17342 Action(E, FD->getParent(), FD, Alignment);
17343 }
17344}
17345
17346void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17347 using namespace std::placeholders;
17348
17349 RefersToMemberWithReducedAlignment(
17350 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
17351 args: _2, args: _3, args: _4));
17352}
17353
17354bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
17355 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17356 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17357 return true;
17358
17359 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
17360 if (A.isInvalid())
17361 return true;
17362
17363 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17364 QualType TyA = A.get()->getType();
17365
17366 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
17367 ArgTyRestr, ArgOrdinal: 1))
17368 return true;
17369
17370 TheCall->setType(TyA);
17371 return false;
17372}
17373
17374bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17375 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17376 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17377 TheCall->setType(*Res);
17378 return false;
17379 }
17380 return true;
17381}
17382
17383bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
17384 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17385 if (!Res)
17386 return true;
17387
17388 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17389 TheCall->setType(VecTy0->getElementType());
17390 else
17391 TheCall->setType(*Res);
17392
17393 return false;
17394}
17395
17396static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
17397 SourceLocation Loc) {
17398 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
17399 R = RHS->getEnumCoercedType(Ctx: S.Context);
17400 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17401 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
17402 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
17403 << LHS->getSourceRange() << RHS->getSourceRange()
17404 << /*Arithmetic Between*/ 0 << L << R;
17405 }
17406 return false;
17407}
17408
17409/// Check if all arguments have the same type. If the types don't match, emit an
17410/// error message and return true. Otherwise return false.
17411///
17412/// For scalars we directly compare their unqualified types. But even if we
17413/// compare unqualified vector types, a difference in qualifiers in the element
17414/// types can make the vector types be considered not equal. For example,
17415/// vector of 4 'const float' values vs vector of 4 'float' values.
17416/// So we compare unqualified types of their elements and number of elements.
17417static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
17418 ArrayRef<Expr *> Args) {
17419 assert(!Args.empty() && "Should have at least one argument.");
17420
17421 Expr *Arg0 = Args.front();
17422 QualType Ty0 = Arg0->getType();
17423
17424 auto EmitError = [&](Expr *ArgI) {
17425 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
17426 DiagID: diag::err_typecheck_call_different_arg_types)
17427 << Arg0->getType() << ArgI->getType();
17428 };
17429
17430 // Compare scalar types.
17431 if (!Ty0->isVectorType()) {
17432 for (Expr *ArgI : Args.drop_front())
17433 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
17434 EmitError(ArgI);
17435 return true;
17436 }
17437
17438 return false;
17439 }
17440
17441 // Compare vector types.
17442 const auto *Vec0 = Ty0->castAs<VectorType>();
17443 for (Expr *ArgI : Args.drop_front()) {
17444 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17445 if (!VecI ||
17446 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
17447 T2: VecI->getElementType()) ||
17448 Vec0->getNumElements() != VecI->getNumElements()) {
17449 EmitError(ArgI);
17450 return true;
17451 }
17452 }
17453
17454 return false;
17455}
17456
17457std::optional<QualType>
17458Sema::BuiltinVectorMath(CallExpr *TheCall,
17459 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17460 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
17461 return std::nullopt;
17462
17463 if (checkBuiltinVectorMathMixedEnums(
17464 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
17465 return std::nullopt;
17466
17467 Expr *Args[2];
17468 for (int I = 0; I < 2; ++I) {
17469 ExprResult Converted =
17470 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17471 if (Converted.isInvalid())
17472 return std::nullopt;
17473 Args[I] = Converted.get();
17474 }
17475
17476 SourceLocation LocA = Args[0]->getBeginLoc();
17477 QualType TyA = Args[0]->getType();
17478
17479 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
17480 return std::nullopt;
17481
17482 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17483 return std::nullopt;
17484
17485 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
17486 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
17487 return TyA;
17488}
17489
17490bool Sema::BuiltinElementwiseTernaryMath(
17491 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17492 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17493 return true;
17494
17495 SourceLocation Loc = TheCall->getExprLoc();
17496 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
17497 RHS: TheCall->getArg(Arg: 1), Loc) ||
17498 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
17499 RHS: TheCall->getArg(Arg: 2), Loc))
17500 return true;
17501
17502 Expr *Args[3];
17503 for (int I = 0; I < 3; ++I) {
17504 ExprResult Converted =
17505 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17506 if (Converted.isInvalid())
17507 return true;
17508 Args[I] = Converted.get();
17509 }
17510
17511 int ArgOrdinal = 1;
17512 for (Expr *Arg : Args) {
17513 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
17514 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
17515 return true;
17516 }
17517
17518 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17519 return true;
17520
17521 for (int I = 0; I < 3; ++I)
17522 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
17523
17524 TheCall->setType(Args[0]->getType());
17525 return false;
17526}
17527
17528bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17529 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17530 return true;
17531
17532 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
17533 if (A.isInvalid())
17534 return true;
17535
17536 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17537 return false;
17538}
17539
17540bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17541 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17542 return true;
17543
17544 ExprResult Arg = TheCall->getArg(Arg: 0);
17545 QualType TyArg = Arg.get()->getType();
17546
17547 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17548 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
17549 DiagID: diag::err_builtin_invalid_arg_type)
17550 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17551
17552 TheCall->setType(TyArg);
17553 return false;
17554}
17555
17556ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17557 ExprResult CallResult) {
17558 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17559 return ExprError();
17560
17561 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
17562 if (MatrixArg.isInvalid())
17563 return MatrixArg;
17564 Expr *Matrix = MatrixArg.get();
17565
17566 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17567 if (!MType) {
17568 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17569 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17570 << Matrix->getType();
17571 return ExprError();
17572 }
17573
17574 // Create returned matrix type by swapping rows and columns of the argument
17575 // matrix type.
17576 QualType ResultType = Context.getConstantMatrixType(
17577 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
17578
17579 // Change the return type to the type of the returned matrix.
17580 TheCall->setType(ResultType);
17581
17582 // Update call argument to use the possibly converted matrix argument.
17583 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
17584 return CallResult;
17585}
17586
17587// Get and verify the matrix dimensions.
17588static std::optional<unsigned>
17589getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17590 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
17591 if (!Value) {
17592 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
17593 << Name;
17594 return {};
17595 }
17596 uint64_t Dim = Value->getZExtValue();
17597 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17598 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
17599 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17600 return {};
17601 }
17602 return Dim;
17603}
17604
17605ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17606 ExprResult CallResult) {
17607 if (!getLangOpts().MatrixTypes) {
17608 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17609 return ExprError();
17610 }
17611
17612 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17613 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17614 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17615 << /*column*/ 1 << /*load*/ 0;
17616 return ExprError();
17617 }
17618
17619 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
17620 return ExprError();
17621
17622 unsigned PtrArgIdx = 0;
17623 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17624 Expr *RowsExpr = TheCall->getArg(Arg: 1);
17625 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
17626 Expr *StrideExpr = TheCall->getArg(Arg: 3);
17627
17628 bool ArgError = false;
17629
17630 // Check pointer argument.
17631 {
17632 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17633 if (PtrConv.isInvalid())
17634 return PtrConv;
17635 PtrExpr = PtrConv.get();
17636 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
17637 if (PtrExpr->isTypeDependent()) {
17638 TheCall->setType(Context.DependentTy);
17639 return TheCall;
17640 }
17641 }
17642
17643 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17644 QualType ElementTy;
17645 if (!PtrTy) {
17646 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17647 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17648 << PtrExpr->getType();
17649 ArgError = true;
17650 } else {
17651 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17652
17653 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
17654 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17655 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17656 << /* no fp */ 0 << PtrExpr->getType();
17657 ArgError = true;
17658 }
17659 }
17660
17661 // Apply default Lvalue conversions and convert the expression to size_t.
17662 auto ApplyArgumentConversions = [this](Expr *E) {
17663 ExprResult Conv = DefaultLvalueConversion(E);
17664 if (Conv.isInvalid())
17665 return Conv;
17666
17667 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
17668 };
17669
17670 // Apply conversion to row and column expressions.
17671 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17672 if (!RowsConv.isInvalid()) {
17673 RowsExpr = RowsConv.get();
17674 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
17675 } else
17676 RowsExpr = nullptr;
17677
17678 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17679 if (!ColumnsConv.isInvalid()) {
17680 ColumnsExpr = ColumnsConv.get();
17681 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
17682 } else
17683 ColumnsExpr = nullptr;
17684
17685 // If any part of the result matrix type is still pending, just use
17686 // Context.DependentTy, until all parts are resolved.
17687 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17688 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17689 TheCall->setType(Context.DependentTy);
17690 return CallResult;
17691 }
17692
17693 // Check row and column dimensions.
17694 std::optional<unsigned> MaybeRows;
17695 if (RowsExpr)
17696 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
17697
17698 std::optional<unsigned> MaybeColumns;
17699 if (ColumnsExpr)
17700 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
17701
17702 // Check stride argument.
17703 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17704 if (StrideConv.isInvalid())
17705 return ExprError();
17706 StrideExpr = StrideConv.get();
17707 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
17708
17709 if (MaybeRows) {
17710 if (std::optional<llvm::APSInt> Value =
17711 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17712 uint64_t Stride = Value->getZExtValue();
17713 if (Stride < *MaybeRows) {
17714 Diag(Loc: StrideExpr->getBeginLoc(),
17715 DiagID: diag::err_builtin_matrix_stride_too_small);
17716 ArgError = true;
17717 }
17718 }
17719 }
17720
17721 if (ArgError || !MaybeRows || !MaybeColumns)
17722 return ExprError();
17723
17724 TheCall->setType(
17725 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
17726 return CallResult;
17727}
17728
17729ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17730 ExprResult CallResult) {
17731 if (!getLangOpts().MatrixTypes) {
17732 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17733 return ExprError();
17734 }
17735
17736 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17737 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17738 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17739 << /*column*/ 1 << /*store*/ 1;
17740 return ExprError();
17741 }
17742
17743 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17744 return ExprError();
17745
17746 unsigned PtrArgIdx = 1;
17747 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17748 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17749 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17750
17751 bool ArgError = false;
17752
17753 {
17754 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17755 if (MatrixConv.isInvalid())
17756 return MatrixConv;
17757 MatrixExpr = MatrixConv.get();
17758 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17759 }
17760 if (MatrixExpr->isTypeDependent()) {
17761 TheCall->setType(Context.DependentTy);
17762 return TheCall;
17763 }
17764
17765 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17766 if (!MatrixTy) {
17767 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17768 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17769 ArgError = true;
17770 }
17771
17772 {
17773 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17774 if (PtrConv.isInvalid())
17775 return PtrConv;
17776 PtrExpr = PtrConv.get();
17777 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17778 if (PtrExpr->isTypeDependent()) {
17779 TheCall->setType(Context.DependentTy);
17780 return TheCall;
17781 }
17782 }
17783
17784 // Check pointer argument.
17785 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17786 if (!PtrTy) {
17787 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17788 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17789 << PtrExpr->getType();
17790 ArgError = true;
17791 } else {
17792 QualType ElementTy = PtrTy->getPointeeType();
17793 if (ElementTy.isConstQualified()) {
17794 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17795 ArgError = true;
17796 }
17797 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17798 if (MatrixTy &&
17799 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17800 Diag(Loc: PtrExpr->getBeginLoc(),
17801 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17802 << ElementTy << MatrixTy->getElementType();
17803 ArgError = true;
17804 }
17805 }
17806
17807 // Apply default Lvalue conversions and convert the stride expression to
17808 // size_t.
17809 {
17810 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17811 if (StrideConv.isInvalid())
17812 return StrideConv;
17813
17814 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17815 if (StrideConv.isInvalid())
17816 return StrideConv;
17817 StrideExpr = StrideConv.get();
17818 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17819 }
17820
17821 // Check stride argument.
17822 if (MatrixTy) {
17823 if (std::optional<llvm::APSInt> Value =
17824 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17825 uint64_t Stride = Value->getZExtValue();
17826 if (Stride < MatrixTy->getNumRows()) {
17827 Diag(Loc: StrideExpr->getBeginLoc(),
17828 DiagID: diag::err_builtin_matrix_stride_too_small);
17829 ArgError = true;
17830 }
17831 }
17832 }
17833
17834 if (ArgError)
17835 return ExprError();
17836
17837 return CallResult;
17838}
17839
17840void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17841 const NamedDecl *Callee) {
17842 // This warning does not make sense in code that has no runtime behavior.
17843 if (isUnevaluatedContext())
17844 return;
17845
17846 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17847
17848 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17849 return;
17850
17851 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17852 // all TCBs the callee is a part of.
17853 llvm::StringSet<> CalleeTCBs;
17854 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17855 CalleeTCBs.insert(key: A->getTCBName());
17856 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17857 CalleeTCBs.insert(key: A->getTCBName());
17858
17859 // Go through the TCBs the caller is a part of and emit warnings if Caller
17860 // is in a TCB that the Callee is not.
17861 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17862 StringRef CallerTCB = A->getTCBName();
17863 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17864 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17865 << Callee << CallerTCB;
17866 }
17867 }
17868}
17869