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
204static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
209 InitializedEntity::InitializeParameter(Context&: S.Context, Type: Ty, Consumed: false);
210 ExprResult Result =
211 S.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 QualType ResultType = S.CheckAddressOfOperand(Operand&: Arg, OpLoc: TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
287 return true;
288
289 if (TheCall->getArg(Arg: 0)->containsErrors())
290 return true;
291
292 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
298 Val: Arg.get()->getAsBuiltinConstantDeclRef(Context: S.getASTContext()));
299
300 if (!FD) {
301 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
307 Loc: TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(Arg: 0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(T: SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Loc: Source->getExprLoc(),
348 DiagID: diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(Arg: 1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(T: SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(Result&: AlignResult, Ctx: S.Context,
363 AllowSideEffects: Expr::SE_AllowSideEffects)) {
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(numBits: MaxAlignmentBits + 1, BitNo: MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(I1: AlignValue, I2: MaxValue) > 0) {
372 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_big)
373 << toString(I: MaxValue, Radix: 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
386 ExprResult SrcArg = S.PerformCopyInitialization(
387 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Type: SrcTy, Consumed: false),
388 EqualLoc: SourceLocation(), Init: Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(Arg: 0, ArgExpr: SrcArg.get());
392 ExprResult AlignArg =
393 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
394 Context&: S.Context, Type: AlignOp->getType(), Consumed: false),
395 EqualLoc: SourceLocation(), Init: AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(Arg: 1, ArgExpr: AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Range&: Builtins, P: [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
419 Lexer::getImmediateMacroName(Loc: TheCall->getExprLoc(),
420 SM: S.getSourceManager(), LangOpts: S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
438 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: I));
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(Arg: I, ArgExpr: Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Loc: Arg.get()->getBeginLoc(), DiagID: diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
455 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 2));
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(Arg: 2, ArgExpr: Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Loc: Arg.get()->getBeginLoc(),
466 DiagID: diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(Arg: I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(T: Ty) > 128)
481 return S.Diag(Loc: Arg->getBeginLoc(),
482 DiagID: diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(E: PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(Elt: OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
515 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Key: Str);
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve(N: (TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(in_start: TheCall->arg_begin() + 2, in_end: TheCall->arg_end());
526 Args.push_back(Elt: getStringLiteral(Str: Format));
527 llvm::append_range(C&: Args, R&: Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
531 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
535 S.pushCodeSynthesisContext(Ctx);
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: TheCall->getArg(Arg: 1),
539 LParenLoc: TheCall->getBeginLoc(), ArgExprs: Args, RParenLoc: TheCall->getRParenLoc());
540
541 S.popCodeSynthesisContext();
542 if (!RealCall.isInvalid())
543 Actions.push_back(Elt: RealCall.get());
544 // Bail out if we've hit any unrecoverable errors, even if we managed
545 // to build the call.
546 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(N: Depth * Policy.Indentation, NV: ' ');
555 return getStringLiteral(Str: Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(Str: T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(QT: T, LangOpt: S.getLangOpts(), Ctx&: S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(os&: OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(os&: OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(T: S.Context.getCanonicalTagType(TD: RD));
618 if (IndentLit ? callPrintFunction(Format: "%s%s", Exprs: {IndentLit, TypeLit})
619 : callPrintFunction(Format: "%s", Exprs: {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, RecordIndent: IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(Inner: E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(Format: " {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(T: Base.getType())
646 : S.Context.getLValueReferenceType(T: Base.getType());
647 ExprResult BasePtr = S.BuildCStyleCastExpr(
648 LParenLoc: Loc, Ty: S.Context.getTrivialTypeSourceInfo(T: BaseType, Loc), RParenLoc: Loc,
649 Op: RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(RD: Base.getType()->getAsRecordDecl(), E: BasePtr.get(),
652 Depth: Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth: Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(Val: D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(T: FD->getType()),
669 getStringLiteral(Str: FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(T: SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(Elt: IntegerLiteral::Create(C: S.Context, V: BitWidth, type: SizeT, l: Loc));
677 }
678
679 Format += "=";
680
681 ExprResult Field =
682 IFD ? S.BuildAnonymousStructUnionMemberReference(
683 SS: CXXScopeSpec(), nameLoc: Loc, indirectField: IFD,
684 FoundDecl: DeclAccessPair::make(D: IFD, AS: AS_public), baseObjectExpr: RecordArg, opLoc: Loc)
685 : S.BuildFieldReferenceExpr(
686 BaseExpr: RecordArg, IsArrow: RecordArgIsPtr, OpLoc: Loc, SS: CXXScopeSpec(), Field: FD,
687 FoundDecl: DeclAccessPair::make(D: FD, AS: AS_public),
688 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(Val: InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Exprs: Args) ||
697 dumpRecordValue(RD: InnerRD, E: Field.get(), RecordIndent: FieldIndentArg, Depth: Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(T: FD->getType(), Str&: Format)) {
702 // We know how to print this field.
703 Args.push_back(Elt: Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(S: nullptr, OpLoc: Loc, Opc: UO_AddrOf, Input: Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(Elt: FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Exprs: Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction(Format: "%s}\n", Exprs: RecordIndent)
722 : callPrintFunction(Format: "}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(Context: S.Context, syntactic: TheCall, semantic: Actions,
727 resultIndex: PseudoObjectExpr::NoResult);
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
735static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
736 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(Arg: 0, ArgExpr: PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(Loc: PtrArgResult.get()->getBeginLoc(),
749 DiagID: diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(Loc: PtrArgResult.get()->getBeginLoc(), T: Pointee,
758 DiagID: diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(Arg: 1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
779 DiagID: diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(Loc: PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, E: PtrArg, Depth: 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(Call: BuiltinCall, DesiredArgCount: 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(Arg: 0);
808 Expr *Chain = BuiltinCall->getArg(Arg: 1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Val: Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens())) {
832 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(E: Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(Ctx: S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ResultTy: ReturnTy, Args: ArgTys, EPI: FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(T: BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(E: Builtin, Type: BuiltinPtrTy, CK: CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(Arg: 1, ArgExpr: ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
867 : public analyze_format_string::FormatStringHandler {
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
896 case analyze_format_string::ConversionSpecifier::sArg:
897 case analyze_format_string::ConversionSpecifier::ScanListArg:
898 NulByte = 1;
899 break;
900 case analyze_format_string::ConversionSpecifier::cArg:
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
926 : public analyze_format_string::FormatStringHandler {
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(a: Format.find(C: 0), b: Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
947 case analyze_format_string::ConversionSpecifier::cArg:
948 case analyze_format_string::ConversionSpecifier::CArg:
949 Size += std::max(a: FieldWidth, b: (size_t)1);
950 break;
951 // Just an integer.
952 case analyze_format_string::ConversionSpecifier::dArg:
953 case analyze_format_string::ConversionSpecifier::DArg:
954 case analyze_format_string::ConversionSpecifier::iArg:
955 case analyze_format_string::ConversionSpecifier::oArg:
956 case analyze_format_string::ConversionSpecifier::OArg:
957 case analyze_format_string::ConversionSpecifier::uArg:
958 case analyze_format_string::ConversionSpecifier::UArg:
959 case analyze_format_string::ConversionSpecifier::xArg:
960 case analyze_format_string::ConversionSpecifier::XArg:
961 Size += std::max(a: FieldWidth, b: Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
969 case analyze_format_string::ConversionSpecifier::gArg:
970 case analyze_format_string::ConversionSpecifier::GArg:
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
975 case analyze_format_string::ConversionSpecifier::fArg:
976 case analyze_format_string::ConversionSpecifier::FArg:
977 Size += std::max(a: FieldWidth, b: 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
983 case analyze_format_string::ConversionSpecifier::eArg:
984 case analyze_format_string::ConversionSpecifier::EArg:
985 Size +=
986 std::max(a: FieldWidth,
987 b: 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
993 case analyze_format_string::ConversionSpecifier::aArg:
994 case analyze_format_string::ConversionSpecifier::AArg:
995 Size +=
996 std::max(a: FieldWidth,
997 b: 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1003 case analyze_format_string::ConversionSpecifier::sArg:
1004 case analyze_format_string::ConversionSpecifier::SArg:
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1009 case analyze_format_string::ConversionSpecifier::pArg:
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(a: FieldWidth, b: 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1018 case analyze_format_string::ConversionSpecifier::PercentArg:
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1036 case analyze_format_string::ConversionSpecifier::oArg:
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1038 case analyze_format_string::ConversionSpecifier::bArg:
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1041 case analyze_format_string::ConversionSpecifier::xArg:
1042 case analyze_format_string::ConversionSpecifier::XArg:
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1053 case analyze_format_string::ConversionSpecifier::aArg:
1054 case analyze_format_string::ConversionSpecifier::AArg:
1055 case analyze_format_string::ConversionSpecifier::eArg:
1056 case analyze_format_string::ConversionSpecifier::EArg:
1057 case analyze_format_string::ConversionSpecifier::fArg:
1058 case analyze_format_string::ConversionSpecifier::FArg:
1059 case analyze_format_string::ConversionSpecifier::gArg:
1060 case analyze_format_string::ConversionSpecifier::GArg:
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1080 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1091 case analyze_format_string::OptionalAmount::NotSpecified:
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1095 case analyze_format_string::ConversionSpecifier::dArg: // %d
1096 case analyze_format_string::ConversionSpecifier::DArg: // %D
1097 case analyze_format_string::ConversionSpecifier::iArg: // %i
1098 Precision = 1;
1099 break;
1100 case analyze_format_string::ConversionSpecifier::oArg: // %d
1101 case analyze_format_string::ConversionSpecifier::OArg: // %D
1102 case analyze_format_string::ConversionSpecifier::uArg: // %d
1103 case analyze_format_string::ConversionSpecifier::UArg: // %D
1104 case analyze_format_string::ConversionSpecifier::xArg: // %d
1105 case analyze_format_string::ConversionSpecifier::XArg: // %D
1106 Precision = 1;
1107 break;
1108 case analyze_format_string::ConversionSpecifier::fArg: // %f
1109 case analyze_format_string::ConversionSpecifier::FArg: // %F
1110 case analyze_format_string::ConversionSpecifier::eArg: // %e
1111 case analyze_format_string::ConversionSpecifier::EArg: // %E
1112 case analyze_format_string::ConversionSpecifier::gArg: // %g
1113 case analyze_format_string::ConversionSpecifier::GArg: // %G
1114 Precision = 6;
1115 break;
1116 case analyze_format_string::ConversionSpecifier::pArg: // %d
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1121 case analyze_format_string::OptionalAmount::Constant:
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(Val: FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(T: Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: FormatStrRef.find(C: 0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150namespace {
1151/// Helper class for buffer overflow/overread checking in fortified functions.
1152class FortifiedBufferChecker {
1153public:
1154 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1155 : S(S), TheCall(TheCall), FD(FD),
1156 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1157 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1158 SizeTypeWidth = TI.getTypeWidth(T: TI.getSizeType());
1159 }
1160
1161 std::optional<unsigned> TranslateIndex(unsigned Index) {
1162 // If we refer to a diagnose_as_builtin attribute, we need to change the
1163 // argument index to refer to the arguments of the called function. Unless
1164 // the index is out of bounds, which presumably means it's a variadic
1165 // function.
1166 if (!DABAttr)
1167 return Index;
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 unsigned NewIndex = Index < DABIndices
1170 ? DABAttr->argIndices_begin()[Index]
1171 : Index - DABIndices + FD->getNumParams();
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 std::optional<llvm::APSInt>
1178 ComputeExplicitObjectSizeArgument(unsigned Index) {
1179 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1180 if (!IndexOptional)
1181 return std::nullopt;
1182 unsigned NewIndex = *IndexOptional;
1183 Expr::EvalResult Result;
1184 Expr *SizeArg = TheCall->getArg(Arg: NewIndex);
1185 if (!SizeArg->EvaluateAsInt(Result, Ctx: S.getASTContext()))
1186 return std::nullopt;
1187 llvm::APSInt Integer = Result.Val.getInt();
1188 assert(Integer.isUnsigned() &&
1189 "size arg should be unsigned after implicit conversion to size_t");
1190 return Integer;
1191 }
1192
1193 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1194 // If the parameter has a pass_object_size attribute, then we should use its
1195 // (potentially) more strict checking mode. Otherwise, conservatively assume
1196 // type 0.
1197 int BOSType = 0;
1198 // This check can fail for variadic functions.
1199 if (Index < FD->getNumParams()) {
1200 if (const auto *POS =
1201 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1202 BOSType = POS->getType();
1203 }
1204
1205 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1206 if (!IndexOptional)
1207 return std::nullopt;
1208 unsigned NewIndex = *IndexOptional;
1209
1210 if (NewIndex >= TheCall->getNumArgs())
1211 return std::nullopt;
1212
1213 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1214 if (std::optional<uint64_t> ObjSize =
1215 ObjArg->tryEvaluateObjectSize(Ctx: S.getASTContext(), Type: BOSType)) {
1216 // Get the object size in the target's size_t width.
1217 return llvm::APSInt::getUnsigned(X: *ObjSize).extOrTrunc(width: SizeTypeWidth);
1218 }
1219 return std::nullopt;
1220 }
1221
1222 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1223 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1224 if (!IndexOptional)
1225 return std::nullopt;
1226 unsigned NewIndex = *IndexOptional;
1227
1228 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1229
1230 if (std::optional<uint64_t> Result =
1231 ObjArg->tryEvaluateStrLen(Ctx: S.getASTContext())) {
1232 // Add 1 for null byte.
1233 return llvm::APSInt::getUnsigned(X: *Result + 1).extOrTrunc(width: SizeTypeWidth);
1234 }
1235 return std::nullopt;
1236 }
1237
1238 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1239
1240 unsigned getBuiltinID() const {
1241 const FunctionDecl *UseDecl = FD;
1242 if (DABAttr) {
1243 UseDecl = DABAttr->getFunction();
1244 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1245 }
1246 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1247 }
1248
1249 /// Return function name after stripping __builtin_ and _chk affixes.
1250 std::string getFunctionName() const {
1251 unsigned ID = getBuiltinID();
1252 if (!ID) {
1253 // Use callee name directly if not a builtin.
1254 const FunctionDecl *Callee = TheCall->getDirectCallee();
1255 assert(Callee && "expected callee");
1256 return Callee->getName().str();
1257 }
1258 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1259 StringRef Ref = Name;
1260 // Strip __builtin___*_chk or __builtin_ prefix.
1261 if (!(Ref.consume_front(Prefix: "__builtin___") && Ref.consume_back(Suffix: "_chk")))
1262 Ref.consume_front(Prefix: "__builtin_");
1263 assert(!Ref.empty() && "expected non-empty function name");
1264 return Ref.str();
1265 }
1266
1267 /// Check for source buffer overread in memory functions.
1268 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1269 if (S.isConstantEvaluatedContext())
1270 return;
1271
1272 const Expr *SrcArg = TheCall->getArg(Arg: SrcArgIdx);
1273 const Expr *SizeArg = TheCall->getArg(Arg: SizeArgIdx);
1274 if (SrcArg->isInstantiationDependent() ||
1275 SizeArg->isInstantiationDependent())
1276 return;
1277
1278 std::optional<llvm::APSInt> CopyLen =
1279 ComputeExplicitObjectSizeArgument(Index: SizeArgIdx);
1280 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(Index: SrcArgIdx);
1281
1282 if (!CopyLen || !SrcBufSize)
1283 return;
1284
1285 // Warn only if copy length exceeds source buffer size.
1286 if (llvm::APSInt::compareValues(I1: *CopyLen, I2: *SrcBufSize) <= 0)
1287 return;
1288
1289 S.DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1290 PD: S.PDiag(DiagID: diag::warn_stringop_overread)
1291 << getFunctionName() << CopyLen->getZExtValue()
1292 << SrcBufSize->getZExtValue());
1293 }
1294
1295private:
1296 Sema &S;
1297 CallExpr *TheCall;
1298 FunctionDecl *FD;
1299 const DiagnoseAsBuiltinAttr *DABAttr;
1300 unsigned SizeTypeWidth;
1301};
1302} // anonymous namespace
1303
1304void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1305 CallExpr *TheCall) {
1306 if (TheCall->isInstantiationDependent() || isConstantEvaluatedContext())
1307 return;
1308
1309 FortifiedBufferChecker Checker(*this, FD, TheCall);
1310
1311 unsigned BuiltinID = Checker.getBuiltinID();
1312 if (!BuiltinID)
1313 return;
1314
1315 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1316
1317 std::optional<llvm::APSInt> SourceSize;
1318 std::optional<llvm::APSInt> DestinationSize;
1319 unsigned DiagID = 0;
1320
1321 switch (BuiltinID) {
1322 default:
1323 return;
1324 case Builtin::BI__builtin_strcat:
1325 case Builtin::BIstrcat:
1326 case Builtin::BI__builtin_stpcpy:
1327 case Builtin::BIstpcpy:
1328 case Builtin::BI__builtin_strcpy:
1329 case Builtin::BIstrcpy: {
1330 DiagID = diag::warn_fortify_strlen_overflow;
1331 SourceSize = Checker.ComputeStrLenArgument(Index: 1);
1332 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1333 break;
1334 }
1335
1336 case Builtin::BI__builtin___strcat_chk:
1337 case Builtin::BI__builtin___stpcpy_chk:
1338 case Builtin::BI__builtin___strcpy_chk: {
1339 DiagID = diag::warn_fortify_strlen_overflow;
1340 SourceSize = Checker.ComputeStrLenArgument(Index: 1);
1341 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1342 break;
1343 }
1344
1345 case Builtin::BIscanf:
1346 case Builtin::BIfscanf:
1347 case Builtin::BIsscanf: {
1348 unsigned FormatIndex = 1;
1349 unsigned DataIndex = 2;
1350 if (BuiltinID == Builtin::BIscanf) {
1351 FormatIndex = 0;
1352 DataIndex = 1;
1353 }
1354
1355 const auto *FormatExpr =
1356 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1357
1358 StringRef FormatStrRef;
1359 size_t StrLen;
1360 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1361 return;
1362
1363 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1364 unsigned SourceSize) {
1365 DiagID = diag::warn_fortify_scanf_overflow;
1366 unsigned Index = ArgIndex + DataIndex;
1367 std::string FunctionName = Checker.getFunctionName();
1368 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1369 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1370 << DestSize << SourceSize);
1371 };
1372
1373 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1374 return Checker.ComputeSizeArgument(Index: Index + DataIndex);
1375 };
1376 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1377 const char *FormatBytes = FormatStrRef.data();
1378 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1379 end: FormatBytes + StrLen, LO: getLangOpts(),
1380 Target: Context.getTargetInfo());
1381
1382 // Unlike the other cases, in this one we have already issued the diagnostic
1383 // here, so no need to continue (because unlike the other cases, here the
1384 // diagnostic refers to the argument number).
1385 return;
1386 }
1387
1388 case Builtin::BIsprintf:
1389 case Builtin::BI__builtin___sprintf_chk: {
1390 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1391 auto *FormatExpr = TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1392
1393 StringRef FormatStrRef;
1394 size_t StrLen;
1395 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1396 EstimateSizeFormatHandler H(FormatStrRef);
1397 const char *FormatBytes = FormatStrRef.data();
1398 if (!analyze_format_string::ParsePrintfString(
1399 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1400 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1401 DiagID = H.isKernelCompatible()
1402 ? diag::warn_format_overflow
1403 : diag::warn_format_overflow_non_kprintf;
1404 SourceSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1405 .extOrTrunc(width: SizeTypeWidth);
1406 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1407 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1408 } else {
1409 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1410 }
1411 break;
1412 }
1413 }
1414 return;
1415 }
1416 case Builtin::BI__builtin___memcpy_chk:
1417 case Builtin::BI__builtin___memmove_chk:
1418 case Builtin::BI__builtin___memset_chk:
1419 case Builtin::BI__builtin___strlcat_chk:
1420 case Builtin::BI__builtin___strlcpy_chk:
1421 case Builtin::BI__builtin___strncat_chk:
1422 case Builtin::BI__builtin___strncpy_chk:
1423 case Builtin::BI__builtin___stpncpy_chk:
1424 case Builtin::BI__builtin___memccpy_chk:
1425 case Builtin::BI__builtin___mempcpy_chk: {
1426 DiagID = diag::warn_builtin_chk_overflow;
1427 SourceSize =
1428 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 2);
1429 DestinationSize =
1430 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1431
1432 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1433 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1434 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1435 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1436 }
1437 break;
1438 }
1439
1440 case Builtin::BI__builtin___snprintf_chk:
1441 case Builtin::BI__builtin___vsnprintf_chk: {
1442 DiagID = diag::warn_builtin_chk_overflow;
1443 SourceSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1444 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(Index: 3);
1445 break;
1446 }
1447
1448 case Builtin::BIstrncat:
1449 case Builtin::BI__builtin_strncat:
1450 case Builtin::BIstrncpy:
1451 case Builtin::BI__builtin_strncpy:
1452 case Builtin::BIstpncpy:
1453 case Builtin::BI__builtin_stpncpy: {
1454 // Whether these functions overflow depends on the runtime strlen of the
1455 // string, not just the buffer size, so emitting the "always overflow"
1456 // diagnostic isn't quite right. We should still diagnose passing a buffer
1457 // size larger than the destination buffer though; this is a runtime abort
1458 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1459 DiagID = diag::warn_fortify_source_size_mismatch;
1460 SourceSize =
1461 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1462 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1463 break;
1464 }
1465
1466 case Builtin::BIbzero:
1467 case Builtin::BI__builtin_bzero:
1468 case Builtin::BImemcpy:
1469 case Builtin::BI__builtin_memcpy:
1470 case Builtin::BImemmove:
1471 case Builtin::BI__builtin_memmove:
1472 case Builtin::BImemset:
1473 case Builtin::BI__builtin_memset:
1474 case Builtin::BImempcpy:
1475 case Builtin::BI__builtin_mempcpy: {
1476 DiagID = diag::warn_fortify_source_overflow;
1477 SourceSize =
1478 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1479 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1480
1481 // Buffer overread doesn't make sense for memset/bzero.
1482 if (BuiltinID != Builtin::BImemset &&
1483 BuiltinID != Builtin::BI__builtin_memset &&
1484 BuiltinID != Builtin::BIbzero &&
1485 BuiltinID != Builtin::BI__builtin_bzero) {
1486 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1487 }
1488 break;
1489 }
1490 case Builtin::BIbcopy:
1491 case Builtin::BI__builtin_bcopy: {
1492 DiagID = diag::warn_fortify_source_overflow;
1493 SourceSize =
1494 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1495 DestinationSize = Checker.ComputeSizeArgument(Index: 1);
1496 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1497 break;
1498 }
1499
1500 // memchr(buf, val, size)
1501 case Builtin::BImemchr:
1502 case Builtin::BI__builtin_memchr: {
1503 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1504 return;
1505 }
1506
1507 // memcmp/bcmp(buf0, buf1, size)
1508 // Two checks since each buffer is read
1509 case Builtin::BImemcmp:
1510 case Builtin::BI__builtin_memcmp:
1511 case Builtin::BIbcmp:
1512 case Builtin::BI__builtin_bcmp: {
1513 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1514 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1515 return;
1516 }
1517 case Builtin::BIsnprintf:
1518 case Builtin::BI__builtin_snprintf:
1519 case Builtin::BIvsnprintf:
1520 case Builtin::BI__builtin_vsnprintf: {
1521 DiagID = diag::warn_fortify_source_size_mismatch;
1522 SourceSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1523 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1524 StringRef FormatStrRef;
1525 size_t StrLen;
1526 if (SourceSize &&
1527 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1528 EstimateSizeFormatHandler H(FormatStrRef);
1529 const char *FormatBytes = FormatStrRef.data();
1530 if (!analyze_format_string::ParsePrintfString(
1531 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1532 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1533 llvm::APSInt FormatSize =
1534 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1535 .extOrTrunc(width: SizeTypeWidth);
1536 if (FormatSize > *SourceSize && *SourceSize != 0) {
1537 unsigned TruncationDiagID =
1538 H.isKernelCompatible() ? diag::warn_format_truncation
1539 : diag::warn_format_truncation_non_kprintf;
1540 SmallString<16> SpecifiedSizeStr;
1541 SmallString<16> FormatSizeStr;
1542 SourceSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1543 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1544 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1545 PD: PDiag(DiagID: TruncationDiagID)
1546 << Checker.getFunctionName()
1547 << SpecifiedSizeStr << FormatSizeStr);
1548 }
1549 }
1550 }
1551 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1552 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1553 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1554 IdentifierInfo *FnInfo = FD->getIdentifier();
1555 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1556 }
1557 }
1558
1559 if (!SourceSize || !DestinationSize ||
1560 llvm::APSInt::compareValues(I1: *SourceSize, I2: *DestinationSize) <= 0)
1561 return;
1562
1563 std::string FunctionName = Checker.getFunctionName();
1564
1565 SmallString<16> DestinationStr;
1566 SmallString<16> SourceStr;
1567 DestinationSize->toString(Str&: DestinationStr, /*Radix=*/10);
1568 SourceSize->toString(Str&: SourceStr, /*Radix=*/10);
1569 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1570 PD: PDiag(DiagID)
1571 << FunctionName << DestinationStr << SourceStr);
1572}
1573
1574void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1575 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1576 return;
1577
1578 // Recognize the libc function by builtin identity rather than by name and
1579 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1580 // builtin id is attached to any file-scope, C-linkage declaration of umask
1581 // regardless of the libc's mode_t spelling -- including a hand-written
1582 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1583 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1584 if (FD->getBuiltinID() != Builtin::BIumask)
1585 return;
1586
1587 // umask(mode_t): warn when the constant-evaluated argument has bits set
1588 // outside the file-permission mask (0777). Those bits are ignored.
1589 if (TheCall->getNumArgs() != 1)
1590 return;
1591 Expr *Arg = TheCall->getArg(Arg: 0);
1592 if (!Arg->getType()->isIntegerType())
1593 return;
1594 Expr::EvalResult R;
1595 if (!Arg->EvaluateAsInt(Result&: R, Ctx: getASTContext()))
1596 return;
1597 // Operate on the raw two's-complement bit pattern so that negative literals
1598 // (which convert to large unsigned mode_t values) are caught.
1599 llvm::APInt RawValue = R.Val.getInt();
1600 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1601 llvm::APInt Extra = RawValue & ~Mask;
1602 if (Extra == 0)
1603 return;
1604 SmallString<16> ExtraStr;
1605 Extra.toString(Str&: ExtraStr, /*Radix=*/8, /*Signed=*/false);
1606 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fortify_umask_unused_bits)
1607 << ExtraStr;
1608}
1609
1610static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1611 Scope::ScopeFlags NeededScopeFlags,
1612 unsigned DiagID) {
1613 // Scopes aren't available during instantiation. Fortunately, builtin
1614 // functions cannot be template args so they cannot be formed through template
1615 // instantiation. Therefore checking once during the parse is sufficient.
1616 if (SemaRef.inTemplateInstantiation())
1617 return false;
1618
1619 Scope *S = SemaRef.getCurScope();
1620 while (S && !S->isSEHExceptScope())
1621 S = S->getParent();
1622 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1623 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1624 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1625 << DRE->getDecl()->getIdentifier();
1626 return true;
1627 }
1628
1629 return false;
1630}
1631
1632// In OpenCL, __builtin_alloca_* should return a pointer to address space
1633// that corresponds to the stack address space i.e private address space.
1634static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1635 QualType RT = TheCall->getType();
1636 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1637 "__builtin_alloca has invalid address space");
1638
1639 RT = RT->getPointeeType();
1640 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1641 TheCall->setType(S.Context.getPointerType(T: RT));
1642}
1643
1644static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1645 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1646 return true;
1647
1648 for (Expr *Arg : TheCall->arguments()) {
1649 // If argument is dependent on a template parameter, we can't resolve now.
1650 if (Arg->isTypeDependent() || Arg->isValueDependent())
1651 continue;
1652 // Reject void types.
1653 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1654 if (ArgTy->isVoidType())
1655 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1656 }
1657
1658 TheCall->setType(S.Context.getSizeType());
1659 return false;
1660}
1661
1662namespace {
1663enum PointerAuthOpKind {
1664 PAO_Strip,
1665 PAO_Sign,
1666 PAO_Auth,
1667 PAO_SignGeneric,
1668 PAO_Discriminator,
1669 PAO_BlendPointer,
1670 PAO_BlendInteger,
1671 PAO_BlendPC
1672};
1673}
1674
1675bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1676 if (getLangOpts().PointerAuthIntrinsics)
1677 return false;
1678
1679 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1680 return true;
1681}
1682
1683static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1684 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1685}
1686
1687static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1688 // Convert it to type 'int'.
1689 if (convertArgumentToType(S, Value&: Arg, Ty: S.Context.IntTy))
1690 return true;
1691
1692 // Value-dependent expressions are okay; wait for template instantiation.
1693 if (Arg->isValueDependent())
1694 return false;
1695
1696 unsigned KeyValue;
1697 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1698}
1699
1700bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1701 // Attempt to constant-evaluate the expression.
1702 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1703 if (!KeyValue) {
1704 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1705 << 0 << Arg->getSourceRange();
1706 return true;
1707 }
1708
1709 // Ask the target to validate the key parameter.
1710 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1711 llvm::SmallString<32> Value;
1712 {
1713 llvm::raw_svector_ostream Str(Value);
1714 Str << *KeyValue;
1715 }
1716
1717 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1718 << Value << Arg->getSourceRange();
1719 return true;
1720 }
1721
1722 Result = KeyValue->getZExtValue();
1723 return false;
1724}
1725
1726bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1727 PointerAuthDiscArgKind Kind,
1728 unsigned &IntVal) {
1729 if (!Arg) {
1730 IntVal = 0;
1731 return true;
1732 }
1733
1734 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1735 if (!Result) {
1736 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1737 return false;
1738 }
1739
1740 unsigned Max;
1741 bool IsAddrDiscArg = false;
1742
1743 switch (Kind) {
1744 case PointerAuthDiscArgKind::Addr:
1745 Max = 1;
1746 IsAddrDiscArg = true;
1747 break;
1748 case PointerAuthDiscArgKind::Extra:
1749 Max = PointerAuthQualifier::MaxDiscriminator;
1750 break;
1751 };
1752
1753 if (*Result < 0 || *Result > Max) {
1754 if (IsAddrDiscArg)
1755 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1756 << Result->getExtValue();
1757 else
1758 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1759 << Result->getExtValue() << Max;
1760
1761 return false;
1762 };
1763
1764 IntVal = Result->getZExtValue();
1765 return true;
1766}
1767
1768static std::pair<const ValueDecl *, CharUnits>
1769findConstantBaseAndOffset(Sema &S, Expr *E) {
1770 // Must evaluate as a pointer.
1771 Expr::EvalResult Result;
1772 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1773 return {nullptr, CharUnits()};
1774
1775 const auto *BaseDecl =
1776 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1777 if (!BaseDecl)
1778 return {nullptr, CharUnits()};
1779
1780 return {BaseDecl, Result.Val.getLValueOffset()};
1781}
1782
1783static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1784 bool RequireConstant = false) {
1785 if (Arg->hasPlaceholderType()) {
1786 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1787 if (R.isInvalid())
1788 return true;
1789 Arg = R.get();
1790 }
1791
1792 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1793 return OpKind != PAO_BlendInteger;
1794 };
1795 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1796 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1797 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1798 };
1799
1800 // Require the value to have the right range of type.
1801 QualType ExpectedTy;
1802 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1803 ExpectedTy = Arg->getType().getUnqualifiedType();
1804 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1805 ExpectedTy = S.Context.VoidPtrTy;
1806 } else if (AllowsInteger(OpKind) &&
1807 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1808 ExpectedTy = S.Context.getUIntPtrType();
1809
1810 } else {
1811 // Diagnose the failures.
1812 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1813 << unsigned(OpKind == PAO_Discriminator ? 1
1814 : OpKind == PAO_BlendPointer ? 2
1815 : OpKind == PAO_BlendInteger ? 3
1816 : OpKind == PAO_BlendPC ? 4
1817 : 0)
1818 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1819 << Arg->getType() << Arg->getSourceRange();
1820 return true;
1821 }
1822
1823 // Convert to that type. This should just be an lvalue-to-rvalue
1824 // conversion.
1825 if (convertArgumentToType(S, Value&: Arg, Ty: ExpectedTy))
1826 return true;
1827
1828 if (!RequireConstant) {
1829 // Warn about null pointers for non-generic sign and auth operations.
1830 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1831 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1832 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1833 ? diag::warn_ptrauth_sign_null_pointer
1834 : diag::warn_ptrauth_auth_null_pointer)
1835 << Arg->getSourceRange();
1836 }
1837
1838 return false;
1839 }
1840
1841 // Perform special checking on the arguments to ptrauth_sign_constant.
1842
1843 // The main argument.
1844 if (OpKind == PAO_Sign) {
1845 // Require the value we're signing to have a special form.
1846 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1847 bool Invalid;
1848
1849 // Must be rooted in a declaration reference.
1850 if (!BaseDecl)
1851 Invalid = true;
1852
1853 // If it's a function declaration, we can't have an offset.
1854 else if (isa<FunctionDecl>(Val: BaseDecl))
1855 Invalid = !Offset.isZero();
1856
1857 // Otherwise we're fine.
1858 else
1859 Invalid = false;
1860
1861 if (Invalid)
1862 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1863 return Invalid;
1864 }
1865
1866 // The discriminator argument.
1867 assert(OpKind == PAO_Discriminator);
1868
1869 // Must be a pointer or integer or blend thereof.
1870 Expr *Pointer = nullptr;
1871 Expr *Integer = nullptr;
1872 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1873 if (Call->getBuiltinCallee() ==
1874 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1875 Pointer = Call->getArg(Arg: 0);
1876 Integer = Call->getArg(Arg: 1);
1877 }
1878 }
1879 if (!Pointer && !Integer) {
1880 if (Arg->getType()->isPointerType())
1881 Pointer = Arg;
1882 else
1883 Integer = Arg;
1884 }
1885
1886 // Check the pointer.
1887 bool Invalid = false;
1888 if (Pointer) {
1889 assert(Pointer->getType()->isPointerType());
1890
1891 // TODO: if we're initializing a global, check that the address is
1892 // somehow related to what we're initializing. This probably will
1893 // never really be feasible and we'll have to catch it at link-time.
1894 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
1895 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
1896 Invalid = true;
1897 }
1898
1899 // Check the integer.
1900 if (Integer) {
1901 assert(Integer->getType()->isIntegerType());
1902 if (!Integer->isEvaluatable(Ctx: S.Context))
1903 Invalid = true;
1904 }
1905
1906 if (Invalid)
1907 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
1908 return Invalid;
1909}
1910
1911static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
1912 if (S.checkArgCount(Call, DesiredArgCount: 2))
1913 return ExprError();
1914 if (checkPointerAuthEnabled(S, E: Call))
1915 return ExprError();
1916 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
1917 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
1918 return ExprError();
1919
1920 Call->setType(Call->getArgs()[0]->getType());
1921 return Call;
1922}
1923
1924static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
1925 if (S.checkArgCount(Call, DesiredArgCount: 2))
1926 return ExprError();
1927 if (checkPointerAuthEnabled(S, E: Call))
1928 return ExprError();
1929 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
1930 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
1931 return ExprError();
1932
1933 Call->setType(S.Context.getUIntPtrType());
1934 return Call;
1935}
1936
1937static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
1938 if (S.checkArgCount(Call, DesiredArgCount: 2))
1939 return ExprError();
1940 if (checkPointerAuthEnabled(S, E: Call))
1941 return ExprError();
1942 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
1943 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
1944 return ExprError();
1945
1946 Call->setType(S.Context.getUIntPtrType());
1947 return Call;
1948}
1949
1950static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
1951 PointerAuthOpKind OpKind,
1952 bool RequireConstant) {
1953 if (S.checkArgCount(Call, DesiredArgCount: 3))
1954 return ExprError();
1955 if (checkPointerAuthEnabled(S, E: Call))
1956 return ExprError();
1957 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
1958 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1959 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
1960 RequireConstant))
1961 return ExprError();
1962
1963 Call->setType(Call->getArgs()[0]->getType());
1964 return Call;
1965}
1966
1967static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
1968 if (S.checkArgCount(Call, DesiredArgCount: 5))
1969 return ExprError();
1970 if (checkPointerAuthEnabled(S, E: Call))
1971 return ExprError();
1972 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1973 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1974 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1975 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1976 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
1977 return ExprError();
1978
1979 Call->setType(Call->getArgs()[0]->getType());
1980 return Call;
1981}
1982
1983static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call) {
1984 if (S.checkArgCount(Call, DesiredArgCount: 6))
1985 return ExprError();
1986 if (checkPointerAuthEnabled(S, E: Call))
1987 return ExprError();
1988 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1989 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1990 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1991 checkPointerAuthValue(S, Arg&: Call->getArgs()[3], OpKind: PAO_BlendPC) ||
1992 checkPointerAuthKey(S, Arg&: Call->getArgs()[4]) ||
1993 checkPointerAuthValue(S, Arg&: Call->getArgs()[5], OpKind: PAO_Discriminator))
1994 return ExprError();
1995
1996 // Validate that the oldKey is IA or IB, not DA or DB.
1997 // This enforces the constraint that auth_with_pc_and_resign only supports
1998 // IA/IB keys for authentication, as only those keys support the PC-based
1999 // signing instructions (paciasppc/pacibsppc).
2000 unsigned OldKey = 0;
2001 if (!S.checkConstantPointerAuthKey(Arg: Call->getArgs()[1], Result&: OldKey)) {
2002 using AK = PointerAuthSchema::ARM8_3Key;
2003 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2004 OldKey != static_cast<unsigned>(AK::ASIB)) {
2005 S.Diag(Loc: Call->getArgs()[1]->getExprLoc(),
2006 DiagID: diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2007 << OldKey << Call->getArgs()[1]->getSourceRange();
2008 return ExprError();
2009 }
2010 }
2011
2012 Call->setType(Call->getArgs()[0]->getType());
2013 return Call;
2014}
2015
2016static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
2017 if (S.checkArgCount(Call, DesiredArgCount: 6))
2018 return ExprError();
2019 if (checkPointerAuthEnabled(S, E: Call))
2020 return ExprError();
2021 const Expr *AddendExpr = Call->getArg(Arg: 5);
2022 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
2023 if (!AddendIsConstInt) {
2024 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
2025 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
2026 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
2027 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
2028 << FDecl->getDeclName() << Arg->getSourceRange();
2029 }
2030 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2031 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2032 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2033 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2034 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
2035 !AddendIsConstInt)
2036 return ExprError();
2037
2038 Call->setType(Call->getArgs()[0]->getType());
2039 return Call;
2040}
2041
2042static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
2043 if (checkPointerAuthEnabled(S, E: Call))
2044 return ExprError();
2045
2046 // We've already performed normal call type-checking.
2047 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
2048
2049 // Operand must be an ordinary or UTF-8 string literal.
2050 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
2051 if (!Literal || Literal->getCharByteWidth() != 1) {
2052 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
2053 << (Literal ? 1 : 0) << Arg->getSourceRange();
2054 return ExprError();
2055 }
2056
2057 return Call;
2058}
2059
2060static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
2061 if (S.checkArgCount(Call, DesiredArgCount: 1))
2062 return ExprError();
2063 Expr *FirstArg = Call->getArg(Arg: 0);
2064 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
2065 if (FirstValue.isInvalid())
2066 return ExprError();
2067 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
2068 QualType FirstArgType = FirstArg->getType();
2069 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2070 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
2071
2072 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2073 if (!FirstArgRecord) {
2074 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2075 << /*isPolymorphic=*/0 << FirstArgType;
2076 return ExprError();
2077 }
2078 if (S.RequireCompleteType(
2079 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
2080 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
2081 return ExprError();
2082 }
2083
2084 if (!FirstArgRecord->isPolymorphic()) {
2085 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2086 << /*isPolymorphic=*/1 << FirstArgRecord;
2087 return ExprError();
2088 }
2089 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
2090 Call->setType(ReturnType);
2091 return Call;
2092}
2093
2094static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
2095 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2096 return ExprError();
2097
2098 // Compute __builtin_launder's parameter type from the argument.
2099 // The parameter type is:
2100 // * The type of the argument if it's not an array or function type,
2101 // Otherwise,
2102 // * The decayed argument type.
2103 QualType ParamTy = [&]() {
2104 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
2105 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2106 return S.Context.getPointerType(T: Ty->getElementType());
2107 if (ArgTy->isFunctionType()) {
2108 return S.Context.getPointerType(T: ArgTy);
2109 }
2110 return ArgTy;
2111 }();
2112
2113 TheCall->setType(ParamTy);
2114
2115 auto DiagSelect = [&]() -> std::optional<unsigned> {
2116 if (!ParamTy->isPointerType())
2117 return 0;
2118 if (ParamTy->isFunctionPointerType())
2119 return 1;
2120 if (ParamTy->isVoidPointerType())
2121 return 2;
2122 return std::optional<unsigned>{};
2123 }();
2124 if (DiagSelect) {
2125 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
2126 << *DiagSelect << TheCall->getSourceRange();
2127 return ExprError();
2128 }
2129
2130 // We either have an incomplete class type, or we have a class template
2131 // whose instantiation has not been forced. Example:
2132 //
2133 // template <class T> struct Foo { T value; };
2134 // Foo<int> *p = nullptr;
2135 // auto *d = __builtin_launder(p);
2136 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
2137 DiagID: diag::err_incomplete_type))
2138 return ExprError();
2139
2140 assert(ParamTy->getPointeeType()->isObjectType() &&
2141 "Unhandled non-object pointer case");
2142
2143 InitializedEntity Entity =
2144 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
2145 ExprResult Arg =
2146 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
2147 if (Arg.isInvalid())
2148 return ExprError();
2149 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2150
2151 return TheCall;
2152}
2153
2154static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
2155 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2156 return ExprError();
2157
2158 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
2159 if (Arg.isInvalid())
2160 return ExprError();
2161 QualType ParamTy = Arg.get()->getType();
2162 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2163 TheCall->setType(S.Context.BoolTy);
2164
2165 // Only accept pointers to objects as arguments, which should have object
2166 // pointer or void pointer types.
2167 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2168 // LWG4138: Function pointer types not allowed
2169 if (PT->getPointeeType()->isFunctionType()) {
2170 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2171 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2172 << 1;
2173 return ExprError();
2174 }
2175 // Disallow VLAs too since those shouldn't be able to
2176 // be a template parameter for `std::is_within_lifetime`
2177 if (PT->getPointeeType()->isVariableArrayType()) {
2178 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2179 << 1 << "__builtin_is_within_lifetime";
2180 return ExprError();
2181 }
2182 } else {
2183 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2184 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2185 << 0;
2186 return ExprError();
2187 }
2188 return TheCall;
2189}
2190
2191static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2192 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2193 return ExprError();
2194
2195 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2196 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2197 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2198 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2199 << /*a pointer*/ 0;
2200 return ExprError();
2201 }
2202
2203 QualType T = Dest->getPointeeType();
2204 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2205 DiagID: diag::err_incomplete_type))
2206 return ExprError();
2207
2208 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2209 T->isIncompleteArrayType()) {
2210 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2211 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2212 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2213 return ExprError();
2214 }
2215
2216 TheCall->setType(Dest);
2217
2218 QualType Src = TheCall->getArg(Arg: 1)->getType();
2219 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2220 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2221 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2222 << /*the same*/ 3;
2223 return ExprError();
2224 }
2225
2226 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2227 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2228 if (Size.isInvalid())
2229 return ExprError();
2230
2231 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2232 if (Size.isInvalid())
2233 return ExprError();
2234 SizeExpr = Size.get();
2235 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2236
2237 return TheCall;
2238}
2239
2240// Emit an error and return true if the current object format type is in the
2241// list of unsupported types.
2242static bool CheckBuiltinTargetNotInUnsupported(
2243 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2244 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2245 llvm::Triple::ObjectFormatType CurObjFormat =
2246 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2247 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2248 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2249 << TheCall->getSourceRange();
2250 return true;
2251 }
2252 return false;
2253}
2254
2255// Emit an error and return true if the current architecture is not in the list
2256// of supported architectures.
2257static bool
2258CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2259 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2260 llvm::Triple::ArchType CurArch =
2261 S.getASTContext().getTargetInfo().getTriple().getArch();
2262 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2263 return false;
2264 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2265 << TheCall->getSourceRange();
2266 return true;
2267}
2268
2269static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2270 SourceLocation CallSiteLoc);
2271
2272bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2273 CallExpr *TheCall) {
2274 switch (TI.getTriple().getArch()) {
2275 default:
2276 // Some builtins don't require additional checking, so just consider these
2277 // acceptable.
2278 return false;
2279 case llvm::Triple::arm:
2280 case llvm::Triple::armeb:
2281 case llvm::Triple::thumb:
2282 case llvm::Triple::thumbeb:
2283 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2284 case llvm::Triple::aarch64:
2285 case llvm::Triple::aarch64_32:
2286 case llvm::Triple::aarch64_be:
2287 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2288 case llvm::Triple::bpfeb:
2289 case llvm::Triple::bpfel:
2290 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2291 case llvm::Triple::dxil:
2292 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2293 case llvm::Triple::hexagon:
2294 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2295 case llvm::Triple::mips:
2296 case llvm::Triple::mipsel:
2297 case llvm::Triple::mips64:
2298 case llvm::Triple::mips64el:
2299 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2300 case llvm::Triple::spirv:
2301 case llvm::Triple::spirv32:
2302 case llvm::Triple::spirv64:
2303 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2304 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2305 return false;
2306 case llvm::Triple::systemz:
2307 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2308 case llvm::Triple::x86:
2309 case llvm::Triple::x86_64:
2310 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2311 case llvm::Triple::ppc:
2312 case llvm::Triple::ppcle:
2313 case llvm::Triple::ppc64:
2314 case llvm::Triple::ppc64le:
2315 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2316 case llvm::Triple::amdgpu:
2317 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2318 case llvm::Triple::riscv32:
2319 case llvm::Triple::riscv64:
2320 case llvm::Triple::riscv32be:
2321 case llvm::Triple::riscv64be:
2322 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2323 case llvm::Triple::loongarch32:
2324 case llvm::Triple::loongarch64:
2325 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2326 TheCall);
2327 case llvm::Triple::wasm32:
2328 case llvm::Triple::wasm64:
2329 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2330 case llvm::Triple::nvptx:
2331 case llvm::Triple::nvptx64:
2332 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2333 }
2334}
2335
2336static bool isValidMathElementType(QualType T) {
2337 return T->isDependentType() ||
2338 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2339}
2340
2341// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2342// not a valid type, emit an error message and return true. Otherwise return
2343// false.
2344static bool
2345checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2346 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2347 int ArgOrdinal) {
2348 clang::QualType EltTy =
2349 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2350 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2351 : ArgTy;
2352
2353 switch (ArgTyRestr) {
2354 case Sema::EltwiseBuiltinArgTyRestriction::None:
2355 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2356 !isValidMathElementType(T: ArgTy)) {
2357 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2358 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2359 << ArgTy;
2360 }
2361 break;
2362 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2363 if (!EltTy->isRealFloatingType()) {
2364 // FIXME: make diagnostic's wording correct for matrices
2365 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2366 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2367 << /* floating-point */ 1 << ArgTy;
2368 }
2369 break;
2370 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2371 if (!EltTy->isIntegerType()) {
2372 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2373 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2374 << /* no fp */ 0 << ArgTy;
2375 }
2376 break;
2377 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2378 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2379 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2380 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2381 << /* or fp */ 1 << ArgTy;
2382 }
2383 break;
2384 }
2385
2386 return false;
2387}
2388
2389/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2390/// This checks that the target supports the builtin and that the string
2391/// argument is constant and valid.
2392static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2393 const TargetInfo *AuxTI, unsigned BuiltinID) {
2394 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2395 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2396 "Expecting __builtin_cpu_...");
2397
2398 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2399 const TargetInfo *TheTI = &TI;
2400 auto SupportsBI = [=](const TargetInfo *TInfo) {
2401 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2402 (!IsCPUSupports && TInfo->supportsCpuIs()));
2403 };
2404 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2405 TheTI = AuxTI;
2406
2407 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2408 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2409 return S.Diag(Loc: TheCall->getBeginLoc(),
2410 DiagID: TI.getTriple().isOSAIX()
2411 ? diag::err_builtin_aix_os_unsupported
2412 : diag::err_builtin_target_unsupported)
2413 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2414
2415 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2416 // Check if the argument is a string literal.
2417 if (!isa<StringLiteral>(Val: Arg))
2418 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2419 << Arg->getSourceRange();
2420
2421 // Check the contents of the string.
2422 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2423 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2424 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2425 << Arg->getSourceRange();
2426 return false;
2427 }
2428 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2429 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2430 << Arg->getSourceRange();
2431 return false;
2432}
2433
2434/// Checks that __builtin_bswapg was called with a single argument, which is an
2435/// unsigned integer, and overrides the return value type to the integer type.
2436static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2437 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2438 return true;
2439 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2440 if (ArgRes.isInvalid())
2441 return true;
2442
2443 Expr *Arg = ArgRes.get();
2444 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2445 if (Arg->isTypeDependent())
2446 return false;
2447
2448 QualType ArgTy = Arg->getType();
2449
2450 if (!ArgTy->isIntegerType()) {
2451 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2452 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2453 << ArgTy;
2454 return true;
2455 }
2456 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2457 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2458 BT->getNumBits() != 1) {
2459 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2460 << ArgTy << BT->getNumBits();
2461 return true;
2462 }
2463 }
2464 TheCall->setType(ArgTy);
2465 return false;
2466}
2467
2468/// Checks that __builtin_bitreverseg was called with a single argument, which
2469/// is an integer
2470static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2471 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2472 return true;
2473 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2474 if (ArgRes.isInvalid())
2475 return true;
2476
2477 Expr *Arg = ArgRes.get();
2478 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2479 if (Arg->isTypeDependent())
2480 return false;
2481
2482 QualType ArgTy = Arg->getType();
2483
2484 if (!ArgTy->isIntegerType()) {
2485 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2486 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2487 << ArgTy;
2488 return true;
2489 }
2490 TheCall->setType(ArgTy);
2491 return false;
2492}
2493
2494/// Checks that __builtin_popcountg was called with a single argument, which is
2495/// an unsigned integer.
2496static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2497 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2498 return true;
2499
2500 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2501 if (ArgRes.isInvalid())
2502 return true;
2503
2504 Expr *Arg = ArgRes.get();
2505 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2506
2507 QualType ArgTy = Arg->getType();
2508
2509 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2510 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2511 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2512 << ArgTy;
2513 return true;
2514 }
2515 return false;
2516}
2517
2518/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2519/// argument and return either int, bool, or the argument type.
2520static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2521 QualType ReturnType) {
2522 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2523 return true;
2524
2525 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2526 if (ArgRes.isInvalid())
2527 return true;
2528
2529 Expr *Arg = ArgRes.get();
2530 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2531
2532 QualType ArgTy = Arg->getType();
2533 // C23 stdbit.h functions do not permit bool or enumeration types.
2534 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2535 return S.Diag(Loc: Arg->getBeginLoc(),
2536 DiagID: diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2537 << 1 /*1st argument*/ << ArgTy;
2538 if (!ArgTy->isUnsignedIntegerType())
2539 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_invalid_arg_type)
2540 << 1 /*1st argument*/ << ArgTy;
2541
2542 // For builtins returning unsigned int, verify the argument's bit width fits.
2543 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2544 // produce a count that overflows the return type.
2545 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2546 uint64_t ArgWidth = S.Context.getIntWidth(T: ArgTy);
2547 uint64_t ReturnTypeWidth = S.Context.getIntWidth(T: S.Context.UnsignedIntTy);
2548 if (!llvm::isUIntN(N: ReturnTypeWidth, x: ArgWidth))
2549 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_result_overflow)
2550 << ArgTy;
2551 }
2552
2553 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2554 return false;
2555}
2556
2557/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2558/// an unsigned integer, and an optional second argument, which is promoted to
2559/// an 'int'.
2560static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2561 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2562 return true;
2563
2564 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2565 if (Arg0Res.isInvalid())
2566 return true;
2567
2568 Expr *Arg0 = Arg0Res.get();
2569 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2570
2571 QualType Arg0Ty = Arg0->getType();
2572
2573 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2574 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2575 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2576 << Arg0Ty;
2577 return true;
2578 }
2579
2580 if (TheCall->getNumArgs() > 1) {
2581 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2582 if (Arg1Res.isInvalid())
2583 return true;
2584
2585 Expr *Arg1 = Arg1Res.get();
2586 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2587
2588 QualType Arg1Ty = Arg1->getType();
2589
2590 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2591 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2592 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2593 return true;
2594 }
2595 }
2596
2597 return false;
2598}
2599
2600class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2601 unsigned ArgIndex;
2602 bool OnlyUnsigned;
2603
2604 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2605 QualType T) {
2606 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2607 << ArgIndex << /*scalar*/ 1
2608 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2609 << /*no fp*/ 0 << T;
2610 }
2611
2612public:
2613 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2614 : ContextualImplicitConverter(/*Suppress=*/false,
2615 /*SuppressConversion=*/true),
2616 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2617
2618 bool match(QualType T) override {
2619 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2620 }
2621
2622 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2623 QualType T) override {
2624 return emitError(S, Loc, T);
2625 }
2626
2627 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2628 QualType T) override {
2629 return emitError(S, Loc, T);
2630 }
2631
2632 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2633 QualType T,
2634 QualType ConvTy) override {
2635 return emitError(S, Loc, T);
2636 }
2637
2638 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2639 QualType ConvTy) override {
2640 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2641 }
2642
2643 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2644 QualType T) override {
2645 return emitError(S, Loc, T);
2646 }
2647
2648 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2649 QualType ConvTy) override {
2650 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2651 }
2652
2653 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2654 QualType T,
2655 QualType ConvTy) override {
2656 llvm_unreachable("conversion functions are permitted");
2657 }
2658};
2659
2660/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2661/// arguments, that the first argument is an unsigned integer type, and that
2662/// the second argument is an integer type.
2663static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2664 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2665 return true;
2666
2667 // First argument (value to rotate) must be unsigned integer type.
2668 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2669 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2670 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2671 if (Arg0Res.isInvalid())
2672 return true;
2673
2674 Expr *Arg0 = Arg0Res.get();
2675 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2676
2677 QualType Arg0Ty = Arg0->getType();
2678 if (!Arg0Ty->isUnsignedIntegerType())
2679 return true;
2680
2681 // Second argument (rotation count) must be integer type.
2682 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2683 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2684 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2685 if (Arg1Res.isInvalid())
2686 return true;
2687
2688 Expr *Arg1 = Arg1Res.get();
2689 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2690
2691 QualType Arg1Ty = Arg1->getType();
2692 if (!Arg1Ty->isIntegerType())
2693 return true;
2694
2695 TheCall->setType(Arg0Ty);
2696 return false;
2697}
2698
2699static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2700 unsigned Pos, bool AllowConst,
2701 bool AllowAS) {
2702 QualType MaskTy = MaskArg->getType();
2703 if (!MaskTy->isExtVectorBoolType())
2704 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2705 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2706 << MaskTy;
2707
2708 QualType PtrTy = PtrArg->getType();
2709 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2710 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2711 << Pos << "scalar pointer";
2712
2713 QualType PointeeTy = PtrTy->getPointeeType();
2714 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2715 (!AllowConst && PointeeTy.isConstQualified()) ||
2716 (!AllowAS && PointeeTy.hasAddressSpace())) {
2717 QualType Target =
2718 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2719 return S.Diag(Loc: PtrArg->getExprLoc(),
2720 DiagID: diag::err_typecheck_convert_incompatible)
2721 << PtrTy << Target << /*different qualifiers=*/5
2722 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2723 << PtrTy << Target;
2724 }
2725 return false;
2726}
2727
2728static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2729 bool TypeDependent = false;
2730 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2731 ExprResult Converted =
2732 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2733 if (Converted.isInvalid())
2734 return true;
2735 TheCall->setArg(Arg, ArgExpr: Converted.get());
2736 TypeDependent |= Converted.get()->isTypeDependent();
2737 }
2738
2739 if (TypeDependent)
2740 TheCall->setType(S.Context.DependentTy);
2741 return false;
2742}
2743
2744static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2745 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2746 return ExprError();
2747
2748 if (ConvertMaskedBuiltinArgs(S, TheCall))
2749 return ExprError();
2750
2751 Expr *MaskArg = TheCall->getArg(Arg: 0);
2752 Expr *PtrArg = TheCall->getArg(Arg: 1);
2753 if (TheCall->isTypeDependent())
2754 return TheCall;
2755
2756 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2757 AllowAS: TheCall->getBuiltinCallee() ==
2758 Builtin::BI__builtin_masked_load))
2759 return ExprError();
2760
2761 QualType MaskTy = MaskArg->getType();
2762 QualType PtrTy = PtrArg->getType();
2763 QualType PointeeTy = PtrTy->getPointeeType();
2764 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2765
2766 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2767 NumElts: MaskVecTy->getNumElements());
2768 if (TheCall->getNumArgs() == 3) {
2769 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2770 QualType PassThruTy = PassThruArg->getType();
2771 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2772 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2773 << /* third argument */ 3 << RetTy;
2774 }
2775
2776 TheCall->setType(RetTy);
2777 return TheCall;
2778}
2779
2780static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2781 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2782 return ExprError();
2783
2784 if (ConvertMaskedBuiltinArgs(S, TheCall))
2785 return ExprError();
2786
2787 Expr *MaskArg = TheCall->getArg(Arg: 0);
2788 Expr *ValArg = TheCall->getArg(Arg: 1);
2789 Expr *PtrArg = TheCall->getArg(Arg: 2);
2790 if (TheCall->isTypeDependent())
2791 return TheCall;
2792
2793 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2794 AllowAS: TheCall->getBuiltinCallee() ==
2795 Builtin::BI__builtin_masked_store))
2796 return ExprError();
2797
2798 QualType MaskTy = MaskArg->getType();
2799 QualType PtrTy = PtrArg->getType();
2800 QualType ValTy = ValArg->getType();
2801 if (!ValTy->isVectorType())
2802 return ExprError(
2803 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2804 << 2 << "vector");
2805
2806 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2807 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2808
2809 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2810 return ExprError(
2811 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2812 << S.getASTContext().BuiltinInfo.getQuotedName(
2813 ID: TheCall->getBuiltinCallee())
2814 << MaskTy << ValTy);
2815 }
2816
2817 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2818 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2819 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2820 DiagID: diag::err_vec_builtin_incompatible_vector)
2821 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2822 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2823 TheCall->getArg(Arg: 1)->getEndLoc()));
2824
2825 TheCall->setType(S.Context.VoidTy);
2826 return TheCall;
2827}
2828
2829static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2830 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2831 return ExprError();
2832
2833 if (ConvertMaskedBuiltinArgs(S, TheCall))
2834 return ExprError();
2835
2836 Expr *MaskArg = TheCall->getArg(Arg: 0);
2837 Expr *IdxArg = TheCall->getArg(Arg: 1);
2838 Expr *PtrArg = TheCall->getArg(Arg: 2);
2839 if (TheCall->isTypeDependent())
2840 return TheCall;
2841
2842 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2843 /*AllowAS=*/true))
2844 return ExprError();
2845
2846 QualType IdxTy = IdxArg->getType();
2847 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2848 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2849 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2850 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2851 << IdxTy;
2852
2853 QualType MaskTy = MaskArg->getType();
2854 QualType PtrTy = PtrArg->getType();
2855 QualType PointeeTy = PtrTy->getPointeeType();
2856 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2857 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2858 return ExprError(
2859 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2860 << S.getASTContext().BuiltinInfo.getQuotedName(
2861 ID: TheCall->getBuiltinCallee())
2862 << MaskTy << IdxTy);
2863
2864 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2865 NumElts: MaskVecTy->getNumElements());
2866 if (TheCall->getNumArgs() == 4) {
2867 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2868 QualType PassThruTy = PassThruArg->getType();
2869 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2870 return S.Diag(Loc: PassThruArg->getExprLoc(),
2871 DiagID: diag::err_vec_masked_load_store_ptr)
2872 << /* fourth argument */ 4 << RetTy;
2873 }
2874
2875 TheCall->setType(RetTy);
2876 return TheCall;
2877}
2878
2879static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2880 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2881 return ExprError();
2882
2883 if (ConvertMaskedBuiltinArgs(S, TheCall))
2884 return ExprError();
2885
2886 Expr *MaskArg = TheCall->getArg(Arg: 0);
2887 Expr *IdxArg = TheCall->getArg(Arg: 1);
2888 Expr *ValArg = TheCall->getArg(Arg: 2);
2889 Expr *PtrArg = TheCall->getArg(Arg: 3);
2890 if (TheCall->isTypeDependent())
2891 return TheCall;
2892
2893 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
2894 /*AllowAS=*/true))
2895 return ExprError();
2896
2897 QualType IdxTy = IdxArg->getType();
2898 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2899 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2900 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2901 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2902 << IdxTy;
2903
2904 QualType ValTy = ValArg->getType();
2905 QualType MaskTy = MaskArg->getType();
2906 QualType PtrTy = PtrArg->getType();
2907
2908 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2909 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2910 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2911 return ExprError(
2912 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2913 << S.getASTContext().BuiltinInfo.getQuotedName(
2914 ID: TheCall->getBuiltinCallee())
2915 << MaskTy << IdxTy);
2916 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2917 return ExprError(
2918 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2919 << S.getASTContext().BuiltinInfo.getQuotedName(
2920 ID: TheCall->getBuiltinCallee())
2921 << MaskTy << ValTy);
2922
2923 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2924 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2925 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2926 DiagID: diag::err_vec_builtin_incompatible_vector)
2927 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2928 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2929 TheCall->getArg(Arg: 1)->getEndLoc()));
2930
2931 TheCall->setType(S.Context.VoidTy);
2932 return TheCall;
2933}
2934
2935static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
2936 SourceLocation Loc = TheCall->getBeginLoc();
2937 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2938 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2939
2940 if (Args.size() == 0) {
2941 S.Diag(Loc: TheCall->getBeginLoc(),
2942 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2943 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2944 << /*is_non_object=*/0 << TheCall->getSourceRange();
2945 return ExprError();
2946 }
2947
2948 QualType FuncT = Args[0]->getType();
2949
2950 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2951 if (Args.size() < 2) {
2952 S.Diag(Loc: TheCall->getBeginLoc(),
2953 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2954 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2955 << /*is_non_object=*/0 << TheCall->getSourceRange();
2956 return ExprError();
2957 }
2958
2959 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2960 QualType ObjectT = Args[1]->getType();
2961
2962 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2963 return ExprError();
2964
2965 ExprResult ObjectArg = [&]() -> ExprResult {
2966 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2967 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2968 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2969 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2970 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2971 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2972 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
2973 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
2974 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
2975 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
2976 return Args[1];
2977 }
2978
2979 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2980 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2981 // reference_wrapper;
2982 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2983 if (RD->isInStdNamespace() &&
2984 RD->getDeclName().getAsString() == "reference_wrapper") {
2985 CXXScopeSpec SS;
2986 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
2987 UnqualifiedId GetID;
2988 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
2989
2990 ExprResult MemExpr = S.ActOnMemberAccessExpr(
2991 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
2992 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
2993
2994 if (MemExpr.isInvalid())
2995 return ExprError();
2996
2997 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
2998 }
2999 }
3000
3001 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3002 // class T and t1 does not satisfy the previous two items;
3003
3004 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
3005 }();
3006
3007 if (ObjectArg.isInvalid())
3008 return ExprError();
3009
3010 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
3011 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
3012 if (BinOp.isInvalid())
3013 return ExprError();
3014
3015 if (MPT->isMemberDataPointer())
3016 return BinOp;
3017
3018 auto *MemCall = new (S.Context)
3019 ParenExpr(SourceLocation(), SourceLocation(), BinOp.get());
3020
3021 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
3022 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
3023 }
3024 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
3025 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
3026}
3027
3028// Performs a similar job to Sema::UsualUnaryConversions, but without any
3029// implicit promotion of integral/enumeration types.
3030static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
3031 // First, convert to an r-value.
3032 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
3033 if (Res.isInvalid())
3034 return ExprError();
3035
3036 // Promote floating-point types.
3037 return S.UsualUnaryFPConversions(E: Res.get());
3038}
3039
3040static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
3041 if (const auto *TyA = VecTy->getAs<VectorType>())
3042 return TyA->getElementType();
3043 if (VecTy->isSizelessVectorType())
3044 return VecTy->getSizelessVectorEltType(Ctx: Context);
3045 return QualType();
3046}
3047
3048ExprResult
3049Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3050 CallExpr *TheCall) {
3051 ExprResult TheCallResult(TheCall);
3052
3053 // Find out if any arguments are required to be integer constant expressions.
3054 unsigned ICEArguments = 0;
3055 ASTContext::GetBuiltinTypeError Error;
3056 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
3057 if (Error != ASTContext::GE_None)
3058 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3059
3060 // If any arguments are required to be ICE's, check and diagnose.
3061 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3062 // Skip arguments not required to be ICE's.
3063 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3064
3065 llvm::APSInt Result;
3066 // If we don't have enough arguments, continue so we can issue better
3067 // diagnostic in checkArgCount(...)
3068 if (ArgNo < TheCall->getNumArgs() &&
3069 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
3070 return true;
3071 ICEArguments &= ~(1 << ArgNo);
3072 }
3073
3074 FPOptions FPO;
3075 switch (BuiltinID) {
3076 case Builtin::BI__builtin___get_unsafe_stack_start:
3077 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3078 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3079 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3080 << "__safestack_get_unsafe_stack_bottom";
3081 break;
3082 case Builtin::BI__builtin___get_unsafe_stack_top:
3083 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3084 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3085 << "__safestack_get_unsafe_stack_top";
3086 break;
3087 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3088 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3089 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3090 << "__safestack_get_unsafe_stack_ptr";
3091 break;
3092 case Builtin::BI__builtin_cpu_supports:
3093 case Builtin::BI__builtin_cpu_is:
3094 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
3095 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
3096 return ExprError();
3097 break;
3098 case Builtin::BI__builtin_cpu_init:
3099 if (!Context.getTargetInfo().supportsCpuInit()) {
3100 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3101 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3102 return ExprError();
3103 }
3104 break;
3105 case Builtin::BI__builtin___CFStringMakeConstantString:
3106 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3107 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3108 if (CheckBuiltinTargetNotInUnsupported(
3109 S&: *this, BuiltinID, TheCall,
3110 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3111 return ExprError();
3112 assert(TheCall->getNumArgs() == 1 &&
3113 "Wrong # arguments to builtin CFStringMakeConstantString");
3114 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
3115 return ExprError();
3116 break;
3117 case Builtin::BI__builtin_ms_va_start:
3118 case Builtin::BI__builtin_zos_va_start:
3119 case Builtin::BI__builtin_stdarg_start:
3120 case Builtin::BI__builtin_va_start:
3121 case Builtin::BI__builtin_c23_va_start:
3122 if (BuiltinVAStart(BuiltinID, TheCall))
3123 return ExprError();
3124 break;
3125 case Builtin::BI__va_start: {
3126 switch (Context.getTargetInfo().getTriple().getArch()) {
3127 case llvm::Triple::aarch64:
3128 case llvm::Triple::arm:
3129 case llvm::Triple::thumb:
3130 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
3131 return ExprError();
3132 break;
3133 default:
3134 if (BuiltinVAStart(BuiltinID, TheCall))
3135 return ExprError();
3136 break;
3137 }
3138 break;
3139 }
3140
3141 // The acquire, release, and no fence variants are ARM and AArch64 only.
3142 case Builtin::BI_interlockedbittestandset_acq:
3143 case Builtin::BI_interlockedbittestandset_rel:
3144 case Builtin::BI_interlockedbittestandset_nf:
3145 case Builtin::BI_interlockedbittestandreset_acq:
3146 case Builtin::BI_interlockedbittestandreset_rel:
3147 case Builtin::BI_interlockedbittestandreset_nf:
3148 if (CheckBuiltinTargetInSupported(
3149 S&: *this, TheCall,
3150 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3151 return ExprError();
3152 break;
3153
3154 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3155 case Builtin::BI_bittest64:
3156 case Builtin::BI_bittestandcomplement64:
3157 case Builtin::BI_bittestandreset64:
3158 case Builtin::BI_bittestandset64:
3159 case Builtin::BI_interlockedbittestandreset64:
3160 case Builtin::BI_interlockedbittestandset64:
3161 if (CheckBuiltinTargetInSupported(
3162 S&: *this, TheCall,
3163 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3164 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3165 return ExprError();
3166 break;
3167
3168 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3169 case Builtin::BI_interlockedbittestandreset64_acq:
3170 case Builtin::BI_interlockedbittestandreset64_rel:
3171 case Builtin::BI_interlockedbittestandreset64_nf:
3172 case Builtin::BI_interlockedbittestandset64_acq:
3173 case Builtin::BI_interlockedbittestandset64_rel:
3174 case Builtin::BI_interlockedbittestandset64_nf:
3175 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
3176 return ExprError();
3177 break;
3178
3179 case Builtin::BI__builtin_set_flt_rounds:
3180 if (CheckBuiltinTargetInSupported(
3181 S&: *this, TheCall,
3182 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3183 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3184 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3185 llvm::Triple::ppc64le}))
3186 return ExprError();
3187 break;
3188
3189 case Builtin::BI__builtin_isgreater:
3190 case Builtin::BI__builtin_isgreaterequal:
3191 case Builtin::BI__builtin_isless:
3192 case Builtin::BI__builtin_islessequal:
3193 case Builtin::BI__builtin_islessgreater:
3194 case Builtin::BI__builtin_isunordered:
3195 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3196 return ExprError();
3197 break;
3198 case Builtin::BI__builtin_fpclassify:
3199 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
3200 return ExprError();
3201 break;
3202 case Builtin::BI__builtin_isfpclass:
3203 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
3204 return ExprError();
3205 break;
3206 case Builtin::BI__builtin_isfinite:
3207 case Builtin::BI__builtin_isinf:
3208 case Builtin::BI__builtin_isinf_sign:
3209 case Builtin::BI__builtin_isnan:
3210 case Builtin::BI__builtin_issignaling:
3211 case Builtin::BI__builtin_isnormal:
3212 case Builtin::BI__builtin_issubnormal:
3213 case Builtin::BI__builtin_iszero:
3214 case Builtin::BI__builtin_signbit:
3215 case Builtin::BI__builtin_signbitf:
3216 case Builtin::BI__builtin_signbitl:
3217 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
3218 return ExprError();
3219 break;
3220 case Builtin::BI__builtin_shufflevector:
3221 return BuiltinShuffleVector(TheCall);
3222 // TheCall will be freed by the smart pointer here, but that's fine, since
3223 // BuiltinShuffleVector guts it, but then doesn't release it.
3224 case Builtin::BI__builtin_masked_load:
3225 case Builtin::BI__builtin_masked_expand_load:
3226 return BuiltinMaskedLoad(S&: *this, TheCall);
3227 case Builtin::BI__builtin_masked_store:
3228 case Builtin::BI__builtin_masked_compress_store:
3229 return BuiltinMaskedStore(S&: *this, TheCall);
3230 case Builtin::BI__builtin_masked_gather:
3231 return BuiltinMaskedGather(S&: *this, TheCall);
3232 case Builtin::BI__builtin_masked_scatter:
3233 return BuiltinMaskedScatter(S&: *this, TheCall);
3234 case Builtin::BI__builtin_invoke:
3235 return BuiltinInvoke(S&: *this, TheCall);
3236 case Builtin::BI__builtin_prefetch:
3237 if (BuiltinPrefetch(TheCall))
3238 return ExprError();
3239 break;
3240 case Builtin::BI__builtin_alloca_with_align:
3241 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3242 if (BuiltinAllocaWithAlign(TheCall))
3243 return ExprError();
3244 [[fallthrough]];
3245 case Builtin::BI__builtin_alloca:
3246 case Builtin::BI__builtin_alloca_uninitialized:
3247 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3248 << TheCall->getDirectCallee();
3249 if (getLangOpts().OpenCL) {
3250 builtinAllocaAddrSpace(S&: *this, TheCall);
3251 }
3252 break;
3253 case Builtin::BI__builtin_infer_alloc_token:
3254 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3255 return ExprError();
3256 break;
3257 case Builtin::BI__arithmetic_fence:
3258 if (BuiltinArithmeticFence(TheCall))
3259 return ExprError();
3260 break;
3261 case Builtin::BI__assume:
3262 case Builtin::BI__builtin_assume:
3263 if (BuiltinAssume(TheCall))
3264 return ExprError();
3265 break;
3266 case Builtin::BI__builtin_assume_aligned:
3267 if (BuiltinAssumeAligned(TheCall))
3268 return ExprError();
3269 break;
3270 case Builtin::BI__builtin_dynamic_object_size:
3271 case Builtin::BI__builtin_object_size:
3272 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3273 return ExprError();
3274 break;
3275 case Builtin::BI__builtin_longjmp:
3276 if (BuiltinLongjmp(TheCall))
3277 return ExprError();
3278 break;
3279 case Builtin::BI__builtin_setjmp:
3280 if (BuiltinSetjmp(TheCall))
3281 return ExprError();
3282 break;
3283 case Builtin::BI__builtin_complex:
3284 if (BuiltinComplex(TheCall))
3285 return ExprError();
3286 break;
3287 case Builtin::BI__builtin_classify_type:
3288 case Builtin::BI__builtin_constant_p: {
3289 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3290 return true;
3291 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3292 if (Arg.isInvalid()) return true;
3293 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3294 TheCall->setType(Context.IntTy);
3295 break;
3296 }
3297 case Builtin::BI__builtin_launder:
3298 return BuiltinLaunder(S&: *this, TheCall);
3299 case Builtin::BI__builtin_is_within_lifetime:
3300 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3301 case Builtin::BI__builtin_trivially_relocate:
3302 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3303 case Builtin::BI__builtin_clear_padding: {
3304 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3305 return ExprError();
3306
3307 const Expr *PtrArg = TheCall->getArg(Arg: 0);
3308 const QualType PtrArgType = PtrArg->getType();
3309 if (!PtrArgType->isPointerType()) {
3310 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
3311 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3312 << "pointer";
3313 return ExprError();
3314 }
3315 QualType PointeeType = PtrArgType->getPointeeType();
3316 if (PointeeType.isConstQualified()) {
3317 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_assign_const)
3318 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3319 return ExprError();
3320 }
3321 if (RequireCompleteType(Loc: PtrArg->getBeginLoc(), T: PointeeType,
3322 DiagID: diag::err_typecheck_decl_incomplete_type))
3323 return ExprError();
3324
3325 // For non trivially copyable types, we try to match gcc's behaviour.
3326 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3327 // object, either a local variable or a function parameter passed by value
3328 auto IsAddrOfDeclExpr = [&]() {
3329 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Ctx: Context);
3330 const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: Inner);
3331 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3332 return false;
3333
3334 const Expr *Operand =
3335 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Ctx: Context);
3336 const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Operand);
3337 if (!DeclRef)
3338 return false;
3339
3340 const auto *VarDecl = dyn_cast<::clang::VarDecl>(Val: DeclRef->getDecl());
3341 if (!VarDecl || VarDecl->getType()->isReferenceType())
3342 return false;
3343
3344 // matching GCC behaviour
3345 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3346 QualType VarQType = VarDecl->getType();
3347 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3348 Context.hasSameUnqualifiedType(T1: PointeeType, T2: VarQType);
3349 };
3350
3351 if (!PointeeType.isTriviallyCopyableType(Context) &&
3352 !PointeeType->isAtomicType() // _Atomic is not copyable
3353 && !IsAddrOfDeclExpr()) {
3354 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_needs_trivial_copy)
3355 << PtrArg->getType() << PtrArg->getSourceRange();
3356 return ExprError();
3357 }
3358
3359 if (auto *Record = PointeeType->getAsRecordDecl();
3360 Record && Record->hasFlexibleArrayMember()) {
3361 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_no_flexible_array)
3362 << PointeeType << PtrArg->getSourceRange();
3363 return ExprError();
3364 }
3365
3366 break;
3367 }
3368 case Builtin::BI__sync_fetch_and_add:
3369 case Builtin::BI__sync_fetch_and_add_1:
3370 case Builtin::BI__sync_fetch_and_add_2:
3371 case Builtin::BI__sync_fetch_and_add_4:
3372 case Builtin::BI__sync_fetch_and_add_8:
3373 case Builtin::BI__sync_fetch_and_add_16:
3374 case Builtin::BI__sync_fetch_and_sub:
3375 case Builtin::BI__sync_fetch_and_sub_1:
3376 case Builtin::BI__sync_fetch_and_sub_2:
3377 case Builtin::BI__sync_fetch_and_sub_4:
3378 case Builtin::BI__sync_fetch_and_sub_8:
3379 case Builtin::BI__sync_fetch_and_sub_16:
3380 case Builtin::BI__sync_fetch_and_or:
3381 case Builtin::BI__sync_fetch_and_or_1:
3382 case Builtin::BI__sync_fetch_and_or_2:
3383 case Builtin::BI__sync_fetch_and_or_4:
3384 case Builtin::BI__sync_fetch_and_or_8:
3385 case Builtin::BI__sync_fetch_and_or_16:
3386 case Builtin::BI__sync_fetch_and_and:
3387 case Builtin::BI__sync_fetch_and_and_1:
3388 case Builtin::BI__sync_fetch_and_and_2:
3389 case Builtin::BI__sync_fetch_and_and_4:
3390 case Builtin::BI__sync_fetch_and_and_8:
3391 case Builtin::BI__sync_fetch_and_and_16:
3392 case Builtin::BI__sync_fetch_and_xor:
3393 case Builtin::BI__sync_fetch_and_xor_1:
3394 case Builtin::BI__sync_fetch_and_xor_2:
3395 case Builtin::BI__sync_fetch_and_xor_4:
3396 case Builtin::BI__sync_fetch_and_xor_8:
3397 case Builtin::BI__sync_fetch_and_xor_16:
3398 case Builtin::BI__sync_fetch_and_nand:
3399 case Builtin::BI__sync_fetch_and_nand_1:
3400 case Builtin::BI__sync_fetch_and_nand_2:
3401 case Builtin::BI__sync_fetch_and_nand_4:
3402 case Builtin::BI__sync_fetch_and_nand_8:
3403 case Builtin::BI__sync_fetch_and_nand_16:
3404 case Builtin::BI__sync_add_and_fetch:
3405 case Builtin::BI__sync_add_and_fetch_1:
3406 case Builtin::BI__sync_add_and_fetch_2:
3407 case Builtin::BI__sync_add_and_fetch_4:
3408 case Builtin::BI__sync_add_and_fetch_8:
3409 case Builtin::BI__sync_add_and_fetch_16:
3410 case Builtin::BI__sync_sub_and_fetch:
3411 case Builtin::BI__sync_sub_and_fetch_1:
3412 case Builtin::BI__sync_sub_and_fetch_2:
3413 case Builtin::BI__sync_sub_and_fetch_4:
3414 case Builtin::BI__sync_sub_and_fetch_8:
3415 case Builtin::BI__sync_sub_and_fetch_16:
3416 case Builtin::BI__sync_and_and_fetch:
3417 case Builtin::BI__sync_and_and_fetch_1:
3418 case Builtin::BI__sync_and_and_fetch_2:
3419 case Builtin::BI__sync_and_and_fetch_4:
3420 case Builtin::BI__sync_and_and_fetch_8:
3421 case Builtin::BI__sync_and_and_fetch_16:
3422 case Builtin::BI__sync_or_and_fetch:
3423 case Builtin::BI__sync_or_and_fetch_1:
3424 case Builtin::BI__sync_or_and_fetch_2:
3425 case Builtin::BI__sync_or_and_fetch_4:
3426 case Builtin::BI__sync_or_and_fetch_8:
3427 case Builtin::BI__sync_or_and_fetch_16:
3428 case Builtin::BI__sync_xor_and_fetch:
3429 case Builtin::BI__sync_xor_and_fetch_1:
3430 case Builtin::BI__sync_xor_and_fetch_2:
3431 case Builtin::BI__sync_xor_and_fetch_4:
3432 case Builtin::BI__sync_xor_and_fetch_8:
3433 case Builtin::BI__sync_xor_and_fetch_16:
3434 case Builtin::BI__sync_nand_and_fetch:
3435 case Builtin::BI__sync_nand_and_fetch_1:
3436 case Builtin::BI__sync_nand_and_fetch_2:
3437 case Builtin::BI__sync_nand_and_fetch_4:
3438 case Builtin::BI__sync_nand_and_fetch_8:
3439 case Builtin::BI__sync_nand_and_fetch_16:
3440 case Builtin::BI__sync_val_compare_and_swap:
3441 case Builtin::BI__sync_val_compare_and_swap_1:
3442 case Builtin::BI__sync_val_compare_and_swap_2:
3443 case Builtin::BI__sync_val_compare_and_swap_4:
3444 case Builtin::BI__sync_val_compare_and_swap_8:
3445 case Builtin::BI__sync_val_compare_and_swap_16:
3446 case Builtin::BI__sync_bool_compare_and_swap:
3447 case Builtin::BI__sync_bool_compare_and_swap_1:
3448 case Builtin::BI__sync_bool_compare_and_swap_2:
3449 case Builtin::BI__sync_bool_compare_and_swap_4:
3450 case Builtin::BI__sync_bool_compare_and_swap_8:
3451 case Builtin::BI__sync_bool_compare_and_swap_16:
3452 case Builtin::BI__sync_lock_test_and_set:
3453 case Builtin::BI__sync_lock_test_and_set_1:
3454 case Builtin::BI__sync_lock_test_and_set_2:
3455 case Builtin::BI__sync_lock_test_and_set_4:
3456 case Builtin::BI__sync_lock_test_and_set_8:
3457 case Builtin::BI__sync_lock_test_and_set_16:
3458 case Builtin::BI__sync_lock_release:
3459 case Builtin::BI__sync_lock_release_1:
3460 case Builtin::BI__sync_lock_release_2:
3461 case Builtin::BI__sync_lock_release_4:
3462 case Builtin::BI__sync_lock_release_8:
3463 case Builtin::BI__sync_lock_release_16:
3464 case Builtin::BI__sync_swap:
3465 case Builtin::BI__sync_swap_1:
3466 case Builtin::BI__sync_swap_2:
3467 case Builtin::BI__sync_swap_4:
3468 case Builtin::BI__sync_swap_8:
3469 case Builtin::BI__sync_swap_16:
3470 return BuiltinAtomicOverloaded(TheCallResult);
3471 case Builtin::BI__sync_synchronize:
3472 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3473 << TheCall->getCallee()->getSourceRange();
3474 break;
3475 case Builtin::BI__builtin_nontemporal_load:
3476 case Builtin::BI__builtin_nontemporal_store:
3477 return BuiltinNontemporalOverloaded(TheCallResult);
3478 case Builtin::BI__builtin_memcpy_inline: {
3479 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3480 // We warn about copying to or from `nullptr` pointers when `size` is
3481 // greater than 0. When `size` is value dependent we cannot evaluate its
3482 // value so we bail out.
3483 if (SizeOp->isValueDependent())
3484 break;
3485 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3486 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3487 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3488 }
3489 break;
3490 }
3491 case Builtin::BI__builtin_memset_inline: {
3492 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3493 // We warn about filling to `nullptr` pointers when `size` is greater than
3494 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3495 // out.
3496 if (SizeOp->isValueDependent())
3497 break;
3498 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3499 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3500 break;
3501 }
3502#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3503 case Builtin::BI##ID: \
3504 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3505#include "clang/Basic/Builtins.inc"
3506 case Builtin::BI__annotation: {
3507 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3508 if (!TT.isOSWindows() && !TT.isUEFI()) {
3509 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3510 << TheCall->getSourceRange();
3511 return ExprError();
3512 }
3513 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3514 return ExprError();
3515 break;
3516 }
3517 case Builtin::BI__builtin_annotation:
3518 if (BuiltinAnnotation(S&: *this, TheCall))
3519 return ExprError();
3520 break;
3521 case Builtin::BI__builtin_addressof:
3522 if (BuiltinAddressof(S&: *this, TheCall))
3523 return ExprError();
3524 break;
3525 case Builtin::BI__builtin_function_start:
3526 if (BuiltinFunctionStart(S&: *this, TheCall))
3527 return ExprError();
3528 break;
3529 case Builtin::BI__builtin_is_aligned:
3530 case Builtin::BI__builtin_align_up:
3531 case Builtin::BI__builtin_align_down:
3532 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3533 return ExprError();
3534 break;
3535 case Builtin::BI__builtin_add_overflow:
3536 case Builtin::BI__builtin_sub_overflow:
3537 case Builtin::BI__builtin_mul_overflow:
3538 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3539 return ExprError();
3540 break;
3541 case Builtin::BI__builtin_operator_new:
3542 case Builtin::BI__builtin_operator_delete: {
3543 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3544 ExprResult Res =
3545 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3546 return Res;
3547 }
3548 case Builtin::BI__builtin_dump_struct:
3549 return BuiltinDumpStruct(S&: *this, TheCall);
3550 case Builtin::BI__builtin_expect_with_probability: {
3551 // We first want to ensure we are called with 3 arguments
3552 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3553 return ExprError();
3554 // then check probability is constant float in range [0.0, 1.0]
3555 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3556 SmallVector<PartialDiagnosticAt, 8> Notes;
3557 Expr::EvalResult Eval;
3558 Eval.Diag = &Notes;
3559 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3560 !Eval.Val.isFloat()) {
3561 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3562 << ProbArg->getSourceRange();
3563 for (const PartialDiagnosticAt &PDiag : Notes)
3564 Diag(Loc: PDiag.first, PD: PDiag.second);
3565 return ExprError();
3566 }
3567 llvm::APFloat Probability = Eval.Val.getFloat();
3568 bool LoseInfo = false;
3569 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3570 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3571 if (!(Probability >= llvm::APFloat(0.0) &&
3572 Probability <= llvm::APFloat(1.0))) {
3573 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3574 << ProbArg->getSourceRange();
3575 return ExprError();
3576 }
3577 break;
3578 }
3579 case Builtin::BI__builtin_preserve_access_index:
3580 if (BuiltinPreserveAI(S&: *this, TheCall))
3581 return ExprError();
3582 break;
3583 case Builtin::BI__builtin_call_with_static_chain:
3584 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3585 return ExprError();
3586 break;
3587 case Builtin::BI__exception_code:
3588 case Builtin::BI_exception_code:
3589 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3590 DiagID: diag::err_seh___except_block))
3591 return ExprError();
3592 break;
3593 case Builtin::BI__exception_info:
3594 case Builtin::BI_exception_info:
3595 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3596 DiagID: diag::err_seh___except_filter))
3597 return ExprError();
3598 break;
3599 case Builtin::BI__GetExceptionInfo:
3600 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3601 return ExprError();
3602
3603 if (CheckCXXThrowOperand(
3604 ThrowLoc: TheCall->getBeginLoc(),
3605 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3606 E: TheCall))
3607 return ExprError();
3608
3609 TheCall->setType(Context.VoidPtrTy);
3610 break;
3611 case Builtin::BIaddressof:
3612 case Builtin::BI__addressof:
3613 case Builtin::BIforward:
3614 case Builtin::BIforward_like:
3615 case Builtin::BImove:
3616 case Builtin::BImove_if_noexcept:
3617 case Builtin::BIas_const: {
3618 // These are all expected to be of the form
3619 // T &/&&/* f(U &/&&)
3620 // where T and U only differ in qualification.
3621 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3622 return ExprError();
3623 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3624 QualType Result = FDecl->getReturnType();
3625 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3626 BuiltinID == Builtin::BI__addressof;
3627 if (!(Param->isReferenceType() &&
3628 (ReturnsPointer ? Result->isAnyPointerType()
3629 : Result->isReferenceType()) &&
3630 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3631 T2: Result->getPointeeType()))) {
3632 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3633 << FDecl;
3634 return ExprError();
3635 }
3636 break;
3637 }
3638 case Builtin::BI__builtin_ptrauth_strip:
3639 return PointerAuthStrip(S&: *this, Call: TheCall);
3640 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3641 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3642 case Builtin::BI__builtin_ptrauth_sign_constant:
3643 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3644 /*RequireConstant=*/true);
3645 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3646 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3647 /*RequireConstant=*/false);
3648 case Builtin::BI__builtin_ptrauth_auth:
3649 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3650 /*RequireConstant=*/false);
3651 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3652 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3653 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3654 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3655 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3656 return PointerAuthAuthWithPCAndResign(S&: *this, Call: TheCall);
3657 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3658 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3659 case Builtin::BI__builtin_ptrauth_string_discriminator:
3660 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3661
3662 case Builtin::BI__builtin_get_vtable_pointer:
3663 return GetVTablePointer(S&: *this, Call: TheCall);
3664
3665 // OpenCL v2.0, s6.13.16 - Pipe functions
3666 case Builtin::BIread_pipe:
3667 case Builtin::BIwrite_pipe:
3668 // Since those two functions are declared with var args, we need a semantic
3669 // check for the argument.
3670 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3671 return ExprError();
3672 break;
3673 case Builtin::BIreserve_read_pipe:
3674 case Builtin::BIreserve_write_pipe:
3675 case Builtin::BIwork_group_reserve_read_pipe:
3676 case Builtin::BIwork_group_reserve_write_pipe:
3677 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3678 return ExprError();
3679 break;
3680 case Builtin::BIsub_group_reserve_read_pipe:
3681 case Builtin::BIsub_group_reserve_write_pipe:
3682 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3683 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3684 return ExprError();
3685 break;
3686 case Builtin::BIcommit_read_pipe:
3687 case Builtin::BIcommit_write_pipe:
3688 case Builtin::BIwork_group_commit_read_pipe:
3689 case Builtin::BIwork_group_commit_write_pipe:
3690 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3691 return ExprError();
3692 break;
3693 case Builtin::BIsub_group_commit_read_pipe:
3694 case Builtin::BIsub_group_commit_write_pipe:
3695 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3696 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3697 return ExprError();
3698 break;
3699 case Builtin::BIget_pipe_num_packets:
3700 case Builtin::BIget_pipe_max_packets:
3701 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3702 return ExprError();
3703 break;
3704 case Builtin::BIto_global:
3705 case Builtin::BIto_local:
3706 case Builtin::BIto_private:
3707 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3708 return ExprError();
3709 break;
3710 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3711 case Builtin::BIenqueue_kernel:
3712 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3713 return ExprError();
3714 break;
3715 case Builtin::BIget_kernel_work_group_size:
3716 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3717 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3718 return ExprError();
3719 break;
3720 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3721 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3722 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3723 return ExprError();
3724 break;
3725 case Builtin::BI__builtin_os_log_format:
3726 Cleanup.setExprNeedsCleanups(true);
3727 [[fallthrough]];
3728 case Builtin::BI__builtin_os_log_format_buffer_size:
3729 if (BuiltinOSLogFormat(TheCall))
3730 return ExprError();
3731 break;
3732 case Builtin::BI__builtin_frame_address:
3733 case Builtin::BI__builtin_return_address: {
3734 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3735 return ExprError();
3736
3737 // -Wframe-address warning if non-zero passed to builtin
3738 // return/frame address.
3739 Expr::EvalResult Result;
3740 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3741 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3742 Result.Val.getInt() != 0)
3743 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3744 << ((BuiltinID == Builtin::BI__builtin_return_address)
3745 ? "__builtin_return_address"
3746 : "__builtin_frame_address")
3747 << TheCall->getSourceRange();
3748 break;
3749 }
3750
3751 case Builtin::BI__builtin_nondeterministic_value: {
3752 if (BuiltinNonDeterministicValue(TheCall))
3753 return ExprError();
3754 break;
3755 }
3756
3757 // __builtin_elementwise_abs restricts the element type to signed integers or
3758 // floating point types only.
3759 case Builtin::BI__builtin_elementwise_abs:
3760 if (PrepareBuiltinElementwiseMathOneArgCall(
3761 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3762 return ExprError();
3763 break;
3764
3765 // These builtins restrict the element type to floating point
3766 // types only.
3767 case Builtin::BI__builtin_elementwise_acos:
3768 case Builtin::BI__builtin_elementwise_asin:
3769 case Builtin::BI__builtin_elementwise_atan:
3770 case Builtin::BI__builtin_elementwise_ceil:
3771 case Builtin::BI__builtin_elementwise_cos:
3772 case Builtin::BI__builtin_elementwise_cosh:
3773 case Builtin::BI__builtin_elementwise_exp:
3774 case Builtin::BI__builtin_elementwise_exp2:
3775 case Builtin::BI__builtin_elementwise_exp10:
3776 case Builtin::BI__builtin_elementwise_floor:
3777 case Builtin::BI__builtin_elementwise_log:
3778 case Builtin::BI__builtin_elementwise_log2:
3779 case Builtin::BI__builtin_elementwise_log10:
3780 case Builtin::BI__builtin_elementwise_roundeven:
3781 case Builtin::BI__builtin_elementwise_round:
3782 case Builtin::BI__builtin_elementwise_rint:
3783 case Builtin::BI__builtin_elementwise_nearbyint:
3784 case Builtin::BI__builtin_elementwise_sin:
3785 case Builtin::BI__builtin_elementwise_sinh:
3786 case Builtin::BI__builtin_elementwise_sqrt:
3787 case Builtin::BI__builtin_elementwise_tan:
3788 case Builtin::BI__builtin_elementwise_tanh:
3789 case Builtin::BI__builtin_elementwise_trunc:
3790 case Builtin::BI__builtin_elementwise_canonicalize:
3791 if (PrepareBuiltinElementwiseMathOneArgCall(
3792 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3793 return ExprError();
3794 break;
3795 case Builtin::BI__builtin_elementwise_fma:
3796 if (BuiltinElementwiseTernaryMath(TheCall))
3797 return ExprError();
3798 break;
3799
3800 case Builtin::BI__builtin_elementwise_ldexp: {
3801 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3802 return ExprError();
3803
3804 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3805 if (A.isInvalid())
3806 return ExprError();
3807 QualType TyA = A.get()->getType();
3808 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3809 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3810 return ExprError();
3811
3812 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3813 if (Exp.isInvalid())
3814 return ExprError();
3815 QualType TyExp = Exp.get()->getType();
3816 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3817 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3818 ArgOrdinal: 2))
3819 return ExprError();
3820
3821 // Check the two arguments are either scalars or vectors of equal length.
3822 const auto *Vec0 = TyA->getAs<VectorType>();
3823 const auto *Vec1 = TyExp->getAs<VectorType>();
3824 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3825 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3826 if (Arg0Length != Arg1Length) {
3827 Diag(Loc: Exp.get()->getBeginLoc(),
3828 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3829 << TyA << TyExp << A.get()->getSourceRange()
3830 << Exp.get()->getSourceRange();
3831 return ExprError();
3832 }
3833
3834 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3835 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3836 TheCall->setType(TyA);
3837 break;
3838 }
3839
3840 // These builtins restrict the element type to floating point
3841 // types only, and take in two arguments.
3842 case Builtin::BI__builtin_elementwise_minnum:
3843 case Builtin::BI__builtin_elementwise_maxnum:
3844 case Builtin::BI__builtin_elementwise_minimum:
3845 case Builtin::BI__builtin_elementwise_maximum:
3846 case Builtin::BI__builtin_elementwise_minimumnum:
3847 case Builtin::BI__builtin_elementwise_maximumnum:
3848 case Builtin::BI__builtin_elementwise_atan2:
3849 case Builtin::BI__builtin_elementwise_fmod:
3850 case Builtin::BI__builtin_elementwise_pow:
3851 if (BuiltinElementwiseMath(TheCall,
3852 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3853 return ExprError();
3854 break;
3855 // These builtins restrict the element type to integer
3856 // types only.
3857 case Builtin::BI__builtin_elementwise_add_sat:
3858 case Builtin::BI__builtin_elementwise_sub_sat:
3859 case Builtin::BI__builtin_elementwise_clmul:
3860 case Builtin::BI__builtin_elementwise_pext:
3861 case Builtin::BI__builtin_elementwise_pdep:
3862 if (BuiltinElementwiseMath(TheCall,
3863 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3864 return ExprError();
3865 break;
3866 case Builtin::BI__builtin_elementwise_fshl:
3867 case Builtin::BI__builtin_elementwise_fshr:
3868 if (BuiltinElementwiseTernaryMath(
3869 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3870 return ExprError();
3871 break;
3872 case Builtin::BI__builtin_elementwise_min:
3873 case Builtin::BI__builtin_elementwise_max: {
3874 if (BuiltinElementwiseMath(TheCall))
3875 return ExprError();
3876 Expr *Arg0 = TheCall->getArg(Arg: 0);
3877 Expr *Arg1 = TheCall->getArg(Arg: 1);
3878 QualType Ty0 = Arg0->getType();
3879 QualType Ty1 = Arg1->getType();
3880 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3881 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3882 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3883 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3884 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3885 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
3886 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
3887 break;
3888 }
3889 case Builtin::BI__builtin_elementwise_popcount:
3890 case Builtin::BI__builtin_elementwise_bitreverse:
3891 if (PrepareBuiltinElementwiseMathOneArgCall(
3892 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3893 return ExprError();
3894 break;
3895 case Builtin::BI__builtin_elementwise_copysign: {
3896 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3897 return ExprError();
3898
3899 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3900 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3901 if (Magnitude.isInvalid() || Sign.isInvalid())
3902 return ExprError();
3903
3904 QualType MagnitudeTy = Magnitude.get()->getType();
3905 QualType SignTy = Sign.get()->getType();
3906 if (checkMathBuiltinElementType(
3907 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
3908 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
3909 checkMathBuiltinElementType(
3910 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
3911 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
3912 return ExprError();
3913 }
3914
3915 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3916 return Diag(Loc: Sign.get()->getBeginLoc(),
3917 DiagID: diag::err_typecheck_call_different_arg_types)
3918 << MagnitudeTy << SignTy;
3919 }
3920
3921 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
3922 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
3923 TheCall->setType(Magnitude.get()->getType());
3924 break;
3925 }
3926 case Builtin::BI__builtin_elementwise_clzg:
3927 case Builtin::BI__builtin_elementwise_ctzg:
3928 // These builtins can be unary or binary. Note for empty calls we call the
3929 // unary checker in order to not emit an error that says the function
3930 // expects 2 arguments, which would be misleading.
3931 if (TheCall->getNumArgs() <= 1) {
3932 if (PrepareBuiltinElementwiseMathOneArgCall(
3933 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3934 return ExprError();
3935 } else if (BuiltinElementwiseMath(
3936 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3937 return ExprError();
3938 break;
3939 case Builtin::BI__builtin_reduce_max:
3940 case Builtin::BI__builtin_reduce_min: {
3941 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3942 return ExprError();
3943
3944 const Expr *Arg = TheCall->getArg(Arg: 0);
3945 const auto *TyA = Arg->getType()->getAs<VectorType>();
3946
3947 QualType ElTy;
3948 if (TyA)
3949 ElTy = TyA->getElementType();
3950 else if (Arg->getType()->isSizelessVectorType())
3951 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3952
3953 if (ElTy.isNull()) {
3954 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3955 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3956 << Arg->getType();
3957 return ExprError();
3958 }
3959
3960 TheCall->setType(ElTy);
3961 break;
3962 }
3963 case Builtin::BI__builtin_reduce_maximum:
3964 case Builtin::BI__builtin_reduce_minimum: {
3965 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3966 return ExprError();
3967
3968 const Expr *Arg = TheCall->getArg(Arg: 0);
3969 const auto *TyA = Arg->getType()->getAs<VectorType>();
3970
3971 QualType ElTy;
3972 if (TyA)
3973 ElTy = TyA->getElementType();
3974 else if (Arg->getType()->isSizelessVectorType())
3975 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3976
3977 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3978 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3979 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3980 << Arg->getType();
3981 return ExprError();
3982 }
3983
3984 TheCall->setType(ElTy);
3985 break;
3986 }
3987
3988 // These builtins support vectors of integers only.
3989 // TODO: ADD/MUL should support floating-point types.
3990 case Builtin::BI__builtin_reduce_add:
3991 case Builtin::BI__builtin_reduce_mul:
3992 case Builtin::BI__builtin_reduce_xor:
3993 case Builtin::BI__builtin_reduce_or:
3994 case Builtin::BI__builtin_reduce_and: {
3995 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3996 return ExprError();
3997
3998 const Expr *Arg = TheCall->getArg(Arg: 0);
3999
4000 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
4001 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4002 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4003 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4004 << Arg->getType();
4005 return ExprError();
4006 }
4007
4008 TheCall->setType(ElTy);
4009 break;
4010 }
4011
4012 case Builtin::BI__builtin_reduce_assoc_fadd:
4013 case Builtin::BI__builtin_reduce_in_order_fadd: {
4014 // For in-order reductions require the user to specify the start value.
4015 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4016 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
4017 return ExprError();
4018
4019 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4020 if (Vec.isInvalid())
4021 return ExprError();
4022
4023 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
4024
4025 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
4026 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4027 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4028 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4029 << Vec.get()->getType();
4030 return ExprError();
4031 }
4032
4033 if (TheCall->getNumArgs() == 2) {
4034 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4035 if (StartValue.isInvalid())
4036 return ExprError();
4037
4038 if (!StartValue.get()->getType()->isRealFloatingType()) {
4039 Diag(Loc: StartValue.get()->getBeginLoc(),
4040 DiagID: diag::err_builtin_invalid_arg_type)
4041 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4042 << StartValue.get()->getType();
4043 return ExprError();
4044 }
4045 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
4046 }
4047
4048 TheCall->setType(ElTy);
4049 break;
4050 }
4051
4052 case Builtin::BI__builtin_matrix_transpose:
4053 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
4054
4055 case Builtin::BI__builtin_matrix_column_major_load:
4056 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
4057
4058 case Builtin::BI__builtin_matrix_column_major_store:
4059 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
4060
4061 case Builtin::BI__builtin_verbose_trap:
4062 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
4063 return ExprError();
4064 break;
4065
4066 case Builtin::BI__builtin_get_device_side_mangled_name: {
4067 auto Check = [](CallExpr *TheCall) {
4068 if (TheCall->getNumArgs() != 1)
4069 return false;
4070 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
4071 if (!DRE)
4072 return false;
4073 auto *D = DRE->getDecl();
4074 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
4075 return false;
4076 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4077 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4078 };
4079 if (!Check(TheCall)) {
4080 Diag(Loc: TheCall->getBeginLoc(),
4081 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
4082 return ExprError();
4083 }
4084 break;
4085 }
4086 case Builtin::BI__builtin_bswapg:
4087 if (BuiltinBswapg(S&: *this, TheCall))
4088 return ExprError();
4089 break;
4090 case Builtin::BI__builtin_bitreverseg:
4091 if (BuiltinBitreverseg(S&: *this, TheCall))
4092 return ExprError();
4093 break;
4094 case Builtin::BI__builtin_popcountg:
4095 if (BuiltinPopcountg(S&: *this, TheCall))
4096 return ExprError();
4097 break;
4098 case Builtin::BI__builtin_clzg:
4099 case Builtin::BI__builtin_ctzg:
4100 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
4101 return ExprError();
4102 break;
4103
4104 case Builtin::BI__builtin_stdc_rotate_left:
4105 case Builtin::BI__builtin_stdc_rotate_right:
4106 if (BuiltinRotateGeneric(S&: *this, TheCall))
4107 return ExprError();
4108 break;
4109
4110 case Builtin::BI__builtin_stdc_memreverse8:
4111 case Builtin::BIstdc_memreverse8:
4112 case Builtin::BIstdc_memreverse8u8:
4113 case Builtin::BIstdc_memreverse8u16:
4114 case Builtin::BIstdc_memreverse8u32:
4115 case Builtin::BIstdc_memreverse8u64:
4116 if (Context.getTargetInfo().getCharWidth() != 8) {
4117 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_requires_char_bit_8)
4118 << TheCall->getDirectCallee()->getName();
4119 return ExprError();
4120 }
4121 break;
4122
4123 case Builtin::BI__builtin_stdc_bit_floor:
4124 case Builtin::BI__builtin_stdc_bit_ceil:
4125 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: QualType()))
4126 return ExprError();
4127 break;
4128 case Builtin::BI__builtin_stdc_has_single_bit:
4129 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.BoolTy))
4130 return ExprError();
4131 break;
4132 case Builtin::BI__builtin_stdc_leading_zeros:
4133 case Builtin::BI__builtin_stdc_leading_ones:
4134 case Builtin::BI__builtin_stdc_trailing_zeros:
4135 case Builtin::BI__builtin_stdc_trailing_ones:
4136 case Builtin::BI__builtin_stdc_first_leading_zero:
4137 case Builtin::BI__builtin_stdc_first_leading_one:
4138 case Builtin::BI__builtin_stdc_first_trailing_zero:
4139 case Builtin::BI__builtin_stdc_first_trailing_one:
4140 case Builtin::BI__builtin_stdc_count_zeros:
4141 case Builtin::BI__builtin_stdc_count_ones:
4142 case Builtin::BI__builtin_stdc_bit_width:
4143 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.UnsignedIntTy))
4144 return ExprError();
4145 break;
4146
4147 case Builtin::BI__builtin_allow_runtime_check: {
4148 Expr *Arg = TheCall->getArg(Arg: 0);
4149 // Check if the argument is a string literal.
4150 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
4151 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4152 << Arg->getSourceRange();
4153 return ExprError();
4154 }
4155 break;
4156 }
4157
4158 case Builtin::BI__builtin_allow_sanitize_check: {
4159 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
4160 return ExprError();
4161
4162 Expr *Arg = TheCall->getArg(Arg: 0);
4163 // Check if the argument is a string literal.
4164 const StringLiteral *SanitizerName =
4165 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
4166 if (!SanitizerName) {
4167 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4168 << Arg->getSourceRange();
4169 return ExprError();
4170 }
4171 // Validate the sanitizer name.
4172 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4173 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
4174 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4175 Value: true)
4176 .Default(Value: false)) {
4177 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
4178 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4179 << Arg->getSourceRange();
4180 return ExprError();
4181 }
4182 break;
4183 }
4184 case Builtin::BI__builtin_counted_by_ref:
4185 if (BuiltinCountedByRef(TheCall))
4186 return ExprError();
4187 break;
4188 }
4189
4190 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4191 return ExprError();
4192
4193 // Since the target specific builtins for each arch overlap, only check those
4194 // of the arch we are compiling for.
4195 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
4196 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
4197 assert(Context.getAuxTargetInfo() &&
4198 "Aux Target Builtin, but not an aux target?");
4199
4200 if (CheckTSBuiltinFunctionCall(
4201 TI: *Context.getAuxTargetInfo(),
4202 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
4203 return ExprError();
4204 } else {
4205 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
4206 TheCall))
4207 return ExprError();
4208 }
4209 }
4210
4211 return TheCallResult;
4212}
4213
4214bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4215 llvm::APSInt Result;
4216 // We can't check the value of a dependent argument.
4217 Expr *Arg = TheCall->getArg(Arg: ArgNum);
4218 if (Arg->isTypeDependent() || Arg->isValueDependent())
4219 return false;
4220
4221 // Check constant-ness first.
4222 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4223 return true;
4224
4225 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4226 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4227 return false;
4228
4229 return Diag(Loc: TheCall->getBeginLoc(),
4230 DiagID: diag::err_argument_not_contiguous_bit_field)
4231 << ArgNum << Arg->getSourceRange();
4232}
4233
4234bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4235 unsigned FirstArg, FormatStringInfo *FSI) {
4236 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4237 bool IsVariadic = false;
4238 if (const FunctionType *FnTy = D->getFunctionType())
4239 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
4240 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
4241 IsVariadic = BD->isVariadic();
4242 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
4243 IsVariadic = OMD->isVariadic();
4244
4245 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4246 IsVariadic, FSI);
4247}
4248
4249bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4250 bool HasImplicitThisParam, bool IsVariadic,
4251 FormatStringInfo *FSI) {
4252 if (FirstArg == 0)
4253 FSI->ArgPassingKind = FAPK_VAList;
4254 else if (IsVariadic)
4255 FSI->ArgPassingKind = FAPK_Variadic;
4256 else
4257 FSI->ArgPassingKind = FAPK_Fixed;
4258 FSI->FormatIdx = FormatIdx - 1;
4259 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4260
4261 // The way the format attribute works in GCC, the implicit this argument
4262 // of member functions is counted. However, it doesn't appear in our own
4263 // lists, so decrement format_idx in that case.
4264 if (HasImplicitThisParam) {
4265 if(FSI->FormatIdx == 0)
4266 return false;
4267 --FSI->FormatIdx;
4268 if (FSI->FirstDataArg != 0)
4269 --FSI->FirstDataArg;
4270 }
4271 return true;
4272}
4273
4274/// Checks if a the given expression evaluates to null.
4275///
4276/// Returns true if the value evaluates to null.
4277static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4278 // Treat (smart) pointers constructed from nullptr as null, whether we can
4279 // const-evaluate them or not.
4280 // This must happen first: the smart pointer expr might have _Nonnull type!
4281 if (isa<CXXNullPtrLiteralExpr>(
4282 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
4283 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
4284 return true;
4285
4286 // If the expression has non-null type, it doesn't evaluate to null.
4287 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4288 if (*nullability == NullabilityKind::NonNull)
4289 return false;
4290 }
4291
4292 // As a special case, transparent unions initialized with zero are
4293 // considered null for the purposes of the nonnull attribute.
4294 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4295 UT &&
4296 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4297 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
4298 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
4299 Expr = ILE->getInit(Init: 0);
4300 }
4301
4302 bool Result;
4303 return (!Expr->isValueDependent() &&
4304 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
4305 !Result);
4306}
4307
4308static void CheckNonNullArgument(Sema &S,
4309 const Expr *ArgExpr,
4310 SourceLocation CallSiteLoc) {
4311 if (CheckNonNullExpr(S, Expr: ArgExpr))
4312 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
4313 PD: S.PDiag(DiagID: diag::warn_null_arg)
4314 << ArgExpr->getSourceRange());
4315}
4316
4317/// Determine whether the given type has a non-null nullability annotation.
4318static bool isNonNullType(QualType type) {
4319 if (auto nullability = type->getNullability())
4320 return *nullability == NullabilityKind::NonNull;
4321
4322 return false;
4323}
4324
4325static void CheckNonNullArguments(Sema &S,
4326 const NamedDecl *FDecl,
4327 const FunctionProtoType *Proto,
4328 ArrayRef<const Expr *> Args,
4329 SourceLocation CallSiteLoc) {
4330 assert((FDecl || Proto) && "Need a function declaration or prototype");
4331
4332 // Already checked by constant evaluator.
4333 if (S.isConstantEvaluatedContext())
4334 return;
4335 // Check the attributes attached to the method/function itself.
4336 llvm::SmallBitVector NonNullArgs;
4337 if (FDecl) {
4338 // Handle the nonnull attribute on the function/method declaration itself.
4339 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4340 if (!NonNull->args_size()) {
4341 // Easy case: all pointer arguments are nonnull.
4342 for (const auto *Arg : Args)
4343 if (S.isValidPointerAttrType(T: Arg->getType()))
4344 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4345 return;
4346 }
4347
4348 for (const ParamIdx &Idx : NonNull->args()) {
4349 unsigned IdxAST = Idx.getASTIndex();
4350 if (IdxAST >= Args.size())
4351 continue;
4352 if (NonNullArgs.empty())
4353 NonNullArgs.resize(N: Args.size());
4354 NonNullArgs.set(IdxAST);
4355 }
4356 }
4357 }
4358
4359 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4360 // Handle the nonnull attribute on the parameters of the
4361 // function/method.
4362 ArrayRef<ParmVarDecl*> parms;
4363 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4364 parms = FD->parameters();
4365 else
4366 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4367
4368 unsigned ParamIndex = 0;
4369 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4370 I != E; ++I, ++ParamIndex) {
4371 const ParmVarDecl *PVD = *I;
4372 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4373 if (NonNullArgs.empty())
4374 NonNullArgs.resize(N: Args.size());
4375
4376 NonNullArgs.set(ParamIndex);
4377 }
4378 }
4379 } else {
4380 // If we have a non-function, non-method declaration but no
4381 // function prototype, try to dig out the function prototype.
4382 if (!Proto) {
4383 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4384 QualType type = VD->getType().getNonReferenceType();
4385 if (auto pointerType = type->getAs<PointerType>())
4386 type = pointerType->getPointeeType();
4387 else if (auto blockType = type->getAs<BlockPointerType>())
4388 type = blockType->getPointeeType();
4389 // FIXME: data member pointers?
4390
4391 // Dig out the function prototype, if there is one.
4392 Proto = type->getAs<FunctionProtoType>();
4393 }
4394 }
4395
4396 // Fill in non-null argument information from the nullability
4397 // information on the parameter types (if we have them).
4398 if (Proto) {
4399 unsigned Index = 0;
4400 for (auto paramType : Proto->getParamTypes()) {
4401 if (isNonNullType(type: paramType)) {
4402 if (NonNullArgs.empty())
4403 NonNullArgs.resize(N: Args.size());
4404
4405 NonNullArgs.set(Index);
4406 }
4407
4408 ++Index;
4409 }
4410 }
4411 }
4412
4413 // Check for non-null arguments.
4414 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4415 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4416 if (NonNullArgs[ArgIndex])
4417 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4418 }
4419}
4420
4421void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4422 StringRef ParamName, QualType ArgTy,
4423 QualType ParamTy) {
4424
4425 // If a function accepts a pointer or reference type
4426 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4427 return;
4428
4429 // If the parameter is a pointer type, get the pointee type for the
4430 // argument too. If the parameter is a reference type, don't try to get
4431 // the pointee type for the argument.
4432 if (ParamTy->isPointerType())
4433 ArgTy = ArgTy->getPointeeType();
4434
4435 // Remove reference or pointer
4436 ParamTy = ParamTy->getPointeeType();
4437
4438 // Find expected alignment, and the actual alignment of the passed object.
4439 // getTypeAlignInChars requires complete types
4440 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4441 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4442 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4443 return;
4444
4445 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4446 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4447
4448 // If the argument is less aligned than the parameter, there is a
4449 // potential alignment issue.
4450 if (ArgAlign < ParamAlign)
4451 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4452 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4453 << ParamName << (FDecl != nullptr) << FDecl;
4454}
4455
4456void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4457 const Expr *ThisArg,
4458 ArrayRef<const Expr *> Args) {
4459 if (!FD || Args.empty())
4460 return;
4461 auto GetArgAt = [&](int Idx) -> const Expr * {
4462 if (Idx == LifetimeCaptureByAttr::Global ||
4463 Idx == LifetimeCaptureByAttr::Unknown)
4464 return nullptr;
4465 if (IsMemberFunction && Idx == 0)
4466 return ThisArg;
4467 return Args[Idx - IsMemberFunction];
4468 };
4469 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4470 unsigned ArgIdx) {
4471 if (!Attr)
4472 return;
4473
4474 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4475 for (int CapturingParamIdx : Attr->params()) {
4476 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4477 continue;
4478 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4479 // initialization codepath.
4480 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4481 isa<CXXConstructorDecl>(Val: FD))
4482 continue;
4483 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4484 CapturingEntity CE{.Entity: Capturing};
4485 // Ensure that 'Captured' outlives the 'Capturing' entity.
4486 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4487 }
4488 };
4489 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4490 for (const auto *A :
4491 FD->getParamDecl(i: I)->specific_attrs<LifetimeCaptureByAttr>())
4492 HandleCaptureByAttr(A, I + IsMemberFunction);
4493 // Check when the implicit object param is captured.
4494 if (IsMemberFunction) {
4495 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4496 if (!TSI)
4497 return;
4498 AttributedTypeLoc ATL;
4499 for (TypeLoc TL = TSI->getTypeLoc();
4500 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4501 TL = ATL.getModifiedLoc())
4502 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4503 }
4504}
4505
4506void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4507 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4508 bool IsMemberFunction, SourceLocation Loc,
4509 SourceRange Range, VariadicCallType CallType) {
4510
4511 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4512 llvm::any_of(Range&: Args, P: [](const Expr *E) {
4513 return E && E->isInstantiationDependent();
4514 }))
4515 return;
4516
4517 // Printf and scanf checking.
4518 llvm::SmallBitVector CheckedVarArgs;
4519 if (FDecl) {
4520 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4521 // Only create vector if there are format attributes.
4522 CheckedVarArgs.resize(N: Args.size());
4523 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4524 CheckedVarArgs);
4525 }
4526
4527 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4528 CheckedVarArgs.resize(N: Args.size());
4529 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4530 CheckedVarArgs);
4531 }
4532 }
4533
4534 // Refuse POD arguments that weren't caught by the format string
4535 // checks above.
4536 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4537 if (CallType != VariadicCallType::DoesNotApply &&
4538 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4539 unsigned NumParams = Proto ? Proto->getNumParams()
4540 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4541 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4542 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4543 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4544 : 0;
4545
4546 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4547 // Args[ArgIdx] can be null in malformed code.
4548 if (const Expr *Arg = Args[ArgIdx]) {
4549 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4550 checkVariadicArgument(E: Arg, CT: CallType);
4551 }
4552 }
4553 }
4554 if (FD)
4555 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4556 if (FDecl || Proto) {
4557 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4558
4559 // Type safety checking.
4560 if (FDecl) {
4561 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4562 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4563 }
4564 }
4565
4566 // Check that passed arguments match the alignment of original arguments.
4567 // Try to get the missing prototype from the declaration.
4568 if (!Proto && FDecl) {
4569 const auto *FT = FDecl->getFunctionType();
4570 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4571 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4572 }
4573 if (Proto) {
4574 // For variadic functions, we may have more args than parameters.
4575 // For some K&R functions, we may have less args than parameters.
4576 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4577 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4578 bool IsScalableArg = false;
4579 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4580 // Args[ArgIdx] can be null in malformed code.
4581 if (const Expr *Arg = Args[ArgIdx]) {
4582 if (Arg->containsErrors())
4583 continue;
4584
4585 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4586 FDecl->hasLinkage() &&
4587 FDecl->getFormalLinkage() != Linkage::Internal &&
4588 CallType == VariadicCallType::DoesNotApply)
4589 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4590
4591 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4592 if (ParamTy->isSizelessVectorType())
4593 IsScalableArg = true;
4594 QualType ArgTy = Arg->getType();
4595 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4596 ArgTy, ParamTy);
4597 }
4598 }
4599
4600 // If the callee has an AArch64 SME attribute to indicate that it is an
4601 // __arm_streaming function, then the caller requires SME to be available.
4602 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4603 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4604 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4605 llvm::StringMap<bool> CallerFeatureMap;
4606 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4607 if (!CallerFeatureMap.contains(Key: "sme"))
4608 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4609 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4610 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4611 }
4612 }
4613
4614 // If the call requires a streaming-mode change and has scalable vector
4615 // arguments or return values, then warn the user that the streaming and
4616 // non-streaming vector lengths may be different.
4617 // When both streaming and non-streaming vector lengths are defined and
4618 // mismatched, produce an error.
4619 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4620 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4621 (IsScalableArg || IsScalableRet)) {
4622 bool IsCalleeStreaming =
4623 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4624 bool IsCalleeStreamingCompatible =
4625 ExtInfo.AArch64SMEAttributes &
4626 FunctionType::SME_PStateSMCompatibleMask;
4627 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4628 if (!IsCalleeStreamingCompatible &&
4629 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4630 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4631 const LangOptions &LO = getLangOpts();
4632 unsigned VL = LO.VScaleMin * 128;
4633 unsigned SVL = LO.VScaleStreamingMin * 128;
4634 bool IsVLMismatch = VL && SVL && VL != SVL;
4635
4636 auto EmitDiag = [&](bool IsArg) {
4637 if (IsVLMismatch) {
4638 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4639 // Emit warning for streaming-compatible callers
4640 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4641 << IsArg << IsCalleeStreaming << SVL << VL;
4642 else
4643 // Emit error otherwise
4644 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4645 << IsArg << SVL << VL;
4646 } else
4647 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4648 << IsArg;
4649 };
4650
4651 if (IsScalableArg)
4652 EmitDiag(true);
4653 if (IsScalableRet)
4654 EmitDiag(false);
4655 }
4656 }
4657
4658 FunctionType::ArmStateValue CalleeArmZAState =
4659 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4660 FunctionType::ArmStateValue CalleeArmZT0State =
4661 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4662 if (CalleeArmZAState != FunctionType::ARM_None ||
4663 CalleeArmZT0State != FunctionType::ARM_None) {
4664 bool CallerHasZAState = false;
4665 bool CallerHasZT0State = false;
4666 if (CallerFD) {
4667 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4668 if (Attr && Attr->isNewZA())
4669 CallerHasZAState = true;
4670 if (Attr && Attr->isNewZT0())
4671 CallerHasZT0State = true;
4672 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4673 CallerHasZAState |=
4674 FunctionType::getArmZAState(
4675 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4676 FunctionType::ARM_None;
4677 CallerHasZT0State |=
4678 FunctionType::getArmZT0State(
4679 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4680 FunctionType::ARM_None;
4681 }
4682 }
4683
4684 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4685 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4686
4687 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4688 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4689
4690 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4691 CalleeArmZT0State != FunctionType::ARM_None) {
4692 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4693 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4694 }
4695 }
4696 }
4697
4698 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4699 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4700 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4701 if (!Arg->isValueDependent()) {
4702 Expr::EvalResult Align;
4703 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4704 const llvm::APSInt &I = Align.Val.getInt();
4705 if (!I.isPowerOf2())
4706 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4707 << Arg->getSourceRange();
4708
4709 if (I > Sema::MaximumAlignment)
4710 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4711 << Arg->getSourceRange() << Sema::MaximumAlignment;
4712 }
4713 }
4714 }
4715
4716 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4717 !isUnevaluatedContext())
4718 SYCL().DiagIfDeviceCode(Loc, DiagID: diag::err_variadic_device_fn)
4719 << diag::OffloadLang::SYCL;
4720
4721 if (FD)
4722 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4723}
4724
4725void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4726 if (TemplateDecl *Decl =
4727 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4728 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4729 }
4730}
4731
4732void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4733 ArrayRef<const Expr *> Args,
4734 const FunctionProtoType *Proto,
4735 SourceLocation Loc) {
4736 VariadicCallType CallType = Proto->isVariadic()
4737 ? VariadicCallType::Constructor
4738 : VariadicCallType::DoesNotApply;
4739
4740 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4741 CheckArgAlignment(
4742 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4743 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4744
4745 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4746 Loc, Range: SourceRange(), CallType);
4747}
4748
4749bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4750 const FunctionProtoType *Proto) {
4751 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4752 isa<CXXMethodDecl>(Val: FDecl);
4753 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4754 IsMemberOperatorCall;
4755 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4756 Fn: TheCall->getCallee());
4757 Expr** Args = TheCall->getArgs();
4758 unsigned NumArgs = TheCall->getNumArgs();
4759
4760 Expr *ImplicitThis = nullptr;
4761 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4762 // If this is a call to a member operator, hide the first
4763 // argument from checkCall.
4764 // FIXME: Our choice of AST representation here is less than ideal.
4765 ImplicitThis = Args[0];
4766 ++Args;
4767 --NumArgs;
4768 } else if (IsMemberFunction && !FDecl->isStatic() &&
4769 !FDecl->hasCXXExplicitFunctionObjectParameter())
4770 ImplicitThis =
4771 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4772
4773 if (ImplicitThis) {
4774 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4775 // used.
4776 QualType ThisType = ImplicitThis->getType();
4777 if (!ThisType->isPointerType()) {
4778 assert(!ThisType->isReferenceType());
4779 ThisType = Context.getPointerType(T: ThisType);
4780 }
4781
4782 QualType ThisTypeFromDecl = Context.getPointerType(
4783 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4784
4785 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4786 ParamTy: ThisTypeFromDecl);
4787 }
4788
4789 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4790 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4791 Range: TheCall->getCallee()->getSourceRange(), CallType);
4792
4793 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4794 // None of the checks below are needed for functions that don't have
4795 // simple names (e.g., C++ conversion functions).
4796 if (!FnInfo)
4797 return false;
4798
4799 // Enforce TCB except for builtin calls, which are always allowed.
4800 if (FDecl->getBuiltinID() == 0)
4801 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4802
4803 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4804 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4805 CheckInfNaNFunction(Call: TheCall, FDecl);
4806
4807 if (getLangOpts().ObjC)
4808 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4809
4810 unsigned CMId = FDecl->getMemoryFunctionKind();
4811
4812 // Handle memory setting and copying functions.
4813 switch (CMId) {
4814 case 0:
4815 return false;
4816 case Builtin::BIstrlcpy: // fallthrough
4817 case Builtin::BIstrlcat:
4818 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4819 break;
4820 case Builtin::BIstrncat:
4821 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4822 break;
4823 case Builtin::BIfree:
4824 CheckFreeArguments(E: TheCall);
4825 break;
4826 default:
4827 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4828 }
4829
4830 return false;
4831}
4832
4833bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4834 const FunctionProtoType *Proto) {
4835 QualType Ty;
4836 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4837 Ty = V->getType().getNonReferenceType();
4838 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4839 Ty = F->getType().getNonReferenceType();
4840 else
4841 return false;
4842
4843 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4844 !Ty->isFunctionProtoType())
4845 return false;
4846
4847 VariadicCallType CallType;
4848 if (!Proto || !Proto->isVariadic()) {
4849 CallType = VariadicCallType::DoesNotApply;
4850 } else if (Ty->isBlockPointerType()) {
4851 CallType = VariadicCallType::Block;
4852 } else { // Ty->isFunctionPointerType()
4853 CallType = VariadicCallType::Function;
4854 }
4855
4856 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4857 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4858 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4859 Range: TheCall->getCallee()->getSourceRange(), CallType);
4860
4861 return false;
4862}
4863
4864bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4865 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4866 Fn: TheCall->getCallee());
4867 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4868 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4869 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4870 Range: TheCall->getCallee()->getSourceRange(), CallType);
4871
4872 return false;
4873}
4874
4875static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4876 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4877 return false;
4878
4879 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4880 switch (Op) {
4881 case AtomicExpr::AO__c11_atomic_init:
4882 case AtomicExpr::AO__opencl_atomic_init:
4883 llvm_unreachable("There is no ordering argument for an init");
4884
4885 case AtomicExpr::AO__c11_atomic_load:
4886 case AtomicExpr::AO__opencl_atomic_load:
4887 case AtomicExpr::AO__hip_atomic_load:
4888 case AtomicExpr::AO__atomic_load_n:
4889 case AtomicExpr::AO__atomic_load:
4890 case AtomicExpr::AO__scoped_atomic_load_n:
4891 case AtomicExpr::AO__scoped_atomic_load:
4892 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4893 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4894
4895 case AtomicExpr::AO__c11_atomic_store:
4896 case AtomicExpr::AO__opencl_atomic_store:
4897 case AtomicExpr::AO__hip_atomic_store:
4898 case AtomicExpr::AO__atomic_store:
4899 case AtomicExpr::AO__atomic_store_n:
4900 case AtomicExpr::AO__scoped_atomic_store:
4901 case AtomicExpr::AO__scoped_atomic_store_n:
4902 case AtomicExpr::AO__atomic_clear:
4903 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4904 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4905 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4906
4907 default:
4908 return true;
4909 }
4910}
4911
4912ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4913 AtomicExpr::AtomicOp Op) {
4914 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4915 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
4916 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4917 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
4918 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
4919 Op);
4920}
4921
4922/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4923/// equivalents. Provide a fixit when the scope is a compile-time constant and
4924/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4925/// compare_exchange builtins differ in how they accept the desired value, so
4926/// only a warning (without a fixit) is emitted for those.
4927static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange,
4928 MultiExprArg Args,
4929 AtomicExpr::AtomicOp Op) {
4930 StringRef OldName;
4931 StringRef NewName;
4932 bool CanFixIt;
4933
4934 switch (Op) {
4935#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4936 case AtomicExpr::AO__hip_atomic_##hip: \
4937 OldName = "__hip_atomic_" #hip; \
4938 NewName = "__scoped_atomic_" #scoped; \
4939 CanFixIt = true; \
4940 break;
4941 HIP_ATOMIC_FIXABLE(load, load_n)
4942 HIP_ATOMIC_FIXABLE(store, store_n)
4943 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4944 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4945 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4946 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4947 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4948 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4949 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4950 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4951#undef HIP_ATOMIC_FIXABLE
4952 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4953 OldName = "__hip_atomic_compare_exchange_weak";
4954 NewName = "__scoped_atomic_compare_exchange";
4955 CanFixIt = false;
4956 break;
4957 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4958 OldName = "__hip_atomic_compare_exchange_strong";
4959 NewName = "__scoped_atomic_compare_exchange";
4960 CanFixIt = false;
4961 break;
4962 default:
4963 llvm_unreachable("unhandled HIP atomic op");
4964 }
4965
4966 auto DB = S.Diag(Loc: ExprRange.getBegin(), DiagID: diag::warn_hip_deprecated_builtin)
4967 << OldName << NewName;
4968 if (!CanFixIt)
4969 return;
4970
4971 DB << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: NewName);
4972
4973 Expr *Scope = Args[Args.size() - 1];
4974 std::optional<llvm::APSInt> ScopeVal =
4975 Scope->getIntegerConstantExpr(Ctx: S.Context);
4976 if (!ScopeVal)
4977 return;
4978
4979 StringRef ScopeName;
4980 switch (ScopeVal->getZExtValue()) {
4981 case AtomicScopeHIPModel::SingleThread:
4982 ScopeName = "__MEMORY_SCOPE_SINGLE";
4983 break;
4984 case AtomicScopeHIPModel::Wavefront:
4985 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4986 break;
4987 case AtomicScopeHIPModel::Workgroup:
4988 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4989 break;
4990 case AtomicScopeHIPModel::Agent:
4991 ScopeName = "__MEMORY_SCOPE_DEVICE";
4992 break;
4993 case AtomicScopeHIPModel::System:
4994 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4995 break;
4996 case AtomicScopeHIPModel::Cluster:
4997 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4998 break;
4999 default:
5000 return;
5001 }
5002
5003 DB << FixItHint::CreateReplacement(
5004 RemoveRange: CharSourceRange::getTokenRange(R: Scope->getSourceRange()), Code: ScopeName);
5005}
5006
5007ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5008 SourceLocation RParenLoc, MultiExprArg Args,
5009 AtomicExpr::AtomicOp Op,
5010 AtomicArgumentOrder ArgOrder) {
5011 // All the non-OpenCL operations take one of the following forms.
5012 // The OpenCL operations take the __c11 forms with one extra argument for
5013 // synchronization scope.
5014 enum {
5015 // C __c11_atomic_init(A *, C)
5016 Init,
5017
5018 // C __c11_atomic_load(A *, int)
5019 Load,
5020
5021 // void __atomic_load(A *, CP, int)
5022 LoadCopy,
5023
5024 // void __atomic_store(A *, CP, int)
5025 Copy,
5026
5027 // C __c11_atomic_add(A *, M, int)
5028 Arithmetic,
5029
5030 // C __atomic_exchange_n(A *, CP, int)
5031 Xchg,
5032
5033 // void __atomic_exchange(A *, C *, CP, int)
5034 GNUXchg,
5035
5036 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5037 C11CmpXchg,
5038
5039 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5040 GNUCmpXchg,
5041
5042 // bool __atomic_test_and_set(A *, int)
5043 TestAndSetByte,
5044
5045 // void __atomic_clear(A *, int)
5046 ClearByte,
5047 } Form = Init;
5048
5049 const unsigned NumForm = ClearByte + 1;
5050 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5051 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5052 // where:
5053 // C is an appropriate type,
5054 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5055 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5056 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5057 // the int parameters are for orderings.
5058
5059 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5060 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5061 "need to update code for modified forms");
5062 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5063 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5064 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5065 "need to update code for modified C11 atomics");
5066 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5067 Op <= AtomicExpr::AO__opencl_atomic_store;
5068 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5069 Op <= AtomicExpr::AO__hip_atomic_store;
5070 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5071 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5072 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5073 Op <= AtomicExpr::AO__c11_atomic_store) ||
5074 IsOpenCL;
5075 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5076 Op == AtomicExpr::AO__atomic_store_n ||
5077 Op == AtomicExpr::AO__atomic_exchange_n ||
5078 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5079 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5080 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5081 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5082 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5083 // Bit mask for extra allowed value types other than integers for atomic
5084 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5085 // allow floating point.
5086 enum ArithOpExtraValueType {
5087 AOEVT_None = 0,
5088 AOEVT_Pointer = 1,
5089 AOEVT_FP = 2,
5090 AOEVT_Int = 4,
5091 };
5092 unsigned ArithAllows = AOEVT_None;
5093
5094 switch (Op) {
5095 case AtomicExpr::AO__c11_atomic_init:
5096 case AtomicExpr::AO__opencl_atomic_init:
5097 Form = Init;
5098 break;
5099
5100 case AtomicExpr::AO__c11_atomic_load:
5101 case AtomicExpr::AO__opencl_atomic_load:
5102 case AtomicExpr::AO__hip_atomic_load:
5103 case AtomicExpr::AO__atomic_load_n:
5104 case AtomicExpr::AO__scoped_atomic_load_n:
5105 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5106 Form = Load;
5107 break;
5108
5109 case AtomicExpr::AO__atomic_load:
5110 case AtomicExpr::AO__scoped_atomic_load:
5111 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5112 Form = LoadCopy;
5113 break;
5114
5115 case AtomicExpr::AO__c11_atomic_store:
5116 case AtomicExpr::AO__opencl_atomic_store:
5117 case AtomicExpr::AO__hip_atomic_store:
5118 case AtomicExpr::AO__atomic_store:
5119 case AtomicExpr::AO__atomic_store_n:
5120 case AtomicExpr::AO__scoped_atomic_store:
5121 case AtomicExpr::AO__scoped_atomic_store_n:
5122 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5123 Form = Copy;
5124 break;
5125 case AtomicExpr::AO__atomic_fetch_add:
5126 case AtomicExpr::AO__atomic_fetch_sub:
5127 case AtomicExpr::AO__atomic_add_fetch:
5128 case AtomicExpr::AO__atomic_sub_fetch:
5129 case AtomicExpr::AO__scoped_atomic_fetch_add:
5130 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5131 case AtomicExpr::AO__scoped_atomic_add_fetch:
5132 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5133 case AtomicExpr::AO__c11_atomic_fetch_add:
5134 case AtomicExpr::AO__c11_atomic_fetch_sub:
5135 case AtomicExpr::AO__opencl_atomic_fetch_add:
5136 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5137 case AtomicExpr::AO__hip_atomic_fetch_add:
5138 case AtomicExpr::AO__hip_atomic_fetch_sub:
5139 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5140 Form = Arithmetic;
5141 break;
5142 case AtomicExpr::AO__atomic_fetch_fminimum:
5143 case AtomicExpr::AO__atomic_fetch_fmaximum:
5144 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5145 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5146 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5147 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5148 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5149 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5150 ArithAllows = AOEVT_FP;
5151 Form = Arithmetic;
5152 break;
5153 case AtomicExpr::AO__atomic_fetch_max:
5154 case AtomicExpr::AO__atomic_fetch_min:
5155 case AtomicExpr::AO__atomic_max_fetch:
5156 case AtomicExpr::AO__atomic_min_fetch:
5157 case AtomicExpr::AO__scoped_atomic_fetch_max:
5158 case AtomicExpr::AO__scoped_atomic_fetch_min:
5159 case AtomicExpr::AO__scoped_atomic_max_fetch:
5160 case AtomicExpr::AO__scoped_atomic_min_fetch:
5161 case AtomicExpr::AO__c11_atomic_fetch_max:
5162 case AtomicExpr::AO__c11_atomic_fetch_min:
5163 case AtomicExpr::AO__opencl_atomic_fetch_max:
5164 case AtomicExpr::AO__opencl_atomic_fetch_min:
5165 case AtomicExpr::AO__hip_atomic_fetch_max:
5166 case AtomicExpr::AO__hip_atomic_fetch_min:
5167 ArithAllows = AOEVT_Int | AOEVT_FP;
5168 Form = Arithmetic;
5169 break;
5170 case AtomicExpr::AO__c11_atomic_fetch_and:
5171 case AtomicExpr::AO__c11_atomic_fetch_or:
5172 case AtomicExpr::AO__c11_atomic_fetch_xor:
5173 case AtomicExpr::AO__hip_atomic_fetch_and:
5174 case AtomicExpr::AO__hip_atomic_fetch_or:
5175 case AtomicExpr::AO__hip_atomic_fetch_xor:
5176 case AtomicExpr::AO__c11_atomic_fetch_nand:
5177 case AtomicExpr::AO__opencl_atomic_fetch_and:
5178 case AtomicExpr::AO__opencl_atomic_fetch_or:
5179 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5180 case AtomicExpr::AO__atomic_fetch_and:
5181 case AtomicExpr::AO__atomic_fetch_or:
5182 case AtomicExpr::AO__atomic_fetch_xor:
5183 case AtomicExpr::AO__atomic_fetch_nand:
5184 case AtomicExpr::AO__atomic_and_fetch:
5185 case AtomicExpr::AO__atomic_or_fetch:
5186 case AtomicExpr::AO__atomic_xor_fetch:
5187 case AtomicExpr::AO__atomic_nand_fetch:
5188 case AtomicExpr::AO__atomic_fetch_uinc:
5189 case AtomicExpr::AO__atomic_fetch_udec:
5190 case AtomicExpr::AO__scoped_atomic_fetch_and:
5191 case AtomicExpr::AO__scoped_atomic_fetch_or:
5192 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5193 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5194 case AtomicExpr::AO__scoped_atomic_and_fetch:
5195 case AtomicExpr::AO__scoped_atomic_or_fetch:
5196 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5197 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5198 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5199 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5200 Form = Arithmetic;
5201 break;
5202
5203 case AtomicExpr::AO__c11_atomic_exchange:
5204 case AtomicExpr::AO__hip_atomic_exchange:
5205 case AtomicExpr::AO__opencl_atomic_exchange:
5206 case AtomicExpr::AO__atomic_exchange_n:
5207 case AtomicExpr::AO__scoped_atomic_exchange_n:
5208 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5209 Form = Xchg;
5210 break;
5211
5212 case AtomicExpr::AO__atomic_exchange:
5213 case AtomicExpr::AO__scoped_atomic_exchange:
5214 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5215 Form = GNUXchg;
5216 break;
5217
5218 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5219 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5220 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5221 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5222 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5223 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5224 Form = C11CmpXchg;
5225 break;
5226
5227 case AtomicExpr::AO__atomic_compare_exchange:
5228 case AtomicExpr::AO__atomic_compare_exchange_n:
5229 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5230 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5231 ArithAllows = AOEVT_Pointer;
5232 Form = GNUCmpXchg;
5233 break;
5234
5235 case AtomicExpr::AO__atomic_test_and_set:
5236 Form = TestAndSetByte;
5237 break;
5238
5239 case AtomicExpr::AO__atomic_clear:
5240 Form = ClearByte;
5241 break;
5242 }
5243
5244 unsigned AdjustedNumArgs = NumArgs[Form];
5245 if ((IsOpenCL || IsHIP || IsScoped) &&
5246 Op != AtomicExpr::AO__opencl_atomic_init)
5247 ++AdjustedNumArgs;
5248 // Check we have the right number of arguments.
5249 if (Args.size() < AdjustedNumArgs) {
5250 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
5251 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5252 << /*is non object*/ 0 << ExprRange;
5253 return ExprError();
5254 } else if (Args.size() > AdjustedNumArgs) {
5255 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
5256 DiagID: diag::err_typecheck_call_too_many_args)
5257 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5258 << /*is non object*/ 0 << ExprRange;
5259 return ExprError();
5260 }
5261
5262 // Inspect the first argument of the atomic operation.
5263 Expr *Ptr = Args[0];
5264 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
5265 if (ConvertedPtr.isInvalid())
5266 return ExprError();
5267
5268 Ptr = ConvertedPtr.get();
5269 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5270 if (!pointerType) {
5271 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5272 << Ptr->getType() << 0 << Ptr->getSourceRange();
5273 return ExprError();
5274 }
5275
5276 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5277 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5278 QualType ValType = AtomTy; // 'C'
5279 if (IsC11) {
5280 if (!AtomTy->isAtomicType()) {
5281 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
5282 << Ptr->getType() << Ptr->getSourceRange();
5283 return ExprError();
5284 }
5285 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5286 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5287 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
5288 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5289 << Ptr->getSourceRange();
5290 return ExprError();
5291 }
5292 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5293 } else if (Form != Load && Form != LoadCopy) {
5294 if (ValType.isConstQualified()) {
5295 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
5296 << Ptr->getType() << Ptr->getSourceRange();
5297 return ExprError();
5298 }
5299 }
5300
5301 if (Form != TestAndSetByte && Form != ClearByte) {
5302 // Pointer to object of size zero is not allowed.
5303 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
5304 DiagID: diag::err_incomplete_type))
5305 return ExprError();
5306
5307 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
5308 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5309 << Ptr->getType() << 1 << Ptr->getSourceRange();
5310 return ExprError();
5311 }
5312 } else {
5313 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5314 // non-const pointer type, including void* and pointers to incomplete
5315 // structs, but only access the first byte.
5316 AtomTy = Context.CharTy;
5317 AtomTy = AtomTy.withCVRQualifiers(
5318 CVR: pointerType->getPointeeType().getCVRQualifiers());
5319 QualType PointerQT = Context.getPointerType(T: AtomTy);
5320 pointerType = PointerQT->getAs<PointerType>();
5321 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
5322 ValType = AtomTy;
5323 }
5324
5325 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5326 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5327 Diag(Loc: ExprRange.getBegin(),
5328 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5329 << 0 << Ptr->getType() << Ptr->getSourceRange();
5330 return ExprError();
5331 }
5332
5333 // For an arithmetic operation, the implied arithmetic must be well-formed.
5334 // For _n operations, the value type must also be a valid atomic type.
5335 if (Form == Arithmetic || IsN) {
5336 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5337 // trivial type errors.
5338 auto IsAllowedValueType = [&](QualType ValType,
5339 unsigned AllowedType) -> bool {
5340 bool IsX87LongDouble =
5341 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
5342 &Context.getTargetInfo().getLongDoubleFormat() ==
5343 &llvm::APFloat::x87DoubleExtended();
5344 if (ValType->isIntegerType())
5345 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5346 // integers. Explicit AOEVT_Int or other combinations allow integers.
5347 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5348 if (ValType->isPointerType())
5349 return AllowedType & AOEVT_Pointer;
5350 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5351 return false;
5352 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5353 if (IsX87LongDouble)
5354 return false;
5355 return true;
5356 };
5357 if (!IsAllowedValueType(ValType, ArithAllows)) {
5358 auto DID =
5359 ArithAllows == AOEVT_FP
5360 ? diag::err_atomic_op_needs_atomic_fp
5361 : (ArithAllows & AOEVT_FP
5362 ? (ArithAllows & AOEVT_Pointer
5363 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5364 : diag::err_atomic_op_needs_atomic_int_or_fp)
5365 : (ArithAllows & AOEVT_Pointer
5366 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5367 : diag::err_atomic_op_needs_atomic_int));
5368 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
5369 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5370 return ExprError();
5371 }
5372 if (IsC11 && ValType->isPointerType() &&
5373 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
5374 DiagID: diag::err_incomplete_type)) {
5375 return ExprError();
5376 }
5377 }
5378
5379 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5380 !AtomTy->isScalarType()) {
5381 // For GNU atomics, require a trivially-copyable type. This is not part of
5382 // the GNU atomics specification but we enforce it for consistency with
5383 // other atomics which generally all require a trivially-copyable type. This
5384 // is because atomics just copy bits.
5385 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
5386 << Ptr->getType() << Ptr->getSourceRange();
5387 return ExprError();
5388 }
5389
5390 switch (ValType.getObjCLifetime()) {
5391 case Qualifiers::OCL_None:
5392 case Qualifiers::OCL_ExplicitNone:
5393 // okay
5394 break;
5395
5396 case Qualifiers::OCL_Weak:
5397 case Qualifiers::OCL_Strong:
5398 case Qualifiers::OCL_Autoreleasing:
5399 // FIXME: Can this happen? By this point, ValType should be known
5400 // to be trivially copyable.
5401 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
5402 << ValType << Ptr->getSourceRange();
5403 return ExprError();
5404 }
5405
5406 // All atomic operations have an overload which takes a pointer to a volatile
5407 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5408 // into the result or the other operands. Similarly atomic_load takes a
5409 // pointer to a const 'A'.
5410 ValType.removeLocalVolatile();
5411 ValType.removeLocalConst();
5412 QualType ResultType = ValType;
5413 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5414 Form == ClearByte)
5415 ResultType = Context.VoidTy;
5416 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5417 ResultType = Context.BoolTy;
5418
5419 // The type of a parameter passed 'by value'. In the GNU atomics, such
5420 // arguments are actually passed as pointers.
5421 QualType ByValType = ValType; // 'CP'
5422 bool IsPassedByAddress = false;
5423 if (!IsC11 && !IsHIP && !IsN) {
5424 ByValType = Ptr->getType();
5425 IsPassedByAddress = true;
5426 }
5427
5428 SmallVector<Expr *, 5> APIOrderedArgs;
5429 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5430 APIOrderedArgs.push_back(Elt: Args[0]);
5431 switch (Form) {
5432 case Init:
5433 case Load:
5434 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
5435 break;
5436 case LoadCopy:
5437 case Copy:
5438 case Arithmetic:
5439 case Xchg:
5440 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5441 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5442 break;
5443 case GNUXchg:
5444 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5445 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
5446 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5447 break;
5448 case C11CmpXchg:
5449 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5450 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5451 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5452 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5453 break;
5454 case GNUCmpXchg:
5455 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5456 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5457 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5458 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5459 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5460 break;
5461 case TestAndSetByte:
5462 case ClearByte:
5463 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5464 break;
5465 }
5466 } else
5467 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5468
5469 // The first argument's non-CV pointer type is used to deduce the type of
5470 // subsequent arguments, except for:
5471 // - weak flag (always converted to bool)
5472 // - memory order (always converted to int)
5473 // - scope (always converted to int)
5474 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5475 QualType Ty;
5476 if (i < NumVals[Form] + 1) {
5477 switch (i) {
5478 case 0:
5479 // The first argument is always a pointer. It has a fixed type.
5480 // It is always dereferenced, a nullptr is undefined.
5481 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5482 // Nothing else to do: we already know all we want about this pointer.
5483 continue;
5484 case 1:
5485 // The second argument is the non-atomic operand. For arithmetic, this
5486 // is always passed by value, and for a compare_exchange it is always
5487 // passed by address. For the rest, GNU uses by-address and C11 uses
5488 // by-value.
5489 assert(Form != Load);
5490 if (Form == Arithmetic && ValType->isPointerType())
5491 Ty = Context.getPointerDiffType();
5492 else if (Form == Init || Form == Arithmetic)
5493 Ty = ValType;
5494 else if (Form == Copy || Form == Xchg) {
5495 if (IsPassedByAddress) {
5496 // The value pointer is always dereferenced, a nullptr is undefined.
5497 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5498 CallSiteLoc: ExprRange.getBegin());
5499 }
5500 Ty = ByValType;
5501 } else {
5502 Expr *ValArg = APIOrderedArgs[i];
5503 // The value pointer is always dereferenced, a nullptr is undefined.
5504 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5505 LangAS AS = LangAS::Default;
5506 // Keep address space of non-atomic pointer type.
5507 if (const PointerType *PtrTy =
5508 ValArg->getType()->getAs<PointerType>()) {
5509 AS = PtrTy->getPointeeType().getAddressSpace();
5510 }
5511 Ty = Context.getPointerType(
5512 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5513 }
5514 break;
5515 case 2:
5516 // The third argument to compare_exchange / GNU exchange is the desired
5517 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5518 if (IsPassedByAddress)
5519 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5520 Ty = ByValType;
5521 break;
5522 case 3:
5523 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5524 Ty = Context.BoolTy;
5525 break;
5526 }
5527 } else {
5528 // The order(s) and scope are always converted to int.
5529 Ty = Context.IntTy;
5530 }
5531
5532 InitializedEntity Entity =
5533 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5534 ExprResult Arg = APIOrderedArgs[i];
5535 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5536 if (Arg.isInvalid())
5537 return true;
5538 APIOrderedArgs[i] = Arg.get();
5539 }
5540
5541 // Permute the arguments into a 'consistent' order.
5542 SmallVector<Expr*, 5> SubExprs;
5543 SubExprs.push_back(Elt: Ptr);
5544 switch (Form) {
5545 case Init:
5546 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5547 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5548 break;
5549 case Load:
5550 case TestAndSetByte:
5551 case ClearByte:
5552 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5553 break;
5554 case LoadCopy:
5555 case Copy:
5556 case Arithmetic:
5557 case Xchg:
5558 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5559 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5560 break;
5561 case GNUXchg:
5562 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5563 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5564 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5565 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5566 break;
5567 case C11CmpXchg:
5568 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5569 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5570 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5571 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5572 break;
5573 case GNUCmpXchg:
5574 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5575 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5576 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5577 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5578 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5579 break;
5580 }
5581
5582 // If the memory orders are constants, check they are valid.
5583 if (SubExprs.size() >= 2 && Form != Init) {
5584 std::optional<llvm::APSInt> Success =
5585 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5586 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5587 Diag(Loc: SubExprs[1]->getBeginLoc(),
5588 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5589 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5590 << SubExprs[1]->getSourceRange();
5591 }
5592 if (SubExprs.size() >= 5) {
5593 if (std::optional<llvm::APSInt> Failure =
5594 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5595 if (!llvm::is_contained(
5596 Set: {llvm::AtomicOrderingCABI::relaxed,
5597 llvm::AtomicOrderingCABI::consume,
5598 llvm::AtomicOrderingCABI::acquire,
5599 llvm::AtomicOrderingCABI::seq_cst},
5600 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5601 Diag(Loc: SubExprs[3]->getBeginLoc(),
5602 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5603 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5604 }
5605 }
5606 }
5607 }
5608
5609 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5610 auto *Scope = Args[Args.size() - 1];
5611 if (std::optional<llvm::APSInt> Result =
5612 Scope->getIntegerConstantExpr(Ctx: Context)) {
5613 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5614 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5615 << Scope->getSourceRange();
5616 }
5617 SubExprs.push_back(Elt: Scope);
5618 }
5619
5620 if (IsHIP)
5621 DiagnoseDeprecatedHIPAtomic(S&: *this, ExprRange, Args, Op);
5622
5623 AtomicExpr *AE = new (Context)
5624 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5625
5626 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5627 Op == AtomicExpr::AO__c11_atomic_store ||
5628 Op == AtomicExpr::AO__opencl_atomic_load ||
5629 Op == AtomicExpr::AO__hip_atomic_load ||
5630 Op == AtomicExpr::AO__opencl_atomic_store ||
5631 Op == AtomicExpr::AO__hip_atomic_store) &&
5632 Context.AtomicUsesUnsupportedLibcall(E: AE))
5633 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5634 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5635 Op == AtomicExpr::AO__opencl_atomic_load ||
5636 Op == AtomicExpr::AO__hip_atomic_load)
5637 ? 0
5638 : 1);
5639
5640 if (ValType->isBitIntType()) {
5641 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5642 return ExprError();
5643 }
5644
5645 return AE;
5646}
5647
5648/// checkBuiltinArgument - Given a call to a builtin function, perform
5649/// normal type-checking on the given argument, updating the call in
5650/// place. This is useful when a builtin function requires custom
5651/// type-checking for some of its arguments but not necessarily all of
5652/// them.
5653///
5654/// Returns true on error.
5655static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5656 FunctionDecl *Fn = E->getDirectCallee();
5657 assert(Fn && "builtin call without direct callee!");
5658
5659 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5660 InitializedEntity Entity =
5661 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5662
5663 ExprResult Arg = E->getArg(Arg: ArgIndex);
5664 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5665 if (Arg.isInvalid())
5666 return true;
5667
5668 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5669 return false;
5670}
5671
5672ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5673 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5674 Expr *Callee = TheCall->getCallee();
5675 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5676 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5677
5678 // Ensure that we have at least one argument to do type inference from.
5679 if (TheCall->getNumArgs() < 1) {
5680 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5681 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5682 << Callee->getSourceRange();
5683 return ExprError();
5684 }
5685
5686 // Inspect the first argument of the atomic builtin. This should always be
5687 // a pointer type, whose element is an integral scalar or pointer type.
5688 // Because it is a pointer type, we don't have to worry about any implicit
5689 // casts here.
5690 // FIXME: We don't allow floating point scalars as input.
5691 Expr *FirstArg = TheCall->getArg(Arg: 0);
5692 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5693 if (FirstArgResult.isInvalid())
5694 return ExprError();
5695 FirstArg = FirstArgResult.get();
5696 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5697
5698 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5699 if (!pointerType) {
5700 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5701 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5702 return ExprError();
5703 }
5704
5705 QualType ValType = pointerType->getPointeeType();
5706 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5707 !ValType->isBlockPointerType()) {
5708 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5709 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5710 return ExprError();
5711 }
5712 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5713 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5714 Diag(Loc: FirstArg->getBeginLoc(),
5715 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5716 << 1 << ValType << FirstArg->getSourceRange();
5717 return ExprError();
5718 }
5719
5720 if (ValType.isConstQualified()) {
5721 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5722 << FirstArg->getType() << FirstArg->getSourceRange();
5723 return ExprError();
5724 }
5725
5726 switch (ValType.getObjCLifetime()) {
5727 case Qualifiers::OCL_None:
5728 case Qualifiers::OCL_ExplicitNone:
5729 // okay
5730 break;
5731
5732 case Qualifiers::OCL_Weak:
5733 case Qualifiers::OCL_Strong:
5734 case Qualifiers::OCL_Autoreleasing:
5735 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5736 << ValType << FirstArg->getSourceRange();
5737 return ExprError();
5738 }
5739
5740 // Strip any qualifiers off ValType.
5741 ValType = ValType.getUnqualifiedType();
5742
5743 // The majority of builtins return a value, but a few have special return
5744 // types, so allow them to override appropriately below.
5745 QualType ResultType = ValType;
5746
5747 // We need to figure out which concrete builtin this maps onto. For example,
5748 // __sync_fetch_and_add with a 2 byte object turns into
5749 // __sync_fetch_and_add_2.
5750#define BUILTIN_ROW(x) \
5751 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5752 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5753
5754 static const unsigned BuiltinIndices[][5] = {
5755 BUILTIN_ROW(__sync_fetch_and_add),
5756 BUILTIN_ROW(__sync_fetch_and_sub),
5757 BUILTIN_ROW(__sync_fetch_and_or),
5758 BUILTIN_ROW(__sync_fetch_and_and),
5759 BUILTIN_ROW(__sync_fetch_and_xor),
5760 BUILTIN_ROW(__sync_fetch_and_nand),
5761
5762 BUILTIN_ROW(__sync_add_and_fetch),
5763 BUILTIN_ROW(__sync_sub_and_fetch),
5764 BUILTIN_ROW(__sync_and_and_fetch),
5765 BUILTIN_ROW(__sync_or_and_fetch),
5766 BUILTIN_ROW(__sync_xor_and_fetch),
5767 BUILTIN_ROW(__sync_nand_and_fetch),
5768
5769 BUILTIN_ROW(__sync_val_compare_and_swap),
5770 BUILTIN_ROW(__sync_bool_compare_and_swap),
5771 BUILTIN_ROW(__sync_lock_test_and_set),
5772 BUILTIN_ROW(__sync_lock_release),
5773 BUILTIN_ROW(__sync_swap)
5774 };
5775#undef BUILTIN_ROW
5776
5777 // Determine the index of the size.
5778 unsigned SizeIndex;
5779 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5780 case 1: SizeIndex = 0; break;
5781 case 2: SizeIndex = 1; break;
5782 case 4: SizeIndex = 2; break;
5783 case 8: SizeIndex = 3; break;
5784 case 16: SizeIndex = 4; break;
5785 default:
5786 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5787 << FirstArg->getType() << FirstArg->getSourceRange();
5788 return ExprError();
5789 }
5790
5791 // Each of these builtins has one pointer argument, followed by some number of
5792 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5793 // that we ignore. Find out which row of BuiltinIndices to read from as well
5794 // as the number of fixed args.
5795 unsigned BuiltinID = FDecl->getBuiltinID();
5796 unsigned BuiltinIndex, NumFixed = 1;
5797 bool WarnAboutSemanticsChange = false;
5798 switch (BuiltinID) {
5799 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5800 case Builtin::BI__sync_fetch_and_add:
5801 case Builtin::BI__sync_fetch_and_add_1:
5802 case Builtin::BI__sync_fetch_and_add_2:
5803 case Builtin::BI__sync_fetch_and_add_4:
5804 case Builtin::BI__sync_fetch_and_add_8:
5805 case Builtin::BI__sync_fetch_and_add_16:
5806 BuiltinIndex = 0;
5807 break;
5808
5809 case Builtin::BI__sync_fetch_and_sub:
5810 case Builtin::BI__sync_fetch_and_sub_1:
5811 case Builtin::BI__sync_fetch_and_sub_2:
5812 case Builtin::BI__sync_fetch_and_sub_4:
5813 case Builtin::BI__sync_fetch_and_sub_8:
5814 case Builtin::BI__sync_fetch_and_sub_16:
5815 BuiltinIndex = 1;
5816 break;
5817
5818 case Builtin::BI__sync_fetch_and_or:
5819 case Builtin::BI__sync_fetch_and_or_1:
5820 case Builtin::BI__sync_fetch_and_or_2:
5821 case Builtin::BI__sync_fetch_and_or_4:
5822 case Builtin::BI__sync_fetch_and_or_8:
5823 case Builtin::BI__sync_fetch_and_or_16:
5824 BuiltinIndex = 2;
5825 break;
5826
5827 case Builtin::BI__sync_fetch_and_and:
5828 case Builtin::BI__sync_fetch_and_and_1:
5829 case Builtin::BI__sync_fetch_and_and_2:
5830 case Builtin::BI__sync_fetch_and_and_4:
5831 case Builtin::BI__sync_fetch_and_and_8:
5832 case Builtin::BI__sync_fetch_and_and_16:
5833 BuiltinIndex = 3;
5834 break;
5835
5836 case Builtin::BI__sync_fetch_and_xor:
5837 case Builtin::BI__sync_fetch_and_xor_1:
5838 case Builtin::BI__sync_fetch_and_xor_2:
5839 case Builtin::BI__sync_fetch_and_xor_4:
5840 case Builtin::BI__sync_fetch_and_xor_8:
5841 case Builtin::BI__sync_fetch_and_xor_16:
5842 BuiltinIndex = 4;
5843 break;
5844
5845 case Builtin::BI__sync_fetch_and_nand:
5846 case Builtin::BI__sync_fetch_and_nand_1:
5847 case Builtin::BI__sync_fetch_and_nand_2:
5848 case Builtin::BI__sync_fetch_and_nand_4:
5849 case Builtin::BI__sync_fetch_and_nand_8:
5850 case Builtin::BI__sync_fetch_and_nand_16:
5851 BuiltinIndex = 5;
5852 WarnAboutSemanticsChange = true;
5853 break;
5854
5855 case Builtin::BI__sync_add_and_fetch:
5856 case Builtin::BI__sync_add_and_fetch_1:
5857 case Builtin::BI__sync_add_and_fetch_2:
5858 case Builtin::BI__sync_add_and_fetch_4:
5859 case Builtin::BI__sync_add_and_fetch_8:
5860 case Builtin::BI__sync_add_and_fetch_16:
5861 BuiltinIndex = 6;
5862 break;
5863
5864 case Builtin::BI__sync_sub_and_fetch:
5865 case Builtin::BI__sync_sub_and_fetch_1:
5866 case Builtin::BI__sync_sub_and_fetch_2:
5867 case Builtin::BI__sync_sub_and_fetch_4:
5868 case Builtin::BI__sync_sub_and_fetch_8:
5869 case Builtin::BI__sync_sub_and_fetch_16:
5870 BuiltinIndex = 7;
5871 break;
5872
5873 case Builtin::BI__sync_and_and_fetch:
5874 case Builtin::BI__sync_and_and_fetch_1:
5875 case Builtin::BI__sync_and_and_fetch_2:
5876 case Builtin::BI__sync_and_and_fetch_4:
5877 case Builtin::BI__sync_and_and_fetch_8:
5878 case Builtin::BI__sync_and_and_fetch_16:
5879 BuiltinIndex = 8;
5880 break;
5881
5882 case Builtin::BI__sync_or_and_fetch:
5883 case Builtin::BI__sync_or_and_fetch_1:
5884 case Builtin::BI__sync_or_and_fetch_2:
5885 case Builtin::BI__sync_or_and_fetch_4:
5886 case Builtin::BI__sync_or_and_fetch_8:
5887 case Builtin::BI__sync_or_and_fetch_16:
5888 BuiltinIndex = 9;
5889 break;
5890
5891 case Builtin::BI__sync_xor_and_fetch:
5892 case Builtin::BI__sync_xor_and_fetch_1:
5893 case Builtin::BI__sync_xor_and_fetch_2:
5894 case Builtin::BI__sync_xor_and_fetch_4:
5895 case Builtin::BI__sync_xor_and_fetch_8:
5896 case Builtin::BI__sync_xor_and_fetch_16:
5897 BuiltinIndex = 10;
5898 break;
5899
5900 case Builtin::BI__sync_nand_and_fetch:
5901 case Builtin::BI__sync_nand_and_fetch_1:
5902 case Builtin::BI__sync_nand_and_fetch_2:
5903 case Builtin::BI__sync_nand_and_fetch_4:
5904 case Builtin::BI__sync_nand_and_fetch_8:
5905 case Builtin::BI__sync_nand_and_fetch_16:
5906 BuiltinIndex = 11;
5907 WarnAboutSemanticsChange = true;
5908 break;
5909
5910 case Builtin::BI__sync_val_compare_and_swap:
5911 case Builtin::BI__sync_val_compare_and_swap_1:
5912 case Builtin::BI__sync_val_compare_and_swap_2:
5913 case Builtin::BI__sync_val_compare_and_swap_4:
5914 case Builtin::BI__sync_val_compare_and_swap_8:
5915 case Builtin::BI__sync_val_compare_and_swap_16:
5916 BuiltinIndex = 12;
5917 NumFixed = 2;
5918 break;
5919
5920 case Builtin::BI__sync_bool_compare_and_swap:
5921 case Builtin::BI__sync_bool_compare_and_swap_1:
5922 case Builtin::BI__sync_bool_compare_and_swap_2:
5923 case Builtin::BI__sync_bool_compare_and_swap_4:
5924 case Builtin::BI__sync_bool_compare_and_swap_8:
5925 case Builtin::BI__sync_bool_compare_and_swap_16:
5926 BuiltinIndex = 13;
5927 NumFixed = 2;
5928 ResultType = Context.BoolTy;
5929 break;
5930
5931 case Builtin::BI__sync_lock_test_and_set:
5932 case Builtin::BI__sync_lock_test_and_set_1:
5933 case Builtin::BI__sync_lock_test_and_set_2:
5934 case Builtin::BI__sync_lock_test_and_set_4:
5935 case Builtin::BI__sync_lock_test_and_set_8:
5936 case Builtin::BI__sync_lock_test_and_set_16:
5937 BuiltinIndex = 14;
5938 break;
5939
5940 case Builtin::BI__sync_lock_release:
5941 case Builtin::BI__sync_lock_release_1:
5942 case Builtin::BI__sync_lock_release_2:
5943 case Builtin::BI__sync_lock_release_4:
5944 case Builtin::BI__sync_lock_release_8:
5945 case Builtin::BI__sync_lock_release_16:
5946 BuiltinIndex = 15;
5947 NumFixed = 0;
5948 ResultType = Context.VoidTy;
5949 break;
5950
5951 case Builtin::BI__sync_swap:
5952 case Builtin::BI__sync_swap_1:
5953 case Builtin::BI__sync_swap_2:
5954 case Builtin::BI__sync_swap_4:
5955 case Builtin::BI__sync_swap_8:
5956 case Builtin::BI__sync_swap_16:
5957 BuiltinIndex = 16;
5958 break;
5959 }
5960
5961 // Now that we know how many fixed arguments we expect, first check that we
5962 // have at least that many.
5963 if (TheCall->getNumArgs() < 1+NumFixed) {
5964 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5965 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5966 << Callee->getSourceRange();
5967 return ExprError();
5968 }
5969
5970 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
5971 << Callee->getSourceRange();
5972
5973 if (WarnAboutSemanticsChange) {
5974 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
5975 << Callee->getSourceRange();
5976 }
5977
5978 // Get the decl for the concrete builtin from this, we can tell what the
5979 // concrete integer type we should convert to is.
5980 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5981 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
5982 FunctionDecl *NewBuiltinDecl;
5983 if (NewBuiltinID == BuiltinID)
5984 NewBuiltinDecl = FDecl;
5985 else {
5986 // Perform builtin lookup to avoid redeclaring it.
5987 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
5988 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5989 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
5990 assert(Res.getFoundDecl());
5991 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
5992 if (!NewBuiltinDecl)
5993 return ExprError();
5994 }
5995
5996 // The first argument --- the pointer --- has a fixed type; we
5997 // deduce the types of the rest of the arguments accordingly. Walk
5998 // the remaining arguments, converting them to the deduced value type.
5999 for (unsigned i = 0; i != NumFixed; ++i) {
6000 ExprResult Arg = TheCall->getArg(Arg: i+1);
6001
6002 // GCC does an implicit conversion to the pointer or integer ValType. This
6003 // can fail in some cases (1i -> int**), check for this error case now.
6004 // Initialize the argument.
6005 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6006 Type: ValType, /*consume*/ Consumed: false);
6007 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6008 if (Arg.isInvalid())
6009 return ExprError();
6010
6011 // Okay, we have something that *can* be converted to the right type. Check
6012 // to see if there is a potentially weird extension going on here. This can
6013 // happen when you do an atomic operation on something like an char* and
6014 // pass in 42. The 42 gets converted to char. This is even more strange
6015 // for things like 45.123 -> char, etc.
6016 // FIXME: Do this check.
6017 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
6018 }
6019
6020 // Create a new DeclRefExpr to refer to the new decl.
6021 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6022 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
6023 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
6024 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6025
6026 // Set the callee in the CallExpr.
6027 // FIXME: This loses syntactic information.
6028 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
6029 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
6030 CK: CK_BuiltinFnToFnPtr);
6031 TheCall->setCallee(PromotedCall.get());
6032
6033 // Change the result type of the call to match the original value type. This
6034 // is arbitrary, but the codegen for these builtins ins design to handle it
6035 // gracefully.
6036 TheCall->setType(ResultType);
6037
6038 // Prohibit problematic uses of bit-precise integer types with atomic
6039 // builtins. The arguments would have already been converted to the first
6040 // argument's type, so only need to check the first argument.
6041 const auto *BitIntValType = ValType->getAs<BitIntType>();
6042 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
6043 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
6044 return ExprError();
6045 }
6046
6047 return TheCallResult;
6048}
6049
6050ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6051 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6052 DeclRefExpr *DRE =
6053 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6054 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6055 unsigned BuiltinID = FDecl->getBuiltinID();
6056 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6057 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6058 "Unexpected nontemporal load/store builtin!");
6059 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6060 unsigned numArgs = isStore ? 2 : 1;
6061
6062 // Ensure that we have the proper number of arguments.
6063 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
6064 return ExprError();
6065
6066 // Inspect the last argument of the nontemporal builtin. This should always
6067 // be a pointer type, from which we imply the type of the memory access.
6068 // Because it is a pointer type, we don't have to worry about any implicit
6069 // casts here.
6070 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
6071 ExprResult PointerArgResult =
6072 DefaultFunctionArrayLvalueConversion(E: PointerArg);
6073
6074 if (PointerArgResult.isInvalid())
6075 return ExprError();
6076 PointerArg = PointerArgResult.get();
6077 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
6078
6079 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6080 if (!pointerType) {
6081 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
6082 << PointerArg->getType() << PointerArg->getSourceRange();
6083 return ExprError();
6084 }
6085
6086 QualType ValType = pointerType->getPointeeType();
6087
6088 // Strip any qualifiers off ValType.
6089 ValType = ValType.getUnqualifiedType();
6090 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6091 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6092 !ValType->isVectorType()) {
6093 Diag(Loc: DRE->getBeginLoc(),
6094 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6095 << PointerArg->getType() << PointerArg->getSourceRange();
6096 return ExprError();
6097 }
6098
6099 if (!isStore) {
6100 TheCall->setType(ValType);
6101 return TheCallResult;
6102 }
6103
6104 ExprResult ValArg = TheCall->getArg(Arg: 0);
6105 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6106 Context, Type: ValType, /*consume*/ Consumed: false);
6107 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
6108 if (ValArg.isInvalid())
6109 return ExprError();
6110
6111 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
6112 TheCall->setType(Context.VoidTy);
6113 return TheCallResult;
6114}
6115
6116/// CheckObjCString - Checks that the format string argument to the os_log()
6117/// and os_trace() functions is correct, and converts it to const char *.
6118ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6119 Arg = Arg->IgnoreParenCasts();
6120 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
6121 if (!Literal) {
6122 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
6123 Literal = ObjcLiteral->getString();
6124 }
6125 }
6126
6127 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6128 return ExprError(
6129 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
6130 << Arg->getSourceRange());
6131 }
6132
6133 ExprResult Result(Literal);
6134 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
6135 InitializedEntity Entity =
6136 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
6137 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
6138 return Result;
6139}
6140
6141/// Check that the user is calling the appropriate va_start builtin for the
6142/// target and calling convention.
6143static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6144 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6145 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6146 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6147 TT.getArch() == llvm::Triple::aarch64_32);
6148 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6149 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6150 if (IsX64 || IsAArch64) {
6151 CallingConv CC = CC_C;
6152 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6153 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6154 if (IsMSVAStart) {
6155 // Don't allow this in System V ABI functions.
6156 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6157 return S.Diag(Loc: Fn->getBeginLoc(),
6158 DiagID: diag::err_ms_va_start_used_in_sysv_function);
6159 } else {
6160 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6161 // On x64 Windows, don't allow this in System V ABI functions.
6162 // (Yes, that means there's no corresponding way to support variadic
6163 // System V ABI functions on Windows.)
6164 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6165 (!IsWindowsOrUEFI && CC == CC_Win64))
6166 return S.Diag(Loc: Fn->getBeginLoc(),
6167 DiagID: diag::err_va_start_used_in_wrong_abi_function)
6168 << !IsWindowsOrUEFI;
6169 }
6170 return false;
6171 }
6172
6173 if (IsMSVAStart)
6174 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
6175 return false;
6176}
6177
6178static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6179 ParmVarDecl **LastParam = nullptr) {
6180 // Determine whether the current function, block, or obj-c method is variadic
6181 // and get its parameter list.
6182 bool IsVariadic = false;
6183 ArrayRef<ParmVarDecl *> Params;
6184 DeclContext *Caller = S.CurContext;
6185 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
6186 IsVariadic = Block->isVariadic();
6187 Params = Block->parameters();
6188 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
6189 IsVariadic = FD->isVariadic();
6190 Params = FD->parameters();
6191 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
6192 IsVariadic = MD->isVariadic();
6193 // FIXME: This isn't correct for methods (results in bogus warning).
6194 Params = MD->parameters();
6195 } else if (isa<CapturedDecl>(Val: Caller)) {
6196 // We don't support va_start in a CapturedDecl.
6197 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
6198 return true;
6199 } else {
6200 // This must be some other declcontext that parses exprs.
6201 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
6202 return true;
6203 }
6204
6205 if (!IsVariadic) {
6206 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
6207 return true;
6208 }
6209
6210 if (LastParam)
6211 *LastParam = Params.empty() ? nullptr : Params.back();
6212
6213 return false;
6214}
6215
6216bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6217 Expr *Fn = TheCall->getCallee();
6218 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
6219 return true;
6220
6221 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6222 // This builtin requires one argument (the va_list), allows two arguments,
6223 // but diagnoses more than two arguments. e.g.,
6224 // __builtin_c23_va_start(); // error
6225 // __builtin_c23_va_start(list); // ok
6226 // __builtin_c23_va_start(list, param); // ok
6227 // __builtin_c23_va_start(list, anything, anything); // error
6228 // This differs from the GCC behavior in that they accept the last case
6229 // with a warning, but it doesn't seem like a useful behavior to allow.
6230 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
6231 return true;
6232 } else {
6233 // In C23 mode, va_start only needs one argument. However, the builtin still
6234 // requires two arguments (which matches the behavior of the GCC builtin),
6235 // <stdarg.h> passes `0` as the second argument in C23 mode.
6236 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6237 return true;
6238 }
6239
6240 // Type-check the first argument normally.
6241 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
6242 return true;
6243
6244 // Check that the current function is variadic, and get its last parameter.
6245 ParmVarDecl *LastParam;
6246 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
6247 return true;
6248
6249 // Verify that the second argument to the builtin is the last non-variadic
6250 // argument of the current function or method. In C23 mode, if the call is
6251 // not to __builtin_c23_va_start, and the second argument is an integer
6252 // constant expression with value 0, then we don't bother with this check.
6253 // For __builtin_c23_va_start, we only perform the check for the second
6254 // argument being the last argument to the current function if there is a
6255 // second argument present.
6256 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6257 TheCall->getNumArgs() < 2) {
6258 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6259 return false;
6260 }
6261
6262 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
6263 if (std::optional<llvm::APSInt> Val =
6264 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
6265 Val && LangOpts.C23 && *Val == 0 &&
6266 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6267 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6268 return false;
6269 }
6270
6271 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6272 // next block.
6273 QualType Type;
6274 SourceLocation ParamLoc;
6275 bool IsCRegister = false;
6276 bool SecondArgIsLastNonVariadicArgument = false;
6277 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
6278 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
6279 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6280
6281 Type = PV->getType();
6282 ParamLoc = PV->getLocation();
6283 IsCRegister =
6284 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6285 }
6286 }
6287
6288 if (!SecondArgIsLastNonVariadicArgument)
6289 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
6290 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6291 else if (IsCRegister || Type->isReferenceType() ||
6292 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
6293 // Promotable integers are UB, but enumerations need a bit of
6294 // extra checking to see what their promotable type actually is.
6295 if (!Context.isPromotableIntegerType(T: Type))
6296 return false;
6297 const auto *ED = Type->getAsEnumDecl();
6298 if (!ED)
6299 return true;
6300 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
6301 }()) {
6302 unsigned Reason = 0;
6303 if (Type->isReferenceType()) Reason = 1;
6304 else if (IsCRegister) Reason = 2;
6305 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
6306 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
6307 }
6308
6309 return false;
6310}
6311
6312bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6313 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6314 const LangOptions &LO = getLangOpts();
6315
6316 if (LO.CPlusPlus)
6317 return Arg->getType()
6318 .getCanonicalType()
6319 .getTypePtr()
6320 ->getPointeeType()
6321 .withoutLocalFastQualifiers() == Context.CharTy;
6322
6323 // In C, allow aliasing through `char *`, this is required for AArch64 at
6324 // least.
6325 return true;
6326 };
6327
6328 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6329 // const char *named_addr);
6330
6331 Expr *Func = Call->getCallee();
6332
6333 if (Call->getNumArgs() < 3)
6334 return Diag(Loc: Call->getEndLoc(),
6335 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6336 << 0 /*function call*/ << 3 << Call->getNumArgs()
6337 << /*is non object*/ 0;
6338
6339 // Type-check the first argument normally.
6340 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
6341 return true;
6342
6343 // Check that the current function is variadic.
6344 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
6345 return true;
6346
6347 // __va_start on Windows does not validate the parameter qualifiers
6348
6349 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
6350 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6351
6352 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
6353 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6354
6355 const QualType &ConstCharPtrTy =
6356 Context.getPointerType(T: Context.CharTy.withConst());
6357 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6358 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6359 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6360 << 0 /* qualifier difference */
6361 << 3 /* parameter mismatch */
6362 << 2 << Arg1->getType() << ConstCharPtrTy;
6363
6364 const QualType SizeTy = Context.getSizeType();
6365 if (!Context.hasSameType(
6366 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
6367 T2: SizeTy))
6368 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6369 << Arg2->getType() << SizeTy << 1 /* different class */
6370 << 0 /* qualifier difference */
6371 << 3 /* parameter mismatch */
6372 << 3 << Arg2->getType() << SizeTy;
6373
6374 return false;
6375}
6376
6377bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6378 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6379 return true;
6380
6381 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6382 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
6383 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6384 << 1 << 0 << TheCall->getSourceRange();
6385
6386 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
6387 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
6388
6389 // Do standard promotions between the two arguments, returning their common
6390 // type.
6391 QualType Res = UsualArithmeticConversions(
6392 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
6393 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6394 return true;
6395
6396 // Make sure any conversions are pushed back into the call; this is
6397 // type safe since unordered compare builtins are declared as "_Bool
6398 // foo(...)".
6399 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
6400 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
6401
6402 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6403 return false;
6404
6405 // If the common type isn't a real floating type, then the arguments were
6406 // invalid for this operation.
6407 if (Res.isNull() || !Res->isRealFloatingType())
6408 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
6409 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
6410 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6411 << SourceRange(OrigArg0.get()->getBeginLoc(),
6412 OrigArg1.get()->getEndLoc());
6413
6414 return false;
6415}
6416
6417bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6418 unsigned BuiltinID) {
6419 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
6420 return true;
6421
6422 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
6423 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6424 BuiltinID == Builtin::BI__builtin_isinf ||
6425 BuiltinID == Builtin::BI__builtin_isinf_sign))
6426 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6427 << 0 << 0 << TheCall->getSourceRange();
6428
6429 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6430 BuiltinID == Builtin::BI__builtin_isunordered))
6431 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6432 << 1 << 0 << TheCall->getSourceRange();
6433
6434 bool IsFPClass = NumArgs == 2;
6435
6436 // Find out position of floating-point argument.
6437 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6438
6439 // We can count on all parameters preceding the floating-point just being int.
6440 // Try all of those.
6441 for (unsigned i = 0; i < FPArgNo; ++i) {
6442 Expr *Arg = TheCall->getArg(Arg: i);
6443
6444 if (Arg->isTypeDependent())
6445 return false;
6446
6447 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
6448 Action: AssignmentAction::Passing);
6449
6450 if (Res.isInvalid())
6451 return true;
6452 TheCall->setArg(Arg: i, ArgExpr: Res.get());
6453 }
6454
6455 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
6456
6457 if (OrigArg->isTypeDependent())
6458 return false;
6459
6460 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6461 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6462 if (!Res.isUsable())
6463 return true;
6464 OrigArg = Res.get();
6465
6466 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6467
6468 QualType VectorResultTy;
6469 QualType ElementTy = OrigArg->getType();
6470 // TODO: When all classification function are implemented with is_fpclass,
6471 // vector argument can be supported in all of them.
6472 if (ElementTy->isVectorType() && IsFPClass) {
6473 VectorResultTy = GetSignedVectorType(V: ElementTy);
6474 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6475 }
6476
6477 // This operation requires a non-_Complex floating-point number.
6478 if (!ElementTy->isRealFloatingType())
6479 return Diag(Loc: OrigArg->getBeginLoc(),
6480 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6481 << OrigArg->getType() << OrigArg->getSourceRange();
6482
6483 // __builtin_isfpclass has integer parameter that specify test mask. It is
6484 // passed in (...), so it should be analyzed completely here.
6485 if (IsFPClass) {
6486 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6487 return true;
6488
6489 ExprResult MaskRes = PerformImplicitConversion(
6490 From: TheCall->getArg(Arg: NumArgs - 1), ToType: Context.IntTy, Action: AssignmentAction::Passing);
6491 if (!MaskRes.isUsable())
6492 return true;
6493 TheCall->setArg(Arg: NumArgs - 1, ArgExpr: MaskRes.get());
6494 }
6495
6496 // TODO: enable this code to all classification functions.
6497 if (IsFPClass) {
6498 QualType ResultTy;
6499 if (!VectorResultTy.isNull())
6500 ResultTy = VectorResultTy;
6501 else
6502 ResultTy = Context.IntTy;
6503 TheCall->setType(ResultTy);
6504 }
6505
6506 return false;
6507}
6508
6509bool Sema::BuiltinComplex(CallExpr *TheCall) {
6510 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6511 return true;
6512
6513 bool Dependent = false;
6514 for (unsigned I = 0; I != 2; ++I) {
6515 Expr *Arg = TheCall->getArg(Arg: I);
6516 QualType T = Arg->getType();
6517 if (T->isDependentType()) {
6518 Dependent = true;
6519 continue;
6520 }
6521
6522 // Despite supporting _Complex int, GCC requires a real floating point type
6523 // for the operands of __builtin_complex.
6524 if (!T->isRealFloatingType()) {
6525 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6526 << Arg->getType() << Arg->getSourceRange();
6527 }
6528
6529 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6530 if (Converted.isInvalid())
6531 return true;
6532 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6533 }
6534
6535 if (Dependent) {
6536 TheCall->setType(Context.DependentTy);
6537 return false;
6538 }
6539
6540 Expr *Real = TheCall->getArg(Arg: 0);
6541 Expr *Imag = TheCall->getArg(Arg: 1);
6542 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6543 return Diag(Loc: Real->getBeginLoc(),
6544 DiagID: diag::err_typecheck_call_different_arg_types)
6545 << Real->getType() << Imag->getType()
6546 << Real->getSourceRange() << Imag->getSourceRange();
6547 }
6548
6549 TheCall->setType(Context.getComplexType(T: Real->getType()));
6550 return false;
6551}
6552
6553/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6554// This is declared to take (...), so we have to check everything.
6555ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6556 unsigned NumArgs = TheCall->getNumArgs();
6557 if (NumArgs < 2)
6558 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6559 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6560 << 0 /*function call*/ << 2 << NumArgs
6561 << /*is non object*/ 0 << TheCall->getSourceRange());
6562
6563 // Determine which of the following types of shufflevector we're checking:
6564 // 1) unary, vector mask: (lhs, mask)
6565 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6566 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6567 unsigned NumElements = 0;
6568
6569 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6570 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6571 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6572 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6573
6574 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6575 return ExprError(
6576 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6577 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6578 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6579 TheCall->getArg(Arg: 1)->getEndLoc()));
6580
6581 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6582 unsigned NumResElements = NumArgs - 2;
6583
6584 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6585 // with mask. If so, verify that RHS is an integer vector type with the
6586 // same number of elts as lhs.
6587 if (NumArgs == 2) {
6588 if (!RHSType->hasIntegerRepresentation() ||
6589 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6590 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6591 DiagID: diag::err_vec_builtin_incompatible_vector)
6592 << TheCall->getDirectCallee()
6593 << /*isMoreThanTwoArgs*/ false
6594 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6595 TheCall->getArg(Arg: 1)->getEndLoc()));
6596 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6597 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6598 DiagID: diag::err_vec_builtin_incompatible_vector)
6599 << TheCall->getDirectCallee()
6600 << /*isMoreThanTwoArgs*/ false
6601 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6602 TheCall->getArg(Arg: 1)->getEndLoc()));
6603 } else if (NumElements != NumResElements) {
6604 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6605 ResType = ResType->isExtVectorType()
6606 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6607 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6608 VecKind: VectorKind::Generic);
6609 }
6610 }
6611
6612 for (unsigned I = 2; I != NumArgs; ++I) {
6613 Expr *Arg = TheCall->getArg(Arg: I);
6614 if (Arg->isTypeDependent() || Arg->isValueDependent())
6615 continue;
6616
6617 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6618 if (!Result)
6619 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6620 DiagID: diag::err_shufflevector_nonconstant_argument)
6621 << Arg->getSourceRange());
6622
6623 // Allow -1 which will be translated to undef in the IR.
6624 if (Result->isSigned() && Result->isAllOnes())
6625 ;
6626 else if (Result->getActiveBits() > 64 ||
6627 Result->getZExtValue() >= NumElements * 2)
6628 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6629 DiagID: diag::err_shufflevector_argument_too_large)
6630 << Arg->getSourceRange());
6631
6632 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6633 }
6634
6635 auto *Result = new (Context) ShuffleVectorExpr(
6636 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6637 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6638
6639 // All moved to Result.
6640 TheCall->shrinkNumArgs(NewNumArgs: 0);
6641 return Result;
6642}
6643
6644ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6645 SourceLocation BuiltinLoc,
6646 SourceLocation RParenLoc) {
6647 ExprValueKind VK = VK_PRValue;
6648 ExprObjectKind OK = OK_Ordinary;
6649 QualType DstTy = TInfo->getType();
6650 QualType SrcTy = E->getType();
6651
6652 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6653 return ExprError(Diag(Loc: BuiltinLoc,
6654 DiagID: diag::err_convertvector_non_vector)
6655 << E->getSourceRange());
6656 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6657 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6658 << "second"
6659 << "__builtin_convertvector");
6660
6661 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6662 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6663 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6664 if (SrcElts != DstElts)
6665 return ExprError(Diag(Loc: BuiltinLoc,
6666 DiagID: diag::err_convertvector_incompatible_vector)
6667 << E->getSourceRange());
6668 }
6669
6670 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6671 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6672}
6673
6674bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6675 unsigned NumArgs = TheCall->getNumArgs();
6676
6677 if (NumArgs > 3)
6678 return Diag(Loc: TheCall->getEndLoc(),
6679 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6680 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6681 << TheCall->getSourceRange();
6682
6683 // Argument 0 is checked for us and the remaining arguments must be
6684 // constant integers.
6685 for (unsigned i = 1; i != NumArgs; ++i)
6686 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6687 return true;
6688
6689 return false;
6690}
6691
6692bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6693 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6694 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6695 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6696 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6697 return true;
6698 Expr *Arg = TheCall->getArg(Arg: 0);
6699 if (Arg->isInstantiationDependent())
6700 return false;
6701
6702 QualType ArgTy = Arg->getType();
6703 if (!ArgTy->hasFloatingRepresentation())
6704 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6705 << ArgTy;
6706 if (Arg->isLValue()) {
6707 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6708 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6709 }
6710 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6711 return false;
6712}
6713
6714bool Sema::BuiltinAssume(CallExpr *TheCall) {
6715 Expr *Arg = TheCall->getArg(Arg: 0);
6716 if (Arg->isInstantiationDependent()) return false;
6717
6718 if (Arg->HasSideEffects(Ctx: Context))
6719 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6720 << Arg->getSourceRange()
6721 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6722
6723 return false;
6724}
6725
6726bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6727 // The alignment must be a constant integer.
6728 Expr *Arg = TheCall->getArg(Arg: 1);
6729
6730 // We can't check the value of a dependent argument.
6731 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6732 if (const auto *UE =
6733 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6734 if (UE->getKind() == UETT_AlignOf ||
6735 UE->getKind() == UETT_PreferredAlignOf)
6736 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6737 << Arg->getSourceRange();
6738
6739 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6740
6741 if (!Result.isPowerOf2())
6742 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6743 << Arg->getSourceRange();
6744
6745 if (Result < Context.getCharWidth())
6746 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6747 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6748
6749 if (Result > std::numeric_limits<int32_t>::max())
6750 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6751 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6752 }
6753
6754 return false;
6755}
6756
6757bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6758 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6759 return true;
6760
6761 unsigned NumArgs = TheCall->getNumArgs();
6762 Expr *FirstArg = TheCall->getArg(Arg: 0);
6763
6764 {
6765 ExprResult FirstArgResult =
6766 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6767 if (!FirstArgResult.get()->getType()->isPointerType()) {
6768 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6769 << TheCall->getSourceRange();
6770 return true;
6771 }
6772 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6773 }
6774
6775 // The alignment must be a constant integer.
6776 Expr *SecondArg = TheCall->getArg(Arg: 1);
6777
6778 // We can't check the value of a dependent argument.
6779 if (!SecondArg->isValueDependent()) {
6780 llvm::APSInt Result;
6781 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6782 return true;
6783
6784 if (!Result.isPowerOf2())
6785 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6786 << SecondArg->getSourceRange();
6787
6788 if (Result > Sema::MaximumAlignment)
6789 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6790 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6791
6792 TheCall->setArg(Arg: 1,
6793 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6794 }
6795
6796 if (NumArgs > 2) {
6797 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6798 if (convertArgumentToType(S&: *this, Value&: ThirdArg, Ty: Context.getSizeType()))
6799 return true;
6800 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6801 }
6802
6803 return false;
6804}
6805
6806bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6807 unsigned BuiltinID =
6808 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6809 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6810
6811 unsigned NumArgs = TheCall->getNumArgs();
6812 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6813 if (NumArgs < NumRequiredArgs) {
6814 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6815 << 0 /* function call */ << NumRequiredArgs << NumArgs
6816 << /*is non object*/ 0 << TheCall->getSourceRange();
6817 }
6818 if (NumArgs >= NumRequiredArgs + 0x100) {
6819 return Diag(Loc: TheCall->getEndLoc(),
6820 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6821 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6822 << /*is non object*/ 0 << TheCall->getSourceRange();
6823 }
6824 unsigned i = 0;
6825
6826 // For formatting call, check buffer arg.
6827 if (!IsSizeCall) {
6828 ExprResult Arg(TheCall->getArg(Arg: i));
6829 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6830 Context, Type: Context.VoidPtrTy, Consumed: false);
6831 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6832 if (Arg.isInvalid())
6833 return true;
6834 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6835 i++;
6836 }
6837
6838 // Check string literal arg.
6839 unsigned FormatIdx = i;
6840 {
6841 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6842 if (Arg.isInvalid())
6843 return true;
6844 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6845 i++;
6846 }
6847
6848 // Make sure variadic args are scalar.
6849 unsigned FirstDataArg = i;
6850 while (i < NumArgs) {
6851 ExprResult Arg = DefaultVariadicArgumentPromotion(
6852 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6853 if (Arg.isInvalid())
6854 return true;
6855 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6856 if (ArgSize.getQuantity() >= 0x100) {
6857 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6858 << i << (int)ArgSize.getQuantity() << 0xff
6859 << TheCall->getSourceRange();
6860 }
6861 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6862 i++;
6863 }
6864
6865 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6866 // call to avoid duplicate diagnostics.
6867 if (!IsSizeCall) {
6868 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6869 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6870 bool Success = CheckFormatArguments(
6871 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6872 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6873 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6874 if (!Success)
6875 return true;
6876 }
6877
6878 if (IsSizeCall) {
6879 TheCall->setType(Context.getSizeType());
6880 } else {
6881 TheCall->setType(Context.VoidPtrTy);
6882 }
6883 return false;
6884}
6885
6886bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6887 llvm::APSInt &Result) {
6888 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6889
6890 if (Arg->isTypeDependent() || Arg->isValueDependent())
6891 return false;
6892
6893 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
6894 if (!R) {
6895 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6896 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6897 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
6898 << FDecl->getDeclName() << Arg->getSourceRange();
6899 }
6900 Result = *R;
6901
6902 return false;
6903}
6904
6905bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6906 int High, bool RangeIsError) {
6907 if (isConstantEvaluatedContext())
6908 return false;
6909 llvm::APSInt Result;
6910
6911 // We can't check the value of a dependent argument.
6912 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6913 if (Arg->isTypeDependent() || Arg->isValueDependent())
6914 return false;
6915
6916 // Check constant-ness first.
6917 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6918 return true;
6919
6920 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6921 if (RangeIsError)
6922 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
6923 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
6924 else
6925 // Defer the warning until we know if the code will be emitted so that
6926 // dead code can ignore this.
6927 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
6928 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
6929 << toString(I: Result, Radix: 10) << Low << High
6930 << Arg->getSourceRange());
6931 }
6932
6933 return false;
6934}
6935
6936bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6937 unsigned Num) {
6938 llvm::APSInt Result;
6939
6940 // We can't check the value of a dependent argument.
6941 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6942 if (Arg->isTypeDependent() || Arg->isValueDependent())
6943 return false;
6944
6945 // Check constant-ness first.
6946 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6947 return true;
6948
6949 if (Result.getSExtValue() % Num != 0)
6950 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
6951 << Num << Arg->getSourceRange();
6952
6953 return false;
6954}
6955
6956bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6957 llvm::APSInt Result;
6958
6959 // We can't check the value of a dependent argument.
6960 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6961 if (Arg->isTypeDependent() || Arg->isValueDependent())
6962 return false;
6963
6964 // Check constant-ness first.
6965 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6966 return true;
6967
6968 if (Result.isPowerOf2())
6969 return false;
6970
6971 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
6972 << Arg->getSourceRange();
6973}
6974
6975static bool IsShiftedByte(llvm::APSInt Value) {
6976 if (Value.isNegative())
6977 return false;
6978
6979 // Check if it's a shifted byte, by shifting it down
6980 while (true) {
6981 // If the value fits in the bottom byte, the check passes.
6982 if (Value < 0x100)
6983 return true;
6984
6985 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6986 // fails.
6987 if ((Value & 0xFF) != 0)
6988 return false;
6989
6990 // If the bottom 8 bits are all 0, but something above that is nonzero,
6991 // then shifting the value right by 8 bits won't affect whether it's a
6992 // shifted byte or not. So do that, and go round again.
6993 Value >>= 8;
6994 }
6995}
6996
6997bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6998 unsigned ArgBits) {
6999 llvm::APSInt Result;
7000
7001 // We can't check the value of a dependent argument.
7002 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7003 if (Arg->isTypeDependent() || Arg->isValueDependent())
7004 return false;
7005
7006 // Check constant-ness first.
7007 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7008 return true;
7009
7010 // Truncate to the given size.
7011 Result = Result.getLoBits(numBits: ArgBits);
7012 Result.setIsUnsigned(true);
7013
7014 if (IsShiftedByte(Value: Result))
7015 return false;
7016
7017 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
7018 << Arg->getSourceRange();
7019}
7020
7021bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7022 unsigned ArgNum,
7023 unsigned ArgBits) {
7024 llvm::APSInt Result;
7025
7026 // We can't check the value of a dependent argument.
7027 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7028 if (Arg->isTypeDependent() || Arg->isValueDependent())
7029 return false;
7030
7031 // Check constant-ness first.
7032 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7033 return true;
7034
7035 // Truncate to the given size.
7036 Result = Result.getLoBits(numBits: ArgBits);
7037 Result.setIsUnsigned(true);
7038
7039 // Check to see if it's in either of the required forms.
7040 if (IsShiftedByte(Value: Result) ||
7041 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7042 return false;
7043
7044 return Diag(Loc: TheCall->getBeginLoc(),
7045 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
7046 << Arg->getSourceRange();
7047}
7048
7049bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7050 if (!Context.getTargetInfo().hasSjLjLowering())
7051 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
7052 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7053
7054 Expr *Arg = TheCall->getArg(Arg: 1);
7055 llvm::APSInt Result;
7056
7057 // TODO: This is less than ideal. Overload this to take a value.
7058 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
7059 return true;
7060
7061 if (Result != 1)
7062 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
7063 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7064
7065 return false;
7066}
7067
7068bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7069 if (!Context.getTargetInfo().hasSjLjLowering())
7070 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
7071 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7072 return false;
7073}
7074
7075bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7076 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
7077 return true;
7078
7079 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
7080 if (ArgRes.isInvalid())
7081 return true;
7082
7083 // For simplicity, we support only limited expressions for the argument.
7084 // Specifically a flexible array member or a pointer with counted_by:
7085 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7086 // complex casting, which really shouldn't be a huge problem.
7087 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7088 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7089 return Diag(Loc: Arg->getBeginLoc(),
7090 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7091 << Arg->getSourceRange();
7092
7093 if (Arg->HasSideEffects(Ctx: Context))
7094 return Diag(Loc: Arg->getBeginLoc(),
7095 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
7096 << Arg->getSourceRange();
7097
7098 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
7099 const auto *CATy =
7100 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7101
7102 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7103 // Member has counted_by attribute - return pointer to count field
7104 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
7105 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7106 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
7107 return false;
7108 }
7109 }
7110
7111 // FAMs and pointers without counted_by return void*
7112 QualType MemberTy = ME->getMemberDecl()->getType();
7113 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7114 return Diag(Loc: Arg->getBeginLoc(),
7115 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7116 << Arg->getSourceRange();
7117 } else {
7118 return Diag(Loc: Arg->getBeginLoc(),
7119 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7120 << Arg->getSourceRange();
7121 }
7122
7123 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
7124 return false;
7125}
7126
7127/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7128/// It allows leaking and modification of bounds safety information.
7129bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7130 BuiltinCountedByRefKind K) {
7131 const CallExpr *CE =
7132 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
7133 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7134 return false;
7135
7136 switch (K) {
7137 case BuiltinCountedByRefKind::Assignment:
7138 case BuiltinCountedByRefKind::Initializer:
7139 Diag(Loc: E->getExprLoc(),
7140 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7141 << 0 << E->getSourceRange();
7142 break;
7143 case BuiltinCountedByRefKind::FunctionArg:
7144 Diag(Loc: E->getExprLoc(),
7145 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7146 << 1 << E->getSourceRange();
7147 break;
7148 case BuiltinCountedByRefKind::ReturnArg:
7149 Diag(Loc: E->getExprLoc(),
7150 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7151 << 2 << E->getSourceRange();
7152 break;
7153 case BuiltinCountedByRefKind::ArraySubscript:
7154 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7155 << 0 << E->getSourceRange();
7156 break;
7157 case BuiltinCountedByRefKind::BinaryExpr:
7158 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7159 << 1 << E->getSourceRange();
7160 break;
7161 }
7162
7163 return true;
7164}
7165
7166namespace {
7167
7168class UncoveredArgHandler {
7169 enum { Unknown = -1, AllCovered = -2 };
7170
7171 signed FirstUncoveredArg = Unknown;
7172 SmallVector<const Expr *, 4> DiagnosticExprs;
7173
7174public:
7175 UncoveredArgHandler() = default;
7176
7177 bool hasUncoveredArg() const {
7178 return (FirstUncoveredArg >= 0);
7179 }
7180
7181 unsigned getUncoveredArg() const {
7182 assert(hasUncoveredArg() && "no uncovered argument");
7183 return FirstUncoveredArg;
7184 }
7185
7186 void setAllCovered() {
7187 // A string has been found with all arguments covered, so clear out
7188 // the diagnostics.
7189 DiagnosticExprs.clear();
7190 FirstUncoveredArg = AllCovered;
7191 }
7192
7193 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7194 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7195
7196 // Don't update if a previous string covers all arguments.
7197 if (FirstUncoveredArg == AllCovered)
7198 return;
7199
7200 // UncoveredArgHandler tracks the highest uncovered argument index
7201 // and with it all the strings that match this index.
7202 if (NewFirstUncoveredArg == FirstUncoveredArg)
7203 DiagnosticExprs.push_back(Elt: StrExpr);
7204 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7205 DiagnosticExprs.clear();
7206 DiagnosticExprs.push_back(Elt: StrExpr);
7207 FirstUncoveredArg = NewFirstUncoveredArg;
7208 }
7209 }
7210
7211 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7212};
7213
7214enum StringLiteralCheckType {
7215 SLCT_NotALiteral,
7216 SLCT_UncheckedLiteral,
7217 SLCT_CheckedLiteral
7218};
7219
7220} // namespace
7221
7222static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7223 BinaryOperatorKind BinOpKind,
7224 bool AddendIsRight) {
7225 unsigned BitWidth = Offset.getBitWidth();
7226 unsigned AddendBitWidth = Addend.getBitWidth();
7227 // There might be negative interim results.
7228 if (Addend.isUnsigned()) {
7229 Addend = Addend.zext(width: ++AddendBitWidth);
7230 Addend.setIsSigned(true);
7231 }
7232 // Adjust the bit width of the APSInts.
7233 if (AddendBitWidth > BitWidth) {
7234 Offset = Offset.sext(width: AddendBitWidth);
7235 BitWidth = AddendBitWidth;
7236 } else if (BitWidth > AddendBitWidth) {
7237 Addend = Addend.sext(width: BitWidth);
7238 }
7239
7240 bool Ov = false;
7241 llvm::APSInt ResOffset = Offset;
7242 if (BinOpKind == BO_Add)
7243 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
7244 else {
7245 assert(AddendIsRight && BinOpKind == BO_Sub &&
7246 "operator must be add or sub with addend on the right");
7247 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
7248 }
7249
7250 // We add an offset to a pointer here so we should support an offset as big as
7251 // possible.
7252 if (Ov) {
7253 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7254 "index (intermediate) result too big");
7255 Offset = Offset.sext(width: 2 * BitWidth);
7256 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7257 return;
7258 }
7259
7260 Offset = std::move(ResOffset);
7261}
7262
7263namespace {
7264
7265// This is a wrapper class around StringLiteral to support offsetted string
7266// literals as format strings. It takes the offset into account when returning
7267// the string and its length or the source locations to display notes correctly.
7268class FormatStringLiteral {
7269 const StringLiteral *FExpr;
7270 int64_t Offset;
7271
7272public:
7273 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7274 : FExpr(fexpr), Offset(Offset) {}
7275
7276 const StringLiteral *getFormatString() const { return FExpr; }
7277
7278 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
7279
7280 unsigned getByteLength() const {
7281 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7282 }
7283
7284 unsigned getLength() const { return FExpr->getLength() - Offset; }
7285 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7286
7287 StringLiteralKind getKind() const { return FExpr->getKind(); }
7288
7289 QualType getType() const { return FExpr->getType(); }
7290
7291 bool isAscii() const { return FExpr->isOrdinary(); }
7292 bool isWide() const { return FExpr->isWide(); }
7293 bool isUTF8() const { return FExpr->isUTF8(); }
7294 bool isUTF16() const { return FExpr->isUTF16(); }
7295 bool isUTF32() const { return FExpr->isUTF32(); }
7296 bool isPascal() const { return FExpr->isPascal(); }
7297
7298 SourceLocation getLocationOfByte(
7299 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7300 const TargetInfo &Target, unsigned *StartToken = nullptr,
7301 unsigned *StartTokenByteOffset = nullptr) const {
7302 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
7303 StartToken, StartTokenByteOffset);
7304 }
7305
7306 SourceLocation getBeginLoc() const LLVM_READONLY {
7307 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7308 }
7309
7310 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7311};
7312
7313} // namespace
7314
7315static void CheckFormatString(
7316 Sema &S, const FormatStringLiteral *FExpr,
7317 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7318 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7319 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7320 bool inFunctionCall, VariadicCallType CallType,
7321 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7322 bool IgnoreStringsWithoutSpecifiers);
7323
7324static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7325 const Expr *E);
7326
7327// Determine if an expression is a string literal or constant string.
7328// If this function returns false on the arguments to a function expecting a
7329// format string, we will usually need to emit a warning.
7330// True string literals are then checked by CheckFormatString.
7331static StringLiteralCheckType
7332checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7333 const Expr *E, ArrayRef<const Expr *> Args,
7334 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7335 unsigned firstDataArg, FormatStringType Type,
7336 VariadicCallType CallType, bool InFunctionCall,
7337 llvm::SmallBitVector &CheckedVarArgs,
7338 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7339 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7340 bool IgnoreStringsWithoutSpecifiers = false) {
7341 if (S.isConstantEvaluatedContext())
7342 return SLCT_NotALiteral;
7343tryAgain:
7344 assert(Offset.isSigned() && "invalid offset");
7345
7346 if (E->isTypeDependent() || E->isValueDependent())
7347 return SLCT_NotALiteral;
7348
7349 E = E->IgnoreParenCasts();
7350
7351 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
7352 // Technically -Wformat-nonliteral does not warn about this case.
7353 // The behavior of printf and friends in this case is implementation
7354 // dependent. Ideally if the format string cannot be null then
7355 // it should have a 'nonnull' attribute in the function prototype.
7356 return SLCT_UncheckedLiteral;
7357
7358 switch (E->getStmtClass()) {
7359 case Stmt::InitListExprClass:
7360 // Handle expressions like {"foobar"}.
7361 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
7362 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7363 format_idx, firstDataArg, Type, CallType,
7364 /*InFunctionCall*/ false, CheckedVarArgs,
7365 UncoveredArg, Offset, CallerFormatParamIdx,
7366 IgnoreStringsWithoutSpecifiers);
7367 }
7368 return SLCT_NotALiteral;
7369 case Stmt::BinaryConditionalOperatorClass:
7370 case Stmt::ConditionalOperatorClass: {
7371 // The expression is a literal if both sub-expressions were, and it was
7372 // completely checked only if both sub-expressions were checked.
7373 const AbstractConditionalOperator *C =
7374 cast<AbstractConditionalOperator>(Val: E);
7375
7376 // Determine whether it is necessary to check both sub-expressions, for
7377 // example, because the condition expression is a constant that can be
7378 // evaluated at compile time.
7379 bool CheckLeft = true, CheckRight = true;
7380
7381 bool Cond;
7382 if (C->getCond()->EvaluateAsBooleanCondition(
7383 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
7384 if (Cond)
7385 CheckRight = false;
7386 else
7387 CheckLeft = false;
7388 }
7389
7390 // We need to maintain the offsets for the right and the left hand side
7391 // separately to check if every possible indexed expression is a valid
7392 // string literal. They might have different offsets for different string
7393 // literals in the end.
7394 StringLiteralCheckType Left;
7395 if (!CheckLeft)
7396 Left = SLCT_UncheckedLiteral;
7397 else {
7398 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
7399 Args, APK, format_idx, firstDataArg, Type,
7400 CallType, InFunctionCall, CheckedVarArgs,
7401 UncoveredArg, Offset, CallerFormatParamIdx,
7402 IgnoreStringsWithoutSpecifiers);
7403 if (Left == SLCT_NotALiteral || !CheckRight) {
7404 return Left;
7405 }
7406 }
7407
7408 StringLiteralCheckType Right = checkFormatStringExpr(
7409 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
7410 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7411 UncoveredArg, Offset, CallerFormatParamIdx,
7412 IgnoreStringsWithoutSpecifiers);
7413
7414 return (CheckLeft && Left < Right) ? Left : Right;
7415 }
7416
7417 case Stmt::ImplicitCastExprClass:
7418 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
7419 goto tryAgain;
7420
7421 case Stmt::OpaqueValueExprClass:
7422 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
7423 E = src;
7424 goto tryAgain;
7425 }
7426 return SLCT_NotALiteral;
7427
7428 case Stmt::PredefinedExprClass:
7429 // While __func__, etc., are technically not string literals, they
7430 // cannot contain format specifiers and thus are not a security
7431 // liability.
7432 return SLCT_UncheckedLiteral;
7433
7434 case Stmt::DeclRefExprClass: {
7435 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
7436
7437 // As an exception, do not flag errors for variables binding to
7438 // const string literals.
7439 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
7440 bool isConstant = false;
7441 QualType T = DR->getType();
7442
7443 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7444 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
7445 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7446 isConstant = T.isConstant(Ctx: S.Context) &&
7447 PT->getPointeeType().isConstant(Ctx: S.Context);
7448 } else if (T->isObjCObjectPointerType()) {
7449 // In ObjC, there is usually no "const ObjectPointer" type,
7450 // so don't check if the pointee type is constant.
7451 isConstant = T.isConstant(Ctx: S.Context);
7452 }
7453
7454 if (isConstant) {
7455 if (const Expr *Init = VD->getAnyInitializer()) {
7456 // Look through initializers like const char c[] = { "foo" }
7457 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7458 if (InitList->isStringLiteralInit())
7459 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7460 }
7461 return checkFormatStringExpr(
7462 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7463 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7464 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7465 }
7466 }
7467
7468 // When the format argument is an argument of this function, and this
7469 // function also has the format attribute, there are several interactions
7470 // for which there shouldn't be a warning. For instance, when calling
7471 // v*printf from a function that has the printf format attribute, we
7472 // should not emit a warning about using `fmt`, even though it's not
7473 // constant, because the arguments have already been checked for the
7474 // caller of `logmessage`:
7475 //
7476 // __attribute__((format(printf, 1, 2)))
7477 // void logmessage(char const *fmt, ...) {
7478 // va_list ap;
7479 // va_start(ap, fmt);
7480 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7481 // ...
7482 // }
7483 //
7484 // Another interaction that we need to support is using a format string
7485 // specified by the format_matches attribute:
7486 //
7487 // __attribute__((format_matches(printf, 1, "%s %d")))
7488 // void logmessage(char const *fmt, const char *a, int b) {
7489 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7490 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7491 // ...
7492 // }
7493 //
7494 // Yet another interaction that we need to support is calling a variadic
7495 // format function from a format function that has fixed arguments. For
7496 // instance:
7497 //
7498 // __attribute__((format(printf, 1, 2)))
7499 // void logstring(char const *fmt, char const *str) {
7500 // printf(fmt, str); /* do not emit a warning about "fmt" */
7501 // }
7502 //
7503 // Same (and perhaps more relatably) for the variadic template case:
7504 //
7505 // template<typename... Args>
7506 // __attribute__((format(printf, 1, 2)))
7507 // void log(const char *fmt, Args&&... args) {
7508 // printf(fmt, forward<Args>(args)...);
7509 // /* do not emit a warning about "fmt" */
7510 // }
7511 //
7512 // Due to implementation difficulty, we only check the format, not the
7513 // format arguments, in all cases.
7514 //
7515 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7516 if (CallerFormatParamIdx)
7517 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7518 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7519 for (const auto *PVFormatMatches :
7520 D->specific_attrs<FormatMatchesAttr>()) {
7521 Sema::FormatStringInfo CalleeFSI;
7522 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7523 FirstArg: 0, FSI: &CalleeFSI))
7524 continue;
7525 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7526 // If using the wrong type of format string, emit a diagnostic
7527 // here and stop checking to avoid irrelevant diagnostics.
7528 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7529 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7530 DiagID: diag::warn_format_string_type_incompatible)
7531 << PVFormatMatches->getType()->getName()
7532 << S.GetFormatStringTypeName(FST: Type);
7533 if (!InFunctionCall) {
7534 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7535 DiagID: diag::note_format_string_defined);
7536 }
7537 return SLCT_UncheckedLiteral;
7538 }
7539 return checkFormatStringExpr(
7540 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7541 Args, APK, format_idx, firstDataArg, Type, CallType,
7542 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7543 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7544 }
7545 }
7546
7547 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7548 Sema::FormatStringInfo CallerFSI;
7549 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7550 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7551 continue;
7552 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7553 // We also check if the formats are compatible.
7554 // We can't pass a 'scanf' string to a 'printf' function.
7555 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7556 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7557 DiagID: diag::warn_format_string_type_incompatible)
7558 << PVFormat->getType()->getName()
7559 << S.GetFormatStringTypeName(FST: Type);
7560 if (!InFunctionCall) {
7561 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7562 }
7563 return SLCT_UncheckedLiteral;
7564 }
7565 // Lastly, check that argument passing kinds transition in a
7566 // way that makes sense:
7567 // from a caller with FAPK_VAList, allow FAPK_VAList
7568 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7569 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7570 // from a caller with FAPK_Variadic, allow FAPK_VAList
7571 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7572 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7573 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7574 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7575 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7576 return SLCT_UncheckedLiteral;
7577 }
7578 }
7579 }
7580 }
7581 }
7582 }
7583
7584 return SLCT_NotALiteral;
7585 }
7586
7587 case Stmt::CallExprClass:
7588 case Stmt::CXXMemberCallExprClass: {
7589 const CallExpr *CE = cast<CallExpr>(Val: E);
7590 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7591 bool IsFirst = true;
7592 StringLiteralCheckType CommonResult;
7593 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7594 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7595 StringLiteralCheckType Result = checkFormatStringExpr(
7596 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7597 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7598 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7599 if (IsFirst) {
7600 CommonResult = Result;
7601 IsFirst = false;
7602 }
7603 }
7604 if (!IsFirst)
7605 return CommonResult;
7606
7607 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7608 unsigned BuiltinID = FD->getBuiltinID();
7609 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7610 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7611 const Expr *Arg = CE->getArg(Arg: 0);
7612 return checkFormatStringExpr(
7613 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7614 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7615 UncoveredArg, Offset, CallerFormatParamIdx,
7616 IgnoreStringsWithoutSpecifiers);
7617 }
7618 }
7619 }
7620 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7621 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7622 format_idx, firstDataArg, Type, CallType,
7623 /*InFunctionCall*/ false, CheckedVarArgs,
7624 UncoveredArg, Offset, CallerFormatParamIdx,
7625 IgnoreStringsWithoutSpecifiers);
7626 return SLCT_NotALiteral;
7627 }
7628 case Stmt::ObjCMessageExprClass: {
7629 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7630 if (const auto *MD = ME->getMethodDecl()) {
7631 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7632 // As a special case heuristic, if we're using the method -[NSBundle
7633 // localizedStringForKey:value:table:], ignore any key strings that lack
7634 // format specifiers. The idea is that if the key doesn't have any
7635 // format specifiers then its probably just a key to map to the
7636 // localized strings. If it does have format specifiers though, then its
7637 // likely that the text of the key is the format string in the
7638 // programmer's language, and should be checked.
7639 const ObjCInterfaceDecl *IFace;
7640 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7641 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7642 MD->getSelector().isKeywordSelector(
7643 Names: {"localizedStringForKey", "value", "table"})) {
7644 IgnoreStringsWithoutSpecifiers = true;
7645 }
7646
7647 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7648 return checkFormatStringExpr(
7649 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7650 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7651 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7652 }
7653 }
7654
7655 return SLCT_NotALiteral;
7656 }
7657 case Stmt::ObjCStringLiteralClass:
7658 case Stmt::StringLiteralClass: {
7659 const StringLiteral *StrE = nullptr;
7660
7661 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7662 StrE = ObjCFExpr->getString();
7663 else
7664 StrE = cast<StringLiteral>(Val: E);
7665
7666 if (StrE) {
7667 if (Offset.isNegative() || Offset > StrE->getLength()) {
7668 // TODO: It would be better to have an explicit warning for out of
7669 // bounds literals.
7670 return SLCT_NotALiteral;
7671 }
7672 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7673 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7674 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7675 CallType, CheckedVarArgs, UncoveredArg,
7676 IgnoreStringsWithoutSpecifiers);
7677 return SLCT_CheckedLiteral;
7678 }
7679
7680 return SLCT_NotALiteral;
7681 }
7682 case Stmt::BinaryOperatorClass: {
7683 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7684
7685 // A string literal + an int offset is still a string literal.
7686 if (BinOp->isAdditiveOp()) {
7687 Expr::EvalResult LResult, RResult;
7688
7689 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7690 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7691 InConstantContext: S.isConstantEvaluatedContext());
7692 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7693 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7694 InConstantContext: S.isConstantEvaluatedContext());
7695
7696 if (LIsInt != RIsInt) {
7697 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7698
7699 if (LIsInt) {
7700 if (BinOpKind == BO_Add) {
7701 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7702 E = BinOp->getRHS();
7703 goto tryAgain;
7704 }
7705 } else {
7706 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7707 E = BinOp->getLHS();
7708 goto tryAgain;
7709 }
7710 }
7711 }
7712
7713 return SLCT_NotALiteral;
7714 }
7715 case Stmt::UnaryOperatorClass: {
7716 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7717 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7718 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7719 Expr::EvalResult IndexResult;
7720 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7721 AllowSideEffects: Expr::SE_NoSideEffects,
7722 InConstantContext: S.isConstantEvaluatedContext())) {
7723 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7724 /*RHS is int*/ AddendIsRight: true);
7725 E = ASE->getBase();
7726 goto tryAgain;
7727 }
7728 }
7729
7730 return SLCT_NotALiteral;
7731 }
7732
7733 default:
7734 return SLCT_NotALiteral;
7735 }
7736}
7737
7738// If this expression can be evaluated at compile-time,
7739// check if the result is a StringLiteral and return it
7740// otherwise return nullptr
7741static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7742 const Expr *E) {
7743 Expr::EvalResult Result;
7744 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7745 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7746 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7747 return LVE;
7748 }
7749 return nullptr;
7750}
7751
7752StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7753 switch (FST) {
7754 case FormatStringType::Scanf:
7755 return "scanf";
7756 case FormatStringType::Printf:
7757 return "printf";
7758 case FormatStringType::NSString:
7759 return "NSString";
7760 case FormatStringType::Strftime:
7761 return "strftime";
7762 case FormatStringType::Strfmon:
7763 return "strfmon";
7764 case FormatStringType::Kprintf:
7765 return "kprintf";
7766 case FormatStringType::FreeBSDKPrintf:
7767 return "freebsd_kprintf";
7768 case FormatStringType::OSLog:
7769 return "os_log";
7770 default:
7771 return "<unknown>";
7772 }
7773}
7774
7775FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7776 return llvm::StringSwitch<FormatStringType>(Flavor)
7777 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7778 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7779 Value: FormatStringType::Printf)
7780 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7781 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7782 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7783 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7784 Value: FormatStringType::Kprintf)
7785 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7786 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7787 .Case(S: "os_log", Value: FormatStringType::OSLog)
7788 .Default(Value: FormatStringType::Unknown);
7789}
7790
7791FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7792 return GetFormatStringType(Flavor: Format->getType()->getName());
7793}
7794
7795FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7796 return GetFormatStringType(Flavor: Format->getType()->getName());
7797}
7798
7799bool Sema::CheckFormatArguments(const FormatAttr *Format,
7800 ArrayRef<const Expr *> Args, bool IsCXXMember,
7801 VariadicCallType CallType, SourceLocation Loc,
7802 SourceRange Range,
7803 llvm::SmallBitVector &CheckedVarArgs) {
7804 FormatStringInfo FSI;
7805 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7806 HasImplicitThisParam: IsCXXMember,
7807 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7808 return CheckFormatArguments(
7809 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7810 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7811 return false;
7812}
7813
7814bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7815 ArrayRef<const Expr *> Args, bool IsCXXMember,
7816 VariadicCallType CallType, SourceLocation Loc,
7817 SourceRange Range,
7818 llvm::SmallBitVector &CheckedVarArgs) {
7819 FormatStringInfo FSI;
7820 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7821 FSI: &FSI)) {
7822 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7823 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7824 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7825 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7826 CallType, Loc, range: Range, CheckedVarArgs);
7827 }
7828 return false;
7829}
7830
7831static bool CheckMissingFormatAttribute(
7832 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7833 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7834 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7835 SourceLocation Loc) {
7836 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7837 return false;
7838
7839 DeclContext *DC = S->CurContext;
7840 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7841 return false;
7842 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7843
7844 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7845
7846 // Find the offset to convert between attribute and parameter indexes.
7847 unsigned CallerArgumentIndexOffset =
7848 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7849
7850 unsigned FirstArgumentIndex = -1;
7851 switch (APK) {
7852 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7853 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7854 // As an extension, clang allows the format attribute on non-variadic
7855 // functions.
7856 // Caller must have fixed arguments to pass them to a fixed or variadic
7857 // function. Try to match caller and callee arguments. If successful, then
7858 // emit a diag with the caller idx, otherwise we can't determine the callee
7859 // arguments.
7860 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7861 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7862 // There aren't enough arguments in the caller to pass to callee.
7863 return false;
7864 }
7865 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7866 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7867 const auto *Arg =
7868 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7869 if (!Arg)
7870 return false;
7871 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7872 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7873 return false;
7874 }
7875 FirstArgumentIndex =
7876 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7877 break;
7878 }
7879 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7880 // Caller arguments are either variadic or a va_list.
7881 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
7882 ? (NumCallerParams + CallerArgumentIndexOffset)
7883 : 0;
7884 break;
7885 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
7886 // The callee has a format_matches attribute. We will emit that instead.
7887 if (!ReferenceFormatString)
7888 return false;
7889 break;
7890 }
7891
7892 // Emit the diagnostic and fixit.
7893 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7894 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
7895 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
7896 do {
7897 std::string Attr, Fixit;
7898 llvm::raw_string_ostream AttrOS(Attr);
7899 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7900 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7901 << FirstArgumentIndex << ")";
7902 } else {
7903 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7904 << ", \"";
7905 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
7906 AttrOS << "\")";
7907 }
7908 AttrOS.flush();
7909 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
7910 if (ND)
7911 DB << ND;
7912 else
7913 DB << "block";
7914
7915 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7916 if (isa<BlockDecl>(Val: Caller))
7917 break;
7918
7919 SourceLocation SL;
7920 llvm::raw_string_ostream IS(Fixit);
7921 // The attribute goes at the start of the declaration in C/C++ functions
7922 // and methods, but after the declaration for Objective-C methods.
7923 if (isa<ObjCMethodDecl>(Val: Caller)) {
7924 IS << ' ';
7925 SL = Caller->getEndLoc();
7926 }
7927 const LangOptions &LO = S->getLangOpts();
7928 if (LO.C23 || LO.CPlusPlus11)
7929 IS << "[[gnu::" << Attr << "]]";
7930 else if (LO.ObjC || LO.GNUMode)
7931 IS << "__attribute__((" << Attr << "))";
7932 else
7933 break;
7934 if (!isa<ObjCMethodDecl>(Val: Caller)) {
7935 IS << ' ';
7936 SL = Caller->getBeginLoc();
7937 }
7938 IS.flush();
7939
7940 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
7941 } while (false);
7942
7943 // Add implicit format or format_matches attribute.
7944 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7945 Caller->addAttr(A: FormatAttr::CreateImplicit(
7946 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7947 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
7948 } else {
7949 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
7950 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7951 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
7952 }
7953
7954 {
7955 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
7956 if (ND)
7957 DB << ND;
7958 else
7959 DB << "block";
7960 }
7961 return true;
7962}
7963
7964bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7965 Sema::FormatArgumentPassingKind APK,
7966 StringLiteral *ReferenceFormatString,
7967 unsigned format_idx, unsigned firstDataArg,
7968 FormatStringType Type,
7969 VariadicCallType CallType, SourceLocation Loc,
7970 SourceRange Range,
7971 llvm::SmallBitVector &CheckedVarArgs) {
7972 // CHECK: printf/scanf-like function is called with no format string.
7973 if (format_idx >= Args.size()) {
7974 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
7975 return false;
7976 }
7977
7978 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7979
7980 // CHECK: format string is not a string literal.
7981 //
7982 // Dynamically generated format strings are difficult to
7983 // automatically vet at compile time. Requiring that format strings
7984 // are string literals: (1) permits the checking of format strings by
7985 // the compiler and thereby (2) can practically remove the source of
7986 // many format string exploits.
7987
7988 // Format string can be either ObjC string (e.g. @"%d") or
7989 // C string (e.g. "%d")
7990 // ObjC string uses the same format specifiers as C string, so we can use
7991 // the same format string checking logic for both ObjC and C strings.
7992 UncoveredArgHandler UncoveredArg;
7993 std::optional<unsigned> CallerParamIdx;
7994 StringLiteralCheckType CT = checkFormatStringExpr(
7995 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
7996 firstDataArg, Type, CallType,
7997 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
7998 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
7999
8000 // Generate a diagnostic where an uncovered argument is detected.
8001 if (UncoveredArg.hasUncoveredArg()) {
8002 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8003 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8004 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
8005 }
8006
8007 if (CT != SLCT_NotALiteral)
8008 // Literal format string found, check done!
8009 return CT == SLCT_CheckedLiteral;
8010
8011 // Do not emit diag when the string param is a macro expansion and the
8012 // format is either NSString or CFString. This is a hack to prevent
8013 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8014 // which are usually used in place of NS and CF string literals.
8015 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8016 if (Type == FormatStringType::NSString &&
8017 SourceMgr.isInSystemMacro(loc: FormatLoc))
8018 return false;
8019
8020 if (CallerParamIdx && CheckMissingFormatAttribute(
8021 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
8022 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
8023 return false;
8024
8025 // Strftime is particular as it always uses a single 'time' argument,
8026 // so it is safe to pass a non-literal string.
8027 if (Type == FormatStringType::Strftime)
8028 return false;
8029
8030 // If there are no arguments specified, warn with -Wformat-security, otherwise
8031 // warn only with -Wformat-nonliteral.
8032 if (Args.size() == firstDataArg) {
8033 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
8034 << OrigFormatExpr->getSourceRange();
8035 switch (Type) {
8036 default:
8037 break;
8038 case FormatStringType::Kprintf:
8039 case FormatStringType::FreeBSDKPrintf:
8040 case FormatStringType::Printf:
8041 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8042 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
8043 break;
8044 case FormatStringType::NSString:
8045 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8046 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
8047 break;
8048 }
8049 } else {
8050 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
8051 << OrigFormatExpr->getSourceRange();
8052 }
8053 return false;
8054}
8055
8056namespace {
8057
8058class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8059protected:
8060 Sema &S;
8061 const FormatStringLiteral *FExpr;
8062 const Expr *OrigFormatExpr;
8063 const FormatStringType FSType;
8064 const unsigned FirstDataArg;
8065 const unsigned NumDataArgs;
8066 const char *Beg; // Start of format string.
8067 const Sema::FormatArgumentPassingKind ArgPassingKind;
8068 ArrayRef<const Expr *> Args;
8069 unsigned FormatIdx;
8070 llvm::SmallBitVector CoveredArgs;
8071 bool usesPositionalArgs = false;
8072 bool atFirstArg = true;
8073 bool inFunctionCall;
8074 VariadicCallType CallType;
8075 llvm::SmallBitVector &CheckedVarArgs;
8076 UncoveredArgHandler &UncoveredArg;
8077
8078public:
8079 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8080 const Expr *origFormatExpr, const FormatStringType type,
8081 unsigned firstDataArg, unsigned numDataArgs,
8082 const char *beg, Sema::FormatArgumentPassingKind APK,
8083 ArrayRef<const Expr *> Args, unsigned formatIdx,
8084 bool inFunctionCall, VariadicCallType callType,
8085 llvm::SmallBitVector &CheckedVarArgs,
8086 UncoveredArgHandler &UncoveredArg)
8087 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8088 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8089 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8090 inFunctionCall(inFunctionCall), CallType(callType),
8091 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8092 CoveredArgs.resize(N: numDataArgs);
8093 CoveredArgs.reset();
8094 }
8095
8096 bool HasFormatArguments() const {
8097 return ArgPassingKind == Sema::FAPK_Fixed ||
8098 ArgPassingKind == Sema::FAPK_Variadic;
8099 }
8100
8101 void DoneProcessing();
8102
8103 void HandleIncompleteSpecifier(const char *startSpecifier,
8104 unsigned specifierLen) override;
8105
8106 void HandleInvalidLengthModifier(
8107 const analyze_format_string::FormatSpecifier &FS,
8108 const analyze_format_string::ConversionSpecifier &CS,
8109 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8110
8111 void HandleNonStandardLengthModifier(
8112 const analyze_format_string::FormatSpecifier &FS,
8113 const char *startSpecifier, unsigned specifierLen);
8114
8115 void HandleNonStandardConversionSpecifier(
8116 const analyze_format_string::ConversionSpecifier &CS,
8117 const char *startSpecifier, unsigned specifierLen);
8118
8119 void HandlePosition(const char *startPos, unsigned posLen) override;
8120
8121 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8122 analyze_format_string::PositionContext p) override;
8123
8124 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8125
8126 void HandleNullChar(const char *nullCharacter) override;
8127
8128 template <typename Range>
8129 static void
8130 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8131 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8132 bool IsStringLocation, Range StringRange,
8133 ArrayRef<FixItHint> Fixit = {});
8134
8135protected:
8136 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8137 const char *startSpec,
8138 unsigned specifierLen,
8139 const char *csStart, unsigned csLen);
8140
8141 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8142 const char *startSpec,
8143 unsigned specifierLen);
8144
8145 SourceRange getFormatStringRange();
8146 CharSourceRange getSpecifierRange(const char *startSpecifier,
8147 unsigned specifierLen);
8148 SourceLocation getLocationOfByte(const char *x);
8149
8150 const Expr *getDataArg(unsigned i) const;
8151
8152 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8153 const analyze_format_string::ConversionSpecifier &CS,
8154 const char *startSpecifier, unsigned specifierLen,
8155 unsigned argIndex);
8156
8157 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8158 const Expr *E, const char *startSpecifier,
8159 unsigned specifierLen);
8160
8161 template <typename Range>
8162 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8163 bool IsStringLocation, Range StringRange,
8164 ArrayRef<FixItHint> Fixit = {});
8165};
8166
8167} // namespace
8168
8169SourceRange CheckFormatHandler::getFormatStringRange() {
8170 return OrigFormatExpr->getSourceRange();
8171}
8172
8173CharSourceRange
8174CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8175 unsigned specifierLen) {
8176 SourceLocation Start = getLocationOfByte(x: startSpecifier);
8177 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
8178
8179 // Advance the end SourceLocation by one due to half-open ranges.
8180 End = End.getLocWithOffset(Offset: 1);
8181
8182 return CharSourceRange::getCharRange(B: Start, E: End);
8183}
8184
8185SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8186 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
8187 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
8188}
8189
8190void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8191 unsigned specifierLen) {
8192 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
8193 Loc: getLocationOfByte(x: startSpecifier),
8194 /*IsStringLocation*/ true,
8195 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8196}
8197
8198bool CheckFormatHandler::CheckUnsupportedType(
8199 const analyze_format_string::ArgType &AT, const Expr *E,
8200 const char *StartSpecifier, unsigned SpecifierLen) {
8201 if (!AT.isUnsupported())
8202 return false;
8203
8204 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_unsupported_type)
8205 << AT.getRepresentativeTypeName(C&: S.Context),
8206 Loc: E->getExprLoc(), /*IsStringLocation=*/false,
8207 StringRange: getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen));
8208 return true;
8209}
8210
8211void CheckFormatHandler::HandleInvalidLengthModifier(
8212 const analyze_format_string::FormatSpecifier &FS,
8213 const analyze_format_string::ConversionSpecifier &CS,
8214 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8215 using namespace analyze_format_string;
8216
8217 const LengthModifier &LM = FS.getLengthModifier();
8218 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8219
8220 // See if we know how to fix this length modifier.
8221 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8222 if (FixedLM) {
8223 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8224 Loc: getLocationOfByte(x: LM.getStart()),
8225 /*IsStringLocation*/ true,
8226 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8227
8228 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8229 << FixedLM->toString()
8230 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8231
8232 } else {
8233 FixItHint Hint;
8234 if (DiagID == diag::warn_format_nonsensical_length)
8235 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
8236
8237 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8238 Loc: getLocationOfByte(x: LM.getStart()),
8239 /*IsStringLocation*/ true,
8240 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: Hint);
8241 }
8242}
8243
8244void CheckFormatHandler::HandleNonStandardLengthModifier(
8245 const analyze_format_string::FormatSpecifier &FS,
8246 const char *startSpecifier, unsigned specifierLen) {
8247 using namespace analyze_format_string;
8248
8249 const LengthModifier &LM = FS.getLengthModifier();
8250 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8251
8252 // See if we know how to fix this length modifier.
8253 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8254 if (FixedLM) {
8255 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8256 << LM.toString() << 0,
8257 Loc: getLocationOfByte(x: LM.getStart()),
8258 /*IsStringLocation*/ true,
8259 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8260
8261 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8262 << FixedLM->toString()
8263 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8264
8265 } else {
8266 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8267 << LM.toString() << 0,
8268 Loc: getLocationOfByte(x: LM.getStart()),
8269 /*IsStringLocation*/ true,
8270 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8271 }
8272}
8273
8274void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8275 const analyze_format_string::ConversionSpecifier &CS,
8276 const char *startSpecifier, unsigned specifierLen) {
8277 using namespace analyze_format_string;
8278
8279 // See if we know how to fix this conversion specifier.
8280 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8281 if (FixedCS) {
8282 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8283 << CS.toString() << /*conversion specifier*/ 1,
8284 Loc: getLocationOfByte(x: CS.getStart()),
8285 /*IsStringLocation*/ true,
8286 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8287
8288 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
8289 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
8290 << FixedCS->toString()
8291 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
8292 } else {
8293 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8294 << CS.toString() << /*conversion specifier*/ 1,
8295 Loc: getLocationOfByte(x: CS.getStart()),
8296 /*IsStringLocation*/ true,
8297 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8298 }
8299}
8300
8301void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8302 if (!S.getDiagnostics().isIgnored(
8303 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
8304 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
8305 Loc: getLocationOfByte(x: startPos),
8306 /*IsStringLocation*/ true,
8307 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8308}
8309
8310void CheckFormatHandler::HandleInvalidPosition(
8311 const char *startSpecifier, unsigned specifierLen,
8312 analyze_format_string::PositionContext p) {
8313 if (!S.getDiagnostics().isIgnored(
8314 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
8315 EmitFormatDiagnostic(
8316 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8317 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
8318 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8319}
8320
8321void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8322 unsigned posLen) {
8323 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
8324 Loc: SourceLocation()))
8325 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
8326 Loc: getLocationOfByte(x: startPos),
8327 /*IsStringLocation*/ true,
8328 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8329}
8330
8331void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8332 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
8333 // The presence of a null character is likely an error.
8334 EmitFormatDiagnostic(
8335 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
8336 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/ true,
8337 StringRange: getFormatStringRange());
8338 }
8339}
8340
8341// Note that this may return NULL if there was an error parsing or building
8342// one of the argument expressions.
8343const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8344 return Args[FirstDataArg + i];
8345}
8346
8347void CheckFormatHandler::DoneProcessing() {
8348 // Does the number of data arguments exceed the number of
8349 // format conversions in the format string?
8350 if (HasFormatArguments()) {
8351 // Find any arguments that weren't covered.
8352 CoveredArgs.flip();
8353 signed notCoveredArg = CoveredArgs.find_first();
8354 if (notCoveredArg >= 0) {
8355 assert((unsigned)notCoveredArg < NumDataArgs);
8356 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
8357 } else {
8358 UncoveredArg.setAllCovered();
8359 }
8360 }
8361}
8362
8363void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8364 const Expr *ArgExpr) {
8365 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8366
8367 if (!ArgExpr)
8368 return;
8369
8370 SourceLocation Loc = ArgExpr->getBeginLoc();
8371
8372 if (S.getSourceManager().isInSystemMacro(loc: Loc))
8373 return;
8374
8375 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
8376 for (auto E : DiagnosticExprs)
8377 PDiag << E->getSourceRange();
8378
8379 CheckFormatHandler::EmitFormatDiagnostic(
8380 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0], PDiag, Loc,
8381 /*IsStringLocation*/ false, StringRange: DiagnosticExprs[0]->getSourceRange());
8382}
8383
8384bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8385 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8386 unsigned specifierLen, const char *csStart, unsigned csLen) {
8387 bool keepGoing = true;
8388 if (argIndex < NumDataArgs) {
8389 // Consider the argument coverered, even though the specifier doesn't
8390 // make sense.
8391 CoveredArgs.set(argIndex);
8392 } else {
8393 // If argIndex exceeds the number of data arguments we
8394 // don't issue a warning because that is just a cascade of warnings (and
8395 // they may have intended '%%' anyway). We don't want to continue processing
8396 // the format string after this point, however, as we will like just get
8397 // gibberish when trying to match arguments.
8398 keepGoing = false;
8399 }
8400
8401 StringRef Specifier(csStart, csLen);
8402
8403 // If the specifier in non-printable, it could be the first byte of a UTF-8
8404 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8405 // hex value.
8406 std::string CodePointStr;
8407 if (!llvm::sys::locale::isPrint(c: *csStart)) {
8408 llvm::UTF32 CodePoint;
8409 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8410 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8411 llvm::ConversionResult Result =
8412 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
8413
8414 if (Result != llvm::conversionOK) {
8415 unsigned char FirstChar = *csStart;
8416 CodePoint = (llvm::UTF32)FirstChar;
8417 }
8418
8419 llvm::raw_string_ostream OS(CodePointStr);
8420 if (CodePoint < 256)
8421 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
8422 else if (CodePoint <= 0xFFFF)
8423 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
8424 else
8425 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
8426 Specifier = CodePointStr;
8427 }
8428
8429 EmitFormatDiagnostic(
8430 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
8431 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8432
8433 return keepGoing;
8434}
8435
8436void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8437 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8438 EmitFormatDiagnostic(
8439 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args), Loc,
8440 /*isStringLoc*/ IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8441}
8442
8443bool CheckFormatHandler::CheckNumArgs(
8444 const analyze_format_string::FormatSpecifier &FS,
8445 const analyze_format_string::ConversionSpecifier &CS,
8446 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8447
8448 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8449 PartialDiagnostic PDiag =
8450 FS.usesPositionalArg()
8451 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
8452 << (argIndex + 1) << NumDataArgs)
8453 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
8454 EmitFormatDiagnostic(PDiag, Loc: getLocationOfByte(x: CS.getStart()),
8455 /*IsStringLocation*/ true,
8456 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8457
8458 // Since more arguments than conversion tokens are given, by extension
8459 // all arguments are covered, so mark this as so.
8460 UncoveredArg.setAllCovered();
8461 return false;
8462 }
8463 return true;
8464}
8465
8466template <typename Range>
8467void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8468 SourceLocation Loc,
8469 bool IsStringLocation,
8470 Range StringRange,
8471 ArrayRef<FixItHint> FixIt) {
8472 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8473 IsStringLocation, StringRange, FixIt);
8474}
8475
8476/// If the format string is not within the function call, emit a note
8477/// so that the function call and string are in diagnostic messages.
8478///
8479/// \param InFunctionCall if true, the format string is within the function
8480/// call and only one diagnostic message will be produced. Otherwise, an
8481/// extra note will be emitted pointing to location of the format string.
8482///
8483/// \param ArgumentExpr the expression that is passed as the format string
8484/// argument in the function call. Used for getting locations when two
8485/// diagnostics are emitted.
8486///
8487/// \param PDiag the callee should already have provided any strings for the
8488/// diagnostic message. This function only adds locations and fixits
8489/// to diagnostics.
8490///
8491/// \param Loc primary location for diagnostic. If two diagnostics are
8492/// required, one will be at Loc and a new SourceLocation will be created for
8493/// the other one.
8494///
8495/// \param IsStringLocation if true, Loc points to the format string should be
8496/// used for the note. Otherwise, Loc points to the argument list and will
8497/// be used with PDiag.
8498///
8499/// \param StringRange some or all of the string to highlight. This is
8500/// templated so it can accept either a CharSourceRange or a SourceRange.
8501///
8502/// \param FixIt optional fix it hint for the format string.
8503template <typename Range>
8504void CheckFormatHandler::EmitFormatDiagnostic(
8505 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8506 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8507 Range StringRange, ArrayRef<FixItHint> FixIt) {
8508 if (InFunctionCall) {
8509 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8510 D << StringRange;
8511 D << FixIt;
8512 } else {
8513 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8514 << ArgumentExpr->getSourceRange();
8515
8516 const Sema::SemaDiagnosticBuilder &Note =
8517 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8518 diag::note_format_string_defined);
8519
8520 Note << StringRange;
8521 Note << FixIt;
8522 }
8523}
8524
8525//===--- CHECK: Printf format string checking -----------------------------===//
8526
8527namespace {
8528
8529class CheckPrintfHandler : public CheckFormatHandler {
8530public:
8531 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8532 const Expr *origFormatExpr, const FormatStringType type,
8533 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8534 const char *beg, Sema::FormatArgumentPassingKind APK,
8535 ArrayRef<const Expr *> Args, unsigned formatIdx,
8536 bool inFunctionCall, VariadicCallType CallType,
8537 llvm::SmallBitVector &CheckedVarArgs,
8538 UncoveredArgHandler &UncoveredArg)
8539 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8540 numDataArgs, beg, APK, Args, formatIdx,
8541 inFunctionCall, CallType, CheckedVarArgs,
8542 UncoveredArg) {}
8543
8544 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8545
8546 /// Returns true if '%@' specifiers are allowed in the format string.
8547 bool allowsObjCArg() const {
8548 return FSType == FormatStringType::NSString ||
8549 FSType == FormatStringType::OSLog ||
8550 FSType == FormatStringType::OSTrace;
8551 }
8552
8553 bool HandleInvalidPrintfConversionSpecifier(
8554 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8555 unsigned specifierLen) override;
8556
8557 void handleInvalidMaskType(StringRef MaskType) override;
8558
8559 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8560 const char *startSpecifier, unsigned specifierLen,
8561 const TargetInfo &Target) override;
8562 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8563 const char *StartSpecifier, unsigned SpecifierLen,
8564 const Expr *E);
8565
8566 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8567 unsigned k, const char *startSpecifier,
8568 unsigned specifierLen);
8569 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8570 const analyze_printf::OptionalAmount &Amt,
8571 unsigned type, const char *startSpecifier,
8572 unsigned specifierLen);
8573 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8574 const analyze_printf::OptionalFlag &flag,
8575 const char *startSpecifier, unsigned specifierLen);
8576 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8577 const analyze_printf::OptionalFlag &ignoredFlag,
8578 const analyze_printf::OptionalFlag &flag,
8579 const char *startSpecifier, unsigned specifierLen);
8580 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8581
8582 void HandleEmptyObjCModifierFlag(const char *startFlag,
8583 unsigned flagLen) override;
8584
8585 void HandleInvalidObjCModifierFlag(const char *startFlag,
8586 unsigned flagLen) override;
8587
8588 void
8589 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8590 const char *flagsEnd,
8591 const char *conversionPosition) override;
8592};
8593
8594/// Keeps around the information needed to verify that two specifiers are
8595/// compatible.
8596class EquatableFormatArgument {
8597public:
8598 enum SpecifierSensitivity : unsigned {
8599 SS_None,
8600 SS_Private,
8601 SS_Public,
8602 SS_Sensitive
8603 };
8604
8605 enum FormatArgumentRole : unsigned {
8606 FAR_Data,
8607 FAR_FieldWidth,
8608 FAR_Precision,
8609 FAR_Auxiliary, // FreeBSD kernel %b and %D
8610 };
8611
8612private:
8613 analyze_format_string::ArgType ArgType;
8614 analyze_format_string::LengthModifier LengthMod;
8615 StringRef SpecifierLetter;
8616 CharSourceRange Range;
8617 SourceLocation ElementLoc;
8618 FormatArgumentRole Role : 2;
8619 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8620 unsigned Position : 14;
8621 unsigned ModifierFor : 14; // not set for FAR_Data
8622
8623 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8624 bool InFunctionCall) const;
8625
8626public:
8627 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8628 analyze_format_string::LengthModifier LengthMod,
8629 StringRef SpecifierLetter,
8630 analyze_format_string::ArgType ArgType,
8631 FormatArgumentRole Role,
8632 SpecifierSensitivity Sensitivity, unsigned Position,
8633 unsigned ModifierFor)
8634 : ArgType(ArgType), LengthMod(LengthMod),
8635 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8636 Role(Role), Sensitivity(Sensitivity), Position(Position),
8637 ModifierFor(ModifierFor) {}
8638
8639 unsigned getPosition() const { return Position; }
8640 SourceLocation getSourceLocation() const { return ElementLoc; }
8641 CharSourceRange getSourceRange() const { return Range; }
8642 analyze_format_string::LengthModifier getLengthModifier() const {
8643 return LengthMod;
8644 }
8645 void setModifierFor(unsigned V) { ModifierFor = V; }
8646
8647 std::string buildFormatSpecifier() const {
8648 std::string result;
8649 llvm::raw_string_ostream(result)
8650 << getLengthModifier().toString() << SpecifierLetter;
8651 return result;
8652 }
8653
8654 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8655 const Expr *FmtExpr, bool InFunctionCall) const;
8656};
8657
8658/// Turns format strings into lists of EquatableSpecifier objects.
8659class DecomposePrintfHandler : public CheckPrintfHandler {
8660 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8661 bool HadError;
8662
8663 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8664 const Expr *origFormatExpr,
8665 const FormatStringType type, unsigned firstDataArg,
8666 unsigned numDataArgs, bool isObjC, const char *beg,
8667 Sema::FormatArgumentPassingKind APK,
8668 ArrayRef<const Expr *> Args, unsigned formatIdx,
8669 bool inFunctionCall, VariadicCallType CallType,
8670 llvm::SmallBitVector &CheckedVarArgs,
8671 UncoveredArgHandler &UncoveredArg,
8672 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8673 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8674 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8675 inFunctionCall, CallType, CheckedVarArgs,
8676 UncoveredArg),
8677 Specs(Specs), HadError(false) {}
8678
8679public:
8680 static bool
8681 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8682 FormatStringType type, bool IsObjC, bool InFunctionCall,
8683 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8684
8685 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8686 const char *startSpecifier,
8687 unsigned specifierLen,
8688 const TargetInfo &Target) override;
8689};
8690
8691} // namespace
8692
8693bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8694 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8695 unsigned specifierLen) {
8696 const analyze_printf::PrintfConversionSpecifier &CS =
8697 FS.getConversionSpecifier();
8698
8699 return HandleInvalidConversionSpecifier(
8700 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
8701 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
8702}
8703
8704void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8705 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8706}
8707
8708// Error out if struct or complex type argments are passed to os_log.
8709static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8710 QualType T) {
8711 if (FSType != FormatStringType::OSLog)
8712 return false;
8713 return T->isRecordType() || T->isComplexType();
8714}
8715
8716bool CheckPrintfHandler::HandleAmount(
8717 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8718 const char *startSpecifier, unsigned specifierLen) {
8719 if (Amt.hasDataArgument()) {
8720 if (HasFormatArguments()) {
8721 unsigned argIndex = Amt.getArgIndex();
8722 if (argIndex >= NumDataArgs) {
8723 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8724 << k,
8725 Loc: getLocationOfByte(x: Amt.getStart()),
8726 /*IsStringLocation*/ true,
8727 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8728 // Don't do any more checking. We will just emit
8729 // spurious errors.
8730 return false;
8731 }
8732
8733 // Type check the data argument. It should be an 'int'.
8734 // Although not in conformance with C99, we also allow the argument to be
8735 // an 'unsigned int' as that is a reasonably safe case. GCC also
8736 // doesn't emit a warning for that case.
8737 CoveredArgs.set(argIndex);
8738 const Expr *Arg = getDataArg(i: argIndex);
8739 if (!Arg)
8740 return false;
8741
8742 QualType T = Arg->getType();
8743
8744 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8745 assert(AT.isValid());
8746
8747 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8748 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8749 ? diag::err_printf_asterisk_wrong_type
8750 : diag::warn_printf_asterisk_wrong_type;
8751 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8752 << k << AT.getRepresentativeTypeName(C&: S.Context)
8753 << T << Arg->getSourceRange(),
8754 Loc: getLocationOfByte(x: Amt.getStart()),
8755 /*IsStringLocation*/ true,
8756 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8757 // Don't do any more checking. We will just emit
8758 // spurious errors.
8759 return false;
8760 }
8761 }
8762 }
8763 return true;
8764}
8765
8766void CheckPrintfHandler::HandleInvalidAmount(
8767 const analyze_printf::PrintfSpecifier &FS,
8768 const analyze_printf::OptionalAmount &Amt, unsigned type,
8769 const char *startSpecifier, unsigned specifierLen) {
8770 const analyze_printf::PrintfConversionSpecifier &CS =
8771 FS.getConversionSpecifier();
8772
8773 FixItHint fixit =
8774 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8775 ? FixItHint::CreateRemoval(
8776 RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength()))
8777 : FixItHint();
8778
8779 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8780 << type << CS.toString(),
8781 Loc: getLocationOfByte(x: Amt.getStart()),
8782 /*IsStringLocation*/ true,
8783 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: fixit);
8784}
8785
8786void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8787 const analyze_printf::OptionalFlag &flag,
8788 const char *startSpecifier,
8789 unsigned specifierLen) {
8790 // Warn about pointless flag with a fixit removal.
8791 const analyze_printf::PrintfConversionSpecifier &CS =
8792 FS.getConversionSpecifier();
8793 EmitFormatDiagnostic(
8794 PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8795 << flag.toString() << CS.toString(),
8796 Loc: getLocationOfByte(x: flag.getPosition()),
8797 /*IsStringLocation*/ true,
8798 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8799 FixIt: FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8800}
8801
8802void CheckPrintfHandler::HandleIgnoredFlag(
8803 const analyze_printf::PrintfSpecifier &FS,
8804 const analyze_printf::OptionalFlag &ignoredFlag,
8805 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8806 unsigned specifierLen) {
8807 // Warn about ignored flag with a fixit removal.
8808 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8809 << ignoredFlag.toString() << flag.toString(),
8810 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8811 /*IsStringLocation*/ true,
8812 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8813 FixIt: FixItHint::CreateRemoval(
8814 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8815}
8816
8817void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8818 unsigned flagLen) {
8819 // Warn about an empty flag.
8820 EmitFormatDiagnostic(
8821 PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag), Loc: getLocationOfByte(x: startFlag),
8822 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8823}
8824
8825void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8826 unsigned flagLen) {
8827 // Warn about an invalid flag.
8828 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8829 StringRef flag(startFlag, flagLen);
8830 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8831 Loc: getLocationOfByte(x: startFlag),
8832 /*IsStringLocation*/ true, StringRange: Range,
8833 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8834}
8835
8836void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8837 const char *flagsStart, const char *flagsEnd,
8838 const char *conversionPosition) {
8839 // Warn about using '[...]' without a '@' conversion.
8840 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8841 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8842 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8843 Loc: getLocationOfByte(x: conversionPosition),
8844 /*IsStringLocation*/ true, StringRange: Range,
8845 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8846}
8847
8848void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8849 const Expr *FmtExpr,
8850 bool InFunctionCall) const {
8851 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8852 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8853}
8854
8855bool EquatableFormatArgument::VerifyCompatible(
8856 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8857 bool InFunctionCall) const {
8858 using MK = analyze_format_string::ArgType::MatchKind;
8859 if (Role != Other.Role) {
8860 // diagnose and stop
8861 EmitDiagnostic(
8862 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8863 FmtExpr, InFunctionCall);
8864 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8865 return false;
8866 }
8867
8868 if (Role != FAR_Data) {
8869 if (ModifierFor != Other.ModifierFor) {
8870 // diagnose and stop
8871 EmitDiagnostic(S,
8872 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8873 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8874 FmtExpr, InFunctionCall);
8875 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8876 return false;
8877 }
8878 return true;
8879 }
8880
8881 bool HadError = false;
8882 if (Sensitivity != Other.Sensitivity) {
8883 // diagnose and continue
8884 EmitDiagnostic(S,
8885 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
8886 << Sensitivity << Other.Sensitivity,
8887 FmtExpr, InFunctionCall);
8888 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8889 << 0 << Other.Range;
8890 }
8891
8892 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
8893 case MK::Match:
8894 break;
8895
8896 case MK::MatchPromotion:
8897 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8898 // MatchPromotion is treated as a failure by format_matches.
8899 case MK::NoMatch:
8900 case MK::NoMatchTypeConfusion:
8901 case MK::NoMatchPromotionTypeConfusion:
8902 EmitDiagnostic(S,
8903 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
8904 << buildFormatSpecifier()
8905 << Other.buildFormatSpecifier(),
8906 FmtExpr, InFunctionCall);
8907 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8908 << 0 << Other.Range;
8909 break;
8910
8911 case MK::NoMatchPedantic:
8912 EmitDiagnostic(S,
8913 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
8914 << buildFormatSpecifier()
8915 << Other.buildFormatSpecifier(),
8916 FmtExpr, InFunctionCall);
8917 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8918 << 0 << Other.Range;
8919 break;
8920
8921 case MK::NoMatchSignedness:
8922 EmitDiagnostic(S,
8923 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
8924 << buildFormatSpecifier()
8925 << Other.buildFormatSpecifier(),
8926 FmtExpr, InFunctionCall);
8927 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8928 << 0 << Other.Range;
8929 break;
8930 }
8931 return !HadError;
8932}
8933
8934bool DecomposePrintfHandler::GetSpecifiers(
8935 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8936 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8937 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
8938 StringRef Data = FSL->getString();
8939 const char *Str = Data.data();
8940 llvm::SmallBitVector BV;
8941 UncoveredArgHandler UA;
8942 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8943 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8944 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8945 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8946 UA, Args);
8947
8948 if (!analyze_format_string::ParsePrintfString(
8949 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
8950 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
8951 H.DoneProcessing();
8952 if (H.HadError)
8953 return false;
8954
8955 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
8956 const EquatableFormatArgument &B) {
8957 return A.getPosition() < B.getPosition();
8958 });
8959 return true;
8960}
8961
8962bool DecomposePrintfHandler::HandlePrintfSpecifier(
8963 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8964 unsigned specifierLen, const TargetInfo &Target) {
8965 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8966 specifierLen, Target)) {
8967 HadError = true;
8968 return false;
8969 }
8970
8971 // Do not add any specifiers to the list for %%. This is possibly incorrect
8972 // if using a precision/width with a data argument, but that combination is
8973 // meaningless and we wouldn't know which format to attach the
8974 // precision/width to.
8975 const auto &CS = FS.getConversionSpecifier();
8976 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
8977 return true;
8978
8979 // have to patch these to have the right ModifierFor if they are used
8980 const unsigned Unset = ~0;
8981 unsigned FieldWidthIndex = Unset;
8982 unsigned PrecisionIndex = Unset;
8983
8984 // field width?
8985 const auto &FieldWidth = FS.getFieldWidth();
8986 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8987 FieldWidthIndex = Specs.size();
8988 Specs.emplace_back(
8989 Args: getSpecifierRange(startSpecifier, specifierLen),
8990 Args: getLocationOfByte(x: FieldWidth.getStart()),
8991 Args: analyze_format_string::LengthModifier(), Args: FieldWidth.getCharacters(),
8992 Args: FieldWidth.getArgType(Ctx&: S.Context),
8993 Args: EquatableFormatArgument::FAR_FieldWidth,
8994 Args: EquatableFormatArgument::SS_None,
8995 Args: FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8996 : FieldWidthIndex,
8997 Args: 0);
8998 }
8999 // precision?
9000 const auto &Precision = FS.getPrecision();
9001 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9002 PrecisionIndex = Specs.size();
9003 Specs.emplace_back(
9004 Args: getSpecifierRange(startSpecifier, specifierLen),
9005 Args: getLocationOfByte(x: Precision.getStart()),
9006 Args: analyze_format_string::LengthModifier(), Args: Precision.getCharacters(),
9007 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
9008 Args: EquatableFormatArgument::SS_None,
9009 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9010 : PrecisionIndex,
9011 Args: 0);
9012 }
9013
9014 // this specifier
9015 unsigned SpecIndex =
9016 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9017 if (FieldWidthIndex != Unset)
9018 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9019 if (PrecisionIndex != Unset)
9020 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9021
9022 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9023 if (FS.isPrivate())
9024 Sensitivity = EquatableFormatArgument::SS_Private;
9025 else if (FS.isPublic())
9026 Sensitivity = EquatableFormatArgument::SS_Public;
9027 else if (FS.isSensitive())
9028 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9029 else
9030 Sensitivity = EquatableFormatArgument::SS_None;
9031
9032 Specs.emplace_back(
9033 Args: getSpecifierRange(startSpecifier, specifierLen),
9034 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier(),
9035 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
9036 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
9037
9038 // auxiliary argument?
9039 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
9040 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
9041 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
9042 Args: getLocationOfByte(x: CS.getStart()),
9043 Args: analyze_format_string::LengthModifier(),
9044 Args: CS.getCharacters(),
9045 Args: analyze_format_string::ArgType::CStrTy,
9046 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
9047 Args: SpecIndex + 1, Args&: SpecIndex);
9048 }
9049 return true;
9050}
9051
9052// Determines if the specified is a C++ class or struct containing
9053// a member with the specified name and kind (e.g. a CXXMethodDecl named
9054// "c_str()").
9055template<typename MemberKind>
9056static llvm::SmallPtrSet<MemberKind*, 1>
9057CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9058 auto *RD = Ty->getAsCXXRecordDecl();
9059 llvm::SmallPtrSet<MemberKind*, 1> Results;
9060
9061 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9062 return Results;
9063
9064 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9065 Sema::LookupMemberName);
9066 R.suppressDiagnostics();
9067
9068 // We just need to include all members of the right kind turned up by the
9069 // filter, at this point.
9070 if (S.LookupQualifiedName(R, LookupCtx: RD))
9071 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9072 NamedDecl *decl = (*I)->getUnderlyingDecl();
9073 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9074 Results.insert(FK);
9075 }
9076 return Results;
9077}
9078
9079/// Check if we could call '.c_str()' on an object.
9080///
9081/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9082/// allow the call, or if it would be ambiguous).
9083bool Sema::hasCStrMethod(const Expr *E) {
9084 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9085
9086 MethodSet Results =
9087 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
9088 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9089 MI != ME; ++MI)
9090 if ((*MI)->getMinRequiredArguments() == 0)
9091 return true;
9092 return false;
9093}
9094
9095// Check if a (w)string was passed when a (w)char* was needed, and offer a
9096// better diagnostic if so. AT is assumed to be valid.
9097// Returns true when a c_str() conversion method is found.
9098bool CheckPrintfHandler::checkForCStrMembers(
9099 const analyze_printf::ArgType &AT, const Expr *E) {
9100 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9101
9102 MethodSet Results =
9103 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
9104
9105 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9106 MI != ME; ++MI) {
9107 const CXXMethodDecl *Method = *MI;
9108 if (Method->getMinRequiredArguments() == 0 &&
9109 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
9110 // FIXME: Suggest parens if the expression needs them.
9111 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
9112 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
9113 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
9114 return true;
9115 }
9116 }
9117
9118 return false;
9119}
9120
9121bool CheckPrintfHandler::HandlePrintfSpecifier(
9122 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9123 unsigned specifierLen, const TargetInfo &Target) {
9124 using namespace analyze_format_string;
9125 using namespace analyze_printf;
9126
9127 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9128
9129 if (FS.consumesDataArgument()) {
9130 if (atFirstArg) {
9131 atFirstArg = false;
9132 usesPositionalArgs = FS.usesPositionalArg();
9133 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9134 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9135 startSpec: startSpecifier, specifierLen);
9136 return false;
9137 }
9138 }
9139
9140 // First check if the field width, precision, and conversion specifier
9141 // have matching data arguments.
9142 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0, startSpecifier,
9143 specifierLen)) {
9144 return false;
9145 }
9146
9147 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1, startSpecifier,
9148 specifierLen)) {
9149 return false;
9150 }
9151
9152 if (!CS.consumesDataArgument()) {
9153 // FIXME: Technically specifying a precision or field width here
9154 // makes no sense. Worth issuing a warning at some point.
9155 return true;
9156 }
9157
9158 // Consume the argument.
9159 unsigned argIndex = FS.getArgIndex();
9160 if (argIndex < NumDataArgs) {
9161 // The check to see if the argIndex is valid will come later.
9162 // We set the bit here because we may exit early from this
9163 // function if we encounter some other error.
9164 CoveredArgs.set(argIndex);
9165 }
9166
9167 // FreeBSD kernel extensions.
9168 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9169 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9170 // We need at least two arguments.
9171 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
9172 return false;
9173
9174 if (HasFormatArguments()) {
9175 // Claim the second argument.
9176 CoveredArgs.set(argIndex + 1);
9177
9178 // Type check the first argument (int for %b, pointer for %D)
9179 const Expr *Ex = getDataArg(i: argIndex);
9180 const analyze_printf::ArgType &AT =
9181 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9182 ? ArgType(S.Context.IntTy)
9183 : ArgType::CPointerTy;
9184 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
9185 EmitFormatDiagnostic(
9186 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9187 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9188 << false << Ex->getSourceRange(),
9189 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9190 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9191
9192 // Type check the second argument (char * for both %b and %D)
9193 Ex = getDataArg(i: argIndex + 1);
9194 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9195 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
9196 EmitFormatDiagnostic(
9197 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9198 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9199 << false << Ex->getSourceRange(),
9200 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9201 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9202 }
9203 return true;
9204 }
9205
9206 // Check for using an Objective-C specific conversion specifier
9207 // in a non-ObjC literal.
9208 if (!allowsObjCArg() && CS.isObjCArg()) {
9209 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9210 specifierLen);
9211 }
9212
9213 // %P can only be used with os_log.
9214 if (FSType != FormatStringType::OSLog &&
9215 CS.getKind() == ConversionSpecifier::PArg) {
9216 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9217 specifierLen);
9218 }
9219
9220 // %n is not allowed with os_log.
9221 if (FSType == FormatStringType::OSLog &&
9222 CS.getKind() == ConversionSpecifier::nArg) {
9223 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
9224 Loc: getLocationOfByte(x: CS.getStart()),
9225 /*IsStringLocation*/ false,
9226 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9227
9228 return true;
9229 }
9230
9231 // Only scalars are allowed for os_trace.
9232 if (FSType == FormatStringType::OSTrace &&
9233 (CS.getKind() == ConversionSpecifier::PArg ||
9234 CS.getKind() == ConversionSpecifier::sArg ||
9235 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9236 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9237 specifierLen);
9238 }
9239
9240 // Check for use of public/private annotation outside of os_log().
9241 if (FSType != FormatStringType::OSLog) {
9242 if (FS.isPublic().isSet()) {
9243 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9244 << "public",
9245 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
9246 /*IsStringLocation*/ false,
9247 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9248 }
9249 if (FS.isPrivate().isSet()) {
9250 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9251 << "private",
9252 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
9253 /*IsStringLocation*/ false,
9254 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9255 }
9256 }
9257
9258 const llvm::Triple &Triple = Target.getTriple();
9259 if (CS.getKind() == ConversionSpecifier::nArg &&
9260 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9261 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
9262 Loc: getLocationOfByte(x: CS.getStart()),
9263 /*IsStringLocation*/ false,
9264 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9265 }
9266
9267 // Check for invalid use of field width
9268 if (!FS.hasValidFieldWidth()) {
9269 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
9270 startSpecifier, specifierLen);
9271 }
9272
9273 // Check for invalid use of precision
9274 if (!FS.hasValidPrecision()) {
9275 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
9276 startSpecifier, specifierLen);
9277 }
9278
9279 // Precision is mandatory for %P specifier.
9280 if (CS.getKind() == ConversionSpecifier::PArg &&
9281 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9282 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
9283 Loc: getLocationOfByte(x: startSpecifier),
9284 /*IsStringLocation*/ false,
9285 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9286 }
9287
9288 // Check each flag does not conflict with any other component.
9289 if (!FS.hasValidThousandsGroupingPrefix())
9290 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9291 if (!FS.hasValidLeadingZeros())
9292 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
9293 if (!FS.hasValidPlusPrefix())
9294 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
9295 if (!FS.hasValidSpacePrefix())
9296 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
9297 if (!FS.hasValidAlternativeForm())
9298 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
9299 if (!FS.hasValidLeftJustified())
9300 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
9301
9302 // Check that flags are not ignored by another flag
9303 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9304 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
9305 startSpecifier, specifierLen);
9306 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9307 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
9308 startSpecifier, specifierLen);
9309
9310 // Check the length modifier is valid with the given conversion specifier.
9311 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9312 LO: S.getLangOpts()))
9313 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9314 DiagID: diag::warn_format_nonsensical_length);
9315 else if (!FS.hasStandardLengthModifier())
9316 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9317 else if (!FS.hasStandardLengthConversionCombination())
9318 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9319 DiagID: diag::warn_format_non_standard_conversion_spec);
9320
9321 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9322 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9323
9324 // The remaining checks depend on the data arguments.
9325 if (!HasFormatArguments())
9326 return true;
9327
9328 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9329 return false;
9330
9331 const Expr *Arg = getDataArg(i: argIndex);
9332 if (!Arg)
9333 return true;
9334
9335 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
9336}
9337
9338static bool requiresParensToAddCast(const Expr *E) {
9339 // FIXME: We should have a general way to reason about operator
9340 // precedence and whether parens are actually needed here.
9341 // Take care of a few common cases where they aren't.
9342 const Expr *Inside = E->IgnoreImpCasts();
9343 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
9344 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9345
9346 switch (Inside->getStmtClass()) {
9347 case Stmt::ArraySubscriptExprClass:
9348 case Stmt::CallExprClass:
9349 case Stmt::CharacterLiteralClass:
9350 case Stmt::CXXBoolLiteralExprClass:
9351 case Stmt::DeclRefExprClass:
9352 case Stmt::FloatingLiteralClass:
9353 case Stmt::IntegerLiteralClass:
9354 case Stmt::MemberExprClass:
9355 case Stmt::ObjCArrayLiteralClass:
9356 case Stmt::ObjCBoolLiteralExprClass:
9357 case Stmt::ObjCBoxedExprClass:
9358 case Stmt::ObjCDictionaryLiteralClass:
9359 case Stmt::ObjCEncodeExprClass:
9360 case Stmt::ObjCIvarRefExprClass:
9361 case Stmt::ObjCMessageExprClass:
9362 case Stmt::ObjCPropertyRefExprClass:
9363 case Stmt::ObjCStringLiteralClass:
9364 case Stmt::ObjCSubscriptRefExprClass:
9365 case Stmt::ParenExprClass:
9366 case Stmt::StringLiteralClass:
9367 case Stmt::UnaryOperatorClass:
9368 return false;
9369 default:
9370 return true;
9371 }
9372}
9373
9374static std::pair<QualType, StringRef>
9375shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9376 const Expr *E) {
9377 // Use a 'while' to peel off layers of typedefs.
9378 QualType TyTy = IntendedTy;
9379 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9380 StringRef Name = UserTy->getDecl()->getName();
9381 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9382 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
9383 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
9384 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
9385 .Case(S: "SInt32", Value: Context.IntTy)
9386 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
9387 .Default(Value: QualType());
9388
9389 if (!CastTy.isNull())
9390 return std::make_pair(x&: CastTy, y&: Name);
9391
9392 TyTy = UserTy->desugar();
9393 }
9394
9395 // Strip parens if necessary.
9396 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
9397 return shouldNotPrintDirectly(Context, IntendedTy: PE->getSubExpr()->getType(),
9398 E: PE->getSubExpr());
9399
9400 // If this is a conditional expression, then its result type is constructed
9401 // via usual arithmetic conversions and thus there might be no necessary
9402 // typedef sugar there. Recurse to operands to check for NSInteger &
9403 // Co. usage condition.
9404 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
9405 QualType TrueTy, FalseTy;
9406 StringRef TrueName, FalseName;
9407
9408 std::tie(args&: TrueTy, args&: TrueName) = shouldNotPrintDirectly(
9409 Context, IntendedTy: CO->getTrueExpr()->getType(), E: CO->getTrueExpr());
9410 std::tie(args&: FalseTy, args&: FalseName) = shouldNotPrintDirectly(
9411 Context, IntendedTy: CO->getFalseExpr()->getType(), E: CO->getFalseExpr());
9412
9413 if (TrueTy == FalseTy)
9414 return std::make_pair(x&: TrueTy, y&: TrueName);
9415 else if (TrueTy.isNull())
9416 return std::make_pair(x&: FalseTy, y&: FalseName);
9417 else if (FalseTy.isNull())
9418 return std::make_pair(x&: TrueTy, y&: TrueName);
9419 }
9420
9421 return std::make_pair(x: QualType(), y: StringRef());
9422}
9423
9424/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9425/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9426/// type do not count.
9427static bool isArithmeticArgumentPromotion(Sema &S,
9428 const ImplicitCastExpr *ICE) {
9429 QualType From = ICE->getSubExpr()->getType();
9430 QualType To = ICE->getType();
9431 // It's an integer promotion if the destination type is the promoted
9432 // source type.
9433 if (ICE->getCastKind() == CK_IntegralCast &&
9434 S.Context.isPromotableIntegerType(T: From) &&
9435 S.Context.getPromotedIntegerType(PromotableType: From) == To)
9436 return true;
9437 // Look through vector types, since we do default argument promotion for
9438 // those in OpenCL.
9439 if (const auto *VecTy = From->getAs<ExtVectorType>())
9440 From = VecTy->getElementType();
9441 if (const auto *VecTy = To->getAs<ExtVectorType>())
9442 To = VecTy->getElementType();
9443 // It's a floating promotion if the source type is a lower rank.
9444 return ICE->getCastKind() == CK_FloatingCast &&
9445 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9446}
9447
9448static analyze_format_string::ArgType::MatchKind
9449handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9450 DiagnosticsEngine &Diags, SourceLocation Loc) {
9451 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9452 if (Diags.isIgnored(
9453 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9454 Loc) ||
9455 Diags.isIgnored(
9456 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9457 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9458 return analyze_format_string::ArgType::Match;
9459 }
9460 }
9461 return Match;
9462}
9463
9464bool CheckPrintfHandler::checkFormatExpr(
9465 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9466 unsigned SpecifierLen, const Expr *E) {
9467 using namespace analyze_format_string;
9468 using namespace analyze_printf;
9469
9470 // Now type check the data expression that matches the
9471 // format specifier.
9472 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9473 if (!AT.isValid())
9474 return true;
9475
9476 QualType ExprTy = E->getType();
9477 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9478 ExprTy = TET->getUnderlyingExpr()->getType();
9479 }
9480
9481 if (const OverflowBehaviorType *OBT =
9482 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9483 ExprTy = OBT->getUnderlyingType();
9484
9485 // When using the format attribute in C++, you can receive a function or an
9486 // array that will necessarily decay to a pointer when passed to the final
9487 // format consumer. Apply decay before type comparison.
9488 if (ExprTy->canDecayToPointerType())
9489 ExprTy = S.Context.getDecayedType(T: ExprTy);
9490
9491 // Diagnose attempts to print a boolean value as a character. Unlike other
9492 // -Wformat diagnostics, this is fine from a type perspective, but it still
9493 // doesn't make sense.
9494 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9495 E->isKnownToHaveBooleanValue()) {
9496 const CharSourceRange &CSR =
9497 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9498 SmallString<4> FSString;
9499 llvm::raw_svector_ostream os(FSString);
9500 FS.toString(os);
9501 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9502 << FSString,
9503 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9504 return true;
9505 }
9506
9507 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9508 // dumping raw class data (like is-a pointer), not actual data.
9509 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9510 ExprTy->isObjCObjectPointerType()) {
9511 const CharSourceRange &CSR =
9512 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9513 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9514 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9515 return true;
9516 }
9517
9518 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9519 return true;
9520
9521 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9522 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9523 ArgType::MatchKind OrigMatch = Match;
9524
9525 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9526 if (Match == ArgType::Match)
9527 return true;
9528
9529 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9530 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9531
9532 // Look through argument promotions for our error message's reported type.
9533 // This includes the integral and floating promotions, but excludes array
9534 // and function pointer decay (seeing that an argument intended to be a
9535 // string has type 'char [6]' is probably more confusing than 'char *') and
9536 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9537 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9538 if (isArithmeticArgumentPromotion(S, ICE)) {
9539 E = ICE->getSubExpr();
9540 ExprTy = E->getType();
9541
9542 // Check if we didn't match because of an implicit cast from a 'char'
9543 // or 'short' to an 'int'. This is done because printf is a varargs
9544 // function.
9545 if (ICE->getType() == S.Context.IntTy ||
9546 ICE->getType() == S.Context.UnsignedIntTy) {
9547 // All further checking is done on the subexpression
9548 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9549 if (OrigMatch == ArgType::NoMatchSignedness &&
9550 ImplicitMatch != ArgType::NoMatchSignedness)
9551 // If the original match was a signedness match this match on the
9552 // implicit cast type also need to be signedness match otherwise we
9553 // might introduce new unexpected warnings from -Wformat-signedness.
9554 return true;
9555 ImplicitMatch = handleFormatSignedness(
9556 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9557 if (ImplicitMatch == ArgType::Match)
9558 return true;
9559 }
9560 }
9561 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9562 // Special case for 'a', which has type 'int' in C.
9563 // Note, however, that we do /not/ want to treat multibyte constants like
9564 // 'MooV' as characters! This form is deprecated but still exists. In
9565 // addition, don't treat expressions as of type 'char' if one byte length
9566 // modifier is provided.
9567 if (ExprTy == S.Context.IntTy &&
9568 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9569 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9570 ExprTy = S.Context.CharTy;
9571 // To improve check results, we consider a character literal in C
9572 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9573 // more likely a type confusion situation, so we will suggest to
9574 // use '%hhd' instead by discarding the MatchPromotion.
9575 if (Match == ArgType::MatchPromotion)
9576 Match = ArgType::NoMatch;
9577 }
9578 }
9579 if (Match == ArgType::MatchPromotion) {
9580 // WG14 N2562 only clarified promotions in *printf
9581 // For NSLog in ObjC, just preserve -Wformat behavior
9582 if (!S.getLangOpts().ObjC &&
9583 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9584 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9585 return true;
9586 Match = ArgType::NoMatch;
9587 }
9588 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9589 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9590 Match = ImplicitMatch;
9591 assert(Match != ArgType::MatchPromotion);
9592
9593 // Look through unscoped enums to their underlying type.
9594 bool IsEnum = false;
9595 bool IsScopedEnum = false;
9596 QualType IntendedTy = ExprTy;
9597 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9598 IntendedTy = ED->getIntegerType();
9599 if (!ED->isScoped()) {
9600 ExprTy = IntendedTy;
9601 // This controls whether we're talking about the underlying type or not,
9602 // which we only want to do when it's an unscoped enum.
9603 IsEnum = true;
9604 } else {
9605 IsScopedEnum = true;
9606 }
9607 }
9608
9609 // %C in an Objective-C context prints a unichar, not a wchar_t.
9610 // If the argument is an integer of some kind, believe the %C and suggest
9611 // a cast instead of changing the conversion specifier.
9612 if (isObjCContext() &&
9613 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9614 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9615 !ExprTy->isCharType()) {
9616 // 'unichar' is defined as a typedef of unsigned short, but we should
9617 // prefer using the typedef if it is visible.
9618 IntendedTy = S.Context.UnsignedShortTy;
9619
9620 // While we are here, check if the value is an IntegerLiteral that happens
9621 // to be within the valid range.
9622 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9623 const llvm::APInt &V = IL->getValue();
9624 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9625 return true;
9626 }
9627
9628 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9629 Sema::LookupOrdinaryName);
9630 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9631 NamedDecl *ND = Result.getFoundDecl();
9632 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9633 if (TD->getUnderlyingType() == IntendedTy)
9634 IntendedTy =
9635 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9636 /*Qualifier=*/std::nullopt, Decl: TD);
9637 }
9638 }
9639 }
9640
9641 // Special-case some of Darwin's platform-independence types by suggesting
9642 // casts to primitive types that are known to be large enough.
9643 bool ShouldNotPrintDirectly = false;
9644 StringRef CastTyName;
9645 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9646 QualType CastTy;
9647 std::tie(args&: CastTy, args&: CastTyName) =
9648 shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9649 if (!CastTy.isNull()) {
9650 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9651 // (long in ASTContext). Only complain to pedants or when they're the
9652 // underlying type of a scoped enum (which always needs a cast).
9653 if (!IsScopedEnum &&
9654 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9655 (AT.isSizeT() || AT.isPtrdiffT()) &&
9656 AT.matchesType(C&: S.Context, argTy: CastTy))
9657 Match = ArgType::NoMatchPedantic;
9658 IntendedTy = CastTy;
9659 ShouldNotPrintDirectly = true;
9660 }
9661 }
9662
9663 // We may be able to offer a FixItHint if it is a supported type.
9664 PrintfSpecifier fixedFS = FS;
9665 bool Success =
9666 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9667
9668 if (Success) {
9669 // Get the fix string from the fixed format specifier
9670 SmallString<16> buf;
9671 llvm::raw_svector_ostream os(buf);
9672 fixedFS.toString(os);
9673
9674 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9675
9676 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9677 unsigned Diag;
9678 switch (Match) {
9679 case ArgType::Match:
9680 case ArgType::MatchPromotion:
9681 case ArgType::NoMatchPromotionTypeConfusion:
9682 llvm_unreachable("expected non-matching");
9683 case ArgType::NoMatchSignedness:
9684 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9685 break;
9686 case ArgType::NoMatchPedantic:
9687 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9688 break;
9689 case ArgType::NoMatchTypeConfusion:
9690 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9691 break;
9692 case ArgType::NoMatch:
9693 Diag = diag::warn_format_conversion_argument_type_mismatch;
9694 break;
9695 }
9696
9697 // In this case, the specifier is wrong and should be changed to match
9698 // the argument.
9699 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9700 << AT.getRepresentativeTypeName(C&: S.Context)
9701 << IntendedTy << IsEnum << E->getSourceRange(),
9702 Loc: E->getBeginLoc(),
9703 /*IsStringLocation*/ false, StringRange: SpecRange,
9704 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9705 } else {
9706 // The canonical type for formatting this value is different from the
9707 // actual type of the expression. (This occurs, for example, with Darwin's
9708 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9709 // should be printed as 'long' for 64-bit compatibility.)
9710 // Rather than emitting a normal format/argument mismatch, we want to
9711 // add a cast to the recommended type (and correct the format string
9712 // if necessary). We should also do so for scoped enumerations.
9713 SmallString<16> CastBuf;
9714 llvm::raw_svector_ostream CastFix(CastBuf);
9715 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9716 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9717 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9718
9719 SmallVector<FixItHint, 4> Hints;
9720 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9721 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9722 Loc: E->getExprLoc());
9723 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9724 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9725
9726 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9727 // If there's already a cast present, just replace it.
9728 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9729 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9730
9731 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9732 // If the expression has high enough precedence,
9733 // just write the C-style cast.
9734 Hints.push_back(
9735 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9736 } else {
9737 // Otherwise, add parens around the expression as well as the cast.
9738 CastFix << "(";
9739 Hints.push_back(
9740 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9741
9742 // We don't use getLocForEndOfToken because it returns invalid source
9743 // locations for macro expansions (by design).
9744 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9745 SourceLocation After = EndLoc.getLocWithOffset(
9746 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9747 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9748 }
9749
9750 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9751 // The expression has a type that should not be printed directly.
9752 // We extract the name from the typedef because we don't want to show
9753 // the underlying type in the diagnostic.
9754 StringRef Name;
9755 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9756 Name = TypedefTy->getDecl()->getName();
9757 else
9758 Name = CastTyName;
9759 unsigned Diag = Match == ArgType::NoMatchPedantic
9760 ? diag::warn_format_argument_needs_cast_pedantic
9761 : diag::warn_format_argument_needs_cast;
9762 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9763 << E->getSourceRange(),
9764 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9765 StringRange: SpecRange, FixIt: Hints);
9766 } else {
9767 // In this case, the expression could be printed using a different
9768 // specifier, but we've decided that the specifier is probably correct
9769 // and we should cast instead. Just use the normal warning message.
9770
9771 unsigned Diag =
9772 IsScopedEnum
9773 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9774 : diag::warn_format_conversion_argument_type_mismatch;
9775
9776 EmitFormatDiagnostic(
9777 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9778 << IsEnum << E->getSourceRange(),
9779 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9780 }
9781 }
9782 } else {
9783 const CharSourceRange &CSR =
9784 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9785 // Since the warning for passing non-POD types to variadic functions
9786 // was deferred until now, we emit a warning for non-POD
9787 // arguments here.
9788 bool EmitTypeMismatch = false;
9789 // Record and complex type arguments cannot be code generated for os_log
9790 // and would crash CodeGen, so they are rejected with a hard error emitted
9791 // after the switch below.
9792 bool EmitOSLogError = false;
9793 switch (S.isValidVarArgType(Ty: ExprTy)) {
9794 case VarArgKind::Valid:
9795 case VarArgKind::ValidInCXX11: {
9796 unsigned Diag;
9797 switch (Match) {
9798 case ArgType::Match:
9799 case ArgType::MatchPromotion:
9800 case ArgType::NoMatchPromotionTypeConfusion:
9801 llvm_unreachable("expected non-matching");
9802 case ArgType::NoMatchSignedness:
9803 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9804 break;
9805 case ArgType::NoMatchPedantic:
9806 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9807 break;
9808 case ArgType::NoMatchTypeConfusion:
9809 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9810 break;
9811 case ArgType::NoMatch:
9812 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy);
9813 Diag = diag::warn_format_conversion_argument_type_mismatch;
9814 break;
9815 }
9816
9817 if (!EmitOSLogError)
9818 EmitFormatDiagnostic(
9819 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9820 << IsEnum << CSR << E->getSourceRange(),
9821 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9822 break;
9823 }
9824 case VarArgKind::Undefined:
9825 case VarArgKind::MSVCUndefined:
9826 if (CallType == VariadicCallType::DoesNotApply) {
9827 EmitTypeMismatch = true;
9828 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)) {
9829 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9830 // does not stop compilation.
9831 EmitOSLogError = true;
9832 } else {
9833 EmitFormatDiagnostic(
9834 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9835 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9836 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9837 << E->getSourceRange(),
9838 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9839 checkForCStrMembers(AT, E);
9840 }
9841 break;
9842
9843 case VarArgKind::Invalid:
9844 if (CallType == VariadicCallType::DoesNotApply)
9845 EmitTypeMismatch = true;
9846 else if (ExprTy->isObjCObjectType())
9847 EmitFormatDiagnostic(
9848 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9849 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9850 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9851 << E->getSourceRange(),
9852 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9853 else
9854 // FIXME: If this is an initializer list, suggest removing the braces
9855 // or inserting a cast to the target type.
9856 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9857 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9858 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9859 break;
9860 }
9861
9862 if (EmitOSLogError)
9863 EmitFormatDiagnostic(
9864 PDiag: S.PDiag(DiagID: diag::err_format_conversion_argument_type_mismatch)
9865 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << IsEnum
9866 << CSR << E->getSourceRange(),
9867 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9868
9869 if (EmitTypeMismatch) {
9870 // The function is not variadic, so we do not generate warnings about
9871 // being allowed to pass that object as a variadic argument. Instead,
9872 // since there are inherently no printf specifiers for types which cannot
9873 // be passed as variadic arguments, emit a plain old specifier mismatch
9874 // argument.
9875 EmitFormatDiagnostic(
9876 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9877 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9878 << E->getSourceRange(),
9879 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9880 }
9881
9882 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9883 "format string specifier index out of range");
9884 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9885 }
9886
9887 return true;
9888}
9889
9890//===--- CHECK: Scanf format string checking ------------------------------===//
9891
9892namespace {
9893
9894class CheckScanfHandler : public CheckFormatHandler {
9895public:
9896 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9897 const Expr *origFormatExpr, FormatStringType type,
9898 unsigned firstDataArg, unsigned numDataArgs,
9899 const char *beg, Sema::FormatArgumentPassingKind APK,
9900 ArrayRef<const Expr *> Args, unsigned formatIdx,
9901 bool inFunctionCall, VariadicCallType CallType,
9902 llvm::SmallBitVector &CheckedVarArgs,
9903 UncoveredArgHandler &UncoveredArg)
9904 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9905 numDataArgs, beg, APK, Args, formatIdx,
9906 inFunctionCall, CallType, CheckedVarArgs,
9907 UncoveredArg) {}
9908
9909 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9910 const char *startSpecifier,
9911 unsigned specifierLen) override;
9912
9913 bool
9914 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9915 const char *startSpecifier,
9916 unsigned specifierLen) override;
9917
9918 void HandleIncompleteScanList(const char *start, const char *end) override;
9919};
9920
9921} // namespace
9922
9923void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9924 const char *end) {
9925 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
9926 Loc: getLocationOfByte(x: end), /*IsStringLocation*/ true,
9927 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
9928}
9929
9930bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9931 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9932 unsigned specifierLen) {
9933 const analyze_scanf::ScanfConversionSpecifier &CS =
9934 FS.getConversionSpecifier();
9935
9936 return HandleInvalidConversionSpecifier(
9937 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
9938 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
9939}
9940
9941bool CheckScanfHandler::HandleScanfSpecifier(
9942 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9943 unsigned specifierLen) {
9944 using namespace analyze_scanf;
9945 using namespace analyze_format_string;
9946
9947 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9948
9949 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9950 // be used to decide if we are using positional arguments consistently.
9951 if (FS.consumesDataArgument()) {
9952 if (atFirstArg) {
9953 atFirstArg = false;
9954 usesPositionalArgs = FS.usesPositionalArg();
9955 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9956 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9957 startSpec: startSpecifier, specifierLen);
9958 return false;
9959 }
9960 }
9961
9962 // Check if the field with is non-zero.
9963 const OptionalAmount &Amt = FS.getFieldWidth();
9964 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9965 if (Amt.getConstantAmount() == 0) {
9966 const CharSourceRange &R =
9967 getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength());
9968 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
9969 Loc: getLocationOfByte(x: Amt.getStart()),
9970 /*IsStringLocation*/ true, StringRange: R,
9971 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
9972 }
9973 }
9974
9975 if (!FS.consumesDataArgument()) {
9976 // FIXME: Technically specifying a precision or field width here
9977 // makes no sense. Worth issuing a warning at some point.
9978 return true;
9979 }
9980
9981 // Consume the argument.
9982 unsigned argIndex = FS.getArgIndex();
9983 if (argIndex < NumDataArgs) {
9984 // The check to see if the argIndex is valid will come later.
9985 // We set the bit here because we may exit early from this
9986 // function if we encounter some other error.
9987 CoveredArgs.set(argIndex);
9988 }
9989
9990 // Check the length modifier is valid with the given conversion specifier.
9991 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9992 LO: S.getLangOpts()))
9993 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9994 DiagID: diag::warn_format_nonsensical_length);
9995 else if (!FS.hasStandardLengthModifier())
9996 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9997 else if (!FS.hasStandardLengthConversionCombination())
9998 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9999 DiagID: diag::warn_format_non_standard_conversion_spec);
10000
10001 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
10002 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10003
10004 // The remaining checks depend on the data arguments.
10005 if (!HasFormatArguments())
10006 return true;
10007
10008 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10009 return false;
10010
10011 // Check that the argument type matches the format specifier.
10012 const Expr *Ex = getDataArg(i: argIndex);
10013 if (!Ex)
10014 return true;
10015
10016 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
10017
10018 if (!AT.isValid()) {
10019 return true;
10020 }
10021
10022 if (CheckUnsupportedType(AT, E: Ex, StartSpecifier: startSpecifier, SpecifierLen: specifierLen))
10023 return true;
10024
10025 analyze_format_string::ArgType::MatchKind Match =
10026 AT.matchesType(C&: S.Context, argTy: Ex->getType());
10027 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
10028 if (Match == analyze_format_string::ArgType::Match)
10029 return true;
10030 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10031 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
10032
10033 ScanfSpecifier fixedFS = FS;
10034 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
10035 LangOpt: S.getLangOpts(), Ctx&: S.Context);
10036
10037 unsigned Diag =
10038 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10039 : Signedness
10040 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10041 : diag::warn_format_conversion_argument_type_mismatch;
10042
10043 if (Success) {
10044 // Get the fix string from the fixed format specifier.
10045 SmallString<128> buf;
10046 llvm::raw_svector_ostream os(buf);
10047 fixedFS.toString(os);
10048
10049 EmitFormatDiagnostic(
10050 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
10051 << Ex->getType() << false << Ex->getSourceRange(),
10052 Loc: Ex->getBeginLoc(),
10053 /*IsStringLocation*/ false,
10054 StringRange: getSpecifierRange(startSpecifier, specifierLen),
10055 FixIt: FixItHint::CreateReplacement(
10056 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
10057 } else {
10058 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
10059 << AT.getRepresentativeTypeName(C&: S.Context)
10060 << Ex->getType() << false << Ex->getSourceRange(),
10061 Loc: Ex->getBeginLoc(),
10062 /*IsStringLocation*/ false,
10063 StringRange: getSpecifierRange(startSpecifier, specifierLen));
10064 }
10065
10066 return true;
10067}
10068
10069static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10070 ArrayRef<EquatableFormatArgument> RefArgs,
10071 const StringLiteral *Fmt,
10072 ArrayRef<EquatableFormatArgument> FmtArgs,
10073 const Expr *FmtExpr, bool InFunctionCall) {
10074 bool HadError = false;
10075 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10076 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10077 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10078 // In positional-style format strings, the same specifier can appear
10079 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10080 // are sorted by getPosition(), and we process each range of equal
10081 // getPosition() values as one group.
10082 // RefArgs are taken from a string literal that was given to
10083 // attribute(format_matches), and if we got this far, we have already
10084 // verified that if it has positional specifiers that appear in multiple
10085 // locations, then they are all mutually compatible. What's left for us to
10086 // do is verify that all specifiers with the same position in FmtArgs are
10087 // compatible with the RefArgs specifiers. We check each specifier from
10088 // FmtArgs against the first member of the RefArgs group.
10089 for (; FmtIter < FmtEnd; ++FmtIter) {
10090 // Clang does not diagnose missing format specifiers in positional-style
10091 // strings (TODO: which it probably should do, as it is UB to skip over a
10092 // format argument). Skip specifiers if needed.
10093 if (FmtIter->getPosition() < RefIter->getPosition())
10094 continue;
10095
10096 // Delimits a new getPosition() value.
10097 if (FmtIter->getPosition() > RefIter->getPosition())
10098 break;
10099
10100 HadError |=
10101 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
10102 }
10103
10104 // Jump RefIter to the start of the next group.
10105 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
10106 return Arg.getPosition() != RefIter->getPosition();
10107 });
10108 }
10109
10110 if (FmtIter < FmtEnd) {
10111 CheckFormatHandler::EmitFormatDiagnostic(
10112 S, InFunctionCall, ArgumentExpr: FmtExpr,
10113 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
10114 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
10115 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
10116 } else if (RefIter < RefEnd) {
10117 CheckFormatHandler::EmitFormatDiagnostic(
10118 S, InFunctionCall, ArgumentExpr: FmtExpr,
10119 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
10120 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
10121 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
10122 << 1 << RefIter->getSourceRange();
10123 }
10124 return !HadError;
10125}
10126
10127static void CheckFormatString(
10128 Sema &S, const FormatStringLiteral *FExpr,
10129 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10130 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
10131 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10132 bool inFunctionCall, VariadicCallType CallType,
10133 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10134 bool IgnoreStringsWithoutSpecifiers) {
10135 // CHECK: is the format string a wide literal?
10136 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10137 CheckFormatHandler::EmitFormatDiagnostic(
10138 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10139 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
10140 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10141 return;
10142 }
10143
10144 // Str - The format string. NOTE: this is NOT null-terminated!
10145 StringRef StrRef = FExpr->getString();
10146 const char *Str = StrRef.data();
10147 // Account for cases where the string literal is truncated in a declaration.
10148 const ConstantArrayType *T =
10149 S.Context.getAsConstantArrayType(T: FExpr->getType());
10150 assert(T && "String literal not of constant array type!");
10151 size_t TypeSize = T->getZExtSize();
10152 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10153 const unsigned numDataArgs = Args.size() - firstDataArg;
10154
10155 if (IgnoreStringsWithoutSpecifiers &&
10156 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10157 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10158 return;
10159
10160 // Emit a warning if the string literal is truncated and does not contain an
10161 // embedded null character.
10162 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
10163 CheckFormatHandler::EmitFormatDiagnostic(
10164 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10165 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
10166 Loc: FExpr->getBeginLoc(),
10167 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
10168 return;
10169 }
10170
10171 // CHECK: empty format string?
10172 if (StrLen == 0 && numDataArgs > 0) {
10173 CheckFormatHandler::EmitFormatDiagnostic(
10174 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10175 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
10176 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10177 return;
10178 }
10179
10180 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
10181 Type == FormatStringType::Kprintf ||
10182 Type == FormatStringType::FreeBSDKPrintf ||
10183 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
10184 bool IsObjC =
10185 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10186 if (ReferenceFormatString == nullptr) {
10187 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10188 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10189 inFunctionCall, CallType, CheckedVarArgs,
10190 UncoveredArg);
10191
10192 if (!analyze_format_string::ParsePrintfString(
10193 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
10194 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
10195 Type == FormatStringType::FreeBSDKPrintf))
10196 H.DoneProcessing();
10197 } else {
10198 S.CheckFormatStringsCompatible(
10199 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
10200 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
10201 }
10202 } else if (Type == FormatStringType::Scanf) {
10203 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10204 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10205 CallType, CheckedVarArgs, UncoveredArg);
10206
10207 if (!analyze_format_string::ParseScanfString(
10208 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10209 H.DoneProcessing();
10210 } // TODO: handle other formats
10211}
10212
10213bool Sema::CheckFormatStringsCompatible(
10214 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10215 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10216 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10217 Type != FormatStringType::Kprintf &&
10218 Type != FormatStringType::FreeBSDKPrintf &&
10219 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10220 return true;
10221
10222 bool IsObjC =
10223 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10224 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
10225 FormatStringLiteral RefLit = AuthoritativeFormatString;
10226 FormatStringLiteral TestLit = TestedFormatString;
10227 const Expr *Arg;
10228 bool DiagAtStringLiteral;
10229 if (FunctionCallArg) {
10230 Arg = FunctionCallArg;
10231 DiagAtStringLiteral = false;
10232 } else {
10233 Arg = TestedFormatString;
10234 DiagAtStringLiteral = true;
10235 }
10236 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
10237 FmtExpr: AuthoritativeFormatString, Type,
10238 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
10239 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
10240 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
10241 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
10242 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
10243 InFunctionCall: DiagAtStringLiteral);
10244 }
10245 return false;
10246}
10247
10248bool Sema::ValidateFormatString(FormatStringType Type,
10249 const StringLiteral *Str) {
10250 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10251 Type != FormatStringType::Kprintf &&
10252 Type != FormatStringType::FreeBSDKPrintf &&
10253 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10254 return true;
10255
10256 FormatStringLiteral RefLit = Str;
10257 llvm::SmallVector<EquatableFormatArgument, 9> Args;
10258 bool IsObjC =
10259 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10260 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
10261 InFunctionCall: true, Args))
10262 return false;
10263
10264 // Group arguments by getPosition() value, and check that each member of the
10265 // group is compatible with the first member. This verifies that when
10266 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10267 // are mutually compatible. As an optimization, don't test the first member
10268 // against itself.
10269 bool HadError = false;
10270 auto Iter = Args.begin();
10271 auto End = Args.end();
10272 while (Iter != End) {
10273 const auto &FirstInGroup = *Iter;
10274 for (++Iter;
10275 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10276 ++Iter) {
10277 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
10278 }
10279 }
10280 return !HadError;
10281}
10282
10283bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10284 // Str - The format string. NOTE: this is NOT null-terminated!
10285 StringRef StrRef = FExpr->getString();
10286 const char *Str = StrRef.data();
10287 // Account for cases where the string literal is truncated in a declaration.
10288 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
10289 assert(T && "String literal not of constant array type!");
10290 size_t TypeSize = T->getZExtSize();
10291 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10292 return analyze_format_string::ParseFormatStringHasSArg(
10293 beg: Str, end: Str + StrLen, LO: getLangOpts(), Target: Context.getTargetInfo());
10294}
10295
10296//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10297
10298// Returns the related absolute value function that is larger, of 0 if one
10299// does not exist.
10300static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10301 switch (AbsFunction) {
10302 default:
10303 return 0;
10304
10305 case Builtin::BI__builtin_abs:
10306 return Builtin::BI__builtin_labs;
10307 case Builtin::BI__builtin_labs:
10308 return Builtin::BI__builtin_llabs;
10309 case Builtin::BI__builtin_llabs:
10310 return 0;
10311
10312 case Builtin::BI__builtin_fabsf:
10313 return Builtin::BI__builtin_fabs;
10314 case Builtin::BI__builtin_fabs:
10315 return Builtin::BI__builtin_fabsl;
10316 case Builtin::BI__builtin_fabsl:
10317 return 0;
10318
10319 case Builtin::BI__builtin_cabsf:
10320 return Builtin::BI__builtin_cabs;
10321 case Builtin::BI__builtin_cabs:
10322 return Builtin::BI__builtin_cabsl;
10323 case Builtin::BI__builtin_cabsl:
10324 return 0;
10325
10326 case Builtin::BIabs:
10327 return Builtin::BIlabs;
10328 case Builtin::BIlabs:
10329 return Builtin::BIllabs;
10330 case Builtin::BIllabs:
10331 return 0;
10332
10333 case Builtin::BIfabsf:
10334 return Builtin::BIfabs;
10335 case Builtin::BIfabs:
10336 return Builtin::BIfabsl;
10337 case Builtin::BIfabsl:
10338 return 0;
10339
10340 case Builtin::BIcabsf:
10341 return Builtin::BIcabs;
10342 case Builtin::BIcabs:
10343 return Builtin::BIcabsl;
10344 case Builtin::BIcabsl:
10345 return 0;
10346 }
10347}
10348
10349// Returns the argument type of the absolute value function.
10350static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10351 unsigned AbsType) {
10352 if (AbsType == 0)
10353 return QualType();
10354
10355 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10356 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
10357 if (Error != ASTContext::GE_None)
10358 return QualType();
10359
10360 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10361 if (!FT)
10362 return QualType();
10363
10364 if (FT->getNumParams() != 1)
10365 return QualType();
10366
10367 return FT->getParamType(i: 0);
10368}
10369
10370// Returns the best absolute value function, or zero, based on type and
10371// current absolute value function.
10372static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10373 unsigned AbsFunctionKind) {
10374 unsigned BestKind = 0;
10375 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
10376 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10377 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
10378 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
10379 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
10380 if (BestKind == 0)
10381 BestKind = Kind;
10382 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
10383 BestKind = Kind;
10384 break;
10385 }
10386 }
10387 }
10388 return BestKind;
10389}
10390
10391enum AbsoluteValueKind {
10392 AVK_Integer,
10393 AVK_Floating,
10394 AVK_Complex
10395};
10396
10397static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10398 if (T->isIntegralOrEnumerationType())
10399 return AVK_Integer;
10400 if (T->isRealFloatingType())
10401 return AVK_Floating;
10402 if (T->isAnyComplexType())
10403 return AVK_Complex;
10404
10405 llvm_unreachable("Type not integer, floating, or complex");
10406}
10407
10408// Changes the absolute value function to a different type. Preserves whether
10409// the function is a builtin.
10410static unsigned changeAbsFunction(unsigned AbsKind,
10411 AbsoluteValueKind ValueKind) {
10412 switch (ValueKind) {
10413 case AVK_Integer:
10414 switch (AbsKind) {
10415 default:
10416 return 0;
10417 case Builtin::BI__builtin_fabsf:
10418 case Builtin::BI__builtin_fabs:
10419 case Builtin::BI__builtin_fabsl:
10420 case Builtin::BI__builtin_cabsf:
10421 case Builtin::BI__builtin_cabs:
10422 case Builtin::BI__builtin_cabsl:
10423 return Builtin::BI__builtin_abs;
10424 case Builtin::BIfabsf:
10425 case Builtin::BIfabs:
10426 case Builtin::BIfabsl:
10427 case Builtin::BIcabsf:
10428 case Builtin::BIcabs:
10429 case Builtin::BIcabsl:
10430 return Builtin::BIabs;
10431 }
10432 case AVK_Floating:
10433 switch (AbsKind) {
10434 default:
10435 return 0;
10436 case Builtin::BI__builtin_abs:
10437 case Builtin::BI__builtin_labs:
10438 case Builtin::BI__builtin_llabs:
10439 case Builtin::BI__builtin_cabsf:
10440 case Builtin::BI__builtin_cabs:
10441 case Builtin::BI__builtin_cabsl:
10442 return Builtin::BI__builtin_fabsf;
10443 case Builtin::BIabs:
10444 case Builtin::BIlabs:
10445 case Builtin::BIllabs:
10446 case Builtin::BIcabsf:
10447 case Builtin::BIcabs:
10448 case Builtin::BIcabsl:
10449 return Builtin::BIfabsf;
10450 }
10451 case AVK_Complex:
10452 switch (AbsKind) {
10453 default:
10454 return 0;
10455 case Builtin::BI__builtin_abs:
10456 case Builtin::BI__builtin_labs:
10457 case Builtin::BI__builtin_llabs:
10458 case Builtin::BI__builtin_fabsf:
10459 case Builtin::BI__builtin_fabs:
10460 case Builtin::BI__builtin_fabsl:
10461 return Builtin::BI__builtin_cabsf;
10462 case Builtin::BIabs:
10463 case Builtin::BIlabs:
10464 case Builtin::BIllabs:
10465 case Builtin::BIfabsf:
10466 case Builtin::BIfabs:
10467 case Builtin::BIfabsl:
10468 return Builtin::BIcabsf;
10469 }
10470 }
10471 llvm_unreachable("Unable to convert function");
10472}
10473
10474static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10475 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10476 if (!FnInfo)
10477 return 0;
10478
10479 switch (FDecl->getBuiltinID()) {
10480 default:
10481 return 0;
10482 case Builtin::BI__builtin_abs:
10483 case Builtin::BI__builtin_fabs:
10484 case Builtin::BI__builtin_fabsf:
10485 case Builtin::BI__builtin_fabsl:
10486 case Builtin::BI__builtin_labs:
10487 case Builtin::BI__builtin_llabs:
10488 case Builtin::BI__builtin_cabs:
10489 case Builtin::BI__builtin_cabsf:
10490 case Builtin::BI__builtin_cabsl:
10491 case Builtin::BIabs:
10492 case Builtin::BIlabs:
10493 case Builtin::BIllabs:
10494 case Builtin::BIfabs:
10495 case Builtin::BIfabsf:
10496 case Builtin::BIfabsl:
10497 case Builtin::BIcabs:
10498 case Builtin::BIcabsf:
10499 case Builtin::BIcabsl:
10500 return FDecl->getBuiltinID();
10501 }
10502 llvm_unreachable("Unknown Builtin type");
10503}
10504
10505// If the replacement is valid, emit a note with replacement function.
10506// Additionally, suggest including the proper header if not already included.
10507static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10508 unsigned AbsKind, QualType ArgType) {
10509 bool EmitHeaderHint = true;
10510 const char *HeaderName = nullptr;
10511 std::string FunctionName;
10512 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10513 FunctionName = "std::abs";
10514 if (ArgType->isIntegralOrEnumerationType()) {
10515 HeaderName = "cstdlib";
10516 } else if (ArgType->isRealFloatingType()) {
10517 HeaderName = "cmath";
10518 } else {
10519 llvm_unreachable("Invalid Type");
10520 }
10521
10522 // Lookup all std::abs
10523 if (NamespaceDecl *Std = S.getStdNamespace()) {
10524 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10525 R.suppressDiagnostics();
10526 S.LookupQualifiedName(R, LookupCtx: Std);
10527
10528 for (const auto *I : R) {
10529 const FunctionDecl *FDecl = nullptr;
10530 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10531 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10532 } else {
10533 FDecl = dyn_cast<FunctionDecl>(Val: I);
10534 }
10535 if (!FDecl)
10536 continue;
10537
10538 // Found std::abs(), check that they are the right ones.
10539 if (FDecl->getNumParams() != 1)
10540 continue;
10541
10542 // Check that the parameter type can handle the argument.
10543 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10544 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10545 S.Context.getTypeSize(T: ArgType) <=
10546 S.Context.getTypeSize(T: ParamType)) {
10547 // Found a function, don't need the header hint.
10548 EmitHeaderHint = false;
10549 break;
10550 }
10551 }
10552 }
10553 } else {
10554 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10555 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10556
10557 if (HeaderName) {
10558 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10559 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10560 R.suppressDiagnostics();
10561 S.LookupName(R, S: S.getCurScope());
10562
10563 if (R.isSingleResult()) {
10564 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10565 if (FD && FD->getBuiltinID() == AbsKind) {
10566 EmitHeaderHint = false;
10567 } else {
10568 return;
10569 }
10570 } else if (!R.empty()) {
10571 return;
10572 }
10573 }
10574 }
10575
10576 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10577 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10578
10579 if (!HeaderName)
10580 return;
10581
10582 if (!EmitHeaderHint)
10583 return;
10584
10585 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10586 << FunctionName;
10587}
10588
10589template <std::size_t StrLen>
10590static bool IsStdFunction(const FunctionDecl *FDecl,
10591 const char (&Str)[StrLen]) {
10592 if (!FDecl)
10593 return false;
10594 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10595 return false;
10596 if (!FDecl->isInStdNamespace())
10597 return false;
10598
10599 return true;
10600}
10601
10602enum class MathCheck { NaN, Inf };
10603static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10604 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10605 return llvm::is_contained(Set: names, Element: calleeName);
10606 };
10607
10608 switch (Check) {
10609 case MathCheck::NaN:
10610 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10611 "__builtin_nanf16", "__builtin_nanf128"});
10612 case MathCheck::Inf:
10613 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10614 "__builtin_inff16", "__builtin_inff128"});
10615 }
10616 llvm_unreachable("unknown MathCheck");
10617}
10618
10619static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10620 if (FDecl->getName() != "infinity")
10621 return false;
10622
10623 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10624 const CXXRecordDecl *RDecl = MDecl->getParent();
10625 if (RDecl->getName() != "numeric_limits")
10626 return false;
10627
10628 if (const NamespaceDecl *NSDecl =
10629 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10630 return NSDecl->isStdNamespace();
10631 }
10632
10633 return false;
10634}
10635
10636void Sema::CheckInfNaNFunction(const CallExpr *Call,
10637 const FunctionDecl *FDecl) {
10638 if (!FDecl->getIdentifier())
10639 return;
10640
10641 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10642 if (FPO.getNoHonorNaNs() &&
10643 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10644 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10645 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10646 << 1 << 0 << Call->getSourceRange();
10647 return;
10648 }
10649
10650 if (FPO.getNoHonorInfs() &&
10651 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10652 IsInfinityFunction(FDecl) ||
10653 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10654 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10655 << 0 << 0 << Call->getSourceRange();
10656 }
10657}
10658
10659void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10660 const FunctionDecl *FDecl) {
10661 if (Call->getNumArgs() != 1)
10662 return;
10663
10664 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10665 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10666 if (AbsKind == 0 && !IsStdAbs)
10667 return;
10668
10669 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10670 QualType ParamType = Call->getArg(Arg: 0)->getType();
10671
10672 // Unsigned types cannot be negative. Suggest removing the absolute value
10673 // function call.
10674 if (ArgType->isUnsignedIntegerType()) {
10675 std::string FunctionName =
10676 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10677 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10678 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10679 << FunctionName
10680 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10681 return;
10682 }
10683
10684 // Taking the absolute value of a pointer is very suspicious, they probably
10685 // wanted to index into an array, dereference a pointer, call a function, etc.
10686 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10687 unsigned DiagType = 0;
10688 if (ArgType->isFunctionType())
10689 DiagType = 1;
10690 else if (ArgType->isArrayType())
10691 DiagType = 2;
10692
10693 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10694 return;
10695 }
10696
10697 // std::abs has overloads which prevent most of the absolute value problems
10698 // from occurring.
10699 if (IsStdAbs)
10700 return;
10701
10702 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10703 // types.
10704 if (!ArgType->isIntegralOrEnumerationType() &&
10705 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10706 return;
10707
10708 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10709 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10710
10711 // The argument and parameter are the same kind. Check if they are the right
10712 // size.
10713 if (ArgValueKind == ParamValueKind) {
10714 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10715 return;
10716
10717 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10718 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10719 << FDecl << ArgType << ParamType;
10720
10721 if (NewAbsKind == 0)
10722 return;
10723
10724 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10725 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10726 return;
10727 }
10728
10729 // ArgValueKind != ParamValueKind
10730 // The wrong type of absolute value function was used. Attempt to find the
10731 // proper one.
10732 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10733 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10734 if (NewAbsKind == 0)
10735 return;
10736
10737 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10738 << FDecl << ParamValueKind << ArgValueKind;
10739
10740 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10741 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10742}
10743
10744//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10745void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10746 const FunctionDecl *FDecl) {
10747 if (!Call || !FDecl) return;
10748
10749 // Ignore template specializations and macros.
10750 if (inTemplateInstantiation()) return;
10751 if (Call->getExprLoc().isMacroID()) return;
10752
10753 // Only care about the one template argument, two function parameter std::max
10754 if (Call->getNumArgs() != 2) return;
10755 if (!IsStdFunction(FDecl, Str: "max")) return;
10756 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10757 if (!ArgList) return;
10758 if (ArgList->size() != 1) return;
10759
10760 // Check that template type argument is unsigned integer.
10761 const auto& TA = ArgList->get(Idx: 0);
10762 if (TA.getKind() != TemplateArgument::Type) return;
10763 QualType ArgType = TA.getAsType();
10764 if (!ArgType->isUnsignedIntegerType()) return;
10765
10766 // See if either argument is a literal zero.
10767 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10768 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10769 if (!MTE) return false;
10770 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10771 if (!Num) return false;
10772 if (Num->getValue() != 0) return false;
10773 return true;
10774 };
10775
10776 const Expr *FirstArg = Call->getArg(Arg: 0);
10777 const Expr *SecondArg = Call->getArg(Arg: 1);
10778 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10779 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10780
10781 // Only warn when exactly one argument is zero.
10782 if (IsFirstArgZero == IsSecondArgZero) return;
10783
10784 SourceRange FirstRange = FirstArg->getSourceRange();
10785 SourceRange SecondRange = SecondArg->getSourceRange();
10786
10787 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10788
10789 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10790 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10791
10792 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10793 SourceRange RemovalRange;
10794 if (IsFirstArgZero) {
10795 RemovalRange = SourceRange(FirstRange.getBegin(),
10796 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10797 } else {
10798 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10799 SecondRange.getEnd());
10800 }
10801
10802 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10803 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10804 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10805}
10806
10807//===--- CHECK: Standard memory functions ---------------------------------===//
10808
10809/// Takes the expression passed to the size_t parameter of functions
10810/// such as memcmp, strncat, etc and warns if it's a comparison.
10811///
10812/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10813static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10814 const IdentifierInfo *FnName,
10815 SourceLocation FnLoc,
10816 SourceLocation RParenLoc) {
10817 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10818 if (!Size)
10819 return false;
10820
10821 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10822 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10823 return false;
10824
10825 SourceRange SizeRange = Size->getSourceRange();
10826 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10827 << SizeRange << FnName;
10828 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10829 << FnName
10830 << FixItHint::CreateInsertion(
10831 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10832 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10833 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10834 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10835 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10836 Code: ")");
10837
10838 return true;
10839}
10840
10841/// Determine whether the given type is or contains a dynamic class type
10842/// (e.g., whether it has a vtable).
10843static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10844 bool &IsContained) {
10845 // Look through array types while ignoring qualifiers.
10846 const Type *Ty = T->getBaseElementTypeUnsafe();
10847 IsContained = false;
10848
10849 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10850 RD = RD ? RD->getDefinition() : nullptr;
10851 if (!RD || RD->isInvalidDecl())
10852 return nullptr;
10853
10854 if (RD->isDynamicClass())
10855 return RD;
10856
10857 // Check all the fields. If any bases were dynamic, the class is dynamic.
10858 // It's impossible for a class to transitively contain itself by value, so
10859 // infinite recursion is impossible.
10860 for (auto *FD : RD->fields()) {
10861 bool SubContained;
10862 if (const CXXRecordDecl *ContainedRD =
10863 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10864 IsContained = true;
10865 return ContainedRD;
10866 }
10867 }
10868
10869 return nullptr;
10870}
10871
10872static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10873 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10874 if (Unary->getKind() == UETT_SizeOf)
10875 return Unary;
10876 return nullptr;
10877}
10878
10879/// If E is a sizeof expression, returns its argument expression,
10880/// otherwise returns NULL.
10881static const Expr *getSizeOfExprArg(const Expr *E) {
10882 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10883 if (!SizeOf->isArgumentType())
10884 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10885 return nullptr;
10886}
10887
10888/// If E is a sizeof expression, returns its argument type.
10889static QualType getSizeOfArgType(const Expr *E) {
10890 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10891 return SizeOf->getTypeOfArgument();
10892 return QualType();
10893}
10894
10895namespace {
10896
10897struct SearchNonTrivialToInitializeField
10898 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10899 using Super =
10900 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10901
10902 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10903
10904 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10905 SourceLocation SL) {
10906 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10907 asDerived().visitArray(PDIK, AT, SL);
10908 return;
10909 }
10910
10911 Super::visitWithKind(PDIK, FT, Args&: SL);
10912 }
10913
10914 void visitARCStrong(QualType FT, SourceLocation SL) {
10915 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10916 }
10917 void visitARCWeak(QualType FT, SourceLocation SL) {
10918 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10919 }
10920 void visitStruct(QualType FT, SourceLocation SL) {
10921 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10922 visit(FT: FD->getType(), Args: FD->getLocation());
10923 }
10924 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10925 const ArrayType *AT, SourceLocation SL) {
10926 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10927 }
10928 void visitTrivial(QualType FT, SourceLocation SL) {}
10929
10930 static void diag(QualType RT, const Expr *E, Sema &S) {
10931 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10932 }
10933
10934 ASTContext &getContext() { return S.getASTContext(); }
10935
10936 const Expr *E;
10937 Sema &S;
10938};
10939
10940struct SearchNonTrivialToCopyField
10941 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10942 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10943
10944 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10945
10946 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10947 SourceLocation SL) {
10948 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10949 asDerived().visitArray(PCK, AT, SL);
10950 return;
10951 }
10952
10953 Super::visitWithKind(PCK, FT, Args&: SL);
10954 }
10955
10956 void visitARCStrong(QualType FT, SourceLocation SL) {
10957 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10958 }
10959 void visitARCWeak(QualType FT, SourceLocation SL) {
10960 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10961 }
10962 void visitPtrAuth(QualType FT, SourceLocation SL) {
10963 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10964 }
10965 void visitStruct(QualType FT, SourceLocation SL) {
10966 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10967 visit(FT: FD->getType(), Args: FD->getLocation());
10968 }
10969 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10970 SourceLocation SL) {
10971 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10972 }
10973 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10974 SourceLocation SL) {}
10975 void visitTrivial(QualType FT, SourceLocation SL) {}
10976 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10977
10978 static void diag(QualType RT, const Expr *E, Sema &S) {
10979 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10980 }
10981
10982 ASTContext &getContext() { return S.getASTContext(); }
10983
10984 const Expr *E;
10985 Sema &S;
10986};
10987
10988}
10989
10990/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10991static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10992 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10993
10994 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
10995 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10996 return false;
10997
10998 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
10999 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
11000 }
11001
11002 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
11003}
11004
11005/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11006///
11007/// \code
11008/// #define MACRO 0
11009/// foo(MACRO);
11010/// foo(0);
11011/// \endcode
11012///
11013/// This should return true for the first call to foo, but not for the second
11014/// (regardless of whether foo is a macro or function).
11015static bool isArgumentExpandedFromMacro(SourceManager &SM,
11016 SourceLocation CallLoc,
11017 SourceLocation ArgLoc) {
11018 if (!CallLoc.isMacroID())
11019 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
11020
11021 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
11022 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
11023}
11024
11025/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11026/// last two arguments transposed.
11027static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11028 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11029 return;
11030
11031 const Expr *SizeArg =
11032 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11033
11034 auto isLiteralZero = [](const Expr *E) {
11035 return (isa<IntegerLiteral>(Val: E) &&
11036 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
11037 (isa<CharacterLiteral>(Val: E) &&
11038 cast<CharacterLiteral>(Val: E)->getValue() == 0);
11039 };
11040
11041 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11042 SourceLocation CallLoc = Call->getRParenLoc();
11043 SourceManager &SM = S.getSourceManager();
11044 if (isLiteralZero(SizeArg) &&
11045 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
11046
11047 SourceLocation DiagLoc = SizeArg->getExprLoc();
11048
11049 // Some platforms #define bzero to __builtin_memset. See if this is the
11050 // case, and if so, emit a better diagnostic.
11051 if (BId == Builtin::BIbzero ||
11052 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
11053 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
11054 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
11055 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
11056 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
11057 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
11058 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
11059 }
11060 return;
11061 }
11062
11063 // If the second argument to a memset is a sizeof expression and the third
11064 // isn't, this is also likely an error. This should catch
11065 // 'memset(buf, sizeof(buf), 0xff)'.
11066 if (BId == Builtin::BImemset &&
11067 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
11068 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
11069 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
11070 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
11071 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
11072 return;
11073 }
11074}
11075
11076void Sema::CheckMemaccessArguments(const CallExpr *Call,
11077 unsigned BId,
11078 IdentifierInfo *FnName) {
11079 assert(BId != 0);
11080
11081 // It is possible to have a non-standard definition of memset. Validate
11082 // we have enough arguments, and if not, abort further checking.
11083 unsigned ExpectedNumArgs =
11084 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11085 if (Call->getNumArgs() < ExpectedNumArgs)
11086 return;
11087
11088 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11089 BId == Builtin::BIstrndup ? 1 : 2);
11090 unsigned LenArg =
11091 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11092 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
11093
11094 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
11095 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11096 return;
11097
11098 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11099 CheckMemaccessSize(S&: *this, BId, Call);
11100
11101 // We have special checking when the length is a sizeof expression.
11102 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
11103
11104 // Although widely used, 'bzero' is not a standard function. Be more strict
11105 // with the argument types before allowing diagnostics and only allow the
11106 // form bzero(ptr, sizeof(...)).
11107 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
11108 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11109 return;
11110
11111 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11112 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
11113 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
11114
11115 QualType DestTy = Dest->getType();
11116 QualType PointeeTy;
11117 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11118 PointeeTy = DestPtrTy->getPointeeType();
11119
11120 // Never warn about void type pointers. This can be used to suppress
11121 // false positives.
11122 if (PointeeTy->isVoidType())
11123 continue;
11124
11125 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11126 // actually comparing the expressions for equality. Because computing the
11127 // expression IDs can be expensive, we only do this if the diagnostic is
11128 // enabled.
11129 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
11130 break;
11131
11132 // Also check for cases where the sizeof argument is the exact same
11133 // type as the memory argument, and where it points to a user-defined
11134 // record type.
11135 if (SizeOfArgTy != QualType()) {
11136 if (PointeeTy->isRecordType() &&
11137 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
11138 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
11139 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
11140 << FnName << SizeOfArgTy << ArgIdx
11141 << PointeeTy << Dest->getSourceRange()
11142 << LenExpr->getSourceRange());
11143 break;
11144 }
11145 }
11146 } else if (DestTy->isArrayType()) {
11147 PointeeTy = DestTy;
11148 }
11149
11150 if (PointeeTy == QualType())
11151 continue;
11152
11153 // Always complain about dynamic classes.
11154 bool IsContained;
11155 if (const CXXRecordDecl *ContainedRD =
11156 getContainedDynamicClass(T: PointeeTy, IsContained)) {
11157
11158 unsigned OperationType = 0;
11159 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11160 // "overwritten" if we're warning about the destination for any call
11161 // but memcmp; otherwise a verb appropriate to the call.
11162 if (ArgIdx != 0 || IsCmp) {
11163 if (BId == Builtin::BImemcpy)
11164 OperationType = 1;
11165 else if(BId == Builtin::BImemmove)
11166 OperationType = 2;
11167 else if (IsCmp)
11168 OperationType = 3;
11169 }
11170
11171 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11172 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
11173 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11174 << IsContained << ContainedRD << OperationType
11175 << Call->getCallee()->getSourceRange());
11176 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11177 BId != Builtin::BImemset)
11178 DiagRuntimeBehavior(
11179 Loc: Dest->getExprLoc(), Statement: Dest,
11180 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
11181 << ArgIdx << FnName << PointeeTy
11182 << Call->getCallee()->getSourceRange());
11183 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11184
11185 // FIXME: Do not consider incomplete types even though they may be
11186 // completed later. GCC does not diagnose such code, but we may want to
11187 // consider diagnosing it in the future, perhaps under a different, but
11188 // related, diagnostic group.
11189 bool NonTriviallyCopyableCXXRecord =
11190 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11191 !PointeeTy.isTriviallyCopyableType(Context);
11192
11193 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11194 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
11195 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11196 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11197 << ArgIdx << FnName << PointeeTy << 0);
11198 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
11199 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11200 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11201 // FIXME: Limiting this warning to dest argument until we decide
11202 // whether it's valid for source argument too.
11203 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11204 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11205 << FnName << PointeeTy);
11206 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11207 RD->isNonTrivialToPrimitiveCopy()) {
11208 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11209 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11210 << ArgIdx << FnName << PointeeTy << 1);
11211 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
11212 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11213 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11214 // FIXME: Limiting this warning to dest argument until we decide
11215 // whether it's valid for source argument too.
11216 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11217 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11218 << FnName << PointeeTy);
11219 } else {
11220 continue;
11221 }
11222 } else
11223 continue;
11224
11225 DiagRuntimeBehavior(
11226 Loc: Dest->getExprLoc(), Statement: Dest,
11227 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
11228 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
11229 break;
11230 }
11231}
11232
11233bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11234 IdentifierInfo *FnName) {
11235 llvm::FoldingSetNodeID SizeOfArgID;
11236 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
11237 if (!SizeOfArg)
11238 return false;
11239 // Computing this warning is expensive, so we only do so if the warning is
11240 // enabled.
11241 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
11242 Loc: SizeOfArg->getExprLoc()))
11243 return false;
11244 QualType DestTy = Dest->getType();
11245 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11246 if (!DestPtrTy)
11247 return false;
11248
11249 QualType PointeeTy = DestPtrTy->getPointeeType();
11250
11251 if (SizeOfArgID == llvm::FoldingSetNodeID())
11252 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
11253
11254 llvm::FoldingSetNodeID DestID;
11255 Dest->Profile(ID&: DestID, Context, Canonical: true);
11256 if (DestID == SizeOfArgID) {
11257 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11258 // over sizeof(src) as well.
11259 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11260 StringRef ReadableName = FnName->getName();
11261
11262 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
11263 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11264 ActionIdx = 1; // If its an address-of operator, just remove it.
11265 if (!PointeeTy->isIncompleteType() &&
11266 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
11267 ActionIdx = 2; // If the pointee's size is sizeof(char),
11268 // suggest an explicit length.
11269
11270 // If the function is defined as a builtin macro, do not show macro
11271 // expansion.
11272 SourceLocation SL = SizeOfArg->getExprLoc();
11273 SourceRange DSR = Dest->getSourceRange();
11274 SourceRange SSR = SizeOfArg->getSourceRange();
11275 SourceManager &SM = getSourceManager();
11276
11277 if (SM.isMacroArgExpansion(Loc: SL)) {
11278 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
11279 SL = SM.getSpellingLoc(Loc: SL);
11280 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
11281 SM.getSpellingLoc(Loc: DSR.getEnd()));
11282 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
11283 SM.getSpellingLoc(Loc: SSR.getEnd()));
11284 }
11285
11286 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11287 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
11288 << ReadableName << PointeeTy << DestTy << DSR
11289 << SSR);
11290 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11291 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
11292 << ActionIdx << SSR);
11293 return true;
11294 }
11295 return false;
11296}
11297
11298// A little helper routine: ignore addition and subtraction of integer literals.
11299// This intentionally does not ignore all integer constant expressions because
11300// we don't want to remove sizeof().
11301static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11302 Ex = Ex->IgnoreParenCasts();
11303
11304 while (true) {
11305 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
11306 if (!BO || !BO->isAdditiveOp())
11307 break;
11308
11309 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11310 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11311
11312 if (isa<IntegerLiteral>(Val: RHS))
11313 Ex = LHS;
11314 else if (isa<IntegerLiteral>(Val: LHS))
11315 Ex = RHS;
11316 else
11317 break;
11318 }
11319
11320 return Ex;
11321}
11322
11323static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11324 ASTContext &Context) {
11325 // Only handle constant-sized or VLAs, but not flexible members.
11326 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
11327 // Only issue the FIXIT for arrays of size > 1.
11328 if (CAT->getZExtSize() <= 1)
11329 return false;
11330 } else if (!Ty->isVariableArrayType()) {
11331 return false;
11332 }
11333 return true;
11334}
11335
11336void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11337 IdentifierInfo *FnName) {
11338
11339 // Don't crash if the user has the wrong number of arguments
11340 unsigned NumArgs = Call->getNumArgs();
11341 if ((NumArgs != 3) && (NumArgs != 4))
11342 return;
11343
11344 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
11345 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
11346 const Expr *CompareWithSrc = nullptr;
11347
11348 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
11349 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11350 return;
11351
11352 // Look for 'strlcpy(dst, x, sizeof(x))'
11353 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
11354 CompareWithSrc = Ex;
11355 else {
11356 // Look for 'strlcpy(dst, x, strlen(x))'
11357 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
11358 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11359 SizeCall->getNumArgs() == 1)
11360 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
11361 }
11362 }
11363
11364 if (!CompareWithSrc)
11365 return;
11366
11367 // Determine if the argument to sizeof/strlen is equal to the source
11368 // argument. In principle there's all kinds of things you could do
11369 // here, for instance creating an == expression and evaluating it with
11370 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11371 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
11372 if (!SrcArgDRE)
11373 return;
11374
11375 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
11376 if (!CompareWithSrcDRE ||
11377 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11378 return;
11379
11380 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
11381 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
11382 << OriginalSizeArg->getSourceRange() << FnName;
11383
11384 // Output a FIXIT hint if the destination is an array (rather than a
11385 // pointer to an array). This could be enhanced to handle some
11386 // pointers if we know the actual size, like if DstArg is 'array+2'
11387 // we could say 'sizeof(array)-2'.
11388 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
11389 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
11390 return;
11391
11392 SmallString<128> sizeString;
11393 llvm::raw_svector_ostream OS(sizeString);
11394 OS << "sizeof(";
11395 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11396 OS << ")";
11397
11398 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
11399 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
11400 Code: OS.str());
11401}
11402
11403/// Check if two expressions refer to the same declaration.
11404static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11405 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
11406 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
11407 return D1->getDecl() == D2->getDecl();
11408 return false;
11409}
11410
11411static const Expr *getStrlenExprArg(const Expr *E) {
11412 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
11413 const FunctionDecl *FD = CE->getDirectCallee();
11414 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11415 return nullptr;
11416 return CE->getArg(Arg: 0)->IgnoreParenCasts();
11417 }
11418 return nullptr;
11419}
11420
11421void Sema::CheckStrncatArguments(const CallExpr *CE,
11422 const IdentifierInfo *FnName) {
11423 // Don't crash if the user has the wrong number of arguments.
11424 if (CE->getNumArgs() < 3)
11425 return;
11426 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
11427 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
11428 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
11429
11430 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
11431 RParenLoc: CE->getRParenLoc()))
11432 return;
11433
11434 // Identify common expressions, which are wrongly used as the size argument
11435 // to strncat and may lead to buffer overflows.
11436 unsigned PatternType = 0;
11437 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
11438 // - sizeof(dst)
11439 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
11440 PatternType = 1;
11441 // - sizeof(src)
11442 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
11443 PatternType = 2;
11444 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
11445 if (BE->getOpcode() == BO_Sub) {
11446 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11447 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11448 // - sizeof(dst) - strlen(dst)
11449 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
11450 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
11451 PatternType = 1;
11452 // - sizeof(src) - (anything)
11453 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
11454 PatternType = 2;
11455 }
11456 }
11457
11458 if (PatternType == 0)
11459 return;
11460
11461 // Generate the diagnostic.
11462 SourceLocation SL = LenArg->getBeginLoc();
11463 SourceRange SR = LenArg->getSourceRange();
11464 SourceManager &SM = getSourceManager();
11465
11466 // If the function is defined as a builtin macro, do not show macro expansion.
11467 if (SM.isMacroArgExpansion(Loc: SL)) {
11468 SL = SM.getSpellingLoc(Loc: SL);
11469 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11470 SM.getSpellingLoc(Loc: SR.getEnd()));
11471 }
11472
11473 // Check if the destination is an array (rather than a pointer to an array).
11474 QualType DstTy = DstArg->getType();
11475 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11476 Context);
11477 if (!isKnownSizeArray) {
11478 if (PatternType == 1)
11479 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11480 else
11481 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11482 return;
11483 }
11484
11485 if (PatternType == 1)
11486 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11487 else
11488 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11489
11490 SmallString<128> sizeString;
11491 llvm::raw_svector_ostream OS(sizeString);
11492 OS << "sizeof(";
11493 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11494 OS << ") - ";
11495 OS << "strlen(";
11496 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11497 OS << ") - 1";
11498
11499 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11500 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11501}
11502
11503namespace {
11504void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11505 const UnaryOperator *UnaryExpr, const Decl *D) {
11506 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11507 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11508 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11509 return;
11510 }
11511}
11512
11513void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11514 const UnaryOperator *UnaryExpr) {
11515 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11516 const Decl *D = Lvalue->getDecl();
11517 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11518 if (!DD->getType()->isReferenceType())
11519 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11520 }
11521 }
11522
11523 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11524 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11525 D: Lvalue->getMemberDecl());
11526}
11527
11528void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11529 const UnaryOperator *UnaryExpr) {
11530 const auto *Lambda = dyn_cast<LambdaExpr>(
11531 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11532 if (!Lambda)
11533 return;
11534
11535 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11536 << CalleeName << 2 /*object: lambda expression*/;
11537}
11538
11539void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11540 const DeclRefExpr *Lvalue) {
11541 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11542 if (Var == nullptr)
11543 return;
11544
11545 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11546 << CalleeName << 0 /*object: */ << Var;
11547}
11548
11549void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11550 const CastExpr *Cast) {
11551 SmallString<128> SizeString;
11552 llvm::raw_svector_ostream OS(SizeString);
11553
11554 clang::CastKind Kind = Cast->getCastKind();
11555 if (Kind == clang::CK_BitCast &&
11556 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11557 return;
11558 if (Kind == clang::CK_IntegralToPointer &&
11559 !isa<IntegerLiteral>(
11560 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11561 return;
11562
11563 switch (Cast->getCastKind()) {
11564 case clang::CK_BitCast:
11565 case clang::CK_IntegralToPointer:
11566 case clang::CK_FunctionToPointerDecay:
11567 OS << '\'';
11568 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11569 OS << '\'';
11570 break;
11571 default:
11572 return;
11573 }
11574
11575 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11576 << CalleeName << 0 /*object: */ << OS.str();
11577}
11578} // namespace
11579
11580void Sema::CheckFreeArguments(const CallExpr *E) {
11581 const std::string CalleeName =
11582 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11583
11584 { // Prefer something that doesn't involve a cast to make things simpler.
11585 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11586 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11587 switch (UnaryExpr->getOpcode()) {
11588 case UnaryOperator::Opcode::UO_AddrOf:
11589 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11590 case UnaryOperator::Opcode::UO_Plus:
11591 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11592 default:
11593 break;
11594 }
11595
11596 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11597 if (Lvalue->getType()->isArrayType())
11598 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11599
11600 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11601 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11602 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11603 return;
11604 }
11605
11606 if (isa<BlockExpr>(Val: Arg)) {
11607 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11608 << CalleeName << 1 /*object: block*/;
11609 return;
11610 }
11611 }
11612 // Maybe the cast was important, check after the other cases.
11613 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11614 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11615}
11616
11617void
11618Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11619 SourceLocation ReturnLoc,
11620 bool isObjCMethod,
11621 const AttrVec *Attrs,
11622 const FunctionDecl *FD) {
11623 // Check if the return value is null but should not be.
11624 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11625 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11626 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11627 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11628 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11629
11630 // C++11 [basic.stc.dynamic.allocation]p4:
11631 // If an allocation function declared with a non-throwing
11632 // exception-specification fails to allocate storage, it shall return
11633 // a null pointer. Any other allocation function that fails to allocate
11634 // storage shall indicate failure only by throwing an exception [...]
11635 if (FD) {
11636 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11637 if (Op == OO_New || Op == OO_Array_New) {
11638 const FunctionProtoType *Proto
11639 = FD->getType()->castAs<FunctionProtoType>();
11640 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11641 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11642 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11643 << FD << getLangOpts().CPlusPlus11;
11644 }
11645 }
11646
11647 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11648 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11649 }
11650
11651 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11652 // here prevent the user from using a PPC MMA type as trailing return type.
11653 if (Context.getTargetInfo().getTriple().isPPC64())
11654 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11655}
11656
11657void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11658 const Expr *RHS, BinaryOperatorKind Opcode) {
11659 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11660 return;
11661
11662 // Match and capture subexpressions such as "(float) X == 0.1".
11663 const FloatingLiteral *FPLiteral;
11664 const CastExpr *FPCast;
11665 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11666 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11667 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11668 return FPLiteral && FPCast;
11669 };
11670
11671 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11672 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11673 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11674 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11675 TargetTy->isFloatingPoint()) {
11676 bool Lossy;
11677 llvm::APFloat TargetC = FPLiteral->getValue();
11678 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11679 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11680 if (Lossy) {
11681 // If the literal cannot be represented in the source type, then a
11682 // check for == is always false and check for != is always true.
11683 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11684 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11685 << LHS->getSourceRange() << RHS->getSourceRange();
11686 return;
11687 }
11688 }
11689 }
11690
11691 // Match a more general floating-point equality comparison (-Wfloat-equal).
11692 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11693 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11694
11695 // Special case: check for x == x (which is OK).
11696 // Do not emit warnings for such cases.
11697 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11698 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11699 if (DRL->getDecl() == DRR->getDecl())
11700 return;
11701
11702 // Special case: check for comparisons against literals that can be exactly
11703 // represented by APFloat. In such cases, do not emit a warning. This
11704 // is a heuristic: often comparison against such literals are used to
11705 // detect if a value in a variable has not changed. This clearly can
11706 // lead to false negatives.
11707 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11708 if (FLL->isExact())
11709 return;
11710 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11711 if (FLR->isExact())
11712 return;
11713
11714 // Check for comparisons with builtin types.
11715 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11716 CL && CL->getBuiltinCallee())
11717 return;
11718
11719 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11720 CR && CR->getBuiltinCallee())
11721 return;
11722
11723 // Emit the diagnostic.
11724 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11725 << LHS->getSourceRange() << RHS->getSourceRange();
11726}
11727
11728//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11729//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11730
11731namespace {
11732
11733/// Structure recording the 'active' range of an integer-valued
11734/// expression.
11735struct IntRange {
11736 /// The number of bits active in the int. Note that this includes exactly one
11737 /// sign bit if !NonNegative.
11738 unsigned Width;
11739
11740 /// True if the int is known not to have negative values. If so, all leading
11741 /// bits before Width are known zero, otherwise they are known to be the
11742 /// same as the MSB within Width.
11743 bool NonNegative;
11744
11745 IntRange(unsigned Width, bool NonNegative)
11746 : Width(Width), NonNegative(NonNegative) {}
11747
11748 /// Number of bits excluding the sign bit.
11749 unsigned valueBits() const {
11750 return NonNegative ? Width : Width - 1;
11751 }
11752
11753 /// Returns the range of the bool type.
11754 static IntRange forBoolType() {
11755 return IntRange(1, true);
11756 }
11757
11758 /// Returns the range of an opaque value of the given integral type.
11759 static IntRange forValueOfType(ASTContext &C, QualType T) {
11760 return forValueOfCanonicalType(C,
11761 T: T->getCanonicalTypeInternal().getTypePtr());
11762 }
11763
11764 /// Returns the range of an opaque value of a canonical integral type.
11765 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11766 assert(T->isCanonicalUnqualified());
11767
11768 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11769 T = VT->getElementType().getTypePtr();
11770 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11771 T = MT->getElementType().getTypePtr();
11772 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11773 T = CT->getElementType().getTypePtr();
11774 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11775 T = AT->getValueType().getTypePtr();
11776 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11777 T = OBT->getUnderlyingType().getTypePtr();
11778
11779 if (!C.getLangOpts().CPlusPlus) {
11780 // For enum types in C code, use the underlying datatype.
11781 if (const auto *ED = T->getAsEnumDecl())
11782 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11783 } else if (auto *Enum = T->getAsEnumDecl()) {
11784 // For enum types in C++, use the known bit width of the enumerators.
11785 // In C++11, enums can have a fixed underlying type. Use this type to
11786 // compute the range.
11787 if (Enum->isFixed()) {
11788 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11789 !Enum->getIntegerType()->isSignedIntegerType());
11790 }
11791
11792 unsigned NumPositive = Enum->getNumPositiveBits();
11793 unsigned NumNegative = Enum->getNumNegativeBits();
11794
11795 if (NumNegative == 0)
11796 return IntRange(NumPositive, true/*NonNegative*/);
11797 else
11798 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11799 false/*NonNegative*/);
11800 }
11801
11802 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11803 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11804
11805 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11806 assert(BT->isInteger());
11807
11808 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11809 }
11810
11811 /// Returns the "target" range of a canonical integral type, i.e.
11812 /// the range of values expressible in the type.
11813 ///
11814 /// This matches forValueOfCanonicalType except that enums have the
11815 /// full range of their type, not the range of their enumerators.
11816 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11817 assert(T->isCanonicalUnqualified());
11818
11819 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11820 T = VT->getElementType().getTypePtr();
11821 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11822 T = MT->getElementType().getTypePtr();
11823 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11824 T = CT->getElementType().getTypePtr();
11825 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11826 T = AT->getValueType().getTypePtr();
11827 if (const auto *ED = T->getAsEnumDecl())
11828 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11829 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11830 T = OBT->getUnderlyingType().getTypePtr();
11831
11832 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11833 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11834
11835 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11836 assert(BT->isInteger());
11837
11838 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11839 }
11840
11841 /// Returns the supremum of two ranges: i.e. their conservative merge.
11842 static IntRange join(IntRange L, IntRange R) {
11843 bool Unsigned = L.NonNegative && R.NonNegative;
11844 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11845 L.NonNegative && R.NonNegative);
11846 }
11847
11848 /// Return the range of a bitwise-AND of the two ranges.
11849 static IntRange bit_and(IntRange L, IntRange R) {
11850 unsigned Bits = std::max(a: L.Width, b: R.Width);
11851 bool NonNegative = false;
11852 if (L.NonNegative) {
11853 Bits = std::min(a: Bits, b: L.Width);
11854 NonNegative = true;
11855 }
11856 if (R.NonNegative) {
11857 Bits = std::min(a: Bits, b: R.Width);
11858 NonNegative = true;
11859 }
11860 return IntRange(Bits, NonNegative);
11861 }
11862
11863 /// Return the range of a sum of the two ranges.
11864 static IntRange sum(IntRange L, IntRange R) {
11865 bool Unsigned = L.NonNegative && R.NonNegative;
11866 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11867 Unsigned);
11868 }
11869
11870 /// Return the range of a difference of the two ranges.
11871 static IntRange difference(IntRange L, IntRange R) {
11872 // We need a 1-bit-wider range if:
11873 // 1) LHS can be negative: least value can be reduced.
11874 // 2) RHS can be negative: greatest value can be increased.
11875 bool CanWiden = !L.NonNegative || !R.NonNegative;
11876 bool Unsigned = L.NonNegative && R.Width == 0;
11877 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11878 !Unsigned,
11879 Unsigned);
11880 }
11881
11882 /// Return the range of a product of the two ranges.
11883 static IntRange product(IntRange L, IntRange R) {
11884 // If both LHS and RHS can be negative, we can form
11885 // -2^L * -2^R = 2^(L + R)
11886 // which requires L + R + 1 value bits to represent.
11887 bool CanWiden = !L.NonNegative && !R.NonNegative;
11888 bool Unsigned = L.NonNegative && R.NonNegative;
11889 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11890 Unsigned);
11891 }
11892
11893 /// Return the range of a remainder operation between the two ranges.
11894 static IntRange rem(IntRange L, IntRange R) {
11895 // The result of a remainder can't be larger than the result of
11896 // either side. The sign of the result is the sign of the LHS.
11897 bool Unsigned = L.NonNegative;
11898 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11899 Unsigned);
11900 }
11901};
11902
11903} // namespace
11904
11905static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11906 if (value.isSigned() && value.isNegative())
11907 return IntRange(value.getSignificantBits(), false);
11908
11909 if (value.getBitWidth() > MaxWidth)
11910 value = value.trunc(width: MaxWidth);
11911
11912 // isNonNegative() just checks the sign bit without considering
11913 // signedness.
11914 return IntRange(value.getActiveBits(), true);
11915}
11916
11917static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11918 if (result.isInt())
11919 return GetValueRange(value&: result.getInt(), MaxWidth);
11920
11921 if (result.isVector()) {
11922 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
11923 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11924 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
11925 R = IntRange::join(L: R, R: El);
11926 }
11927 return R;
11928 }
11929
11930 if (result.isComplexInt()) {
11931 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
11932 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
11933 return IntRange::join(L: R, R: I);
11934 }
11935
11936 // This can happen with lossless casts to intptr_t of "based" lvalues.
11937 // Assume it might use arbitrary bits.
11938 // FIXME: The only reason we need to pass the type in here is to get
11939 // the sign right on this one case. It would be nice if APValue
11940 // preserved this.
11941 assert(result.isLValue() || result.isAddrLabelDiff());
11942 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11943}
11944
11945static QualType GetExprType(const Expr *E) {
11946 QualType Ty = E->getType();
11947 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11948 Ty = AtomicRHS->getValueType();
11949 return Ty;
11950}
11951
11952/// Attempts to estimate an approximate range for the given integer expression.
11953/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11954/// reliable estimation cannot be determined.
11955///
11956/// \param MaxWidth The width to which the value will be truncated.
11957/// \param InConstantContext If \c true, interpret the expression within a
11958/// constant context.
11959/// \param Approximate If \c true, provide a likely range of values by assuming
11960/// that arithmetic on narrower types remains within those types.
11961/// If \c false, return a range that includes all possible values
11962/// resulting from the expression.
11963/// \returns A range of values that the expression might take, or
11964/// std::nullopt if a reliable estimation cannot be determined.
11965static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11966 unsigned MaxWidth,
11967 bool InConstantContext,
11968 bool Approximate) {
11969 E = E->IgnoreParens();
11970
11971 // Try a full evaluation first.
11972 Expr::EvalResult result;
11973 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
11974 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
11975
11976 // I think we only want to look through implicit casts here; if the
11977 // user has an explicit widening cast, we should treat the value as
11978 // being of the new, wider type.
11979 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11980 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11981 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
11982 Approximate);
11983
11984 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
11985
11986 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11987 CE->getCastKind() == CK_BooleanToSignedIntegral;
11988
11989 // Assume that non-integer casts can span the full range of the type.
11990 if (!isIntegerCast)
11991 return OutputTypeRange;
11992
11993 std::optional<IntRange> SubRange = TryGetExprRange(
11994 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
11995 InConstantContext, Approximate);
11996 if (!SubRange)
11997 return std::nullopt;
11998
11999 // Bail out if the subexpr's range is as wide as the cast type.
12000 if (SubRange->Width >= OutputTypeRange.Width)
12001 return OutputTypeRange;
12002
12003 // Otherwise, we take the smaller width, and we're non-negative if
12004 // either the output type or the subexpr is.
12005 return IntRange(SubRange->Width,
12006 SubRange->NonNegative || OutputTypeRange.NonNegative);
12007 }
12008
12009 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12010 // If we can fold the condition, just take that operand.
12011 bool CondResult;
12012 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
12013 return TryGetExprRange(
12014 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12015 InConstantContext, Approximate);
12016
12017 // Otherwise, conservatively merge.
12018 // TryGetExprRange requires an integer expression, but a throw expression
12019 // results in a void type.
12020 Expr *TrueExpr = CO->getTrueExpr();
12021 if (TrueExpr->getType()->isVoidType())
12022 return std::nullopt;
12023
12024 std::optional<IntRange> L =
12025 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
12026 if (!L)
12027 return std::nullopt;
12028
12029 Expr *FalseExpr = CO->getFalseExpr();
12030 if (FalseExpr->getType()->isVoidType())
12031 return std::nullopt;
12032
12033 std::optional<IntRange> R =
12034 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
12035 if (!R)
12036 return std::nullopt;
12037
12038 return IntRange::join(L: *L, R: *R);
12039 }
12040
12041 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12042 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12043
12044 switch (BO->getOpcode()) {
12045 case BO_Cmp:
12046 llvm_unreachable("builtin <=> should have class type");
12047
12048 // Boolean-valued operations are single-bit and positive.
12049 case BO_LAnd:
12050 case BO_LOr:
12051 case BO_LT:
12052 case BO_GT:
12053 case BO_LE:
12054 case BO_GE:
12055 case BO_EQ:
12056 case BO_NE:
12057 return IntRange::forBoolType();
12058
12059 // The type of the assignments is the type of the LHS, so the RHS
12060 // is not necessarily the same type.
12061 case BO_MulAssign:
12062 case BO_DivAssign:
12063 case BO_RemAssign:
12064 case BO_AddAssign:
12065 case BO_SubAssign:
12066 case BO_XorAssign:
12067 case BO_OrAssign:
12068 // TODO: bitfields?
12069 return IntRange::forValueOfType(C, T: GetExprType(E));
12070
12071 // Simple assignments just pass through the RHS, which will have
12072 // been coerced to the LHS type.
12073 case BO_Assign:
12074 // TODO: bitfields?
12075 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12076 Approximate);
12077
12078 // Operations with opaque sources are black-listed.
12079 case BO_PtrMemD:
12080 case BO_PtrMemI:
12081 return IntRange::forValueOfType(C, T: GetExprType(E));
12082
12083 // Bitwise-and uses the *infinum* of the two source ranges.
12084 case BO_And:
12085 case BO_AndAssign:
12086 Combine = IntRange::bit_and;
12087 break;
12088
12089 // Left shift gets black-listed based on a judgement call.
12090 case BO_Shl:
12091 // ...except that we want to treat '1 << (blah)' as logically
12092 // positive. It's an important idiom.
12093 if (IntegerLiteral *I
12094 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
12095 if (I->getValue() == 1) {
12096 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
12097 return IntRange(R.Width, /*NonNegative*/ true);
12098 }
12099 }
12100 [[fallthrough]];
12101
12102 case BO_ShlAssign:
12103 return IntRange::forValueOfType(C, T: GetExprType(E));
12104
12105 // Right shift by a constant can narrow its left argument.
12106 case BO_Shr:
12107 case BO_ShrAssign: {
12108 std::optional<IntRange> L = TryGetExprRange(
12109 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12110 if (!L)
12111 return std::nullopt;
12112
12113 // If the shift amount is a positive constant, drop the width by
12114 // that much.
12115 if (std::optional<llvm::APSInt> shift =
12116 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12117 if (shift->isNonNegative()) {
12118 if (shift->uge(RHS: L->Width))
12119 L->Width = (L->NonNegative ? 0 : 1);
12120 else
12121 L->Width -= shift->getZExtValue();
12122 }
12123 }
12124
12125 return L;
12126 }
12127
12128 // Comma acts as its right operand.
12129 case BO_Comma:
12130 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12131 Approximate);
12132
12133 case BO_Add:
12134 if (!Approximate)
12135 Combine = IntRange::sum;
12136 break;
12137
12138 case BO_Sub:
12139 if (BO->getLHS()->getType()->isPointerType())
12140 return IntRange::forValueOfType(C, T: GetExprType(E));
12141 if (!Approximate)
12142 Combine = IntRange::difference;
12143 break;
12144
12145 case BO_Mul:
12146 if (!Approximate)
12147 Combine = IntRange::product;
12148 break;
12149
12150 // The width of a division result is mostly determined by the size
12151 // of the LHS.
12152 case BO_Div: {
12153 // Don't 'pre-truncate' the operands.
12154 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
12155 std::optional<IntRange> L = TryGetExprRange(
12156 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12157 if (!L)
12158 return std::nullopt;
12159
12160 // If the divisor is constant, use that.
12161 if (std::optional<llvm::APSInt> divisor =
12162 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12163 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12164 if (log2 >= L->Width)
12165 L->Width = (L->NonNegative ? 0 : 1);
12166 else
12167 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
12168 return L;
12169 }
12170
12171 // Otherwise, just use the LHS's width.
12172 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12173 // could be -1.
12174 std::optional<IntRange> R = TryGetExprRange(
12175 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12176 if (!R)
12177 return std::nullopt;
12178
12179 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12180 }
12181
12182 case BO_Rem:
12183 Combine = IntRange::rem;
12184 break;
12185
12186 // The default behavior is okay for these.
12187 case BO_Xor:
12188 case BO_Or:
12189 break;
12190 }
12191
12192 // Combine the two ranges, but limit the result to the type in which we
12193 // performed the computation.
12194 QualType T = GetExprType(E);
12195 unsigned opWidth = C.getIntWidth(T);
12196 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
12197 InConstantContext, Approximate);
12198 if (!L)
12199 return std::nullopt;
12200
12201 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
12202 InConstantContext, Approximate);
12203 if (!R)
12204 return std::nullopt;
12205
12206 IntRange C = Combine(*L, *R);
12207 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12208 C.Width = std::min(a: C.Width, b: MaxWidth);
12209 return C;
12210 }
12211
12212 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12213 switch (UO->getOpcode()) {
12214 // Boolean-valued operations are white-listed.
12215 case UO_LNot:
12216 return IntRange::forBoolType();
12217
12218 // Operations with opaque sources are black-listed.
12219 case UO_Deref:
12220 case UO_AddrOf: // should be impossible
12221 return IntRange::forValueOfType(C, T: GetExprType(E));
12222
12223 case UO_Minus: {
12224 if (E->getType()->isUnsignedIntegerType()) {
12225 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12226 Approximate);
12227 }
12228
12229 std::optional<IntRange> SubRange = TryGetExprRange(
12230 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12231
12232 if (!SubRange)
12233 return std::nullopt;
12234
12235 // If the range was previously non-negative, we need an extra bit for the
12236 // sign bit. Otherwise, we need an extra bit because the negation of the
12237 // most-negative value is one bit wider than that value.
12238 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
12239 }
12240
12241 case UO_Not: {
12242 if (E->getType()->isUnsignedIntegerType()) {
12243 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12244 Approximate);
12245 }
12246
12247 std::optional<IntRange> SubRange = TryGetExprRange(
12248 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12249
12250 if (!SubRange)
12251 return std::nullopt;
12252
12253 // The width increments by 1 if the sub-expression cannot be negative
12254 // since it now can be.
12255 return IntRange(
12256 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
12257 false);
12258 }
12259
12260 default:
12261 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12262 Approximate);
12263 }
12264 }
12265
12266 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12267 // The source expression is null for the OpaqueValueExpr that stands in for
12268 // a non-type template argument of pointer or reference type; fall back to
12269 // the range of the type in that case.
12270 if (const Expr *SourceExpr = OVE->getSourceExpr())
12271 return TryGetExprRange(C, E: SourceExpr, MaxWidth, InConstantContext,
12272 Approximate);
12273 }
12274
12275 if (const auto *BitField = E->getSourceBitField())
12276 return IntRange(BitField->getBitWidthValue(),
12277 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12278
12279 if (GetExprType(E)->isVoidType())
12280 return std::nullopt;
12281
12282 return IntRange::forValueOfType(C, T: GetExprType(E));
12283}
12284
12285static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12286 bool InConstantContext,
12287 bool Approximate) {
12288 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
12289 Approximate);
12290}
12291
12292/// Checks whether the given value, which currently has the given
12293/// source semantics, has the same value when coerced through the
12294/// target semantics.
12295static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12296 const llvm::fltSemantics &Src,
12297 const llvm::fltSemantics &Tgt) {
12298 llvm::APFloat truncated = value;
12299
12300 bool ignored;
12301 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12302 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12303
12304 return truncated.bitwiseIsEqual(RHS: value);
12305}
12306
12307/// Checks whether the given value, which currently has the given
12308/// source semantics, has the same value when coerced through the
12309/// target semantics.
12310///
12311/// The value might be a vector of floats (or a complex number).
12312static bool IsSameFloatAfterCast(const APValue &value,
12313 const llvm::fltSemantics &Src,
12314 const llvm::fltSemantics &Tgt) {
12315 if (value.isFloat())
12316 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
12317
12318 if (value.isVector()) {
12319 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12320 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
12321 return false;
12322 return true;
12323 }
12324
12325 if (value.isMatrix()) {
12326 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12327 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
12328 return false;
12329 return true;
12330 }
12331
12332 assert(value.isComplexFloat());
12333 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
12334 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
12335}
12336
12337static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12338 bool IsListInit = false);
12339
12340static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12341 // Suppress cases where we are comparing against an enum constant.
12342 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
12343 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
12344 return true;
12345
12346 // Suppress cases where the value is expanded from a macro, unless that macro
12347 // is how a language represents a boolean literal. This is the case in both C
12348 // and Objective-C.
12349 SourceLocation BeginLoc = E->getBeginLoc();
12350 if (BeginLoc.isMacroID()) {
12351 StringRef MacroName = Lexer::getImmediateMacroName(
12352 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
12353 return MacroName != "YES" && MacroName != "NO" &&
12354 MacroName != "true" && MacroName != "false";
12355 }
12356
12357 return false;
12358}
12359
12360static bool isKnownToHaveUnsignedValue(const Expr *E) {
12361 return E->getType()->isIntegerType() &&
12362 (!E->getType()->isSignedIntegerType() ||
12363 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12364}
12365
12366namespace {
12367/// The promoted range of values of a type. In general this has the
12368/// following structure:
12369///
12370/// |-----------| . . . |-----------|
12371/// ^ ^ ^ ^
12372/// Min HoleMin HoleMax Max
12373///
12374/// ... where there is only a hole if a signed type is promoted to unsigned
12375/// (in which case Min and Max are the smallest and largest representable
12376/// values).
12377struct PromotedRange {
12378 // Min, or HoleMax if there is a hole.
12379 llvm::APSInt PromotedMin;
12380 // Max, or HoleMin if there is a hole.
12381 llvm::APSInt PromotedMax;
12382
12383 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12384 if (R.Width == 0)
12385 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12386 else if (R.Width >= BitWidth && !Unsigned) {
12387 // Promotion made the type *narrower*. This happens when promoting
12388 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12389 // Treat all values of 'signed int' as being in range for now.
12390 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
12391 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
12392 } else {
12393 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
12394 .extOrTrunc(width: BitWidth);
12395 PromotedMin.setIsUnsigned(Unsigned);
12396
12397 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
12398 .extOrTrunc(width: BitWidth);
12399 PromotedMax.setIsUnsigned(Unsigned);
12400 }
12401 }
12402
12403 // Determine whether this range is contiguous (has no hole).
12404 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12405
12406 // Where a constant value is within the range.
12407 enum ComparisonResult {
12408 LT = 0x1,
12409 LE = 0x2,
12410 GT = 0x4,
12411 GE = 0x8,
12412 EQ = 0x10,
12413 NE = 0x20,
12414 InRangeFlag = 0x40,
12415
12416 Less = LE | LT | NE,
12417 Min = LE | InRangeFlag,
12418 InRange = InRangeFlag,
12419 Max = GE | InRangeFlag,
12420 Greater = GE | GT | NE,
12421
12422 OnlyValue = LE | GE | EQ | InRangeFlag,
12423 InHole = NE
12424 };
12425
12426 ComparisonResult compare(const llvm::APSInt &Value) const {
12427 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12428 Value.isUnsigned() == PromotedMin.isUnsigned());
12429 if (!isContiguous()) {
12430 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12431 if (Value.isMinValue()) return Min;
12432 if (Value.isMaxValue()) return Max;
12433 if (Value >= PromotedMin) return InRange;
12434 if (Value <= PromotedMax) return InRange;
12435 return InHole;
12436 }
12437
12438 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
12439 case -1: return Less;
12440 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12441 case 1:
12442 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
12443 case -1: return InRange;
12444 case 0: return Max;
12445 case 1: return Greater;
12446 }
12447 }
12448
12449 llvm_unreachable("impossible compare result");
12450 }
12451
12452 static std::optional<StringRef>
12453 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12454 if (Op == BO_Cmp) {
12455 ComparisonResult LTFlag = LT, GTFlag = GT;
12456 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
12457
12458 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12459 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12460 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12461 return std::nullopt;
12462 }
12463
12464 ComparisonResult TrueFlag, FalseFlag;
12465 if (Op == BO_EQ) {
12466 TrueFlag = EQ;
12467 FalseFlag = NE;
12468 } else if (Op == BO_NE) {
12469 TrueFlag = NE;
12470 FalseFlag = EQ;
12471 } else {
12472 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12473 TrueFlag = LT;
12474 FalseFlag = GE;
12475 } else {
12476 TrueFlag = GT;
12477 FalseFlag = LE;
12478 }
12479 if (Op == BO_GE || Op == BO_LE)
12480 std::swap(a&: TrueFlag, b&: FalseFlag);
12481 }
12482 if (R & TrueFlag)
12483 return StringRef("true");
12484 if (R & FalseFlag)
12485 return StringRef("false");
12486 return std::nullopt;
12487 }
12488};
12489}
12490
12491static bool HasEnumType(const Expr *E) {
12492 // Strip off implicit integral promotions.
12493 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12494 if (ICE->getCastKind() != CK_IntegralCast &&
12495 ICE->getCastKind() != CK_NoOp)
12496 break;
12497 E = ICE->getSubExpr();
12498 }
12499
12500 return E->getType()->isEnumeralType();
12501}
12502
12503static int classifyConstantValue(Expr *Constant) {
12504 // The values of this enumeration are used in the diagnostics
12505 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12506 enum ConstantValueKind {
12507 Miscellaneous = 0,
12508 LiteralTrue,
12509 LiteralFalse
12510 };
12511 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12512 return BL->getValue() ? ConstantValueKind::LiteralTrue
12513 : ConstantValueKind::LiteralFalse;
12514 return ConstantValueKind::Miscellaneous;
12515}
12516
12517static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12518 Expr *Constant, Expr *Other,
12519 const llvm::APSInt &Value,
12520 bool RhsConstant) {
12521 if (S.inTemplateInstantiation())
12522 return false;
12523
12524 Expr *OriginalOther = Other;
12525
12526 Constant = Constant->IgnoreParenImpCasts();
12527 Other = Other->IgnoreParenImpCasts();
12528
12529 // Suppress warnings on tautological comparisons between values of the same
12530 // enumeration type. There are only two ways we could warn on this:
12531 // - If the constant is outside the range of representable values of
12532 // the enumeration. In such a case, we should warn about the cast
12533 // to enumeration type, not about the comparison.
12534 // - If the constant is the maximum / minimum in-range value. For an
12535 // enumeratin type, such comparisons can be meaningful and useful.
12536 if (Constant->getType()->isEnumeralType() &&
12537 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12538 return false;
12539
12540 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12541 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12542 if (!OtherValueRange)
12543 return false;
12544
12545 QualType OtherT = Other->getType();
12546 if (const auto *AT = OtherT->getAs<AtomicType>())
12547 OtherT = AT->getValueType();
12548 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12549
12550 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12551 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12552 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12553 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12554 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12555
12556 // Whether we're treating Other as being a bool because of the form of
12557 // expression despite it having another type (typically 'int' in C).
12558 bool OtherIsBooleanDespiteType =
12559 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12560 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12561 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12562
12563 // Check if all values in the range of possible values of this expression
12564 // lead to the same comparison outcome.
12565 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12566 Value.isUnsigned());
12567 auto Cmp = OtherPromotedValueRange.compare(Value);
12568 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12569 if (!Result)
12570 return false;
12571
12572 // Also consider the range determined by the type alone. This allows us to
12573 // classify the warning under the proper diagnostic group.
12574 bool TautologicalTypeCompare = false;
12575 {
12576 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12577 Value.isUnsigned());
12578 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12579 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12580 ConstantOnRHS: RhsConstant)) {
12581 TautologicalTypeCompare = true;
12582 Cmp = TypeCmp;
12583 Result = TypeResult;
12584 }
12585 }
12586
12587 // Don't warn if the non-constant operand actually always evaluates to the
12588 // same value.
12589 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12590 return false;
12591
12592 // Suppress the diagnostic for an in-range comparison if the constant comes
12593 // from a macro or enumerator. We don't want to diagnose
12594 //
12595 // some_long_value <= INT_MAX
12596 //
12597 // when sizeof(int) == sizeof(long).
12598 bool InRange = Cmp & PromotedRange::InRangeFlag;
12599 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12600 return false;
12601
12602 // A comparison of an unsigned bit-field against 0 is really a type problem,
12603 // even though at the type level the bit-field might promote to 'signed int'.
12604 if (Other->refersToBitField() && InRange && Value == 0 &&
12605 Other->getType()->isUnsignedIntegerOrEnumerationType())
12606 TautologicalTypeCompare = true;
12607
12608 // If this is a comparison to an enum constant, include that
12609 // constant in the diagnostic.
12610 const EnumConstantDecl *ED = nullptr;
12611 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12612 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12613
12614 // Should be enough for uint128 (39 decimal digits)
12615 SmallString<64> PrettySourceValue;
12616 llvm::raw_svector_ostream OS(PrettySourceValue);
12617 if (ED) {
12618 OS << '\'' << *ED << "' (" << Value << ")";
12619 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12620 Val: Constant->IgnoreParenImpCasts())) {
12621 OS << (BL->getValue() ? "YES" : "NO");
12622 } else {
12623 OS << Value;
12624 }
12625
12626 if (!TautologicalTypeCompare) {
12627 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12628 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12629 << E->getOpcodeStr() << OS.str() << *Result
12630 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12631 return true;
12632 }
12633
12634 if (IsObjCSignedCharBool) {
12635 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12636 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12637 << OS.str() << *Result);
12638 return true;
12639 }
12640
12641 // FIXME: We use a somewhat different formatting for the in-range cases and
12642 // cases involving boolean values for historical reasons. We should pick a
12643 // consistent way of presenting these diagnostics.
12644 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12645
12646 S.DiagRuntimeBehavior(
12647 Loc: E->getOperatorLoc(), Statement: E,
12648 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12649 : diag::warn_tautological_bool_compare)
12650 << OS.str() << classifyConstantValue(Constant) << OtherT
12651 << OtherIsBooleanDespiteType << *Result
12652 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12653 } else {
12654 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12655 unsigned Diag =
12656 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12657 ? (HasEnumType(E: OriginalOther)
12658 ? diag::warn_unsigned_enum_always_true_comparison
12659 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12660 : diag::warn_unsigned_always_true_comparison)
12661 : diag::warn_tautological_constant_compare;
12662
12663 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12664 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12665 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12666 }
12667
12668 return true;
12669}
12670
12671/// Analyze the operands of the given comparison. Implements the
12672/// fallback case from AnalyzeComparison.
12673static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12674 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12675 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12676}
12677
12678/// Implements -Wsign-compare.
12679///
12680/// \param E the binary operator to check for warnings
12681static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12682 // The type the comparison is being performed in.
12683 QualType T = E->getLHS()->getType();
12684
12685 // Only analyze comparison operators where both sides have been converted to
12686 // the same type.
12687 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12688 return AnalyzeImpConvsInComparison(S, E);
12689
12690 // Don't analyze value-dependent comparisons directly.
12691 if (E->isValueDependent())
12692 return AnalyzeImpConvsInComparison(S, E);
12693
12694 Expr *LHS = E->getLHS();
12695 Expr *RHS = E->getRHS();
12696
12697 if (T->isIntegralType(Ctx: S.Context)) {
12698 std::optional<llvm::APSInt> RHSValue =
12699 RHS->getIntegerConstantExpr(Ctx: S.Context);
12700 std::optional<llvm::APSInt> LHSValue =
12701 LHS->getIntegerConstantExpr(Ctx: S.Context);
12702
12703 // We don't care about expressions whose result is a constant.
12704 if (RHSValue && LHSValue)
12705 return AnalyzeImpConvsInComparison(S, E);
12706
12707 // We only care about expressions where just one side is literal
12708 if ((bool)RHSValue ^ (bool)LHSValue) {
12709 // Is the constant on the RHS or LHS?
12710 const bool RhsConstant = (bool)RHSValue;
12711 Expr *Const = RhsConstant ? RHS : LHS;
12712 Expr *Other = RhsConstant ? LHS : RHS;
12713 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12714
12715 // Check whether an integer constant comparison results in a value
12716 // of 'true' or 'false'.
12717 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12718 return AnalyzeImpConvsInComparison(S, E);
12719 }
12720 }
12721
12722 if (!T->hasUnsignedIntegerRepresentation()) {
12723 // We don't do anything special if this isn't an unsigned integral
12724 // comparison: we're only interested in integral comparisons, and
12725 // signed comparisons only happen in cases we don't care to warn about.
12726 return AnalyzeImpConvsInComparison(S, E);
12727 }
12728
12729 LHS = LHS->IgnoreParenImpCasts();
12730 RHS = RHS->IgnoreParenImpCasts();
12731
12732 if (!S.getLangOpts().CPlusPlus) {
12733 // Avoid warning about comparison of integers with different signs when
12734 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12735 // the type of `E`.
12736 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12737 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12738 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12739 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12740 }
12741
12742 // Check to see if one of the (unmodified) operands is of different
12743 // signedness.
12744 Expr *signedOperand, *unsignedOperand;
12745 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12746 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12747 "unsigned comparison between two signed integer expressions?");
12748 signedOperand = LHS;
12749 unsignedOperand = RHS;
12750 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12751 signedOperand = RHS;
12752 unsignedOperand = LHS;
12753 } else {
12754 return AnalyzeImpConvsInComparison(S, E);
12755 }
12756
12757 // Otherwise, calculate the effective range of the signed operand.
12758 std::optional<IntRange> signedRange =
12759 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12760 /*Approximate=*/true);
12761 if (!signedRange)
12762 return;
12763
12764 // Go ahead and analyze implicit conversions in the operands. Note
12765 // that we skip the implicit conversions on both sides.
12766 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12767 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12768
12769 // If the signed range is non-negative, -Wsign-compare won't fire.
12770 if (signedRange->NonNegative)
12771 return;
12772
12773 // For (in)equality comparisons, if the unsigned operand is a
12774 // constant which cannot collide with a overflowed signed operand,
12775 // then reinterpreting the signed operand as unsigned will not
12776 // change the result of the comparison.
12777 if (E->isEqualityOp()) {
12778 unsigned comparisonWidth = S.Context.getIntWidth(T);
12779 std::optional<IntRange> unsignedRange = TryGetExprRange(
12780 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12781 /*Approximate=*/true);
12782 if (!unsignedRange)
12783 return;
12784
12785 // We should never be unable to prove that the unsigned operand is
12786 // non-negative.
12787 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12788
12789 if (unsignedRange->Width < comparisonWidth)
12790 return;
12791 }
12792
12793 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12794 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12795 << LHS->getType() << RHS->getType()
12796 << LHS->getSourceRange() << RHS->getSourceRange());
12797}
12798
12799/// Analyzes an attempt to assign the given value to a bitfield.
12800///
12801/// Returns true if there was something fishy about the attempt.
12802static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12803 SourceLocation InitLoc) {
12804 assert(Bitfield->isBitField());
12805 if (Bitfield->isInvalidDecl())
12806 return false;
12807
12808 // White-list bool bitfields.
12809 QualType BitfieldType = Bitfield->getType();
12810 if (BitfieldType->isBooleanType())
12811 return false;
12812
12813 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12814 // If the underlying enum type was not explicitly specified as an unsigned
12815 // type and the enum contain only positive values, MSVC++ will cause an
12816 // inconsistency by storing this as a signed type.
12817 if (S.getLangOpts().CPlusPlus11 &&
12818 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12819 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12820 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12821 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12822 << BitfieldEnumDecl;
12823 }
12824 }
12825
12826 // Ignore value- or type-dependent expressions.
12827 if (Bitfield->getBitWidth()->isValueDependent() ||
12828 Bitfield->getBitWidth()->isTypeDependent() ||
12829 Init->isValueDependent() ||
12830 Init->isTypeDependent())
12831 return false;
12832
12833 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12834 unsigned FieldWidth = Bitfield->getBitWidthValue();
12835
12836 Expr::EvalResult Result;
12837 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12838 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12839 // The RHS is not constant. If the RHS has an enum type, make sure the
12840 // bitfield is wide enough to hold all the values of the enum without
12841 // truncation.
12842 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12843 const PreferredTypeAttr *PTAttr = nullptr;
12844 if (!ED) {
12845 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12846 if (PTAttr)
12847 ED = PTAttr->getType()->getAsEnumDecl();
12848 }
12849 if (ED) {
12850 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12851
12852 // Enum types are implicitly signed on Windows, so check if there are any
12853 // negative enumerators to see if the enum was intended to be signed or
12854 // not.
12855 bool SignedEnum = ED->getNumNegativeBits() > 0;
12856
12857 // Check for surprising sign changes when assigning enum values to a
12858 // bitfield of different signedness. If the bitfield is signed and we
12859 // have exactly the right number of bits to store this unsigned enum,
12860 // suggest changing the enum to an unsigned type. This typically happens
12861 // on Windows where unfixed enums always use an underlying type of 'int'.
12862 unsigned DiagID = 0;
12863 if (SignedEnum && !SignedBitfield) {
12864 DiagID =
12865 PTAttr == nullptr
12866 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12867 : diag::
12868 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12869 } else if (SignedBitfield && !SignedEnum &&
12870 ED->getNumPositiveBits() == FieldWidth) {
12871 DiagID =
12872 PTAttr == nullptr
12873 ? diag::warn_signed_bitfield_enum_conversion
12874 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12875 }
12876 if (DiagID) {
12877 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12878 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12879 SourceRange TypeRange =
12880 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12881 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
12882 << SignedEnum << TypeRange;
12883 if (PTAttr)
12884 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12885 << ED;
12886 }
12887
12888 // Compute the required bitwidth. If the enum has negative values, we need
12889 // one more bit than the normal number of positive bits to represent the
12890 // sign bit.
12891 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
12892 b: ED->getNumNegativeBits())
12893 : ED->getNumPositiveBits();
12894
12895 // Check the bitwidth.
12896 if (BitsNeeded > FieldWidth) {
12897 Expr *WidthExpr = Bitfield->getBitWidth();
12898 auto DiagID =
12899 PTAttr == nullptr
12900 ? diag::warn_bitfield_too_small_for_enum
12901 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12902 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12903 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
12904 << BitsNeeded << ED << WidthExpr->getSourceRange();
12905 if (PTAttr)
12906 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12907 << ED;
12908 }
12909 }
12910
12911 return false;
12912 }
12913
12914 llvm::APSInt Value = Result.Val.getInt();
12915
12916 unsigned OriginalWidth = Value.getBitWidth();
12917
12918 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12919 // false positives where the user is demonstrating they intend to use the
12920 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12921 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12922 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12923 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12924 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12925 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
12926 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
12927 return false;
12928 }
12929
12930 if (!Value.isSigned() || Value.isNegative())
12931 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
12932 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12933 OriginalWidth = Value.getSignificantBits();
12934
12935 if (OriginalWidth <= FieldWidth)
12936 return false;
12937
12938 // Compute the value which the bitfield will contain.
12939 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
12940 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12941
12942 // Check whether the stored value is equal to the original value.
12943 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
12944 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
12945 return false;
12946
12947 std::string PrettyValue = toString(I: Value, Radix: 10);
12948 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
12949
12950 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
12951 ? diag::warn_impcast_single_bit_bitield_precision_constant
12952 : diag::warn_impcast_bitfield_precision_constant)
12953 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12954 << Init->getSourceRange();
12955
12956 return true;
12957}
12958
12959/// Analyze the given simple or compound assignment for warning-worthy
12960/// operations.
12961static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12962 // Just recurse on the LHS.
12963 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12964
12965 // We want to recurse on the RHS as normal unless we're assigning to
12966 // a bitfield.
12967 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12968 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
12969 InitLoc: E->getOperatorLoc())) {
12970 // Recurse, ignoring any implicit conversions on the RHS.
12971 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
12972 CC: E->getOperatorLoc());
12973 }
12974 }
12975
12976 // Set context flag for overflow behavior type assignment analysis, use RAII
12977 // pattern to handle nested assignments.
12978 llvm::SaveAndRestore OBTAssignmentContext(
12979 S.InOverflowBehaviorAssignmentContext, true);
12980
12981 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12982
12983 // Diagnose implicitly sequentially-consistent atomic assignment.
12984 if (E->getLHS()->getType()->isAtomicType())
12985 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12986}
12987
12988/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12989static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12990 QualType T, SourceLocation CContext, unsigned diag,
12991 bool PruneControlFlow = false) {
12992 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12993 // address space annotations isn't really useful. The warnings aren't because
12994 // you're converting a `private int` to `unsigned int`, it is because you're
12995 // conerting `int` to `unsigned int`.
12996 if (SourceType.hasAddressSpace())
12997 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
12998 if (T.hasAddressSpace())
12999 T = S.getASTContext().removeAddrSpaceQualType(T);
13000 if (PruneControlFlow) {
13001 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13002 PD: S.PDiag(DiagID: diag)
13003 << SourceType << T << E->getSourceRange()
13004 << SourceRange(CContext));
13005 return;
13006 }
13007 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
13008 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13009}
13010
13011/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13012static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13013 SourceLocation CContext, unsigned diag,
13014 bool PruneControlFlow = false) {
13015 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
13016}
13017
13018/// Diagnose an implicit cast from a floating point value to an integer value.
13019static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13020 SourceLocation CContext) {
13021 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
13022 bool PruneWarnings = S.inTemplateInstantiation();
13023
13024 const Expr *InnerE = E->IgnoreParenImpCasts();
13025 // We also want to warn on, e.g., "int i = -1.234"
13026 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
13027 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13028 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13029
13030 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
13031
13032 llvm::APFloat Value(0.0);
13033 bool IsConstant =
13034 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
13035 if (!IsConstant) {
13036 if (S.ObjC().isSignedCharBool(Ty: T)) {
13037 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13038 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
13039 << E->getType());
13040 }
13041
13042 return DiagnoseImpCast(S, E, T, CContext,
13043 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13044 }
13045
13046 bool isExact = false;
13047
13048 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13049 T->hasUnsignedIntegerRepresentation());
13050 llvm::APFloat::opStatus Result = Value.convertToInteger(
13051 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
13052
13053 // FIXME: Force the precision of the source value down so we don't print
13054 // digits which are usually useless (we don't really care here if we
13055 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13056 // would automatically print the shortest representation, but it's a bit
13057 // tricky to implement.
13058 SmallString<16> PrettySourceValue;
13059 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13060 precision = (precision * 59 + 195) / 196;
13061 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
13062
13063 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
13064 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13065 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13066 << PrettySourceValue);
13067 }
13068
13069 if (Result == llvm::APFloat::opOK && isExact) {
13070 if (IsLiteral) return;
13071 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
13072 PruneControlFlow: PruneWarnings);
13073 }
13074
13075 // Conversion of a floating-point value to a non-bool integer where the
13076 // integral part cannot be represented by the integer type is undefined.
13077 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13078 return DiagnoseImpCast(
13079 S, E, T, CContext,
13080 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13081 : diag::warn_impcast_float_to_integer_out_of_range,
13082 PruneControlFlow: PruneWarnings);
13083
13084 unsigned DiagID = 0;
13085 if (IsLiteral) {
13086 // Warn on floating point literal to integer.
13087 DiagID = diag::warn_impcast_literal_float_to_integer;
13088 } else if (IntegerValue == 0) {
13089 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13090 return DiagnoseImpCast(S, E, T, CContext,
13091 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13092 }
13093 // Warn on non-zero to zero conversion.
13094 DiagID = diag::warn_impcast_float_to_integer_zero;
13095 } else {
13096 if (IntegerValue.isUnsigned()) {
13097 if (!IntegerValue.isMaxValue()) {
13098 return DiagnoseImpCast(S, E, T, CContext,
13099 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13100 }
13101 } else { // IntegerValue.isSigned()
13102 if (!IntegerValue.isMaxSignedValue() &&
13103 !IntegerValue.isMinSignedValue()) {
13104 return DiagnoseImpCast(S, E, T, CContext,
13105 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13106 }
13107 }
13108 // Warn on evaluatable floating point expression to integer conversion.
13109 DiagID = diag::warn_impcast_float_to_integer;
13110 }
13111
13112 SmallString<16> PrettyTargetValue;
13113 if (IsBool)
13114 PrettyTargetValue = Value.isZero() ? "false" : "true";
13115 else
13116 IntegerValue.toString(Str&: PrettyTargetValue);
13117
13118 if (PruneWarnings) {
13119 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13120 PD: S.PDiag(DiagID)
13121 << E->getType() << T.getUnqualifiedType()
13122 << PrettySourceValue << PrettyTargetValue
13123 << E->getSourceRange() << SourceRange(CContext));
13124 } else {
13125 S.Diag(Loc: E->getExprLoc(), DiagID)
13126 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13127 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13128 }
13129}
13130
13131/// Analyze the given compound assignment for the possible losing of
13132/// floating-point precision.
13133static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13134 assert(isa<CompoundAssignOperator>(E) &&
13135 "Must be compound assignment operation");
13136 // Recurse on the LHS and RHS in here
13137 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13138 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13139
13140 if (E->getLHS()->getType()->isAtomicType())
13141 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13142
13143 // Now check the outermost expression
13144 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13145 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
13146 ->getComputationResultType()
13147 ->getAs<BuiltinType>();
13148
13149 // The below checks assume source is floating point.
13150 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13151
13152 // If source is floating point but target is an integer.
13153 if (ResultBT->isInteger())
13154 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
13155 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
13156
13157 if (!ResultBT->isFloatingPoint())
13158 return;
13159
13160 // If both source and target are floating points, warn about losing precision.
13161 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13162 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
13163 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
13164 // warn about dropping FP rank.
13165 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
13166 diag: diag::warn_impcast_float_result_precision);
13167}
13168
13169static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13170 IntRange Range) {
13171 if (!Range.Width) return "0";
13172
13173 llvm::APSInt ValueInRange = Value;
13174 ValueInRange.setIsSigned(!Range.NonNegative);
13175 ValueInRange = ValueInRange.trunc(width: Range.Width);
13176 return toString(I: ValueInRange, Radix: 10);
13177}
13178
13179static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13180 bool ToBool) {
13181 if (!isa<ImplicitCastExpr>(Val: Ex))
13182 return false;
13183
13184 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13185 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
13186 const Type *Source =
13187 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
13188 if (Target->isDependentType())
13189 return false;
13190
13191 const auto *FloatCandidateBT =
13192 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
13193 const Type *BoolCandidateType = ToBool ? Target : Source;
13194
13195 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
13196 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13197}
13198
13199static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13200 SourceLocation CC) {
13201 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13202 const Expr *CurrA = TheCall->getArg(Arg: I);
13203 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
13204 continue;
13205
13206 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13207 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
13208 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13209 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
13210 if (IsSwapped) {
13211 // Warn on this floating-point to bool conversion.
13212 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
13213 T: CurrA->getType(), CContext: CC,
13214 diag: diag::warn_impcast_floating_point_to_bool);
13215 }
13216 }
13217}
13218
13219static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13220 SourceLocation CC) {
13221 // Don't warn on functions which have return type nullptr_t.
13222 if (isa<CallExpr>(Val: E))
13223 return;
13224
13225 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13226 const Expr *NewE = E->IgnoreParenImpCasts();
13227 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
13228 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13229 if (!IsGNUNullExpr && !HasNullPtrType)
13230 return;
13231
13232 // Return if target type is a safe conversion.
13233 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13234 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13235 return;
13236
13237 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
13238 Loc: E->getExprLoc()))
13239 return;
13240
13241 SourceLocation Loc = E->getSourceRange().getBegin();
13242
13243 // Venture through the macro stacks to get to the source of macro arguments.
13244 // The new location is a better location than the complete location that was
13245 // passed in.
13246 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13247 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
13248
13249 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13250 if (IsGNUNullExpr && Loc.isMacroID()) {
13251 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13252 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
13253 if (MacroName == "NULL")
13254 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13255 }
13256
13257 // Only warn if the null and context location are in the same macro expansion.
13258 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
13259 return;
13260
13261 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
13262 << HasNullPtrType << T << SourceRange(CC)
13263 << FixItHint::CreateReplacement(RemoveRange: Loc,
13264 Code: S.getFixItZeroLiteralForType(T, Loc));
13265}
13266
13267// Helper function to filter out cases for constant width constant conversion.
13268// Don't warn on char array initialization or for non-decimal values.
13269static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13270 SourceLocation CC) {
13271 // If initializing from a constant, and the constant starts with '0',
13272 // then it is a binary, octal, or hexadecimal. Allow these constants
13273 // to fill all the bits, even if there is a sign change.
13274 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
13275 const char FirstLiteralCharacter =
13276 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
13277 if (FirstLiteralCharacter == '0')
13278 return false;
13279 }
13280
13281 // If the CC location points to a '{', and the type is char, then assume
13282 // assume it is an array initialization.
13283 if (CC.isValid() && T->isCharType()) {
13284 const char FirstContextCharacter =
13285 S.getSourceManager().getCharacterData(SL: CC)[0];
13286 if (FirstContextCharacter == '{')
13287 return false;
13288 }
13289
13290 return true;
13291}
13292
13293static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13294 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
13295 if (!IL) {
13296 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13297 if (UO->getOpcode() == UO_Minus)
13298 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13299 }
13300 }
13301
13302 return IL;
13303}
13304
13305static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13306 E = E->IgnoreParenImpCasts();
13307 SourceLocation ExprLoc = E->getExprLoc();
13308
13309 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
13310 BinaryOperator::Opcode Opc = BO->getOpcode();
13311 Expr::EvalResult Result;
13312 // Do not diagnose unsigned shifts.
13313 if (Opc == BO_Shl) {
13314 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
13315 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
13316 if (LHS && LHS->getValue() == 0)
13317 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
13318 else if (!E->isValueDependent() && LHS && RHS &&
13319 RHS->getValue().isNonNegative() &&
13320 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
13321 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
13322 << (Result.Val.getInt() != 0);
13323 else if (E->getType()->isSignedIntegerType())
13324 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
13325 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
13326 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
13327 Code: ") != 0");
13328 }
13329 }
13330
13331 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13332 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
13333 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
13334 if (!LHS || !RHS)
13335 return;
13336 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13337 (RHS->getValue() == 0 || RHS->getValue() == 1))
13338 // Do not diagnose common idioms.
13339 return;
13340 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13341 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
13342 }
13343}
13344
13345static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
13346 const Type *Target, Expr *E,
13347 QualType T,
13348 SourceLocation CC) {
13349 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13350 Source != Target);
13351
13352 // Lone surrogates have a distinct representation in UTF-32.
13353 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13354 // so don't warn on such conversion.
13355 if (Source->isChar16Type() && Target->isChar32Type())
13356 return;
13357
13358 Expr::EvalResult Result;
13359 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
13360 InConstantContext: S.isConstantEvaluatedContext())) {
13361 llvm::APSInt Value(32);
13362 Value = Result.Val.getInt();
13363 bool IsASCII = Value <= 0x7F;
13364 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13365 bool ConversionPreservesSemantics =
13366 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13367
13368 if (!ConversionPreservesSemantics) {
13369 auto IsSingleCodeUnitCP = [](const QualType &T,
13370 const llvm::APSInt &Value) {
13371 if (T->isChar8Type())
13372 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13373 if (T->isChar16Type())
13374 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13375 assert(T->isChar32Type());
13376 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13377 };
13378
13379 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
13380 << E->getType() << T
13381 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13382 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
13383 }
13384 } else {
13385 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
13386 S.getASTContext().getIntWidth(T);
13387 DiagnoseImpCast(S, E, T, CContext: CC,
13388 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
13389 : diag::warn_impcast_unicode_char_type);
13390 }
13391}
13392
13393bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
13394 From = Context.getCanonicalType(T: From);
13395 To = Context.getCanonicalType(T: To);
13396 QualType MaybePointee = From->getPointeeType();
13397 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13398 From = MaybePointee;
13399 MaybePointee = To->getPointeeType();
13400 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13401 To = MaybePointee;
13402
13403 if (const auto *FromFn = From->getAs<FunctionType>()) {
13404 if (const auto *ToFn = To->getAs<FunctionType>()) {
13405 if (FromFn->getCFIUncheckedCalleeAttr() &&
13406 !ToFn->getCFIUncheckedCalleeAttr())
13407 return true;
13408 }
13409 }
13410 return false;
13411}
13412
13413void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
13414 bool *ICContext, bool IsListInit) {
13415 if (E->isTypeDependent() || E->isValueDependent()) return;
13416
13417 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
13418 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13419 if (Source == Target) return;
13420 if (Target->isDependentType()) return;
13421
13422 // If the conversion context location is invalid don't complain. We also
13423 // don't want to emit a warning if the issue occurs from the expansion of
13424 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13425 // delay this check as long as possible. Once we detect we are in that
13426 // scenario, we just return.
13427 if (CC.isInvalid())
13428 return;
13429
13430 if (Source->isAtomicType())
13431 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13432
13433 // Diagnose implicit casts to bool.
13434 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
13435 if (isa<StringLiteral>(Val: E))
13436 // Warn on string literal to bool. Checks for string literals in logical
13437 // and expressions, for instance, assert(0 && "error here"), are
13438 // prevented by a check in AnalyzeImplicitConversions().
13439 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13440 diag: diag::warn_impcast_string_literal_to_bool);
13441 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
13442 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
13443 // This covers the literal expressions that evaluate to Objective-C
13444 // objects.
13445 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13446 diag: diag::warn_impcast_objective_c_literal_to_bool);
13447 }
13448 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13449 // Warn on pointer to bool conversion that is always true.
13450 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
13451 Range: SourceRange(CC));
13452 }
13453 }
13454
13455 CheckOverflowBehaviorTypeConversion(E, T, CC);
13456
13457 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13458 // is a typedef for signed char (macOS), then that constant value has to be 1
13459 // or 0.
13460 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
13461 Expr::EvalResult Result;
13462 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
13463 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13464 ObjC().adornBoolConversionDiagWithTernaryFixit(
13465 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13466 << toString(I: Result.Val.getInt(), Radix: 10));
13467 }
13468 return;
13469 }
13470 }
13471
13472 // Check implicit casts from Objective-C collection literals to specialized
13473 // collection types, e.g., NSArray<NSString *> *.
13474 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13475 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13476 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13477 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13478
13479 // Strip complex types.
13480 if (isa<ComplexType>(Val: Source)) {
13481 if (!isa<ComplexType>(Val: Target)) {
13482 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13483 return;
13484
13485 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13486 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13487 diag: diag::err_impcast_incompatible_type);
13488 }
13489
13490 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13491 diag: getLangOpts().CPlusPlus
13492 ? diag::err_impcast_complex_scalar
13493 : diag::warn_impcast_complex_scalar);
13494 }
13495
13496 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13497 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13498 }
13499
13500 // Strip vector types.
13501 if (isa<VectorType>(Val: Source)) {
13502 if (Target->isSveVLSBuiltinType() &&
13503 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13504 SecondType: QualType(Source, 0)) ||
13505 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13506 SecondType: QualType(Source, 0))))
13507 return;
13508
13509 if (Target->isRVVVLSBuiltinType() &&
13510 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13511 SecondType: QualType(Source, 0)) ||
13512 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13513 SecondType: QualType(Source, 0))))
13514 return;
13515
13516 if (!isa<VectorType>(Val: Target)) {
13517 if (SourceMgr.isInSystemMacro(loc: CC))
13518 return;
13519 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13520 }
13521 if (getLangOpts().HLSL &&
13522 Target->castAs<VectorType>()->getNumElements() <
13523 Source->castAs<VectorType>()->getNumElements()) {
13524 // Diagnose vector truncation but don't return. We may also want to
13525 // diagnose an element conversion.
13526 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13527 diag: diag::warn_hlsl_impcast_vector_truncation);
13528 }
13529
13530 // If the vector cast is cast between two vectors of the same size, it is
13531 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13532 if (!getLangOpts().HLSL &&
13533 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13534 return;
13535
13536 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13537 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13538 }
13539 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13540 Target = VecTy->getElementType().getTypePtr();
13541
13542 // Strip matrix types.
13543 if (isa<ConstantMatrixType>(Val: Source)) {
13544 if (Target->isScalarType())
13545 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13546
13547 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13548 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13549 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13550 // Diagnose Matrix truncation but don't return. We may also want to
13551 // diagnose an element conversion.
13552 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13553 diag: diag::warn_hlsl_impcast_matrix_truncation);
13554 }
13555
13556 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13557 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13558 }
13559 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13560 Target = MatTy->getElementType().getTypePtr();
13561
13562 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13563 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13564
13565 // Strip SVE vector types
13566 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13567 // Need the original target type for vector type checks
13568 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13569 // Handle conversion from scalable to fixed when msve-vector-bits is
13570 // specified
13571 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13572 SecondType: QualType(Source, 0)) ||
13573 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13574 SecondType: QualType(Source, 0)))
13575 return;
13576
13577 // If the vector cast is cast between two vectors of the same size, it is
13578 // a bitcast, not a conversion.
13579 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13580 return;
13581
13582 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13583 }
13584
13585 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13586 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13587
13588 // If the source is floating point...
13589 if (SourceBT && SourceBT->isFloatingPoint()) {
13590 // ...and the target is floating point...
13591 if (TargetBT && TargetBT->isFloatingPoint()) {
13592 // ...then warn if we're dropping FP rank.
13593
13594 int Order = getASTContext().getFloatingTypeSemanticOrder(
13595 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13596 if (Order > 0) {
13597 // Don't warn about float constants that are precisely
13598 // representable in the target type.
13599 Expr::EvalResult result;
13600 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13601 // Value might be a float, a float vector, or a float complex.
13602 if (IsSameFloatAfterCast(
13603 value: result.Val,
13604 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13605 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13606 return;
13607 }
13608
13609 if (SourceMgr.isInSystemMacro(loc: CC))
13610 return;
13611
13612 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13613 }
13614 // ... or possibly if we're increasing rank, too
13615 else if (Order < 0) {
13616 if (SourceMgr.isInSystemMacro(loc: CC))
13617 return;
13618
13619 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13620 }
13621 return;
13622 }
13623
13624 // If the target is integral, always warn.
13625 if (TargetBT && TargetBT->isInteger()) {
13626 if (SourceMgr.isInSystemMacro(loc: CC))
13627 return;
13628
13629 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13630 }
13631
13632 // Detect the case where a call result is converted from floating-point to
13633 // to bool, and the final argument to the call is converted from bool, to
13634 // discover this typo:
13635 //
13636 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13637 //
13638 // FIXME: This is an incredibly special case; is there some more general
13639 // way to detect this class of misplaced-parentheses bug?
13640 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13641 // Check last argument of function call to see if it is an
13642 // implicit cast from a type matching the type the result
13643 // is being cast to.
13644 CallExpr *CEx = cast<CallExpr>(Val: E);
13645 if (unsigned NumArgs = CEx->getNumArgs()) {
13646 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13647 Expr *InnerE = LastA->IgnoreParenImpCasts();
13648 if (isa<ImplicitCastExpr>(Val: LastA) &&
13649 InnerE->getType()->isBooleanType()) {
13650 // Warn on this floating-point to bool conversion
13651 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13652 diag: diag::warn_impcast_floating_point_to_bool);
13653 }
13654 }
13655 }
13656 return;
13657 }
13658
13659 // Valid casts involving fixed point types should be accounted for here.
13660 if (Source->isFixedPointType()) {
13661 if (Target->isUnsaturatedFixedPointType()) {
13662 Expr::EvalResult Result;
13663 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13664 InConstantContext: isConstantEvaluatedContext())) {
13665 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13666 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13667 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13668 if (Value > MaxVal || Value < MinVal) {
13669 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13670 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13671 << Value.toString() << T
13672 << E->getSourceRange()
13673 << clang::SourceRange(CC));
13674 return;
13675 }
13676 }
13677 } else if (Target->isIntegerType()) {
13678 Expr::EvalResult Result;
13679 if (!isConstantEvaluatedContext() &&
13680 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13681 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13682
13683 bool Overflowed;
13684 llvm::APSInt IntResult = FXResult.convertToInt(
13685 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13686 Overflow: &Overflowed);
13687
13688 if (Overflowed) {
13689 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13690 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13691 << FXResult.toString() << T
13692 << E->getSourceRange()
13693 << clang::SourceRange(CC));
13694 return;
13695 }
13696 }
13697 }
13698 } else if (Target->isUnsaturatedFixedPointType()) {
13699 if (Source->isIntegerType()) {
13700 Expr::EvalResult Result;
13701 if (!isConstantEvaluatedContext() &&
13702 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13703 llvm::APSInt Value = Result.Val.getInt();
13704
13705 bool Overflowed;
13706 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13707 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13708
13709 if (Overflowed) {
13710 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13711 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13712 << toString(I: Value, /*Radix=*/10) << T
13713 << E->getSourceRange()
13714 << clang::SourceRange(CC));
13715 return;
13716 }
13717 }
13718 }
13719 }
13720
13721 // If we are casting an integer type to a floating point type without
13722 // initialization-list syntax, we might lose accuracy if the floating
13723 // point type has a narrower significand than the integer type.
13724 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13725 TargetBT->isFloatingType() && !IsListInit) {
13726 // Determine the number of precision bits in the source integer type.
13727 std::optional<IntRange> SourceRange =
13728 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13729 /*Approximate=*/true);
13730 if (!SourceRange)
13731 return;
13732 unsigned int SourcePrecision = SourceRange->Width;
13733
13734 // Determine the number of precision bits in the
13735 // target floating point type.
13736 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13737 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13738
13739 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13740 SourcePrecision > TargetPrecision) {
13741
13742 if (std::optional<llvm::APSInt> SourceInt =
13743 E->getIntegerConstantExpr(Ctx: Context)) {
13744 // If the source integer is a constant, convert it to the target
13745 // floating point type. Issue a warning if the value changes
13746 // during the whole conversion.
13747 llvm::APFloat TargetFloatValue(
13748 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13749 llvm::APFloat::opStatus ConversionStatus =
13750 TargetFloatValue.convertFromAPInt(
13751 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13752 RM: llvm::APFloat::rmNearestTiesToEven);
13753
13754 if (ConversionStatus != llvm::APFloat::opOK) {
13755 SmallString<32> PrettySourceValue;
13756 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13757 SmallString<32> PrettyTargetValue;
13758 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13759
13760 DiagRuntimeBehavior(
13761 Loc: E->getExprLoc(), Statement: E,
13762 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13763 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13764 << E->getSourceRange() << clang::SourceRange(CC));
13765 }
13766 } else {
13767 // Otherwise, the implicit conversion may lose precision.
13768 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13769 diag: diag::warn_impcast_integer_float_precision);
13770 }
13771 }
13772 }
13773
13774 DiagnoseNullConversion(S&: *this, E, T, CC);
13775
13776 DiscardMisalignedMemberAddress(T: Target, E);
13777
13778 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13779 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13780 return;
13781 }
13782
13783 if (Target->isBooleanType())
13784 DiagnoseIntInBoolContext(S&: *this, E);
13785
13786 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13787 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13788 << QualType(Source, 0) << QualType(Target, 0);
13789 }
13790
13791 if (!Source->isIntegerType() || !Target->isIntegerType())
13792 return;
13793
13794 // TODO: remove this early return once the false positives for constant->bool
13795 // in templates, macros, etc, are reduced or removed.
13796 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13797 return;
13798
13799 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13800 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13801 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13802 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13803 << E->getType());
13804 }
13805 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13806 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13807 if (!LikelySourceRange)
13808 return;
13809
13810 IntRange SourceTypeRange =
13811 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13812 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13813
13814 if (LikelySourceRange->Width > TargetRange.Width) {
13815 // Check if target is a wrapping OBT - if so, don't warn about constant
13816 // conversion as this type may be used intentionally with implicit
13817 // truncation, especially during assignments.
13818 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13819 if (TargetOBT->isWrapKind()) {
13820 return;
13821 }
13822 }
13823
13824 // Check if source expression has an explicit __ob_wrap cast because if so,
13825 // wrapping was explicitly requested and we shouldn't warn
13826 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13827 if (SourceOBT->isWrapKind()) {
13828 return;
13829 }
13830 }
13831
13832 // If the source is a constant, use a default-on diagnostic.
13833 // TODO: this should happen for bitfield stores, too.
13834 Expr::EvalResult Result;
13835 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13836 InConstantContext: isConstantEvaluatedContext())) {
13837 llvm::APSInt Value(32);
13838 Value = Result.Val.getInt();
13839
13840 if (SourceMgr.isInSystemMacro(loc: CC))
13841 return;
13842
13843 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13844 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13845
13846 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13847 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13848 << PrettySourceValue << PrettyTargetValue
13849 << E->getType() << T << E->getSourceRange()
13850 << SourceRange(CC));
13851 return;
13852 }
13853
13854 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13855 if (SourceMgr.isInSystemMacro(loc: CC))
13856 return;
13857
13858 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13859 if (UO->getOpcode() == UO_Minus)
13860 return DiagnoseImpCast(
13861 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13862 }
13863
13864 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13865 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13866 /* pruneControlFlow */ PruneControlFlow: true);
13867 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13868 diag: diag::warn_impcast_integer_precision);
13869 }
13870
13871 if (TargetRange.Width > SourceTypeRange.Width) {
13872 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13873 if (UO->getOpcode() == UO_Minus)
13874 if (Source->isUnsignedIntegerType()) {
13875 if (Target->isUnsignedIntegerType())
13876 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13877 diag: diag::warn_impcast_high_order_zero_bits);
13878 if (Target->isSignedIntegerType())
13879 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13880 diag: diag::warn_impcast_nonnegative_result);
13881 }
13882 }
13883
13884 if (TargetRange.Width == LikelySourceRange->Width &&
13885 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13886 Source->isSignedIntegerType()) {
13887 // Warn when doing a signed to signed conversion, warn if the positive
13888 // source value is exactly the width of the target type, which will
13889 // cause a negative value to be stored.
13890
13891 Expr::EvalResult Result;
13892 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
13893 !SourceMgr.isInSystemMacro(loc: CC)) {
13894 llvm::APSInt Value = Result.Val.getInt();
13895 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
13896 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13897 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13898
13899 Diag(Loc: E->getExprLoc(),
13900 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13901 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13902 << E->getSourceRange() << SourceRange(CC));
13903 return;
13904 }
13905 }
13906
13907 // Fall through for non-constants to give a sign conversion warning.
13908 }
13909
13910 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
13911 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13912 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13913 LikelySourceRange->Width == TargetRange.Width))) {
13914 if (SourceMgr.isInSystemMacro(loc: CC))
13915 return;
13916
13917 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13918 TargetBT->isInteger() &&
13919 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13920 return;
13921 }
13922
13923 unsigned DiagID = diag::warn_impcast_integer_sign;
13924
13925 // Traditionally, gcc has warned about this under -Wsign-compare.
13926 // We also want to warn about it in -Wconversion.
13927 // So if -Wconversion is off, use a completely identical diagnostic
13928 // in the sign-compare group.
13929 // The conditional-checking code will
13930 if (ICContext) {
13931 DiagID = diag::warn_impcast_integer_sign_conditional;
13932 *ICContext = true;
13933 }
13934
13935 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
13936 }
13937
13938 // If we're implicitly converting from an integer into an enumeration, that
13939 // is valid in C but invalid in C++.
13940 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
13941 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13942 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
13943 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
13944
13945 // Diagnose conversions between different enumeration types.
13946 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13947 // type, to give us better diagnostics.
13948 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
13949
13950 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13951 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13952 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13953 TargetEnum->getDecl()->hasNameForLinkage() &&
13954 SourceEnum != TargetEnum) {
13955 if (SourceMgr.isInSystemMacro(loc: CC))
13956 return;
13957
13958 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
13959 diag: diag::warn_impcast_different_enum_types);
13960 }
13961}
13962
13963static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13964 SourceLocation CC, QualType T);
13965
13966static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13967 SourceLocation CC, bool &ICContext) {
13968 E = E->IgnoreParenImpCasts();
13969 // Diagnose incomplete type for second or third operand in C.
13970 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13971 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
13972
13973 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
13974 return CheckConditionalOperator(S, E: CO, CC, T);
13975
13976 AnalyzeImplicitConversions(S, E, CC);
13977 if (E->getType() != T)
13978 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
13979}
13980
13981static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13982 SourceLocation CC, QualType T) {
13983 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
13984
13985 Expr *TrueExpr = E->getTrueExpr();
13986 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
13987 TrueExpr = BCO->getCommon();
13988
13989 bool Suspicious = false;
13990 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
13991 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
13992
13993 if (T->isBooleanType())
13994 DiagnoseIntInBoolContext(S, E);
13995
13996 // If -Wconversion would have warned about either of the candidates
13997 // for a signedness conversion to the context type...
13998 if (!Suspicious) return;
13999
14000 // ...but it's currently ignored...
14001 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
14002 return;
14003
14004 // ...then check whether it would have warned about either of the
14005 // candidates for a signedness conversion to the condition type.
14006 if (E->getType() == T) return;
14007
14008 Suspicious = false;
14009 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
14010 ICContext: &Suspicious);
14011 if (!Suspicious)
14012 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
14013 T: E->getType(), CC, ICContext: &Suspicious);
14014}
14015
14016/// Check conversion of given expression to boolean.
14017/// Input argument E is a logical expression.
14018static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
14019 // Run the bool-like conversion checks only for C since there bools are
14020 // still not used as the return type from "boolean" operators or as the input
14021 // type for conditional operators.
14022 if (S.getLangOpts().CPlusPlus)
14023 return;
14024 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
14025 return;
14026 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
14027}
14028
14029namespace {
14030struct AnalyzeImplicitConversionsWorkItem {
14031 Expr *E;
14032 SourceLocation CC;
14033 bool IsListInit;
14034};
14035}
14036
14037static void CheckCommaOperand(
14038 Sema &S, Expr *E, QualType T, SourceLocation CC,
14039 bool ExtraCheckForImplicitConversion,
14040 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14041 E = E->IgnoreParenImpCasts();
14042 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
14043
14044 if (ExtraCheckForImplicitConversion && E->getType() != T)
14045 S.CheckImplicitConversion(E, T, CC);
14046}
14047
14048/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14049/// that should be visited are added to WorkList.
14050static void AnalyzeImplicitConversions(
14051 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14052 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14053 Expr *OrigE = Item.E;
14054 SourceLocation CC = Item.CC;
14055
14056 QualType T = OrigE->getType();
14057 Expr *E = OrigE->IgnoreParenImpCasts();
14058
14059 // Propagate whether we are in a C++ list initialization expression.
14060 // If so, we do not issue warnings for implicit int-float conversion
14061 // precision loss, because C++11 narrowing already handles it.
14062 //
14063 // HLSL's initialization lists are special, so they shouldn't observe the C++
14064 // behavior here.
14065 bool IsListInit =
14066 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
14067 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14068
14069 if (E->isTypeDependent() || E->isValueDependent())
14070 return;
14071
14072 Expr *SourceExpr = E;
14073 // Examine, but don't traverse into the source expression of an
14074 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14075 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14076 // evaluate it in the context of checking the specific conversion to T though.
14077 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
14078 if (auto *Src = OVE->getSourceExpr())
14079 SourceExpr = Src;
14080
14081 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
14082 if (UO->getOpcode() == UO_Not &&
14083 UO->getSubExpr()->isKnownToHaveBooleanValue())
14084 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
14085 << OrigE->getSourceRange() << T->isBooleanType()
14086 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
14087
14088 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
14089 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14090 BO->getLHS()->isKnownToHaveBooleanValue() &&
14091 BO->getRHS()->isKnownToHaveBooleanValue() &&
14092 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
14093 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
14094 SourceManager &SM = S.getSourceManager();
14095 const LangOptions &LO = S.getLangOpts();
14096 SourceLocation BLoc = BO->getOperatorLoc();
14097 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
14098 StringRef SR = clang::Lexer::getSourceText(
14099 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
14100 // To reduce false positives, only issue the diagnostic if the operator
14101 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14102 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14103 // in C, along with other macro spellings the user might invent.
14104 if (SR.str() == "&" || SR.str() == "|") {
14105
14106 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
14107 << (BO->getOpcode() == BO_And ? "&" : "|")
14108 << OrigE->getSourceRange()
14109 << FixItHint::CreateReplacement(
14110 RemoveRange: BO->getOperatorLoc(),
14111 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
14112 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
14113 }
14114 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14115 /// Analyze the given comma operator. The basic idea behind the analysis
14116 /// is to analyze the left and right operands slightly differently. The
14117 /// left operand needs to check whether the operand itself has an implicit
14118 /// conversion, but not whether the left operand induces an implicit
14119 /// conversion for the entire comma expression itself. This is similar to
14120 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14121 /// were directly used for the implicit conversion check.
14122 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
14123 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14124 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
14125 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14126 return;
14127 }
14128 }
14129
14130 // For conditional operators, we analyze the arguments as if they
14131 // were being fed directly into the output.
14132 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
14133 CheckConditionalOperator(S, E: CO, CC, T);
14134 return;
14135 }
14136
14137 // Check implicit argument conversions for function calls.
14138 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
14139 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
14140
14141 // Go ahead and check any implicit conversions we might have skipped.
14142 // The non-canonical typecheck is just an optimization;
14143 // CheckImplicitConversion will filter out dead implicit conversions.
14144 if (SourceExpr->getType() != T)
14145 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
14146
14147 // Now continue drilling into this expression.
14148
14149 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
14150 // The bound subexpressions in a PseudoObjectExpr are not reachable
14151 // as transitive children.
14152 // FIXME: Use a more uniform representation for this.
14153 for (auto *SE : POE->semantics())
14154 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
14155 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14156 }
14157
14158 // Skip past explicit casts.
14159 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
14160 E = CE->getSubExpr();
14161 // In the special case of a C++ function-style cast with braces,
14162 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14163 // initializer. This InitListExpr basically belongs to the cast itself, so
14164 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14165 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
14166 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
14167 if (InitListE->getNumInits() == 1) {
14168 E = InitListE->getInit(Init: 0);
14169 }
14170 }
14171 }
14172 E = E->IgnoreParenImpCasts();
14173 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14174 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
14175 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
14176 return;
14177 }
14178
14179 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
14180 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
14181 // The base expression is only used to initialize the parameter for
14182 // arguments to `inout` parameters, so we only traverse down the base
14183 // expression for `inout` cases.
14184 if (OutArgE->isInOut())
14185 WorkList.push_back(
14186 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14187 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
14188 return;
14189 }
14190
14191 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14192 // Do a somewhat different check with comparison operators.
14193 if (BO->isComparisonOp())
14194 return AnalyzeComparison(S, E: BO);
14195
14196 // And with simple assignments.
14197 if (BO->getOpcode() == BO_Assign)
14198 return AnalyzeAssignment(S, E: BO);
14199 // And with compound assignments.
14200 if (BO->isAssignmentOp())
14201 return AnalyzeCompoundAssignment(S, E: BO);
14202 }
14203
14204 // These break the otherwise-useful invariant below. Fortunately,
14205 // we don't really need to recurse into them, because any internal
14206 // expressions should have been analyzed already when they were
14207 // built into statements.
14208 if (isa<StmtExpr>(Val: E)) return;
14209
14210 // Don't descend into unevaluated contexts.
14211 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
14212
14213 // Now just recurse over the expression's children.
14214 CC = E->getExprLoc();
14215 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
14216 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14217 for (Stmt *SubStmt : E->children()) {
14218 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
14219 if (!ChildExpr)
14220 continue;
14221
14222 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
14223 if (ChildExpr == CSE->getOperand())
14224 // Do not recurse over a CoroutineSuspendExpr's operand.
14225 // The operand is also a subexpression of getCommonExpr(), and
14226 // recursing into it directly would produce duplicate diagnostics.
14227 continue;
14228
14229 if (IsLogicalAndOperator &&
14230 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
14231 // Ignore checking string literals that are in logical and operators.
14232 // This is a common pattern for asserts.
14233 continue;
14234 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
14235 }
14236
14237 if (BO && BO->isLogicalOp()) {
14238 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14239 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14240 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14241
14242 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14243 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14244 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14245 }
14246
14247 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
14248 if (U->getOpcode() == UO_LNot) {
14249 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
14250 } else if (U->getOpcode() != UO_AddrOf) {
14251 if (U->getSubExpr()->getType()->isAtomicType())
14252 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
14253 DiagID: diag::warn_atomic_implicit_seq_cst);
14254 }
14255 }
14256}
14257
14258/// AnalyzeImplicitConversions - Find and report any interesting
14259/// implicit conversions in the given expression. There are a couple
14260/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14261static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14262 bool IsListInit/*= false*/) {
14263 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14264 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
14265 while (!WorkList.empty())
14266 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
14267}
14268
14269// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14270// Returns true when emitting a warning about taking the address of a reference.
14271static bool CheckForReference(Sema &SemaRef, const Expr *E,
14272 const PartialDiagnostic &PD) {
14273 E = E->IgnoreParenImpCasts();
14274
14275 const FunctionDecl *FD = nullptr;
14276
14277 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14278 if (!DRE->getDecl()->getType()->isReferenceType())
14279 return false;
14280 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14281 if (!M->getMemberDecl()->getType()->isReferenceType())
14282 return false;
14283 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
14284 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
14285 return false;
14286 FD = Call->getDirectCallee();
14287 } else {
14288 return false;
14289 }
14290
14291 SemaRef.Diag(Loc: E->getExprLoc(), PD);
14292
14293 // If possible, point to location of function.
14294 if (FD) {
14295 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
14296 }
14297
14298 return true;
14299}
14300
14301// Returns true if the SourceLocation is expanded from any macro body.
14302// Returns false if the SourceLocation is invalid, is from not in a macro
14303// expansion, or is from expanded from a top-level macro argument.
14304static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14305 if (Loc.isInvalid())
14306 return false;
14307
14308 while (Loc.isMacroID()) {
14309 if (SM.isMacroBodyExpansion(Loc))
14310 return true;
14311 Loc = SM.getImmediateMacroCallerLoc(Loc);
14312 }
14313
14314 return false;
14315}
14316
14317void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14318 Expr::NullPointerConstantKind NullKind,
14319 bool IsEqual, SourceRange Range) {
14320 if (!E)
14321 return;
14322
14323 // Don't warn inside macros.
14324 if (E->getExprLoc().isMacroID()) {
14325 const SourceManager &SM = getSourceManager();
14326 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
14327 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
14328 return;
14329 }
14330 E = E->IgnoreImpCasts();
14331
14332 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14333
14334 if (isa<CXXThisExpr>(Val: E)) {
14335 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14336 : diag::warn_this_bool_conversion;
14337 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14338 return;
14339 }
14340
14341 bool IsAddressOf = false;
14342
14343 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
14344 if (UO->getOpcode() != UO_AddrOf)
14345 return;
14346 IsAddressOf = true;
14347 E = UO->getSubExpr();
14348 }
14349
14350 if (IsAddressOf) {
14351 unsigned DiagID = IsCompare
14352 ? diag::warn_address_of_reference_null_compare
14353 : diag::warn_address_of_reference_bool_conversion;
14354 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14355 << IsEqual;
14356 if (CheckForReference(SemaRef&: *this, E, PD)) {
14357 return;
14358 }
14359 }
14360
14361 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14362 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
14363 std::string Str;
14364 llvm::raw_string_ostream S(Str);
14365 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14366 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14367 : diag::warn_cast_nonnull_to_bool;
14368 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
14369 << E->getSourceRange() << Range << IsEqual;
14370 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
14371 };
14372
14373 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14374 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
14375 if (auto *Callee = Call->getDirectCallee()) {
14376 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14377 ComplainAboutNonnullParamOrCall(A);
14378 return;
14379 }
14380 }
14381 }
14382
14383 // Complain if we are converting a lambda expression to a boolean value
14384 // outside of instantiation.
14385 if (!inTemplateInstantiation()) {
14386 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
14387 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14388 MRecordDecl && MRecordDecl->isLambda()) {
14389 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
14390 << /*LambdaPointerConversionOperatorType=*/3
14391 << MRecordDecl->getSourceRange() << Range << IsEqual;
14392 return;
14393 }
14394 }
14395 }
14396
14397 // Expect to find a single Decl. Skip anything more complicated.
14398 ValueDecl *D = nullptr;
14399 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
14400 D = R->getDecl();
14401 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14402 D = M->getMemberDecl();
14403 }
14404
14405 // Weak Decls can be null.
14406 if (!D || D->isWeak())
14407 return;
14408
14409 // Check for parameter decl with nonnull attribute
14410 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
14411 if (getCurFunction() &&
14412 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
14413 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14414 ComplainAboutNonnullParamOrCall(A);
14415 return;
14416 }
14417
14418 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
14419 // Skip function template not specialized yet.
14420 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14421 return;
14422 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
14423 assert(ParamIter != FD->param_end());
14424 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
14425
14426 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14427 if (!NonNull->args_size()) {
14428 ComplainAboutNonnullParamOrCall(NonNull);
14429 return;
14430 }
14431
14432 for (const ParamIdx &ArgNo : NonNull->args()) {
14433 if (ArgNo.getASTIndex() == ParamNo) {
14434 ComplainAboutNonnullParamOrCall(NonNull);
14435 return;
14436 }
14437 }
14438 }
14439 }
14440 }
14441 }
14442
14443 QualType T = D->getType();
14444 // A reference to a function is never null either; look through it.
14445 const bool IsFunctionReference =
14446 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14447 if (IsFunctionReference)
14448 T = T->getPointeeType();
14449 const bool IsArray = T->isArrayType();
14450 const bool IsFunction = T->isFunctionType();
14451
14452 // Address of function is used to silence the function warning.
14453 if (IsAddressOf && IsFunction) {
14454 return;
14455 }
14456
14457 // Found nothing.
14458 if (!IsAddressOf && !IsFunction && !IsArray)
14459 return;
14460
14461 // Pretty print the expression for the diagnostic.
14462 std::string Str;
14463 llvm::raw_string_ostream S(Str);
14464 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14465
14466 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14467 : diag::warn_impcast_pointer_to_bool;
14468 enum {
14469 AddressOf,
14470 FunctionPointer,
14471 ArrayPointer
14472 } DiagType;
14473 if (IsAddressOf)
14474 DiagType = AddressOf;
14475 else if (IsFunction)
14476 DiagType = FunctionPointer;
14477 else if (IsArray)
14478 DiagType = ArrayPointer;
14479 else
14480 llvm_unreachable("Could not determine diagnostic.");
14481 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14482 << Range << IsEqual;
14483
14484 // The fix-it notes below only apply to a bare function name, not a reference.
14485 if (!IsFunction || IsFunctionReference)
14486 return;
14487
14488 // Suggest '&' to silence the function warning.
14489 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14490 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14491
14492 // Check to see if '()' fixit should be emitted.
14493 QualType ReturnType;
14494 UnresolvedSet<4> NonTemplateOverloads;
14495 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14496 if (ReturnType.isNull())
14497 return;
14498
14499 if (IsCompare) {
14500 // There are two cases here. If there is null constant, the only suggest
14501 // for a pointer return type. If the null is 0, then suggest if the return
14502 // type is a pointer or an integer type.
14503 if (!ReturnType->isPointerType()) {
14504 if (NullKind == Expr::NPCK_ZeroExpression ||
14505 NullKind == Expr::NPCK_ZeroLiteral) {
14506 if (!ReturnType->isIntegerType())
14507 return;
14508 } else {
14509 return;
14510 }
14511 }
14512 } else { // !IsCompare
14513 // For function to bool, only suggest if the function pointer has bool
14514 // return type.
14515 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14516 return;
14517 }
14518 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14519 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14520}
14521
14522bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14523 SourceLocation CC) {
14524 QualType Source = E->getType();
14525 QualType Target = T;
14526
14527 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14528 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14529 // Overflow behavior type is being stripped - issue warning
14530 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14531 Target->isUnsignedIntegerType()) {
14532 // For unsigned wrap to unsigned conversions, use pedantic version
14533 unsigned DiagId =
14534 InOverflowBehaviorAssignmentContext
14535 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14536 : diag::warn_impcast_overflow_behavior_pedantic;
14537 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14538 } else {
14539 unsigned DiagId = InOverflowBehaviorAssignmentContext
14540 ? diag::warn_impcast_overflow_behavior_assignment
14541 : diag::warn_impcast_overflow_behavior;
14542 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14543 }
14544 }
14545 }
14546
14547 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14548 if (TargetOBT->isWrapKind()) {
14549 return true;
14550 }
14551 }
14552
14553 return false;
14554}
14555
14556void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14557 // Don't diagnose in unevaluated contexts.
14558 if (isUnevaluatedContext())
14559 return;
14560
14561 // Don't diagnose for value- or type-dependent expressions.
14562 if (E->isTypeDependent() || E->isValueDependent())
14563 return;
14564
14565 // Check for array bounds violations in cases where the check isn't triggered
14566 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14567 // ArraySubscriptExpr is on the RHS of a variable initialization.
14568 CheckArrayAccess(E);
14569
14570 // This is not the right CC for (e.g.) a variable initialization.
14571 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14572}
14573
14574void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14575 ::CheckBoolLikeConversion(S&: *this, E, CC);
14576}
14577
14578void Sema::CheckForIntOverflow (const Expr *E) {
14579 // Use a work list to deal with nested struct initializers.
14580 SmallVector<const Expr *, 2> Exprs(1, E);
14581
14582 do {
14583 const Expr *OriginalE = Exprs.pop_back_val();
14584 const Expr *E = OriginalE->IgnoreParenCasts();
14585
14586 if (isa<BinaryOperator>(Val: E) ||
14587 (isa<UnaryOperator>(Val: E) && cast<UnaryOperator>(Val: E)->canOverflow())) {
14588 E->EvaluateForOverflow(Ctx: Context);
14589 continue;
14590 }
14591
14592 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14593 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14594 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14595 E->EvaluateForOverflow(Ctx: Context);
14596 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14597 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14598 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14599 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14600 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14601 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14602 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14603 Exprs.push_back(Elt: Temporary->getSubExpr());
14604 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14605 Exprs.push_back(Elt: Array->getIdx());
14606 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14607 Exprs.push_back(Elt: Compound->getInitializer());
14608 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14609 New && New->isArray()) {
14610 if (auto ArraySize = New->getArraySize())
14611 Exprs.push_back(Elt: *ArraySize);
14612 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14613 Exprs.push_back(Elt: MTE->getSubExpr());
14614 } while (!Exprs.empty());
14615}
14616
14617namespace {
14618
14619/// Visitor for expressions which looks for unsequenced operations on the
14620/// same object.
14621class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14622 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14623
14624 /// A tree of sequenced regions within an expression. Two regions are
14625 /// unsequenced if one is an ancestor or a descendent of the other. When we
14626 /// finish processing an expression with sequencing, such as a comma
14627 /// expression, we fold its tree nodes into its parent, since they are
14628 /// unsequenced with respect to nodes we will visit later.
14629 class SequenceTree {
14630 struct Value {
14631 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14632 unsigned Parent : 31;
14633 LLVM_PREFERRED_TYPE(bool)
14634 unsigned Merged : 1;
14635 };
14636 SmallVector<Value, 8> Values;
14637
14638 public:
14639 /// A region within an expression which may be sequenced with respect
14640 /// to some other region.
14641 class Seq {
14642 friend class SequenceTree;
14643
14644 unsigned Index;
14645
14646 explicit Seq(unsigned N) : Index(N) {}
14647
14648 public:
14649 Seq() : Index(0) {}
14650 };
14651
14652 SequenceTree() { Values.push_back(Elt: Value(0)); }
14653 Seq root() const { return Seq(0); }
14654
14655 /// Create a new sequence of operations, which is an unsequenced
14656 /// subset of \p Parent. This sequence of operations is sequenced with
14657 /// respect to other children of \p Parent.
14658 Seq allocate(Seq Parent) {
14659 Values.push_back(Elt: Value(Parent.Index));
14660 return Seq(Values.size() - 1);
14661 }
14662
14663 /// Merge a sequence of operations into its parent.
14664 void merge(Seq S) {
14665 Values[S.Index].Merged = true;
14666 }
14667
14668 /// Determine whether two operations are unsequenced. This operation
14669 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14670 /// should have been merged into its parent as appropriate.
14671 bool isUnsequenced(Seq Cur, Seq Old) {
14672 unsigned C = representative(K: Cur.Index);
14673 unsigned Target = representative(K: Old.Index);
14674 while (C >= Target) {
14675 if (C == Target)
14676 return true;
14677 C = Values[C].Parent;
14678 }
14679 return false;
14680 }
14681
14682 private:
14683 /// Pick a representative for a sequence.
14684 unsigned representative(unsigned K) {
14685 if (Values[K].Merged)
14686 // Perform path compression as we go.
14687 return Values[K].Parent = representative(K: Values[K].Parent);
14688 return K;
14689 }
14690 };
14691
14692 /// An object for which we can track unsequenced uses.
14693 using Object = const NamedDecl *;
14694
14695 /// Different flavors of object usage which we track. We only track the
14696 /// least-sequenced usage of each kind.
14697 enum UsageKind {
14698 /// A read of an object. Multiple unsequenced reads are OK.
14699 UK_Use,
14700
14701 /// A modification of an object which is sequenced before the value
14702 /// computation of the expression, such as ++n in C++.
14703 UK_ModAsValue,
14704
14705 /// A modification of an object which is not sequenced before the value
14706 /// computation of the expression, such as n++.
14707 UK_ModAsSideEffect,
14708
14709 UK_Count = UK_ModAsSideEffect + 1
14710 };
14711
14712 /// Bundle together a sequencing region and the expression corresponding
14713 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14714 struct Usage {
14715 const Expr *UsageExpr = nullptr;
14716 SequenceTree::Seq Seq;
14717
14718 Usage() = default;
14719 };
14720
14721 struct UsageInfo {
14722 Usage Uses[UK_Count];
14723
14724 /// Have we issued a diagnostic for this object already?
14725 bool Diagnosed = false;
14726
14727 UsageInfo();
14728 };
14729 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14730
14731 Sema &SemaRef;
14732
14733 /// Sequenced regions within the expression.
14734 SequenceTree Tree;
14735
14736 /// Declaration modifications and references which we have seen.
14737 UsageInfoMap UsageMap;
14738
14739 /// The region we are currently within.
14740 SequenceTree::Seq Region;
14741
14742 /// Filled in with declarations which were modified as a side-effect
14743 /// (that is, post-increment operations).
14744 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14745
14746 /// Expressions to check later. We defer checking these to reduce
14747 /// stack usage.
14748 SmallVectorImpl<const Expr *> &WorkList;
14749
14750 /// RAII object wrapping the visitation of a sequenced subexpression of an
14751 /// expression. At the end of this process, the side-effects of the evaluation
14752 /// become sequenced with respect to the value computation of the result, so
14753 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14754 /// UK_ModAsValue.
14755 struct SequencedSubexpression {
14756 SequencedSubexpression(SequenceChecker &Self)
14757 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14758 Self.ModAsSideEffect = &ModAsSideEffect;
14759 }
14760
14761 ~SequencedSubexpression() {
14762 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14763 // Add a new usage with usage kind UK_ModAsValue, and then restore
14764 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14765 // the previous one was empty).
14766 UsageInfo &UI = Self.UsageMap[M.first];
14767 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14768 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14769 SideEffectUsage = M.second;
14770 }
14771 Self.ModAsSideEffect = OldModAsSideEffect;
14772 }
14773
14774 SequenceChecker &Self;
14775 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14776 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14777 };
14778
14779 /// RAII object wrapping the visitation of a subexpression which we might
14780 /// choose to evaluate as a constant. If any subexpression is evaluated and
14781 /// found to be non-constant, this allows us to suppress the evaluation of
14782 /// the outer expression.
14783 class EvaluationTracker {
14784 public:
14785 EvaluationTracker(SequenceChecker &Self)
14786 : Self(Self), Prev(Self.EvalTracker) {
14787 Self.EvalTracker = this;
14788 }
14789
14790 ~EvaluationTracker() {
14791 Self.EvalTracker = Prev;
14792 if (Prev)
14793 Prev->EvalOK &= EvalOK;
14794 }
14795
14796 bool evaluate(const Expr *E, bool &Result) {
14797 if (!EvalOK || E->isValueDependent())
14798 return false;
14799 EvalOK = E->EvaluateAsBooleanCondition(
14800 Result, Ctx: Self.SemaRef.Context,
14801 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14802 return EvalOK;
14803 }
14804
14805 private:
14806 SequenceChecker &Self;
14807 EvaluationTracker *Prev;
14808 bool EvalOK = true;
14809 } *EvalTracker = nullptr;
14810
14811 /// Find the object which is produced by the specified expression,
14812 /// if any.
14813 Object getObject(const Expr *E, bool Mod) const {
14814 E = E->IgnoreParenCasts();
14815 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14816 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14817 return getObject(E: UO->getSubExpr(), Mod);
14818 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14819 if (BO->getOpcode() == BO_Comma)
14820 return getObject(E: BO->getRHS(), Mod);
14821 if (Mod && BO->isAssignmentOp())
14822 return getObject(E: BO->getLHS(), Mod);
14823 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14824 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14825 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14826 return ME->getMemberDecl();
14827 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14828 // FIXME: If this is a reference, map through to its value.
14829 return DRE->getDecl();
14830 return nullptr;
14831 }
14832
14833 /// Note that an object \p O was modified or used by an expression
14834 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14835 /// the object \p O as obtained via the \p UsageMap.
14836 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14837 // Get the old usage for the given object and usage kind.
14838 Usage &U = UI.Uses[UK];
14839 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14840 // If we have a modification as side effect and are in a sequenced
14841 // subexpression, save the old Usage so that we can restore it later
14842 // in SequencedSubexpression::~SequencedSubexpression.
14843 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14844 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14845 // Then record the new usage with the current sequencing region.
14846 U.UsageExpr = UsageExpr;
14847 U.Seq = Region;
14848 }
14849 }
14850
14851 /// Check whether a modification or use of an object \p O in an expression
14852 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14853 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14854 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14855 /// usage and false we are checking for a mod-use unsequenced usage.
14856 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14857 UsageKind OtherKind, bool IsModMod) {
14858 if (UI.Diagnosed)
14859 return;
14860
14861 const Usage &U = UI.Uses[OtherKind];
14862 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14863 return;
14864
14865 const Expr *Mod = U.UsageExpr;
14866 const Expr *ModOrUse = UsageExpr;
14867 if (OtherKind == UK_Use)
14868 std::swap(a&: Mod, b&: ModOrUse);
14869
14870 SemaRef.DiagRuntimeBehavior(
14871 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14872 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14873 : diag::warn_unsequenced_mod_use)
14874 << O << SourceRange(ModOrUse->getExprLoc()));
14875 UI.Diagnosed = true;
14876 }
14877
14878 // A note on note{Pre, Post}{Use, Mod}:
14879 //
14880 // (It helps to follow the algorithm with an expression such as
14881 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14882 // operations before C++17 and both are well-defined in C++17).
14883 //
14884 // When visiting a node which uses/modify an object we first call notePreUse
14885 // or notePreMod before visiting its sub-expression(s). At this point the
14886 // children of the current node have not yet been visited and so the eventual
14887 // uses/modifications resulting from the children of the current node have not
14888 // been recorded yet.
14889 //
14890 // We then visit the children of the current node. After that notePostUse or
14891 // notePostMod is called. These will 1) detect an unsequenced modification
14892 // as side effect (as in "k++ + k") and 2) add a new usage with the
14893 // appropriate usage kind.
14894 //
14895 // We also have to be careful that some operation sequences modification as
14896 // side effect as well (for example: || or ,). To account for this we wrap
14897 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14898 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14899 // which record usages which are modifications as side effect, and then
14900 // downgrade them (or more accurately restore the previous usage which was a
14901 // modification as side effect) when exiting the scope of the sequenced
14902 // subexpression.
14903
14904 void notePreUse(Object O, const Expr *UseExpr) {
14905 UsageInfo &UI = UsageMap[O];
14906 // Uses conflict with other modifications.
14907 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14908 }
14909
14910 void notePostUse(Object O, const Expr *UseExpr) {
14911 UsageInfo &UI = UsageMap[O];
14912 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14913 /*IsModMod=*/false);
14914 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
14915 }
14916
14917 void notePreMod(Object O, const Expr *ModExpr) {
14918 UsageInfo &UI = UsageMap[O];
14919 // Modifications conflict with other modifications and with uses.
14920 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14921 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14922 }
14923
14924 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14925 UsageInfo &UI = UsageMap[O];
14926 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14927 /*IsModMod=*/true);
14928 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
14929 }
14930
14931public:
14932 SequenceChecker(Sema &S, const Expr *E,
14933 SmallVectorImpl<const Expr *> &WorkList)
14934 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14935 Visit(S: E);
14936 // Silence a -Wunused-private-field since WorkList is now unused.
14937 // TODO: Evaluate if it can be used, and if not remove it.
14938 (void)this->WorkList;
14939 }
14940
14941 void VisitStmt(const Stmt *S) {
14942 // Skip all statements which aren't expressions for now.
14943 }
14944
14945 void VisitExpr(const Expr *E) {
14946 // By default, just recurse to evaluated subexpressions.
14947 Base::VisitStmt(S: E);
14948 }
14949
14950 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14951 for (auto *Sub : CSE->children()) {
14952 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
14953 if (!ChildExpr)
14954 continue;
14955
14956 if (ChildExpr == CSE->getOperand())
14957 // Do not recurse over a CoroutineSuspendExpr's operand.
14958 // The operand is also a subexpression of getCommonExpr(), and
14959 // recursing into it directly could confuse object management
14960 // for the sake of sequence tracking.
14961 continue;
14962
14963 Visit(S: Sub);
14964 }
14965 }
14966
14967 void VisitCastExpr(const CastExpr *E) {
14968 Object O = Object();
14969 if (E->getCastKind() == CK_LValueToRValue)
14970 O = getObject(E: E->getSubExpr(), Mod: false);
14971
14972 if (O)
14973 notePreUse(O, UseExpr: E);
14974 VisitExpr(E);
14975 if (O)
14976 notePostUse(O, UseExpr: E);
14977 }
14978
14979 void VisitSequencedExpressions(const Expr *SequencedBefore,
14980 const Expr *SequencedAfter) {
14981 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
14982 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
14983 SequenceTree::Seq OldRegion = Region;
14984
14985 {
14986 SequencedSubexpression SeqBefore(*this);
14987 Region = BeforeRegion;
14988 Visit(S: SequencedBefore);
14989 }
14990
14991 Region = AfterRegion;
14992 Visit(S: SequencedAfter);
14993
14994 Region = OldRegion;
14995
14996 Tree.merge(S: BeforeRegion);
14997 Tree.merge(S: AfterRegion);
14998 }
14999
15000 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15001 // C++17 [expr.sub]p1:
15002 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15003 // expression E1 is sequenced before the expression E2.
15004 if (SemaRef.getLangOpts().CPlusPlus17)
15005 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
15006 else {
15007 Visit(S: ASE->getLHS());
15008 Visit(S: ASE->getRHS());
15009 }
15010 }
15011
15012 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15013 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15014 void VisitBinPtrMem(const BinaryOperator *BO) {
15015 // C++17 [expr.mptr.oper]p4:
15016 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15017 // the expression E1 is sequenced before the expression E2.
15018 if (SemaRef.getLangOpts().CPlusPlus17)
15019 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15020 else {
15021 Visit(S: BO->getLHS());
15022 Visit(S: BO->getRHS());
15023 }
15024 }
15025
15026 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15027 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15028 void VisitBinShlShr(const BinaryOperator *BO) {
15029 // C++17 [expr.shift]p4:
15030 // The expression E1 is sequenced before the expression E2.
15031 if (SemaRef.getLangOpts().CPlusPlus17)
15032 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15033 else {
15034 Visit(S: BO->getLHS());
15035 Visit(S: BO->getRHS());
15036 }
15037 }
15038
15039 void VisitBinComma(const BinaryOperator *BO) {
15040 // C++11 [expr.comma]p1:
15041 // Every value computation and side effect associated with the left
15042 // expression is sequenced before every value computation and side
15043 // effect associated with the right expression.
15044 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15045 }
15046
15047 void VisitBinAssign(const BinaryOperator *BO) {
15048 SequenceTree::Seq RHSRegion;
15049 SequenceTree::Seq LHSRegion;
15050 if (SemaRef.getLangOpts().CPlusPlus17) {
15051 RHSRegion = Tree.allocate(Parent: Region);
15052 LHSRegion = Tree.allocate(Parent: Region);
15053 } else {
15054 RHSRegion = Region;
15055 LHSRegion = Region;
15056 }
15057 SequenceTree::Seq OldRegion = Region;
15058
15059 // C++11 [expr.ass]p1:
15060 // [...] the assignment is sequenced after the value computation
15061 // of the right and left operands, [...]
15062 //
15063 // so check it before inspecting the operands and update the
15064 // map afterwards.
15065 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
15066 if (O)
15067 notePreMod(O, ModExpr: BO);
15068
15069 if (SemaRef.getLangOpts().CPlusPlus17) {
15070 // C++17 [expr.ass]p1:
15071 // [...] The right operand is sequenced before the left operand. [...]
15072 {
15073 SequencedSubexpression SeqBefore(*this);
15074 Region = RHSRegion;
15075 Visit(S: BO->getRHS());
15076 }
15077
15078 Region = LHSRegion;
15079 Visit(S: BO->getLHS());
15080
15081 if (O && isa<CompoundAssignOperator>(Val: BO))
15082 notePostUse(O, UseExpr: BO);
15083
15084 } else {
15085 // C++11 does not specify any sequencing between the LHS and RHS.
15086 Region = LHSRegion;
15087 Visit(S: BO->getLHS());
15088
15089 if (O && isa<CompoundAssignOperator>(Val: BO))
15090 notePostUse(O, UseExpr: BO);
15091
15092 Region = RHSRegion;
15093 Visit(S: BO->getRHS());
15094 }
15095
15096 // C++11 [expr.ass]p1:
15097 // the assignment is sequenced [...] before the value computation of the
15098 // assignment expression.
15099 // C11 6.5.16/3 has no such rule.
15100 Region = OldRegion;
15101 if (O)
15102 notePostMod(O, ModExpr: BO,
15103 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15104 : UK_ModAsSideEffect);
15105 if (SemaRef.getLangOpts().CPlusPlus17) {
15106 Tree.merge(S: RHSRegion);
15107 Tree.merge(S: LHSRegion);
15108 }
15109 }
15110
15111 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15112 VisitBinAssign(BO: CAO);
15113 }
15114
15115 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15116 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15117 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15118 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15119 if (!O)
15120 return VisitExpr(E: UO);
15121
15122 notePreMod(O, ModExpr: UO);
15123 Visit(S: UO->getSubExpr());
15124 // C++11 [expr.pre.incr]p1:
15125 // the expression ++x is equivalent to x+=1
15126 notePostMod(O, ModExpr: UO,
15127 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15128 : UK_ModAsSideEffect);
15129 }
15130
15131 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15132 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15133 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15134 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15135 if (!O)
15136 return VisitExpr(E: UO);
15137
15138 notePreMod(O, ModExpr: UO);
15139 Visit(S: UO->getSubExpr());
15140 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
15141 }
15142
15143 void VisitBinLOr(const BinaryOperator *BO) {
15144 // C++11 [expr.log.or]p2:
15145 // If the second expression is evaluated, every value computation and
15146 // side effect associated with the first expression is sequenced before
15147 // every value computation and side effect associated with the
15148 // second expression.
15149 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15150 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15151 SequenceTree::Seq OldRegion = Region;
15152
15153 EvaluationTracker Eval(*this);
15154 {
15155 SequencedSubexpression Sequenced(*this);
15156 Region = LHSRegion;
15157 Visit(S: BO->getLHS());
15158 }
15159
15160 // C++11 [expr.log.or]p1:
15161 // [...] the second operand is not evaluated if the first operand
15162 // evaluates to true.
15163 bool EvalResult = false;
15164 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15165 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15166 if (ShouldVisitRHS) {
15167 Region = RHSRegion;
15168 Visit(S: BO->getRHS());
15169 }
15170
15171 Region = OldRegion;
15172 Tree.merge(S: LHSRegion);
15173 Tree.merge(S: RHSRegion);
15174 }
15175
15176 void VisitBinLAnd(const BinaryOperator *BO) {
15177 // C++11 [expr.log.and]p2:
15178 // If the second expression is evaluated, every value computation and
15179 // side effect associated with the first expression is sequenced before
15180 // every value computation and side effect associated with the
15181 // second expression.
15182 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15183 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15184 SequenceTree::Seq OldRegion = Region;
15185
15186 EvaluationTracker Eval(*this);
15187 {
15188 SequencedSubexpression Sequenced(*this);
15189 Region = LHSRegion;
15190 Visit(S: BO->getLHS());
15191 }
15192
15193 // C++11 [expr.log.and]p1:
15194 // [...] the second operand is not evaluated if the first operand is false.
15195 bool EvalResult = false;
15196 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15197 bool ShouldVisitRHS = !EvalOK || EvalResult;
15198 if (ShouldVisitRHS) {
15199 Region = RHSRegion;
15200 Visit(S: BO->getRHS());
15201 }
15202
15203 Region = OldRegion;
15204 Tree.merge(S: LHSRegion);
15205 Tree.merge(S: RHSRegion);
15206 }
15207
15208 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15209 // C++11 [expr.cond]p1:
15210 // [...] Every value computation and side effect associated with the first
15211 // expression is sequenced before every value computation and side effect
15212 // associated with the second or third expression.
15213 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
15214
15215 // No sequencing is specified between the true and false expression.
15216 // However since exactly one of both is going to be evaluated we can
15217 // consider them to be sequenced. This is needed to avoid warning on
15218 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15219 // both the true and false expressions because we can't evaluate x.
15220 // This will still allow us to detect an expression like (pre C++17)
15221 // "(x ? y += 1 : y += 2) = y".
15222 //
15223 // We don't wrap the visitation of the true and false expression with
15224 // SequencedSubexpression because we don't want to downgrade modifications
15225 // as side effect in the true and false expressions after the visition
15226 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15227 // not warn between the two "y++", but we should warn between the "y++"
15228 // and the "y".
15229 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
15230 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
15231 SequenceTree::Seq OldRegion = Region;
15232
15233 EvaluationTracker Eval(*this);
15234 {
15235 SequencedSubexpression Sequenced(*this);
15236 Region = ConditionRegion;
15237 Visit(S: CO->getCond());
15238 }
15239
15240 // C++11 [expr.cond]p1:
15241 // [...] The first expression is contextually converted to bool (Clause 4).
15242 // It is evaluated and if it is true, the result of the conditional
15243 // expression is the value of the second expression, otherwise that of the
15244 // third expression. Only one of the second and third expressions is
15245 // evaluated. [...]
15246 bool EvalResult = false;
15247 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
15248 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15249 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15250 if (ShouldVisitTrueExpr) {
15251 Region = TrueRegion;
15252 Visit(S: CO->getTrueExpr());
15253 }
15254 if (ShouldVisitFalseExpr) {
15255 Region = FalseRegion;
15256 Visit(S: CO->getFalseExpr());
15257 }
15258
15259 Region = OldRegion;
15260 Tree.merge(S: ConditionRegion);
15261 Tree.merge(S: TrueRegion);
15262 Tree.merge(S: FalseRegion);
15263 }
15264
15265 void VisitCallExpr(const CallExpr *CE) {
15266 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15267
15268 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
15269 return;
15270
15271 // C++11 [intro.execution]p15:
15272 // When calling a function [...], every value computation and side effect
15273 // associated with any argument expression, or with the postfix expression
15274 // designating the called function, is sequenced before execution of every
15275 // expression or statement in the body of the function [and thus before
15276 // the value computation of its result].
15277 SequencedSubexpression Sequenced(*this);
15278 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
15279 // C++17 [expr.call]p5
15280 // The postfix-expression is sequenced before each expression in the
15281 // expression-list and any default argument. [...]
15282 SequenceTree::Seq CalleeRegion;
15283 SequenceTree::Seq OtherRegion;
15284 if (SemaRef.getLangOpts().CPlusPlus17) {
15285 CalleeRegion = Tree.allocate(Parent: Region);
15286 OtherRegion = Tree.allocate(Parent: Region);
15287 } else {
15288 CalleeRegion = Region;
15289 OtherRegion = Region;
15290 }
15291 SequenceTree::Seq OldRegion = Region;
15292
15293 // Visit the callee expression first.
15294 Region = CalleeRegion;
15295 if (SemaRef.getLangOpts().CPlusPlus17) {
15296 SequencedSubexpression Sequenced(*this);
15297 Visit(S: CE->getCallee());
15298 } else {
15299 Visit(S: CE->getCallee());
15300 }
15301
15302 // Then visit the argument expressions.
15303 Region = OtherRegion;
15304 for (const Expr *Argument : CE->arguments())
15305 Visit(S: Argument);
15306
15307 Region = OldRegion;
15308 if (SemaRef.getLangOpts().CPlusPlus17) {
15309 Tree.merge(S: CalleeRegion);
15310 Tree.merge(S: OtherRegion);
15311 }
15312 });
15313 }
15314
15315 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15316 // C++17 [over.match.oper]p2:
15317 // [...] the operator notation is first transformed to the equivalent
15318 // function-call notation as summarized in Table 12 (where @ denotes one
15319 // of the operators covered in the specified subclause). However, the
15320 // operands are sequenced in the order prescribed for the built-in
15321 // operator (Clause 8).
15322 //
15323 // From the above only overloaded binary operators and overloaded call
15324 // operators have sequencing rules in C++17 that we need to handle
15325 // separately.
15326 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15327 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15328 return VisitCallExpr(CE: CXXOCE);
15329
15330 enum {
15331 NoSequencing,
15332 LHSBeforeRHS,
15333 RHSBeforeLHS,
15334 LHSBeforeRest
15335 } SequencingKind;
15336 switch (CXXOCE->getOperator()) {
15337 case OO_Equal:
15338 case OO_PlusEqual:
15339 case OO_MinusEqual:
15340 case OO_StarEqual:
15341 case OO_SlashEqual:
15342 case OO_PercentEqual:
15343 case OO_CaretEqual:
15344 case OO_AmpEqual:
15345 case OO_PipeEqual:
15346 case OO_LessLessEqual:
15347 case OO_GreaterGreaterEqual:
15348 SequencingKind = RHSBeforeLHS;
15349 break;
15350
15351 case OO_LessLess:
15352 case OO_GreaterGreater:
15353 case OO_AmpAmp:
15354 case OO_PipePipe:
15355 case OO_Comma:
15356 case OO_ArrowStar:
15357 case OO_Subscript:
15358 SequencingKind = LHSBeforeRHS;
15359 break;
15360
15361 case OO_Call:
15362 SequencingKind = LHSBeforeRest;
15363 break;
15364
15365 default:
15366 SequencingKind = NoSequencing;
15367 break;
15368 }
15369
15370 if (SequencingKind == NoSequencing)
15371 return VisitCallExpr(CE: CXXOCE);
15372
15373 // This is a call, so all subexpressions are sequenced before the result.
15374 SequencedSubexpression Sequenced(*this);
15375
15376 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
15377 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15378 "Should only get there with C++17 and above!");
15379 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15380 "Should only get there with an overloaded binary operator"
15381 " or an overloaded call operator!");
15382
15383 if (SequencingKind == LHSBeforeRest) {
15384 assert(CXXOCE->getOperator() == OO_Call &&
15385 "We should only have an overloaded call operator here!");
15386
15387 // This is very similar to VisitCallExpr, except that we only have the
15388 // C++17 case. The postfix-expression is the first argument of the
15389 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15390 // are in the following arguments.
15391 //
15392 // Note that we intentionally do not visit the callee expression since
15393 // it is just a decayed reference to a function.
15394 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
15395 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
15396 SequenceTree::Seq OldRegion = Region;
15397
15398 assert(CXXOCE->getNumArgs() >= 1 &&
15399 "An overloaded call operator must have at least one argument"
15400 " for the postfix-expression!");
15401 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15402 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15403 CXXOCE->getNumArgs() - 1);
15404
15405 // Visit the postfix-expression first.
15406 {
15407 Region = PostfixExprRegion;
15408 SequencedSubexpression Sequenced(*this);
15409 Visit(S: PostfixExpr);
15410 }
15411
15412 // Then visit the argument expressions.
15413 Region = ArgsRegion;
15414 for (const Expr *Arg : Args)
15415 Visit(S: Arg);
15416
15417 Region = OldRegion;
15418 Tree.merge(S: PostfixExprRegion);
15419 Tree.merge(S: ArgsRegion);
15420 } else {
15421 assert(CXXOCE->getNumArgs() == 2 &&
15422 "Should only have two arguments here!");
15423 assert((SequencingKind == LHSBeforeRHS ||
15424 SequencingKind == RHSBeforeLHS) &&
15425 "Unexpected sequencing kind!");
15426
15427 // We do not visit the callee expression since it is just a decayed
15428 // reference to a function.
15429 const Expr *E1 = CXXOCE->getArg(Arg: 0);
15430 const Expr *E2 = CXXOCE->getArg(Arg: 1);
15431 if (SequencingKind == RHSBeforeLHS)
15432 std::swap(a&: E1, b&: E2);
15433
15434 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
15435 }
15436 });
15437 }
15438
15439 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15440 // This is a call, so all subexpressions are sequenced before the result.
15441 SequencedSubexpression Sequenced(*this);
15442
15443 if (!CCE->isListInitialization())
15444 return VisitExpr(E: CCE);
15445
15446 // In C++11, list initializations are sequenced.
15447 SequenceExpressionsInOrder(
15448 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15449 }
15450
15451 void VisitInitListExpr(const InitListExpr *ILE) {
15452 if (!SemaRef.getLangOpts().CPlusPlus11)
15453 return VisitExpr(E: ILE);
15454
15455 // In C++11, list initializations are sequenced.
15456 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
15457 }
15458
15459 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15460 // C++20 parenthesized list initializations are sequenced. See C++20
15461 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15462 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
15463 }
15464
15465private:
15466 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15467 SmallVector<SequenceTree::Seq, 32> Elts;
15468 SequenceTree::Seq Parent = Region;
15469 for (const Expr *E : ExpressionList) {
15470 if (!E)
15471 continue;
15472 Region = Tree.allocate(Parent);
15473 Elts.push_back(Elt: Region);
15474 Visit(S: E);
15475 }
15476
15477 // Forget that the initializers are sequenced.
15478 Region = Parent;
15479 for (unsigned I = 0; I < Elts.size(); ++I)
15480 Tree.merge(S: Elts[I]);
15481 }
15482};
15483
15484SequenceChecker::UsageInfo::UsageInfo() = default;
15485
15486} // namespace
15487
15488void Sema::CheckUnsequencedOperations(const Expr *E) {
15489 SmallVector<const Expr *, 8> WorkList;
15490 WorkList.push_back(Elt: E);
15491 while (!WorkList.empty()) {
15492 const Expr *Item = WorkList.pop_back_val();
15493 SequenceChecker(*this, Item, WorkList);
15494 }
15495}
15496
15497void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15498 bool IsConstexpr) {
15499 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15500 IsConstexpr || isa<ConstantExpr>(Val: E));
15501 CheckImplicitConversions(E, CC: CheckLoc);
15502 if (!E->isInstantiationDependent())
15503 CheckUnsequencedOperations(E);
15504 if (!IsConstexpr && !E->isValueDependent())
15505 CheckForIntOverflow(E);
15506}
15507
15508void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15509 FieldDecl *BitField,
15510 Expr *Init) {
15511 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15512}
15513
15514static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15515 SourceLocation Loc) {
15516 if (!PType->isVariablyModifiedType())
15517 return;
15518 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15519 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15520 return;
15521 }
15522 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15523 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15524 return;
15525 }
15526 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15527 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15528 return;
15529 }
15530
15531 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15532 if (!AT)
15533 return;
15534
15535 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15536 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15537 return;
15538 }
15539
15540 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15541}
15542
15543bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15544 bool CheckParameterNames) {
15545 bool HasInvalidParm = false;
15546 for (ParmVarDecl *Param : Parameters) {
15547 assert(Param && "null in a parameter list");
15548 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15549 // function declarator that is part of a function definition of
15550 // that function shall not have incomplete type.
15551 //
15552 // C++23 [dcl.fct.def.general]/p2
15553 // The type of a parameter [...] for a function definition
15554 // shall not be a (possibly cv-qualified) class type that is incomplete
15555 // or abstract within the function body unless the function is deleted.
15556 if (!Param->isInvalidDecl() &&
15557 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15558 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15559 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15560 DiagID: diag::err_abstract_type_in_decl,
15561 Args: AbstractParamType))) {
15562 Param->setInvalidDecl();
15563 HasInvalidParm = true;
15564 }
15565
15566 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15567 // declaration of each parameter shall include an identifier.
15568 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15569 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15570 // Diagnose this as an extension in C17 and earlier.
15571 if (!getLangOpts().C23)
15572 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15573 }
15574
15575 // C99 6.7.5.3p12:
15576 // If the function declarator is not part of a definition of that
15577 // function, parameters may have incomplete type and may use the [*]
15578 // notation in their sequences of declarator specifiers to specify
15579 // variable length array types.
15580 QualType PType = Param->getOriginalType();
15581 // FIXME: This diagnostic should point the '[*]' if source-location
15582 // information is added for it.
15583 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15584
15585 // If the parameter is a c++ class type and it has to be destructed in the
15586 // callee function, declare the destructor so that it can be called by the
15587 // callee function. Do not perform any direct access check on the dtor here.
15588 if (!Param->isInvalidDecl()) {
15589 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15590 if (!ClassDecl->isInvalidDecl() &&
15591 !ClassDecl->hasIrrelevantDestructor() &&
15592 !ClassDecl->isDependentContext() &&
15593 ClassDecl->isParamDestroyedInCallee()) {
15594 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15595 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15596 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15597 }
15598 }
15599 }
15600
15601 // Parameters with the pass_object_size attribute only need to be marked
15602 // constant at function definitions. Because we lack information about
15603 // whether we're on a declaration or definition when we're instantiating the
15604 // attribute, we need to check for constness here.
15605 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15606 if (!Param->getType().isConstQualified())
15607 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15608 << Attr->getSpelling() << 1;
15609
15610 // Check for parameter names shadowing fields from the class.
15611 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15612 // The owning context for the parameter should be the function, but we
15613 // want to see if this function's declaration context is a record.
15614 DeclContext *DC = Param->getDeclContext();
15615 if (DC && DC->isFunctionOrMethod()) {
15616 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15617 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15618 RD, /*DeclIsField*/ false);
15619 }
15620 }
15621
15622 if (!Param->isInvalidDecl() &&
15623 Param->getOriginalType()->isWebAssemblyTableType()) {
15624 Param->setInvalidDecl();
15625 HasInvalidParm = true;
15626 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15627 }
15628 }
15629
15630 return HasInvalidParm;
15631}
15632
15633std::optional<std::pair<
15634 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15635 *E,
15636 ASTContext
15637 &Ctx);
15638
15639/// Compute the alignment and offset of the base class object given the
15640/// derived-to-base cast expression and the alignment and offset of the derived
15641/// class object.
15642static std::pair<CharUnits, CharUnits>
15643getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15644 CharUnits BaseAlignment, CharUnits Offset,
15645 ASTContext &Ctx) {
15646 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15647 ++PathI) {
15648 const CXXBaseSpecifier *Base = *PathI;
15649 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15650 if (Base->isVirtual()) {
15651 // The complete object may have a lower alignment than the non-virtual
15652 // alignment of the base, in which case the base may be misaligned. Choose
15653 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15654 // conservative lower bound of the complete object alignment.
15655 CharUnits NonVirtualAlignment =
15656 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15657 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15658 Offset = CharUnits::Zero();
15659 } else {
15660 const ASTRecordLayout &RL =
15661 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15662 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15663 }
15664 DerivedType = Base->getType();
15665 }
15666
15667 return std::make_pair(x&: BaseAlignment, y&: Offset);
15668}
15669
15670/// Compute the alignment and offset of a binary additive operator.
15671static std::optional<std::pair<CharUnits, CharUnits>>
15672getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15673 bool IsSub, ASTContext &Ctx) {
15674 QualType PointeeType = PtrE->getType()->getPointeeType();
15675
15676 if (!PointeeType->isConstantSizeType())
15677 return std::nullopt;
15678
15679 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15680
15681 if (!P)
15682 return std::nullopt;
15683
15684 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15685 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15686 CharUnits Offset = EltSize * IdxRes->getExtValue();
15687 if (IsSub)
15688 Offset = -Offset;
15689 return std::make_pair(x&: P->first, y: P->second + Offset);
15690 }
15691
15692 // If the integer expression isn't a constant expression, compute the lower
15693 // bound of the alignment using the alignment and offset of the pointer
15694 // expression and the element size.
15695 return std::make_pair(
15696 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15697 y: CharUnits::Zero());
15698}
15699
15700/// This helper function takes an lvalue expression and returns the alignment of
15701/// a VarDecl and a constant offset from the VarDecl.
15702std::optional<std::pair<
15703 CharUnits,
15704 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15705 ASTContext &Ctx) {
15706 E = E->IgnoreParens();
15707 switch (E->getStmtClass()) {
15708 default:
15709 break;
15710 case Stmt::CStyleCastExprClass:
15711 case Stmt::CXXStaticCastExprClass:
15712 case Stmt::ImplicitCastExprClass: {
15713 auto *CE = cast<CastExpr>(Val: E);
15714 const Expr *From = CE->getSubExpr();
15715 switch (CE->getCastKind()) {
15716 default:
15717 break;
15718 case CK_NoOp:
15719 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15720 case CK_UncheckedDerivedToBase:
15721 case CK_DerivedToBase: {
15722 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15723 if (!P)
15724 break;
15725 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15726 Offset: P->second, Ctx);
15727 }
15728 }
15729 break;
15730 }
15731 case Stmt::ArraySubscriptExprClass: {
15732 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15733 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15734 IsSub: false, Ctx);
15735 }
15736 case Stmt::DeclRefExprClass: {
15737 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15738 // FIXME: If VD is captured by copy or is an escaping __block variable,
15739 // use the alignment of VD's type.
15740 if (!VD->getType()->isReferenceType()) {
15741 // Dependent alignment cannot be resolved -> bail out.
15742 if (VD->hasDependentAlignment())
15743 break;
15744 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15745 }
15746 if (VD->hasInit())
15747 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15748 }
15749 break;
15750 }
15751 case Stmt::MemberExprClass: {
15752 auto *ME = cast<MemberExpr>(Val: E);
15753 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15754 if (!FD || FD->getType()->isReferenceType() ||
15755 !ASTContext::hasLayout(D: FD->getParent()))
15756 break;
15757 std::optional<std::pair<CharUnits, CharUnits>> P;
15758 if (ME->isArrow())
15759 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15760 else
15761 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15762 if (!P)
15763 break;
15764 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15765 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15766 return std::make_pair(x&: P->first,
15767 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15768 }
15769 case Stmt::UnaryOperatorClass: {
15770 auto *UO = cast<UnaryOperator>(Val: E);
15771 switch (UO->getOpcode()) {
15772 default:
15773 break;
15774 case UO_Deref:
15775 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15776 }
15777 break;
15778 }
15779 case Stmt::BinaryOperatorClass: {
15780 auto *BO = cast<BinaryOperator>(Val: E);
15781 auto Opcode = BO->getOpcode();
15782 switch (Opcode) {
15783 default:
15784 break;
15785 case BO_Comma:
15786 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15787 }
15788 break;
15789 }
15790 }
15791 return std::nullopt;
15792}
15793
15794/// This helper function takes a pointer expression and returns the alignment of
15795/// a VarDecl and a constant offset from the VarDecl.
15796std::optional<std::pair<
15797 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15798 *E,
15799 ASTContext
15800 &Ctx) {
15801 E = E->IgnoreParens();
15802 switch (E->getStmtClass()) {
15803 default:
15804 break;
15805 case Stmt::CStyleCastExprClass:
15806 case Stmt::CXXStaticCastExprClass:
15807 case Stmt::ImplicitCastExprClass: {
15808 auto *CE = cast<CastExpr>(Val: E);
15809 const Expr *From = CE->getSubExpr();
15810 switch (CE->getCastKind()) {
15811 default:
15812 break;
15813 case CK_NoOp:
15814 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15815 case CK_ArrayToPointerDecay:
15816 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15817 case CK_UncheckedDerivedToBase:
15818 case CK_DerivedToBase: {
15819 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15820 if (!P)
15821 break;
15822 return getDerivedToBaseAlignmentAndOffset(
15823 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15824 }
15825 }
15826 break;
15827 }
15828 case Stmt::CXXThisExprClass: {
15829 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15830 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15831 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15832 }
15833 case Stmt::UnaryOperatorClass: {
15834 auto *UO = cast<UnaryOperator>(Val: E);
15835 if (UO->getOpcode() == UO_AddrOf)
15836 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15837 break;
15838 }
15839 case Stmt::BinaryOperatorClass: {
15840 auto *BO = cast<BinaryOperator>(Val: E);
15841 auto Opcode = BO->getOpcode();
15842 switch (Opcode) {
15843 default:
15844 break;
15845 case BO_Add:
15846 case BO_Sub: {
15847 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15848 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15849 std::swap(a&: LHS, b&: RHS);
15850 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15851 Ctx);
15852 }
15853 case BO_Comma:
15854 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15855 }
15856 break;
15857 }
15858 }
15859 return std::nullopt;
15860}
15861
15862static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15863 // See if we can compute the alignment of a VarDecl and an offset from it.
15864 std::optional<std::pair<CharUnits, CharUnits>> P =
15865 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15866
15867 if (P)
15868 return P->first.alignmentAtOffset(offset: P->second);
15869
15870 // If that failed, return the type's alignment.
15871 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15872}
15873
15874void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15875 // This is actually a lot of work to potentially be doing on every
15876 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15877 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
15878 return;
15879
15880 // Ignore dependent types.
15881 if (T->isDependentType() || Op->getType()->isDependentType())
15882 return;
15883
15884 // Require that the destination be a pointer type.
15885 const PointerType *DestPtr = T->getAs<PointerType>();
15886 if (!DestPtr) return;
15887
15888 // If the destination has alignment 1, we're done.
15889 QualType DestPointee = DestPtr->getPointeeType();
15890 if (DestPointee->isIncompleteType()) return;
15891 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
15892 if (DestAlign.isOne()) return;
15893
15894 // Require that the source be a pointer type.
15895 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15896 if (!SrcPtr) return;
15897 QualType SrcPointee = SrcPtr->getPointeeType();
15898
15899 // Explicitly allow casts from cv void*. We already implicitly
15900 // allowed casts to cv void*, since they have alignment 1.
15901 // Also allow casts involving incomplete types, which implicitly
15902 // includes 'void'.
15903 if (SrcPointee->isIncompleteType()) return;
15904
15905 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
15906
15907 if (SrcAlign >= DestAlign) return;
15908
15909 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
15910 << Op->getType() << T
15911 << static_cast<unsigned>(SrcAlign.getQuantity())
15912 << static_cast<unsigned>(DestAlign.getQuantity())
15913 << TRange << Op->getSourceRange();
15914}
15915
15916void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15917 const ArraySubscriptExpr *ASE,
15918 bool AllowOnePastEnd, bool IndexNegated) {
15919 // Already diagnosed by the constant evaluator.
15920 if (isConstantEvaluatedContext())
15921 return;
15922
15923 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15924 if (IndexExpr->isValueDependent())
15925 return;
15926
15927 const Type *EffectiveType =
15928 BaseExpr->getType()->getPointeeOrArrayElementType();
15929 BaseExpr = BaseExpr->IgnoreParenCasts();
15930 const ConstantArrayType *ArrayTy =
15931 Context.getAsConstantArrayType(T: BaseExpr->getType());
15932
15933 LangOptions::StrictFlexArraysLevelKind
15934 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15935
15936 const Type *BaseType =
15937 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15938 bool IsUnboundedArray =
15939 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15940 Context, StrictFlexArraysLevel,
15941 /*IgnoreTemplateOrMacroSubstitution=*/true);
15942 if (EffectiveType->isDependentType() ||
15943 (!IsUnboundedArray && BaseType->isDependentType()))
15944 return;
15945
15946 Expr::EvalResult Result;
15947 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
15948 return;
15949
15950 llvm::APSInt index = Result.Val.getInt();
15951 if (IndexNegated) {
15952 index.setIsUnsigned(false);
15953 index = -index;
15954 }
15955
15956 if (IsUnboundedArray) {
15957 if (EffectiveType->isFunctionType())
15958 return;
15959 if (index.isUnsigned() || !index.isNegative()) {
15960 const auto &ASTC = getASTContext();
15961 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15962 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15963 if (index.getBitWidth() < AddrBits)
15964 index = index.zext(width: AddrBits);
15965 std::optional<CharUnits> ElemCharUnits =
15966 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
15967 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15968 // pointer) bounds-checking isn't meaningful.
15969 if (!ElemCharUnits || ElemCharUnits->isZero())
15970 return;
15971 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15972 // If index has more active bits than address space, we already know
15973 // we have a bounds violation to warn about. Otherwise, compute
15974 // address of (index + 1)th element, and warn about bounds violation
15975 // only if that address exceeds address space.
15976 if (index.getActiveBits() <= AddrBits) {
15977 bool Overflow;
15978 llvm::APInt Product(index);
15979 Product += 1;
15980 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
15981 if (!Overflow && Product.getActiveBits() <= AddrBits)
15982 return;
15983 }
15984
15985 // Need to compute max possible elements in address space, since that
15986 // is included in diag message.
15987 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
15988 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
15989 MaxElems += 1;
15990 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
15991 MaxElems = MaxElems.udiv(RHS: ElemBytes);
15992
15993 unsigned DiagID =
15994 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15995 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15996
15997 // Diag message shows element size in bits and in "bytes" (platform-
15998 // dependent CharUnits)
15999 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16000 PD: PDiag(DiagID) << index << AddrBits
16001 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
16002 << ElemBytes << MaxElems
16003 << MaxElems.getZExtValue()
16004 << IndexExpr->getSourceRange());
16005
16006 const NamedDecl *ND = nullptr;
16007 // Try harder to find a NamedDecl to point at in the note.
16008 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16009 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16010 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16011 ND = DRE->getDecl();
16012 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16013 ND = ME->getMemberDecl();
16014
16015 if (ND)
16016 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16017 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16018 }
16019 return;
16020 }
16021
16022 if (index.isUnsigned() || !index.isNegative()) {
16023 // It is possible that the type of the base expression after
16024 // IgnoreParenCasts is incomplete, even though the type of the base
16025 // expression before IgnoreParenCasts is complete (see PR39746 for an
16026 // example). In this case we have no information about whether the array
16027 // access exceeds the array bounds. However we can still diagnose an array
16028 // access which precedes the array bounds.
16029 if (BaseType->isIncompleteType())
16030 return;
16031
16032 llvm::APInt size = ArrayTy->getSize();
16033
16034 if (BaseType != EffectiveType) {
16035 // Make sure we're comparing apples to apples when comparing index to
16036 // size.
16037 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
16038 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
16039
16040 // Handle ptrarith_typesize being zero, such as when casting to void*.
16041 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16042 if (!ptrarith_typesize)
16043 ptrarith_typesize = Context.getCharWidth();
16044
16045 if (ptrarith_typesize != array_typesize) {
16046 // There's a cast to a different size type involved.
16047 uint64_t ratio = array_typesize / ptrarith_typesize;
16048
16049 // TODO: Be smarter about handling cases where array_typesize is not a
16050 // multiple of ptrarith_typesize.
16051 if (ptrarith_typesize * ratio == array_typesize)
16052 size *= llvm::APInt(size.getBitWidth(), ratio);
16053 }
16054 }
16055
16056 if (size.getBitWidth() > index.getBitWidth())
16057 index = index.zext(width: size.getBitWidth());
16058 else if (size.getBitWidth() < index.getBitWidth())
16059 size = size.zext(width: index.getBitWidth());
16060
16061 // For array subscripting the index must be less than size, but for pointer
16062 // arithmetic also allow the index (offset) to be equal to size since
16063 // computing the next address after the end of the array is legal and
16064 // commonly done e.g. in C++ iterators and range-based for loops.
16065 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
16066 return;
16067
16068 // Suppress the warning if the subscript expression (as identified by the
16069 // ']' location) and the index expression are both from macro expansions
16070 // within a system header.
16071 if (ASE) {
16072 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16073 Loc: ASE->getRBracketLoc());
16074 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
16075 SourceLocation IndexLoc =
16076 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
16077 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
16078 return;
16079 }
16080 }
16081
16082 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16083 : diag::warn_ptr_arith_exceeds_bounds;
16084 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16085 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16086
16087 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16088 PD: PDiag(DiagID)
16089 << index << ArrayTy->desugar() << CastMsg
16090 << CastMsgTy << IndexExpr->getSourceRange());
16091 } else {
16092 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16093 if (!ASE) {
16094 DiagID = diag::warn_ptr_arith_precedes_bounds;
16095 if (index.isNegative()) index = -index;
16096 }
16097
16098 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16099 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
16100 }
16101
16102 const NamedDecl *ND = nullptr;
16103 // Try harder to find a NamedDecl to point at in the note.
16104 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16105 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16106 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16107 ND = DRE->getDecl();
16108 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16109 ND = ME->getMemberDecl();
16110
16111 if (ND)
16112 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16113 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16114}
16115
16116void Sema::CheckArrayAccess(const Expr *expr) {
16117 int AllowOnePastEnd = 0;
16118 while (expr) {
16119 expr = expr->IgnoreParenImpCasts();
16120 switch (expr->getStmtClass()) {
16121 case Stmt::ArraySubscriptExprClass: {
16122 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
16123 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
16124 AllowOnePastEnd: AllowOnePastEnd > 0);
16125 expr = ASE->getBase();
16126 break;
16127 }
16128 case Stmt::MemberExprClass: {
16129 expr = cast<MemberExpr>(Val: expr)->getBase();
16130 break;
16131 }
16132 case Stmt::CXXMemberCallExprClass: {
16133 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
16134 break;
16135 }
16136 case Stmt::ArraySectionExprClass: {
16137 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
16138 // FIXME: We should probably be checking all of the elements to the
16139 // 'length' here as well.
16140 if (ASE->getLowerBound())
16141 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
16142 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
16143 return;
16144 }
16145 case Stmt::UnaryOperatorClass: {
16146 // Only unwrap the * and & unary operators
16147 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
16148 expr = UO->getSubExpr();
16149 switch (UO->getOpcode()) {
16150 case UO_AddrOf:
16151 AllowOnePastEnd++;
16152 break;
16153 case UO_Deref:
16154 AllowOnePastEnd--;
16155 break;
16156 default:
16157 return;
16158 }
16159 break;
16160 }
16161 case Stmt::ConditionalOperatorClass: {
16162 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
16163 if (const Expr *lhs = cond->getLHS())
16164 CheckArrayAccess(expr: lhs);
16165 if (const Expr *rhs = cond->getRHS())
16166 CheckArrayAccess(expr: rhs);
16167 return;
16168 }
16169 case Stmt::CXXOperatorCallExprClass: {
16170 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
16171 for (const auto *Arg : OCE->arguments())
16172 CheckArrayAccess(expr: Arg);
16173 return;
16174 }
16175 default:
16176 return;
16177 }
16178 }
16179}
16180
16181static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16182 Expr *RHS, bool isProperty) {
16183 // Check if RHS is an Objective-C object literal, which also can get
16184 // immediately zapped in a weak reference. Note that we explicitly
16185 // allow ObjCStringLiterals, since those are designed to never really die.
16186 RHS = RHS->IgnoreParenImpCasts();
16187
16188 // This enum needs to match with the 'select' in
16189 // warn_objc_arc_literal_assign (off-by-1).
16190 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
16191 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16192 return false;
16193
16194 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
16195 << (unsigned) Kind
16196 << (isProperty ? 0 : 1)
16197 << RHS->getSourceRange();
16198
16199 return true;
16200}
16201
16202static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16203 Qualifiers::ObjCLifetime LT,
16204 Expr *RHS, bool isProperty) {
16205 // Strip off any implicit cast added to get to the one ARC-specific.
16206 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16207 if (cast->getCastKind() == CK_ARCConsumeObject) {
16208 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
16209 << (LT == Qualifiers::OCL_ExplicitNone)
16210 << (isProperty ? 0 : 1)
16211 << RHS->getSourceRange();
16212 return true;
16213 }
16214 RHS = cast->getSubExpr();
16215 }
16216
16217 if (LT == Qualifiers::OCL_Weak &&
16218 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16219 return true;
16220
16221 return false;
16222}
16223
16224bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16225 QualType LHS, Expr *RHS) {
16226 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16227
16228 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16229 return false;
16230
16231 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
16232 return true;
16233
16234 return false;
16235}
16236
16237void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16238 Expr *LHS, Expr *RHS) {
16239 QualType LHSType;
16240 // PropertyRef on LHS type need be directly obtained from
16241 // its declaration as it has a PseudoType.
16242 ObjCPropertyRefExpr *PRE
16243 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
16244 if (PRE && !PRE->isImplicitProperty()) {
16245 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16246 if (PD)
16247 LHSType = PD->getType();
16248 }
16249
16250 if (LHSType.isNull())
16251 LHSType = LHS->getType();
16252
16253 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16254
16255 if (LT == Qualifiers::OCL_Weak) {
16256 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
16257 getCurFunction()->markSafeWeakUse(E: LHS);
16258 }
16259
16260 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
16261 return;
16262
16263 // FIXME. Check for other life times.
16264 if (LT != Qualifiers::OCL_None)
16265 return;
16266
16267 if (PRE) {
16268 if (PRE->isImplicitProperty())
16269 return;
16270 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16271 if (!PD)
16272 return;
16273
16274 unsigned Attributes = PD->getPropertyAttributes();
16275 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16276 // when 'assign' attribute was not explicitly specified
16277 // by user, ignore it and rely on property type itself
16278 // for lifetime info.
16279 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16280 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16281 LHSType->isObjCRetainableType())
16282 return;
16283
16284 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16285 if (cast->getCastKind() == CK_ARCConsumeObject) {
16286 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
16287 << RHS->getSourceRange();
16288 return;
16289 }
16290 RHS = cast->getSubExpr();
16291 }
16292 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16293 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
16294 return;
16295 }
16296 }
16297}
16298
16299//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16300
16301static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16302 SourceLocation StmtLoc,
16303 const NullStmt *Body) {
16304 // Do not warn if the body is a macro that expands to nothing, e.g:
16305 //
16306 // #define CALL(x)
16307 // if (condition)
16308 // CALL(0);
16309 if (Body->hasLeadingEmptyMacro())
16310 return false;
16311
16312 // Get line numbers of statement and body.
16313 bool StmtLineInvalid;
16314 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
16315 Invalid: &StmtLineInvalid);
16316 if (StmtLineInvalid)
16317 return false;
16318
16319 bool BodyLineInvalid;
16320 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
16321 Invalid: &BodyLineInvalid);
16322 if (BodyLineInvalid)
16323 return false;
16324
16325 // Warn if null statement and body are on the same line.
16326 if (StmtLine != BodyLine)
16327 return false;
16328
16329 return true;
16330}
16331
16332void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16333 const Stmt *Body,
16334 unsigned DiagID) {
16335 // Since this is a syntactic check, don't emit diagnostic for template
16336 // instantiations, this just adds noise.
16337 if (CurrentInstantiationScope)
16338 return;
16339
16340 // The body should be a null statement.
16341 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16342 if (!NBody)
16343 return;
16344
16345 // Do the usual checks.
16346 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16347 return;
16348
16349 Diag(Loc: NBody->getSemiLoc(), DiagID);
16350 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16351}
16352
16353void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16354 const Stmt *PossibleBody) {
16355 assert(!CurrentInstantiationScope); // Ensured by caller
16356
16357 SourceLocation StmtLoc;
16358 const Stmt *Body;
16359 unsigned DiagID;
16360 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
16361 StmtLoc = FS->getRParenLoc();
16362 Body = FS->getBody();
16363 DiagID = diag::warn_empty_for_body;
16364 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
16365 StmtLoc = WS->getRParenLoc();
16366 Body = WS->getBody();
16367 DiagID = diag::warn_empty_while_body;
16368 } else
16369 return; // Neither `for' nor `while'.
16370
16371 // The body should be a null statement.
16372 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16373 if (!NBody)
16374 return;
16375
16376 // Skip expensive checks if diagnostic is disabled.
16377 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
16378 return;
16379
16380 // Do the usual checks.
16381 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16382 return;
16383
16384 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16385 // noise level low, emit diagnostics only if for/while is followed by a
16386 // CompoundStmt, e.g.:
16387 // for (int i = 0; i < n; i++);
16388 // {
16389 // a(i);
16390 // }
16391 // or if for/while is followed by a statement with more indentation
16392 // than for/while itself:
16393 // for (int i = 0; i < n; i++);
16394 // a(i);
16395 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
16396 if (!ProbableTypo) {
16397 bool BodyColInvalid;
16398 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16399 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
16400 if (BodyColInvalid)
16401 return;
16402
16403 bool StmtColInvalid;
16404 unsigned StmtCol =
16405 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
16406 if (StmtColInvalid)
16407 return;
16408
16409 if (BodyCol > StmtCol)
16410 ProbableTypo = true;
16411 }
16412
16413 if (ProbableTypo) {
16414 Diag(Loc: NBody->getSemiLoc(), DiagID);
16415 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16416 }
16417}
16418
16419//===--- CHECK: Warn on self move with std::move. -------------------------===//
16420
16421void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16422 SourceLocation OpLoc) {
16423 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
16424 return;
16425
16426 if (inTemplateInstantiation())
16427 return;
16428
16429 // Strip parens and casts away.
16430 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16431 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16432
16433 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16434 // which we can treat as an inlined std::move
16435 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
16436 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16437 RHSExpr = CE->getArg(Arg: 0);
16438 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
16439 CXXSCE && CXXSCE->isXValue())
16440 RHSExpr = CXXSCE->getSubExpr();
16441 else
16442 return;
16443
16444 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
16445 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
16446
16447 // Two DeclRefExpr's, check that the decls are the same.
16448 if (LHSDeclRef && RHSDeclRef) {
16449 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16450 return;
16451 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16452 RHSDeclRef->getDecl()->getCanonicalDecl())
16453 return;
16454
16455 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16456 << LHSExpr->getType() << LHSExpr->getSourceRange()
16457 << RHSExpr->getSourceRange();
16458 if (const FieldDecl *F =
16459 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
16460 D << 1 << F
16461 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
16462 else
16463 D << 0;
16464 return;
16465 }
16466
16467 // Member variables require a different approach to check for self moves.
16468 // MemberExpr's are the same if every nested MemberExpr refers to the same
16469 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16470 // the base Expr's are CXXThisExpr's.
16471 const Expr *LHSBase = LHSExpr;
16472 const Expr *RHSBase = RHSExpr;
16473 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
16474 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
16475 if (!LHSME || !RHSME)
16476 return;
16477
16478 while (LHSME && RHSME) {
16479 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16480 RHSME->getMemberDecl()->getCanonicalDecl())
16481 return;
16482
16483 LHSBase = LHSME->getBase();
16484 RHSBase = RHSME->getBase();
16485 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16486 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16487 }
16488
16489 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16490 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16491 if (LHSDeclRef && RHSDeclRef) {
16492 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16493 return;
16494 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16495 RHSDeclRef->getDecl()->getCanonicalDecl())
16496 return;
16497
16498 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16499 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16500 << RHSExpr->getSourceRange();
16501 return;
16502 }
16503
16504 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16505 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16506 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16507 << RHSExpr->getSourceRange();
16508}
16509
16510//===--- Layout compatibility ----------------------------------------------//
16511
16512static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16513
16514/// Check if two enumeration types are layout-compatible.
16515static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16516 const EnumDecl *ED2) {
16517 // C++11 [dcl.enum] p8:
16518 // Two enumeration types are layout-compatible if they have the same
16519 // underlying type.
16520 return ED1->isComplete() && ED2->isComplete() &&
16521 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16522}
16523
16524/// Check if two fields are layout-compatible.
16525/// Can be used on union members, which are exempt from alignment requirement
16526/// of common initial sequence.
16527static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16528 const FieldDecl *Field2,
16529 bool AreUnionMembers = false) {
16530#ifndef NDEBUG
16531 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16532 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16533 assert(((Field1Parent->isStructureOrClassType() &&
16534 Field2Parent->isStructureOrClassType()) ||
16535 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16536 "Can't evaluate layout compatibility between a struct field and a "
16537 "union field.");
16538 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16539 (AreUnionMembers && Field1Parent->isUnionType())) &&
16540 "AreUnionMembers should be 'true' for union fields (only).");
16541#endif
16542
16543 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16544 return false;
16545
16546 if (Field1->isBitField() != Field2->isBitField())
16547 return false;
16548
16549 if (Field1->isBitField()) {
16550 // Make sure that the bit-fields are the same length.
16551 unsigned Bits1 = Field1->getBitWidthValue();
16552 unsigned Bits2 = Field2->getBitWidthValue();
16553
16554 if (Bits1 != Bits2)
16555 return false;
16556 }
16557
16558 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16559 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16560 return false;
16561
16562 if (!AreUnionMembers &&
16563 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16564 return false;
16565
16566 return true;
16567}
16568
16569/// Check if two standard-layout structs are layout-compatible.
16570/// (C++11 [class.mem] p17)
16571static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16572 const RecordDecl *RD2) {
16573 // Get to the class where the fields are declared
16574 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16575 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16576
16577 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16578 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16579
16580 // Check the fields.
16581 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16582 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16583 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16584 });
16585}
16586
16587/// Check if two standard-layout unions are layout-compatible.
16588/// (C++11 [class.mem] p18)
16589static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16590 const RecordDecl *RD2) {
16591 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16592 RD2->fields());
16593
16594 for (auto *Field1 : RD1->fields()) {
16595 auto It = llvm::find_if(Range&: UnmatchedFields, P: [&](const FieldDecl *Field2) {
16596 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/AreUnionMembers: true);
16597 });
16598 if (It == UnmatchedFields.end())
16599 return false;
16600 [[maybe_unused]] bool Result = UnmatchedFields.erase(Ptr: *It);
16601 assert(Result);
16602 }
16603
16604 return UnmatchedFields.empty();
16605}
16606
16607static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16608 const RecordDecl *RD2) {
16609 if (RD1->isUnion() != RD2->isUnion())
16610 return false;
16611
16612 if (RD1->isUnion())
16613 return isLayoutCompatibleUnion(C, RD1, RD2);
16614 else
16615 return isLayoutCompatibleStruct(C, RD1, RD2);
16616}
16617
16618/// Check if two types are layout-compatible in C++11 sense.
16619static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16620 if (T1.isNull() || T2.isNull())
16621 return false;
16622
16623 // C++20 [basic.types] p11:
16624 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16625 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16626 // or layout-compatible standard-layout class types (11.4).
16627 T1 = T1.getCanonicalType().getUnqualifiedType();
16628 T2 = T2.getCanonicalType().getUnqualifiedType();
16629
16630 if (C.hasSameType(T1, T2))
16631 return true;
16632
16633 const Type::TypeClass TC1 = T1->getTypeClass();
16634 const Type::TypeClass TC2 = T2->getTypeClass();
16635
16636 if (TC1 != TC2)
16637 return false;
16638
16639 if (TC1 == Type::Enum)
16640 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16641 if (TC1 == Type::Record) {
16642 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16643 return false;
16644
16645 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16646 RD2: T2->castAsRecordDecl());
16647 }
16648
16649 return false;
16650}
16651
16652bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16653 return isLayoutCompatible(C: getASTContext(), T1, T2);
16654}
16655
16656//===-------------- Pointer interconvertibility ----------------------------//
16657
16658bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16659 const TypeSourceInfo *Derived) {
16660 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16661 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16662
16663 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16664 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16665 return true;
16666
16667 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16668 return false;
16669
16670 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16671 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16672 return true;
16673
16674 return false;
16675}
16676
16677//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16678
16679/// Given a type tag expression find the type tag itself.
16680///
16681/// \param TypeExpr Type tag expression, as it appears in user's code.
16682///
16683/// \param VD Declaration of an identifier that appears in a type tag.
16684///
16685/// \param MagicValue Type tag magic value.
16686///
16687/// \param isConstantEvaluated whether the evalaution should be performed in
16688
16689/// constant context.
16690static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16691 const ValueDecl **VD, uint64_t *MagicValue,
16692 bool isConstantEvaluated) {
16693 while(true) {
16694 if (!TypeExpr)
16695 return false;
16696
16697 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16698
16699 switch (TypeExpr->getStmtClass()) {
16700 case Stmt::UnaryOperatorClass: {
16701 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16702 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16703 TypeExpr = UO->getSubExpr();
16704 continue;
16705 }
16706 return false;
16707 }
16708
16709 case Stmt::DeclRefExprClass: {
16710 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16711 *VD = DRE->getDecl();
16712 return true;
16713 }
16714
16715 case Stmt::IntegerLiteralClass: {
16716 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16717 llvm::APInt MagicValueAPInt = IL->getValue();
16718 if (MagicValueAPInt.getActiveBits() <= 64) {
16719 *MagicValue = MagicValueAPInt.getZExtValue();
16720 return true;
16721 } else
16722 return false;
16723 }
16724
16725 case Stmt::BinaryConditionalOperatorClass:
16726 case Stmt::ConditionalOperatorClass: {
16727 const AbstractConditionalOperator *ACO =
16728 cast<AbstractConditionalOperator>(Val: TypeExpr);
16729 bool Result;
16730 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16731 InConstantContext: isConstantEvaluated)) {
16732 if (Result)
16733 TypeExpr = ACO->getTrueExpr();
16734 else
16735 TypeExpr = ACO->getFalseExpr();
16736 continue;
16737 }
16738 return false;
16739 }
16740
16741 case Stmt::BinaryOperatorClass: {
16742 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16743 if (BO->getOpcode() == BO_Comma) {
16744 TypeExpr = BO->getRHS();
16745 continue;
16746 }
16747 return false;
16748 }
16749
16750 default:
16751 return false;
16752 }
16753 }
16754}
16755
16756/// Retrieve the C type corresponding to type tag TypeExpr.
16757///
16758/// \param TypeExpr Expression that specifies a type tag.
16759///
16760/// \param MagicValues Registered magic values.
16761///
16762/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16763/// kind.
16764///
16765/// \param TypeInfo Information about the corresponding C type.
16766///
16767/// \param isConstantEvaluated whether the evalaution should be performed in
16768/// constant context.
16769///
16770/// \returns true if the corresponding C type was found.
16771static bool GetMatchingCType(
16772 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16773 const ASTContext &Ctx,
16774 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16775 *MagicValues,
16776 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16777 bool isConstantEvaluated) {
16778 FoundWrongKind = false;
16779
16780 // Variable declaration that has type_tag_for_datatype attribute.
16781 const ValueDecl *VD = nullptr;
16782
16783 uint64_t MagicValue;
16784
16785 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16786 return false;
16787
16788 if (VD) {
16789 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16790 if (I->getArgumentKind() != ArgumentKind) {
16791 FoundWrongKind = true;
16792 return false;
16793 }
16794 TypeInfo.Type = I->getMatchingCType();
16795 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16796 TypeInfo.MustBeNull = I->getMustBeNull();
16797 return true;
16798 }
16799 return false;
16800 }
16801
16802 if (!MagicValues)
16803 return false;
16804
16805 llvm::DenseMap<Sema::TypeTagMagicValue,
16806 Sema::TypeTagData>::const_iterator I =
16807 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16808 if (I == MagicValues->end())
16809 return false;
16810
16811 TypeInfo = I->second;
16812 return true;
16813}
16814
16815void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16816 uint64_t MagicValue, QualType Type,
16817 bool LayoutCompatible,
16818 bool MustBeNull) {
16819 if (!TypeTagForDatatypeMagicValues)
16820 TypeTagForDatatypeMagicValues.reset(
16821 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16822
16823 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16824 (*TypeTagForDatatypeMagicValues)[Magic] =
16825 TypeTagData(Type, LayoutCompatible, MustBeNull);
16826}
16827
16828static bool IsSameCharType(QualType T1, QualType T2) {
16829 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16830 if (!BT1)
16831 return false;
16832
16833 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16834 if (!BT2)
16835 return false;
16836
16837 BuiltinType::Kind T1Kind = BT1->getKind();
16838 BuiltinType::Kind T2Kind = BT2->getKind();
16839
16840 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16841 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16842 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16843 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16844}
16845
16846void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16847 const ArrayRef<const Expr *> ExprArgs,
16848 SourceLocation CallSiteLoc) {
16849 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16850 bool IsPointerAttr = Attr->getIsPointer();
16851
16852 // Retrieve the argument representing the 'type_tag'.
16853 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16854 if (TypeTagIdxAST >= ExprArgs.size()) {
16855 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16856 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16857 return;
16858 }
16859 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16860 bool FoundWrongKind;
16861 TypeTagData TypeInfo;
16862 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16863 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16864 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16865 if (FoundWrongKind)
16866 Diag(Loc: TypeTagExpr->getExprLoc(),
16867 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16868 << TypeTagExpr->getSourceRange();
16869 return;
16870 }
16871
16872 // Retrieve the argument representing the 'arg_idx'.
16873 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16874 if (ArgumentIdxAST >= ExprArgs.size()) {
16875 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16876 << 1 << Attr->getArgumentIdx().getSourceIndex();
16877 return;
16878 }
16879 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16880 if (IsPointerAttr) {
16881 // Skip implicit cast of pointer to `void *' (as a function argument).
16882 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
16883 if (ICE->getType()->isVoidPointerType() &&
16884 ICE->getCastKind() == CK_BitCast)
16885 ArgumentExpr = ICE->getSubExpr();
16886 }
16887 QualType ArgumentType = ArgumentExpr->getType();
16888
16889 // Passing a `void*' pointer shouldn't trigger a warning.
16890 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16891 return;
16892
16893 if (TypeInfo.MustBeNull) {
16894 // Type tag with matching void type requires a null pointer.
16895 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
16896 NPC: Expr::NPC_ValueDependentIsNotNull)) {
16897 Diag(Loc: ArgumentExpr->getExprLoc(),
16898 DiagID: diag::warn_type_safety_null_pointer_required)
16899 << ArgumentKind->getName()
16900 << ArgumentExpr->getSourceRange()
16901 << TypeTagExpr->getSourceRange();
16902 }
16903 return;
16904 }
16905
16906 QualType RequiredType = TypeInfo.Type;
16907 if (IsPointerAttr)
16908 RequiredType = Context.getPointerType(T: RequiredType);
16909
16910 bool mismatch = false;
16911 if (!TypeInfo.LayoutCompatible) {
16912 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
16913
16914 // C++11 [basic.fundamental] p1:
16915 // Plain char, signed char, and unsigned char are three distinct types.
16916 //
16917 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16918 // char' depending on the current char signedness mode.
16919 if (mismatch)
16920 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
16921 T2: RequiredType->getPointeeType())) ||
16922 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
16923 mismatch = false;
16924 } else
16925 if (IsPointerAttr)
16926 mismatch = !isLayoutCompatible(C: Context,
16927 T1: ArgumentType->getPointeeType(),
16928 T2: RequiredType->getPointeeType());
16929 else
16930 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
16931
16932 if (mismatch)
16933 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
16934 << ArgumentType << ArgumentKind
16935 << TypeInfo.LayoutCompatible << RequiredType
16936 << ArgumentExpr->getSourceRange()
16937 << TypeTagExpr->getSourceRange();
16938}
16939
16940void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16941 CharUnits Alignment) {
16942 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
16943 Args&: Alignment);
16944}
16945
16946void Sema::DiagnoseMisalignedMembers() {
16947 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16948 const NamedDecl *ND = m.RD;
16949 if (ND->getName().empty()) {
16950 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16951 ND = TD;
16952 }
16953 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
16954 << m.MD << ND << m.E->getSourceRange();
16955 }
16956 currentEvaluationContext().MisalignedMembers.clear();
16957}
16958
16959void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16960 E = E->IgnoreParens();
16961 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16962 return;
16963 if (isa<UnaryOperator>(Val: E) &&
16964 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
16965 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
16966 if (isa<MemberExpr>(Val: Op)) {
16967 auto &MisalignedMembersForExpr =
16968 currentEvaluationContext().MisalignedMembers;
16969 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
16970 if (MA != MisalignedMembersForExpr.end() &&
16971 (T->isDependentType() || T->isIntegerType() ||
16972 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16973 Context.getTypeAlignInChars(
16974 T: T->getPointeeType()) <= MA->Alignment))))
16975 MisalignedMembersForExpr.erase(CI: MA);
16976 }
16977 }
16978}
16979
16980void Sema::RefersToMemberWithReducedAlignment(
16981 Expr *E,
16982 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16983 Action) {
16984 const auto *ME = dyn_cast<MemberExpr>(Val: E);
16985 if (!ME)
16986 return;
16987
16988 // No need to check expressions with an __unaligned-qualified type.
16989 if (E->getType().getQualifiers().hasUnaligned())
16990 return;
16991
16992 // For a chain of MemberExpr like "a.b.c.d" this list
16993 // will keep FieldDecl's like [d, c, b].
16994 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16995 const MemberExpr *TopME = nullptr;
16996 bool AnyIsPacked = false;
16997 do {
16998 QualType BaseType = ME->getBase()->getType();
16999 if (BaseType->isDependentType())
17000 return;
17001 if (ME->isArrow())
17002 BaseType = BaseType->getPointeeType();
17003 auto *RD = BaseType->castAsRecordDecl();
17004 if (RD->isInvalidDecl())
17005 return;
17006
17007 ValueDecl *MD = ME->getMemberDecl();
17008 auto *FD = dyn_cast<FieldDecl>(Val: MD);
17009 // We do not care about non-data members.
17010 if (!FD || FD->isInvalidDecl())
17011 return;
17012
17013 AnyIsPacked =
17014 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17015 ReverseMemberChain.push_back(Elt: FD);
17016
17017 TopME = ME;
17018 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
17019 } while (ME);
17020 assert(TopME && "We did not compute a topmost MemberExpr!");
17021
17022 // Not the scope of this diagnostic.
17023 if (!AnyIsPacked)
17024 return;
17025
17026 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17027 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
17028 // TODO: The innermost base of the member expression may be too complicated.
17029 // For now, just disregard these cases. This is left for future
17030 // improvement.
17031 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
17032 return;
17033
17034 // Alignment expected by the whole expression.
17035 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
17036
17037 // No need to do anything else with this case.
17038 if (ExpectedAlignment.isOne())
17039 return;
17040
17041 // Synthesize offset of the whole access.
17042 CharUnits Offset;
17043 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
17044 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
17045
17046 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17047 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17048 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
17049
17050 // The base expression of the innermost MemberExpr may give
17051 // stronger guarantees than the class containing the member.
17052 if (DRE && !TopME->isArrow()) {
17053 const ValueDecl *VD = DRE->getDecl();
17054 if (!VD->getType()->isReferenceType())
17055 CompleteObjectAlignment =
17056 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
17057 }
17058
17059 // Check if the synthesized offset fulfills the alignment.
17060 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
17061 // It may fulfill the offset it but the effective alignment may still be
17062 // lower than the expected expression alignment.
17063 CompleteObjectAlignment < ExpectedAlignment) {
17064 // If this happens, we want to determine a sensible culprit of this.
17065 // Intuitively, watching the chain of member expressions from right to
17066 // left, we start with the required alignment (as required by the field
17067 // type) but some packed attribute in that chain has reduced the alignment.
17068 // It may happen that another packed structure increases it again. But if
17069 // we are here such increase has not been enough. So pointing the first
17070 // FieldDecl that either is packed or else its RecordDecl is,
17071 // seems reasonable.
17072 FieldDecl *FD = nullptr;
17073 CharUnits Alignment;
17074 for (FieldDecl *FDI : ReverseMemberChain) {
17075 if (FDI->hasAttr<PackedAttr>() ||
17076 FDI->getParent()->hasAttr<PackedAttr>()) {
17077 FD = FDI;
17078 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
17079 b: Context.getTypeAlignInChars(
17080 T: Context.getCanonicalTagType(TD: FD->getParent())));
17081 break;
17082 }
17083 }
17084 assert(FD && "We did not find a packed FieldDecl!");
17085 Action(E, FD->getParent(), FD, Alignment);
17086 }
17087}
17088
17089void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17090 using namespace std::placeholders;
17091
17092 RefersToMemberWithReducedAlignment(
17093 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
17094 args: _2, args: _3, args: _4));
17095}
17096
17097bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
17098 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17099 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17100 return true;
17101
17102 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
17103 if (A.isInvalid())
17104 return true;
17105
17106 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17107 QualType TyA = A.get()->getType();
17108
17109 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
17110 ArgTyRestr, ArgOrdinal: 1))
17111 return true;
17112
17113 TheCall->setType(TyA);
17114 return false;
17115}
17116
17117bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17118 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17119 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17120 TheCall->setType(*Res);
17121 return false;
17122 }
17123 return true;
17124}
17125
17126bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
17127 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17128 if (!Res)
17129 return true;
17130
17131 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17132 TheCall->setType(VecTy0->getElementType());
17133 else
17134 TheCall->setType(*Res);
17135
17136 return false;
17137}
17138
17139static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
17140 SourceLocation Loc) {
17141 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
17142 R = RHS->getEnumCoercedType(Ctx: S.Context);
17143 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17144 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
17145 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
17146 << LHS->getSourceRange() << RHS->getSourceRange()
17147 << /*Arithmetic Between*/ 0 << L << R;
17148 }
17149 return false;
17150}
17151
17152/// Check if all arguments have the same type. If the types don't match, emit an
17153/// error message and return true. Otherwise return false.
17154///
17155/// For scalars we directly compare their unqualified types. But even if we
17156/// compare unqualified vector types, a difference in qualifiers in the element
17157/// types can make the vector types be considered not equal. For example,
17158/// vector of 4 'const float' values vs vector of 4 'float' values.
17159/// So we compare unqualified types of their elements and number of elements.
17160static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
17161 ArrayRef<Expr *> Args) {
17162 assert(!Args.empty() && "Should have at least one argument.");
17163
17164 Expr *Arg0 = Args.front();
17165 QualType Ty0 = Arg0->getType();
17166
17167 auto EmitError = [&](Expr *ArgI) {
17168 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
17169 DiagID: diag::err_typecheck_call_different_arg_types)
17170 << Arg0->getType() << ArgI->getType();
17171 };
17172
17173 // Compare scalar types.
17174 if (!Ty0->isVectorType()) {
17175 for (Expr *ArgI : Args.drop_front())
17176 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
17177 EmitError(ArgI);
17178 return true;
17179 }
17180
17181 return false;
17182 }
17183
17184 // Compare vector types.
17185 const auto *Vec0 = Ty0->castAs<VectorType>();
17186 for (Expr *ArgI : Args.drop_front()) {
17187 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17188 if (!VecI ||
17189 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
17190 T2: VecI->getElementType()) ||
17191 Vec0->getNumElements() != VecI->getNumElements()) {
17192 EmitError(ArgI);
17193 return true;
17194 }
17195 }
17196
17197 return false;
17198}
17199
17200std::optional<QualType>
17201Sema::BuiltinVectorMath(CallExpr *TheCall,
17202 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17203 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
17204 return std::nullopt;
17205
17206 if (checkBuiltinVectorMathMixedEnums(
17207 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
17208 return std::nullopt;
17209
17210 Expr *Args[2];
17211 for (int I = 0; I < 2; ++I) {
17212 ExprResult Converted =
17213 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17214 if (Converted.isInvalid())
17215 return std::nullopt;
17216 Args[I] = Converted.get();
17217 }
17218
17219 SourceLocation LocA = Args[0]->getBeginLoc();
17220 QualType TyA = Args[0]->getType();
17221
17222 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
17223 return std::nullopt;
17224
17225 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17226 return std::nullopt;
17227
17228 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
17229 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
17230 return TyA;
17231}
17232
17233bool Sema::BuiltinElementwiseTernaryMath(
17234 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17235 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17236 return true;
17237
17238 SourceLocation Loc = TheCall->getExprLoc();
17239 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
17240 RHS: TheCall->getArg(Arg: 1), Loc) ||
17241 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
17242 RHS: TheCall->getArg(Arg: 2), Loc))
17243 return true;
17244
17245 Expr *Args[3];
17246 for (int I = 0; I < 3; ++I) {
17247 ExprResult Converted =
17248 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17249 if (Converted.isInvalid())
17250 return true;
17251 Args[I] = Converted.get();
17252 }
17253
17254 int ArgOrdinal = 1;
17255 for (Expr *Arg : Args) {
17256 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
17257 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
17258 return true;
17259 }
17260
17261 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17262 return true;
17263
17264 for (int I = 0; I < 3; ++I)
17265 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
17266
17267 TheCall->setType(Args[0]->getType());
17268 return false;
17269}
17270
17271bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17272 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17273 return true;
17274
17275 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
17276 if (A.isInvalid())
17277 return true;
17278
17279 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17280 return false;
17281}
17282
17283bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17284 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17285 return true;
17286
17287 ExprResult Arg = TheCall->getArg(Arg: 0);
17288 QualType TyArg = Arg.get()->getType();
17289
17290 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17291 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
17292 DiagID: diag::err_builtin_invalid_arg_type)
17293 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17294
17295 TheCall->setType(TyArg);
17296 return false;
17297}
17298
17299ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17300 ExprResult CallResult) {
17301 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17302 return ExprError();
17303
17304 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
17305 if (MatrixArg.isInvalid())
17306 return MatrixArg;
17307 Expr *Matrix = MatrixArg.get();
17308
17309 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17310 if (!MType) {
17311 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17312 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17313 << Matrix->getType();
17314 return ExprError();
17315 }
17316
17317 // Create returned matrix type by swapping rows and columns of the argument
17318 // matrix type.
17319 QualType ResultType = Context.getConstantMatrixType(
17320 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
17321
17322 // Change the return type to the type of the returned matrix.
17323 TheCall->setType(ResultType);
17324
17325 // Update call argument to use the possibly converted matrix argument.
17326 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
17327 return CallResult;
17328}
17329
17330// Get and verify the matrix dimensions.
17331static std::optional<unsigned>
17332getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17333 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
17334 if (!Value) {
17335 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
17336 << Name;
17337 return {};
17338 }
17339 uint64_t Dim = Value->getZExtValue();
17340 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17341 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
17342 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17343 return {};
17344 }
17345 return Dim;
17346}
17347
17348ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17349 ExprResult CallResult) {
17350 if (!getLangOpts().MatrixTypes) {
17351 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17352 return ExprError();
17353 }
17354
17355 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17356 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17357 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17358 << /*column*/ 1 << /*load*/ 0;
17359 return ExprError();
17360 }
17361
17362 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
17363 return ExprError();
17364
17365 unsigned PtrArgIdx = 0;
17366 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17367 Expr *RowsExpr = TheCall->getArg(Arg: 1);
17368 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
17369 Expr *StrideExpr = TheCall->getArg(Arg: 3);
17370
17371 bool ArgError = false;
17372
17373 // Check pointer argument.
17374 {
17375 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17376 if (PtrConv.isInvalid())
17377 return PtrConv;
17378 PtrExpr = PtrConv.get();
17379 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
17380 if (PtrExpr->isTypeDependent()) {
17381 TheCall->setType(Context.DependentTy);
17382 return TheCall;
17383 }
17384 }
17385
17386 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17387 QualType ElementTy;
17388 if (!PtrTy) {
17389 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17390 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17391 << PtrExpr->getType();
17392 ArgError = true;
17393 } else {
17394 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17395
17396 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
17397 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17398 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17399 << /* no fp */ 0 << PtrExpr->getType();
17400 ArgError = true;
17401 }
17402 }
17403
17404 // Apply default Lvalue conversions and convert the expression to size_t.
17405 auto ApplyArgumentConversions = [this](Expr *E) {
17406 ExprResult Conv = DefaultLvalueConversion(E);
17407 if (Conv.isInvalid())
17408 return Conv;
17409
17410 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
17411 };
17412
17413 // Apply conversion to row and column expressions.
17414 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17415 if (!RowsConv.isInvalid()) {
17416 RowsExpr = RowsConv.get();
17417 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
17418 } else
17419 RowsExpr = nullptr;
17420
17421 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17422 if (!ColumnsConv.isInvalid()) {
17423 ColumnsExpr = ColumnsConv.get();
17424 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
17425 } else
17426 ColumnsExpr = nullptr;
17427
17428 // If any part of the result matrix type is still pending, just use
17429 // Context.DependentTy, until all parts are resolved.
17430 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17431 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17432 TheCall->setType(Context.DependentTy);
17433 return CallResult;
17434 }
17435
17436 // Check row and column dimensions.
17437 std::optional<unsigned> MaybeRows;
17438 if (RowsExpr)
17439 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
17440
17441 std::optional<unsigned> MaybeColumns;
17442 if (ColumnsExpr)
17443 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
17444
17445 // Check stride argument.
17446 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17447 if (StrideConv.isInvalid())
17448 return ExprError();
17449 StrideExpr = StrideConv.get();
17450 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
17451
17452 if (MaybeRows) {
17453 if (std::optional<llvm::APSInt> Value =
17454 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17455 uint64_t Stride = Value->getZExtValue();
17456 if (Stride < *MaybeRows) {
17457 Diag(Loc: StrideExpr->getBeginLoc(),
17458 DiagID: diag::err_builtin_matrix_stride_too_small);
17459 ArgError = true;
17460 }
17461 }
17462 }
17463
17464 if (ArgError || !MaybeRows || !MaybeColumns)
17465 return ExprError();
17466
17467 TheCall->setType(
17468 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
17469 return CallResult;
17470}
17471
17472ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17473 ExprResult CallResult) {
17474 if (!getLangOpts().MatrixTypes) {
17475 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17476 return ExprError();
17477 }
17478
17479 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17480 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17481 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17482 << /*column*/ 1 << /*store*/ 1;
17483 return ExprError();
17484 }
17485
17486 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17487 return ExprError();
17488
17489 unsigned PtrArgIdx = 1;
17490 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17491 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17492 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17493
17494 bool ArgError = false;
17495
17496 {
17497 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17498 if (MatrixConv.isInvalid())
17499 return MatrixConv;
17500 MatrixExpr = MatrixConv.get();
17501 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17502 }
17503 if (MatrixExpr->isTypeDependent()) {
17504 TheCall->setType(Context.DependentTy);
17505 return TheCall;
17506 }
17507
17508 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17509 if (!MatrixTy) {
17510 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17511 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17512 ArgError = true;
17513 }
17514
17515 {
17516 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17517 if (PtrConv.isInvalid())
17518 return PtrConv;
17519 PtrExpr = PtrConv.get();
17520 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17521 if (PtrExpr->isTypeDependent()) {
17522 TheCall->setType(Context.DependentTy);
17523 return TheCall;
17524 }
17525 }
17526
17527 // Check pointer argument.
17528 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17529 if (!PtrTy) {
17530 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17531 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17532 << PtrExpr->getType();
17533 ArgError = true;
17534 } else {
17535 QualType ElementTy = PtrTy->getPointeeType();
17536 if (ElementTy.isConstQualified()) {
17537 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17538 ArgError = true;
17539 }
17540 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17541 if (MatrixTy &&
17542 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17543 Diag(Loc: PtrExpr->getBeginLoc(),
17544 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17545 << ElementTy << MatrixTy->getElementType();
17546 ArgError = true;
17547 }
17548 }
17549
17550 // Apply default Lvalue conversions and convert the stride expression to
17551 // size_t.
17552 {
17553 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17554 if (StrideConv.isInvalid())
17555 return StrideConv;
17556
17557 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17558 if (StrideConv.isInvalid())
17559 return StrideConv;
17560 StrideExpr = StrideConv.get();
17561 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17562 }
17563
17564 // Check stride argument.
17565 if (MatrixTy) {
17566 if (std::optional<llvm::APSInt> Value =
17567 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17568 uint64_t Stride = Value->getZExtValue();
17569 if (Stride < MatrixTy->getNumRows()) {
17570 Diag(Loc: StrideExpr->getBeginLoc(),
17571 DiagID: diag::err_builtin_matrix_stride_too_small);
17572 ArgError = true;
17573 }
17574 }
17575 }
17576
17577 if (ArgError)
17578 return ExprError();
17579
17580 return CallResult;
17581}
17582
17583void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17584 const NamedDecl *Callee) {
17585 // This warning does not make sense in code that has no runtime behavior.
17586 if (isUnevaluatedContext())
17587 return;
17588
17589 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17590
17591 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17592 return;
17593
17594 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17595 // all TCBs the callee is a part of.
17596 llvm::StringSet<> CalleeTCBs;
17597 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17598 CalleeTCBs.insert(key: A->getTCBName());
17599 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17600 CalleeTCBs.insert(key: A->getTCBName());
17601
17602 // Go through the TCBs the caller is a part of and emit warnings if Caller
17603 // is in a TCB that the Callee is not.
17604 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17605 StringRef CallerTCB = A->getTCBName();
17606 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17607 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17608 << Callee << CallerTCB;
17609 }
17610 }
17611}
17612